Files
PORTAL_COD2/src/front/src/components/vote/VoteConstructor.vue
T

621 lines
24 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<v-row class="pt-2 mx-1 flex-column fill-height flex-grow-0">
<CreatedVote v-if="isVoteCreated" :title="isTest ? 'Тест успешно создан' : 'Голосование успешно создано'">
<v-btn class="mt-4" color="teal-darken-4" @click="resetForm">
{{ isTest ? 'Создать ещё один тест' : 'Создать ещё одно голосование' }}
</v-btn>
</CreatedVote>
<template v-else>
<div class="v-col flex-grow-1">
<v-stepper v-model="step" class="d-flex flex-column fill-height" editable>
<v-stepper-header class="flex-grow-0 flex-shrink-1">
<v-stepper-item :complete="step > 0" step="1">Основная информация</v-stepper-item>
<v-divider></v-divider>
<v-stepper-item :complete="step > 1" step="2">{{ isTest ? 'Создание теста' : 'Создание опроса' }}</v-stepper-item>
<v-divider></v-divider>
<v-stepper-item :complete="step > 2" step="3">Подтверждение</v-stepper-item>
</v-stepper-header>
<v-stepper-window class="fill-height">
<!-- Основная информация -->
<v-stepper-window-item class="fill-height" step="1">
<MainInfo v-model:form="form" :rules="rules" :isTest="isTest">
<template v-if="isTest">
<v-card-text>
<div class="d-flex">
<v-text-field
v-model="testSettings.pass_perc"
:rules="[rules.required, rules.percent]"
label="Минимальный % правильных ответов"
type="number"
min="0"
max="100"
required
class="mr-2"
></v-text-field>
<v-text-field
v-model="testSettings.time"
:rules="[rules.required, rules.positive]"
label="Время на прохождение (мин)"
type="number"
min="1"
required
class="mr-2"
></v-text-field>
<v-text-field
v-model="testSettings.attemps_number"
:rules="[rules.required, rules.positive]"
label="Количество попыток"
type="number"
min="1"
required
></v-text-field>
</div>
<!-- Загрузка основного изображения теста -->
<div class="mt-4">
<v-file-input
v-model="testImage"
accept="image/*"
density="comfortable"
label="Изображение теста"
variant="outlined"
prepend-icon="mdi-image"
placeholder="Выберите изображение для теста"
hint="Логотип или изображение для теста"
:show-size="true"
@update:model-value="previewImage"
></v-file-input>
<!-- Превью изображения -->
<div v-if="imagePreview" class="d-flex justify-center mt-3">
<v-img
:src="imagePreview"
max-height="200"
max-width="300"
contain
>
<template v-slot:placeholder>
<v-row class="fill-height ma-0" align="center" justify="center">
<v-progress-circular indeterminate color="grey-lighten-5"></v-progress-circular>
</v-row>
</template>
</v-img>
</div>
</div>
</v-card-text>
</template>
<v-card-actions>
<v-btn color="teal-darken-4" size="medium" @click="step = 1">Далее</v-btn>
</v-card-actions>
</MainInfo>
</v-stepper-window-item>
<!-- Создание опроса -->
<v-stepper-window-item class="fill-height" step="2">
<v-card class="fill-height d-flex flex-column" flat>
<v-card-title>{{ isTest ? 'Создание теста:' : 'Создание опроса:' }}</v-card-title>
<v-card-text style="max-height: 62vh; overflow-y: auto">
<NewQuestion
:form="form"
:rules="rules"
:quests="quests"
@update:form="val => form.value = val"
:allEmployees="allEmployees"
:allEmployeesgroupedbydep="allEmployeesgroupedbydep"
:handleSelectAll="handleSelectAll"
:onEmployeesChange="onEmployeesChange"
:findEmployeeById="findEmployeeById"
:onlyDepdict="onlyDepdict"
:isTest="isTest"
/>
<v-divider class="ma-2 pa-1"></v-divider>
<div class="d-flex justify-center">
<v-btn color="orange-darken-4" size="small" @click="addQuestion"
>Добавить вопрос
</v-btn>
</div>
</v-card-text>
<v-card-actions>
<v-btn color="teal-darken-4" size="medium" @click="step -= 1">Назад</v-btn>
<v-btn color="teal-darken-4" size="medium" @click="step = 2">Далее</v-btn>
</v-card-actions>
</v-card>
</v-stepper-window-item>
<!-- Подтверждение -->
<v-stepper-window-item class="fill-height" step="3">
<v-card class="fill-height d-flex flex-column" flat>
<v-card-title>Подтверждение</v-card-title>
<v-card-text style="max-height: 62vh; overflow-y: auto">
<v-alert v-if="errorMessage" class="mb-4" type="error">
{{ errorMessage }}
</v-alert>
<p>
<v-icon
:class="form.title === null || form.title.length === 0 ? '' : 'opacity-0'"
color="red"
icon="mdi-alert"
size="xsmall"
/>
<strong class="px-2">Название:</strong> {{ form.title }}
</p>
<p>
<v-icon
:class="
form.description === null || form.description.length === 0
? ''
: 'opacity-0'
"
color="red"
icon="mdi-alert"
size="xsmall"
/>
<strong class="px-2">Описание:</strong> {{ form.description }}
</p>
<p>
<strong class="px-2">Дата начала:</strong>
{{ form.startDate.toLocaleDateString() }}
</p>
<p>
<strong class="px-2">Дата окончания:</strong>
{{ form.endDate.toLocaleDateString() }}
</p>
<!-- Показываем информацию о тесте, если это тест -->
<template v-if="isTest">
<p><strong class="px-2">Минимальный процент для сдачи:</strong> {{ testSettings.pass_perc }}%</p>
<p><strong class="px-2">Время прохождения (мин):</strong> {{ testSettings.time }}</p>
<p><strong class="px-2">Количество вопросов:</strong> {{ actualQuestionCount }}</p>
<p><strong class="px-2">Количество попыток:</strong> {{ testSettings.attemps_number }}</p>
<!-- Превью изображения теста на странице подтверждения -->
<div class="mt-2 mb-4">
<p><strong class="px-2">Изображение теста:</strong></p>
<div v-if="imagePreview" class="d-flex justify-center mt-2">
<v-img
:src="imagePreview"
max-height="150"
max-width="250"
contain
class="border rounded"
></v-img>
</div>
<p v-else class="text-grey text-center mt-2">Не выбрано</p>
</div>
</template>
<p><strong class="px-2">Вопросы:</strong></p>
<v-card
v-for="(question, index) in form.questions"
:key="index"
class="mb-4 pa-3"
>
<div class="pa-2">
<p>
<strong>Вопрос {{ index + 1 }}:</strong> {{ question.text }} ({{
question.type
}})
</p>
<!-- Показываем превью изображения вопроса, если оно есть -->
<div v-if="question.image" class="mt-2 mb-2">
<img
v-if="typeof question.image === 'object' && question.image !== null"
:src="getImagePreviewUrl(question.image)"
alt="Изображение вопроса"
style="max-width: 150px; max-height: 100px; object-fit: contain;"
class="ml-3 border-thin"
/>
</div>
<div v-if="question.settings.choice === 'free' && question.answers.length">
<p><strong>Варианты ответов:</strong></p>
<ul>
<li v-for="(answer, answerIndex) in question.answers" :key="answerIndex" class="mb-2">
<div class="d-flex align-center">
<span>{{ answer.text }}</span>
<!-- Для тестов показываем правильность ответа -->
<v-icon
v-if="isTest"
:color="answer.right_wrong ? 'green' : 'red'"
class="ml-2"
small
>
{{ answer.right_wrong ? 'mdi-check-circle' : 'mdi-close-circle' }}
</v-icon>
<!-- Показываем превью изображения ответа, если оно есть -->
<div v-if="answer.image" class="ml-2">
<img
v-if="typeof answer.image === 'object' && answer.image !== null"
:src="getImagePreviewUrl(answer.image)"
alt="Изображение ответа"
style="max-width: 100px; max-height: 60px; object-fit: contain;"
class="ml-1 border-thin"
/>
</div>
</div>
</li>
</ul>
</div>
<div
v-if="question.settings.choice === 'employee' && question.answers.length"
>
<div>
Количество допустимых ответов: {{ question.settings.multiChoice }}
</div>
<div class="">
Голосование по отделам:
{{ onlyDepdict.find((e) => e.value === question.settings.onlyDep).name }}
</div>
<p><strong>Выбранные сотрудники:</strong></p>
<ul>
<li v-for="employeeId in question.answers" :key="employeeId">
{{ findEmployeeById(employeeId.text).fio }}
</li>
</ul>
</div>
</div>
</v-card>
</v-card-text>
<v-card-actions>
<v-btn color="teal-darken-4" size="medium" @click="step -= 1">Назад</v-btn>
<v-btn
:disabled="errorMessage !== ''"
color="teal-darken-4"
size="medium"
@click="saveVoting"
>
Сохранить
</v-btn>
</v-card-actions>
</v-card>
</v-stepper-window-item>
</v-stepper-window>
</v-stepper>
</div>
</template>
</v-row>
</template>
<script>
import { computed, ref, watch } from 'vue';
import { createVote, getEmployees, createTest, assignTest } from '@/utils/axios-api';
import DateSelect from '@/components/UI/date-select.vue';
import MainInfo from '@/components/vote/ConstructorVote/MainInfo.vue';
import CreatedVote from '@/components/vote/ConstructorVote/CreatedVote.vue';
import NewQuestion from '@/components/vote/ConstructorVote/NewQuestion.vue';
import SearcEmployess from '@/components/UI/SearcEmployess.vue';
export default {
components: { NewQuestion, CreatedVote, MainInfo, DateSelect, SearcEmployess },
props: {
isTest: {
type: Boolean,
default: false
}
},
emits: ['updating'],
setup(props, { emit }) {
const step = ref(0);
const isVoteCreated = ref(false);
const form = ref({
title: '',
description: '',
startDate: new Date(),
endDate: new Date(new Date().setDate(new Date().getDate() + 14)),
questions: [],
createnews: false,
appoint: false
});
const testSettings = ref({
pass_perc: '70',
time: '30',
question_count: '10',
attemps_number: '3',
});
const testImage = ref(null);
const imagePreview = ref(null);
const selectedEmployees = ref([]);
const rules = {
required: (value) => !!value || 'Это поле обязательно для заполнения',
positive: (value) => parseInt(value) > 0 || 'Должно быть положительное число',
percent: (value) => (parseInt(value) >= 0 && parseInt(value) <= 100) || 'Должно быть от 0 до 100'
};
const currentQuestionIndex = ref(0);
const groupedEmployees = ref([]);
const allEmployees = computed(() => [...groupedEmployees.value]);
getEmployees().then((r) => (groupedEmployees.value = r));
const currentQuestion = computed(
() => form.value.questions[currentQuestionIndex.value] || null,
);
const allEmployeesgroupedbydep = computed(() => {
let groupped = [];
for (let x of allEmployees.value.sort(
(a, b) => a.id_dict_department - b.id_dict_department,
)) {
if (!groupped.includes(x.department)) groupped.push(x.department);
groupped.push(x);
}
return groupped;
});
const findEmployeeById = (id) =>
groupedEmployees.value.find((employee) => employee.id === id) || {};
const handleSelectAll = (selected, index) => {
if (!selected) {
form.value.questions[index].answers = groupedEmployees.value.map((employee) => ({
text: employee.id,
image: null,
}));
form.value.questions[index].selectedEmployees = groupedEmployees.value.map(
(employee) => employee.id,
);
} else {
form.value.questions[index].answers = [];
form.value.questions[index].selectedEmployees = [];
}
};
const isAllSelected = computed(
() => currentQuestion.value.answers.length === groupedEmployees.value.length,
);
const addQuestion = () => {
const initialAnswers = props.isTest ? [
{ text: '', image: null, right_wrong: false },
{ text: '', image: null, right_wrong: false },
] : [];
form.value.questions.push({
text: '',
settings: { choice: 'free', multiChoice: 1, onlyDep: null },
image: null,
answers: initialAnswers,
selectedEmployees: [],
});
currentQuestionIndex.value = form.value.questions.length - 1;
};
const removeQuestion = (index) => {
form.value.questions.splice(index, 1);
if (currentQuestionIndex.value >= form.value.questions.length) {
currentQuestionIndex.value = form.value.questions.length - 1;
}
};
const addAnswer = (index) => {
if (currentQuestion.value) {
form.value.questions[index].answers.push({
text: '',
image: null,
right_wrong: props.isTest ? false : undefined
});
}
};
const removeAnswer = (index, ind) => {
form.value.questions[index].answers.splice(ind, 1);
};
const errorMessage = ref('');
const validateAnswers = () => {
return form.value.questions.some((question) => {
if (question.settings.choice === 'free') {
return question.answers.some((answer) => !answer.text || answer.text.trim() === '');
}
return false;
});
};
const saveVoting = async () => {
try {
if (props.isTest) {
const testData = {
name: form.value.title,
description: form.value.description,
datestart: form.value.startDate,
dateend: form.value.endDate,
questions: form.value.questions.map(q => ({
text: q.text,
image: q.image,
settings: q.settings,
answers: q.answers.map(a => ({
text: a.text,
image: a.image,
right_wrong: a.right_wrong || false
}))
})),
image: testImage.value,
pass_perc: Number(testSettings.value.pass_perc),
time: Number(testSettings.value.time),
question_count: actualQuestionCount.value,
attemps_number: Number(testSettings.value.attemps_number)
};
const result = await createTest(testData);
if (selectedEmployees.value?.length > 0) {
await assignTest(result.id, selectedEmployees.value);
}
isVoteCreated.value = true;
emit('updating');
} else {
await createVote(form.value);
isVoteCreated.value = true;
emit('updating');
}
} catch (error) {
console.error('Ошибка при создании:', error);
let errorMessage = 'Произошла ошибка при создании';
if (error.response?.data?.message) {
errorMessage += ': ' + error.response.data.message;
}
alert(errorMessage);
}
};
const previewImage = () => {
if (testImage.value) {
const reader = new FileReader();
reader.onload = (e) => {
imagePreview.value = e.target.result;
};
reader.readAsDataURL(testImage.value);
} else {
imagePreview.value = null;
}
};
const resetForm = () => {
form.value = {
title: '',
description: '',
startDate: new Date(),
endDate: new Date(new Date().setDate(new Date().getDate() + 14)),
questions: [],
createnews: false,
appoint: false
};
testSettings.value = {
pass_perc: '70',
time: '30',
question_count: '10',
attemps_number: '3',
};
testImage.value = null;
imagePreview.value = null;
selectedEmployees.value = [];
step.value = 0;
isVoteCreated.value = false;
};
watch(
form.value,
() => {
if (!form.value.title || !form.value.description || form.value.questions.length < 1) {
errorMessage.value = 'Все обязательные поля должны быть заполнены';
} else {
errorMessage.value = '';
}
},
{ deep: true },
);
watch(
() => form.value.questions,
(newQuestions) => {
quests.value = newQuestions.map((q) => !!q.text.trim());
const hasEmptyQuestions = newQuestions.some((q) => !q.text || q.text.trim() === '');
const hasInvalidAnswers = validateAnswers();
errorMessage.value =
hasEmptyQuestions || hasInvalidAnswers
? 'Все вопросы и ответы должны быть заполнены'
: '';
},
{ deep: true },
);
const onEmployeesChange = (selected, index) => {
let ind = form.value.questions[index].selectedEmployees.findIndex((e) => e === selected);
if (ind > -1) {
form.value.questions[index].selectedEmployees.splice(ind, 1);
let answ = form.value.questions[index].answers.findIndex((a) => a.text === selected);
form.value.questions[index].answers.splice(answ, 1);
} else {
form.value.questions[index].selectedEmployees.push(selected);
form.value.questions[index].answers.push({ text: selected, image: null });
}
};
const onlyDepdict = [
{ name: 'За любого сотрудника', value: null },
{
name: 'Кроме своего отдела',
value: false,
},
{ name: 'Только за свой отдел', value: true },
];
const quests = computed(() => form.value.questions.map((question) => question.text.length > 0));
const actualQuestionCount = computed(() => form.value.questions.length);
const getImagePreviewUrl = (file) => {
if (file instanceof File) {
if (!file._cachedUrl) {
file._cachedUrl = URL.createObjectURL(file);
}
return file._cachedUrl;
}
return '';
};
if (props.isTest && form.value.questions.length === 0) {
addQuestion();
}
watch(testImage, () => {
previewImage();
});
return {
quests,
onlyDepdict,
allEmployeesgroupedbydep,
onEmployeesChange,
step,
form,
addQuestion,
removeQuestion,
addAnswer,
removeAnswer,
findEmployeeById,
saveVoting,
isVoteCreated,
resetForm,
rules,
errorMessage,
allEmployees,
handleSelectAll,
isAllSelected,
testSettings,
testImage,
imagePreview,
previewImage,
getImagePreviewUrl,
actualQuestionCount,
isTest: props.isTest
};
},
};
</script>
<style>
.v-input--horizontal .v-input__prepend {
margin-inline-end: 4px;
}
.list-enter-active,
.list-leave-active {
transition: all 0.5s ease;
}
.list-enter-from,
.list-leave-to {
opacity: 0;
transform: translateX(50px);
}
</style>