fix [P-290]: фикс событий в виджете календаря

This commit is contained in:
Inna committed 2025-10-07 13:38:37 +03:00
1 parent 3f0f1e8f1a
commit 0d404e533b
11 files changed
+333 -140

No files matched your search

@@ -199,26 +199,37 @@ export default {
// Получаем имя файла из объекта файла // Получаем имя файла из объекта файла
const getFileName = (fileData) => { const getFileName = (fileData) => {
// Для новых файлов (File object) - берем оригинальное имя
if (fileData instanceof File) { if (fileData instanceof File) {
return cleanFileName(fileData.name); return fileData.name;
} }
// Для существующих файлов с бэка - извлекаем имя из пути
// Для существующих файлов с бэкенда - извлекаем из URL
if (fileData.file) { if (fileData.file) {
try { try {
const filePath = fileData.file.split('?')[0]; // Убираем параметры const filePath = fileData.file.startsWith('http')
const fileName = filePath.split('/').pop(); // Берем последнюю часть пути ? new URL(fileData.file).pathname
return cleanFileName(fileName) || 'Файл'; : fileData.file;
} catch {
// Извлекаем имя файла
let fileName = filePath.split('/').pop();
// Декодируем URL-encoded символы, но НЕ изменяем имя
fileName = decodeURIComponent(fileName);
return fileName || 'Файл';
} catch (error) {
console.warn('Ошибка извлечения имени файла:', error, fileData);
return 'Файл'; return 'Файл';
} }
} }
return cleanFileName(fileData.name || 'Файл'); // Если есть name в данных - используем как есть
}; if (fileData.name) {
return fileData.name;
}
const cleanFileName = (fileName) => { return 'Файл';
// Убираем суффиксы в скобках (1), (2) и т.д.
return fileName.replace(/\s*\(\d+\)(?=\.\w+$|$)/, '');
}; };
// Иконка в зависимости от типа файла // Иконка в зависимости от типа файла
@@ -306,27 +317,25 @@ export default {
const downloadExistingFile = async (file) => { const downloadExistingFile = async (file) => {
try { try {
const getOriginalFileName = (filePath) => { const fileName = getFileName(file); // Теперь будет работать правильно!
try { const fileUrl = file.file.startsWith('http')
const pathParts = filePath.split('/'); ? file.file
return pathParts[pathParts.length - 1]; : `${window.location.origin}${file.file}`; // Для относительных путей
} catch {
return 'file';
}
};
const fileName = getOriginalFileName(file.file);
const fileUrl = file.file;
// Создаем временную ссылку для скачивания
const link = document.createElement('a'); const link = document.createElement('a');
link.href = fileUrl; link.href = fileUrl;
link.download = fileName; // Указываем имя файла при скачивании link.download = fileName;
link.style.display = 'none';
document.body.appendChild(link); document.body.appendChild(link);
link.click(); link.click();
document.body.removeChild(link);
setTimeout(() => {
document.body.removeChild(link);
}, 100);
} catch (error) { } catch (error) {
console.error('Ошибка при скачивании файла:', error); console.error('Ошибка при скачивании файла:', error);
errorMessages.value = ['Ошибка скачивания файла'];
} }
}; };
@@ -360,7 +369,6 @@ export default {
handleFileSelect, handleFileSelect,
triggerFileInput, triggerFileInput,
handleDrop, handleDrop,
cleanFileName,
downloadExistingFile, downloadExistingFile,
truncateFileName, truncateFileName,
}; };
@@ -59,6 +59,10 @@ export default {
calendarStore.loadCalendars(); calendarStore.loadCalendars();
}; };
const getDictEmployee = () => {
calendarStore.loadEmployees();
};
const getEvent = (idEvent) => { const getEvent = (idEvent) => {
if (!idEvent) { if (!idEvent) {
eventFromCalendar.value = createEmptyEvent(); eventFromCalendar.value = createEmptyEvent();
@@ -98,6 +102,8 @@ export default {
onMounted(() => { onMounted(() => {
getEvent(); getEvent();
week.getWeekend(MyYear.value); week.getWeekend(MyYear.value);
getDictEmployee();
getCalendar();
}); });
const closeEventDialog = () => { const closeEventDialog = () => {
@@ -151,6 +157,7 @@ export default {
openEventDialog, openEventDialog,
createEmptyEvent, createEmptyEvent,
eventKey, eventKey,
getDictEmployee,
}; };
}, },
}; };
@@ -113,7 +113,7 @@ export default {
const handleEventClick = (info) => { const handleEventClick = (info) => {
if (calendarStore.canEditEvent(info.event.id)) { if (calendarStore.canEditEvent(info.event.id)) {
emit('openEventDialog', info); emit('openEventDialog', info);
} }
}; };
const calendarOptions = ref({ const calendarOptions = ref({
@@ -310,6 +310,36 @@ export default {
selectedDate.value = dateStr; selectedDate.value = dateStr;
}; };
// const updateCalendarEvents = () => {
// if (!calendarRef.value) return;
// const api = calendarApi.value;
// api.removeAllEvents();
// allEvents.value.forEach((event) => {
// const eventColor = calendarColorMap.value.get(event.calendar) || '#3788d8';
// api.addEvent({
// id: event.id,
// title: event.name || event.title,
// start: event.date_start || event.start,
// end: event.date_end || event.end,
// allDay: event.allday || event.all_day,
// textColor: '#ffffff',
// backgroundColor: eventColor,
// borderColor: eventColor,
// extendedProps: {
// originalEventId: event.id,
// description: event.description,
// participant: event.participant,
// calendar: event.calendar,
// files: event.files,
// isRecurringInstance: event.isRecurringInstance || false,
// },
// });
// });
// };
// Обновление событий в календаре // Обновление событий в календаре
const updateCalendarEvents = () => { const updateCalendarEvents = () => {
if (!calendarRef.value) return; if (!calendarRef.value) return;
@@ -37,8 +37,6 @@
}" }"
@click="onDateClick(day.date)" @click="onDateClick(day.date)"
> >
<div class="day-content"> <div class="day-content">
<span class="day-number">{{ day.day }}</span> <span class="day-number">{{ day.day }}</span>
<div class="day-events"> <div class="day-events">
@@ -59,7 +57,9 @@
<!-- Дневное расписание --> <!-- Дневное расписание -->
<v-col cols="5" class="pl-2"> <v-col cols="5" class="pl-2">
<div class="schedule-header"> <div class="schedule-header">
<h3 class="day-title"> <span v-if="isToday(selectedDate)">Сегодня, </span>{{formattedSelectedDate }}</h3> <h3 class="day-title">
<span v-if="isToday(selectedDate)">Сегодня, </span>{{ formattedSelectedDate }}
</h3>
</div> </div>
<v-card variant="outlined" class="day-schedule" elevation="0"> <v-card variant="outlined" class="day-schedule" elevation="0">
@@ -102,6 +102,7 @@
import { ref, computed, onMounted, watch } from 'vue'; import { ref, computed, onMounted, watch } from 'vue';
import { storeToRefs } from 'pinia'; import { storeToRefs } from 'pinia';
import { useCalendarStore } from '@/store/calendarStore'; import { useCalendarStore } from '@/store/calendarStore';
import { useRecurrence } from '@/components/calendar_of_events/composables/useReccurrence';
export default { export default {
name: 'HomeCalendarWidget', name: 'HomeCalendarWidget',
@@ -115,6 +116,7 @@ export default {
// Работа с хранилищем // Работа с хранилищем
const calendarStore = useCalendarStore(); const calendarStore = useCalendarStore();
const { allEvents, calendarColorMap } = storeToRefs(calendarStore); const { allEvents, calendarColorMap } = storeToRefs(calendarStore);
const { generateRecurringInstances, isRecurringEvent } = useRecurrence();
// Утилиты для работы с датами (главный источник проблем!) // Утилиты для работы с датами (главный источник проблем!)
const formatToLocalDate = (date) => { const formatToLocalDate = (date) => {
@@ -134,25 +136,92 @@ export default {
return getStartOfDay(date1).getTime() === getStartOfDay(date2).getTime(); return getStartOfDay(date1).getTime() === getStartOfDay(date2).getTime();
}; };
// Преобразование событий с защитой от ошибок
const events = computed(() => { const events = computed(() => {
const userEvents = allEvents.value.map((event) => { const expandedEvents = allEvents.value.flatMap((event) => {
const eventColor = calendarColorMap.value.get(event.calendar) || event.color || '#1976d2'; const startDate = new Date(event.date_start);
return { const endDate = new Date(event.date_end);
id: event.id, const isMultiDay = startDate.toDateString() !== endDate.toDateString();
title: event.name || event.title || 'Без названия', const hasRecurrence = event.period && event.period !== 'null';
start: event.date_start || event.start,
end: event.date_end || event.end, // 1. Периодичное + многодневное
description: event.description, if (hasRecurrence && isMultiDay) {
color: eventColor || '#1976d2', const instances = generateRecurringInstances(event, 12);
calendar: event.calendar, return instances.flatMap((instance) => expandMultiDayInstance(event, instance));
isHoliday: false, }
};
// 2. Периодичное + однодневное
if (hasRecurrence && !isMultiDay) {
const instances = generateRecurringInstances(event, 12);
return instances.map((instance) => ({
...event,
id: instance.id,
date_start: instance.date_start || instance.start,
date_end: instance.date_end || instance.end,
isRecurringInstance: true,
}));
}
// 3. Непериодичное + многодневное
if (!hasRecurrence && isMultiDay) {
return expandMultiDayInstance(event, event);
}
// 4. Непериодичное + однодневное
return event;
}); });
return [...userEvents]; return expandedEvents.map((event) => formatForWidget(event));
}); });
// Разбивает многодневный экземпляр на дни
const expandMultiDayInstance = (originalEvent, instance) => {
const startDate = new Date(instance.date_start || instance.start);
const endDate = new Date(instance.date_end || instance.end);
const days = [];
const currentDay = new Date(startDate);
while (currentDay < endDate) {
const dayStart = new Date(currentDay);
const dayEnd = new Date(currentDay);
dayEnd.setDate(dayEnd.getDate() + 1);
days.push({
...originalEvent,
id: instance.id, // ID от экземпляра периодичности
date_start: dayStart.toISOString(),
date_end: dayEnd.toISOString(),
allday: true,
isMultiDayPart: true,
isRecurringInstance: instance.isRecurringInstance || false,
originalStart: instance.date_start || instance.start,
originalEnd: instance.date_end || instance.end,
});
currentDay.setDate(currentDay.getDate() + 1);
}
return days;
};
// Форматирование для виджета
const formatForWidget = (event) => {
const eventColor =
event.calendarData?.cl_color || calendarColorMap.value?.get(event.calendar) || '#1976d2';
return {
id: event.id,
title: event.name || 'Без названия',
start: event.date_start,
end: event.date_end,
description: event.description,
color: eventColor,
calendar: event.calendar,
calendarData: event.calendarData,
isRecurringInstance: event.isRecurringInstance || false,
isMultiDayPart: event.isMultiDayPart || false,
};
};
const russianWeekdays = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс']; const russianWeekdays = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'];
// Генерация календаря // Генерация календаря
@@ -316,6 +385,8 @@ export default {
calendarStore, calendarStore,
allEvents, allEvents,
expandMultiDayInstance,
formatForWidget,
}; };
}, },
}; };
@@ -529,6 +600,6 @@ export default {
} }
.day-cell:not(.current-month).non-working-day { .day-cell:not(.current-month).non-working-day {
color: inherit !important; /* color: inherit !important; */
} }
</style> </style>
@@ -86,7 +86,6 @@ export default {
loadCalendars(); loadCalendars();
updateCalendarDays(); updateCalendarDays();
setInterval(updateCalendarDays, 500);
}); });
// Реакция на изменения пользователя // Реакция на изменения пользователя
@@ -96,6 +95,18 @@ export default {
} }
}); });
watch(selectedDate, () => {
updateCalendarDays();
});
watch(
[myCalendars, subscribedCalendars],
() => {
updateCalendarDays();
},
{ deep: true },
);
// Функция для добавления классов дням // Функция для добавления классов дням
const updateCalendarDays = () => { const updateCalendarDays = () => {
nextTick(() => { nextTick(() => {
@@ -22,23 +22,14 @@
size="36px" size="36px"
@click="$emit('delObject')" @click="$emit('delObject')"
/> />
<!-- <v-btn <v-btn
class="text-subtitle-1"
elevation="0"
width="150"
@click="clearValidation"
color="btn_gray"
variant="flat"
>резет</v-btn
> -->
<!-- <v-btn @click="clearFormValidation"></v-btn> -->
<v-btn
class="text-subtitle-1" class="text-subtitle-1"
elevation="0" elevation="0"
width="150" width="150"
@click="$emit('closeDialog')" @click="$emit('closeDialog')"
color="btn_gray" color="btn_gray"
variant="flat" variant="flat"
type="button"
>Отменить</v-btn >Отменить</v-btn
> >
@@ -48,7 +39,7 @@
variant="flat" variant="flat"
elevation="0" elevation="0"
width="150" width="150"
type="transformation" type="submit"
> >
{{ newOrOld ? "Создать" : "Сохранить" }} {{ newOrOld ? "Создать" : "Сохранить" }}
</v-btn> </v-btn>
@@ -23,7 +23,7 @@
<v-chip class="me-2" color="teal-darken-3" size="small" label> <v-chip class="me-2" color="teal-darken-3" size="small" label>
<span> {{ item.title }}</span> <span> {{ item.title }}</span>
<v-icon <v-icon
v-if="item.value != accountStore.user.is_idEmployee" v-if="item.value != accountStore.user.is_idEmployee && !isAuthor(item.raw)"
icon="mdi-close-circle" icon="mdi-close-circle"
size="x-small" size="x-small"
class="ml-3" class="ml-3"
@@ -46,7 +46,35 @@
></v-checkbox-btn> ></v-checkbox-btn>
</template> </template>
</v-list-item> </v-list-item>
<!-- ВСЕ НАЧАЛЬНИКИ -->
<v-list-item
:disabled="!hasBossesInStaff"
class="text-body-2"
@click.stop="toggleByPosition('начальник')"
>
<span class="text-body-2"> ВСЕ НАЧАЛЬНИКИ </span>
<template v-slot:prepend>
<v-checkbox-btn
:model-value="hasBossesSelected"
:disabled="!hasBossesInStaff"
></v-checkbox-btn>
</template>
</v-list-item>
<!-- ВСЕ ЗАМЕСТИТЕЛИ -->
<v-list-item
:disabled="!hasDeputiesInStaff"
class="text-body-2"
@click.stop="toggleByPosition('заместитель')"
>
<span class="text-body-2"> ВСЕ ЗАМЕСТИТЕЛИ </span>
<template v-slot:prepend>
<v-checkbox-btn
:model-value="hasDeputiesSelected"
:disabled="!hasDeputiesInStaff"
></v-checkbox-btn>
</template>
</v-list-item>
<v-divider class="mt-2"></v-divider> <v-divider class="mt-2"></v-divider>
</template> </template>
@@ -60,7 +88,7 @@
:color="'indigo-darken-4'" :color="'indigo-darken-4'"
:true-value="true" :true-value="true"
:false-value="false" :false-value="false"
:disabled="disable(item.raw)" :disabled="disable(item.raw) || isAuthor(item.raw)"
:indeterminate=" :indeterminate="
item.raw.employees.some((e) => e[okey] == true) && item.raw.employees.some((e) => e[okey] == true) &&
!item.raw.employees.every((e) => e[okey] == true) !item.raw.employees.every((e) => e[okey] == true)
@@ -78,12 +106,12 @@
:key="x.id" :key="x.id"
:value="x.title" :value="x.title"
@click.stop="selectedStaff = x" @click.stop="selectedStaff = x"
:disabled="x.id == accountStore.user.is_idEmployee" :disabled="x.id == accountStore.user.is_idEmployee || isAuthor(x)"
density="compact" density="compact"
> >
<template v-slot:prepend> <template v-slot:prepend>
<v-checkbox-btn <v-checkbox-btn
:disabled="x.id == accountStore.user.is_idEmployee" :disabled="x.id == accountStore.user.is_idEmployee || isAuthor(x)"
color="indigo-darken-4" color="indigo-darken-4"
:model-value="x[okey]" :model-value="x[okey]"
></v-checkbox-btn> ></v-checkbox-btn>
@@ -94,7 +122,7 @@
</template> </template>
</v-autocomplete> </v-autocomplete>
<!-- Кнопки быстрого выбора --> <!-- Кнопки быстрого выбора -->
<div class="quick-filters mb-3"> <!-- <div class="quick-filters mb-3">
<v-btn <v-btn
size="small" size="small"
:variant="hasBossesSelected ? 'tonal' : 'outlined'" :variant="hasBossesSelected ? 'tonal' : 'outlined'"
@@ -103,7 +131,7 @@
@click="toggleByPosition('начальник')" @click="toggleByPosition('начальник')"
:disabled="!dictEmployeesLoaded || !hasBossesInStaff" :disabled="!dictEmployeesLoaded || !hasBossesInStaff"
> >
{{ hasBossesSelected ? 'Снять начальников' : 'Выбрать всех начальников' }} {{ hasBossesSelected ? 'Отменить выбор начальников' : 'Выбрать всех начальников' }}
</v-btn> </v-btn>
<v-btn <v-btn
@@ -113,17 +141,18 @@
@click="toggleByPosition('заместитель')" @click="toggleByPosition('заместитель')"
:disabled="!dictEmployeesLoaded || !hasDeputiesInStaff" :disabled="!dictEmployeesLoaded || !hasDeputiesInStaff"
> >
{{ hasDeputiesSelected ? 'Снять заместителей' : 'Выбрать всех заместителей' }} {{ hasDeputiesSelected ? 'Отменить выбор заместителей' : 'Выбрать всех заместителей' }}
</v-btn> </v-btn>
</div> </div> -->
</div> </div>
</template> </template>
<script> <script>
import { ref, computed } from 'vue'; import { ref, computed } from 'vue';
import { storeToRefs } from 'pinia';
import { splitname } from '@/utils/universal_functions'; import { splitname } from '@/utils/universal_functions';
import { useAccountStore } from '@/store/AccountStore'; import { useAccountStore } from '@/store/AccountStore';
import { axiosApiInstance } from '@/utils/axios-api'; import { useCalendarStore } from '@/store/calendarStore';
export default { export default {
props: { props: {
@@ -135,11 +164,19 @@ export default {
type: String, type: String,
default: 'selected', default: 'selected',
}, },
authorID: {
type: Number,
default: null,
},
}, },
setup(props, { emit }) { setup(props, { emit }) {
const filtered = ref(''); const filtered = ref('');
const accountStore = useAccountStore(); const accountStore = useAccountStore();
const calendarStore = useCalendarStore();
const { dictEmployeesLoaded } = storeToRefs(calendarStore);
const back = ref([]); const back = ref([]);
const staffed = computed({ const staffed = computed({
@@ -284,27 +321,23 @@ export default {
: false; : false;
}; };
// Функция проверки является ли сотрудник создателем
const isAuthor = (item) => {
if (!props.authorID) return false;
// Если это отдел - проверяем всех сотрудников
if ('employees' in item) {
return item.employees.some((emp) => emp.id === props.authorID);
}
// Если это сотрудник - проверяем напрямую
return item.id === props.authorID;
};
const allUser = () => { const allUser = () => {
emitUp(staffed.value); emitUp(staffed.value);
}; };
const dictEmployees = ref([]);
const dictEmployeesLoaded = ref(false);
// Загружаем данные с должностями
const loadDictEmployees = async () => {
try {
const response = await axiosApiInstance.get('api/vote/getdictemployee/');
dictEmployees.value = response.data;
dictEmployeesLoaded.value = true;
} catch (error) {
console.error('Ошибка загрузки должностей:', error);
dictEmployeesLoaded.value = false;
}
};
loadDictEmployees();
// Проверяем выбраны ли все начальники (с исключениями) // Проверяем выбраны ли все начальники (с исключениями)
const hasBossesSelected = computed(() => { const hasBossesSelected = computed(() => {
const bosses = findEmployeesByPosition(['начальник', 'и.о'], ['заместитель', 'зам.']); const bosses = findEmployeesByPosition(['начальник', 'и.о'], ['заместитель', 'зам.']);
@@ -333,12 +366,27 @@ export default {
const employeesToToggle = findEmployeesByPosition(keywords, excludeKeywords); const employeesToToggle = findEmployeesByPosition(keywords, excludeKeywords);
const shouldSelect = !employeesToToggle.every((emp) => emp[props.okey] === true); const shouldSelect = !employeesToToggle.every((emp) => emp[props.okey] === true);
// if (employeesToToggle.length > 0) {
// employeesToToggle.forEach((employee) => {
// if (employee[props.okey] !== shouldSelect) {
// emitUp(employee);
// }
// });
// }
if (employeesToToggle.length > 0) { if (employeesToToggle.length > 0) {
employeesToToggle.forEach((employee) => { // ФИЛЬТРУЕМ - убираем создателя события из массовых операций
if (employee[props.okey] !== shouldSelect) { const filteredEmployees = employeesToToggle.filter(
emitUp(employee); (employee) => employee.id !== props.authorID, //
} );
});
if (filteredEmployees.length > 0) {
filteredEmployees.forEach((employee) => {
if (employee[props.okey] !== shouldSelect) {
selectedStaff.value = employee;
}
});
}
} }
}; };
@@ -346,12 +394,11 @@ export default {
const findEmployeesByPosition = (positionKeywords, excludeKeywords = []) => { const findEmployeesByPosition = (positionKeywords, excludeKeywords = []) => {
const foundEmployees = []; const foundEmployees = [];
if (!dictEmployeesLoaded.value) {
return foundEmployees;
}
props.staff.forEach((department) => { props.staff.forEach((department) => {
department.employees.forEach((employee) => { department.employees.forEach((employee) => {
if (department.id == 1) {
return;
}
if (employee.id === accountStore.user.is_idEmployee) { if (employee.id === accountStore.user.is_idEmployee) {
return; return;
} }
@@ -360,7 +407,7 @@ export default {
return; return;
} }
const employeeData = dictEmployees.value.find((de) => de.id === employee.id); const employeeData = calendarStore.dictEmployees.find((de) => de.id === employee.id);
if (employeeData && employeeData.post) { if (employeeData && employeeData.post) {
const post = employeeData.post.toLowerCase(); const post = employeeData.post.toLowerCase();
@@ -384,7 +431,10 @@ export default {
}; };
// Проверяем есть ли начальники в staff // Проверяем есть ли начальники в staff
const hasBossesInStaff = computed(() => { const hasBossesInStaff = computed(() => {
return findEmployeesByPosition(['начальник', 'и.о. начальника']).length > 0; return (
findEmployeesByPosition(['начальник', 'и.о. начальника'], ['заместитель', 'зам.']).length >
0
);
}); });
// Проверяем есть ли заместители в staff // Проверяем есть ли заместители в staff
@@ -396,6 +446,7 @@ export default {
}); });
return { return {
isAuthor,
staffed, staffed,
filtered, filtered,
accountStore, accountStore,
@@ -406,11 +457,11 @@ export default {
customFilterFn, customFilterFn,
findEmployeesByPosition, findEmployeesByPosition,
toggleByPosition, toggleByPosition,
dictEmployeesLoaded,
hasBossesInStaff, hasBossesInStaff,
hasBossesSelected, hasBossesSelected,
hasDeputiesInStaff, hasDeputiesInStaff,
hasDeputiesSelected, hasDeputiesSelected,
dictEmployeesLoaded,
}; };
}, },
}; };
@@ -46,6 +46,7 @@
<calendar-create-select <calendar-create-select
:staff="newStaff" :staff="newStaff"
@returnIdParticant="returnIdParticant" @returnIdParticant="returnIdParticant"
:authorID="calendarAuthorId"
/> </v-col /> </v-col
></v-row> ></v-row>
</v-col> </v-col>
@@ -69,6 +70,7 @@
:staff="newStaff" :staff="newStaff"
:okey="'editor'" :okey="'editor'"
@returnIdParticant="returnIdParticant" @returnIdParticant="returnIdParticant"
:authorID="calendarAuthorId"
/> />
</v-col> </v-col>
<v-col lg="1" class="text-center"> <v-col lg="1" class="text-center">
@@ -109,6 +111,15 @@ export default {
setup(props, { emit }) { setup(props, { emit }) {
const accountStore = useAccountStore(); const accountStore = useAccountStore();
const calendarAuthorId = computed(() => {
// Для нового календаря - текущий пользователь
if (isNewCalendar.value) {
return accountStore.user.is_idEmployee;
}
// Для существующего - автор из props
return propsCalendar.value.author;
});
const returnIdParticant = (idPart) => { const returnIdParticant = (idPart) => {
idPart.staff.forEach((e) => { idPart.staff.forEach((e) => {
let indx = propsCalendar.value.participant.findIndex((l) => l.participant_calendar == e.id); let indx = propsCalendar.value.participant.findIndex((l) => l.participant_calendar == e.id);
@@ -206,40 +217,22 @@ export default {
}, },
}); });
// const color = [
// '#3788d8', // Синий (аналог default FullCalendar)
// '#4caf50', // Зеленый
// '#ff9800', // Оранжевый
// '#9c27b0', // Фиолетовый
// '#2196f3', // Голубой
// '#795548', // Коричневый
// '#607d8b', // Серо-голубой
// '#e91e63', // Розовый
// '#00bcd4', // Бирюзовый
// '#8bc34a', // Салатовый
// '#ff5722', // Красно-оранжевый
// '#673ab7', // Темно-фиолетовый
// '#3f51b5', // Индиго
// '#009688', // Зелено-бирюзовый
// '#ffc107', // Янтарный
// ];
const color = [ const color = [
'#4299e1', // Яркий синий '#4f46e5', // Индиго (профессиональный синий)
'#48bb78', // Сочный зеленый '#0ea5e9', // Яркий голубой
'#ed8936', // Оранжевый '#10b981', // Изумрудно-зеленый
'#9f7aea', // Фиолетовый '#f59e0b', // Теплый янтарный
'#38b2ac', // Бирюзовый '#ef4444', // Акцентный красный
'#f56565', // Коралловый '#8b5cf6', // Фиолетовый
'#667eea', // Голубой '#06b6d4', // Бирюзовый
'#68d391', // Светло-зеленый '#84cc16', // Лаймовый
'#f6ad55', // Персиковый '#f97316', // Оранжевый
'#b794f4', // Лавандовый '#ec4899', // Розовый
'#4fd1c7', // Яркий бирюзовый '#6366f1', // Фиолетово-синий
'#fc8181', // Розово-коралловый '#14b8a6', // Бирюзово-зеленый
'#5a67d8', // Индиго '#eab308', // Золотисто-желтый
'#ecc94b', // Золотистый '#3b82f6', // Королевский синий
'#0bc5ea', // Голубой океан '#22c55e', // Зеленый
]; ];
const colorPik = (col) => { const colorPik = (col) => {
@@ -279,6 +272,7 @@ export default {
newCalendar, newCalendar,
newStaff, newStaff,
isNewCalendar, isNewCalendar,
calendarAuthorId,
}; };
}, },
}; };
@@ -127,17 +127,11 @@ export default {
toggleCalendarVisibility(cal.id); toggleCalendarVisibility(cal.id);
}; };
watch( watch(hiddenCalendarIds, (newHiddenIds) => {}, { deep: true });
hiddenCalendarIds,
(newHiddenIds) => {
},
{ deep: true },
);
watch( watch(
() => props.calendars, () => props.calendars,
(newCalendars) => { (newCalendars) => {},
},
{ deep: true }, { deep: true },
); );
@@ -33,6 +33,7 @@
<calendar-create-select <calendar-create-select
:staff="newStaff" :staff="newStaff"
@returnIdParticant="returnIdParticant" @returnIdParticant="returnIdParticant"
:authorID="currentCalendarAuthorId"
/> </v-col /> </v-col
></v-row> ></v-row>
@@ -228,6 +229,20 @@ export default {
const staff = ref([]); const staff = ref([]);
const currentCalendarAuthorId = computed(() => {
if (isNewEvent.value) {
// Для нового события - автор текущего выбранного календаря
return myCalendar.value?.author;
} else {
// Для существующего события - автор календаря события
const eventCalendarId = propsEvent.value.event.calendar;
const currentCalendar = propsEvent.value.mycalendars?.find(
(cal) => parseInt(cal.id) === parseInt(eventCalendarId),
);
return currentCalendar?.author;
}
});
axiosApiInstance.get('api/calendar_of_events/get_employees/').then((res) => { axiosApiInstance.get('api/calendar_of_events/get_employees/').then((res) => {
staff.value = res.data.filter((e) => e.employees.length > 0); staff.value = res.data.filter((e) => e.employees.length > 0);
}); });
@@ -235,6 +250,7 @@ export default {
const newStaff = computed({ const newStaff = computed({
get() { get() {
let filteredStaff = []; let filteredStaff = [];
if (isNewEvent.value) { if (isNewEvent.value) {
if (myCalendar.value == null) return []; if (myCalendar.value == null) return [];
const participants = myCalendar.value.participant || []; const participants = myCalendar.value.participant || [];
@@ -562,9 +578,13 @@ export default {
); );
if (propsEvent.value.event.files !== null) { if (propsEvent.value.event.files !== null) {
newFiles.value.forEach((e) => postEvent.append('files', e)); // newFiles.value.forEach((e) => postEvent.append('files', e));
newFiles.value.forEach((file) => {
postEvent.append('files', file, file.name);
});
} }
axiosApiInstance.post('api/calendar_of_events/my_events/', postEvent).then((result) => { axiosApiInstance.post('api/calendar_of_events/my_events/', postEvent).then((result) => {
feedalert.alert = true; feedalert.alert = true;
feedalert.text = result.data.mess; feedalert.text = result.data.mess;
@@ -681,6 +701,7 @@ export default {
safeCalendars, safeCalendars,
isCalendarsReady, isCalendarsReady,
isNewEvent, isNewEvent,
currentCalendarAuthorId,
repeatRules, repeatRules,
updatePeriodRule, updatePeriodRule,
+18 -3
View File
@@ -1,6 +1,6 @@
import { defineStore } from 'pinia'; import { defineStore } from 'pinia';
import { ref, computed, watch } from 'vue'; import { ref, computed, watch } from 'vue';
import { axiosApiInstance, getEmployees } from '@/utils/axios-api'; import { axiosApiInstance } from '@/utils/axios-api';
import { useAccountStore } from '@/store/AccountStore'; import { useAccountStore } from '@/store/AccountStore';
export const useCalendarStore = defineStore('calendarStore', () => { export const useCalendarStore = defineStore('calendarStore', () => {
@@ -15,6 +15,8 @@ export const useCalendarStore = defineStore('calendarStore', () => {
const calendars = ref([]); // Список календарей пользователя const calendars = ref([]); // Список календарей пользователя
const lastUpdatedBy = ref(null); const lastUpdatedBy = ref(null);
const holidays = ref([]); const holidays = ref([]);
const dictEmployees = ref([]);
const dictEmployeesLoaded = ref(false);
// Массив ID скрытых календарей. Загружаем из localStorage при инициализации. // Массив ID скрытых календарей. Загружаем из localStorage при инициализации.
const hiddenCalendarIds = ref([]); const hiddenCalendarIds = ref([]);
@@ -90,6 +92,17 @@ export const useCalendarStore = defineStore('calendarStore', () => {
} }
}; };
const loadEmployees = async () => {
try {
const response = await axiosApiInstance.get(`api/vote/getdictemployee/`);
dictEmployees.value = response.data;
dictEmployeesLoaded.value = true;
} catch (error) {
console.error('Ошибка получения всех сотрудников:', error);
dictEmployeesLoaded.value = false;
}
};
const toggleCalendarVisibility = (calendarId) => { const toggleCalendarVisibility = (calendarId) => {
const index = hiddenCalendarIds.value.indexOf(calendarId); const index = hiddenCalendarIds.value.indexOf(calendarId);
if (index === -1) { if (index === -1) {
@@ -210,7 +223,7 @@ export const useCalendarStore = defineStore('calendarStore', () => {
return result; return result;
}; };
// Открыть диалог создания/редактирования // Открыть диалог создания/редактирования
const openEventDialog = (event = null) => { const openEventDialog = (event = null) => {
selectedEvent.value = event; selectedEvent.value = event;
showEventDialog.value = true; showEventDialog.value = true;
@@ -233,6 +246,7 @@ export const useCalendarStore = defineStore('calendarStore', () => {
lastUpdatedBy, lastUpdatedBy,
hiddenCalendarIds, hiddenCalendarIds,
holidays, holidays,
dictEmployeesLoaded,
// Getters // Getters
formattedSelectedDate, formattedSelectedDate,
@@ -243,6 +257,7 @@ export const useCalendarStore = defineStore('calendarStore', () => {
allEvents, allEvents,
calendarColorMap, calendarColorMap,
dictEmployees,
editableEvents, editableEvents,
canEditEvent, canEditEvent,
@@ -257,6 +272,6 @@ export const useCalendarStore = defineStore('calendarStore', () => {
toggleCalendarVisibility, toggleCalendarVisibility,
fetchHolidays, fetchHolidays,
isNonWorkingDay, isNonWorkingDay,
// loadEmployees, loadEmployees,
}; };
}); });