Merge branch 'dev-denzel' into сja

This commit is contained in:
Cja committed 2025-01-14 17:09:52 +03:00
commit 2369c32233
11 files changed
+642 -388

No files matched your search

-1
View File
@@ -15,7 +15,6 @@ class GetVotes(APIView):
def get(self, request):
user = request.user
print(type(user))
# user = User.objects.get(username='9966-00-125')
now = datetime.now()
status = request.query_params.get('status')
@@ -0,0 +1,76 @@
<template>
<div class="px-4">
{{ displayDays + declOfNum(displayDays, [' день', ' дня', ' дней']) }}
{{ displayHours + declOfNum(displayHours, [' час', ' часа', ' часов']) }}
{{ displayMinutes + declOfNum(displayMinutes, [' минута', ' минуты', ' минут']) }}
{{ displaySeconds + declOfNum(displaySeconds, [' секунда', ' секунды', ' секунд']) }}
</div>
</template>
<script>
import { computed, ref } from 'vue'
export default {
props: {
endTime: {
type: Date,
default: () => { return new Date.setFullYear() }
}
},
setup(props) {
const seconds = 1000
const displayMinutes = ref(0);
const displayHours = ref(0);
const displayDays = ref(0);
const displaySeconds = ref(0)
const minutes = computed(() => {
return seconds * 60
})
const hours = computed(() => {
return minutes.value * 60
})
const days = computed(() => {
return hours.value * 24
})
function declOfNum(value, titles) {
const cases = [2, 0, 1, 1, 1, 2]
return titles[(value % 100 > 4 && value % 100 < 20) ? 2 : cases[(value % 10 < 5) ? value % 10 : 5]]
}
function countDown() {
const timer = setInterval(() => {
const date = new Date()
const distance = props.endTime.getTime() - date.getTime()
if (distance < 0) {
clearInterval(timer)
return
}
displayDays.value = Math.floor(distance / days.value)
displayHours.value = Math.floor((distance % days.value) / hours.value)
displayMinutes.value = Math.floor((distance % hours.value) / minutes.value)
displaySeconds.value = Math.floor((distance % minutes.value) / seconds)
}, 1000)
}
countDown()
return {
displayMinutes,
displayHours,
displayDays,
displaySeconds,
declOfNum,
}
}
}
</script>
+106
View File
@@ -0,0 +1,106 @@
<template>
<v-row dense class="ma-1 ">
<v-card variant="text" class="py-1">
<v-card-title class="text-body-1"> До окончания голосования осталось: </v-card-title>
<v-row dense class="align-baseline justify-center">
<v-col cols="auto" class="text-center">
<v-card class="bg-yellow-darken-4">
<v-card-title>{{ displayDays }}</v-card-title>
</v-card>
<span class="text-caption">{{ declOfNum(displayDays, [' день', ' дня', ' дней']) }}</span>
</v-col>
<v-col cols="auto">:</v-col>
<v-col cols="auto" class="text-center">
<v-card class="bg-yellow-darken-4">
<v-card-title>{{ displayHours }}</v-card-title>
</v-card>
<span class="text-caption">{{ declOfNum(displayHours, [' час', ' часа', ' часов']) }}</span>
</v-col>
<v-col cols="auto">:</v-col>
<v-col cols="auto" class="text-center">
<v-card class="bg-yellow-darken-4">
<v-card-title>{{ displayMinutes }}</v-card-title>
</v-card>
<span class="text-caption">{{ declOfNum(displayMinutes, [' минута', ' минуты', ' минут']) }}</span>
</v-col>
<v-col cols="auto">:</v-col>
<v-col cols="auto" class="text-center">
<v-card class="bg-yellow-darken-4">
<v-card-title>{{ displaySeconds }}</v-card-title>
</v-card>
<span class="text-caption">{{ declOfNum(displaySeconds, [' секунда', ' секунды', ' секунд']) }}</span>
</v-col>
</v-row>
</v-card>
</v-row>
</template>
<script>
import { computed, ref } from 'vue'
export default {
props: {
endTime: {
type: String,
default: () => { return new Date(props.endTime).setFullYear() }
}
},
setup(props) {
const seconds = 1000
const displayMinutes = ref(0);
const displayHours = ref(0);
const displayDays = ref(0);
const displaySeconds = ref(0)
const minutes = computed(() => {
return seconds * 60
})
const hours = computed(() => {
return minutes.value * 60
})
const days = computed(() => {
return hours.value * 24
})
function declOfNum(value, titles) {
const cases = [2, 0, 1, 1, 1, 2]
return titles[(value % 100 > 4 && value % 100 < 20) ? 2 : cases[(value % 10 < 5) ? value % 10 : 5]]
}
function countDown() {
const timer = setInterval(() => {
const date = new Date()
const distance = new Date(props.endTime).getTime() - date.getTime()
if (distance < 0) {
clearInterval(timer)
return
}
const daysOf = Math.floor(distance / days.value)
const hoursOf = Math.floor((distance % days.value) / hours.value)
const minutesOf = Math.floor((distance % hours.value) / minutes.value)
const secondsOf = Math.floor((distance % minutes.value) / seconds)
displayDays.value = daysOf < 10 ? "0" + daysOf : daysOf
displayHours.value = hoursOf < 10 ? "0" + hoursOf : hoursOf
displayMinutes.value = minutesOf < 10 ? "0" + minutesOf : minutesOf
displaySeconds.value = secondsOf < 10 ? "0" + secondsOf : secondsOf
}, 1000)
}
countDown()
return {
displayMinutes,
displayHours,
displayDays,
displaySeconds,
declOfNum,
}
}
}
</script>
+95 -124
View File
@@ -1,78 +1,69 @@
<template>
<template v-if="!isVoteSubmitted">
<!-- Заголовок голосовалки -->
<v-row class="pt-0">
<v-col cols="12">
<v-card flat>
<v-card-title>{{ title }}</v-card-title>
<v-card-subtitle>{{ description }}</v-card-subtitle>
</v-card>
</v-col>
</v-row>
<v-stepper v-model="activeStep">
<v-card-title>{{ data.name }}</v-card-title>
<v-card-subtitle>{{ data.description }}</v-card-subtitle>
<!-- Ожидаемая дата окончания голосования -->
<v-row>
<v-col cols="12">
<v-chip :color="isVotingActive ? 'green' : 'red'">
<v-icon>{{ isVotingActive ? 'mdi-check-circle' : 'mdi-clock' }}</v-icon>&nbsp;
{{ isVotingActive ? 'Голосование активно' : `Голосование закончится: ${endDateFormatted}` }}
</v-chip>
</v-col>
</v-row>
<!-- Вопросы голосования -->
<v-row v-for="(question, index) in questions" :key="index">
<v-col cols="12">
<v-card flat>
<v-card-title>{{ question.text }}</v-card-title>
<!-- Вопросы с типом "Ввести вручную" -->
<v-card-text v-if="question.type === 'Ввести вручную'">
<v-row v-for="(answer, id) in question.answers" :key="id">
<v-checkbox
v-model="answers[index]"
:value="answer.text"
color="teal-darken-4 opacity-100"
hide-details
>
<template #label>
<span class="text-black text-subtitle-1 opacity-100">{{ answer.text }}</span>
</template>
</v-checkbox>
</v-row>
</v-card-text>
<!-- Вопросы с типом "Выбрать сотрудника" -->
<v-card-text v-if="question.type === 'Выбрать сотрудника'">
<v-row v-for="employee in question.selectedEmployees" :key="employee.id">
<v-checkbox
v-model="selectedEmployees[index]"
:value="employee.id"
color="teal-darken-4 opacity-100"
hide-details
>
<template #label>
<span class="text-black text-subtitle-1 opacity-100">{{ employee.name }}</span>
</template>
</v-checkbox>
</v-row>
</v-card-text>
</v-card>
</v-col>
</v-row>
<!-- Кнопка для отправки голосования -->
<v-row>
<v-col cols="12">
<v-btn
:disabled="!isVotingActive || !isAllQuestionsAnswered"
color="teal-darken-4"
@click="submitVote"
<!-- Шаги голосования -->
<v-stepper-header>
<v-stepper-item
v-for="(question, index) in data.questions"
:key="index"
:complete="index < activeStep"
:step="index + 1"
>
Отправить голос
</v-btn>
</v-col>
</v-row>
Вопрос {{ index + 1 }}
</v-stepper-item>
</v-stepper-header>
<v-stepper-window>
<v-stepper-window-item
v-for="(question, index) in data.questions"
:key="index"
:step="index + 1"
>
<v-card flat>
<v-card-title>{{ question.question }}</v-card-title>
<v-card-text>
<!-- Ответы на вопрос -->
<v-row v-for="(answer, id) in question.answers" :key="id">
<v-checkbox
v-model="answers[index]"
:value="answer.answer"
color="teal-darken-4"
hide-details
>
<template #label>
<span class="text-black">{{ answer.answer }}</span>
</template>
</v-checkbox>
</v-row>
</v-card-text>
<!-- Действия -->
<v-card-actions>
<v-btn v-if="index > 0" @click="prevStep" outlined>Назад</v-btn>
<v-btn
v-if="index < data.questions.length - 1"
:disabled="!isCurrentQuestionAnswered"
@click="nextStep"
color="teal-darken-4"
>
Далее
</v-btn>
<v-btn
v-else
:disabled="!isCurrentQuestionAnswered"
color="teal-darken-4"
@click="submitVote"
>
Отправить
</v-btn>
</v-card-actions>
</v-card>
</v-stepper-window-item>
</v-stepper-window>
</v-stepper>
</template>
<!-- Спасибо за голос -->
@@ -87,84 +78,64 @@
</template>
<script>
import {computed, ref} from "vue";
import { computed, ref } from "vue";
export default {
props: {
description: String,
endDate: String,
questions: Array,
startDate: String,
title: String,
data: {
type: Object,
required: true,
default: () => ({}),
},
},
setup(props, {emit}) {
// Ответы на вопросы
const answers = ref([]);
const selectedEmployees = ref(props.questions.map(() => []));
// Форматированная дата окончания голосования
const endDateFormatted = computed(() =>
new Date(props.endDate).toLocaleString()
);
// Проверка активности голосования
const isVotingActive = computed(() => {
const currentDate = new Date();
const endDate = new Date(props.endDate);
return currentDate < endDate;
});
// Проверка, все ли вопросы были отвечены
const isAllQuestionsAnswered = computed(() => {
return props.questions.every((question, index) => {
if (question.type === "Ввести вручную") {
return !!answers.value[index];
}
if (question.type === "Выбрать сотрудника") {
return selectedEmployees.value[index].length > 0;
}
return false;
});
});
// Состояние для определения отправки голоса
setup(props, { emit }) {
const activeStep = ref(0);
const answers = ref(props.data.questions.map(() => null));
const isVoteSubmitted = ref(false);
// Отправка голосования
const isCurrentQuestionAnswered = computed(() => {
return !!answers.value[activeStep.value];
});
const nextStep = () => {
if (activeStep.value < props.data.questions.length - 1) {
activeStep.value++;
}
};
const prevStep = () => {
if (activeStep.value > 0) {
activeStep.value--;
}
};
const submitVote = () => {
const voteData = props.questions.map((question, index) => ({
question: question.text,
type: question.type,
answer:
question.type === "Ввести вручную"
? answers.value[index]
: selectedEmployees.value[index],
const voteData = props.data.questions.map((question, index) => ({
question: question.question,
answer: answers.value[index],
}));
console.log("Отправляем данные голосования:", voteData);
// После успешной отправки
isVoteSubmitted.value = true;
emit("submit", voteData);
};
return {
activeStep,
answers,
selectedEmployees,
endDateFormatted,
isVotingActive,
isVoteSubmitted,
isAllQuestionsAnswered,
isCurrentQuestionAnswered,
nextStep,
prevStep,
submitVote,
isVoteSubmitted,
};
},
};
</script>
<style>
.v-label {
color: #000 !important;
opacity: 1 !important;
}
</style>
@@ -0,0 +1,54 @@
<template>
<v-card>
<v-card-text class="d-flex justify-space-between ga-3 text-h6"> {{ voteCard.name }}
<v-btn flat size="medium" @click="$emit('openEditVoteModal', voteCard)">
<v-icon color="orange-lighten-1">mdi-pencil</v-icon>
</v-btn>
</v-card-text>
<v-img cover :src="voteCard.pictures" />
<v-card-text class="text-body-1">{{ voteCard.description }}</v-card-text>
<TimerUI :endTime="voteCard.dateend" />
<v-card-actions class="justify-space-between">
<v-btn
v-if="!voteCard.is_passed"
color="teal-darken-4"
prepend-icon="mdi-vote-outline"
variant="outlined"
rounded="xl"
size="medium"
class="pa-2"
@click="$emit('openVoteModal', voteCard)">
Проголосовать
</v-btn>
<v-btn v-else color="teal-darken-4" disabled size="medium">Уже проголосовали</v-btn>
<v-btn color="error" @click="$emit('deleteVoting', voteCard.id)" size="medium">
<v-icon>mdi-delete</v-icon>
</v-btn>
</v-card-actions>
</v-card>
</template>
<script>
import TimerUI from '../secret/TimerUI.vue';
export default {
components: { TimerUI },
emits: ['openVoteModal', 'openEditVoteModal', 'deleteVoting'],
props: {
voteCard: {
type: Object,
default: () => {
return {
id: 0,
name: "Допустим, здесь могла быть ваша реклама",
description: "Но таких денег у вас нет, чтобы получить ее на нашем прекрасном голосовании",
pictures: "https://cdn.vuetifyjs.com/images/parallax/material.jpg",
dateend: new Date(new Date().getTime() + 600000),
is_passed: false,
}
}
}
}
}
</script>
@@ -25,8 +25,18 @@
<v-card flat>
<v-card-title>Основная информация</v-card-title>
<v-card-text>
<v-text-field v-model="form.title" label="Название голосования" outlined></v-text-field>
<v-textarea v-model="form.description" label="Описание" outlined></v-textarea>
<v-text-field
v-model="form.title"
label="Название голосования"
outlined
:rules="[rules.required]"
></v-text-field>
<v-textarea
v-model="form.description"
label="Описание"
outlined
:rules="[rules.required]"
></v-textarea>
<v-text-field
:placeholder="form.startDate.toLocaleDateString()"
:value="form.startDate.toLocaleDateString()"
@@ -87,6 +97,7 @@
v-model="question.text"
:label="'Вопрос ' + (index + 1)"
outlined
:rules="[rules.required]"
></v-text-field>
<v-file-input
v-model="question.image"
@@ -142,6 +153,7 @@
:label="'Ответ ' + (index + 1)"
class="mr-4"
outlined
:rules="[rules.required]"
></v-text-field>
<v-file-input
v-model="answer.image"
@@ -238,6 +250,9 @@
<v-btn color="teal-darken-4" size="medium" @click="step -= 1">Назад</v-btn>
<v-btn color="teal-darken-4" size="medium" @click="saveVoting">Сохранить</v-btn>
</v-card-actions>
<v-alert v-if="errorMessage" type="error" class="mb-4">
{{ errorMessage }}
</v-alert>
</v-card>
</v-stepper-window-item>
@@ -249,10 +264,11 @@
<script>
import {computed, ref} from "vue";
import {createVote, getVotes} from "@/utils/axios-api";
import { createVote } from "@/utils/axios-api";
export default {
setup() {
emits: ['updating'],
setup(props, {emit}) {
const step = ref(0);
const isVoteCreated = ref(false);
const form = ref({
@@ -263,6 +279,10 @@ export default {
questions: [],
});
const rules = {
required: (value) => !!value || "Это поле обязательно для заполнения",
};
const currentQuestionIndex = ref(0);
const questionTypes = ["Ввести вручную", "Выбрать сотрудника"];
@@ -312,18 +332,18 @@ export default {
}
};
const errorMessage = ref("");
const saveVoting = async () => {
if (!form.value.title || !form.value.description || form.value.questions < 1) {
errorMessage.value = "Все обязательные поля должны быть заполнены";
return;
}
try {
const response = await createVote(form.value);
console.log("Голосование успешно создано:", response);
isVoteCreated.value = true;
getVotes('active')
.then(data => {
console.log('Активные голосования:', data);
})
.catch(err => {
console.error('Ошибка:', err);
});
emit('updating', 'active')
} catch (error) {
console.error("Ошибка при создании голосования:", error);
}
@@ -356,7 +376,9 @@ export default {
removeEmployee,
saveVoting,
isVoteCreated,
resetForm
resetForm,
rules,
errorMessage
};
},
};
+24
View File
@@ -152,6 +152,30 @@ const routes = [
component: () =>
import("@/views/VoteHomePage.vue")
},
{
path: "/vote/voting/:id",
name: "Voting",
component: () =>
import("@/views/VoteHomePage.vue")
},
{
path: "/vote/edit-vote/:id",
name: "EditVote",
component: () =>
import("@/views/VoteHomePage.vue")
},
{
path: "/vote/vote-results/:id",
name: "VoteResults",
component: () =>
import("@/views/VoteHomePage.vue")
},
{
path: '/secret',
name: 'Secret Page',
component: () =>
import("@/views/secret/SecretPage.vue")
}
],
},
];
-48
View File
@@ -1,48 +0,0 @@
export const votingData = {
description: "Описание первой голосовалки",
endDate: "2025-01-27T10:43:04+03:00",
questions: [
{
answers: [
{
text: "аыфавы",
image: null
},
{
text: "оаок5е",
image: null
}
],
image: {
name: "ed777ac1e74742aa118f59d72e231763d08ac93fv2_hq.jpg",
size: 11530
},
selectedEmployeeImages: {},
selectedEmployees: [],
text: "Опрос1",
type: "Ввести вручную"
},
{
answers: [],
image: {
name: "ed777ac1e74742aa118f59d72e231763d08ac93fv2_hq.jpg",
size: 11530
},
selectedEmployeeImages: {},
selectedEmployees: [
{
id: 1,
name: "Сотрудник 1"
},
{
id: 2,
name: "Сотрудник 2"
}
],
text: "Опрос2",
type: "Выбрать сотрудника"
}
],
startDate: "2025-01-13T10:43:04+03:00",
title: "Заголовок голосовалки"
}
+112 -63
View File
@@ -1,9 +1,10 @@
import {useAccountStore} from '@/store/AccountStore'
import axios from "axios";
const spravURL = 'http://10.252.44.33/accounting6/images/photo/'
const spravURLBase = 'http://10.252.44.33/accounting6/'
const baseURL = process.env.NODE_ENV === 'development'? 'http://127.0.0.1:8000/': `http://${window.location.host}/`;
const baseWS = process.env.NODE_ENV == 'development'? 'ws://127.0.0.1:8000/': `ws://${window.location.host}/`;
const baseURL = process.env.NODE_ENV === 'development' ? 'http://127.0.0.1:8000/' : `http://${window.location.host}/`;
const baseWS = process.env.NODE_ENV == 'development' ? 'ws://127.0.0.1:8000/' : `ws://${window.location.host}/`;
// const baseURL = process.env.NODE_ENV == 'development'? 'http://127.0.0.1:8000/': `http://10.252.44.60:9965/`;
// const baseWS = process.env.NODE_ENV == 'development'? 'ws://127.0.0.1:8000/': `ws://10.252.44.60:9966/`;
// для релизного меняем 'http://ukd/'
@@ -11,82 +12,76 @@ const baseWS = process.env.NODE_ENV == 'development'? 'ws://127.0.0.1:8000/': `w
async function refreshToken() {
const refresh = localStorage.getItem('refresh');
const refresh = localStorage.getItem('refresh');
try {
const result = await axios.post('/api/accounts/token/refresh/', {refresh}, {
baseURL
})
try {
const result = await axios.post('/api/accounts/token/refresh/', {refresh}, {
baseURL
})
if (result.config.data) localStorage.setItem('refresh', JSON.parse(result.config.data).refresh);
localStorage.setItem('access', result.data.access)
if (result.config.data) localStorage.setItem('refresh', JSON.parse(result.config.data).refresh);
localStorage.setItem('access', result.data.access)
return result.data.access;
}
return result.data.access;
} catch (e) {
const accountStore = useAccountStore()
accountStore.logout()
accountStore.cod2user.value = false
catch(e) {
const accountStore = useAccountStore()
accountStore.logout()
accountStore.cod2user.value=false
return Promise.reject(e);
}
return Promise.reject(e);
}
}
const axiosApiInstance = axios.create({
baseURL,
baseURL,
});
const clearAxios = axios.create({
baseURL,
baseURL,
});
axiosApiInstance.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('access')}`
axiosApiInstance.interceptors.request.use(config => {
const access = localStorage.getItem('access');
if (access) {
config.headers = {
'Authorization': `Bearer ${access}`,
}
const access = localStorage.getItem('access');
if (access) {
config.headers = {
'Authorization': `Bearer ${access}`,
}
return config;
}
return config;
}, error => {
return Promise.reject(error);
return Promise.reject(error);
})
axiosApiInstance.interceptors.response.use(
response => {
response => {
return response;
},
async error => {
},
async error => {
const originalRequest = error.config;
if ((error.response.status === 401 || error.response.status === 403) && !originalRequest._retry) {
originalRequest._retry = true;
try {
originalRequest._retry = true;
try {
const token = await refreshToken();
const token = await refreshToken();
axiosApiInstance.defaults.headers.common['Authorization'] = `Bearer ${token}`;
axiosApiInstance.defaults.headers.common['Authorization'] = `Bearer ${token}`;
if (originalRequest.data){
originalRequest.data = JSON.parse(originalRequest.data); }
return axiosApiInstance(originalRequest);
} catch(e) {
//
// if (window.location.pathname!='/auth') window.location.reload()
// window.location.reload()
return Promise.reject(error);
if (originalRequest.data) {
originalRequest.data = JSON.parse(originalRequest.data);
}
return axiosApiInstance(originalRequest);
} catch (e) {
return Promise.reject(error);
}
}
return Promise.reject(error);
})
})
async function getVotes(status) {
try {
@@ -98,21 +93,21 @@ async function getVotes(status) {
}
}
getVotes('completed')
.then(data => {
console.log('Завершённые голосования:', data);
})
.catch(err => {
console.error('Ошибка:', err);
});
// getVotes('completed')
// .then(data => {
// console.log('Завершённые голосования:', data);
// })
// .catch(err => {
// console.error('Ошибка:', err);
// });
getVotes('active')
.then(data => {
console.log('Активные голосования:', data);
})
.catch(err => {
console.error('Ошибка:', err);
});
// getVotes('active')
// .then(data => {
// console.log('Активные голосования:', data);
// })
// .catch(err => {
// console.error('Ошибка:', err);
// });
async function createVote(voteData, files) {
try {
@@ -125,7 +120,7 @@ async function createVote(voteData, files) {
formData.append('questions', JSON.stringify(voteData.questions));
const response = await axiosApiInstance.post('/api/vote/votecreate/', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
headers: {'Content-Type': 'multipart/form-data'},
});
return response.data;
@@ -135,4 +130,58 @@ async function createVote(voteData, files) {
}
}
export { axiosApiInstance, clearAxios, baseURL,spravURL, spravURLBase, baseWS, getVotes, createVote }
async function getVoteDetail(id) {
try {
const response = await axiosApiInstance.get(`/api/vote/votedetail/${id}/`);
return response.data;
} catch (error) {
console.error("Ошибка получения деталей голосования:", error);
throw error;
}
}
async function updateVote(id, updatedData) {
try {
const response = await axiosApiInstance.put(`/api/vote/votedetail/${id}/`, updatedData);
return response.data;
} catch (error) {
console.error("Ошибка обновления голосования:", error);
throw error;
}
}
async function patchVote(id, partialData) {
try {
const response = await axiosApiInstance.patch(`/api/vote/votedetail/${id}/`, partialData);
return response.data;
} catch (error) {
console.error("Ошибка частичного обновления голосования:", error);
throw error;
}
}
async function deleteVote(id) {
try {
await axiosApiInstance.delete(`/api/vote/votedetail/${id}/`);
console.log("Голосование успешно удалено");
} catch (error) {
console.error("Ошибка удаления голосования:", error);
throw error;
}
}
export {
axiosApiInstance,
clearAxios,
baseURL,
spravURL,
spravURLBase,
baseWS,
getVotes,
createVote,
getVoteDetail,
updateVote,
patchVote,
deleteVote
}
+113 -140
View File
@@ -2,12 +2,11 @@
<v-container>
<v-toolbar color="transparent">
<v-toolbar-title>Голосования</v-toolbar-title>
<template v-slot:extension>
<v-tabs v-model="currentTab">
<v-tab :key="0" value="current">Текущие голосования</v-tab>
<v-tab :key="1" value="completed">Завершенные голосования</v-tab>
<v-tab :key="2" value="constructor">Создать новое голосование</v-tab>
<v-tab value="current">Текущие голосования</v-tab>
<v-tab value="completed">Завершенные голосования</v-tab>
<v-tab value="constructor">Создать новое голосование</v-tab>
</v-tabs>
</template>
</v-toolbar>
@@ -20,35 +19,16 @@
<v-col
v-for="voting in sortedCurrentVotes"
:key="voting.id"
cols="12" lg="3" md="4"
cols="12"
lg="3"
md="4"
>
<v-card :class="{ 'voted-card': voting.voted }">
<v-card-title class="d-flex justify-space-between">{{ voting.title }}
<v-btn flat size="medium" @click="openEditVoteModal(voting)">
<v-icon color="orange-lighten-1">mdi-pencil</v-icon>
</v-btn>
</v-card-title>
<v-card-subtitle>
Окончание: {{ formatDate(voting.endDate) }}
</v-card-subtitle>
<v-card-text>
Осталось: {{ timeRemaining(voting.endDate) }}
</v-card-text>
<v-card-actions class="justify-space-between">
<v-btn
v-if="!voting.voted"
color="teal-darken-4"
size="medium"
@click="openVoteModal(voting)"
>
Проголосовать
</v-btn>
<v-btn v-else color="teal-darken-4" disabled size="medium">Проголосовали</v-btn>
<v-btn color="error" size="medium" @click="deleteVoting(voting.id)">
<v-icon>mdi-delete</v-icon>
</v-btn>
</v-card-actions>
</v-card>
<VoteCardVue
:voteCard="voting"
@openVoteModal="(voting) => openModal('vote', voting)"
@openEditVoteModal="(voting) => openModal('edit', voting)"
@deleteVoting="deleteVoting"
/>
</v-col>
</v-row>
</v-container>
@@ -61,7 +41,10 @@
<v-col
v-for="voting in sortedCompletedVotes"
:key="voting.id"
cols="12" lg="3" md="4"
cols="12"
lg="3"
md="4"
:class="{ 'voted-card': voting.voted }"
>
<v-card>
<v-card-title>{{ voting.title }}</v-card-title>
@@ -69,7 +52,7 @@
Завершено: {{ formatDate(voting.endDate) }}
</v-card-subtitle>
<v-card-actions class="justify-space-between">
<v-btn color="teal-darken-4" size="medium" @click="openResultsModal(voting)">
<v-btn color="teal-darken-4" size="medium" @click="(voting) => openModal('results', voting)">
Результаты
</v-btn>
<v-btn color="error" size="medium" @click="deleteVoting(voting.id)">
@@ -84,55 +67,45 @@
<!-- Конструктор -->
<v-tabs-window-item value="constructor">
<VoteConstructor/>
<VoteConstructor @updating="updating" />
</v-tabs-window-item>
</v-tabs-window>
<!-- Модальное окно для голосования -->
<v-dialog v-model="voteModal" max-width="1200px">
<!-- Модальные окна -->
<v-dialog v-model="voteModal" max-width="1200px" @click:outside="closeModal">
<v-card>
<v-card-actions>
<!--<v-btn color="teal-darken-4" @click="submitVote">Проголосовать</v-btn>-->
<v-btn color="red-darken-1" size="medium" @click="closeVoteModal">
<v-btn color="red-darken-1" size="medium" @click="closeModal">
<v-icon>mdi-close-thick</v-icon>
</v-btn>
</v-card-actions>
<v-card-text class="pt-0">
<CurrentVote
:description="votingData.description"
:endDate="votingData.endDate"
:questions="votingData.questions"
:startDate="votingData.startDate"
:title="votingData.title"
/>
<CurrentVote :data="res" />
</v-card-text>
</v-card>
</v-dialog>
<!-- Модальное окно для редактирования -->
<v-dialog v-model="editVoteModal" max-width="1200px">
<v-dialog v-model="editVoteModal" max-width="1200px" @click:outside="closeModal">
<v-card>
<v-card-title>Голосование: {{ selectedVoting?.title }}</v-card-title>
<v-card-title>Редактировать голосование: {{ selectedVoting?.title }}</v-card-title>
<v-card-text>
<!-- <p>Редактирование голосования...</p> -->
<VoteConstructor/>
<VoteConstructor />
</v-card-text>
<v-card-actions>
<v-btn color="teal-darken-4">Сохранить</v-btn>
<v-btn @click="closeEditVoteModal">Закрыть</v-btn>
<v-btn @click="closeModal">Закрыть</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<!-- Модальное окно для результатов -->
<v-dialog v-model="resultsModal" max-width="1200px">
<v-dialog v-model="resultsModal" max-width="1200px" @click:outside="closeModal">
<v-card>
<v-card-title>Результаты голосования: {{ selectedVoting?.title }}</v-card-title>
<v-card-text>
<p>Здесь отображаются результаты голосования...</p>
</v-card-text>
<v-card-actions>
<v-btn @click="closeResultsModal">Закрыть</v-btn>
<v-btn @click="closeModal">Закрыть</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
@@ -140,124 +113,124 @@
</template>
<script>
import {computed, ref} from "vue";
import { ref, computed, watch } from "vue";
import VoteConstructor from "@/components/vote/VoteConstructor.vue";
import CurrentVote from "@/components/vote/CurrentVote.vue";
import {votingData} from '@/test/testDataForVote'
import VoteCardVue from "@/components/vote/VoteCard.vue";
import { useRoute, useRouter } from "vue-router";
import { deleteVote, getVoteDetail, getVotes } from "@/utils/axios-api";
import { formatDate } from "@vueuse/shared";
export default {
computed: {
votingData() {
return votingData
}
},
components: {CurrentVote, VoteConstructor},
methods: { formatDate },
components: { CurrentVote, VoteConstructor, VoteCardVue },
setup() {
const currentTab = ref("current");
const votes = ref([
{
id: 1,
title: "Голосование 1",
endDate: new Date(new Date().getTime() + 600000), // 10 минут
voted: false,
},
{
id: 2,
title: "Голосование 2",
endDate: new Date(new Date().getTime() - 600000), // Уже завершено
voted: true,
},
{
id: 3,
title: "Голосование 3",
endDate: new Date(new Date().getTime() + 3600000), // 1 час
voted: true,
},
]);
const votes = ref([]);
const router = useRouter();
const route = useRoute();
const res = ref(null);
const updating = async (param) => {
const data = await getVotes(param);
votes.value = data;
};
updating("active");
const voteModal = ref(false);
const editVoteModal = ref(false);
const resultsModal = ref(false);
const selectedVoting = ref(null);
const sortedCurrentVotes = computed(() => {
return votes.value
.filter((v) => new Date(v.endDate) > new Date())
.sort((a, b) => new Date(a.endDate) - new Date(b.endDate));
});
const sortedCurrentVotes = computed(() =>
votes.value
.filter((v) => new Date(v.dateend) > new Date())
.sort((a, b) => new Date(a.dateend) - new Date(b.dateend))
);
const sortedCompletedVotes = computed(() => {
return votes.value
.filter((v) => new Date(v.endDate) <= new Date())
.sort((a, b) => new Date(b.endDate) - new Date(a.endDate));
});
const sortedCompletedVotes = computed(() =>
votes.value
.filter((v) => new Date(v.dateend) <= new Date())
.sort((a, b) => new Date(b.dateend) - new Date(a.dateend))
);
const timeRemaining = (endDate) => {
const now = new Date();
const diff = new Date(endDate) - now;
return diff > 0 ? `${Math.floor(diff / 60000)} минут` : "Завершено";
const loadVoteDetails = async (id) => {
try {
const data = await getVoteDetail(id);
res.value = data;
} catch (error) {
console.error("Ошибка при загрузке данных голосования:", error);
res.value = null;
}
};
const formatDate = (date) => new Date(date).toLocaleString();
const openVoteModal = (voting) => {
selectedVoting.value = voting;
voteModal.value = true;
};
const closeVoteModal = () => {
const closeModal = () => {
voteModal.value = false;
selectedVoting.value = null;
};
const openEditVoteModal = (voting) => {
selectedVoting.value = voting;
editVoteModal.value = true;
};
const closeEditVoteModal = () => {
editVoteModal.value = false;
selectedVoting.value = null;
};
const submitVote = () => {
selectedVoting.value.voted = true;
closeVoteModal();
};
const openResultsModal = (voting) => {
selectedVoting.value = voting;
resultsModal.value = true;
};
const closeResultsModal = () => {
resultsModal.value = false;
selectedVoting.value = null;
router.push({ name: "VoteHomePage" });
};
const deleteVoting = (id) => {
votes.value = votes.value.filter((v) => v.id !== id);
const openModal = async (type, voting) => {
selectedVoting.value = voting;
if (type === "vote") {
await loadVoteDetails(voting.id);
voteModal.value = true;
router.push({ name: "Voting", params: { id: voting.id } });
} else if (type === "edit") {
editVoteModal.value = true;
router.push({ name: "EditVote", params: { id: voting.id } });
} else if (type === "results") {
resultsModal.value = true;
router.push({ name: "VoteResults", params: { id: voting.id } });
}
};
const deleteVoting = async (id) => {
try {
await deleteVote(id);
votes.value = votes.value.filter((v) => v.id !== id);
} catch (error) {
console.error("Ошибка при удалении голосования:", error);
}
};
watch(
() => route,
async () => {
if (!voteModal.value && !editVoteModal.value && !resultsModal.value) {
const voting = votes.value.find((v) => v.id === route.params.id);
if (route.name === "Voting") {
await loadVoteDetails(route.params.id);
voteModal.value = true;
}
if (route.name === "EditVote") editVoteModal.value = true;
if (route.name === "VoteResults") resultsModal.value = true;
selectedVoting.value = voting || null;
}
},
{ immediate: true }
);
updating("active");
return {
currentTab,
votes,
sortedCurrentVotes,
sortedCompletedVotes,
voteModal,
editVoteModal,
resultsModal,
selectedVoting,
timeRemaining,
formatDate,
openVoteModal,
closeVoteModal,
submitVote,
openResultsModal,
closeResultsModal,
openModal,
closeModal,
deleteVoting,
editVoteModal,
openEditVoteModal,
closeEditVoteModal,
updating,
res,
};
},
};
+28
View File
@@ -0,0 +1,28 @@
<template>
<!-- <v-container>
<TimerUI :endTime="end" />
<SmallTimer :endTime="end"/>
</v-container> -->
<VoteCard />
</template>
<script>
// import TimerUI from "@/components/secret/TimerUI.vue"
// import SmallTimer from "@/components/secret/SmallTimer.vue"
import VoteCard from "@/components/vote/VoteCard.vue"
export default {
components: {
// TimerUI,
// SmallTimer,
VoteCard
},
setup() {
// const end = new Date(2025, 0, 14, 15, 58, 5)
return {
// end
}
}
}
</script>