P-92 добавление, удаление и открытие конкретных голосовалок

This commit is contained in:
Denzel committed 2025-01-14 16:51:09 +03:00
1 parent 135c5fb87d
commit 5ec31af7c0
4 files changed
+174 -191

No files matched your search

+44 -70
View File
@@ -1,72 +1,61 @@
<template>
<template v-if="!isVoteSubmitted">
<v-stepper v-model="activeStep" editable>
<v-card-title>{{ title }}</v-card-title>
<v-card-subtitle>{{ description }}</v-card-subtitle>
<!-- Заголовок -->
<v-stepper v-model="activeStep">
<v-card-title>{{ data.name }}</v-card-title>
<v-card-subtitle>{{ data.description }}</v-card-subtitle>
<!-- Шаги голосования -->
<v-stepper-header>
<v-stepper-item
v-for="(question, index) in questions"
:key="index"
:complete="index < activeStep"
:step="index + 1"
v-for="(question, index) in data.questions"
:key="index"
:complete="index < activeStep"
:step="index + 1"
>
Вопрос {{ index + 1 }}
</v-stepper-item>
</v-stepper-header>
<v-stepper-window>
<v-stepper-window-item v-for="(question, index) in questions" :key="index" :step="index + 1">
<v-stepper-window-item
v-for="(question, index) in data.questions"
:key="index"
:step="index + 1"
>
<v-card flat>
<v-card-title>{{ question.text }}</v-card-title>
<!-- Вопросы с типом "Ввести вручную" -->
<v-card-text v-if="question.type === 'Ввести вручную'">
<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.text"
color="teal-darken-4"
hide-details
v-model="answers[index]"
:value="answer.answer"
color="teal-darken-4"
hide-details
>
<template #label>
<span class="text-black">{{ 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"
hide-details
>
<template #label>
<span class="text-black">{{ employee.name }}</span>
<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 < questions.length - 1"
:disabled="!isCurrentQuestionAnswered"
@click="nextStep"
color="teal-darken-4"
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-else
:disabled="!isCurrentQuestionAnswered"
color="teal-darken-4"
@click="submitVote"
>
Отправить
</v-btn>
@@ -87,36 +76,29 @@
</v-row>
</template>
</template>
<script>
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 activeStep = ref(0);
const answers = ref([]);
const selectedEmployees = ref(props.questions.map(() => []));
const answers = ref(props.data.questions.map(() => null));
const isVoteSubmitted = ref(false);
const isCurrentQuestionAnswered = computed(() => {
const currentQuestion = props.questions[activeStep.value];
if (currentQuestion.type === "Ввести вручную") {
return !!answers.value[activeStep.value];
}
if (currentQuestion.type === "Выбрать сотрудника") {
return selectedEmployees.value[activeStep.value].length > 0;
}
return false;
return !!answers.value[activeStep.value];
});
const nextStep = () => {
if (activeStep.value < props.questions.length - 1) {
if (activeStep.value < props.data.questions.length - 1) {
activeStep.value++;
}
};
@@ -128,13 +110,9 @@ export default {
};
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);
@@ -145,23 +123,19 @@ export default {
return {
activeStep,
answers,
selectedEmployees,
isCurrentQuestionAnswered,
nextStep,
prevStep,
submitVote,
isVoteSubmitted
isVoteSubmitted,
};
},
};
</script>
<style>
.v-label {
color: #000 !important;
opacity: 1 !important;
}
</style>
-60
View File
@@ -1,60 +0,0 @@
export const votingData = {
description: "Описание первой голосовалки",
endDate: "2025-01-27T10:43:04+03:00",
questions: [
{
answers: [
{
text: "Да",
image: null
},
{
text: "Нет",
image: null
}
],
image: {
name: "ed777ac1e74742aa118f59d72e231763d08ac93fv2_hq.jpg",
size: 11530
},
selectedEmployeeImages: {},
selectedEmployees: [],
text: "Ваши родители знают что Вы гей?",
type: "Ввести вручную"
},
{
answers: [],
image: {
name: "ed777ac1e74742aa118f59d72e231763d08ac93fv2_hq.jpg",
size: 11530
},
selectedEmployeeImages: {},
selectedEmployees: [
{ id: 1, name: "Иванов Иван" },
{ id: 2, name: "Петров Пётр" },
{ id: 3, name: "Сидоров Сергей" },
{ id: 4, name: "Алексеева Алена" },
{ id: 5, name: "Михайлов Михаил" },
{ id: 6, name: "Кузнецов Константин" },
{ id: 7, name: "Смирнова Светлана" },
{ id: 8, name: "Попов Павел" },
{ id: 9, name: "Егорова Екатерина" },
{ id: 10, name: "Фёдоров Фёдор" },
{ id: 11, name: "Васильев Василий" },
{ id: 12, name: "Ковалёва Ксения" },
{ id: 13, name: "Григорьев Григорий" },
{ id: 14, name: "Леонова Лилия" },
{ id: 15, name: "Орлов Олег" },
{ id: 16, name: "Белова Белла" },
{ id: 17, name: "Захаров Захар" },
{ id: 18, name: "Чернова Надежда" },
{ id: 19, name: "Максимов Максим" },
{ id: 20, name: "Тимофеева Тамара" }
],
text: "Самый подозрительный сотрудник",
type: "Выбрать сотрудника"
}
],
startDate: "2025-01-13T10:43:04+03:00",
title: "Заголовок голосовалки"
}
+98 -44
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,77 +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) {
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 {
@@ -120,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;
@@ -130,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
}
+32 -17
View File
@@ -80,8 +80,7 @@
</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>
@@ -119,30 +118,25 @@ import VoteConstructor from "@/components/vote/VoteConstructor.vue";
import CurrentVote from "@/components/vote/CurrentVote.vue";
import VoteCardVue from "@/components/vote/VoteCard.vue";
import { useRoute, useRouter } from "vue-router";
import { getVotes } from "@/utils/axios-api";
import {votingData} from "@/test/testDataForVote";
import {formatDate} from "@vueuse/shared";
import { deleteVote, getVoteDetail, getVotes } from "@/utils/axios-api";
import { formatDate } from "@vueuse/shared";
export default {
methods: {formatDate},
computed: {
votingData() {
return votingData
}
},
methods: { formatDate },
components: { CurrentVote, VoteConstructor, VoteCardVue },
setup() {
const currentTab = ref("current");
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')
updating("active");
const voteModal = ref(false);
const editVoteModal = ref(false);
@@ -161,6 +155,16 @@ export default {
.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);
res.value = null;
}
};
const closeModal = () => {
voteModal.value = false;
editVoteModal.value = false;
@@ -169,9 +173,11 @@ export default {
router.push({ name: "VoteHomePage" });
};
const openModal = (type, voting) => {
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") {
@@ -183,16 +189,24 @@ export default {
}
};
const deleteVoting = (id) => {
votes.value = votes.value.filter((v) => v.id !== 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") voteModal.value = true;
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;
@@ -216,6 +230,7 @@ export default {
closeModal,
deleteVoting,
updating,
res,
};
},
};