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
+421 -66

No files matched your search

@@ -29,6 +29,17 @@
<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="d-flex align-center mb-2">
<v-icon icon="mdi-calendar-clock" color="teal-darken-2" class="mr-2"></v-icon>
@@ -36,7 +47,7 @@
</div>
<date-select
:datedefault="completionDate"
@returndate="handleDateChange"
@returndate="(date) => handleDateChange(date, 'end')"
/>
</div>
@@ -59,6 +70,9 @@
<div class="d-flex align-center">
<div>
<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">
Дата окончания: {{ new Date(employee.completion_date).toLocaleDateString('ru-RU') }}
</div>
@@ -150,9 +164,12 @@ export default {
emits: ['update:modelValue', 'assign', 'unassign'],
setup(props, { emit }) {
const selectedEmployees = ref([]);
const defaultDate = new Date();
defaultDate.setHours(18, 0, 0, 0);
const completionDate = ref(defaultDate);
const defaultEndDate = new Date();
defaultEndDate.setHours(18, 0, 0, 0);
const defaultStartDate = new Date();
defaultStartDate.setHours(9, 0, 0, 0);
const completionDate = ref(defaultEndDate);
const startDate = ref(defaultStartDate);
const snackbar = ref({
show: false,
text: '',
@@ -171,18 +188,43 @@ export default {
selectedEmployees.value = value;
};
const handleDateChange = (date) => {
const handleDateChange = (date, type = 'end') => {
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();
today.setHours(0, 0, 0, 0);
if (date < today) {
if (newDate < today) {
showSnackbar('Нельзя назначить прошедшую дату');
completionDate.value = null;
if (type === 'end') {
completionDate.value = null;
} else {
startDate.value = null;
}
return;
}
if (type === 'end') {
if (startDate.value && newDate < startDate.value) {
showSnackbar('Дата окончания не может быть раньше даты начала');
completionDate.value = null;
return;
}
completionDate.value = newDate;
} else {
if (completionDate.value && newDate > completionDate.value) {
showSnackbar('Дата начала не может быть позже даты окончания');
startDate.value = null;
return;
}
startDate.value = newDate;
}
}
completionDate.value = date;
};
const handleAssign = () => {
@@ -191,21 +233,27 @@ export default {
return;
}
if (!completionDate.value) {
showSnackbar('Укажите дату окончания теста');
if (!completionDate.value || !startDate.value) {
showSnackbar('Укажите дату начала и окончания теста');
return;
}
const today = new Date();
today.setHours(0, 0, 0, 0);
if (completionDate.value < today) {
if (completionDate.value < today || startDate.value < today) {
showSnackbar('Нельзя назначить прошедшую дату');
return;
}
if (startDate.value > completionDate.value) {
showSnackbar('Дата начала не может быть позже даты окончания');
return;
}
emit('assign', {
selectedEmployees: selectedEmployees.value,
completionDate: completionDate.value
completionDate: completionDate.value,
startDate: startDate.value
});
selectedEmployees.value = [];
@@ -216,6 +264,7 @@ export default {
return {
selectedEmployees,
completionDate,
startDate,
handleEmployeeSelection,
handleAssign,
handleDateChange,
+164 -25
View File
@@ -19,17 +19,18 @@
<v-row class="mt-2">
<v-col cols="12" sm="4">
<v-card
class="pa-4 text-center result-card"
class="pa-4 text-center result-card"
:class="{ 'cursor-pointer': isPracticeMode }"
elevation="2"
:color="testPassed ? 'success-light' : 'error-light'"
@click="isPracticeMode && (showAnswersDialog = true)"
>
<v-icon size="36" :color="testPassed ? 'success' : 'error'" class="mb-2">
mdi-checkbox-marked-circle
</v-icon>
<p class="text-h5 mb-1">{{ correctAnswers }}/{{ totalQuestions }}</p>
<div class="text-body-2">
Правильных ответов
<v-icon v-if="isPracticeMode" small color="primary">mdi-information</v-icon>
{{ isPracticeMode ? 'Правильных ответов (нажмите чтобы увидеть детали)' : 'Правильных ответов' }}
</div>
</v-card>
</v-col>
@@ -51,7 +52,7 @@
</v-col>
</v-row>
<!-- Модальное окно с правильными ответами отображается только в режиме тренировки -->
<!-- Модальное окно с правильными ответами (только для тренировочного режима) -->
<v-dialog v-if="isPracticeMode" v-model="showAnswersDialog" max-width="600">
<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">
@@ -68,10 +69,10 @@
<v-expansion-panel-title>
<div class="d-flex align-center">
<v-icon
:color="isQuestionCorrect(index) ? 'success' : 'error'"
:color="getQuestionStatusColor(index)"
class="mr-2"
>
{{ isQuestionCorrect(index) ? 'mdi-check-circle' : 'mdi-close-circle' }}
{{ getQuestionStatusIcon(index) }}
</v-icon>
<span>Вопрос {{ index + 1 }}</span>
</div>
@@ -79,18 +80,32 @@
<v-expansion-panel-text>
<p class="mb-2 font-weight-bold">{{ question.name }}</p>
<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
:color="answer.right_wrong ? 'success' : ''"
:color="getAnswerColor(index, answer)"
size="small"
class="mr-1"
class="mr-2"
>
{{ answer.right_wrong ? 'mdi-check' : 'mdi-minus' }}
{{ getAnswerIcon(index, answer) }}
</v-icon>
<span :class="{ 'font-weight-bold': answer.right_wrong }">
<span :class="{ 'font-weight-bold': isAnswerCorrect(index, answer) }">
{{ answer.name }}
</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>
</v-expansion-panel-text>
</v-expansion-panel>
@@ -98,6 +113,19 @@
</v-card-text>
</v-card>
</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>
</template>
@@ -125,6 +153,10 @@ export default {
userAnswers: {
type: Array,
required: true
},
fromCompletedTab: {
type: Boolean,
default: false
}
},
setup(props) {
@@ -133,25 +165,132 @@ export default {
const isPracticeMode = computed(() => !route.query.mode || route.query.mode === 'practice');
const isQuestionCorrect = (questionIndex) => {
const question = props.questions[questionIndex];
const userAnswer = props.userAnswers[questionIndex];
if (!userAnswer) return false;
if (Array.isArray(userAnswer)) {
const correctAnswers = question.answers.filter(a => a.right_wrong).map(a => a.name);
return userAnswer.length === correctAnswers.length &&
userAnswer.every(answer => correctAnswers.includes(answer));
const getQuestionStatusColor = (questionIndex) => {
if (!props.questions[questionIndex]?.answers) return 'grey';
if (props.fromCompletedTab) {
return 'grey';
}
return question.answers.find(a => a.name === userAnswer)?.right_wrong || false;
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 (Array.isArray(userAnswer)) {
return userAnswer.includes(answerName);
}
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 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 {
showAnswersDialog,
isPracticeMode,
isQuestionCorrect
isQuestionCorrect,
hasUserAnswer,
showUserAnswer,
isAnswerCorrect,
getAnswerColor,
getAnswerIcon,
getQuestionStatusColor,
getQuestionStatusIcon
};
}
};
@@ -4,7 +4,7 @@
<div
v-for="(answer, aIndex) in question.answers"
:key="aIndex"
class="d-flex align-start mb-4"
class="d-flex align-start mb-4 ga-4"
>
<!-- Показываем иконку для переключения статуса только в режиме теста -->
<v-btn
@@ -35,12 +35,13 @@
hide-details
label="Картинка"
variant="outlined"
@update:model-value="() => previewAnswerImage(answer, aIndex)"
:error-messages="answer.imageError"
@update:model-value="(file) => handleImageUpload(file, answer, aIndex)"
></v-file-input>
<!-- Превью изображения ответа, если оно загружено -->
<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-avatar>
</div>
@@ -93,11 +94,50 @@ export default {
setup(props) {
const route = useRoute();
// Поддерживаем оба способа определения: через роут или через явный проп
const isTestRoute = computed(() => {
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) => {
// Используем right_wrong для тестов (совместимо с бэкендом)
answer.right_wrong = !answer.right_wrong;
@@ -128,6 +168,7 @@ export default {
isTestRoute,
toggleCorrect,
previewAnswerImage,
handleImageUpload,
isTest: props.isTest
};
}
@@ -12,7 +12,9 @@
label="Картинка для вопроса"
variant="outlined"
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>
<!-- Превью изображения вопроса, если оно загружено -->
@@ -225,6 +227,45 @@ export default {
const route = useRoute();
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 = () => {
props.question.answers = [];
emit('update:question', props.question);
@@ -290,7 +331,8 @@ export default {
onEmployeesChange,
isTestRoute,
questionImagePreview,
previewQuestionImage
previewQuestionImage,
handleQuestionImageUpload
};
},
};
@@ -44,11 +44,8 @@
></v-text-field>
<v-text-field
v-model="testSettings.question_count"
:rules="[rules.required, rules.positive]"
label="Количество вопросов в тесте"
type="number"
min="1"
:max="actualQuestionCount"
required
class="mr-2"
></v-text-field>
@@ -72,9 +69,10 @@
variant="outlined"
prepend-icon="mdi-image"
placeholder="Выберите изображение для теста"
hint="Логотип или изображение для теста"
hint="Логотип или изображение для теста (макс. 5MB, форматы: JPEG, PNG, GIF, WEBP)"
:error-messages="imageError"
:show-size="true"
@update:model-value="previewImage"
@update:model-value="handleTestImageUpload"
></v-file-input>
<!-- Превью изображения -->
@@ -316,6 +314,21 @@ export default {
setup(props, { emit }) {
const step = ref(0);
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({
title: '',
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 () => {
try {
if (props.isTest) {
@@ -603,7 +655,7 @@ export default {
}
watch(testImage, () => {
previewImage();
handleTestImageUpload(testImage.value);
});
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 {
if (!completionDate) {
const testDetails = await getTestDetail(testId);
completionDate = testDetails.dateend;
}
if (!startDate) {
const testDetails = await getTestDetail(testId);
startDate = testDetails.datestart;
}
const userIds = Array.from(employeeIds).map(id => Number(id));
const promises = userIds.map(userId =>
assignTestToUser(userId, testId, completionDate)
assignTestToUser(userId, testId, completionDate, startDate)
);
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 {
const response = await axiosApiInstance.post('/api/tests/testingview/', {
user_id: Number(userId),
test_id: Number(testId),
completion_date: completionDate
completion_date: completionDate,
datestart: startDate
});
return response.data;
} catch (error) {
+38 -12
View File
@@ -105,7 +105,7 @@
</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" />
</v-window-item>
</v-window>
@@ -175,6 +175,7 @@
:formattedTime="testResults.time_spent"
:questions="testResults.questions"
:userAnswers="testResults.user_answers"
:fromCompletedTab="testResults.fromCompletedTab"
/>
</v-card-text>
</v-card>
@@ -264,7 +265,7 @@ export default {
{ value: 0, title: `Назначенные (${currentTest.value})` },
{ value: 1, title: 'Завершенные' },
{ value: 2, title: 'Каталог' },
{ value: 3, title: 'Создать новый тест' },
...(accountStore.user.is_staff ? [{ value: 3, title: 'Создать новый тест' }] : []),
]);
const goToTest = (id) => router.push(`/test/testdetail/${id}`);
@@ -292,18 +293,21 @@ export default {
try {
const response = await getTestToUser(id);
console.log('API Response:', response);
const assignmentsByUser = response.reduce((acc, testing) => {
if (testing.user_details && testing.is_active) {
const existingUser = acc.find(u => u.id === testing.user_details.id);
if (!existingUser) {
acc.push({
...testing.user_details,
completion_date: testing.completion_date
completion_date: testing.completion_date,
datestart: testing.datestart
});
}
}
return acc;
}, []);
console.log('Transformed Data:', assignmentsByUser);
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 {
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;
getTestById();
@@ -387,14 +391,36 @@ export default {
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 = {
passed: resultResponse.data.is_passed,
total_questions: testDetailResponse.data.question_count,
total_answers: resultResponse.data.answered_questions_total,
correct_answers: resultResponse.data.score,
time_spent: `${testDetailResponse.data.time} мин`,
questions: [],
userAnswers: []
passed: resultResponse.data.is_passed || false,
total_questions: testDetailResponse.data.question_count || 0,
total_answers: resultResponse.data.answered_questions_total || 0,
correct_answers: resultResponse.data.score || 0,
time_spent: `${testDetailResponse.data.time || 0} мин`,
questions: questions,
userAnswers: userAnswers,
fromCompletedTab: activeTab.value === 1
};
showResultsDialog.value = true;