refactor [P-143 VoteConstructor]: объединение вотчеров

This commit is contained in:
Denzel committed 2025-02-14 10:01:11 +03:00
1 parent aae575f722
commit 55c575be71
1 file changed
+324 -198
+324 -198
View File
@@ -1,6 +1,5 @@
<template> <template>
<v-row class="pt-2 mx-1 flex-column fill-height flex-grow-0">
<v-row class="pt-2 mx-1 flex-column fill-height flex-grow-0 ">
<template v-if="isVoteCreated"> <template v-if="isVoteCreated">
<v-card class="d-flex flex-column flex-grow-1 flex-shrink-0 text-center pa-8" flat> <v-card class="d-flex flex-column flex-grow-1 flex-shrink-0 text-center pa-8" flat>
<v-spacer></v-spacer> <v-spacer></v-spacer>
@@ -8,18 +7,15 @@
<v-icon color="success" size="48">mdi-check-circle</v-icon> <v-icon color="success" size="48">mdi-check-circle</v-icon>
<h2 class="mt-4">Голосование создано!</h2> <h2 class="mt-4">Голосование создано!</h2>
<v-btn class="mt-4" color="teal-darken-4" @click="resetForm">Создать ещё</v-btn> <v-btn class="mt-4" color="teal-darken-4" @click="resetForm">Создать ещё</v-btn>
</div> </div>
<v-spacer></v-spacer> <v-spacer></v-spacer>
</v-card> </v-card>
</template> </template>
<template v-else> <template v-else>
<div class="v-col flex-grow-1 flex-shrink-0 "> <div class="v-col flex-grow-1 flex-shrink-0">
<v-stepper v-model="step" class="d-flex flex-column fill-height" editable> <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-header class="flex-grow-0 flex-shrink-1">
<v-stepper-item :complete="step > 0" step="1">Основная информация <v-stepper-item :complete="step > 0" step="1">Основная информация </v-stepper-item>
</v-stepper-item>
<v-divider></v-divider> <v-divider></v-divider>
<v-stepper-item :complete="step > 1" step="2">Создание опроса</v-stepper-item> <v-stepper-item :complete="step > 1" step="2">Создание опроса</v-stepper-item>
<v-divider></v-divider> <v-divider></v-divider>
@@ -29,35 +25,49 @@
<v-stepper-window class="fill-height"> <v-stepper-window class="fill-height">
<!-- Основная информация --> <!-- Основная информация -->
<v-stepper-window-item class="fill-height" step="1"> <v-stepper-window-item class="fill-height" step="1">
<v-card class="fill-height d-flex flex-column " flat> <v-card class="fill-height d-flex flex-column" flat>
<v-card-title>Основная информация</v-card-title> <v-card-title>Основная информация</v-card-title>
<v-card-text class="d-flex flex-column overflow-auto"> <v-card-text class="d-flex flex-column overflow-auto">
<v-text-field v-model="form.title" :rules="[rules.required]" class="flex-grow-0 flex-shrink-1" <v-text-field
v-model="form.title"
:rules="[rules.required]"
class="flex-grow-0 flex-shrink-1"
label="Название голосования" label="Название голосования"
variant="underlined"></v-text-field> variant="underlined"
></v-text-field>
<div class="flex-grow-1 flex-shrink-0"> <div class="flex-grow-1 flex-shrink-0">
<v-textarea
<v-textarea v-model="form.description" :rules="[rules.required]" label="Описание" v-model="form.description"
:rules="[rules.required]"
variant="outlined"></v-textarea> label="Описание"
variant="outlined"
></v-textarea>
</div> </div>
<v-divider></v-divider> <v-divider></v-divider>
<div class="flex-grow-0 flex-shrink-1"> <div class="flex-grow-0 flex-shrink-1">
<div class="pt-2 d-flex align-center"><span class="text-overline text-grey text-center">Публикация новости: </span> <div class="pt-2 d-flex align-center">
<v-switch v-model="form.createnews" <span class="text-overline text-grey text-center">Публикация новости: </span>
<v-switch
v-model="form.createnews"
class="px-2" class="px-2"
density="comfortable" density="comfortable"
hide-details hide-details
color="primary" color="primary"
:label="form.createnews?'да':'нет'" :label="form.createnews ? 'да' : 'нет'"
></v-switch></div> ></v-switch>
</div>
<div class="pt-2 text-overline text-grey">Дата и время:</div> <div class="pt-2 text-overline text-grey">Дата и время:</div>
<div class="d-flex justify-space-around"> <div class="d-flex justify-space-around">
<div class="d-flex ga-3 align-center"> <div class="d-flex ga-3 align-center">
<h6 class="text-subtitle-1 pt-2">начало:</h6> <h6 class="text-subtitle-1 pt-2">начало:</h6>
<date-select :datedefault="form.startDate" @returndate="returnstart"/> <date-select :datedefault="form.startDate" @returndate="returnstart" />
<v-select v-model="selectedTimeStart" :items="timeOptions" density="compact" hide-details <v-select
variant="plain"> v-model="selectedTimeStart"
:items="timeOptions"
density="compact"
hide-details
variant="plain"
>
<template v-slot:prepend-inner> <template v-slot:prepend-inner>
<v-icon color="red" icon="mdi-timer" size="xsmall"></v-icon> <v-icon color="red" icon="mdi-timer" size="xsmall"></v-icon>
</template> </template>
@@ -65,10 +75,15 @@
</div> </div>
<div class="d-flex ga-3 align-center"> <div class="d-flex ga-3 align-center">
<h6 class="text-subtitle-1 pt-2">окончание:</h6> <h6 class="text-subtitle-1 pt-2">окончание:</h6>
<date-select :datedefault="form.endDate" @returndate="returnend"/> <date-select :datedefault="form.endDate" @returndate="returnend" />
<v-select v-model="selectedTimeEnd" :items="timeOptions" density="compact" hide-details <v-select
v-model="selectedTimeEnd"
:items="timeOptions"
density="compact"
hide-details
outlined outlined
variant="plain"> variant="plain"
>
<template v-slot:prepend-inner> <template v-slot:prepend-inner>
<v-icon color="red" icon="mdi-timer" size="xsmall"></v-icon> <v-icon color="red" icon="mdi-timer" size="xsmall"></v-icon>
</template> </template>
@@ -86,15 +101,14 @@
<!-- Создание опроса --> <!-- Создание опроса -->
<v-stepper-window-item class="fill-height" step="2"> <v-stepper-window-item class="fill-height" step="2">
<v-card class="fill-height d-flex flex-column" flat> <v-card class="fill-height d-flex flex-column" flat>
<v-card-title>Создание опроса:</v-card-title> <v-card-title>Создание опроса:</v-card-title>
<v-card-text style="max-height: 62vh; overflow-y: auto;"> <v-card-text style="max-height: 62vh; overflow-y: auto">
<transition-group name="list" tag="div"> <transition-group name="list" tag="div">
<div v-for="(question, index) in form.questions" :key="index" class="mb-4"> <div v-for="(question, index) in form.questions" :key="index" class="mb-4">
<div class="d-flex"> <div class="d-flex">
<!-- <v-text-field v-model="question.text" :label="'Вопрос ' + (index + 1)" :rules="[rules.required]"--> <!-- <v-text-field v-model="question.text" :label="'Вопрос ' + (index + 1)" :rules="[rules.required]"-->
<!-- density="comfortable" variant="underlined">--> <!-- density="comfortable" variant="underlined">-->
<v-text-field <v-text-field
v-model="question.text" v-model="question.text"
:label="'Вопрос ' + (index + 1)" :label="'Вопрос ' + (index + 1)"
@@ -104,59 +118,79 @@
@input="updateQuest(index)" @input="updateQuest(index)"
> >
<template v-slot:append> <template v-slot:append>
<v-btn color="error" icon="mdi-delete" size="small" @click="removeQuestion(index)"/> <v-btn
color="error"
icon="mdi-delete"
size="small"
@click="removeQuestion(index)"
/>
</template> </template>
</v-text-field> </v-text-field>
</div> </div>
<v-file-input v-model="question.image" accept="image/*" density="comfortable" <v-file-input
label="Картинка для вопроса" variant="outlined"></v-file-input> v-model="question.image"
accept="image/*"
density="comfortable"
label="Картинка для вопроса"
variant="outlined"
></v-file-input>
<v-divider></v-divider> <v-divider></v-divider>
<div class="py-2 text-overline text-grey">Настройки вопроса</div> <div class="py-2 text-overline text-grey">Настройки вопроса</div>
<div class="v-row "> <div class="v-row">
<v-col class="align-self-center font-weight-bold py-0" cols="auto"> <v-col class="align-self-center font-weight-bold py-0" cols="auto">
Тип ответа Тип ответа
</v-col> </v-col>
<v-col class="py-0 align-self-center " cols="3"> <v-col class="py-0 align-self-center" cols="3">
<v-select
<v-select v-model="question.settings.choice" :items="questionTypes" :list-props="{density:'compact'}" v-model="question.settings.choice"
:items="questionTypes"
:list-props="{ density: 'compact' }"
density="compact" density="compact"
hide-details hide-details
item-title="name" item-value="choice" label="" variant="outlined" item-title="name"
@update:model-value="question.answers=[]"></v-select> item-value="choice"
label=""
variant="outlined"
@update:model-value="question.answers = []"
></v-select>
<!-- choice --> <!-- choice -->
</v-col> </v-col>
<v-spacer/> <v-spacer />
<v-col class="align-self-center font-weight-bold" cols="auto"> <v-col class="align-self-center font-weight-bold" cols="auto">
Число возможных ответов Число возможных ответов
</v-col> </v-col>
<v-col class="" cols="1"> <v-col class="" cols="1">
<v-text-field v-model="question.settings.multiChoice" :rules="[rules.required && question.settings.multiChoice > 0]" <v-text-field
density="compact" hide-details v-model="question.settings.multiChoice"
:rules="[rules.required && question.settings.multiChoice > 0]"
density="compact"
hide-details
min="1" min="1"
type="number" variant="outlined"> type="number"
<template v-slot:prepend> variant="outlined"
>
</template> <template v-slot:prepend> </template>
</v-text-field> </v-text-field>
</v-col> </v-col>
</div> </div>
<div class="v-row"> <div class="v-row"></div>
</div>
<v-card-text class="px-0"> <v-card-text class="px-0">
<div v-if="question.settings.choice === 'free'"> <div v-if="question.settings.choice === 'free'">
<transition-group name="list" tag="div"> <transition-group name="list" tag="div">
<div v-for="(answer, ind) in question.answers" :key="ind" class="d-flex align-start mb-4"> <div
v-for="(answer, ind) in question.answers"
:key="ind"
class="d-flex align-start mb-4"
>
<v-text-field <v-text-field
v-model="answer.text" v-model="answer.text"
:label="'Ответ ' + (ind + 1)" :label="'Ответ ' + (ind + 1)"
:rules="[rules.required]" :rules="[rules.required]"
class="mr-4" class="mr-4"
density="compact" density="compact"
variant="outlined"> variant="outlined"
>
</v-text-field> </v-text-field>
<v-file-input <v-file-input
v-model="answer.image" v-model="answer.image"
@@ -165,28 +199,38 @@
density="compact" density="compact"
hide-details hide-details
label="Картинка" label="Картинка"
variant="outlined"> variant="outlined"
>
</v-file-input> </v-file-input>
<v-btn <v-btn
class="ms-1" class="ms-1"
color="error" color="error"
icon="mdi-delete" icon="mdi-delete"
size="small" size="small"
@click="removeAnswer(index, ind)"> @click="removeAnswer(index, ind)"
>
</v-btn> </v-btn>
</div> </div>
</transition-group> </transition-group>
<div class="d-flex justify-start"> <div class="d-flex justify-start">
<v-btn color="teal-darken-4" size="small" @click="addAnswer(index)">Добавить ответ</v-btn> <v-btn color="teal-darken-4" size="small" @click="addAnswer(index)"
>Добавить ответ</v-btn
>
</div> </div>
</div> </div>
<div v-else> <div v-else>
<div class="v-row"> <div class="v-row">
<v-radio-group v-model="question.settings.onlyDep" class="text-caption" inline> <v-radio-group
v-model="question.settings.onlyDep"
class="text-caption"
inline
>
<template v-slot:label> <template v-slot:label>
<div class="text-body-2 font-weight-bold">Голосование по отделам:</div> <div class="text-body-2 font-weight-bold">
Голосование по отделам:
</div>
</template> </template>
<v-radio v-for="x in onlyDepdict" :key="x.name" :value=x.value> <v-radio v-for="x in onlyDepdict" :key="x.name" :value="x.value">
<template v-slot:label> <template v-slot:label>
<div class="text-caption">{{ x.name }}</div> <div class="text-caption">{{ x.name }}</div>
</template> </template>
@@ -195,66 +239,114 @@
</div> </div>
<v-autocomplete <v-autocomplete
v-model="question.selectedEmployees" v-model="question.selectedEmployees"
:items="allEmployeesgroupedbydep" class=" text-no-wrap" :items="allEmployeesgroupedbydep"
density="compact" item-title="fio" item-value="id" label="Выберите сотрудников" multiple class="text-no-wrap"
density="compact"
item-title="fio"
item-value="id"
label="Выберите сотрудников"
multiple
variant="outlined" variant="outlined"
@update:model-value="(selected)=>question.answers=question.answers.filter(e=>selected.includes(e.text))" @update:model-value="
(selected) =>
(question.answers = question.answers.filter((e) =>
selected.includes(e.text),
))
"
> >
<template #prepend-item> <template #prepend-item>
<v-checkbox :model-value="question.selectedEmployees.length===allEmployees.length" <v-checkbox
:model-value="
question.selectedEmployees.length === allEmployees.length
"
class="pa-0" class="pa-0"
label="Все" label="Все"
@update:model-value="handleSelectAll(question.selectedEmployees.length===allEmployees.length, index)"></v-checkbox> @update:model-value="
handleSelectAll(
question.selectedEmployees.length === allEmployees.length,
index,
)
"
></v-checkbox>
</template> </template>
<template #selection="{item}"> <template #selection="{ item }">
<v-chip <v-chip
:prepend-avatar="checkremote(`${spravURL}${item.raw.login}.jpg`)" :prepend-avatar="checkremote(`${spravURL}${item.raw.login}.jpg`)"
> >
{{ item.raw.familyname }} {{ item.raw.familyname }}
</v-chip> </v-chip>
</template> </template>
<template #item="data"> <template #item="data">
<template v-if="typeof data.item.raw !== 'object'"> <template v-if="typeof data.item.raw !== 'object'">
<v-divider/> <v-divider />
<v-list-group class='pa-4 text-overline text-grey' <v-list-group
v-text="data.item.raw"></v-list-group> class="pa-4 text-overline text-grey"
v-text="data.item.raw"
></v-list-group>
</template> </template>
<template v-else> <template v-else>
<v-list-item <v-list-item
:append-avatar="
:append-avatar="checkremote(`${spravURL}${data.item.raw.login}.jpg`)" checkremote(`${spravURL}${data.item.raw.login}.jpg`)
"
density="compact" density="compact"
slim slim
@click="onEmployeesChange(data.item.raw.id, index)" @click="onEmployeesChange(data.item.raw.id, index)"
> >
<template #prepend> <template #prepend>
<v-checkbox
<v-checkbox :model-value="question.selectedEmployees.includes(data.item.raw.id)" :model-value="
question.selectedEmployees.includes(data.item.raw.id)
"
density="compact" density="compact"
hide-details></v-checkbox> hide-details
></v-checkbox>
</template> </template>
<v-list-item-title class="text-third" v-text="data.item.raw.fio"></v-list-item-title> <v-list-item-title
class="text-third"
v-text="data.item.raw.fio"
></v-list-item-title>
</v-list-item> </v-list-item>
</template> </template>
</template> </template>
</v-autocomplete> </v-autocomplete>
<transition-group name="list" tag="div"> <transition-group name="list" tag="div">
<div v-for="(person, ind) in question.answers" :key="person" <div
class="v-row align-center mb-4"> v-for="(person, ind) in question.answers"
:key="person"
class="v-row align-center mb-4"
>
<v-col class="py-0" cols="7"> <v-col class="py-0" cols="7">
<v-chip <v-chip
:prepend-avatar="checkremote(`${spravURL}${findEmployeeById(person.text)?.login}.jpg`)" :prepend-avatar="
:text="findEmployeeById(person.text)?.fio "> checkremote(
`${spravURL}${findEmployeeById(person.text)?.login}.jpg`,
)
"
:text="findEmployeeById(person.text)?.fio"
>
</v-chip> </v-chip>
</v-col> </v-col>
<v-col class="py-0 d-flex" cols="5"> <v-col class="py-0 d-flex" cols="5">
<v-file-input v-model="person.image" accept="image/*" dense density="compact" <v-file-input
v-model="person.image"
accept="image/*"
dense
density="compact"
hide-details hide-details
label="Картинка" variant="outlined"></v-file-input> label="Картинка"
<v-btn class="ms-1" color="error" icon="mdi-delete" size="small" variant="outlined"
@click="question.selectedEmployees.splice(ind,1); removeAnswer(index,ind)"> ></v-file-input>
<v-btn
class="ms-1"
color="error"
icon="mdi-delete"
size="small"
@click="
question.selectedEmployees.splice(ind, 1);
removeAnswer(index, ind);
"
>
</v-btn> </v-btn>
</v-col> </v-col>
</div> </div>
@@ -265,7 +357,9 @@
</transition-group> </transition-group>
<v-divider class="ma-2 pa-1"></v-divider> <v-divider class="ma-2 pa-1"></v-divider>
<div class="d-flex justify-center"> <div class="d-flex justify-center">
<v-btn color="orange-darken-4" size="small" @click="addQuestion">Добавить вопрос</v-btn> <v-btn color="orange-darken-4" size="small" @click="addQuestion"
>Добавить вопрос</v-btn
>
</div> </div>
</v-card-text> </v-card-text>
<v-card-actions> <v-card-actions>
@@ -273,52 +367,79 @@
<v-btn color="teal-darken-4" size="medium" @click="step = 2">Далее</v-btn> <v-btn color="teal-darken-4" size="medium" @click="step = 2">Далее</v-btn>
</v-card-actions> </v-card-actions>
</v-card> </v-card>
</v-stepper-window-item> </v-stepper-window-item>
<!-- Подтверждение --> <!-- Подтверждение -->
<v-stepper-window-item class="fill-height" step="3"> <v-stepper-window-item class="fill-height" step="3">
<v-card class="fill-height d-flex flex-column" flat> <v-card class="fill-height d-flex flex-column" flat>
<v-card-title>Подтверждение</v-card-title> <v-card-title>Подтверждение</v-card-title>
<v-card-text style="max-height: 62vh; overflow-y: auto;"> <v-card-text style="max-height: 62vh; overflow-y: auto">
<v-alert v-if="errorMessage" class="mb-4 " type="error"> <v-alert v-if="errorMessage" class="mb-4" type="error">
{{ errorMessage }} {{ errorMessage }}
</v-alert> </v-alert>
<p> <p>
<v-icon :class="form.title===null||form.title.length===0?'':'opacity-0'" color='red' icon="mdi-alert" <v-icon
size="xsmall"/> :class="form.title === null || form.title.length === 0 ? '' : 'opacity-0'"
color="red"
icon="mdi-alert"
size="xsmall"
/>
<strong class="px-2">Название:</strong> {{ form.title }} <strong class="px-2">Название:</strong> {{ form.title }}
</p> </p>
<p> <p>
<v-icon :class="form.description===null||form.description.length===0?'':'opacity-0'" color='red' <v-icon
icon="mdi-alert" size="xsmall"/> :class="
form.description === null || form.description.length === 0
? ''
: 'opacity-0'
"
color="red"
icon="mdi-alert"
size="xsmall"
/>
<strong class="px-2">Описание:</strong> {{ form.description }} <strong class="px-2">Описание:</strong> {{ form.description }}
</p> </p>
<p><strong class="px-2">Дата начала:</strong> {{ form.startDate.toLocaleDateString() }}</p> <p>
<p><strong class="px-2">Дата окончания:</strong> {{ form.endDate.toLocaleDateString() }}</p> <strong class="px-2">Дата начала:</strong>
{{ form.startDate.toLocaleDateString() }}
</p>
<p>
<strong class="px-2">Дата окончания:</strong>
{{ form.endDate.toLocaleDateString() }}
</p>
<p><strong class="px-2">Вопросы:</strong></p> <p><strong class="px-2">Вопросы:</strong></p>
<v-card v-for="(question, index) in form.questions" :key="index" class="mb-4 pa-3"> <v-card
v-for="(question, index) in form.questions"
:key="index"
class="mb-4 pa-3"
>
<div class="pa-2"> <div class="pa-2">
<p>
<p><strong>Вопрос {{ index + 1 }}:</strong> {{ question.text }} ({{ question.type }})</p> <strong>Вопрос {{ index + 1 }}:</strong> {{ question.text }} ({{
question.type
}})
</p>
<div v-if="question.settings.choice === 'free' && question.answers.length"> <div v-if="question.settings.choice === 'free' && question.answers.length">
<p><strong>Варианты ответов:</strong></p> <p><strong>Варианты ответов:</strong></p>
<ul> <ul>
<li v-for="(answer, answerIndex) in question.answers" :key="answerIndex"> <li v-for="(answer, answerIndex) in question.answers" :key="answerIndex">
{{ answer.text }} {{ answer.text }}
</li> </li>
</ul> </ul>
</div> </div>
<div v-if="question.settings.choice === 'employee' && question.answers.length"> <div
<div>Количество допустимых ответов: {{ question.settings.multiChoice }}</div> v-if="question.settings.choice === 'employee' && question.answers.length"
<div class="">Голосование по отделам: >
{{ onlyDepdict.find(e => e.value === question.settings.onlyDep).name }} <div>
Количество допустимых ответов: {{ question.settings.multiChoice }}
</div>
<div class="">
Голосование по отделам:
{{ onlyDepdict.find((e) => e.value === question.settings.onlyDep).name }}
</div> </div>
<p><strong>Выбранные сотрудники:</strong></p> <p><strong>Выбранные сотрудники:</strong></p>
<ul> <ul>
@@ -329,100 +450,105 @@
</div> </div>
</div> </div>
</v-card> </v-card>
</v-card-text> </v-card-text>
<v-card-actions> <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 -= 1">Назад</v-btn>
<v-btn :disabled="errorMessage!=''" color="teal-darken-4" size="medium" @click="saveVoting"> <v-btn
:disabled="errorMessage != ''"
color="teal-darken-4"
size="medium"
@click="saveVoting"
>
Сохранить Сохранить
</v-btn> </v-btn>
</v-card-actions> </v-card-actions>
</v-card> </v-card>
</v-stepper-window-item> </v-stepper-window-item>
</v-stepper-window> </v-stepper-window>
</v-stepper> </v-stepper>
</div> </div>
</template> </template>
</v-row> </v-row>
</template> </template>
<script> <script>
import {computed, ref, watch} from "vue"; import { computed, ref, watch } from 'vue';
import {createVote, getEmployees, spravURL} from "@/utils/axios-api"; import { createVote, getEmployees, spravURL } from '@/utils/axios-api';
import DateSelect from "@/components/UI/date-select.vue"; import DateSelect from '@/components/UI/date-select.vue';
import {checkremote} from "@/utils/universal_functions"; import { checkremote } from '@/utils/universal_functions';
export default { export default {
components: {DateSelect}, components: { DateSelect },
emits: ['updating'], emits: ['updating'],
setup(props, {emit}) { setup(props, { emit }) {
const step = ref(0); const step = ref(0);
const isVoteCreated = ref(false); const isVoteCreated = ref(false);
const form = ref({ const form = ref({
title: "", title: '',
description: "", description: '',
startDate: new Date(), startDate: new Date(),
endDate: new Date(new Date().setDate(new Date().getDate() + 14)), endDate: new Date(new Date().setDate(new Date().getDate() + 14)),
questions: [], questions: [],
createnews:false createnews: false,
}); });
const rules = { const rules = {
required: (value) => !!value || "Это поле обязательно для заполнения", required: (value) => !!value || 'Это поле обязательно для заполнения',
}; };
const currentQuestionIndex = ref(0); const currentQuestionIndex = ref(0);
const questionTypes = [{name: "Ввести вручную", choice: 'free'}, {name: "Выбрать сотрудника", choice: 'employee'}]; const questionTypes = [
{ name: 'Ввести вручную', choice: 'free' },
{ name: 'Выбрать сотрудника', choice: 'employee' },
];
const groupedEmployees = ref([]); const groupedEmployees = ref([]);
const allEmployees = computed(() => [ const allEmployees = computed(() => [...groupedEmployees.value]);
...groupedEmployees.value,
]);
getEmployees() getEmployees().then((r) => (groupedEmployees.value = r));
.then(r => groupedEmployees.value = r)
const currentQuestion = computed(() => const currentQuestion = computed(
form.value.questions[currentQuestionIndex.value] || null () => form.value.questions[currentQuestionIndex.value] || null,
); );
const allEmployeesgroupedbydep = computed(() => { const allEmployeesgroupedbydep = computed(() => {
let groupped = [] let groupped = [];
for (let x of allEmployees.value.sort((a, b) => a.id_dict_department - b.id_dict_department)) { for (let x of allEmployees.value.sort(
if (!groupped.includes(x.department)) groupped.push(x.department) (a, b) => a.id_dict_department - b.id_dict_department,
groupped.push(x) )) {
if (!groupped.includes(x.department)) groupped.push(x.department);
groupped.push(x);
} }
return groupped return groupped;
}) });
const findEmployeeById = (id) => const findEmployeeById = (id) =>
groupedEmployees.value.find((employee) => employee.id === id) || {}; groupedEmployees.value.find((employee) => employee.id === id) || {};
const handleSelectAll = (selected, index) => { const handleSelectAll = (selected, index) => {
if (!selected) { if (!selected) {
form.value.questions[index].answers = groupedEmployees.value.map((employee) => ({ form.value.questions[index].answers = groupedEmployees.value.map((employee) => ({
text: employee.id, text: employee.id,
image: null, image: null,
})); }));
form.value.questions[index].selectedEmployees = groupedEmployees.value.map(employee => employee.id); form.value.questions[index].selectedEmployees = groupedEmployees.value.map(
(employee) => employee.id,
);
} else { } else {
form.value.questions[index].answers = []; form.value.questions[index].answers = [];
form.value.questions[index].selectedEmployees = [] form.value.questions[index].selectedEmployees = [];
} }
}; };
const isAllSelected = computed(() => currentQuestion.value.answers.length === groupedEmployees.value.length); const isAllSelected = computed(
() => currentQuestion.value.answers.length === groupedEmployees.value.length,
);
const addQuestion = () => { const addQuestion = () => {
form.value.questions.push({ form.value.questions.push({
text: "", text: '',
settings: {choice: "free", multiChoice: 1, onlyDep: null}, settings: { choice: 'free', multiChoice: 1, onlyDep: null },
image: null, image: null,
answers: [], answers: [],
selectedEmployees: [] selectedEmployees: [],
}); });
currentQuestionIndex.value = form.value.questions.length - 1; currentQuestionIndex.value = form.value.questions.length - 1;
}; };
@@ -440,22 +566,20 @@ export default {
const addAnswer = (index) => { const addAnswer = (index) => {
if (currentQuestion.value) { if (currentQuestion.value) {
form.value.questions[index].answers.push({text: "", image: null}); form.value.questions[index].answers.push({ text: '', image: null });
} }
}; };
const removeAnswer = (index, ind) => { const removeAnswer = (index, ind) => {
form.value.questions[index].answers.splice(ind, 1) form.value.questions[index].answers.splice(ind, 1);
}; };
const errorMessage = ref(""); const errorMessage = ref('');
const validateAnswers = () => { const validateAnswers = () => {
return form.value.questions.some((question) => { return form.value.questions.some((question) => {
if (question.settings.choice === "free") { if (question.settings.choice === 'free') {
return question.answers.some( return question.answers.some((answer) => !answer.text || answer.text.trim() === '');
(answer) => !answer.text || answer.text.trim() === ""
);
} }
return false; return false;
}); });
@@ -472,25 +596,24 @@ export default {
hasEmptyQuestions || hasEmptyQuestions ||
hasInvalidAnswers hasInvalidAnswers
) { ) {
errorMessage.value = "Все обязательные поля и ответы должны быть заполнены"; errorMessage.value = 'Все обязательные поля и ответы должны быть заполнены';
return; return;
} }
try { try {
const response = await createVote(form.value); const response = await createVote(form.value);
console.log("Голосование успешно создано:", response); console.log('Голосование успешно создано:', response);
isVoteCreated.value = true; isVoteCreated.value = true;
emit("updating", "active"); emit('updating', 'active');
} catch (error) { } catch (error) {
console.error("Ошибка при создании голосования:", error); console.error('Ошибка при создании голосования:', error);
} }
}; };
const resetForm = () => { const resetForm = () => {
form.value = { form.value = {
title: "", title: '',
description: "", description: '',
startDate: new Date(), startDate: new Date(),
endDate: new Date(new Date().setDate(new Date().getDate() + 14)), endDate: new Date(new Date().setDate(new Date().getDate() + 14)),
questions: [], questions: [],
@@ -499,94 +622,98 @@ export default {
isVoteCreated.value = false; isVoteCreated.value = false;
}; };
const timeOptions = Array.from({length: 48}, (_, i) => { const timeOptions = Array.from({ length: 48 }, (_, i) => {
const hours = String(Math.floor(i / 2)).padStart(2, "0"); const hours = String(Math.floor(i / 2)).padStart(2, '0');
const minutes = i % 2 === 0 ? "00" : "30"; const minutes = i % 2 === 0 ? '00' : '30';
return `${hours}:${minutes}`; return `${hours}:${minutes}`;
}); });
const selectedTimeStart = ref( const selectedTimeStart = ref(
`${(form.value.startDate.getHours() + 1).toString().padStart(2, "0")}:00` `${(form.value.startDate.getHours() + 1).toString().padStart(2, '0')}:00`,
); );
const selectedTimeEnd = ref( const selectedTimeEnd = ref(
`${(form.value.endDate.getHours() + 1).toString().padStart(2, "0")}:00` `${(form.value.endDate.getHours() + 1).toString().padStart(2, '0')}:00`,
); );
watch(form.value, () => { watch(
form.value,
() => {
if (!form.value.title || !form.value.description || form.value.questions.length < 1) { if (!form.value.title || !form.value.description || form.value.questions.length < 1) {
errorMessage.value = "Все обязательные поля должны быть заполнены"; errorMessage.value = 'Все обязательные поля должны быть заполнены';
} else { } else {
errorMessage.value = ""; errorMessage.value = '';
} }
}, { deep: true }); },
{ deep: true },
);
const updateQuests = () => { const updateQuests = () => {
quests.value = form.value.questions.map((q) => !!q.text.trim()); quests.value = form.value.questions.map((q) => !!q.text.trim());
}; };
watch(() => form.value.questions, updateQuests, { deep: true });
watch( watch(
() => form.value.questions, () => form.value.questions,
(newQuestions) => { (newQuestions) => {
const hasEmptyQuestions = newQuestions.some((q) => !q.text || q.text.trim() === ""); // Обновляем quests
quests.value = newQuestions.map((q) => !!q.text.trim());
// Проверяем, есть ли пустые вопросы или невалидные ответы
const hasEmptyQuestions = newQuestions.some((q) => !q.text || q.text.trim() === '');
const hasInvalidAnswers = validateAnswers(); const hasInvalidAnswers = validateAnswers();
if (hasEmptyQuestions || hasInvalidAnswers) { errorMessage.value =
errorMessage.value = "Все вопросы и ответы должны быть заполнены"; hasEmptyQuestions || hasInvalidAnswers
} else { ? 'Все вопросы и ответы должны быть заполнены'
errorMessage.value = ""; : '';
}
}, },
{ deep: true } { deep: true },
); );
watch([selectedTimeStart, selectedTimeEnd], ([newStart, newEnd]) => {
watch(selectedTimeStart, () => { updateStartDate();
updateStartDate() updateEndDate();
}) });
watch(selectedTimeEnd, () => {
updateEndDate()
})
const updateStartDate = () => { const updateStartDate = () => {
const [hours, minutes] = selectedTimeStart.value.split(":").map(Number); const [hours, minutes] = selectedTimeStart.value.split(':').map(Number);
form.value.startDate.setHours(hours, minutes); form.value.startDate.setHours(hours, minutes);
}; };
const updateEndDate = () => { const updateEndDate = () => {
const [hours, minutes] = selectedTimeEnd.value.split(":").map(Number); const [hours, minutes] = selectedTimeEnd.value.split(':').map(Number);
form.value.endDate.setHours(hours, minutes); form.value.endDate.setHours(hours, minutes);
}; };
const returnstart = (dates) => { const returnstart = (dates) => {
form.value.startDate = dates form.value.startDate = dates;
} };
const returnend = (dates) => { const returnend = (dates) => {
form.value.endDate = dates form.value.endDate = dates;
} };
const onEmployeesChange = (selected, index) => { const onEmployeesChange = (selected, index) => {
let ind = form.value.questions[index].selectedEmployees.findIndex(e => e === selected) let ind = form.value.questions[index].selectedEmployees.findIndex((e) => e === selected);
if (ind > -1) { if (ind > -1) {
form.value.questions[index].selectedEmployees.splice(ind, 1) form.value.questions[index].selectedEmployees.splice(ind, 1);
let answ = form.value.questions[index].answers.findIndex(a => a.text === selected) let answ = form.value.questions[index].answers.findIndex((a) => a.text === selected);
form.value.questions[index].answers.splice(answ, 1) form.value.questions[index].answers.splice(answ, 1);
} else { } else {
form.value.questions[index].selectedEmployees.push(selected) form.value.questions[index].selectedEmployees.push(selected);
form.value.questions[index].answers.push({text: selected, image: null}); form.value.questions[index].answers.push({ text: selected, image: null });
} }
}; };
const onlyDepdict = [{name: 'За любого сотрудника', value: null}, { const onlyDepdict = [
name: "Кроме своего отдела", { name: 'За любого сотрудника', value: null },
value: false {
}, {name: "Только за свой отдел", value: true}] name: 'Кроме своего отдела',
value: false,
},
{ name: 'Только за свой отдел', value: true },
];
const quests = computed(() => const quests = computed(() => form.value.questions.map((question) => question.text.length > 0));
form.value.questions.map((question) => question.text.length > 0)
);
return { return {
quests, quests,
@@ -616,7 +743,7 @@ export default {
handleSelectAll, handleSelectAll,
isAllSelected, isAllSelected,
checkremote, checkremote,
spravURL spravURL,
}; };
}, },
}; };
@@ -637,5 +764,4 @@ export default {
opacity: 0; opacity: 0;
transform: translateX(50px); transform: translateX(50px);
} }
</style> </style>