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): def get(self, request):
user = request.user user = request.user
print(type(user))
# user = User.objects.get(username='9966-00-125') # user = User.objects.get(username='9966-00-125')
now = datetime.now() now = datetime.now()
status = request.query_params.get('status') 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>
<template v-if="!isVoteSubmitted"> <template v-if="!isVoteSubmitted">
<!-- Заголовок голосовалки --> <v-stepper v-model="activeStep">
<v-row class="pt-0"> <v-card-title>{{ data.name }}</v-card-title>
<v-col cols="12"> <v-card-subtitle>{{ data.description }}</v-card-subtitle>
<v-card flat>
<v-card-title>{{ title }}</v-card-title>
<v-card-subtitle>{{ description }}</v-card-subtitle>
</v-card>
</v-col>
</v-row>
<!-- Ожидаемая дата окончания голосования --> <!-- Шаги голосования -->
<v-row> <v-stepper-header>
<v-col cols="12"> <v-stepper-item
<v-chip :color="isVotingActive ? 'green' : 'red'"> v-for="(question, index) in data.questions"
<v-icon>{{ isVotingActive ? 'mdi-check-circle' : 'mdi-clock' }}</v-icon>&nbsp; :key="index"
{{ isVotingActive ? 'Голосование активно' : `Голосование закончится: ${endDateFormatted}` }} :complete="index < activeStep"
</v-chip> :step="index + 1"
</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"
> >
Отправить голос Вопрос {{ index + 1 }}
</v-btn> </v-stepper-item>
</v-col> </v-stepper-header>
</v-row>
<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> </template>
<!-- Спасибо за голос --> <!-- Спасибо за голос -->
@@ -87,84 +78,64 @@
</template> </template>
<script> <script>
import {computed, ref} from "vue"; import { computed, ref } from "vue";
export default { export default {
props: { props: {
description: String, data: {
endDate: String, type: Object,
questions: Array, required: true,
startDate: String, default: () => ({}),
title: String, },
}, },
setup(props, {emit}) { setup(props, { emit }) {
// Ответы на вопросы const activeStep = ref(0);
const answers = ref([]); const answers = ref(props.data.questions.map(() => null));
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;
});
});
// Состояние для определения отправки голоса
const isVoteSubmitted = ref(false); 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 submitVote = () => {
const voteData = props.questions.map((question, index) => ({ const voteData = props.data.questions.map((question, index) => ({
question: question.text, question: question.question,
type: question.type, answer: answers.value[index],
answer:
question.type === "Ввести вручную"
? answers.value[index]
: selectedEmployees.value[index],
})); }));
console.log("Отправляем данные голосования:", voteData); console.log("Отправляем данные голосования:", voteData);
// После успешной отправки
isVoteSubmitted.value = true; isVoteSubmitted.value = true;
emit("submit", voteData); emit("submit", voteData);
}; };
return { return {
activeStep,
answers, answers,
selectedEmployees, isCurrentQuestionAnswered,
endDateFormatted, nextStep,
isVotingActive, prevStep,
isVoteSubmitted,
isAllQuestionsAnswered,
submitVote, submitVote,
isVoteSubmitted,
}; };
}, },
}; };
</script> </script>
<style> <style>
.v-label { .v-label {
color: #000 !important; color: #000 !important;
opacity: 1 !important; opacity: 1 !important;
} }
</style> </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 flat>
<v-card-title>Основная информация</v-card-title> <v-card-title>Основная информация</v-card-title>
<v-card-text> <v-card-text>
<v-text-field v-model="form.title" label="Название голосования" outlined></v-text-field> <v-text-field
<v-textarea v-model="form.description" label="Описание" outlined></v-textarea> 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 <v-text-field
:placeholder="form.startDate.toLocaleDateString()" :placeholder="form.startDate.toLocaleDateString()"
:value="form.startDate.toLocaleDateString()" :value="form.startDate.toLocaleDateString()"
@@ -87,6 +97,7 @@
v-model="question.text" v-model="question.text"
:label="'Вопрос ' + (index + 1)" :label="'Вопрос ' + (index + 1)"
outlined outlined
:rules="[rules.required]"
></v-text-field> ></v-text-field>
<v-file-input <v-file-input
v-model="question.image" v-model="question.image"
@@ -142,6 +153,7 @@
:label="'Ответ ' + (index + 1)" :label="'Ответ ' + (index + 1)"
class="mr-4" class="mr-4"
outlined outlined
:rules="[rules.required]"
></v-text-field> ></v-text-field>
<v-file-input <v-file-input
v-model="answer.image" 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="step -= 1">Назад</v-btn>
<v-btn color="teal-darken-4" size="medium" @click="saveVoting">Сохранить</v-btn> <v-btn color="teal-darken-4" size="medium" @click="saveVoting">Сохранить</v-btn>
</v-card-actions> </v-card-actions>
<v-alert v-if="errorMessage" type="error" class="mb-4">
{{ errorMessage }}
</v-alert>
</v-card> </v-card>
</v-stepper-window-item> </v-stepper-window-item>
@@ -249,10 +264,11 @@
<script> <script>
import {computed, ref} from "vue"; import {computed, ref} from "vue";
import {createVote, getVotes} from "@/utils/axios-api"; import { createVote } from "@/utils/axios-api";
export default { export default {
setup() { emits: ['updating'],
setup(props, {emit}) {
const step = ref(0); const step = ref(0);
const isVoteCreated = ref(false); const isVoteCreated = ref(false);
const form = ref({ const form = ref({
@@ -263,6 +279,10 @@ export default {
questions: [], questions: [],
}); });
const rules = {
required: (value) => !!value || "Это поле обязательно для заполнения",
};
const currentQuestionIndex = ref(0); const currentQuestionIndex = ref(0);
const questionTypes = ["Ввести вручную", "Выбрать сотрудника"]; const questionTypes = ["Ввести вручную", "Выбрать сотрудника"];
@@ -312,18 +332,18 @@ export default {
} }
}; };
const errorMessage = ref("");
const saveVoting = async () => { const saveVoting = async () => {
if (!form.value.title || !form.value.description || form.value.questions < 1) {
errorMessage.value = "Все обязательные поля должны быть заполнены";
return;
}
try { try {
const response = await createVote(form.value); const response = await createVote(form.value);
console.log("Голосование успешно создано:", response); console.log("Голосование успешно создано:", response);
isVoteCreated.value = true; isVoteCreated.value = true;
getVotes('active') emit('updating', 'active')
.then(data => {
console.log('Активные голосования:', data);
})
.catch(err => {
console.error('Ошибка:', err);
});
} catch (error) { } catch (error) {
console.error("Ошибка при создании голосования:", error); console.error("Ошибка при создании голосования:", error);
} }
@@ -356,7 +376,9 @@ export default {
removeEmployee, removeEmployee,
saveVoting, saveVoting,
isVoteCreated, isVoteCreated,
resetForm resetForm,
rules,
errorMessage
}; };
}, },
}; };
+24
View File
@@ -152,6 +152,30 @@ const routes = [
component: () => component: () =>
import("@/views/VoteHomePage.vue") 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 {useAccountStore} from '@/store/AccountStore'
import axios from "axios"; import axios from "axios";
const spravURL = 'http://10.252.44.33/accounting6/images/photo/' const spravURL = 'http://10.252.44.33/accounting6/images/photo/'
const spravURLBase = 'http://10.252.44.33/accounting6/' 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 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 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 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/`; // const baseWS = process.env.NODE_ENV == 'development'? 'ws://127.0.0.1:8000/': `ws://10.252.44.60:9966/`;
// для релизного меняем 'http://ukd/' // для релизного меняем 'http://ukd/'
@@ -11,82 +12,76 @@ const baseWS = process.env.NODE_ENV == 'development'? 'ws://127.0.0.1:8000/': `w
async function refreshToken() { async function refreshToken() {
const refresh = localStorage.getItem('refresh'); const refresh = localStorage.getItem('refresh');
try { try {
const result = await axios.post('/api/accounts/token/refresh/', {refresh}, { const result = await axios.post('/api/accounts/token/refresh/', {refresh}, {
baseURL baseURL
}) })
if (result.config.data) localStorage.setItem('refresh', JSON.parse(result.config.data).refresh); if (result.config.data) localStorage.setItem('refresh', JSON.parse(result.config.data).refresh);
localStorage.setItem('access', result.data.access) 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) { return Promise.reject(e);
const accountStore = useAccountStore() }
accountStore.logout()
accountStore.cod2user.value=false
return Promise.reject(e);
}
} }
const axiosApiInstance = axios.create({ const axiosApiInstance = axios.create({
baseURL, baseURL,
}); });
const clearAxios = axios.create({ const clearAxios = axios.create({
baseURL, baseURL,
}); });
axiosApiInstance.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('access')}` axiosApiInstance.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('access')}`
axiosApiInstance.interceptors.request.use(config => { axiosApiInstance.interceptors.request.use(config => {
const access = localStorage.getItem('access'); const access = localStorage.getItem('access');
if (access) { if (access) {
config.headers = { config.headers = {
'Authorization': `Bearer ${access}`, 'Authorization': `Bearer ${access}`,
}
} }
return config; }
return config;
}, error => { }, error => {
return Promise.reject(error); return Promise.reject(error);
}) })
axiosApiInstance.interceptors.response.use( axiosApiInstance.interceptors.response.use(
response => { response => {
return response; return response;
}, },
async error => { async error => {
const originalRequest = error.config; const originalRequest = error.config;
if ((error.response.status === 401 || error.response.status === 403) && !originalRequest._retry) { if ((error.response.status === 401 || error.response.status === 403) && !originalRequest._retry) {
originalRequest._retry = true; originalRequest._retry = true;
try { 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){ if (originalRequest.data) {
originalRequest.data = JSON.parse(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);
} }
return axiosApiInstance(originalRequest);
} catch (e) {
return Promise.reject(error);
}
} }
return Promise.reject(error); return Promise.reject(error);
}) })
async function getVotes(status) { async function getVotes(status) {
try { try {
@@ -98,21 +93,21 @@ async function getVotes(status) {
} }
} }
getVotes('completed') // getVotes('completed')
.then(data => { // .then(data => {
console.log('Завершённые голосования:', data); // console.log('Завершённые голосования:', data);
}) // })
.catch(err => { // .catch(err => {
console.error('Ошибка:', err); // console.error('Ошибка:', err);
}); // });
getVotes('active') // getVotes('active')
.then(data => { // .then(data => {
console.log('Активные голосования:', data); // console.log('Активные голосования:', data);
}) // })
.catch(err => { // .catch(err => {
console.error('Ошибка:', err); // console.error('Ошибка:', err);
}); // });
async function createVote(voteData, files) { async function createVote(voteData, files) {
try { try {
@@ -125,7 +120,7 @@ async function createVote(voteData, files) {
formData.append('questions', JSON.stringify(voteData.questions)); formData.append('questions', JSON.stringify(voteData.questions));
const response = await axiosApiInstance.post('/api/vote/votecreate/', formData, { const response = await axiosApiInstance.post('/api/vote/votecreate/', formData, {
headers: { 'Content-Type': 'multipart/form-data' }, headers: {'Content-Type': 'multipart/form-data'},
}); });
return response.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-container>
<v-toolbar color="transparent"> <v-toolbar color="transparent">
<v-toolbar-title>Голосования</v-toolbar-title> <v-toolbar-title>Голосования</v-toolbar-title>
<template v-slot:extension> <template v-slot:extension>
<v-tabs v-model="currentTab"> <v-tabs v-model="currentTab">
<v-tab :key="0" value="current">Текущие голосования</v-tab> <v-tab value="current">Текущие голосования</v-tab>
<v-tab :key="1" value="completed">Завершенные голосования</v-tab> <v-tab value="completed">Завершенные голосования</v-tab>
<v-tab :key="2" value="constructor">Создать новое голосование</v-tab> <v-tab value="constructor">Создать новое голосование</v-tab>
</v-tabs> </v-tabs>
</template> </template>
</v-toolbar> </v-toolbar>
@@ -20,35 +19,16 @@
<v-col <v-col
v-for="voting in sortedCurrentVotes" v-for="voting in sortedCurrentVotes"
:key="voting.id" :key="voting.id"
cols="12" lg="3" md="4" cols="12"
lg="3"
md="4"
> >
<v-card :class="{ 'voted-card': voting.voted }"> <VoteCardVue
<v-card-title class="d-flex justify-space-between">{{ voting.title }} :voteCard="voting"
<v-btn flat size="medium" @click="openEditVoteModal(voting)"> @openVoteModal="(voting) => openModal('vote', voting)"
<v-icon color="orange-lighten-1">mdi-pencil</v-icon> @openEditVoteModal="(voting) => openModal('edit', voting)"
</v-btn> @deleteVoting="deleteVoting"
</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>
</v-col> </v-col>
</v-row> </v-row>
</v-container> </v-container>
@@ -61,7 +41,10 @@
<v-col <v-col
v-for="voting in sortedCompletedVotes" v-for="voting in sortedCompletedVotes"
:key="voting.id" :key="voting.id"
cols="12" lg="3" md="4" cols="12"
lg="3"
md="4"
:class="{ 'voted-card': voting.voted }"
> >
<v-card> <v-card>
<v-card-title>{{ voting.title }}</v-card-title> <v-card-title>{{ voting.title }}</v-card-title>
@@ -69,7 +52,7 @@
Завершено: {{ formatDate(voting.endDate) }} Завершено: {{ formatDate(voting.endDate) }}
</v-card-subtitle> </v-card-subtitle>
<v-card-actions class="justify-space-between"> <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>
<v-btn color="error" size="medium" @click="deleteVoting(voting.id)"> <v-btn color="error" size="medium" @click="deleteVoting(voting.id)">
@@ -84,55 +67,45 @@
<!-- Конструктор --> <!-- Конструктор -->
<v-tabs-window-item value="constructor"> <v-tabs-window-item value="constructor">
<VoteConstructor/> <VoteConstructor @updating="updating" />
</v-tabs-window-item> </v-tabs-window-item>
</v-tabs-window> </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>
<v-card-actions> <v-card-actions>
<!--<v-btn color="teal-darken-4" @click="submitVote">Проголосовать</v-btn>--> <v-btn color="red-darken-1" size="medium" @click="closeModal">
<v-btn color="red-darken-1" size="medium" @click="closeVoteModal">
<v-icon>mdi-close-thick</v-icon> <v-icon>mdi-close-thick</v-icon>
</v-btn> </v-btn>
</v-card-actions> </v-card-actions>
<v-card-text class="pt-0"> <v-card-text class="pt-0">
<CurrentVote <CurrentVote :data="res" />
:description="votingData.description"
:endDate="votingData.endDate"
:questions="votingData.questions"
:startDate="votingData.startDate"
:title="votingData.title"
/>
</v-card-text> </v-card-text>
</v-card> </v-card>
</v-dialog> </v-dialog>
<!-- Модальное окно для редактирования --> <v-dialog v-model="editVoteModal" max-width="1200px" @click:outside="closeModal">
<v-dialog v-model="editVoteModal" max-width="1200px">
<v-card> <v-card>
<v-card-title>Голосование: {{ selectedVoting?.title }}</v-card-title> <v-card-title>Редактировать голосование: {{ selectedVoting?.title }}</v-card-title>
<v-card-text> <v-card-text>
<!-- <p>Редактирование голосования...</p> --> <VoteConstructor />
<VoteConstructor/>
</v-card-text> </v-card-text>
<v-card-actions> <v-card-actions>
<v-btn color="teal-darken-4">Сохранить</v-btn> <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-actions>
</v-card> </v-card>
</v-dialog> </v-dialog>
<!-- Модальное окно для результатов --> <v-dialog v-model="resultsModal" max-width="1200px" @click:outside="closeModal">
<v-dialog v-model="resultsModal" max-width="1200px">
<v-card> <v-card>
<v-card-title>Результаты голосования: {{ selectedVoting?.title }}</v-card-title> <v-card-title>Результаты голосования: {{ selectedVoting?.title }}</v-card-title>
<v-card-text> <v-card-text>
<p>Здесь отображаются результаты голосования...</p> <p>Здесь отображаются результаты голосования...</p>
</v-card-text> </v-card-text>
<v-card-actions> <v-card-actions>
<v-btn @click="closeResultsModal">Закрыть</v-btn> <v-btn @click="closeModal">Закрыть</v-btn>
</v-card-actions> </v-card-actions>
</v-card> </v-card>
</v-dialog> </v-dialog>
@@ -140,124 +113,124 @@
</template> </template>
<script> <script>
import {computed, ref} from "vue"; import { ref, computed, watch } from "vue";
import VoteConstructor from "@/components/vote/VoteConstructor.vue"; import VoteConstructor from "@/components/vote/VoteConstructor.vue";
import CurrentVote from "@/components/vote/CurrentVote.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 { export default {
computed: { methods: { formatDate },
votingData() { components: { CurrentVote, VoteConstructor, VoteCardVue },
return votingData
}
},
components: {CurrentVote, VoteConstructor},
setup() { setup() {
const currentTab = ref("current"); const currentTab = ref("current");
const votes = ref([ const votes = ref([]);
{ const router = useRouter();
id: 1, const route = useRoute();
title: "Голосование 1", const res = ref(null);
endDate: new Date(new Date().getTime() + 600000), // 10 минут
voted: false, const updating = async (param) => {
}, const data = await getVotes(param);
{ votes.value = data;
id: 2, };
title: "Голосование 2",
endDate: new Date(new Date().getTime() - 600000), // Уже завершено updating("active");
voted: true,
},
{
id: 3,
title: "Голосование 3",
endDate: new Date(new Date().getTime() + 3600000), // 1 час
voted: true,
},
]);
const voteModal = ref(false); const voteModal = ref(false);
const editVoteModal = ref(false); const editVoteModal = ref(false);
const resultsModal = ref(false); const resultsModal = ref(false);
const selectedVoting = ref(null); const selectedVoting = ref(null);
const sortedCurrentVotes = computed(() => { const sortedCurrentVotes = computed(() =>
return votes.value votes.value
.filter((v) => new Date(v.endDate) > new Date()) .filter((v) => new Date(v.dateend) > new Date())
.sort((a, b) => new Date(a.endDate) - new Date(b.endDate)); .sort((a, b) => new Date(a.dateend) - new Date(b.dateend))
}); );
const sortedCompletedVotes = computed(() => { const sortedCompletedVotes = computed(() =>
return votes.value votes.value
.filter((v) => new Date(v.endDate) <= new Date()) .filter((v) => new Date(v.dateend) <= new Date())
.sort((a, b) => new Date(b.endDate) - new Date(a.endDate)); .sort((a, b) => new Date(b.dateend) - new Date(a.dateend))
}); );
const timeRemaining = (endDate) => { const loadVoteDetails = async (id) => {
const now = new Date(); try {
const diff = new Date(endDate) - now; const data = await getVoteDetail(id);
return diff > 0 ? `${Math.floor(diff / 60000)} минут` : "Завершено"; res.value = data;
} catch (error) {
console.error("Ошибка при загрузке данных голосования:", error);
res.value = null;
}
}; };
const formatDate = (date) => new Date(date).toLocaleString(); const closeModal = () => {
const openVoteModal = (voting) => {
selectedVoting.value = voting;
voteModal.value = true;
};
const closeVoteModal = () => {
voteModal.value = false; voteModal.value = false;
selectedVoting.value = null;
};
const openEditVoteModal = (voting) => {
selectedVoting.value = voting;
editVoteModal.value = true;
};
const closeEditVoteModal = () => {
editVoteModal.value = false; 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; resultsModal.value = false;
selectedVoting.value = null; selectedVoting.value = null;
router.push({ name: "VoteHomePage" });
}; };
const deleteVoting = (id) => { const openModal = async (type, voting) => {
votes.value = votes.value.filter((v) => v.id !== id); 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 { return {
currentTab, currentTab,
votes, votes,
sortedCurrentVotes, sortedCurrentVotes,
sortedCompletedVotes, sortedCompletedVotes,
voteModal, voteModal,
editVoteModal,
resultsModal, resultsModal,
selectedVoting, selectedVoting,
timeRemaining, openModal,
formatDate, closeModal,
openVoteModal,
closeVoteModal,
submitVote,
openResultsModal,
closeResultsModal,
deleteVoting, deleteVoting,
editVoteModal, updating,
openEditVoteModal, res,
closeEditVoteModal,
}; };
}, },
}; };
+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>