chore [P-261]: cja

This commit is contained in:
Denis Voinovich committed 2025-06-19 15:16:19 +03:00
commit 892bf1b1d7
56 files changed
+395 -67

No files matched your search

+2
View File
@@ -5,11 +5,13 @@ import nested_admin
class TestAnswerInline(nested_admin.NestedStackedInline): class TestAnswerInline(nested_admin.NestedStackedInline):
model = TestAnswer model = TestAnswer
extra = 0 extra = 0
fields = ('name', 'file', 'right_wrong')
class TestQuestionInline(nested_admin.NestedStackedInline): class TestQuestionInline(nested_admin.NestedStackedInline):
model = TestQuestion model = TestQuestion
extra = 0 extra = 0
inlines = [TestAnswerInline] inlines = [TestAnswerInline]
fields = ('name', 'file')
class TestAdmin(nested_admin.NestedModelAdmin): class TestAdmin(nested_admin.NestedModelAdmin):
inlines = [TestQuestionInline] inlines = [TestQuestionInline]
+19 -3
View File
@@ -1,6 +1,22 @@
from django.contrib import admin from django.contrib import admin
from .models import * from .models import *
import nested_admin
admin.site.register(Vote) # admin.site.register(Vote)
admin.site.register(Question) # admin.site.register(Question)
admin.site.register(Answer) # admin.site.register(Answer)
class AnswerInline(nested_admin.NestedTabularInline):
model = Answer
extra = 1
fields = ('name', 'file')
class QuestionInline(nested_admin.NestedStackedInline):
model = Question
inlines = [AnswerInline]
extra = 1
fields = ('name', 'file')
@admin.register(Vote)
class VoteAdmin(nested_admin.NestedModelAdmin):
inlines = [QuestionInline]
@@ -0,0 +1,37 @@
# Generated by Django 5.1.6 on 2025-06-19 08:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("vote", "0003_vote_news"),
]
operations = [
migrations.AlterField(
model_name="answer",
name="file",
field=models.FileField(
blank=True, null=True, upload_to="vote/answer_files/", verbose_name="Картинка"
),
),
migrations.AlterField(
model_name="answer",
name="name",
field=models.CharField(max_length=255, verbose_name="Ответ"),
),
migrations.AlterField(
model_name="question",
name="file",
field=models.ImageField(
blank=True, null=True, upload_to="vote/question_images/", verbose_name="Картинка"
),
),
migrations.AlterField(
model_name="question",
name="name",
field=models.CharField(max_length=255, verbose_name="Вопрос"),
),
]
+4 -4
View File
@@ -26,9 +26,9 @@ class Vote(models.Model):
verbose_name_plural = "Голосования" verbose_name_plural = "Голосования"
class Question(models.Model): class Question(models.Model):
name = models.CharField(max_length=255) name = models.CharField(max_length=255, verbose_name="Вопрос")
vote = models.ForeignKey(Vote, related_name='questions', on_delete=models.CASCADE) vote = models.ForeignKey(Vote, related_name='questions', on_delete=models.CASCADE)
file = models.ImageField(upload_to='vote/question_images/', null=True, blank=True) file = models.ImageField(upload_to='vote/question_images/', null=True, blank=True,verbose_name='Картинка')
numb = models.PositiveIntegerField() numb = models.PositiveIntegerField()
settings = models.JSONField(default=dict, verbose_name='Json настроек голосования') settings = models.JSONField(default=dict, verbose_name='Json настроек голосования')
@@ -40,8 +40,8 @@ class Question(models.Model):
verbose_name_plural = "Вопросы" verbose_name_plural = "Вопросы"
class Answer(models.Model): class Answer(models.Model):
name = models.CharField(max_length=255) name = models.CharField(max_length=255, verbose_name='Ответ')
file = models.FileField(upload_to='vote/answer_files/', null=True, blank=True) file = models.FileField(upload_to='vote/answer_files/', null=True, blank=True,verbose_name='Картинка')
question = models.ForeignKey(Question, related_name='answers', on_delete=models.CASCADE) question = models.ForeignKey(Question, related_name='answers', on_delete=models.CASCADE)
def __str__(self): def __str__(self):
+5 -2
View File
@@ -41,6 +41,7 @@
<v-icon <v-icon
size="x-small" size="x-small"
class="me-1" class="me-1"
color="teal-darken-4"
:icon="news.scores.filter(e=> e.user==accountStore.user.login && e.score == true).length>0?'mdi-thumb-up':'mdi-thumb-up-outline'" :icon="news.scores.filter(e=> e.user==accountStore.user.login && e.score == true).length>0?'mdi-thumb-up':'mdi-thumb-up-outline'"
@click="toggleIncrementLike(news.id, true)" @click="toggleIncrementLike(news.id, true)"
/> />
@@ -53,6 +54,7 @@
<v-icon <v-icon
size="x-small" size="x-small"
class="me-1" class="me-1"
color="teal-darken-4"
:icon="news.scores.filter(e=> e.user==accountStore.user.login && e.score == false).length>0?'mdi-thumb-down':'mdi-thumb-down-outline'" :icon="news.scores.filter(e=> e.user==accountStore.user.login && e.score == false).length>0?'mdi-thumb-down':'mdi-thumb-down-outline'"
@click="toggleIncrementLike(news.id, false)" @click="toggleIncrementLike(news.id, false)"
/> />
@@ -65,6 +67,7 @@
<v-icon <v-icon
size="x-small" size="x-small"
class="me-1" class="me-1"
color="teal-darken-4"
icon="mdi-message-text-outline" icon="mdi-message-text-outline"
/> />
<span class="subheading"> <span class="subheading">
@@ -76,6 +79,7 @@
<v-icon <v-icon
size="x-small" size="x-small"
class="me-1 mb-1" class="me-1 mb-1"
color="teal-darken-4"
icon="mdi-image" icon="mdi-image"
/> />
<span class="subheading"> <span class="subheading">
@@ -102,8 +106,7 @@
<v-row class="flex-grow-0 ma-0"> <v-row class="flex-grow-0 ma-0">
<v-col class="d-flex justify-space-between"> <v-col class="d-flex justify-space-between">
<v-btn <v-btn
color="more_details_btn" color="teal-darken-4"
:to='`/newsfull?id=${news.id}`' :to='`/newsfull?id=${news.id}`'
size="small" size="small"
rounded="xl" rounded="xl"
@@ -18,6 +18,13 @@
@click="handleSelectAll" @click="handleSelectAll"
></v-checkbox> ></v-checkbox>
</template> </template>
<template #no-data>
<v-list-item>
<v-list-item-title class="text-grey">
Нет доступных данных
</v-list-item-title>
</v-list-item>
</template>
<template #selection="{ item }"> <template #selection="{ item }">
<v-chip :prepend-avatar="checkremote(`${spravURL}${item.raw.login}.jpg`)"> <v-chip :prepend-avatar="checkremote(`${spravURL}${item.raw.login}.jpg`)">
{{ item.raw.familyname }} {{ item.raw.familyname }}
@@ -4,10 +4,11 @@
v-if="from_which == 'dialog-search'" v-if="from_which == 'dialog-search'"
class="pl-4 h-100 text-left pa-2" class="pl-4 h-100 text-left pa-2"
@click="open = true" @click="open = true"
active-color="teal-darken-4"
> >
<template v-slot:prepend> <template v-slot:prepend>
<v-avatar <v-avatar
color="grey-darken-3" :color="'teal-darken-4'"
:image="checkremote(`${spravURL}${author.login}.jpg`)" :image="checkremote(`${spravURL}${author.login}.jpg`)"
/> />
</template> </template>
@@ -23,16 +24,17 @@
v-if="from_which == 'top-user'" v-if="from_which == 'top-user'"
class="h-100 text-left pa-0 pl-0" class="h-100 text-left pa-0 pl-0"
@click="open = true" @click="open = true"
active-color="teal-darken-4"
> >
<v-chip <v-chip
class="cursor-pointer pa-0" class="cursor-pointer pa-0"
variant="text" variant="text"
label label
color="grey-darken-3" color="teal-darken-4"
size="small" size="small"
> >
<v-avatar <v-avatar
color="grey-darken-3" color="teal-darken-4"
:image="checkremote(`${spravURL}${author.login}.jpg`)" :image="checkremote(`${spravURL}${author.login}.jpg`)"
class="mr-2" class="mr-2"
/> />
+1 -1
View File
@@ -11,7 +11,7 @@
v-bind="attrs" v-bind="attrs"
v-on="on" v-on="on"
size="large" size="large"
color="indigo" color="teal-darken-4"
icon="mdi-owl" icon="mdi-owl"
@click="menu = !menu" @click="menu = !menu"
></v-icon> ></v-icon>
+7 -1
View File
@@ -9,7 +9,7 @@
hide-delimiters hide-delimiters
hide-delimiter-background hide-delimiter-background
:show-arrows="carous.length < 2 ? false : 'hover'" :show-arrows="carous.length < 2 ? false : 'hover'"
color="white" color="teal-darken-4"
@update:modelValue="slidechanged" @update:modelValue="slidechanged"
> >
<template v-for="(x, i) in carous" :key="i"> <template v-for="(x, i) in carous" :key="i">
@@ -187,3 +187,9 @@ export default {
cursor: default !important; cursor: default !important;
} }
</style> </style>
<style scoped>
.titles, .text-text_carous, .text-text_caroustext-black, .v-card-title, .v-card-text, .v-textarea .v-field__input {
color: #111 !important;
text-shadow: none !important;
}
</style>
+12 -2
View File
@@ -28,7 +28,7 @@
</v-card-title> </v-card-title>
<v-card-text <v-card-text
@click="detailRound(x.position, x.position__name)" @click="detailRound(x.position, x.position__name)"
class="numstyle mt-2 py-0 font-weight-bold cursor-pointer bg-black_and_white" class="numstyle mt-2 py-0 font-weight-bold cursor-pointer bg-black_and_white text-teal-darken-4"
> >
<vue3-autocounter <vue3-autocounter
@@ -53,7 +53,7 @@
v-if="accountStore.user.is_staff" v-if="accountStore.user.is_staff"
v-model="changeData" v-model="changeData"
class="pl-3 d-flex justify-end" class="pl-3 d-flex justify-end"
color="white" color="teal-darken-4"
@click="changeData=!changeData"> @click="changeData=!changeData">
</v-switch> </v-switch>
</v-col> </v-col>
@@ -234,4 +234,14 @@ export default {
.fiction .v-input__control { .fiction .v-input__control {
display: none; display: none;
} }
</style>
<style scoped>
.numstyle {
font-size: 2.8rem !important;
font-weight: 900 !important;
color: #222 !important;
letter-spacing: 0.05em;
font-family: 'Montserrat', 'Arial', sans-serif;
}
</style> </style>
+5 -1
View File
@@ -282,7 +282,7 @@
variant="text" variant="text"
size="small" size="small"
icon="mdi-delete" icon="mdi-delete"
color="delete_btn" color="teal-darken-4"
@click="deletComment(y.id, newsFull.id)" @click="deletComment(y.id, newsFull.id)"
/> />
</v-col> </v-col>
@@ -353,6 +353,7 @@
density="compact" density="compact"
variant="text" variant="text"
icon="mdi-close" icon="mdi-close"
color="teal-darken-4"
@click="dialogfoto = false" @click="dialogfoto = false"
/> />
</v-col> </v-col>
@@ -364,6 +365,7 @@
density="compact" density="compact"
variant="text" variant="text"
icon="mdi-chevron-left" icon="mdi-chevron-left"
color="teal-darken-4"
@click=" @click="
indximg != 0 indximg != 0
? (indximg -= 1) ? (indximg -= 1)
@@ -382,6 +384,7 @@
density="compact" density="compact"
variant="text" variant="text"
icon="mdi-chevron-right" icon="mdi-chevron-right"
color="teal-darken-4"
@click=" @click="
indximg != newsFull.gallery.length - 1 indximg != newsFull.gallery.length - 1
? (indximg += 1) ? (indximg += 1)
@@ -422,6 +425,7 @@
density="compact" density="compact"
variant="text" variant="text"
icon="mdi-close" icon="mdi-close"
color="teal-darken-4"
@click="dialogfotoOne = false" @click="dialogfotoOne = false"
/> />
</v-col> </v-col>
+1 -1
View File
@@ -56,7 +56,7 @@
size="small" size="small"
variant="text" variant="text"
icon="mdi-newspaper" icon="mdi-newspaper"
color="blue-darken-4" color="teal-darken-4"
:to='`/news`' :to='`/news`'
/> />
</v-col> </v-col>
@@ -57,12 +57,11 @@
{{ data?.question_count }} {{ data?.question_count }}
</span> </span>
</div> </div>
<div class="d-flex align-center mb-3"> <div class="d-flex align-center mb-3" v-if="isExamMode">
<v-icon icon="mdi-refresh" color="teal-darken-2" class="mr-2" /> <v-icon icon="mdi-refresh" color="teal-darken-2" class="mr-2" />
<span class="text-body-1"> <span class="text-body-1">
<strong>Количество попыток:</strong> <strong>Количество попыток:</strong> {{ remainingAttempts !== undefined ? remainingAttempts : data?.attemps_number }}
{{ data?.attemps_number }}
</span> </span>
</div> </div>
@@ -75,13 +74,23 @@
</div> </div>
</v-card-text> </v-card-text>
<v-card-actions v-if="!isDialog" class="mx-2 my-4"> <v-card-actions v-if="!isDialog" class="mx-2 my-4">
<v-btn <v-btn
color="btn_text" v-if="!isExamMode || remainingAttempts === undefined || remainingAttempts > 0"
class="ml-auto px-9 text-white" color="btn_text"
class="ml-auto px-9 text-white"
@click="startTest" @click="startTest"
> >
{{ isExamMode ? "Начать" : "Тренироваться" }} {{ isExamMode ? "Начать" : "Тренироваться" }}
</v-btn> </v-btn>
<v-alert
v-else
type="warning"
class="ml-auto my-2 w-100"
border="start"
density="compact"
>
Все попытки израсходованы
</v-alert>
</v-card-actions> </v-card-actions>
</v-card> </v-card>
</v-col> </v-col>
@@ -100,8 +109,12 @@ export default {
data: Object, data: Object,
isDialog: { isDialog: {
type: Boolean, type: Boolean,
default: false, default: false
}, },
remainingAttempts: {
type: Number,
default: undefined
}
}, },
setup(props) { setup(props) {
const route = useRoute(); const route = useRoute();
@@ -1,6 +1,7 @@
<!-- Раздел с назначенным тестированием --> <!-- Раздел с назначенным тестированием -->
<template> <template>
<!-- <div class="my-4 text-h5 font-weight-medium">{{ title }}</div> --> <!-- <div class="my-4 text-h5 font-weight-medium">{{ title }}</div> -->
<div :class="containerClass">
<v-container :fluid="true"> <v-container :fluid="true">
<v-row> <v-row>
<v-text-field <v-text-field
@@ -80,6 +81,7 @@
</v-card-title> </v-card-title>
</v-row> </v-row>
</v-container> </v-container>
</div>
</template> </template>
<script> <script>
@@ -103,9 +105,16 @@ export default {
type: Array, type: Array,
default: () => [], default: () => [],
}, },
class: {
type: [String, Object, Array],
default: '',
},
}, },
setup(props) { setup(props) {
const search = ref(''); const search = ref('');
// Create a computed property to handle the containerClass
const containerClass = computed(() => props.class);
const searchTest = computed(() => { const searchTest = computed(() => {
let filteredTests = props.testingCard; let filteredTests = props.testingCard;
@@ -169,7 +178,7 @@ export default {
return text.replace(/\r?\n/g, '<br>'); return text.replace(/\r?\n/g, '<br>');
}; };
return { search, searchTest, momenter, activeTabIcon, baseURL, formatDescription, defaultImage }; return { search, searchTest, momenter, activeTabIcon, baseURL, formatDescription, defaultImage, containerClass };
}, },
}; };
</script> </script>
@@ -12,7 +12,7 @@
/> />
<!-- Блок информации о тесте --> <!-- Блок информации о тесте -->
<BodyDetailTesting v-if="!testStarted && !testFinished" :data="data" :startTest="startTest" /> <BodyDetailTesting v-if="!testStarted && !testFinished" :data="data" :startTest="startTest" :remainingAttempts="remainingAttempts" />
<!-- Вопросы теста --> <!-- Вопросы теста -->
<QuestionBlock <QuestionBlock
@@ -65,7 +65,7 @@ import HeaderDetailTesting from '@/components/testing/HeaderDetailTesting.vue';
import BodyDetailTesting from '@/components/testing/BodyDetailTesting.vue'; import BodyDetailTesting from '@/components/testing/BodyDetailTesting.vue';
import QuestionBlock from '@/components/testing/QuestionBlock.vue'; import QuestionBlock from '@/components/testing/QuestionBlock.vue';
import TestResults from '@/components/testing/TestResults.vue'; import TestResults from '@/components/testing/TestResults.vue';
import { axiosApiInstance } from '@/utils/axios-api'; import { axiosApiInstance, getActiveTest } from '@/utils/axios-api';
import { useRoute } from 'vue-router'; import { useRoute } from 'vue-router';
export default { export default {
@@ -82,6 +82,7 @@ export default {
const testingId = ref(null); const testingId = ref(null);
const testResults = ref(null); const testResults = ref(null);
const spentTime = ref(0); const spentTime = ref(0);
const remainingAttempts = ref(undefined);
const formatSpentTime = computed(() => { const formatSpentTime = computed(() => {
const minutes = Math.floor(spentTime.value / 60); const minutes = Math.floor(spentTime.value / 60);
@@ -90,10 +91,23 @@ export default {
}); });
const getTestById = async (id) => { const getTestById = async (id) => {
// Загружаем детали теста из API testdetail
const resp = await axiosApiInstance.get(`/api/tests/testdetail/${id}`); const resp = await axiosApiInstance.get(`/api/tests/testdetail/${id}`);
data.value = resp.data; data.value = resp.data;
try { try {
// Проверяем оставшиеся попытки из API gettests со статусом active
const activeTest = await getActiveTest(id);
// Если нашли тест в активных, проверяем количество попыток
if (activeTest) {
remainingAttempts.value = activeTest.attemps_number;
} else {
// Если тест не найден в активных, устанавливаем 0 попыток
remainingAttempts.value = 0;
}
// Получаем данные о назначениях теста
const testingResp = await axiosApiInstance.get(`/api/tests/testingview/?test_id=${id}`); const testingResp = await axiosApiInstance.get(`/api/tests/testingview/?test_id=${id}`);
const userTestings = testingResp.data; const userTestings = testingResp.data;
if (userTestings?.length > 0) { if (userTestings?.length > 0) {
@@ -133,6 +147,13 @@ export default {
const startTest = async () => { const startTest = async () => {
await getTestById(testId); await getTestById(testId);
// Проверяем попытки только для режима экзамена
const isExamMode = route.query.mode === 'exam';
if (isExamMode && remainingAttempts.value !== undefined && remainingAttempts.value <= 0) {
console.log('Нет оставшихся попыток для прохождения теста');
return; // Прерываем запуск теста если попыток не осталось
}
testStarted.value = true; testStarted.value = true;
testFinished.value = false; testFinished.value = false;
@@ -206,11 +227,15 @@ export default {
const answers = ref([]); const answers = ref([]);
watch(data.value?.questions, (newData) => { watch(
if (newData && Array.isArray(newData.questions)) { () => data.value?.questions,
answers.value = newData.questions.map(() => null); (newQuestions) => {
} if (newQuestions && Array.isArray(newQuestions)) {
}); answers.value = newQuestions.map(() => null);
}
},
{ deep: true }
);
const correctAnswers = computed( const correctAnswers = computed(
() => () =>
@@ -274,6 +299,7 @@ export default {
answeredQuestions, answeredQuestions,
testPassed, testPassed,
data, data,
remainingAttempts,
}; };
}, },
}; };
@@ -10,7 +10,7 @@
<v-card-text> <v-card-text>
<v-img <v-img
v-if="question.file" v-if="question.file"
:src="`http://127.0.0.1:8000${question.file}`" :src="`${baseURL.slice(0, -1)}${question.file}`"
class="w-50 mx-auto mb-4" class="w-50 mx-auto mb-4"
/> />
@@ -28,7 +28,7 @@
<div class="text-center"> <div class="text-center">
<v-img <v-img
v-if="option.file" v-if="option.file"
:src="`http://127.0.0.1:8000${option.file}`" :src="`${baseURL.slice(0, -1)}${option.file}`"
class="mb-4" class="mb-4"
width="400" width="400"
min-width="300" min-width="300"
@@ -56,7 +56,7 @@
<div class="text-center"> <div class="text-center">
<v-img <v-img
v-if="option.file" v-if="option.file"
:src="`http://127.0.0.1:8000${option.file}`" :src="`${baseURL.slice(0, -1)}${option.file}`"
class="mb-4" class="mb-4"
width="400" width="400"
min-width="300" min-width="300"
@@ -97,8 +97,9 @@
</template> </template>
<script> <script>
import { computed, watch } from "vue"; import { computed, watch } from 'vue';
import { useRoute } from "vue-router"; import { useRoute } from 'vue-router';
import { baseURL } from '@/utils/axios-api';
export default { export default {
props: { props: {
@@ -133,6 +134,7 @@ export default {
return { return {
isMultipleChoice, isMultipleChoice,
isPracticeMode, isPracticeMode,
baseURL
}; };
}, },
emits: ["change-question"], emits: ["change-question"],
@@ -36,6 +36,7 @@
label="Картинка" label="Картинка"
variant="outlined" variant="outlined"
:error-messages="answer.imageError" :error-messages="answer.imageError"
class="file-input-fixed"
@update:model-value="(file) => handleImageUpload(file, answer, aIndex)" @update:model-value="(file) => handleImageUpload(file, answer, aIndex)"
></v-file-input> ></v-file-input>
@@ -174,3 +175,11 @@ export default {
} }
}; };
</script> </script>
<style>
.file-input-fixed {
max-width: 250px;
min-width: 200px;
flex-grow: 0;
}
</style>
@@ -15,6 +15,7 @@
:rules="[rules.required]" :rules="[rules.required]"
label="Описание" label="Описание"
variant="outlined" variant="outlined"
class="scrollable-textarea"
></v-textarea> ></v-textarea>
</div> </div>
<div v-if="!isTest" class="pt-2 d-flex align-center"> <div v-if="!isTest" class="pt-2 d-flex align-center">
@@ -183,5 +184,54 @@ export default {
</script> </script>
<style scoped> <style scoped>
.scrollable-textarea :deep(.v-field__field) {
overflow-y: auto !important;
max-height: 300px !important;
}
.scrollable-textarea :deep(textarea) {
max-height: none !important;
}
.scrollable-textarea :deep(::-webkit-scrollbar) {
width: 14px !important;
}
.scrollable-textarea :deep(::-webkit-scrollbar-track) {
background-color: #f1f1f1 !important;
border-radius: 8px !important;
}
.scrollable-textarea :deep(::-webkit-scrollbar-thumb) {
background-color: #004D40 !important;
border-radius: 8px !important;
border: 2px solid #f1f1f1 !important;
}
.scrollable-textarea :deep(::-webkit-scrollbar-thumb:hover) {
background-color: #00796B !important;
}
.scrollable-textarea :deep(textarea)::-webkit-scrollbar,
.scrollable-textarea :deep(.v-field__input)::-webkit-scrollbar {
width: 14px !important;
}
.scrollable-textarea :deep(textarea)::-webkit-scrollbar-track,
.scrollable-textarea :deep(.v-field__input)::-webkit-scrollbar-track {
background-color: #f1f1f1 !important;
border-radius: 8px !important;
}
.scrollable-textarea :deep(textarea)::-webkit-scrollbar-thumb,
.scrollable-textarea :deep(.v-field__input)::-webkit-scrollbar-thumb {
background-color: #004D40 !important;
border-radius: 8px !important;
border: 2px solid #f1f1f1 !important;
}
.scrollable-textarea :deep(textarea)::-webkit-scrollbar-thumb:hover,
.scrollable-textarea :deep(.v-field__input)::-webkit-scrollbar-thumb:hover {
background-color: #00796B !important;
}
</style> </style>
@@ -45,7 +45,7 @@
> >
<template v-slot:label> <template v-slot:label>
<div class="text-body-2 font-weight-bold"> <div class="text-body-2 font-weight-bold">
Голосование по отделам: Голосование:
</div> </div>
</template> </template>
<v-radio <v-radio
@@ -60,6 +60,7 @@
</v-radio-group> </v-radio-group>
</div> </div>
<v-autocomplete <v-autocomplete
v-if="question.settings.onlyDep === null"
v-model="question.selectedEmployees" v-model="question.selectedEmployees"
:items="allEmployeesgroupedbydep" :items="allEmployeesgroupedbydep"
class="text-no-wrap" class="text-no-wrap"
@@ -68,6 +69,8 @@
item-value="id" item-value="id"
label="Выберите сотрудников" label="Выберите сотрудников"
multiple multiple
chips
closable-chips
variant="outlined" variant="outlined"
@update:model-value="onEmployeeUpdate" @update:model-value="onEmployeeUpdate"
> >
@@ -79,9 +82,11 @@
@update:model-value="toggleSelectAll" @update:model-value="toggleSelectAll"
></v-checkbox> ></v-checkbox>
</template> </template>
<template #selection="{ item }"> <template #selection="{ item, index }">
<v-chip <v-chip
:prepend-avatar="checkremote(`${spravURL}${item.raw.login}.jpg`)" :prepend-avatar="checkremote(`${spravURL}${item.raw.login}.jpg`)"
closable
@click:close="removeSelectedEmployee(item.raw.id)"
> >
{{ item.raw.familyname }} {{ item.raw.familyname }}
</v-chip> </v-chip>
@@ -116,7 +121,8 @@
</template> </template>
</template> </template>
</v-autocomplete> </v-autocomplete>
<transition-group name="list" tag="div">
<transition-group v-if="question.settings.onlyDep === null" name="list" tag="div">
<div <div
v-for="(person, pIndex) in question.answers" v-for="(person, pIndex) in question.answers"
:key="person" :key="person"
@@ -125,6 +131,8 @@
<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="checkremote(`${spravURL}${findEmployeeById(person.text)?.login}.jpg`)"
closable
@click:close="removeEmployeeAnswer(pIndex)"
> >
{{ findEmployeeById(person.text)?.fio }} {{ findEmployeeById(person.text)?.fio }}
</v-chip> </v-chip>
@@ -158,7 +166,7 @@
import QuestionHeader from '@/components/vote/ConstructorVote/QuestionHeader.vue'; import QuestionHeader from '@/components/vote/ConstructorVote/QuestionHeader.vue';
import QuestionSettings from '@/components/vote/ConstructorVote/QuestionSettings.vue'; import QuestionSettings from '@/components/vote/ConstructorVote/QuestionSettings.vue';
import AnswerList from '@/components/vote/ConstructorVote/AnswerList.vue'; import AnswerList from '@/components/vote/ConstructorVote/AnswerList.vue';
import { computed, ref } from 'vue'; import { computed, ref, watch } from 'vue';
import { useRoute } from 'vue-router'; import { useRoute } from 'vue-router';
export default { export default {
@@ -295,11 +303,55 @@ export default {
}; };
const onEmployeeUpdate = (selected) => { const onEmployeeUpdate = (selected) => {
// Filter existing answers to keep only those that are still selected
props.question.answers = props.question.answers.filter((e) => props.question.answers = props.question.answers.filter((e) =>
selected.includes(e.text) selected.includes(e.text)
); );
// Add new answers for newly selected employees that don't have answers yet
const existingAnswerIds = props.question.answers.map(a => a.text);
const newEmployeeIds = selected.filter(id => !existingAnswerIds.includes(id));
// Add new answers for the newly selected employees
newEmployeeIds.forEach(employeeId => {
props.question.answers.push({ text: employeeId, image: null });
});
// Also update the saved state for potential future switching between radio options
props.question._savedSelectedEmployees = [...selected];
props.question._savedAnswers = [...props.question.answers];
emit('update:question', props.question); emit('update:question', props.question);
}; };
const removeSelectedEmployee = (employeeId) => {
// Находим индекс сотрудника в массиве selectedEmployees
const index = props.question.selectedEmployees.indexOf(employeeId);
if (index !== -1) {
// Удаляем сотрудника из списка выбранных
props.question.selectedEmployees.splice(index, 1);
// Находим соответствующий ответ и удаляем его
const answerIndex = props.question.answers.findIndex(a => a.text === employeeId);
if (answerIndex !== -1) {
props.question.answers.splice(answerIndex, 1);
}
// Обновляем сохраненное состояние
if (props.question._savedSelectedEmployees) {
const savedIndex = props.question._savedSelectedEmployees.indexOf(employeeId);
if (savedIndex !== -1) {
props.question._savedSelectedEmployees.splice(savedIndex, 1);
}
const savedAnswerIndex = props.question._savedAnswers?.findIndex(a => a.text === employeeId);
if (savedAnswerIndex !== -1) {
props.question._savedAnswers.splice(savedAnswerIndex, 1);
}
}
emit('update:question', props.question);
}
};
const toggleSelectAll = (value) => { const toggleSelectAll = (value) => {
props.handleSelectAll(value, props.index); props.handleSelectAll(value, props.index);
@@ -307,8 +359,21 @@ export default {
}; };
const removeEmployeeAnswer = (pIndex) => { const removeEmployeeAnswer = (pIndex) => {
props.question.selectedEmployees.splice(pIndex, 1); const employeeId = props.question.answers[pIndex].text;
props.question.selectedEmployees = props.question.selectedEmployees.filter(id => id !== employeeId);
props.question.answers.splice(pIndex, 1); props.question.answers.splice(pIndex, 1);
// Обновляем сохраненное состояние
if (props.question._savedSelectedEmployees) {
props.question._savedSelectedEmployees = props.question._savedSelectedEmployees.filter(id => id !== employeeId);
const savedAnswerIndex = props.question._savedAnswers?.findIndex(a => a.text === employeeId);
if (savedAnswerIndex !== -1) {
props.question._savedAnswers.splice(savedAnswerIndex, 1);
}
}
emit('update:question', props.question); emit('update:question', props.question);
}; };
@@ -320,6 +385,27 @@ export default {
const isTestRoute = computed(() => { const isTestRoute = computed(() => {
return route.path && String(route.path).includes('test'); return route.path && String(route.path).includes('test');
}); });
// Добавляем наблюдение за изменением выбора типа голосования
watch(() => props.question.settings.onlyDep, (newValue, oldValue) => {
// Если выбрано любое значение кроме null, автоматически выбрать всех сотрудников
if (newValue !== null) {
// Сохраняем выбранных сотрудников перед выбором "все"
if (oldValue === null) {
// Сохраняем текущий выбор сотрудников для возможного возврата к "произвольным сотрудникам"
props.question._savedSelectedEmployees = [...props.question.selectedEmployees];
props.question._savedAnswers = [...props.question.answers];
}
toggleSelectAll(true);
}
// Если переключаемся на "За произвольного сотрудника" (null) и у нас есть сохраненный выбор
else if (newValue === null && oldValue !== null && props.question._savedSelectedEmployees) {
// Восстанавливаем ранее сохраненный выбор сотрудников
props.question.selectedEmployees = [...props.question._savedSelectedEmployees];
props.question.answers = [...props.question._savedAnswers];
emit('update:question', props.question);
}
});
return { return {
resetAnswers, resetAnswers,
@@ -328,6 +414,7 @@ export default {
onEmployeeUpdate, onEmployeeUpdate,
toggleSelectAll, toggleSelectAll,
removeEmployeeAnswer, removeEmployeeAnswer,
removeSelectedEmployee,
onEmployeesChange, onEmployeesChange,
isTestRoute, isTestRoute,
questionImagePreview, questionImagePreview,
+18 -3
View File
@@ -64,7 +64,7 @@
{{ answer.employee?.fio || answer.name }} {{ answer.employee?.fio || answer.name }}
<template v-slot:prepend="{ isSelected }"> <template v-slot:prepend="{ isSelected }">
<v-list-item-action start> <v-list-item-action start @click.stop="toggleAnswer(question.id, answer.id)">
<v-checkbox-btn :model-value="isSelected"></v-checkbox-btn> <v-checkbox-btn :model-value="isSelected"></v-checkbox-btn>
</v-list-item-action> </v-list-item-action>
</template> </template>
@@ -197,6 +197,20 @@ export default {
} }
}; };
const toggleAnswer = (questionId, answerId) => {
const currentAnswers = result.value[questionId];
const index = currentAnswers.indexOf(answerId);
if (index === -1) {
const question = props.data.questions.find(q => q.id === questionId);
if (currentAnswers.length < question.settings.multiChoice) {
currentAnswers.push(answerId);
}
} else {
currentAnswers.splice(index, 1);
}
};
const submitVote = () => { const submitVote = () => {
let voteData = [] let voteData = []
for (let val of Object.values(result.value)) { for (let val of Object.values(result.value)) {
@@ -220,10 +234,10 @@ export default {
activepick.value = val activepick.value = val
} }
const groupedAnswers = (question) => { const groupedAnswers = (question) => {
const filtered = question.answers.filter(answer => answer.employee?.id !== accountStore.user.is_idEmployee); const filtered = question.answers.filter(answer => answer.employee?.id !== accountStore.user.is_idEmployee);
if (question.settings.onlyDep === null) { if (question.settings.onlyDep === null || question.settings.onlyDep === 'any') {
return groupByDepartment(filtered); return groupByDepartment(filtered);
} else if (question.settings.onlyDep) { } else if (question.settings.onlyDep) {
const byDepartment = filtered.filter( const byDepartment = filtered.filter(
@@ -263,6 +277,7 @@ export default {
isCurrentQuestionAnswered, isCurrentQuestionAnswered,
nextStep, nextStep,
prevStep, prevStep,
toggleAnswer,
submitVote, submitVote,
isVoteSubmitted, isVoteSubmitted,
result result
@@ -263,12 +263,17 @@
Голосование по отделам: Голосование по отделам:
{{ onlyDepdict.find((e) => e.value === question.settings.onlyDep).name }} {{ onlyDepdict.find((e) => e.value === question.settings.onlyDep).name }}
</div> </div>
<p><strong>Выбранные сотрудники:</strong></p> <div v-if="question.settings.onlyDep !== null">
<ul> <p><strong>Выбрано {{ question.answers.length }} сотрудников</strong></p>
<li v-for="employeeId in question.answers" :key="employeeId"> </div>
{{ findEmployeeById(employeeId.text).fio }} <div v-else>
</li> <p><strong>Выбранные сотрудники:</strong></p>
</ul> <ul>
<li v-for="employeeId in question.answers" :key="employeeId">
{{ findEmployeeById(employeeId.text).fio }}
</li>
</ul>
</div>
</div> </div>
</div> </div>
</v-card> </v-card>
@@ -588,9 +593,9 @@ export default {
}; };
watch( watch(
form.value, () => form.value,
() => { (formValue) => {
if (!form.value.title || !form.value.description || form.value.questions.length < 1) { if (!formValue.title || !formValue.description || formValue.questions.length < 1) {
errorMessage.value = 'Все обязательные поля должны быть заполнены'; errorMessage.value = 'Все обязательные поля должны быть заполнены';
} else { } else {
errorMessage.value = ''; errorMessage.value = '';
@@ -602,7 +607,6 @@ export default {
watch( watch(
() => form.value.questions, () => form.value.questions,
(newQuestions) => { (newQuestions) => {
quests.value = newQuestions.map((q) => !!q.text.trim());
const hasEmptyQuestions = newQuestions.some((q) => !q.text || q.text.trim() === ''); const hasEmptyQuestions = newQuestions.some((q) => !q.text || q.text.trim() === '');
const hasInvalidAnswers = validateAnswers(); const hasInvalidAnswers = validateAnswers();
@@ -628,12 +632,13 @@ export default {
}; };
const onlyDepdict = [ const onlyDepdict = [
{ name: 'За любого сотрудника', value: null }, { name: 'За любого сотрудника', value: 'any' },
{ {
name: 'Кроме своего отдела', name: 'Только за сотрудника из другого отдела',
value: false, value: false,
}, },
{ name: 'Только за свой отдел', value: true }, { name: 'Только за сотрудника из своего отдела', value: true },
{ name: 'За произвольного сотрудника (есть возможность добавить картинку)', value: null },
]; ];
const quests = computed(() => form.value.questions.map((question) => question.text.length > 0)); const quests = computed(() => form.value.questions.map((question) => question.text.length > 0));
@@ -686,11 +691,13 @@ export default {
testImage, testImage,
imagePreview, imagePreview,
previewImage, previewImage,
handleTestImageUpload,
getImagePreviewUrl, getImagePreviewUrl,
actualQuestionCount, actualQuestionCount,
actualTestQuestionCount, actualTestQuestionCount,
isTest: props.isTest, isTest: props.isTest,
imageError imageError,
validateImage
}; };
}, },
}; };
+1 -1
View File
@@ -30,7 +30,7 @@
</v-tabs> </v-tabs>
<v-tabs-window v-model="activeTab"> <v-tabs-window v-model="activeTab">
<v-tabs-window-item v-for="(question, questionIndex) in questions" :key="questionIndex"> <v-tabs-window-item v-for="(question, questionIndex) in questions" :key="questionIndex">
<v-row v-if="question.settings.onlyDep"> <v-row v-if="question.settings.onlyDep === true">
<v-col <v-col
v-for="(winner, department) in getWinnersByDepartment(question).winnersByDepartment" v-for="(winner, department) in getWinnersByDepartment(question).winnersByDepartment"
:key="department" :key="department"
+13
View File
@@ -368,6 +368,18 @@ async function deleteTestingRecord(testingId) {
} }
} }
async function getActiveTest(id) {
try {
const response = await axiosApiInstance.get(`/api/tests/gettests/?status=active`);
const activeTests = response.data;
const activeTest = activeTests.find(test => test.id === Number(id));
return activeTest || null;
} catch (error) {
console.error("Ошибка получения активного теста:", error);
throw error;
}
}
export { export {
axiosApiInstance, axiosApiInstance,
@@ -392,4 +404,5 @@ export {
assignTestToUser, assignTestToUser,
getTestToUser, getTestToUser,
deleteTestingRecord, deleteTestingRecord,
getActiveTest,
} }
+15 -5
View File
@@ -44,10 +44,10 @@
<v-sheet class="mx-auto" :class="favorit.length > 10 ? 'mx-n3' : ''" max-width="800"> <v-sheet class="mx-auto" :class="favorit.length > 10 ? 'mx-n3' : ''" max-width="800">
<v-slide-group show-arrows> <v-slide-group show-arrows>
<v-slide-group-item v-for="x in favorit" :key="x"> <v-slide-group-item v-for="x in favorit" :key="x">
<v-btn-toggle v-model="toggle" divided variant="outlined"> <v-btn-toggle v-model="toggle" divided variant="outlined" color="teal-darken-4">
<v-tooltip :text="x.pages__page" location="top"> <v-tooltip :text="x.pages__page" location="top">
<template v-slot:activator="{ props }"> <template v-slot:activator="{ props }">
<v-btn v-bind="props" :icon="x.pages__ico" :to="x.pages__fullPath" /> <v-btn v-bind="props" :icon="x.pages__ico" :to="x.pages__fullPath" color="teal-darken-4" />
</template> </template>
</v-tooltip> </v-tooltip>
</v-btn-toggle> </v-btn-toggle>
@@ -146,12 +146,22 @@ export default {
} }
.bgCard { .bgCard {
/* #ffffff6b #ffffff8c*/ background: #fff !important;
background: #ffffff38;
} }
.bgText { .bgText {
background: #ffffffb0; background: #f5f5f5 !important;
color: #222 !important;
line-height: 2.1rem !important; line-height: 2.1rem !important;
} }
.card-unified {
border-radius: 18px;
box-shadow: none;
}
.text-unified {
color: #222 !important;
font-family: 'Montserrat', 'Arial', sans-serif;
}
</style> </style>