refactor [P-36 УМТ]: карточки тестов

This commit is contained in:
Denzel committed 2025-02-17 12:05:45 +03:00
1 parent 8322398c10
commit 18bff58f66
171 files changed
+1908 -68116

No files matched your search

@@ -0,0 +1,34 @@
<template>
<v-container class="pa-4">
<v-row class="justify-center mt-6">
<v-col cols="12" md="8" lg="6">
<v-card elevation="2">
<v-card-title class="text-h6 font-weight-bold">Информация</v-card-title>
<v-card-text class="d-flex flex-lg-column ga-6 border-b-thin">
<p>Текст описания теста</p>
<p>
Текст описания технических возможностей тестирования (можно пропускать вопросы,
возвращаться, менять ответы, завершить досрочно тест...)
</p>
<p><strong>Время на прохождение — 15 минут</strong></p>
<p><strong>Срок прохождения — 22.06.2024</strong></p>
</v-card-text>
<v-card-actions class="mx-2 my-4">
<p>Попытка 1 из 2</p>
<v-btn color="white" class="ml-auto bg-teal-darken-1 px-9" @click="startTest">
Начать
</v-btn>
</v-card-actions>
</v-card>
</v-col>
</v-row>
</v-container>
</template>
<script>
export default {
props: {
startTest: Function,
},
};
</script>
+134 -134
View File
@@ -1,148 +1,148 @@
<!-- Раздел с назначенным тестированием -->
<template>
<div class="my-4 text-h5"> {{ title }} </div>
<v-container :fluid="true">
<v-row>
<v-text-field
v-model="search"
append-inner-icon="mdi-magnify"
label="Найти тестирование по названию"
variant="solo"
@click:append-inner="searchTest"
clearable/>
</v-row>
</v-container>
<!-- Карточка где буду отрисовываться тесты в цикле -->
<v-card v-for="cardValue in searchTest" :key="cardValue.id" class="my-2 border-sm">
<v-row class="pa-2">
<v-col cols="1">
<v-img height="125" :src="cardValue.file" />
</v-col>
<v-col cols="auto" class="d-flex flex-grow-1">
<div class="d-flex flex-column justify-center flex-grow-1">
<div class="text-body-1 font-weight-medium mb-2">{{ cardValue.name }}</div>
<div class="text-body-1 text-disabled mb-2">{{ cardValue.description }}</div>
<div class="d-flex ga-4">
<slot name="results"></slot>
<div v-for="icon in activeTabIcon">
<v-icon :color="icon.color" :icon="icon.icon" size="large" />
<span class="ml-1">{{ momenter(cardValue[icon.field], icon.field) }}</span>
</div>
</div>
</div>
</v-col>
<v-col cols="auto" class="align-self-center">
<slot name="buttons"></slot>
</v-col>
</v-row>
</v-card>
<!-- Если данные отсутствуют, выводим сообщение об этом -->
<v-container v-if="!searchTest.length" :fluid="true">
<v-row class="align-center flex-column">
<v-icon icon="mdi-note-off-outline" color="grey-lighten-1" size="x-large" />
<v-card-title class="text-h4 text-grey-lighten-1">Данные не найдены</v-card-title>
</v-row>
</v-container>
<div class="my-4 text-h5">{{ title }}</div>
<v-container :fluid="true">
<v-row>
<v-text-field
v-model="search"
append-inner-icon="mdi-magnify"
label="Найти тестирование по названию"
variant="solo"
@click:append-inner="searchTest"
clearable
/>
</v-row>
</v-container>
<!-- Карточка где буду отрисовываться тесты в цикле -->
<v-card v-for="cardValue in searchTest" :key="cardValue.id" class="my-2 border-sm">
<v-row class="pa-2">
<v-col cols="2" class="justify-center">
<v-img :src="cardValue.file" class="mx-auto" />
</v-col>
<v-col cols="auto" class="d-flex flex-grow-1">
<div class="d-flex flex-column justify-center flex-grow-1">
<div class="text-body-1 font-weight-medium mb-2">{{ cardValue.name }}</div>
<div class="text-body-1 text-disabled mb-2">{{ cardValue.description }}</div>
<div class="d-flex ga-4">
<slot name="results"></slot>
<div v-for="icon in activeTabIcon">
<v-icon :color="icon.color" :icon="icon.icon" size="large" />
<span class="ml-1">{{ momenter(cardValue[icon.field], icon.field) }}</span>
</div>
</div>
</div>
</v-col>
<v-col cols="auto" class="align-self-center">
<slot name="buttons"></slot>
</v-col>
</v-row>
</v-card>
<!-- Если данные отсутствуют, выводим сообщение об этом -->
<v-container v-if="!searchTest.length" :fluid="true" class="h-100">
<v-row class="align-center flex-column">
<v-icon icon="mdi-note-off-outline" color="grey-lighten-1" size="x-large" />
<v-card-title class="text-h4 text-grey-lighten-1">Данные не найдены</v-card-title>
</v-row>
</v-container>
</template>
<script>
import moment from 'moment';
import { declOfNum } from '@/utils/universal_functions'
import { baseURL } from "@/utils/axios-api";
import { declOfNum } from '@/utils/universal_functions';
import { baseURL } from '@/utils/axios-api';
import { ref, computed } from 'vue';
export default {
props: {
title: {
type: String,
default: 'Не забыть передать тайтл сюда!',
},
activeTab: {
type: Number,
default: 0,
},
testingCard: {
type: Array,
default: () => [
{
id: 1,
name: 'Комплекс тестовых вопросов на знание в области информационно-коммуникационных технологий',
type: 'test',
description: 'Краткое описание тестирования',
file: 'https://icdn.lenta.ru/images/2024/03/27/12/20240327123127525/square_1280_63e6b3d7acbfce65d885ae4cf216dfe2.jpg',
dateend: new Date(),
question_count: 20,
time: 20,
attemps_number: 3,
},
{
id: 2,
name: 'Удобство раздела тестирования',
type: 'test',
description: 'Опрос среди сотрудников ЦОД МФ',
file: 'https://icdn.lenta.ru/images/2024/03/27/12/20240327123127525/square_1280_63e6b3d7acbfce65d885ae4cf216dfe2.jpg',
dateend: new Date(),
question_count: 28,
time: 15,
attemps_number: 1,
},
]
}
props: {
title: {
type: String,
default: 'Не забыть передать тайтл сюда!',
},
setup(props) {
const search = ref('');
const searchTest = computed(() => {
if (!search.value) return props.testingCard
return props.testingCard.filter(item => item.name.toLowerCase().includes(search.value.toLowerCase()))
})
activeTab: {
type: Number,
default: 0,
},
testingCard: {
type: Array,
default: () => [
{
id: 1,
name: 'Комплекс тестовых вопросов на знание в области информационно-коммуникационных технологий',
type: 'test',
description: 'Краткое описание тестирования',
file: 'https://icdn.lenta.ru/images/2024/03/27/12/20240327123127525/square_1280_63e6b3d7acbfce65d885ae4cf216dfe2.jpg',
dateend: new Date(),
question_count: 20,
time: 20,
attemps_number: 3,
},
{
id: 2,
name: 'Удобство раздела тестирования',
type: 'test',
description: 'Опрос среди сотрудников ЦОД МФ',
file: 'https://icdn.lenta.ru/images/2024/03/27/12/20240327123127525/square_1280_63e6b3d7acbfce65d885ae4cf216dfe2.jpg',
dateend: new Date(),
question_count: 28,
time: 15,
attemps_number: 1,
},
],
},
},
setup(props) {
const search = ref('');
const activeTabIcon = computed(() => {
let icons = [
// иконки для использования в карточках
{
icon: 'mdi-calendar-clock',
field: 'dateend',
color: 'teal-darken-1',
},
{
icon: 'mdi-clipboard-list-outline',
field: 'question_count',
color: 'teal-darken-1',
},
{
icon: 'mdi-timer-outline',
field: 'time',
color: 'teal-darken-1',
},
{
icon: 'mdi-fire',
field: 'attemps_number',
color: '#FF9800'
},
]
if (props.activeTab == 0) {
return icons
} else {
return icons.splice(1,2)
}
})
const searchTest = computed(() => {
if (!search.value) return props.testingCard;
return props.testingCard.filter((item) =>
item.name.toLowerCase().includes(search.value.toLowerCase()),
);
});
const momenter = (val, field)=>{
if (field == 'dateend'){
return 'до ' + moment(val).format('DD.MM.YYYY, HH:mm')
}
else if (field == 'question_count') {
return val + declOfNum(val, [' вопрос', ' вопроса', ' вопросов'])
}
else if (field == 'time') {
return val + declOfNum(val, [' минута', ' минуты', ' минут'])
}
return val
}
const activeTabIcon = computed(() => {
let icons = [
// иконки для использования в карточках
{
icon: 'mdi-calendar-clock',
field: 'dateend',
color: 'teal-darken-1',
},
{
icon: 'mdi-clipboard-list-outline',
field: 'question_count',
color: 'teal-darken-1',
},
{
icon: 'mdi-timer-outline',
field: 'time',
color: 'teal-darken-1',
},
{
icon: 'mdi-fire',
field: 'attemps_number',
color: '#FF9800',
},
];
if (props.activeTab === 0) {
return icons;
} else {
return icons.splice(1, 2);
}
});
return { search, searchTest, momenter, activeTabIcon, baseURL }
}
}
const momenter = (val, field) => {
if (field === 'dateend') {
return 'до ' + moment(val).format('DD.MM.YYYY, HH:mm');
} else if (field === 'question_count') {
return val + declOfNum(val, [' вопрос', ' вопроса', ' вопросов']);
} else if (field === 'time') {
return val + declOfNum(val, [' минута', ' минуты', ' минут']);
}
return val;
};
</script>
return { search, searchTest, momenter, activeTabIcon, baseURL };
},
};
</script>
@@ -1,18 +1,159 @@
<template>
<v-container>
<HeaderDetailTesting />
<v-container class="pa-4">
<!-- Верхняя панель -->
<HeaderDetailTesting
:testStarted="testStarted"
:formattedTime="formattedTime"
:finishTest="openFinishDialog"
:currentQuestion="currentQuestion"
:totalQuestions="questions.length"
@change-question="changeQuestion"
/>
</v-container>
<!-- Блок информации о тесте -->
<BodyDetailTesting v-if="!testStarted && !testFinished" :startTest="startTest" />
<!-- Вопросы теста -->
<QuestionBlock
v-if="testStarted"
:question="questions[currentQuestion]"
:currentQuestion="currentQuestion"
:totalQuestions="questions.length"
:answers="answers"
@change-question="changeQuestion"
/>
<!-- Результаты теста -->
<TestResults
v-if="testFinished"
:testFinished="testFinished"
:testPassed="testPassed"
:correctAnswers="correctAnswers"
:answeredQuestions="answeredQuestions"
:totalQuestions="questions.length"
:formattedTime="formattedTime"
/>
<!-- Диалог подтверждения завершения теста -->
<v-dialog v-model="showFinishDialog" persistent max-width="400px">
<v-card>
<v-card-title class="text-h6">Завершить тест?</v-card-title>
<v-card-text>Вы уверены, что хотите завершить тестирование?</v-card-text>
<v-card-actions class="d-flex justify-end">
<v-btn color="teal-darken-1" @click="finishTest">Да, завершить</v-btn>
<v-btn color="grey" @click="showFinishDialog = false">Отмена</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</v-container>
</template>
<script>
import HeaderDetailTesting from './HeaderDetailTesting.vue';
import { computed, ref, onUnmounted } from 'vue';
import HeaderDetailTesting from '@/components/testing/HeaderDetailTesting.vue';
import BodyDetailTesting from '@/components/testing/BodyDetailTesting.vue';
import QuestionBlock from '@/components/testing/QuestionBlock.vue';
import TestResults from '@/components/testing/TestResults.vue';
export default {
components: {
HeaderDetailTesting,
}
}
components: { BodyDetailTesting, HeaderDetailTesting, QuestionBlock, TestResults },
setup() {
const timeLeft = ref(900);
const testStarted = ref(false);
const testFinished = ref(false);
const showFinishDialog = ref(false);
const currentQuestion = ref(0);
let timer = null;
</script>
const questions = ref([
{
question: 'Ваши родители знают что Вы гей?',
options: ['Да', 'Нет'],
correct: 'Да',
},
{
question: 'Какой цвет у неба?',
options: ['Синий', 'Зеленый', 'Красный', 'Желтый'],
correct: 'Синий',
},
{ question: 'Сколько дней в неделе?', options: ['5', '6', '7', '8'], correct: '7' },
{
question: 'Как называется столица Франции?',
options: ['Берлин', 'Париж', 'Лондон', 'Рим'],
correct: 'Париж',
},
{ question: 'Сколько ног у паука?', options: ['4', '6', '8', '10'], correct: '8' },
]);
const answers = ref(new Array(questions.value.length).fill(null));
const formattedTime = computed(() => {
const minutes = Math.floor(timeLeft.value / 60);
const seconds = timeLeft.value % 60;
return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
});
const correctAnswers = computed(
() =>
answers.value.filter((answer, index) => answer === questions.value[index].correct).length,
);
const answeredQuestions = computed(
() => answers.value.filter((answer) => answer !== null).length,
);
const testPassed = computed(() => correctAnswers.value >= questions.value.length / 2);
const startTest = () => {
testStarted.value = true;
testFinished.value = false;
timer = setInterval(() => {
if (timeLeft.value > 0) {
timeLeft.value--;
} else {
clearInterval(timer);
openFinishDialog();
}
}, 1000);
};
const changeQuestion = (newIndex) => {
if (newIndex >= 0 && newIndex < questions.value.length) {
currentQuestion.value = newIndex;
}
};
const openFinishDialog = () => {
showFinishDialog.value = true;
};
const finishTest = () => {
clearInterval(timer);
testStarted.value = false;
testFinished.value = true;
showFinishDialog.value = false;
};
onUnmounted(() => {
if (timer) clearInterval(timer);
});
return {
testStarted,
testFinished,
formattedTime,
startTest,
finishTest,
questions,
answers,
currentQuestion,
changeQuestion,
showFinishDialog,
openFinishDialog,
correctAnswers,
answeredQuestions,
testPassed,
};
},
};
</script>
@@ -1,43 +1,91 @@
<template>
<v-row class="ma-0 border-b-thin">
<v-col cols="auto" class="flex-grow-1">
<div class="text-subtitle-1 text-grey-lighten-1">Тест</div>
<div class="text-h5">{{ title }}</div>
</v-col>
<v-col cols="auto" class="d-flex flex-column">
<div class="align-self-end text-grey-lighten-1">!!!</div>
<div class="text-h4 text-grey-lighten-1">{{ time }}Таймер сюдаааа!!!</div>
</v-col>
<v-container class="pa-4">
<v-row align="center" class="border-b-thin">
<v-col class="text-h6 font-weight-regular">
Комплекс тестовых вопросов на знание в области информационно-коммуникационных технологий
</v-col>
<span class="text-h6 text-grey-darken-1 font-weight-bold mr-4">{{ formattedTime }}</span>
</v-row>
<v-row class="ma-0 border-b-thin">
<v-col cols="auto" class="flex-grow-1">
<v-container class="d-flex align-center max-width">
<v-btn elevation="1" color="teal-darken-1" size="x-small" rounded icon="mdi-information-outline" />
<v-pagination :length="25" :total-visible="20" next-icon="mdi-menu-right" prev-icon="mdi-menu-left">
<template #item="item">
{{ item }}
</template>
</v-pagination>
</v-container>
</v-col>
<v-col cols="auto" class="align-self-center">
<v-btn elevation="0" color="#0000001F" rounded="1">Выйти</v-btn>
</v-col>
<v-row align="center" class="border-b-thin pa-2">
<v-btn
elevation="1"
color="teal-darken-1"
size="x-small"
rounded
icon="mdi-information-outline"
/>
<!-- Пагинация только при запущенном тесте -->
<v-pagination
v-if="testStarted"
:length="totalQuestions"
:total-visible="5"
:model-value="currentQuestion + 1"
@update:model-value="changePage"
></v-pagination>
<v-btn
v-if="testStarted"
elevation="0"
color="red-darken-1"
rounded="lg"
class="ml-auto"
@click="finishTest"
>
Завершить
</v-btn>
<v-btn
v-else
elevation="0"
color="grey-lighten-3"
rounded="lg"
class="ml-auto"
@click="showExitDialog = true"
>
Выйти
</v-btn>
</v-row>
<!-- Диалоговое окно выхода -->
<v-dialog v-model="showExitDialog" width="400">
<v-card>
<v-card-title class="text-h6">Вы действительно хотите выйти?</v-card-title>
<v-card-text>Прогресс будет сброшен.</v-card-text>
<v-card-actions>
<v-btn color="red" @click="exitTest">Да</v-btn>
<v-btn color="grey" @click="showExitDialog = false">Отмена</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</v-container>
</template>
<script>
import { ref } from 'vue';
export default {
props: {
title: {
type: String,
default: 'Название теста здесь',
},
time: {
props: {
testStarted: Boolean,
formattedTime: String,
finishTest: Function,
currentQuestion: Number,
totalQuestions: Number,
},
emits: ['change-question'],
setup(props, { emit }) {
const showExitDialog = ref(false);
}
}
}
const exitTest = () => {
showExitDialog.value = false;
window.history.back();
};
</script>
const changePage = (newPage) => {
emit('change-question', newPage - 1);
};
return { showExitDialog, exitTest, changePage };
},
};
</script>
@@ -0,0 +1,45 @@
<template>
<v-card class="mt-4 w-75 mx-auto">
<v-card-title class="text-h6 font-weight-bold">
Вопрос {{ currentQuestion + 1 }} из {{ totalQuestions }}
</v-card-title>
<v-card-text>
<p>{{ question.question }}</p>
<v-radio-group v-model="answers[currentQuestion]">
<v-radio
v-for="(option, index) in question.options"
:key="index"
:label="option"
:value="option"
/>
</v-radio-group>
</v-card-text>
<v-card-actions class="d-flex">
<v-btn
:disabled="currentQuestion === 0"
@click="$emit('change-question', currentQuestion - 1)"
>
Назад
</v-btn>
<v-btn
:disabled="currentQuestion === totalQuestions - 1"
color="teal-darken-1"
@click="$emit('change-question', currentQuestion + 1)"
>
Далее
</v-btn>
</v-card-actions>
</v-card>
</template>
<script>
export default {
props: {
question: Object,
currentQuestion: Number,
totalQuestions: Number,
answers: Array,
},
emits: ['change-question'],
};
</script>
@@ -0,0 +1,49 @@
<template>
<v-card v-if="testFinished" class="mt-4 pa-4">
<v-card-title class="text-h6 font-weight-bold">Результаты тестирования</v-card-title>
<v-card-text>
<v-alert v-if="testPassed" type="success" class="mt-4 d-flex align-center">
Тест успешно пройден
</v-alert>
<v-alert v-if="!testPassed" type="error" class="mt-4 d-flex align-center">
Тест не пройден
</v-alert>
</v-card-text>
<v-row class="mt-2">
<v-col cols="4">
<v-card class="pa-2 text-center">
<p class="text-h6">{{ correctAnswers }}/{{ totalQuestions }}</p>
<small>Правильных ответов</small>
</v-card>
</v-col>
<v-col cols="4">
<v-card class="pa-2 text-center">
<p class="text-h6">{{ answeredQuestions }}/{{ totalQuestions }}</p>
<small>Ответов дано</small>
</v-card>
</v-col>
<v-col cols="4">
<v-card class="pa-2 text-center">
<p class="text-h6">{{ formattedTime }}</p>
<small>Оставшееся время</small>
</v-card>
</v-col>
</v-row>
</v-card>
</template>
<script>
export default {
props: {
testFinished: Boolean,
testPassed: Boolean,
correctAnswers: Number,
answeredQuestions: Number,
totalQuestions: Number,
formattedTime: String,
},
};
</script>
@@ -1,35 +0,0 @@
<template>
<v-card-title>{{ item.title }}</v-card-title>
<v-card-subtitle>
<div>{{ item.description }}</div>
</v-card-subtitle>
<v-card-actions class="ga-4">
<div>
<v-icon color="teal-darken-4">mdi-calendar</v-icon>
<strong> До:</strong> {{ new Date(item.date).toLocaleDateString() }}
</div>
<div>
<v-icon color="teal-darken-4">mdi-calendar-text</v-icon>
<strong> Вопросов:</strong> {{ item.questions }}
</div>
<div v-if="item.time">
<v-icon color="teal-darken-4">mdi-clock</v-icon>
<strong> Время:</strong> {{ item.time }}
</div>
<div v-if="item.attempts">
<v-icon color="deep-orange-accent-4">mdi-alert-outline</v-icon>
<strong> Попытки:</strong> {{ item.attempts }}
</div>
</v-card-actions>
</template>
<script>
export default {
props: {
item: {
type: Object,
required: true
}
}
};
</script>
@@ -648,10 +648,6 @@ export default {
{ deep: true },
);
const updateQuests = () => {
quests.value = form.value.questions.map((q) => !!q.text.trim());
};
watch(
() => form.value.questions,
(newQuestions) => {
+19 -23
View File
@@ -1,42 +1,37 @@
<template>
<v-container :fluid="true">
<v-tabs v-model="activeTab" class="mb-2 text-teal-darken-4">
<v-tab v-for="tab in tabs" :key="tab.value" :value="tab.value"> {{ tab.title }} </v-tab>
<v-container :fluid="true" class="pa-2 d-flex flex-column h-100">
<v-tabs v-model="activeTab" class="mx-2">
<v-tab v-for="tab in tabs" :key="tab.value" :value="tab.value"> {{ tab.title }}</v-tab>
</v-tabs>
<v-tabs-window v-model="activeTab" class="border-t-thin">
<v-tabs-window v-model="activeTab">
<!-- Вкладка назначенные -->
<v-tabs-window-item class="my-2">
<CatalogTest title="Назначенные" :activeTab="activeTab" :testingCard="getAllTests">
<v-tabs-window-item class="my-2 w-75 mx-auto h-100">
<CatalogTest :activeTab="activeTab" :testingCard="getAllTests" title="Назначенные">
<template #buttons>
<v-btn color="#00897B1F" class="mr-2 text-teal-darken-1" elevation="0">
<v-btn class="mr-2 text-teal-darken-1" color="#00897B1F" elevation="0">
Тренироваться
</v-btn>
<v-btn color="teal-darken-1" elevation="0"> Пройти </v-btn>
<v-btn color="teal-darken-1" elevation="0"> Пройти</v-btn>
</template>
</CatalogTest>
</v-tabs-window-item>
<!-- Вкладка завершенных -->
<v-tabs-window-item>
<CatalogTest title="Завершенные" :activeTab="activeTab" :testingCard="getAllTests">
<v-tabs-window-item class="w-75 mx-auto">
<CatalogTest :activeTab="activeTab" :testingCard="getAllTests" title="Завершенные">
<!-- Здесь отобразить результат теста после того как будет готов БЭК и УМТ -->
<template #results>
<!-- <div>
<v-icon icon="mdi-calendar-clock" size="large" />
<span class="ml-1">12354</span>
</div> -->
</template>
<template #results></template>
<template #buttons>
<v-btn color="#00897B1F" class="mr-2 text-teal-darken-1" elevation="0">
<v-btn class="mr-2 text-teal-darken-1" color="#00897B1F" elevation="0">
Результаты
</v-btn>
</template>
</CatalogTest>
</v-tabs-window-item>
<!-- Вкладка каталога -->
<v-tabs-window-item>
<CatalogTest title="Каталог" :activeTab="activeTab" :testingCard="getAllTests">
<v-tabs-window-item class="w-75 mx-auto h-100">
<CatalogTest :activeTab="activeTab" :testingCard="getAllTests" title="Каталог">
<template #buttons>
<v-btn color="#00897B1F" class="mr-2 text-teal-darken-1" elevation="0">
<v-btn class="mr-2 text-teal-darken-1" color="#00897B1F" elevation="0">
Тренироваться
</v-btn>
</template>
@@ -50,7 +45,7 @@
import CatalogTest from '@/components/testing/CatalogTest.vue';
import { axiosApiInstance } from '@/utils/axios-api';
import { ref, computed, watch } from 'vue';
import { computed, ref, watch } from 'vue';
export default {
components: {
@@ -64,12 +59,12 @@ export default {
const getTestById = () => {
let status =
activeTab.value == 0 ? '?status=active' : activeTab.value == 1 ? '?status=completed' : '';
activeTab.value === 0 ? '?status=active' : activeTab.value === 1 ? '?status=completed' : '';
axiosApiInstance
.get(`/api/tests/gettests/${status}`)
.then((resp) => (getAllTests.value = resp.data))
.finally(() => {
if (activeTab.value == 0) {
if (activeTab.value === 0) {
currentTest.value = getAllTests.value.length;
}
});
@@ -81,6 +76,7 @@ export default {
() => activeTab.value,
() => {
getTestById();
console.log(getAllTests);
},
);
+70 -72
View File
@@ -2,30 +2,25 @@
<v-container class="pt-2 d-flex flex-column" fluid>
<v-row class="flex-column">
<v-col cols="auto">
<v-tabs
v-model="currentTab"
align="center">
<v-tabs v-model="currentTab" align="center">
<v-tab v-for="x in tabs" :key="x.value" :value="x.value">{{ x.text }}</v-tab>
<v-tab v-if="accountStore.user.is_staff" value="constructor">Создать новое голосование</v-tab>
<v-tab v-if="accountStore.user.is_staff" value="constructor"
>Создать новое голосование</v-tab
>
</v-tabs>
</v-col>
<v-col class="pa-0 overflow-hidden">
<v-window v-model="currentTab" class="h-100">
<!-- Текущие голосования -->
<v-tabs-window-item v-for="x in ['active','completed']" :value="x" class="h-100 overflow-auto">
<v-tabs-window-item
v-for="x in ['active', 'completed']"
:value="x"
class="h-100 overflow-auto"
>
<v-row v-if="sortedVotes.length > 0" class="mx-2">
<v-col
v-for="voting in sortedVotes"
:key="voting.id"
cols="12"
lg="3"
md="4"
>
<v-col v-for="voting in sortedVotes" :key="voting.id" cols="12" lg="3" md="4">
<VoteCardVue
:isFinished="currentTab==='active'"
:isFinished="currentTab === 'active'"
:voteCard="voting"
@deleteVoting="deleteVoting"
@openResultModal="(voting) => openModal('results', voting)"
@@ -33,17 +28,21 @@
/>
</v-col>
</v-row>
<NoneVote v-else :current="currentTab == 'active' ? 'Текущих' : 'Завершенных'"/>
<NoneVote v-else :current="currentTab === 'active' ? 'Текущих' : 'Завершенных'" />
</v-tabs-window-item>
<!-- Конструктор -->
<v-tabs-window-item v-if="accountStore.user.is_staff" class="h-100 overflow-auto" value="constructor">
<VoteConstructor @updating="updating" ref="constructor"/>
<v-tabs-window-item
v-if="accountStore.user.is_staff"
class="h-100 overflow-auto"
value="constructor"
>
<VoteConstructor @updating="updating" ref="constructor" />
</v-tabs-window-item>
</v-window>
<!-- Модальные окна -->
<v-dialog v-model="voteModal" @click:outside="closeModal">
<CurrentVote :data="res" @closer="closeModal"/>
<CurrentVote :data="res" @closer="closeModal" />
</v-dialog>
<v-dialog v-model="resultsModal" max-width="1200px" @click:outside="closeModal">
@@ -57,60 +56,59 @@
</template>
<script>
import {computed, ref, watch} from "vue";
import VoteConstructor from "@/components/vote/VoteConstructor.vue";
import CurrentVote from "@/components/vote/CurrentVote.vue";
import VoteCardVue from "@/components/vote/VoteCard.vue";
import NoneVote from "@/components/vote/NoneVote.vue"
import {useRoute, useRouter} from "vue-router";
import VoteResult from "@/components/vote/VoteResult.vue";
import {deleteVote, getVoteDetail, getVoteResult, getVotes} from "@/utils/axios-api";
import { computed, ref, watch } from 'vue';
import VoteConstructor from '@/components/vote/VoteConstructor.vue';
import CurrentVote from '@/components/vote/CurrentVote.vue';
import VoteCardVue from '@/components/vote/VoteCard.vue';
import NoneVote from '@/components/vote/NoneVote.vue';
import { useRoute, useRouter } from 'vue-router';
import VoteResult from '@/components/vote/VoteResult.vue';
import { deleteVote, getVoteDetail, getVoteResult, getVotes } from '@/utils/axios-api';
// import {formatDate} from "@vueuse/shared";
import { useAccountStore } from "@/store/AccountStore";
import {pagecounter} from '@/utils/universal_functions'
import { useAccountStore } from '@/store/AccountStore';
import { pagecounter } from '@/utils/universal_functions';
export default {
components: {CurrentVote, VoteConstructor, VoteCardVue, VoteResult, NoneVote},
components: { CurrentVote, VoteConstructor, VoteCardVue, VoteResult, NoneVote },
setup() {
pagecounter()
pagecounter();
const accountStore = useAccountStore();
const tabs = [
{value: "active", text: 'Текущие голосования'},
{value: "completed", text: 'Завершенные голосования'},
{ value: 'active', text: 'Текущие голосования' },
{ value: 'completed', text: 'Завершенные голосования' },
];
]
const currentTab = ref("active");
const currentTab = ref('active');
const votes = ref([]);
const router = useRouter();
const route = useRoute();
const res = ref(null);
const result = ref(null);
const constructor = ref(null)
const constructor = ref(null);
const updating = async (param) => {
const data = await getVotes(param);
votes.value = data;
};
updating("active");
updating('active');
const voteModal = ref(false);
const resultsModal = ref(false);
const selectedVoting = ref(null);
const sortedVotes = computed(() => currentTab.value === 'active' ? votes.value.sort((a, b) =>
new Date(a.dateend) - new Date(b.dateend)) :
votes.value.sort((a, b) => new Date(b.dateend) - new Date(a.dateend)));
const sortedVotes = computed(() =>
currentTab.value === 'active'
? votes.value.sort((a, b) => new Date(a.dateend) - new Date(b.dateend))
: votes.value.sort((a, b) => new Date(b.dateend) - new Date(a.dateend)),
);
const loadVoteDetails = async (id) => {
try {
const data = await getVoteDetail(id);
res.value = data;
} catch (error) {
console.error("Ошибка при загрузке данных голосования:", error);
console.error('Ошибка при загрузке данных голосования:', error);
// res.value = {};
throw error;
@@ -122,7 +120,7 @@ export default {
const data = await getVoteResult(id);
result.value = data;
} catch (error) {
console.error("Ошибка при загрузке данных голосования:", error);
console.error('Ошибка при загрузке данных голосования:', error);
res.value = {};
}
};
@@ -131,26 +129,26 @@ export default {
voteModal.value = false;
resultsModal.value = false;
selectedVoting.value = null;
router.push({name: "VoteHomePage"});
if (route.name === "Voting") updating('active')
if (route.name === "VoteResults") updating('completed')
router.push({ name: 'VoteHomePage' });
if (route.name === 'Voting') updating('active');
if (route.name === 'VoteResults') updating('completed');
};
const openModal = async (type, voting) => {
selectedVoting.value = voting;
if (type === "vote") {
try{
if (type === 'vote') {
try {
await loadVoteDetails(voting.id);
console.log("sd;lkjs;ljlmnjlk");
console.log('sd;lkjs;ljlmnjlk');
voteModal.value = true;
router.push({name: "Voting", params: {id: voting.id}});
}catch(e){
router.push({ name: "VoteHomePage" })
router.push({ name: 'Voting', params: { id: voting.id } });
} catch (e) {
router.push({ name: 'VoteHomePage' });
}
} else if (type === "results") {
} else if (type === 'results') {
await loadVoteResult(voting.id);
resultsModal.value = true;
router.push({name: "VoteResults", params: {id: voting.id}});
router.push({ name: 'VoteResults', params: { id: voting.id } });
}
};
@@ -159,45 +157,45 @@ export default {
await deleteVote(id);
votes.value = votes.value.filter((v) => v.id !== id);
} catch (error) {
console.error("Ошибка при удалении голосования:", error);
console.error('Ошибка при удалении голосования:', error);
}
};
watch(currentTab, async () => {
if (currentTab.value !== 'constructor') {
await updating(currentTab.value)
await updating(currentTab.value);
console.log(constructor.value, '!!!');
if (constructor.value !== null) {
constructor.value.resetForm()
constructor.value.resetForm();
}
}
})
});
watch(
() => route,
async () => {
if (!voteModal.value && !resultsModal.value) {
const voting = votes.value.find((v) => v.id === route.params.id);
if (route.name === "Voting") {
try{
await loadVoteDetails(route.params.id);
voteModal.value = true;}
catch(e){
router.push({ name: "VoteHomePage" })
if (route.name === 'Voting') {
try {
await loadVoteDetails(route.params.id);
voteModal.value = true;
} catch (e) {
router.push({ name: 'VoteHomePage' });
}
}
// if (route.name === "EditVote") editVoteModal.value = true;
if (route.name === "VoteResults") {
await loadVoteResult(route.params.id)
if (route.name === 'VoteResults') {
await loadVoteResult(route.params.id);
resultsModal.value = true;
}
selectedVoting.value = voting || null;
}
},
{immediate: true}
{ immediate: true },
);
updating("active");
updating('active');
return {
accountStore,
@@ -214,7 +212,7 @@ export default {
res,
tabs,
result,
constructor
constructor,
};
},
};