fix [P-47]: фикс событий

This commit is contained in:
Inna committed 2025-09-30 12:07:58 +03:00
1 parent b56f5e3a27
commit b0b619288c
6 files changed
+111 -93

No files matched your search

@@ -102,7 +102,7 @@ export default {
const currentTitle = ref('Календарь'); const currentTitle = ref('Календарь');
const calendarStore = useCalendarStore(); const calendarStore = useCalendarStore();
const { selectedDate, lastUpdatedBy, allEvents } = storeToRefs(calendarStore); const { selectedDate, lastUpdatedBy, allEvents, calendarColorMap } = storeToRefs(calendarStore);
const { parseRecurrenceOptions, isRecurringEvent } = useRecurrence(); const { parseRecurrenceOptions, isRecurringEvent } = useRecurrence();
const handleEventClick = (info) => { const handleEventClick = (info) => {
@@ -314,6 +314,14 @@ export default {
selectedDate.value = dateStr; selectedDate.value = dateStr;
}; };
// const calendarColorMap = computed(() => {
// const map = new Map();
// calendarStore.myCalendars.forEach((calendar) => {
// map.set(calendar.id, calendar.cl_color);
// });
// return map;
// });
// Обновление событий в календаре // Обновление событий в календаре
const updateCalendarEvents = () => { const updateCalendarEvents = () => {
if (calendarRef.value) { if (calendarRef.value) {
@@ -332,8 +340,8 @@ export default {
end: new Date(event.date_end), end: new Date(event.date_end),
allDay: event.all_day, allDay: event.all_day,
textColor: '#ffffff', textColor: '#ffffff',
// backgroundColor: eventColor, backgroundColor: eventColor,
// borderColor: eventColor, borderColor: eventColor,
}; };
if (!rruleOptions) { if (!rruleOptions) {
@@ -355,14 +363,6 @@ export default {
} }
}; };
const calendarColorMap = computed(() => {
const map = new Map();
calendarStore.myCalendars.forEach((calendar) => {
map.set(calendar.id, calendar.cl_color);
});
return map;
});
onMounted(() => { onMounted(() => {
nextTick(() => { nextTick(() => {
if (calendarRef.value && calendarRef.value.getApi) { if (calendarRef.value && calendarRef.value.getApi) {
@@ -397,11 +397,13 @@ export default {
}); });
watch( watch(
allEvents, [allEvents],
(newEvents) => { ([newEvents]) => {
updateCalendarEvents(); if (newEvents.length > 0) {
updateCalendarEvents();
}
}, },
{ deep: true }, { deep: true, immediate: true },
); );
watch( watch(
@@ -427,7 +429,6 @@ export default {
handleDateSelection, handleDateSelection,
updateCalendarEvents, updateCalendarEvents,
handleEventClick, handleEventClick,
calendarColorMap,
calendarStore, calendarStore,
}; };
}, },
@@ -540,24 +541,4 @@ export default {
:deep(.fc-day.grey-background) { :deep(.fc-day.grey-background) {
background-color: #f5f5f5 !important; background-color: #f5f5f5 !important;
} }
/* :deep(.fc-daygrid-day-frame) {
position: relative;
min-height: 50px;
}
:deep(.fc-daygrid-more-link) {
position: absolute;
bottom: -6px;
right: 2px;
font-size: 11px;
padding: 1px 3px;
background: rgba(0, 0, 0, 0.05);
border-radius: 3px;
z-index: 3;
}
:deep(.fc-popover) {
} */
</style> </style>
@@ -37,6 +37,8 @@
}" }"
@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">
@@ -58,9 +60,6 @@
<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">Сегодня, {{ formattedSelectedDate }}</h3> <h3 class="day-title">Сегодня, {{ formattedSelectedDate }}</h3>
<!-- <v-chip size="small" color="primary" variant="outlined" v-if="isToday(selectedDate)">
Сегодня
</v-chip> -->
</div> </div>
<v-card variant="outlined" class="day-schedule" elevation="0"> <v-card variant="outlined" class="day-schedule" elevation="0">
@@ -72,7 +71,10 @@
:class="{ 'current-event': isCurrentEvent(event) }" :class="{ 'current-event': isCurrentEvent(event) }"
> >
<template #prepend> <template #prepend>
<v-icon :color="event.color" size="small" class="mr-2"> mdi-circle-small </v-icon> <div
class="event-color-indicator"
:style="{ backgroundColor: event.color }"
></div>
</template> </template>
<v-list-item-title class="event-time"> <v-list-item-title class="event-time">
@@ -97,7 +99,7 @@
</template> </template>
<script> <script>
import { ref, computed, onMounted } 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';
@@ -112,7 +114,7 @@ export default {
// Работа с хранилищем // Работа с хранилищем
const calendarStore = useCalendarStore(); const calendarStore = useCalendarStore();
const { allEvents } = storeToRefs(calendarStore); const { allEvents, calendarColorMap } = storeToRefs(calendarStore);
// Утилиты для работы с датами (главный источник проблем!) // Утилиты для работы с датами (главный источник проблем!)
const formatToLocalDate = (date) => { const formatToLocalDate = (date) => {
@@ -135,13 +137,15 @@ export default {
// Преобразование событий с защитой от ошибок // Преобразование событий с защитой от ошибок
const events = computed(() => { const events = computed(() => {
const userEvents = allEvents.value.map((event) => { const userEvents = allEvents.value.map((event) => {
const eventColor = calendarColorMap.value.get(event.calendar) || event.color || '#1976d2';
return { return {
id: event.id, id: event.id,
title: event.name || event.title || 'Без названия', title: event.name || event.title || 'Без названия',
start: event.date_start || event.start, start: event.date_start || event.start,
end: event.date_end || event.end, end: event.date_end || event.end,
description: event.description, description: event.description,
color: event.color || '#1976d2', color: eventColor || '#1976d2',
calendar: event.calendar,
isHoliday: false, isHoliday: false,
}; };
}); });
@@ -278,6 +282,14 @@ export default {
calendarStore.fetchHolidays(currentYear); calendarStore.fetchHolidays(currentYear);
}); });
watch(
calendarColorMap,
(newMap) => {
newMap.value;
},
{ deep: true },
);
return { return {
// Реактивные данные // Реактивные данные
currentDate, currentDate,
@@ -353,7 +365,7 @@ export default {
color: #666; color: #666;
text-align: center; text-align: center;
padding: 8px 4px; padding: 8px 4px;
border-bottom: 1px solid #e0e0e0; border-bottom: 1px solid #afadad;
} }
.day-cell { .day-cell {
@@ -383,7 +395,7 @@ export default {
} }
.day-cell.selected { .day-cell.selected {
background-color: #00897B; background-color: #00897b;
color: white; color: white;
} }
@@ -419,6 +431,15 @@ export default {
display: block; display: block;
} }
.event-color-indicator {
width: 10px;
height: 10px;
border-radius: 50%;
margin-right: 12px;
flex-shrink: 0;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1);
}
/* Дневное расписание */ /* Дневное расписание */
.schedule-header { .schedule-header {
display: flex; display: flex;
@@ -446,7 +467,7 @@ export default {
min-height: 48px; min-height: 48px;
padding: 8px 12px; padding: 8px 12px;
border-left: 4px solid transparent; border-left: 4px solid transparent;
border-bottom: 1px solid #f5f5f5; border-bottom: 1px solid #d3cecede;
} }
.schedule-item:last-child { .schedule-item:last-child {
@@ -461,16 +482,16 @@ export default {
.event-time { .event-time {
font-size: 0.8rem; font-size: 0.8rem;
font-weight: 600; font-weight: 600;
color: #666; color: #302f2f;
margin-bottom: 2px; margin-bottom: 2px;
} }
.event-title { .event-title {
font-size: 0.85rem; font-size: 0.9rem;
white-space: nowrap; white-space: nowrap;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
color: #333; color: #1b1b1b;
} }
.no-events { .no-events {
@@ -125,7 +125,6 @@ export default {
new Date(propsDateEvent.value).getMinutes(), new Date(propsDateEvent.value).getMinutes(),
).padStart(2, '0')}`; ).padStart(2, '0')}`;
}, },
set(newValue) { set(newValue) {
createdDate(modelDate.value, newValue); createdDate(modelDate.value, newValue);
}, },
@@ -137,28 +136,21 @@ export default {
newDate.setHours(hours, minutes, 0, 0); newDate.setHours(hours, minutes, 0, 0);
if (props.order[0] == 4) { if (props.order[0] == 4) {
// Для окончания: проверяем чтобы не было раньше начала
const startDate = new Date(props.limitation); const startDate = new Date(props.limitation);
if (newDate <= startDate) { if (newDate <= startDate) {
const correctedDate = new Date(startDate); const correctedDate = new Date(startDate);
correctedDate.setHours(startDate.getHours() + 1); correctedDate.setHours(startDate.getHours() + 1);
propsDateEvent.value = newDate; propsDateEvent.value = correctedDate;
} else { } else {
propsDateEvent.value = newDate; propsDateEvent.value = newDate;
} }
// propsDateEvent.value = newDate >= startDate ? newDate : startDate;
} else { } else {
// Для начала: просто устанавливаем дату
propsDateEvent.value = newDate; propsDateEvent.value = newDate;
// Автоматически двигаем окончание, если оно стало раньше начала
const currentEnd = new Date(props.limitation); const currentEnd = new Date(props.limitation);
if (newDate > currentEnd) { if (newDate > currentEnd) {
// Ставим окончание на 1 час позже нового начала
const newEnd = new Date(newDate); const newEnd = new Date(newDate);
newEnd.setHours(newDate.getHours() + 1); newEnd.setHours(newDate.getHours() + 1);
emit('adjustEndDate', newEnd.toISOString()); // Новый emit emit('adjustEndDate', newEnd.toISOString());
} }
} }
@@ -148,7 +148,7 @@
<v-row <v-row
no-gutters no-gutters
class="align-start d-flex pt-3 mb-3" class="align-start d-flex pt-3 mb-3"
style=" height:auto; min-height: 200px; max-height: 400px" style="height: auto; min-height: 200px; max-height: 400px"
> >
<v-col class="text-body-2 text-text_grey pb-5 pt-3" lg="2"> Файлы </v-col> <v-col class="text-body-2 text-text_grey pb-5 pt-3" lg="2"> Файлы </v-col>
@@ -329,25 +329,44 @@ export default {
const isCalendarsReady = computed(() => safeCalendars.value.length > 0); const isCalendarsReady = computed(() => safeCalendars.value.length > 0);
// Автовыбор при появлении данных // Computed для календаря события
watch(isCalendarsReady, (ready) => { const eventCalendar = computed(() => {
if (ready && !myCalendar.value && safeCalendars.value[0]) { if (!propsEvent.value?.event?.calendar || !safeCalendars.value.length) return null;
myCalendar.value = safeCalendars.value[0]; return safeCalendars.value.find((cal) => cal.id === propsEvent.value.event.calendar);
}
}); });
watch( // Единоразовая инициализация при монтировании/получении данных
() => propsEvent.value, const initializeCalendar = () => {
(newEvent) => { if (myCalendar.value) return; // Уже инициализирован
if (!newEvent || !safeCalendars.value.length) return;
// РЕДАКТИРОВАНИЕ - календарь из события // Приоритет 1: календарь из события (редактирование)
const eventCalendar = safeCalendars.value.find((cal) => cal.id === newEvent.event.calendar); if (eventCalendar.value) {
myCalendar.value = eventCalendar || safeCalendars.value[0]; myCalendar.value = eventCalendar.value;
return;
}
// Приоритет 2: первый доступный календарь (создание)
if (safeCalendars.value.length > 0) {
myCalendar.value = safeCalendars.value[0];
}
};
// Инициализируем когда все готово
watch(
[() => safeCalendars.value.length, () => propsEvent.value],
() => {
initializeCalendar();
}, },
{ immediate: true, deep: true }, { immediate: true },
); );
// Дополнительная защита - вотчер только на смену самого календаря
watch(eventCalendar, (newCalendar) => {
if (newCalendar && newCalendar.id !== myCalendar.value?.id) {
myCalendar.value = newCalendar;
}
});
const staff = ref([]); const staff = ref([]);
axiosApiInstance.get('api/calendar_of_events/get_employees/').then((res) => { axiosApiInstance.get('api/calendar_of_events/get_employees/').then((res) => {
@@ -611,6 +630,7 @@ export default {
handleAutoAdjustEnd, handleAutoAdjustEnd,
newFiles, newFiles,
handleFilesUpdate, handleFilesUpdate,
initializeCalendar,
}; };
}, },
}; };
+17 -13
View File
@@ -118,6 +118,14 @@ export const useCalendarStore = defineStore('calendarStore', () => {
calendars.value.filter((calendar) => !hiddenCalendarIds.value.includes(calendar.id)), calendars.value.filter((calendar) => !hiddenCalendarIds.value.includes(calendar.id)),
); );
const calendarColorMap = computed(() => {
const map = new Map();
myCalendars.value.forEach((calendar) => {
map.set(calendar.id, calendar.cl_color);
});
return map;
});
const allEvents = computed(() => { const allEvents = computed(() => {
return calendars.value return calendars.value
.filter((calendar) => !hiddenCalendarIds.value.includes(calendar.id)) .filter((calendar) => !hiddenCalendarIds.value.includes(calendar.id))
@@ -130,25 +138,20 @@ export const useCalendarStore = defineStore('calendarStore', () => {
}); });
const editableEvents = computed(() => { const editableEvents = computed(() => {
const calendarsMap = new Map(myCalendars.value.map((cal) => [cal.id, cal]));
const currentUserId = accountStore.user.is_idEmployee;
return allEvents.value.filter((event) => { return allEvents.value.filter((event) => {
const calendar = myCalendars.value.find((cal) => cal.id == event.calendar); const calendar = calendarsMap.get(event.calendar);
if (!calendar) return false; // Автор календаря
if (calendar?.author == currentUserId) return true;
// Пользователь - автор календаря // Участник события
if (calendar.author == accountStore.user.is_idEmployee) return true; return event.participant?.includes(currentUserId);
// Ищем участника с правами редактора
const participant = calendar.participant.find(
(p) => p.participant_calendar == accountStore.user.is_idEmployee,
);
return participant?.editor === true;
}); });
}); });
const canEditEvent = (eventId) => { const canEditEvent = (eventId) => {
const id = Number(eventId); const id = Number(eventId);
return editableEvents.value.some((e) => e.id === id); return editableEvents.value.some((e) => e.id === id);
}; };
@@ -244,6 +247,7 @@ export const useCalendarStore = defineStore('calendarStore', () => {
eventsForSelectedDate, eventsForSelectedDate,
visibleCalendars, visibleCalendars,
allEvents, allEvents,
calendarColorMap,
editableEvents, editableEvents,
canEditEvent, canEditEvent,
+7 -7
View File
@@ -32,7 +32,7 @@ export function checking_for_entry(where, what) {
if (!where.includes(what)) { if (!where.includes(what)) {
where.push(what); where.push(what);
} }
} }
export function getfromserver(path, reactive) { export function getfromserver(path, reactive) {
try { try {
@@ -63,7 +63,7 @@ export function checkremote(filecheck) {
export default str; export default str;
export function splitname(name) { export function splitname(name) {
return name.familyname + " " + name.name[0] + "." + name.parentname[0] + "."; return name.familyname + " " + name.name[0] + "." + name.parentname[0] + ".";
} }
@@ -71,7 +71,7 @@ export function pagecounter() {
// Функция записи посещения страницы сотрудникам. // Функция записи посещения страницы сотрудникам.
// В случае, если в роуте присутствует ключ мета и в нем ико - тогда производится запись // В случае, если в роуте присутствует ключ мета и в нем ико - тогда производится запись
const router = useRouter(); const router = useRouter();
if('meta' in router.currentRoute.value && 'ico' in router.currentRoute.value.meta){ if('meta' in router.currentRoute.value && 'ico' in router.currentRoute.value.meta){
const accountStore = useAccountStore(); const accountStore = useAccountStore();
const appStore = useAppStore(); const appStore = useAppStore();
@@ -95,7 +95,7 @@ export function pagecounter() {
export function useICalReader(url) { export function useICalReader(url) {
/// ///
const events = ref([]); const events = ref([]);
const loadICalFile = async () => { const loadICalFile = async () => {
try { try {
const response = await fetch(url); const response = await fetch(url);
@@ -120,13 +120,13 @@ export function useICalReader(url) {
location: event.location, location: event.location,
} }
}) })
return { return {
type: "calendar", type: "calendar",
title: name, title: name,
calendar: calendarEvents, calendar: calendarEvents,
} }
// const vevents = comp.getAllSubcomponents('vevent') // const vevents = comp.getAllSubcomponents('vevent')
// const eventsData = vevents.map(vevent => ({ // const eventsData = vevents.map(vevent => ({
// vevent: vevent, // vevent: vevent,
@@ -173,4 +173,4 @@ export function useICalReader(url) {
export function declOfNum(value, titles) { export function declOfNum(value, titles) {
const cases = [2, 0, 1, 1, 1, 2]; const cases = [2, 0, 1, 1, 1, 2];
return titles[(value % 100 > 4 && value % 100 < 20) ? 2 : cases[(value % 10 < 5) ? value % 10 : 5]]; return titles[(value % 100 > 4 && value % 100 < 20) ? 2 : cases[(value % 10 < 5) ? value % 10 : 5]];
} }