fix [P-265]: 1.1.1 обновление теста

This commit is contained in:
Nukeap committed 2025-06-30 08:08:07 +03:00
commit 77e0537d96
69 files changed
+654 -206

No files matched your search

+1 -1
View File
@@ -55,4 +55,4 @@ NGINX_EXTERNAL_PORT=80
NGINX_INTERNAL_PORT=80
RUN_WITH_DOCS=False
PRODUCTION=False
PRODUCTION=True
+1 -1
View File
@@ -1 +1 @@
/home/nukeap/projects/PORTAL_COD2/sys/scripts/easydockersave.sh
/home/denzel/Документы/PORTAL_COD2/sys/scripts/easydockersave.sh
+1 -1
View File
@@ -1 +1 @@
/home/nukeap/projects/PORTAL_COD2/sys/scripts/easyserver.sh
/home/denzel/Документы/PORTAL_COD2/sys/scripts/easyserver.sh
+2 -2
View File
@@ -21,9 +21,9 @@ class Settings:
self.db = {
"default": {
"ENGINE": "django.db.backends.mysql",
"NAME": os.getenv("DB_NAME"), # Имя базы данных
"NAME": "portal_test", # Имя базы данных
"USER": os.getenv("DB_USER"), # Имя пользователя
"PASSWORD": os.getenv("DB_PASSWORD"), # Пароль
"PASSWORD": "P@sw0rd", # Пароль
"HOST": os.getenv("DB_HOST"), # Хост
"PORT": os.getenv("DB_INTERNAL_PORT"), # Порт
}
+2
View File
@@ -5,11 +5,13 @@ import nested_admin
class TestAnswerInline(nested_admin.NestedStackedInline):
model = TestAnswer
extra = 0
fields = ('name', 'file', 'right_wrong')
class TestQuestionInline(nested_admin.NestedStackedInline):
model = TestQuestion
extra = 0
inlines = [TestAnswerInline]
fields = ('name', 'file')
class TestAdmin(nested_admin.NestedModelAdmin):
inlines = [TestQuestionInline]
@@ -0,0 +1,23 @@
# Generated by Django 5.1.6 on 2025-06-24 08:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("tests", "0007_alter_testattempt_testing_alter_testing_user"),
]
operations = [
migrations.AlterField(
model_name="test",
name="pass_perc",
field=models.FloatField(verbose_name="Мин. % правильных ответов"),
),
migrations.AlterField(
model_name="testanswer",
name="right_wrong",
field=models.BooleanField(verbose_name="Правильно"),
),
]
+2 -2
View File
@@ -16,7 +16,7 @@ class Test(models.Model):
description = models.TextField(verbose_name='Описание')
author = models.ForeignKey(User, on_delete=models.CASCADE,
verbose_name='Создатель тестирования')
pass_perc = models.FloatField(blank=False, verbose_name="Мин. кол-во правильных ответов")
pass_perc = models.FloatField(blank=False, verbose_name="Мин. % правильных ответов")
time = models.FloatField(blank=False, verbose_name="Время прохождения теста")
question_count = models.PositiveIntegerField(blank=False, verbose_name="Количество вопросов")
attemps_number = models.PositiveIntegerField(blank=False, verbose_name="Количество попыток")
@@ -60,7 +60,7 @@ class TestAnswer(models.Model):
related_name='answers',
on_delete=models.CASCADE,
verbose_name="Вопрос")
right_wrong = models.BooleanField(blank=False, verbose_name="Правильно/Неправильно")
right_wrong = models.BooleanField(blank=False, verbose_name="Правильно")
class Meta:
verbose_name = "Ответ"
+8 -2
View File
@@ -517,6 +517,10 @@ class TestResultView(generics.ListCreateAPIView):
test_answers = TestAnswer.objects.filter(id__in=answer_ids)
test = Test.objects.get(id=test_id)
answered_questions_total = test_answers.values('question').distinct().count()
q_count = test.question_count
all_questions = len(TestQuestion.objects.filter(test=test))
if all_questions <= q_count:
q_count = all_questions
correct_questions = sum(
TestAnswer.objects.filter(
@@ -531,8 +535,10 @@ class TestResultView(generics.ListCreateAPIView):
pass_perc = test.pass_perc
correct_answers_perc = 0
if answered_questions_total !=0:
correct_answers_perc = correct_questions/answered_questions_total*100
if q_count !=0:
correct_answers_perc = correct_questions/q_count*100
# if answered_questions_total !=0:
# correct_answers_perc = correct_questions/answered_questions_total*100
result = {
"is_passed": correct_answers_perc >= pass_perc,
"score": correct_questions,
+19 -3
View File
@@ -1,6 +1,22 @@
from django.contrib import admin
from .models import *
import nested_admin
admin.site.register(Vote)
admin.site.register(Question)
admin.site.register(Answer)
# admin.site.register(Vote)
# admin.site.register(Question)
# 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 = "Голосования"
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)
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()
settings = models.JSONField(default=dict, verbose_name='Json настроек голосования')
@@ -40,8 +40,8 @@ class Question(models.Model):
verbose_name_plural = "Вопросы"
class Answer(models.Model):
name = models.CharField(max_length=255)
file = models.FileField(upload_to='vote/answer_files/', null=True, blank=True)
name = models.CharField(max_length=255, verbose_name='Ответ')
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)
def __str__(self):
+5 -2
View File
@@ -41,6 +41,7 @@
<v-icon
size="x-small"
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'"
@click="toggleIncrementLike(news.id, true)"
/>
@@ -53,6 +54,7 @@
<v-icon
size="x-small"
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'"
@click="toggleIncrementLike(news.id, false)"
/>
@@ -65,6 +67,7 @@
<v-icon
size="x-small"
class="me-1"
color="teal-darken-4"
icon="mdi-message-text-outline"
/>
<span class="subheading">
@@ -76,6 +79,7 @@
<v-icon
size="x-small"
class="me-1 mb-1"
color="teal-darken-4"
icon="mdi-image"
/>
<span class="subheading">
@@ -102,8 +106,7 @@
<v-row class="flex-grow-0 ma-0">
<v-col class="d-flex justify-space-between">
<v-btn
color="more_details_btn"
color="teal-darken-4"
:to='`/newsfull?id=${news.id}`'
size="small"
rounded="xl"
@@ -18,6 +18,13 @@
@click="handleSelectAll"
></v-checkbox>
</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 }">
<v-chip :prepend-avatar="checkremote(`${spravURL}${item.raw.login}.jpg`)">
{{ item.raw.familyname }}
@@ -4,10 +4,11 @@
v-if="from_which == 'dialog-search'"
class="pl-4 h-100 text-left pa-2"
@click="open = true"
active-color="teal-darken-4"
>
<template v-slot:prepend>
<v-avatar
color="grey-darken-3"
:color="'teal-darken-4'"
:image="checkremote(`${spravURL}${author.login}.jpg`)"
/>
</template>
@@ -23,16 +24,17 @@
v-if="from_which == 'top-user'"
class="h-100 text-left pa-0 pl-0"
@click="open = true"
active-color="teal-darken-4"
>
<v-chip
class="cursor-pointer pa-0"
variant="text"
label
color="grey-darken-3"
color="teal-darken-4"
size="small"
>
<v-avatar
color="grey-darken-3"
color="teal-darken-4"
:image="checkremote(`${spravURL}${author.login}.jpg`)"
class="mr-2"
/>
+1 -1
View File
@@ -11,7 +11,7 @@
v-bind="attrs"
v-on="on"
size="large"
color="indigo"
color="teal-darken-4"
icon="mdi-owl"
@click="menu = !menu"
></v-icon>
+7 -1
View File
@@ -9,7 +9,7 @@
hide-delimiters
hide-delimiter-background
:show-arrows="carous.length < 2 ? false : 'hover'"
color="white"
color="teal-darken-4"
@update:modelValue="slidechanged"
>
<template v-for="(x, i) in carous" :key="i">
@@ -187,3 +187,9 @@ export default {
cursor: default !important;
}
</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-text
@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
@@ -53,7 +53,7 @@
v-if="accountStore.user.is_staff"
v-model="changeData"
class="pl-3 d-flex justify-end"
color="white"
color="teal-darken-4"
@click="changeData=!changeData">
</v-switch>
</v-col>
@@ -234,4 +234,14 @@ export default {
.fiction .v-input__control {
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>
+5 -1
View File
@@ -282,7 +282,7 @@
variant="text"
size="small"
icon="mdi-delete"
color="delete_btn"
color="teal-darken-4"
@click="deletComment(y.id, newsFull.id)"
/>
</v-col>
@@ -353,6 +353,7 @@
density="compact"
variant="text"
icon="mdi-close"
color="teal-darken-4"
@click="dialogfoto = false"
/>
</v-col>
@@ -364,6 +365,7 @@
density="compact"
variant="text"
icon="mdi-chevron-left"
color="teal-darken-4"
@click="
indximg != 0
? (indximg -= 1)
@@ -382,6 +384,7 @@
density="compact"
variant="text"
icon="mdi-chevron-right"
color="teal-darken-4"
@click="
indximg != newsFull.gallery.length - 1
? (indximg += 1)
@@ -422,6 +425,7 @@
density="compact"
variant="text"
icon="mdi-close"
color="teal-darken-4"
@click="dialogfotoOne = false"
/>
</v-col>
+1 -1
View File
@@ -56,7 +56,7 @@
size="small"
variant="text"
icon="mdi-newspaper"
color="blue-darken-4"
color="teal-darken-4"
:to='`/news`'
/>
</v-col>
@@ -208,7 +208,7 @@ export default {
// Устанавливаем начальные даты
const currentDate = new Date();
const defaultStartDate = new Date(currentDate);
defaultStartDate.setHours(9, 0, 0, 0);
defaultStartDate.setHours(8, 0, 0, 0);
const defaultEndDate = new Date(currentDate);
defaultEndDate.setHours(18, 0, 0, 0);
@@ -1,45 +1,70 @@
<template>
<v-container :class="{ 'pa-4': !isDialog, 'pa-0': isDialog }">
<v-row class="justify-center" :class="{ 'mt-6': !isDialog, 'ma-0': isDialog }">
<v-col :cols="isDialog ? 12 : '12'" :md="isDialog ? 12 : '8'" :lg="isDialog ? 12 : '6'" class="pa-0">
<v-row
class="justify-center"
:class="{ 'mt-6': !isDialog, 'ma-0': isDialog }"
>
<v-col
:cols="isDialog ? 12 : '12'"
:md="isDialog ? 12 : '8'"
:lg="isDialog ? 12 : '6'"
class="pa-0"
>
<v-card :elevation="isDialog ? 0 : 2" class="rounded-lg" color="cards">
<v-card-title v-if="!isDialog" class="text-h6 font-weight-bold">Информация</v-card-title>
<v-card-text :class="[
'd-flex flex-column ga-6',
{ 'border-b-thin': !isDialog, 'pa-0': isDialog }
]">
<v-card-title v-if="!isDialog" class="text-h6 font-weight-bold"
>Информация</v-card-title
>
<v-card-text
:class="[
'd-flex flex-column ga-6',
{ 'border-b-thin': !isDialog, 'pa-0': isDialog },
]"
>
<div class="test-info">
<div class="d-flex justify-center mb-4">
<v-img
:src="data?.file || defaultImage"
class="rounded-lg"
max-height="200"
contain
<v-img
:src="data?.file || defaultImage"
class="rounded-lg"
max-height="200"
contain
/>
</div>
<div class="text-body-1 mb-4" v-html="formatDescription(data?.description)"></div>
<div
class="text-body-1 mb-4"
v-html="formatDescription(data?.description)"
></div>
<div class="d-flex align-center mb-3">
<v-icon icon="mdi-clock-outline" color="teal-darken-2" class="mr-2" />
<v-icon
icon="mdi-clock-outline"
color="teal-darken-2"
class="mr-2"
/>
<span class="text-body-1">
<strong>Время на прохождение:</strong> {{ formatTime.value }} {{ formatTime.unit }}
<strong>Время на прохождение:</strong> {{ formatTime.value }}
{{ formatTime.unit }}
</span>
</div>
<div class="d-flex align-center mb-3">
<v-icon
icon="mdi-format-list-numbered"
color="teal-darken-2"
class="mr-2"
/>
<span class="text-body-1">
<strong>Количество вопросов:</strong>
{{ data?.question_count }}
</span>
</div>
<div class="d-flex align-center mb-3">
<v-icon icon="mdi-format-list-numbered" color="teal-darken-2" class="mr-2" />
<span class="text-body-1">
<strong>Количество вопросов:</strong> {{ data?.question_count }}
</span>
</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" />
<span class="text-body-1">
<strong>Количество попыток:</strong> {{ remainingAttempts !== undefined ? remainingAttempts : data?.attemps_number }}
</span>
</div>
<div class="d-flex align-center">
<v-icon icon="mdi-percent" color="teal-darken-2" class="mr-2" />
<span class="text-body-1">
@@ -50,12 +75,12 @@
</v-card-text>
<v-card-actions v-if="!isDialog" class="mx-2 my-4">
<v-btn
v-if="remainingAttempts === undefined || remainingAttempts > 0"
v-if="!isExamMode || remainingAttempts === undefined || remainingAttempts > 0"
color="btn_text"
class="ml-auto px-9 text-white"
@click="startTest"
>
{{ isExamMode ? 'Начать' : 'Тренироваться' }}
{{ isExamMode ? "Начать" : "Тренироваться" }}
</v-btn>
<v-alert
v-else
@@ -74,9 +99,9 @@
</template>
<script>
import { useRoute } from 'vue-router';
import { computed } from 'vue';
import defaultImage from '@/assets/emblem.png';
import { useRoute } from "vue-router";
import { computed } from "vue";
import defaultImage from "@/assets/emblem.png";
export default {
props: {
@@ -93,11 +118,11 @@ export default {
},
setup(props) {
const route = useRoute();
const isExamMode = computed(() => route.query.mode === 'exam');
const isExamMode = computed(() => route.query.mode === "exam");
const formatTime = computed(() => {
if (!props.data?.time) return { value: 0, unit: 'минут' };
if (!props.data?.time) return { value: 0, unit: "минут" };
const time = Number(props.data.time);
// Если число больше 60, значит это секунды (таймер запущен)
@@ -106,32 +131,33 @@ export default {
const seconds = time % 60;
return {
value: `${minutes} мин. ${seconds}`,
unit: 'сек.'
unit: "сек.",
};
} else {
// Если меньше 60, значит это минуты (таймер не запущен)
return {
value: time,
unit: time === 1 ? 'минута' : time >= 2 && time <= 4 ? 'минуты' : 'минут'
unit:
time === 1 ? "минута" : time >= 2 && time <= 4 ? "минуты" : "минут",
};
}
});
const timeWordDeclension = computed(() => {
if (!props.data?.time) return 'минут';
if (!props.data?.time) return "минут";
const lastDigit = props.data.time % 10;
const lastTwoDigits = props.data.time % 100;
if (lastTwoDigits >= 11 && lastTwoDigits <= 14) return 'минут';
if (lastDigit === 1) return 'минута';
if (lastDigit >= 2 && lastDigit <= 4) return 'минуты';
return 'минут';
if (lastTwoDigits >= 11 && lastTwoDigits <= 14) return "минут";
if (lastDigit === 1) return "минута";
if (lastDigit >= 2 && lastDigit <= 4) return "минуты";
return "минут";
});
const formatDescription = (text) => {
if (!text) return '';
return text.replace(/\r?\n/g, '<br>');
if (!text) return "";
return text.replace(/\r?\n/g, "<br>");
};
return {
@@ -139,9 +165,9 @@ export default {
timeWordDeclension,
formatDescription,
formatTime,
defaultImage
defaultImage,
};
}
},
};
</script>
@@ -1,6 +1,7 @@
<!-- Раздел с назначенным тестированием -->
<template>
<!-- <div class="my-4 text-h5 font-weight-medium">{{ title }}</div> -->
<div :class="containerClass">
<v-container :fluid="true">
<v-row>
<v-text-field
@@ -58,9 +59,14 @@
<slot name="buttons" :cardValue="cardValue"></slot>
</template>
<template v-else>
<div class="d-flex align-center status-badge error">
<v-icon color="red-darken-1" icon="mdi-alert-circle-outline" size="small" class="mr-2" />
<span class="text-red-darken-1 text-body-2 font-weight-medium">Попытки закончились</span>
<div>
<div class="d-flex status-badge error mb-2">
<v-icon color="red-darken-1" icon="mdi-alert-circle-outline" size="small" class="mr-2" />
<span class="text-red-darken-1 text-body-2 font-weight-medium">Попытки закончились</span>
</div>
<div class="text-caption text-grey-darken-1 text-center">
Для повторного прохождения<br>обратитесь к администратору
</div>
</div>
</template>
</v-col>
@@ -80,6 +86,7 @@
</v-card-title>
</v-row>
</v-container>
</div>
</template>
<script>
@@ -103,9 +110,16 @@ export default {
type: Array,
default: () => [],
},
class: {
type: [String, Object, Array],
default: '',
},
},
setup(props) {
const search = ref('');
// Create a computed property to handle the containerClass
const containerClass = computed(() => props.class);
const searchTest = computed(() => {
let filteredTests = props.testingCard;
@@ -169,7 +183,7 @@ export default {
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>
@@ -208,6 +222,15 @@ export default {
background: rgba(244, 67, 54, 0.1);
}
.no-attempts-container {
display: flex;
flex-direction: column;
align-items: center;
padding: 12px;
max-width: 200px;
text-align: center;
}
.empty-state {
min-height: 300px;
display: flex;
@@ -23,6 +23,7 @@
:answers="answers"
:finishTest="openFinishDialog"
@change-question="changeQuestion"
@answer-changed="onAnswerChanged"
/>
<!-- Результаты теста -->
@@ -36,6 +37,7 @@
:formattedTime="formatSpentTime"
:questions="data?.questions"
:userAnswers="answers"
:remainingAttempts="remainingAttempts"
@restart="startTest"
/>
@@ -147,16 +149,20 @@ export default {
const startTest = async () => {
await getTestById(testId);
// Проверяем, есть ли оставшиеся попытки
if (remainingAttempts.value !== undefined && remainingAttempts.value <= 0) {
const isExamMode = route.query.mode === 'exam';
if (isExamMode && remainingAttempts.value !== undefined && remainingAttempts.value <= 0) {
console.log('Нет оставшихся попыток для прохождения теста');
return; // Прерываем запуск теста если попыток не осталось
return;
}
testStarted.value = true;
testFinished.value = false;
currentQuestion.value = 0;
answers.value = Array(data.value.questions.length).fill(null);
answers.value = data.value.questions.map((question) => {
const correctAnswersCount = question.answers.filter(answer => answer.right_wrong).length;
return correctAnswersCount > 1 ? [] : null;
});
const initialTime = data.value.time * 60;
data.value = { ...data.value, time: initialTime };
@@ -168,7 +174,7 @@ export default {
timer = setInterval(() => {
if (data.value?.time > 0) {
data.value = { ...data.value, time: data.value.time - 1 };
data.value.time = data.value.time - 1;
spentTime.value += 1;
} else {
finishTest();
@@ -183,7 +189,6 @@ export default {
showFinishDialog.value = false;
try {
// [{ question_id, answers_id: [id, ...] }]
let answersToSubmit = [];
data.value.questions.forEach((question, questionIndex) => {
const answer = answers.value[questionIndex];
@@ -226,11 +231,20 @@ export default {
const answers = ref([]);
watch(data.value?.questions, (newData) => {
if (newData && Array.isArray(newData.questions)) {
answers.value = newData.questions.map(() => null);
}
});
watch(
() => data.value?.questions,
(newQuestions) => {
if (newQuestions && Array.isArray(newQuestions)) {
if (!answers.value || answers.value.length === 0) {
answers.value = newQuestions.map((question) => {
const correctAnswersCount = question.answers.filter(answer => answer.right_wrong).length;
return correctAnswersCount > 1 ? [] : null;
});
}
}
},
{ deep: true }
);
const correctAnswers = computed(
() =>
@@ -255,7 +269,11 @@ export default {
);
const answeredQuestions = computed(
() => answers.value.filter((answer) => answer !== null).length,
() => answers.value.filter((answer) => {
if (answer === null || answer === undefined) return false;
if (Array.isArray(answer)) return answer.length > 0;
return true;
}).length,
);
const testPassed = computed(() => testResults.value?.is_passed ?? false);
@@ -266,6 +284,13 @@ export default {
}
};
const onAnswerChanged = (questionIndex, value) => {
const newAnswers = [...answers.value];
newAnswers[questionIndex] = value;
answers.value = newAnswers;
};
const openFinishDialog = () => {
showFinishDialog.value = true;
};
@@ -288,6 +313,7 @@ export default {
answers,
currentQuestion,
changeQuestion,
onAnswerChanged,
showFinishDialog,
openFinishDialog,
correctAnswers,
@@ -52,7 +52,7 @@
<v-btn
v-else
elevation="0"
color="grey-darken-1"
color="teal-darken-1"
variant="tonal"
rounded="lg"
class="ml-auto px-6"
@@ -10,14 +10,14 @@
<v-card-text>
<v-img
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"
/>
<!-- Одиночный выбор -->
<v-radio-group
v-if="!isMultipleChoice"
v-model="answers[currentQuestion]"
v-model="currentAnswer"
>
<v-radio
v-for="(option, index) in question.answers"
@@ -25,10 +25,10 @@
:value="option.name"
>
<template v-slot:label>
<div class="text-center">
<div>
<v-img
v-if="option.file"
:src="`http://127.0.0.1:8000${option.file}`"
:src="`${baseURL.slice(0, -1)}${option.file}`"
class="mb-4"
width="400"
min-width="300"
@@ -48,15 +48,15 @@
<v-checkbox
v-for="(option, index) in question.answers"
:key="index"
v-model="answers[currentQuestion]"
v-model="currentAnswer"
:value="option.name"
class="mb-n6"
>
<template v-slot:label>
<div class="text-center">
<div>
<v-img
v-if="option.file"
:src="`http://127.0.0.1:8000${option.file}`"
:src="`${baseURL.slice(0, -1)}${option.file}`"
class="mb-4"
width="400"
min-width="300"
@@ -97,8 +97,9 @@
</template>
<script>
import { computed, watch } from "vue";
import { useRoute } from "vue-router";
import { computed } from 'vue';
import { useRoute } from 'vue-router';
import { baseURL } from '@/utils/axios-api';
export default {
props: {
@@ -108,7 +109,7 @@ export default {
finishTest: Function,
answers: Array,
},
setup(props) {
setup(props, { emit }) {
const route = useRoute();
const isPracticeMode = computed(
() => !route.query.mode || route.query.mode === "practice",
@@ -120,22 +121,24 @@ export default {
);
});
watch(
() => props.currentQuestion,
(newVal) => {
if (isMultipleChoice.value && !Array.isArray(props.answers[newVal])) {
props.answers[newVal] = [];
}
const currentAnswer = computed({
get() {
const answer = props.answers[props.currentQuestion];
return answer;
},
{ immediate: true },
);
set(value) {
emit('answer-changed', props.currentQuestion, value);
}
});
return {
isMultipleChoice,
isPracticeMode,
baseURL,
currentAnswer
};
},
emits: ["change-question"],
emits: ["change-question", "answer-changed"],
};
</script>
@@ -166,11 +169,6 @@ export default {
color: rgb(var(--v-theme-text_carous));
}
.v-radio-group :deep(.v-radio:hover),
.v-checkbox:hover {
transform: translateX(4px);
}
.v-btn {
text-transform: none;
font-weight: 500;
+104 -49
View File
@@ -12,28 +12,11 @@
</div>
<div v-else class="result-animation error">
<v-icon size="64" color="error" class="shake">mdi-close-circle</v-icon>
<div class="text-h6 error--text mt-2 fade-in">Не пройдено</div>
<div class="text-h6 error--text mt-2 fade-in">Тест не пройден</div>
</div>
</div>
<v-row class="mt-2">
<v-col cols="12" sm="4">
<v-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">
{{ isPracticeMode ? 'Правильных ответов (нажмите чтобы увидеть детали)' : 'Правильных ответов' }}
</div>
</v-card>
</v-col>
<v-col cols="12" sm="4">
<v-card class="pa-4 text-center result-card" elevation="2">
@@ -43,6 +26,24 @@
</v-card>
</v-col>
<v-col cols="12" sm="4">
<v-card
class="pa-4 text-center result-card"
:class="{ 'cursor-pointer': !fromCompletedTab }"
elevation="2"
:color="testPassed ? 'success-light' : 'error-light'"
@click="!fromCompletedTab && (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">
{{ !fromCompletedTab ? 'Правильных ответов (нажмите чтобы увидеть детали)' : 'Правильных ответов' }}
</div>
</v-card>
</v-col>
<v-col cols="12" sm="4">
<v-card class="pa-4 text-center result-card" elevation="2">
<v-icon size="36" color="primary" class="mb-2">mdi-clock-outline</v-icon>
@@ -52,11 +53,11 @@
</v-col>
</v-row>
<!-- Модальное окно с правильными ответами (только для тренировочного режима) -->
<v-dialog v-if="isPracticeMode" v-model="showAnswersDialog" max-width="600">
<!-- Модальное окно с правильными ответами -->
<v-dialog 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">
<span>Правильные ответы</span>
<span>{{ isPracticeMode ? 'Правильные ответы' : 'Результаты по вопросам' }}</span>
<v-spacer></v-spacer>
<v-btn icon="mdi-close" variant="text" @click="showAnswersDialog = false" color="white"></v-btn>
</v-card-title>
@@ -78,33 +79,46 @@
</div>
</v-expansion-panel-title>
<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-2 d-flex align-center">
<v-icon
:color="getAnswerColor(index, answer)"
size="small"
class="mr-2"
>
{{ getAnswerIcon(index, answer) }}
</v-icon>
<span :class="{ 'font-weight-bold': isAnswerCorrect(index, answer) }">
{{ answer.name }}
</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">
<p class="mb-4 font-weight-bold">{{ question.name }}</p>
<!-- Показываем варианты ответов только в тренировочном режиме -->
<div v-if="isPracticeMode">
<v-divider class="mb-2"></v-divider>
<div class="text-caption">
{{ isQuestionCorrect(index) ? 'Правильно ✓' : 'Неправильно ✗' }}
<div v-for="answer in question.answers" :key="answer.id" class="mb-2 d-flex align-center">
<v-icon
:color="getAnswerColor(index, answer)"
size="small"
class="mr-2"
>
{{ getAnswerIcon(index, answer) }}
</v-icon>
<span :class="{ 'font-weight-bold': isAnswerCorrect(index, answer) }">
{{ answer.name }}
</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>
<!-- В режиме экзамена показываем только статус ответа -->
<div v-if="hasUserAnswer(index)">
<v-divider v-if="isPracticeMode" class="mb-2"></v-divider>
<div class="text-body-2 font-weight-medium d-flex align-center">
<v-icon
:color="isQuestionCorrect(index) ? 'success' : 'error'"
class="mr-2"
size="small"
>
{{ isQuestionCorrect(index) ? 'mdi-check-circle' : 'mdi-close-circle' }}
</v-icon>
{{ isQuestionCorrect(index) ? 'Правильно' : 'Неправильно' }}
</div>
</div>
</v-expansion-panel-text>
@@ -114,9 +128,10 @@
</v-card>
</v-dialog>
<!-- Кнопка "Попробовать ещё раз" для тренировочного режима -->
<div v-if="isPracticeMode && !fromCompletedTab" class="d-flex justify-center mt-6">
<!-- Кнопка "Попробовать ещё раз" или информационное сообщение -->
<div class="d-flex justify-center mt-6">
<v-btn
v-if="canRetry"
color="teal-darken-1"
@click="$emit('restart')"
class="px-6"
@@ -125,6 +140,16 @@
<v-icon start>mdi-refresh</v-icon>
Попробовать ещё раз
</v-btn>
<v-alert
v-else-if="getRetryMessage"
type="info"
variant="tonal"
class="text-center"
:icon="testPassed ? 'mdi-check-circle' : 'mdi-information'"
>
{{ getRetryMessage }}
</v-alert>
</div>
</v-card>
</template>
@@ -157,6 +182,10 @@ export default {
fromCompletedTab: {
type: Boolean,
default: false
},
remainingAttempts: {
type: Number,
default: undefined
}
},
setup(props) {
@@ -164,6 +193,29 @@ export default {
const showAnswersDialog = ref(false);
const isPracticeMode = computed(() => !route.query.mode || route.query.mode === 'practice');
const isExamMode = computed(() => route.query.mode === 'exam');
const canRetry = computed(() => {
if (props.fromCompletedTab) return false;
if (isPracticeMode.value) return true;
if (isExamMode.value) {
// В режиме экзамена можно повторить только если есть попытки и тест не пройден
return props.remainingAttempts > 0 && !props.testPassed;
}
return true;
});
const getRetryMessage = computed(() => {
if (isExamMode.value && props.remainingAttempts !== undefined) {
if (props.testPassed) {
return 'Тест успешно пройден. Повторное прохождение недоступно.';
}
if (props.remainingAttempts <= 0) {
return 'Нет оставшихся попыток для прохождения теста. Для повторного прохождения обратитесь к администратору.';
}
}
return null;
});
const getQuestionStatusColor = (questionIndex) => {
if (!props.questions[questionIndex]?.answers) return 'grey';
@@ -301,6 +353,9 @@ export default {
return {
showAnswersDialog,
isPracticeMode,
isExamMode,
canRetry,
getRetryMessage,
isQuestionCorrect,
hasUserAnswer,
showUserAnswer,
@@ -36,6 +36,7 @@
label="Картинка"
variant="outlined"
:error-messages="answer.imageError"
class="file-input-fixed"
@update:model-value="(file) => handleImageUpload(file, answer, aIndex)"
></v-file-input>
@@ -174,3 +175,11 @@ export default {
}
};
</script>
<style>
.file-input-fixed {
max-width: 250px;
min-width: 200px;
flex-grow: 0;
}
</style>
@@ -15,6 +15,7 @@
:rules="[rules.required]"
label="Описание"
variant="outlined"
class="scrollable-textarea"
></v-textarea>
</div>
<div v-if="!isTest" class="pt-2 d-flex align-center">
@@ -183,5 +184,54 @@ export default {
</script>
<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>
@@ -45,7 +45,7 @@
>
<template v-slot:label>
<div class="text-body-2 font-weight-bold">
Голосование по отделам:
Голосование:
</div>
</template>
<v-radio
@@ -60,6 +60,7 @@
</v-radio-group>
</div>
<v-autocomplete
v-if="question.settings.onlyDep === null"
v-model="question.selectedEmployees"
:items="allEmployeesgroupedbydep"
class="text-no-wrap"
@@ -68,6 +69,8 @@
item-value="id"
label="Выберите сотрудников"
multiple
chips
closable-chips
variant="outlined"
@update:model-value="onEmployeeUpdate"
>
@@ -79,9 +82,11 @@
@update:model-value="toggleSelectAll"
></v-checkbox>
</template>
<template #selection="{ item }">
<template #selection="{ item, index }">
<v-chip
:prepend-avatar="checkremote(`${spravURL}${item.raw.login}.jpg`)"
closable
@click:close="removeSelectedEmployee(item.raw.id)"
>
{{ item.raw.familyname }}
</v-chip>
@@ -116,7 +121,8 @@
</template>
</template>
</v-autocomplete>
<transition-group name="list" tag="div">
<transition-group v-if="question.settings.onlyDep === null" name="list" tag="div">
<div
v-for="(person, pIndex) in question.answers"
:key="person"
@@ -125,6 +131,8 @@
<v-col class="py-0" cols="7">
<v-chip
:prepend-avatar="checkremote(`${spravURL}${findEmployeeById(person.text)?.login}.jpg`)"
closable
@click:close="removeEmployeeAnswer(pIndex)"
>
{{ findEmployeeById(person.text)?.fio }}
</v-chip>
@@ -158,7 +166,7 @@
import QuestionHeader from '@/components/vote/ConstructorVote/QuestionHeader.vue';
import QuestionSettings from '@/components/vote/ConstructorVote/QuestionSettings.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';
export default {
@@ -295,11 +303,55 @@ export default {
};
const onEmployeeUpdate = (selected) => {
// Filter existing answers to keep only those that are still selected
props.question.answers = props.question.answers.filter((e) =>
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);
};
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) => {
props.handleSelectAll(value, props.index);
@@ -307,8 +359,21 @@ export default {
};
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);
// Обновляем сохраненное состояние
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);
};
@@ -320,6 +385,27 @@ export default {
const isTestRoute = computed(() => {
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 {
resetAnswers,
@@ -328,6 +414,7 @@ export default {
onEmployeeUpdate,
toggleSelectAll,
removeEmployeeAnswer,
removeSelectedEmployee,
onEmployeesChange,
isTestRoute,
questionImagePreview,
+18 -3
View File
@@ -64,7 +64,7 @@
{{ answer.employee?.fio || answer.name }}
<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-list-item-action>
</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 = () => {
let voteData = []
for (let val of Object.values(result.value)) {
@@ -220,10 +234,10 @@ export default {
activepick.value = val
}
const groupedAnswers = (question) => {
const groupedAnswers = (question) => {
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);
} else if (question.settings.onlyDep) {
const byDepartment = filtered.filter(
@@ -263,6 +277,7 @@ export default {
isCurrentQuestionAnswered,
nextStep,
prevStep,
toggleAnswer,
submitVote,
isVoteSubmitted,
result
@@ -263,12 +263,17 @@
Голосование по отделам:
{{ 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 v-if="question.settings.onlyDep !== null">
<p><strong>Выбрано {{ question.answers.length }} сотрудников</strong></p>
</div>
<div v-else>
<p><strong>Выбранные сотрудники:</strong></p>
<ul>
<li v-for="employeeId in question.answers" :key="employeeId">
{{ findEmployeeById(employeeId.text).fio }}
</li>
</ul>
</div>
</div>
</div>
</v-card>
@@ -588,9 +593,9 @@ export default {
};
watch(
form.value,
() => {
if (!form.value.title || !form.value.description || form.value.questions.length < 1) {
() => form.value,
(formValue) => {
if (!formValue.title || !formValue.description || formValue.questions.length < 1) {
errorMessage.value = 'Все обязательные поля должны быть заполнены';
} else {
errorMessage.value = '';
@@ -602,14 +607,13 @@ export default {
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 },
@@ -628,12 +632,13 @@ export default {
};
const onlyDepdict = [
{ name: 'За любого сотрудника', value: null },
{ name: 'За любого сотрудника', value: 'any' },
{
name: 'Кроме своего отдела',
name: 'Только за сотрудника из другого отдела',
value: false,
},
{ name: 'Только за свой отдел', value: true },
{ name: 'Только за сотрудника из своего отдела', value: true },
{ name: 'За произвольного сотрудника (есть возможность добавить картинку)', value: null },
];
const quests = computed(() => form.value.questions.map((question) => question.text.length > 0));
@@ -686,11 +691,13 @@ export default {
testImage,
imagePreview,
previewImage,
handleTestImageUpload,
getImagePreviewUrl,
actualQuestionCount,
actualTestQuestionCount,
isTest: props.isTest,
imageError
imageError,
validateImage
};
},
};
+1 -1
View File
@@ -30,7 +30,7 @@
</v-tabs>
<v-tabs-window v-model="activeTab">
<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-for="(winner, department) in getWinnersByDepartment(question).winnersByDepartment"
:key="department"
+15 -5
View File
@@ -44,10 +44,10 @@
<v-sheet class="mx-auto" :class="favorit.length > 10 ? 'mx-n3' : ''" max-width="800">
<v-slide-group show-arrows>
<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">
<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>
</v-tooltip>
</v-btn-toggle>
@@ -146,12 +146,22 @@ export default {
}
.bgCard {
/* #ffffff6b #ffffff8c*/
background: #ffffff38;
background: #fff !important;
}
.bgText {
background: #ffffffb0;
background: #f5f5f5 !important;
color: #222 !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>
+38 -10
View File
@@ -223,7 +223,8 @@ export default {
pagecounter();
const accountStore = useAccountStore();
const router = useRouter();
const activeTab = ref(0);
const savedTab = localStorage.getItem('testHomePage_activeTab');
const activeTab = ref(savedTab ? parseInt(savedTab) : 0);
const currentTest = ref('');
const getAllTests = ref([]);
const deleteDialog = ref(false);
@@ -239,13 +240,38 @@ export default {
color: 'error'
});
// Функция для показа уведомлений
const showNotification = (text, color = 'error') => {
snackbar.value.text = text;
snackbar.value.color = color;
snackbar.value.show = true;
};
const updateCurrentTestCount = () => {
if (activeTab.value === 0) {
currentTest.value = getAllTests.value.filter(test =>
test.is_active &&
test.is_passed !== true &&
test.attemps_number > 0
).length;
}
};
const getAssignedTestsCount = () => {
axiosApiInstance
.get('/api/tests/gettests?status=active')
.then((resp) => {
const assignedTests = resp.data.filter(test =>
test.is_active &&
test.is_passed !== true &&
test.attemps_number > 0
);
currentTest.value = assignedTests.length;
})
.catch(() => {
currentTest.value = 0;
});
};
const getTestById = () => {
const status = activeTab.value === 2 ? '' :
activeTab.value === 0 ? '?status=active' :
@@ -258,26 +284,29 @@ export default {
})
.finally(() => {
if (activeTab.value === 0) {
currentTest.value = getAllTests.value.filter(test =>
test.is_active &&
test.is_passed !== true &&
test.attemps_number > 0
).length;
updateCurrentTestCount();
} else {
getAssignedTestsCount();
}
});
};
getTestById();
if (activeTab.value !== 0) {
getAssignedTestsCount();
}
watch(
() => activeTab.value,
() => {
(newTab) => {
localStorage.setItem('testHomePage_activeTab', newTab.toString());
getTestById();
},
);
const tabs = computed(() => [
{ value: 0, title: `Назначенные (${currentTest.value})` },
{ value: 0, title: `Назначенные${currentTest.value !== '' ? ` (${currentTest.value})` : ''}` },
{ value: 1, title: 'Завершенные' },
{ value: 2, title: 'Каталог' },
...(accountStore.user.is_staff ? [{ value: 3, title: 'Создать новый тест' }] : []),
@@ -363,7 +392,6 @@ export default {
const assignmentIds = activeAssignments.map(assignment => assignment.id);
await deleteTestingRecord(assignmentIds);
// Обновляем данные диалога после удаления всех назначений
await openAddDialog(selectedTestId.value);
showNotification('Все назначения успешно отменены', 'green');
-2
View File
@@ -16,8 +16,6 @@ done
shift $((OPTIND -1))
if [[ "${PRODUCTION}" != "False" ]]; then
if [[ "$AUTO_CONFIRM" == false ]]; then
read -p "Вы уверены, что хотите загрузить образы $COMPOSE_PROJECT_NAME? (y/n): " confirmation