Merge branch 'dev-denzel' into cja_new

This commit is contained in:
cja committed 2025-06-02 10:31:05 +03:00
commit e2446d3dee
8 files changed
+414 -59

No files matched your search

@@ -29,6 +29,17 @@
<v-divider class="mb-4"></v-divider> <v-divider class="mb-4"></v-divider>
<div class="mb-4">
<div class="d-flex align-center mb-2">
<v-icon icon="mdi-calendar-clock-outline" color="teal-darken-2" class="mr-2"></v-icon>
<span class="text-subtitle-1 font-weight-medium text-teal-darken-1">Дата начала теста</span>
</div>
<date-select
:datedefault="startDate"
@returndate="(date) => handleDateChange(date, 'start')"
/>
</div>
<div class="mb-6"> <div class="mb-6">
<div class="d-flex align-center mb-2"> <div class="d-flex align-center mb-2">
<v-icon icon="mdi-calendar-clock" color="teal-darken-2" class="mr-2"></v-icon> <v-icon icon="mdi-calendar-clock" color="teal-darken-2" class="mr-2"></v-icon>
@@ -36,7 +47,7 @@
</div> </div>
<date-select <date-select
:datedefault="completionDate" :datedefault="completionDate"
@returndate="handleDateChange" @returndate="(date) => handleDateChange(date, 'end')"
/> />
</div> </div>
@@ -59,6 +70,9 @@
<div class="d-flex align-center"> <div class="d-flex align-center">
<div> <div>
<span class="text-orange-darken-2">{{ employee.fio }}</span> <span class="text-orange-darken-2">{{ employee.fio }}</span>
<div class="text-caption text-grey-darken-1" v-if="employee.datestart">
Дата начала: {{ new Date(employee.datestart).toLocaleDateString('ru-RU') }}
</div>
<div class="text-caption text-grey-darken-1" v-if="employee.completion_date"> <div class="text-caption text-grey-darken-1" v-if="employee.completion_date">
Дата окончания: {{ new Date(employee.completion_date).toLocaleDateString('ru-RU') }} Дата окончания: {{ new Date(employee.completion_date).toLocaleDateString('ru-RU') }}
</div> </div>
@@ -150,9 +164,12 @@ export default {
emits: ['update:modelValue', 'assign', 'unassign'], emits: ['update:modelValue', 'assign', 'unassign'],
setup(props, { emit }) { setup(props, { emit }) {
const selectedEmployees = ref([]); const selectedEmployees = ref([]);
const defaultDate = new Date(); const defaultEndDate = new Date();
defaultDate.setHours(18, 0, 0, 0); defaultEndDate.setHours(18, 0, 0, 0);
const completionDate = ref(defaultDate); const defaultStartDate = new Date();
defaultStartDate.setHours(9, 0, 0, 0);
const completionDate = ref(defaultEndDate);
const startDate = ref(defaultStartDate);
const snackbar = ref({ const snackbar = ref({
show: false, show: false,
text: '', text: '',
@@ -171,18 +188,43 @@ export default {
selectedEmployees.value = value; selectedEmployees.value = value;
}; };
const handleDateChange = (date) => { const handleDateChange = (date, type = 'end') => {
if (date) { if (date) {
date.setHours(18, 0, 0, 0); const newDate = new Date(date);
if (type === 'end') {
newDate.setHours(18, 0, 0, 0);
} else {
newDate.setHours(9, 0, 0, 0);
}
const today = new Date(); const today = new Date();
today.setHours(0, 0, 0, 0); today.setHours(0, 0, 0, 0);
if (date < today) { if (newDate < today) {
showSnackbar('Нельзя назначить прошедшую дату'); showSnackbar('Нельзя назначить прошедшую дату');
if (type === 'end') {
completionDate.value = null;
} else {
startDate.value = null;
}
return;
}
if (type === 'end') {
if (startDate.value && newDate < startDate.value) {
showSnackbar('Дата окончания не может быть раньше даты начала');
completionDate.value = null; completionDate.value = null;
return; return;
} }
completionDate.value = newDate;
} else {
if (completionDate.value && newDate > completionDate.value) {
showSnackbar('Дата начала не может быть позже даты окончания');
startDate.value = null;
return;
}
startDate.value = newDate;
}
} }
completionDate.value = date;
}; };
const handleAssign = () => { const handleAssign = () => {
@@ -191,21 +233,27 @@ export default {
return; return;
} }
if (!completionDate.value) { if (!completionDate.value || !startDate.value) {
showSnackbar('Укажите дату окончания теста'); showSnackbar('Укажите дату начала и окончания теста');
return; return;
} }
const today = new Date(); const today = new Date();
today.setHours(0, 0, 0, 0); today.setHours(0, 0, 0, 0);
if (completionDate.value < today) { if (completionDate.value < today || startDate.value < today) {
showSnackbar('Нельзя назначить прошедшую дату'); showSnackbar('Нельзя назначить прошедшую дату');
return; return;
} }
if (startDate.value > completionDate.value) {
showSnackbar('Дата начала не может быть позже даты окончания');
return;
}
emit('assign', { emit('assign', {
selectedEmployees: selectedEmployees.value, selectedEmployees: selectedEmployees.value,
completionDate: completionDate.value completionDate: completionDate.value,
startDate: startDate.value
}); });
selectedEmployees.value = []; selectedEmployees.value = [];
@@ -216,6 +264,7 @@ export default {
return { return {
selectedEmployees, selectedEmployees,
completionDate, completionDate,
startDate,
handleEmployeeSelection, handleEmployeeSelection,
handleAssign, handleAssign,
handleDateChange, handleDateChange,
+158 -19
View File
@@ -20,16 +20,17 @@
<v-col cols="12" sm="4"> <v-col cols="12" sm="4">
<v-card <v-card
class="pa-4 text-center result-card" class="pa-4 text-center result-card"
:class="{ 'cursor-pointer': isPracticeMode }"
elevation="2" elevation="2"
:color="testPassed ? 'success-light' : 'error-light'" :color="testPassed ? 'success-light' : 'error-light'"
@click="isPracticeMode && (showAnswersDialog = true)"
> >
<v-icon size="36" :color="testPassed ? 'success' : 'error'" class="mb-2"> <v-icon size="36" :color="testPassed ? 'success' : 'error'" class="mb-2">
mdi-checkbox-marked-circle mdi-checkbox-marked-circle
</v-icon> </v-icon>
<p class="text-h5 mb-1">{{ correctAnswers }}/{{ totalQuestions }}</p> <p class="text-h5 mb-1">{{ correctAnswers }}/{{ totalQuestions }}</p>
<div class="text-body-2"> <div class="text-body-2">
Правильных ответов {{ isPracticeMode ? 'Правильных ответов (нажмите чтобы увидеть детали)' : 'Правильных ответов' }}
<v-icon v-if="isPracticeMode" small color="primary">mdi-information</v-icon>
</div> </div>
</v-card> </v-card>
</v-col> </v-col>
@@ -51,7 +52,7 @@
</v-col> </v-col>
</v-row> </v-row>
<!-- Модальное окно с правильными ответами отображается только в режиме тренировки --> <!-- Модальное окно с правильными ответами (только для тренировочного режима) -->
<v-dialog v-if="isPracticeMode" v-model="showAnswersDialog" max-width="600"> <v-dialog v-if="isPracticeMode" v-model="showAnswersDialog" max-width="600">
<v-card> <v-card>
<v-card-title class="d-flex align-center text-h6 font-weight-bold px-4 py-3 bg-teal-darken-4 text-white"> <v-card-title class="d-flex align-center text-h6 font-weight-bold px-4 py-3 bg-teal-darken-4 text-white">
@@ -68,10 +69,10 @@
<v-expansion-panel-title> <v-expansion-panel-title>
<div class="d-flex align-center"> <div class="d-flex align-center">
<v-icon <v-icon
:color="isQuestionCorrect(index) ? 'success' : 'error'" :color="getQuestionStatusColor(index)"
class="mr-2" class="mr-2"
> >
{{ isQuestionCorrect(index) ? 'mdi-check-circle' : 'mdi-close-circle' }} {{ getQuestionStatusIcon(index) }}
</v-icon> </v-icon>
<span>Вопрос {{ index + 1 }}</span> <span>Вопрос {{ index + 1 }}</span>
</div> </div>
@@ -79,18 +80,32 @@
<v-expansion-panel-text> <v-expansion-panel-text>
<p class="mb-2 font-weight-bold">{{ question.name }}</p> <p class="mb-2 font-weight-bold">{{ question.name }}</p>
<v-divider class="mb-2"></v-divider> <v-divider class="mb-2"></v-divider>
<div v-for="answer in question.answers" :key="answer.id" class="mb-1"> <div v-for="answer in question.answers" :key="answer.id" class="mb-2 d-flex align-center">
<v-icon <v-icon
:color="answer.right_wrong ? 'success' : ''" :color="getAnswerColor(index, answer)"
size="small" size="small"
class="mr-1" class="mr-2"
> >
{{ answer.right_wrong ? 'mdi-check' : 'mdi-minus' }} {{ getAnswerIcon(index, answer) }}
</v-icon> </v-icon>
<span :class="{ 'font-weight-bold': answer.right_wrong }"> <span :class="{ 'font-weight-bold': isAnswerCorrect(index, answer) }">
{{ answer.name }} {{ answer.name }}
</span> </span>
<span v-if="answer.right_wrong" class="text-success">(правильный ответ)</span> <v-chip
v-if="answer.isUserAnswer"
size="small"
class="ml-2"
:color="answer.right_wrong === true ? 'success' : 'error'"
variant="outlined"
>
Ваш ответ
</v-chip>
</div>
<div v-if="hasUserAnswer(index)" class="mt-4">
<v-divider class="mb-2"></v-divider>
<div class="text-caption">
{{ isQuestionCorrect(index) ? 'Правильно ✓' : 'Неправильно ✗' }}
</div>
</div> </div>
</v-expansion-panel-text> </v-expansion-panel-text>
</v-expansion-panel> </v-expansion-panel>
@@ -98,6 +113,19 @@
</v-card-text> </v-card-text>
</v-card> </v-card>
</v-dialog> </v-dialog>
<!-- Кнопка "Попробовать ещё раз" для тренировочного режима -->
<div v-if="isPracticeMode && !fromCompletedTab" class="d-flex justify-center mt-6">
<v-btn
color="teal-darken-1"
@click="$emit('restart')"
class="px-6"
size="large"
>
<v-icon start>mdi-refresh</v-icon>
Попробовать ещё раз
</v-btn>
</div>
</v-card> </v-card>
</template> </template>
@@ -125,6 +153,10 @@ export default {
userAnswers: { userAnswers: {
type: Array, type: Array,
required: true required: true
},
fromCompletedTab: {
type: Boolean,
default: false
} }
}, },
setup(props) { setup(props) {
@@ -133,25 +165,132 @@ export default {
const isPracticeMode = computed(() => !route.query.mode || route.query.mode === 'practice'); const isPracticeMode = computed(() => !route.query.mode || route.query.mode === 'practice');
const isQuestionCorrect = (questionIndex) => { const getQuestionStatusColor = (questionIndex) => {
const question = props.questions[questionIndex]; if (!props.questions[questionIndex]?.answers) return 'grey';
const userAnswer = props.userAnswers[questionIndex];
if (props.fromCompletedTab) {
return 'grey';
}
const hasCorrectAnswers = props.questions[questionIndex].answers.some(a => a.right_wrong === true);
return hasCorrectAnswers ? 'success' : 'grey';
};
const getQuestionStatusIcon = (questionIndex) => {
if (!props.questions[questionIndex]?.answers) return 'mdi-circle-outline';
if (props.fromCompletedTab) {
return '';
}
const hasCorrectAnswers = props.questions[questionIndex].answers.some(a => a.right_wrong === true);
return hasCorrectAnswers ? 'mdi-check-circle' : 'mdi-circle-outline';
};
const hasUserAnswer = (index) => {
const answer = props.userAnswers?.[index];
return answer !== null && answer !== undefined;
};
const showUserAnswer = (index, answerName) => {
const userAnswer = props.userAnswers?.[index];
if (!userAnswer) return false; if (!userAnswer) return false;
if (Array.isArray(userAnswer)) { if (Array.isArray(userAnswer)) {
const correctAnswers = question.answers.filter(a => a.right_wrong).map(a => a.name); return userAnswer.includes(answerName);
return userAnswer.length === correctAnswers.length && }
userAnswer.every(answer => correctAnswers.includes(answer)); return userAnswer === answerName;
}; const isQuestionCorrect = (questionIndex) => {
const question = props.questions?.[questionIndex];
if (!question?.answers || !Array.isArray(question.answers)) return false;
const userAnswer = props.userAnswers?.[questionIndex];
if (!userAnswer) return false;
const correctAnswers = question.answers.filter(a => a.right_wrong === true);
if (correctAnswers.length === 0) return false;
if (Array.isArray(userAnswer)) {
return correctAnswers.length === userAnswer.length &&
correctAnswers.every(a => userAnswer.includes(a.name)) &&
userAnswer.every(ua => correctAnswers.some(ca => ca.name === ua));
} }
return question.answers.find(a => a.name === userAnswer)?.right_wrong || false; return correctAnswers.some(a => a.name === userAnswer);
};
const isAnswerCorrect = (questionIndex, answer) => {
if (!answer || !answer.name || questionIndex === undefined || questionIndex === null) {
return false;
}
if (!props.fromCompletedTab) {
return answer.right_wrong === true;
}
const userAnswer = props.userAnswers?.[questionIndex];
if (!userAnswer) return false;
const isSelected = Array.isArray(userAnswer)
? userAnswer.includes(answer.name)
: userAnswer === answer.name;
return isSelected && answer.right_wrong === true;
};
const getAnswerColor = (questionIndex, answer) => {
if (!answer?.name) return 'grey';
if (answer.right_wrong === true) {
return 'success';
}
const userAnswer = props.userAnswers?.[questionIndex];
if (userAnswer) {
const isSelected = Array.isArray(userAnswer)
? userAnswer.includes(answer.name)
: userAnswer === answer.name;
if (isSelected) {
return 'error';
}
}
return 'grey';
};
const getAnswerIcon = (questionIndex, answer) => {
if (!answer?.name) return 'mdi-circle-outline';
if (answer.right_wrong === true) {
return 'mdi-check-circle';
}
const userAnswer = props.userAnswers?.[questionIndex];
if (userAnswer) {
const isSelected = Array.isArray(userAnswer)
? userAnswer.includes(answer.name)
: userAnswer === answer.name;
if (isSelected) {
return 'mdi-close-circle';
}
}
return 'mdi-circle-outline';
}; };
return { return {
showAnswersDialog, showAnswersDialog,
isPracticeMode, isPracticeMode,
isQuestionCorrect isQuestionCorrect,
hasUserAnswer,
showUserAnswer,
isAnswerCorrect,
getAnswerColor,
getAnswerIcon,
getQuestionStatusColor,
getQuestionStatusIcon
}; };
} }
}; };
@@ -4,7 +4,7 @@
<div <div
v-for="(answer, aIndex) in question.answers" v-for="(answer, aIndex) in question.answers"
:key="aIndex" :key="aIndex"
class="d-flex align-start mb-4" class="d-flex align-start mb-4 ga-4"
> >
<!-- Показываем иконку для переключения статуса только в режиме теста --> <!-- Показываем иконку для переключения статуса только в режиме теста -->
<v-btn <v-btn
@@ -35,12 +35,13 @@
hide-details hide-details
label="Картинка" label="Картинка"
variant="outlined" variant="outlined"
@update:model-value="() => previewAnswerImage(answer, aIndex)" :error-messages="answer.imageError"
@update:model-value="(file) => handleImageUpload(file, answer, aIndex)"
></v-file-input> ></v-file-input>
<!-- Превью изображения ответа, если оно загружено --> <!-- Превью изображения ответа, если оно загружено -->
<div v-if="answer.imagePreview" class="ml-2"> <div v-if="answer.imagePreview" class="ml-2">
<v-avatar size="32"> <v-avatar size="40">
<v-img :src="answer.imagePreview" alt="Превью"></v-img> <v-img :src="answer.imagePreview" alt="Превью"></v-img>
</v-avatar> </v-avatar>
</div> </div>
@@ -93,11 +94,50 @@ export default {
setup(props) { setup(props) {
const route = useRoute(); const route = useRoute();
// Поддерживаем оба способа определения: через роут или через явный проп
const isTestRoute = computed(() => { const isTestRoute = computed(() => {
return route.path && String(route.path).includes('test'); return route.path && String(route.path).includes('test');
}); });
const validateImage = (file) => {
if (!file) return null;
// Проверяем тип файла
const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
if (!validTypes.includes(file.type)) {
return 'Разрешены только изображения (JPEG, PNG, GIF, WEBP)';
}
// Проверяем размер файла (максимум 5MB)
const maxSize = 5 * 1024 * 1024; // 5MB в байтах
if (file.size > maxSize) {
return 'Размер изображения не должен превышать 5MB';
}
return null;
};
const handleImageUpload = (file, answer, index) => {
// Сбрасываем предыдущие ошибки
answer.imageError = '';
if (!file) {
answer.image = null;
answer.imagePreview = null;
return;
}
const error = validateImage(file);
if (error) {
answer.imageError = error;
answer.image = null;
answer.imagePreview = null;
return;
}
// Если валидация прошла успешно, показываем превью
previewAnswerImage(answer, index);
};
const toggleCorrect = (answer) => { const toggleCorrect = (answer) => {
// Используем right_wrong для тестов (совместимо с бэкендом) // Используем right_wrong для тестов (совместимо с бэкендом)
answer.right_wrong = !answer.right_wrong; answer.right_wrong = !answer.right_wrong;
@@ -128,6 +168,7 @@ export default {
isTestRoute, isTestRoute,
toggleCorrect, toggleCorrect,
previewAnswerImage, previewAnswerImage,
handleImageUpload,
isTest: props.isTest isTest: props.isTest
}; };
} }
@@ -12,7 +12,9 @@
label="Картинка для вопроса" label="Картинка для вопроса"
variant="outlined" variant="outlined"
class="flex-grow-1" class="flex-grow-1"
@update:model-value="previewQuestionImage" :error-messages="question.imageError"
hint="Допустимые форматы: JPEG, PNG, GIF, WEBP. Макс. размер: 5MB"
@update:model-value="handleQuestionImageUpload"
></v-file-input> ></v-file-input>
<!-- Превью изображения вопроса, если оно загружено --> <!-- Превью изображения вопроса, если оно загружено -->
@@ -225,6 +227,45 @@ export default {
const route = useRoute(); const route = useRoute();
const questionImagePreview = ref(null); const questionImagePreview = ref(null);
const validateImage = (file) => {
if (!file) return null;
// Проверяем тип файла
const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
if (!validTypes.includes(file.type)) {
return 'Разрешены только изображения (JPEG, PNG, GIF, WEBP)';
}
// Проверяем размер файла (максимум 5MB)
const maxSize = 5 * 1024 * 1024; // 5MB в байтах
if (file.size > maxSize) {
return 'Размер изображения не должен превышать 5MB';
}
return null;
};
const handleQuestionImageUpload = (file) => {
// Сбрасываем предыдущие ошибки
props.question.imageError = '';
questionImagePreview.value = null;
if (!file) {
props.question.image = null;
return;
}
const error = validateImage(file);
if (error) {
props.question.imageError = error;
props.question.image = null;
return;
}
// Если валидация прошла успешно, показываем превью
previewQuestionImage();
};
const resetAnswers = () => { const resetAnswers = () => {
props.question.answers = []; props.question.answers = [];
emit('update:question', props.question); emit('update:question', props.question);
@@ -290,7 +331,8 @@ export default {
onEmployeesChange, onEmployeesChange,
isTestRoute, isTestRoute,
questionImagePreview, questionImagePreview,
previewQuestionImage previewQuestionImage,
handleQuestionImageUpload
}; };
}, },
}; };
@@ -44,11 +44,8 @@
></v-text-field> ></v-text-field>
<v-text-field <v-text-field
v-model="testSettings.question_count" v-model="testSettings.question_count"
:rules="[rules.required, rules.positive]"
label="Количество вопросов в тесте" label="Количество вопросов в тесте"
type="number" type="number"
min="1"
:max="actualQuestionCount"
required required
class="mr-2" class="mr-2"
></v-text-field> ></v-text-field>
@@ -72,9 +69,10 @@
variant="outlined" variant="outlined"
prepend-icon="mdi-image" prepend-icon="mdi-image"
placeholder="Выберите изображение для теста" placeholder="Выберите изображение для теста"
hint="Логотип или изображение для теста" hint="Логотип или изображение для теста (макс. 5MB, форматы: JPEG, PNG, GIF, WEBP)"
:error-messages="imageError"
:show-size="true" :show-size="true"
@update:model-value="previewImage" @update:model-value="handleTestImageUpload"
></v-file-input> ></v-file-input>
<!-- Превью изображения --> <!-- Превью изображения -->
@@ -316,6 +314,21 @@ export default {
setup(props, { emit }) { setup(props, { emit }) {
const step = ref(0); const step = ref(0);
const isVoteCreated = ref(false); const isVoteCreated = ref(false);
// Добавляем наблюдение за изменением шага
watch(step, () => {
// Прокручиваем основной скролл страницы
window.scrollTo({ top: 0, behavior: 'smooth' });
// Находим все контейнеры с overflow-y: auto и прокручиваем их наверх
setTimeout(() => {
const scrollContainers = document.querySelectorAll('.v-card-text[style*="overflow-y: auto"]');
scrollContainers.forEach(container => {
container.scrollTo({ top: 0, behavior: 'smooth' });
});
}, 100);
});
const form = ref({ const form = ref({
title: '', title: '',
description: '', description: '',
@@ -439,6 +452,45 @@ export default {
}); });
}; };
const validateImage = (file) => {
if (!file) return null;
// Проверяем тип файла
const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
if (!validTypes.includes(file.type)) {
return 'Разрешены только изображения (JPEG, PNG, GIF, WEBP)';
}
// Проверяем размер файла (максимум 5MB)
const maxSize = 5 * 1024 * 1024; // 5MB в байтах
if (file.size > maxSize) {
return 'Размер изображения не должен превышать 5MB';
}
return null;
};
const handleTestImageUpload = (file) => {
// Сбрасываем предыдущие ошибки
imageError.value = '';
imagePreview.value = null;
if (!file) {
testImage.value = null;
return;
}
const error = validateImage(file);
if (error) {
imageError.value = error;
testImage.value = null;
return;
}
// Если валидация прошла успешно, показываем превью
previewImage();
};
const saveVoting = async () => { const saveVoting = async () => {
try { try {
if (props.isTest) { if (props.isTest) {
@@ -603,7 +655,7 @@ export default {
} }
watch(testImage, () => { watch(testImage, () => {
previewImage(); handleTestImageUpload(testImage.value);
}); });
return { return {
+10 -4
View File
@@ -243,16 +243,21 @@ async function createTest(testData) {
} }
} }
async function assignTest(testId, employeeIds, completionDate) { async function assignTest(testId, employeeIds, completionDate, startDate) {
try { try {
if (!completionDate) { if (!completionDate) {
const testDetails = await getTestDetail(testId); const testDetails = await getTestDetail(testId);
completionDate = testDetails.dateend; completionDate = testDetails.dateend;
} }
if (!startDate) {
const testDetails = await getTestDetail(testId);
startDate = testDetails.datestart;
}
const userIds = Array.from(employeeIds).map(id => Number(id)); const userIds = Array.from(employeeIds).map(id => Number(id));
const promises = userIds.map(userId => const promises = userIds.map(userId =>
assignTestToUser(userId, testId, completionDate) assignTestToUser(userId, testId, completionDate, startDate)
); );
await Promise.all(promises); await Promise.all(promises);
@@ -291,13 +296,14 @@ async function deleteTest(id) {
} }
} }
async function assignTestToUser(userId, testId, completionDate) { async function assignTestToUser(userId, testId, completionDate, startDate) {
try { try {
const response = await axiosApiInstance.post('/api/tests/testingview/', { const response = await axiosApiInstance.post('/api/tests/testingview/', {
user_id: Number(userId), user_id: Number(userId),
test_id: Number(testId), test_id: Number(testId),
completion_date: completionDate completion_date: completionDate,
datestart: startDate
}); });
return response.data; return response.data;
} catch (error) { } catch (error) {
+38 -12
View File
@@ -105,7 +105,7 @@
</v-window-item> </v-window-item>
<!-- Конструктор --> <!-- Конструктор -->
<v-window-item :class="{'w-100': $vuetify.display.smAndDown, 'w-75': $vuetify.display.mdAndUp, 'mx-auto': true}"> <v-window-item v-if="accountStore.user.is_staff" :class="{'w-100': $vuetify.display.smAndDown, 'w-75': $vuetify.display.mdAndUp, 'mx-auto': true}">
<VoteConstructor @updating="getTestById" :isTest="true" /> <VoteConstructor @updating="getTestById" :isTest="true" />
</v-window-item> </v-window-item>
</v-window> </v-window>
@@ -175,6 +175,7 @@
:formattedTime="testResults.time_spent" :formattedTime="testResults.time_spent"
:questions="testResults.questions" :questions="testResults.questions"
:userAnswers="testResults.user_answers" :userAnswers="testResults.user_answers"
:fromCompletedTab="testResults.fromCompletedTab"
/> />
</v-card-text> </v-card-text>
</v-card> </v-card>
@@ -264,7 +265,7 @@ export default {
{ value: 0, title: `Назначенные (${currentTest.value})` }, { value: 0, title: `Назначенные (${currentTest.value})` },
{ value: 1, title: 'Завершенные' }, { value: 1, title: 'Завершенные' },
{ value: 2, title: 'Каталог' }, { value: 2, title: 'Каталог' },
{ value: 3, title: 'Создать новый тест' }, ...(accountStore.user.is_staff ? [{ value: 3, title: 'Создать новый тест' }] : []),
]); ]);
const goToTest = (id) => router.push(`/test/testdetail/${id}`); const goToTest = (id) => router.push(`/test/testdetail/${id}`);
@@ -292,18 +293,21 @@ export default {
try { try {
const response = await getTestToUser(id); const response = await getTestToUser(id);
console.log('API Response:', response);
const assignmentsByUser = response.reduce((acc, testing) => { const assignmentsByUser = response.reduce((acc, testing) => {
if (testing.user_details && testing.is_active) { if (testing.user_details && testing.is_active) {
const existingUser = acc.find(u => u.id === testing.user_details.id); const existingUser = acc.find(u => u.id === testing.user_details.id);
if (!existingUser) { if (!existingUser) {
acc.push({ acc.push({
...testing.user_details, ...testing.user_details,
completion_date: testing.completion_date completion_date: testing.completion_date,
datestart: testing.datestart
}); });
} }
} }
return acc; return acc;
}, []); }, []);
console.log('Transformed Data:', assignmentsByUser);
assignedEmployees.value = assignmentsByUser.map(user => user.id); assignedEmployees.value = assignmentsByUser.map(user => user.id);
@@ -350,7 +354,7 @@ export default {
} }
}; };
const handleAssign = async ({ selectedEmployees: employees, completionDate }) => { const handleAssign = async ({ selectedEmployees: employees, completionDate, startDate }) => {
try { try {
let employeesToAssign = [...employees]; let employeesToAssign = [...employees];
@@ -361,7 +365,7 @@ export default {
} }
} }
await assignTest(selectedTestId.value, employeesToAssign, completionDate); await assignTest(selectedTestId.value, employeesToAssign, completionDate, startDate);
addDialog.value = false; addDialog.value = false;
getTestById(); getTestById();
@@ -387,14 +391,36 @@ export default {
axiosApiInstance.get(`/api/tests/testresultview/?id=${id}`) axiosApiInstance.get(`/api/tests/testresultview/?id=${id}`)
]); ]);
const questions = (testDetailResponse.data.questions || []).map(q => ({
...q,
answers: (q.answers || []).map(a => ({
...a,
isUserAnswer: false
}))
}));
const userAnswers = questions.map(question => {
const userAnswer = resultResponse.data.user_answers?.[question.id];
if (!userAnswer) return null;
question.answers.forEach(answer => {
answer.isUserAnswer = Array.isArray(userAnswer)
? userAnswer.includes(answer.name)
: userAnswer === answer.name;
});
return userAnswer;
});
testResults.value = { testResults.value = {
passed: resultResponse.data.is_passed, passed: resultResponse.data.is_passed || false,
total_questions: testDetailResponse.data.question_count, total_questions: testDetailResponse.data.question_count || 0,
total_answers: resultResponse.data.answered_questions_total, total_answers: resultResponse.data.answered_questions_total || 0,
correct_answers: resultResponse.data.score, correct_answers: resultResponse.data.score || 0,
time_spent: `${testDetailResponse.data.time} мин`, time_spent: `${testDetailResponse.data.time || 0} мин`,
questions: [], questions: questions,
userAnswers: [] userAnswers: userAnswers,
fromCompletedTab: activeTab.value === 1
}; };
showResultsDialog.value = true; showResultsDialog.value = true;