feat [P-297]: кликабельность событий и навигация в календарь

This commit is contained in:
Inna authored and denzel committed 2026-05-29 09:16:03 +03:00
1 parent 472d67d50c
commit ee66b1c8d6
7 files changed
+403 -532

No files matched your search

@@ -15,6 +15,7 @@ import CustomCalendar from '@/components/calendar_of_events/UI_calendar/CustomCa
import MiniCalendar from '@/components/calendar_of_events/UI_calendar/MiniCalendar.vue'; import MiniCalendar from '@/components/calendar_of_events/UI_calendar/MiniCalendar.vue';
import { useCalendarStore } from '@/store/calendarStore'; import { useCalendarStore } from '@/store/calendarStore';
import { useAccountStore } from '@/store/AccountStore'; import { useAccountStore } from '@/store/AccountStore';
import { useRoute } from 'vue-router';
export default { export default {
components: { MiniCalendar, CustomCalendar }, components: { MiniCalendar, CustomCalendar },
@@ -22,6 +23,7 @@ export default {
const calendarStore = useCalendarStore(); const calendarStore = useCalendarStore();
const accountStore = useAccountStore(); const accountStore = useAccountStore();
const calendarKey = ref(0); const calendarKey = ref(0);
const route = useRoute();
onMounted(() => { onMounted(() => {
const currentYear = new Date().getFullYear(); const currentYear = new Date().getFullYear();
@@ -29,6 +31,9 @@ export default {
calendarStore.loadCalendars(); calendarStore.loadCalendars();
calendarStore.loadDictEmployees(); calendarStore.loadDictEmployees();
calendarStore.loadEmployees(); calendarStore.loadEmployees();
if (route.query.date) {
calendarStore.setSelectedDate(route.query.date);
}
}); });
watch( watch(
@@ -531,15 +531,18 @@ watch(eventCalendar, (newCalendar) => {
} }
}); });
const delEvent = (idev) => { const delEvent = async (idev) => {
axiosApiInstance.delete(`api/calendar_of_events/my_events/?delid=${idev}`).then((result) => { try {
feedalert.alert = true; const result = await axiosApiInstance.delete(`api/calendar_of_events/my_events/?delid=${idev}`)
feedalert.text = result.data.mess; feedalert.alert = true
feedalert.ico = 'mdi-check'; feedalert.text = result.data.mess
feedalert.color = 'orange-accent-1'; feedalert.ico = 'mdi-check'
emit('getCalendar'); feedalert.color = 'orange-accent-1'
}); emit('getCalendar')
emit('closeDialog'); emit('closeDialog')
} catch (e) {
console.error('Ошибка удаления события:', e);
}
}; };
const newFiles = ref([]); const newFiles = ref([]);
@@ -1,185 +1,172 @@
<template> <template>
<v-dialog v-model="internalShow" max-width="700"> <v-card class="pa-0" rounded="lg" elevation="8">
<v-card class="pa-4" min-height="400"> <!-- Акцентная полоса -->
<!-- Заголовок --> <div :style="{ height: '4px', background: calendarColor }" />
<v-card-title class="pr-0 pl-2 d-flex justify-space-between pb-3">
<span class="text-h5 font-weight-medium">Просмотр события</span>
<v-icon
icon="mdi-close"
size="small"
color="grey"
class="cursor-pointer"
@click="closeDialog"
/>
</v-card-title>
<v-divider></v-divider> <!-- Шапка -->
<div class="d-flex align-center justify-space-between pa-5 pb-4">
<div class="d-flex align-center" style="min-width: 0">
<v-avatar :color="calendarColor" size="40" class="mr-3 flex-shrink-0">
<v-icon icon="mdi-calendar-text" color="white" size="22" />
</v-avatar>
<div style="min-width: 0">
<div class="text-caption text-medium-emphasis text-uppercase">
{{ calendarName }}
</div>
<div class="text-h6 font-weight-medium text-truncate" :title="eventData.event?.name">
{{ eventData.event?.name || 'Без названия' }}
</div>
</div>
</div>
<!-- Контент --> <v-btn icon="mdi-close" variant="text" density="comfortable" size="small" @click="closeDialog" />
<v-card-text class="px-2"> </div>
<v-row no-gutters class="flex-column">
<!-- Название события -->
<v-row no-gutters class="align-center border-bottom">
<v-col
style="font-size: 1.1rem; line-height: 1.4"
class="text-body-1 text-text_grey font-weight-medium"
lg="3"
>
Название
</v-col>
<v-col>
<div class="text-body-1" style="font-size: 1.1rem; line-height: 1.4">
{{ eventData.event?.name || 'Без названия' }}
</div>
</v-col>
</v-row>
<!-- Календарь --> <v-divider />
<v-row no-gutters class="align-center pb-3 mb-3 border-bottom">
<v-col class="text-body-1 text-text_grey font-weight-medium" lg="3"> Календарь </v-col>
<v-col>
<div class="d-flex align-center">
<v-avatar size="20" :color="calendarColor" class="mr-3" />
<span class="text-body-1">{{ calendarName }}</span>
</div>
</v-col>
</v-row>
<!-- Участники --> <!-- Контент -->
<v-row <v-card-text class="pa-5">
no-gutters <v-list density="comfortable" bg-color="transparent" class="pa-0">
class="align-start pb-3 mb-3 border-bottom" <!-- Дата и время -->
v-if="participantsList.length > 0" <v-list-item class="px-0">
> <template #prepend>
<v-col class="text-body-1 text-text_grey font-weight-medium pt-1" lg="3"> <v-icon icon="mdi-clock-outline" color="medium-emphasis" class="mr-3" />
</template>
<v-list-item-title class="text-caption text-medium-emphasis">
Дата и время
</v-list-item-title>
<v-list-item-subtitle class="text-body-2 text-high-emphasis mt-1" style="opacity: 1">
<span class="font-weight-medium">
{{ formatDateTime(eventData.event?.date_start, eventData.event?.allday) }}
</span>
<v-icon icon="mdi-arrow-right" size="14" class="mx-2" />
<span class="font-weight-medium">
{{ formatDateTime(eventData.event?.date_end, eventData.event?.allday) }}
</span>
</v-list-item-subtitle>
</v-list-item>
<v-divider class="my-1" />
<!-- Повторение -->
<template v-if="eventData.event?.period">
<v-list-item class="px-0">
<template #prepend>
<v-icon icon="mdi-refresh" color="medium-emphasis" class="mr-3" />
</template>
<v-list-item-title class="text-caption text-medium-emphasis">Повтор</v-list-item-title>
<v-list-item-subtitle class="text-body-2 mt-1" style="opacity: 1">
{{ recurrenceText }}
<span v-if="showRepeatEnd" class="text-medium-emphasis ml-2">
· до {{ formatRepeatEndDate }}
</span>
</v-list-item-subtitle>
</v-list-item>
<v-divider class="my-1" />
</template>
<!-- Участники -->
<template v-if="participantsList.length">
<v-list-item class="px-0">
<template #prepend>
<v-icon icon="mdi-account-multiple-outline" color="medium-emphasis" class="mr-3" />
</template>
<v-list-item-title class="text-caption text-medium-emphasis">
Участники Участники
</v-col> <v-chip size="x-small" variant="tonal" class="ml-2">{{ participantsList.length }}</v-chip>
<v-col> </v-list-item-title>
<div class="participants-list"> <v-list-item-subtitle class="mt-2" style="opacity: 1">
<div <div class="d-flex flex-wrap ga-2">
v-for="participant in participantsList" <v-chip
:key="participant.id" v-for="p in participantsList"
class="text-body-1 mb-1" :key="p.id"
size="small"
variant="tonal"
prepend-icon="mdi-account"
> >
• {{ participant.title }} {{ p.title }}
</div> </v-chip>
</div> </div>
</v-col> </v-list-item-subtitle>
</v-row> </v-list-item>
<v-divider class="my-1" />
</template>
<!-- Дата и время --> <!-- Файлы -->
<v-row no-gutters class="align-top pb-3 mb-3 border-bottom"> <template v-if="eventData.event?.files?.length">
<v-col class="text-body-1 text-text_grey font-weight-medium pt-1" lg="3"> <v-list-item class="px-0">
Дата и время <template #prepend>
</v-col> <v-icon icon="mdi-paperclip" color="medium-emphasis" class="mr-3" />
<v-col class="d-flex flex-column"> </template>
<div class="d-flex align-center gap"> <v-list-item-title class="text-caption text-medium-emphasis">
<div class="text-body-1 font-weight-medium"> Файлы
{{ formatDateTime(eventData.event?.date_start, eventData.event?.allday) }} <v-chip size="x-small" variant="tonal" class="ml-2">
</div> {{ eventData.event.files.length }}
<v-icon icon="mdi-minus" color="grey" class="mx-3" /> </v-chip>
<div class="text-body-1 font-weight-medium"> </v-list-item-title>
{{ formatDateTime(eventData.event?.date_end, eventData.event?.allday) }} <v-list-item-subtitle class="mt-2" style="opacity: 1">
</div> <v-list density="compact" bg-color="transparent" class="pa-0">
</div> <v-list-item
</v-col>
</v-row>
<!-- Повторение -->
<v-row
no-gutters
class="align-center pb-3 mb-3 border-bottom"
v-if="eventData.event?.period"
>
<v-col class="text-body-1 text-text_grey font-weight-medium" lg="3">
Повтор события
</v-col>
<v-col>
<div class="text-body-1">{{ recurrenceText }}</div>
</v-col>
</v-row>
<!-- Окончание события -->
<v-row no-gutters class="align-center pb-3 mb-3 border-bottom" v-if="showRepeatEnd">
<v-col class="text-body-1 text-text_grey font-weight-medium" lg="3">
Окончание события
</v-col>
<v-col>
<div class="text-body-1">
{{ formatRepeatEndDate }}
</div>
</v-col>
</v-row>
<!-- Файлы -->
<v-row
no-gutters
class="align-top pb-3 mb-3 border-bottom"
v-if="eventData.event?.files?.length"
>
<v-col class="text-body-1 text-text_grey font-weight-medium" lg="3"> Файлы </v-col>
<v-col>
<div class="files-list">
<div
v-for="file in eventData.event.files" v-for="file in eventData.event.files"
:key="file.id" :key="file.id"
class="d-flex align-center mb-2 cursor-pointer" :prepend-icon="getFileIcon(file)"
:title="truncateFileName(getFileName(file))"
append-icon="mdi-download"
rounded="md"
variant="tonal"
density="compact"
class="mb-1"
@click="downloadFile(file)" @click="downloadFile(file)"
> />
<v-icon :icon="getFileIcon(file)" color="primary" class="mr-2" size="small" /> </v-list>
<span class="text-body-1 text-primary text-decoration-underline"> </v-list-item-subtitle>
{{ truncateFileName(getFileName(file)) }} </v-list-item>
</span> <v-divider class="my-1" />
</div> </template>
</div>
</v-col>
</v-row>
<!-- Описание --> <!-- Описание -->
<v-row no-gutters class="align-top pb-3" v-if="eventData.event?.description"> <v-list-item v-if="eventData.event?.description" class="px-0">
<v-col class="text-body-1 text-text_grey font-weight-medium" lg="3"> Описание </v-col> <template #prepend>
<v-col> <v-icon icon="mdi-text" color="medium-emphasis" class="mr-3" />
<div class="text-body-1 description-text"> </template>
{{ eventData.event.description }} <v-list-item-title class="text-caption text-medium-emphasis">Описание</v-list-item-title>
</div> <v-list-item-subtitle class="mt-2" style="opacity: 1">
</v-col> <v-sheet
</v-row> rounded="md"
color="surface-light"
class="pa-3"
:style="{ borderLeft: `3px solid ${calendarColor}`, whiteSpace: 'pre-wrap' }"
>
{{ eventData.event.description }}
</v-sheet>
</v-list-item-subtitle>
</v-list-item>
</v-list>
<!-- Если нет данных --> <!-- Пусто -->
<v-row v-if="!eventData.event?.name" class="justify-center mt-8"> <div v-if="!eventData.event?.name" class="text-center py-8">
<v-col class="text-center"> <v-icon size="56" color="grey-lighten-1" icon="mdi-calendar-remove" />
<v-icon size="64" color="grey-lighten-1">mdi-calendar-remove</v-icon> <div class="text-body-1 text-medium-emphasis mt-3">Нет данных о событии</div>
<div class="text-h6 text-grey mt-2">Нет данных о событии</div> </div>
</v-col> </v-card-text>
</v-row>
</v-row>
</v-card-text>
<!-- Кнопки --> <v-divider />
<v-card-actions class="justify-end pa-4 pt-0">
<v-btn <!-- Кнопки -->
v-if="canEdit" <v-card-actions class="pa-4">
width="140" <v-spacer />
color="btn_text"
variant="elevated" <v-btn
prepend-icon="mdi-pencil" v-if="canEdit"
class="text-body-1" :color="calendarColor"
@click="onEdit" variant="elevated"
> prepend-icon="mdi-pencil"
Редактировать @click="onEdit"
</v-btn> >
<v-btn Редактировать
width="120" </v-btn>
@click="closeDialog" </v-card-actions>
color="grey-darken-1" </v-card>
variant="tonal"
class="text-body-1"
>
Закрыть
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</template> </template>
<script> <script>
@@ -192,10 +179,6 @@ export default {
name: 'EventCalendarShow', name: 'EventCalendarShow',
props: { props: {
show: {
type: Boolean,
default: false,
},
eventData: { eventData: {
type: Object, type: Object,
default: () => ({}), default: () => ({}),
@@ -210,31 +193,13 @@ export default {
}, },
}, },
emits: ['update:show', 'close'], emits: ['close'],
setup(props, { emit }) { setup(props, { emit }) {
const internalShow = ref(props.show);
const { parseRecurrenceOptions, isRecurringEvent } = useRecurrence(); const { parseRecurrenceOptions, isRecurringEvent } = useRecurrence();
const calendarStore = useCalendarStore(); const calendarStore = useCalendarStore();
// Синхронизация с внешним состоянием const closeDialog = () => emit('close');
watch(
() => props.show,
(newVal) => {
internalShow.value = newVal;
},
);
watch(internalShow, (newVal) => {
if (!newVal) {
emit('update:show', false);
emit('close');
}
});
const closeDialog = () => {
internalShow.value = false;
};
const calendarInfo = computed(() => { const calendarInfo = computed(() => {
const calendarId = props.eventData.event?.calendar; const calendarId = props.eventData.event?.calendar;
@@ -481,7 +446,6 @@ export default {
}; };
return { return {
internalShow,
closeDialog, closeDialog,
calendarName, calendarName,
calendarColor, calendarColor,
@@ -495,7 +459,7 @@ export default {
showRepeatEnd, showRepeatEnd,
formatRepeatEndDate, formatRepeatEndDate,
canEdit, canEdit,
onEdit onEdit,
}; };
}, },
}; };
@@ -10,13 +10,15 @@
/> />
</v-dialog> </v-dialog>
<event-show <v-dialog v-model="calendarStore.showViewDialog" max-width="700">
v-model:show="calendarStore.showViewDialog" <event-show
:all-calendars="calendarStore.calendars" v-if="calendarStore.showViewDialog"
:event-data="calendarStore.selectedEventForView" :event-data="calendarStore.selectedEventForView"
:employees="calendarStore.employees" :all-calendars="calendarStore.calendars"
@close="calendarStore.closeEventView" :employees="calendarStore.employees"
/> @close="calendarStore.closeEventView"
/>
</v-dialog>
</template> </template>
<script setup> <script setup>
@@ -104,6 +104,7 @@ import { useAccountStore } from '@/store/AccountStore';
import EventsListView from './EventsListView.vue'; import EventsListView from './EventsListView.vue';
import EventListFilters from './EventListFilters.vue'; import EventListFilters from './EventListFilters.vue';
import { useEventListFilters } from '../composables/useEventListFilters'; import { useEventListFilters } from '../composables/useEventListFilters';
import { useRoute } from 'vue-router';
export default { export default {
name: 'CustomCalendar', name: 'CustomCalendar',
@@ -126,6 +127,7 @@ export default {
const calendarStore = useCalendarStore(); const calendarStore = useCalendarStore();
const { selectedDate, lastUpdatedBy, allEvents, calendarColorMap } = storeToRefs(calendarStore); const { selectedDate, lastUpdatedBy, allEvents, calendarColorMap } = storeToRefs(calendarStore);
const { isRecurringEvent, generateRecurringInstances } = useRecurrence(); const { isRecurringEvent, generateRecurringInstances } = useRecurrence();
const route = useRoute();
const calendarApi = computed(() => { const calendarApi = computed(() => {
return calendarRef.value?.getApi?.() || null; return calendarRef.value?.getApi?.() || null;
@@ -471,6 +473,9 @@ export default {
nextTick(() => { nextTick(() => {
calendarApi.value.gotoDate(newDate); calendarApi.value.gotoDate(newDate);
handleDateSelection(newDate); handleDateSelection(newDate);
if (route.query.date && currentView.value !== 'timeGridDay') {
currentView.value = 'timeGridDay';
}
}); });
} }
}); });
@@ -5,11 +5,11 @@
<!-- Месячный календарь --> <!-- Месячный календарь -->
<v-col cols="7" class="pr-2"> <v-col cols="7" class="pr-2">
<div class="calendar-header"> <div class="calendar-header">
<v-btn icon size="small" @click="prevMonth" class="nav-btn"> <v-btn icon size="small" class="nav-btn" @click="prevMonth">
<v-icon>mdi-chevron-left</v-icon> <v-icon>mdi-chevron-left</v-icon>
</v-btn> </v-btn>
<span class="month-title">{{ currentMonth }}</span> <span class="month-title">{{ currentMonth }}</span>
<v-btn icon size="small" @click="nextMonth" class="nav-btn"> <v-btn icon size="small" class="nav-btn" @click="nextMonth">
<v-icon>mdi-chevron-right</v-icon> <v-icon>mdi-chevron-right</v-icon>
</v-btn> </v-btn>
</div> </div>
@@ -17,13 +17,11 @@
<v-table class="month-table"> <v-table class="month-table">
<thead> <thead>
<tr> <tr>
<th v-for="day in russianWeekdays" :key="day" class="weekday-header"> <th v-for="day in WEEKDAYS" :key="day" class="weekday-header">{{ day }}</th>
{{ day }}
</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<tr v-for="(week, weekIndex) in calendarWeeks" :key="weekIndex"> <tr v-for="(week, i) in calendarWeeks" :key="i">
<td <td
v-for="day in week" v-for="day in week"
:key="day.date" :key="day.date"
@@ -35,7 +33,8 @@
'non-working-day': day.isHoliday, 'non-working-day': day.isHoliday,
'grey-background': day.isWeekend, 'grey-background': day.isWeekend,
}" }"
@click="onDateClick(day.date)" @click="selectedDate = day.date"
@dblclick.stop="goToDay(day.date)"
> >
<div class="day-content"> <div class="day-content">
<span class="day-number">{{ day.day }}</span> <span class="day-number">{{ day.day }}</span>
@@ -45,7 +44,7 @@
:key="event.id" :key="event.id"
class="event-indicator" class="event-indicator"
:style="{ backgroundColor: event.color }" :style="{ backgroundColor: event.color }"
></span> />
</div> </div>
</div> </div>
</td> </td>
@@ -64,29 +63,25 @@
<v-card variant="outlined" class="day-schedule" elevation="0"> <v-card variant="outlined" class="day-schedule" elevation="0">
<v-list density="comfortable" class="py-0"> <v-list density="comfortable" class="py-0">
<v-list-item <template v-if="dayEvents.length">
v-for="event in dayEvents" <v-list-item
:key="event.id" v-for="event in dayEvents"
class="schedule-item" :key="event.id"
:class="{ 'current-event': isCurrentEvent(event) }" class="schedule-item"
@click="handleEventClick(event)" :class="{ 'current-event': isCurrentEvent(event) }"
> @click="calendarStore.handleEventClick({ event: { id: event.id } })"
<template #prepend> >
<div <template #prepend>
class="event-color-indicator" <div class="event-color-indicator" :style="{ backgroundColor: event.color }" />
:style="{ backgroundColor: event.color }" </template>
></div> <v-list-item-title class="event-time">{{
</template> formatTime(event.start)
}}</v-list-item-title>
<v-list-item-subtitle class="event-title">{{ event.title }}</v-list-item-subtitle>
</v-list-item>
</template>
<v-list-item-title class="event-time"> <v-list-item v-else class="no-events">
{{ formatTime(event.start) }}
</v-list-item-title>
<v-list-item-subtitle class="event-title">
{{ event.title }}
</v-list-item-subtitle>
</v-list-item>
<v-list-item v-if="dayEvents.length === 0" class="no-events">
<v-list-item-title class="text-grey text-center"> <v-list-item-title class="text-grey text-center">
На этот день событий нет На этот день событий нет
</v-list-item-title> </v-list-item-title>
@@ -99,297 +94,187 @@
</v-card> </v-card>
</template> </template>
<script> <script setup>
import { ref, computed, onMounted, watch } from 'vue'; import { ref, computed, onMounted } from 'vue';
import { storeToRefs } from 'pinia'; import { storeToRefs } from 'pinia';
import { useRouter } from 'vue-router';
import { useCalendarStore } from '@/store/calendarStore'; import { useCalendarStore } from '@/store/calendarStore';
import { useRecurrence } from '@/components/calendar_of_events/composables/useReccurrence'; import { useRecurrence } from '@/components/calendar_of_events/composables/useReccurrence';
export default { const WEEKDAYS = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'];
name: 'HomeCalendarWidget',
setup() { const toLocalDateStr = (date) => {
// Реактивные данные const y = date.getFullYear();
const currentDate = ref(new Date()); const m = String(date.getMonth() + 1).padStart(2, '0');
const selectedDate = ref(''); // Будет установлено в формате YYYY-MM-DD const d = String(date.getDate()).padStart(2, '0');
const currentYear = new Date().getFullYear(); return `${y}-${m}-${d}`;
// Работа с хранилищем
const calendarStore = useCalendarStore();
const { allEvents, calendarColorMap } = storeToRefs(calendarStore);
const { generateRecurringInstances, isRecurringEvent } = useRecurrence();
// Утилиты для работы с датами (главный источник проблем!)
const formatToLocalDate = (date) => {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};
const getStartOfDay = (date) => {
const newDate = new Date(date);
newDate.setHours(0, 0, 0, 0);
return newDate;
};
const areDatesEqual = (date1, date2) => {
return getStartOfDay(date1).getTime() === getStartOfDay(date2).getTime();
};
const events = computed(() => {
const expandedEvents = allEvents.value.flatMap((event) => {
const startDate = new Date(event.date_start);
const endDate = new Date(event.date_end);
const isMultiDay = startDate.toDateString() !== endDate.toDateString();
const hasRecurrence = event.period && event.period !== 'null';
// 1. Периодичное + многодневное
if (hasRecurrence && isMultiDay) {
const instances = generateRecurringInstances(event, 12);
return instances.flatMap((instance) => expandMultiDayInstance(event, instance));
}
// 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 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 calendarWeeks = computed(() => {
const year = currentDate.value.getFullYear();
const month = currentDate.value.getMonth();
const firstDay = new Date(year, month, 1);
const weeks = [];
let week = [];
// Находим понедельник первой недели
const startDay = new Date(firstDay);
startDay.setDate(startDay.getDate() - ((startDay.getDay() + 6) % 7));
// Генерируем 6 недель (фиксированное количество для стабильности)
for (let i = 0; i < 42; i++) {
const currentDay = new Date(startDay);
currentDay.setDate(startDay.getDate() + i);
const dayInfo = calendarStore.isNonWorkingDay(currentDay);
week.push({
day: currentDay.getDate(),
date: formatToLocalDate(currentDay),
isCurrentMonth: currentDay.getMonth() === month,
isHoliday: dayInfo.isHoliday,
isWeekend: dayInfo.isWeekendForStyling,
});
if (week.length === 7) {
weeks.push([...week]);
week = [];
}
}
return weeks;
});
const currentMonth = computed(() => {
return currentDate.value.toLocaleDateString('ru-RU', {
month: 'long',
year: 'numeric',
});
});
const formattedSelectedDate = computed(() => {
if (!selectedDate.value) return '';
// Добавляем время для избежания смещения часовых поясов
const date = new Date(selectedDate.value + 'T12:00:00');
return date.toLocaleDateString('ru-RU', {
day: 'numeric',
month: 'long',
year: 'numeric',
});
});
const dayEvents = computed(() => {
if (!selectedDate.value) return [];
const selected = new Date(selectedDate.value + 'T12:00:00');
return events.value
.filter((event) => {
const eventDate = new Date(event.start);
return areDatesEqual(eventDate, selected);
})
.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime());
});
// Методы
const isToday = (date) => {
const today = new Date();
const checkDate = new Date(date + 'T12:00:00');
return areDatesEqual(today, checkDate);
};
const isSelected = (date) => {
return date === selectedDate.value;
};
const getDayEvents = (date) => {
const checkDate = new Date(date + 'T12:00:00');
return events.value.filter((event) => {
const eventDate = new Date(event.start);
return areDatesEqual(eventDate, checkDate);
});
};
const isCurrentEvent = (event) => {
const now = new Date();
const start = new Date(event.start);
const end = new Date(event.end);
return now >= start && now <= end;
};
const formatTime = (dateString) => {
return new Date(dateString).toLocaleTimeString('ru-RU', {
hour: '2-digit',
minute: '2-digit',
});
};
const onDateClick = (date) => {
selectedDate.value = date;
};
const prevMonth = () => {
const date = new Date(currentDate.value);
date.setMonth(date.getMonth() - 1);
currentDate.value = date;
};
const nextMonth = () => {
const date = new Date(currentDate.value);
date.setMonth(date.getMonth() + 1);
currentDate.value = date;
};
const isWeekendOrHoliday = (dateString) => {
const dayInfo = calendarStore.isNonWorkingDay(dateString);
return dayInfo.isHoliday || dayInfo.isWeekendForStyling;
};
const handleEventClick = (event) => {
calendarStore.handleEventClick({ event: { id: event.id } });
};
onMounted(async () => {
selectedDate.value = formatToLocalDate(new Date());
await calendarStore.fetchHolidays(currentYear);
});
return {
// Реактивные данные
currentDate,
selectedDate,
// Вычисляемые свойства
events,
russianWeekdays,
calendarWeeks,
currentMonth,
formattedSelectedDate,
dayEvents,
isWeekendOrHoliday,
// Методы
isToday,
isSelected,
getDayEvents,
isCurrentEvent,
formatTime,
onDateClick,
prevMonth,
nextMonth,
calendarStore,
allEvents,
expandMultiDayInstance,
formatForWidget,
handleEventClick,
};
},
}; };
const startOfDay = (date) => {
const d = new Date(date);
d.setHours(0, 0, 0, 0);
return d;
};
const datesEqual = (a, b) => startOfDay(a).getTime() === startOfDay(b).getTime();
const router = useRouter();
const calendarStore = useCalendarStore();
const { allEvents, calendarColorMap } = storeToRefs(calendarStore);
const { generateRecurringInstances } = useRecurrence();
const currentDate = ref(new Date());
const selectedDate = ref('');
const prevMonth = () => {
const d = new Date(currentDate.value);
d.setMonth(d.getMonth() - 1);
currentDate.value = d;
};
const nextMonth = () => {
const d = new Date(currentDate.value);
d.setMonth(d.getMonth() + 1);
currentDate.value = d;
};
const goToDay = (date) => {
calendarStore.setSelectedDate(date);
router.push({ name: 'Calendar', query: { date, view: 'day' } });
};
const expandMultiDay = (originalEvent, instance) => {
const start = new Date(instance.date_start || instance.start);
const end = new Date(instance.date_end || instance.end);
const days = [];
const cur = new Date(start);
while (cur < end) {
const dayEnd = new Date(cur);
dayEnd.setDate(dayEnd.getDate() + 1);
days.push({
...originalEvent,
id: instance.id,
date_start: new Date(cur).toISOString(),
date_end: dayEnd.toISOString(),
allday: true,
isMultiDayPart: true,
isRecurringInstance: instance.isRecurringInstance || false,
});
cur.setDate(cur.getDate() + 1);
}
return days;
};
const toWidgetEvent = (event) => ({
id: event.id,
title: event.name || 'Без названия',
start: event.date_start,
end: event.date_end,
color: event.calendarData?.cl_color || calendarColorMap.value?.get(event.calendar) || '#1976d2',
description: event.description,
calendar: event.calendar,
isRecurringInstance: event.isRecurringInstance || false,
isMultiDayPart: event.isMultiDayPart || false,
});
const events = computed(() =>
allEvents.value
.flatMap((event) => {
const start = new Date(event.date_start);
const end = new Date(event.date_end);
const isMultiDay = start.toDateString() !== end.toDateString();
const hasRecur = event.period && event.period !== 'null';
if (hasRecur && isMultiDay) {
return generateRecurringInstances(event, 12).flatMap((inst) => expandMultiDay(event, inst));
}
if (hasRecur && !isMultiDay) {
return generateRecurringInstances(event, 12).map((inst) => ({
...event,
id: inst.id,
date_start: inst.date_start || inst.start,
date_end: inst.date_end || inst.end,
isRecurringInstance: true,
}));
}
if (!hasRecur && isMultiDay) return expandMultiDay(event, event);
return event;
})
.map(toWidgetEvent),
);
const calendarWeeks = computed(() => {
const year = currentDate.value.getFullYear();
const month = currentDate.value.getMonth();
const start = new Date(year, month, 1);
start.setDate(start.getDate() - ((start.getDay() + 6) % 7));
const weeks = [];
let week = [];
for (let i = 0; i < 42; i++) {
const day = new Date(start);
day.setDate(start.getDate() + i);
const info = calendarStore.isNonWorkingDay(day);
week.push({
day: day.getDate(),
date: toLocalDateStr(day),
isCurrentMonth: day.getMonth() === month,
isHoliday: info.isHoliday,
isWeekend: info.isWeekendForStyling,
});
if (week.length === 7) {
weeks.push([...week]);
week = [];
}
}
return weeks;
});
const currentMonth = computed(() =>
currentDate.value.toLocaleDateString('ru-RU', { month: 'long', year: 'numeric' }),
);
const formattedSelectedDate = computed(() => {
if (!selectedDate.value) return '';
return new Date(`${selectedDate.value}T12:00:00`).toLocaleDateString('ru-RU', {
day: 'numeric',
month: 'long',
year: 'numeric',
});
});
const dayEvents = computed(() => {
if (!selectedDate.value) return [];
const sel = new Date(`${selectedDate.value}T12:00:00`);
return events.value
.filter((e) => datesEqual(new Date(e.start), sel))
.sort((a, b) => new Date(a.start) - new Date(b.start));
});
const isToday = (date) => datesEqual(new Date(), new Date(`${date}T12:00:00`));
const isSelected = (date) => date === selectedDate.value;
const getDayEvents = (date) => {
const d = new Date(`${date}T12:00:00`);
return events.value.filter((e) => datesEqual(new Date(e.start), d));
};
const isCurrentEvent = (event) => {
const now = new Date();
return now >= new Date(event.start) && now <= new Date(event.end);
};
const formatTime = (dateStr) =>
new Date(dateStr).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
onMounted(async () => {
selectedDate.value = toLocalDateStr(new Date());
await calendarStore.fetchHolidays(new Date().getFullYear());
});
</script> </script>
<style scoped> <style scoped>
+15 -8
View File
@@ -19,8 +19,8 @@ export const useCalendarStore = defineStore('calendarStore', () => {
const employees = ref([]); const employees = ref([]);
const selectedEvent = ref(null); const selectedEvent = ref(null);
const showEventDialog = ref(false);
const selectedEventForView = ref(null); const selectedEventForView = ref(null);
const showEventDialog = ref(false);
const showViewDialog = ref(false); const showViewDialog = ref(false);
// Массив ID скрытых календарей. Загружаем из localStorage при инициализации. // Массив ID скрытых календарей. Загружаем из localStorage при инициализации.
@@ -292,7 +292,8 @@ export const useCalendarStore = defineStore('calendarStore', () => {
const { data } = await axiosApiInstance.get( const { data } = await axiosApiInstance.get(
`api/calendar_of_events/my_events/?id=${eventId}`, `api/calendar_of_events/my_events/?id=${eventId}`,
); );
selectedEventForView.value = data; selectedEventForView.value = data?.event ? data : { event: data };
showViewDialog.value = true; showViewDialog.value = true;
} catch (error) { } catch (error) {
console.error('Ошибка загрузки события:', error); console.error('Ошибка загрузки события:', error);
@@ -306,19 +307,27 @@ export const useCalendarStore = defineStore('calendarStore', () => {
const handleEventClick = (info) => { const handleEventClick = (info) => {
const id = info.event?.id ?? info.id; const id = info.event?.id ?? info.id;
if (canEditEvent(id)) { if (id) {
openEventDialog(info);
} else {
openEventView(id); openEventView(id);
} }
}; };
const editFromView = () => {
if (!selectedEventForView.value) return;
selectedEvent.value = selectedEventForView.value;
showViewDialog.value = false;
selectedEventForView.value = null;
showEventDialog.value = true;
};
return { return {
// State // State
selectedDate, selectedDate,
events, events,
selectedEvent, selectedEvent,
selectedEventForView,
showEventDialog, showEventDialog,
showViewDialog,
currentView, currentView,
calendars, calendars,
lastUpdatedBy, lastUpdatedBy,
@@ -357,8 +366,6 @@ export const useCalendarStore = defineStore('calendarStore', () => {
loadDictEmployees, loadDictEmployees,
loadEmployees, loadEmployees,
setSelectedEvent, setSelectedEvent,
editFromView,
getEmptyEventWrapper,
buildEventWrapper,
}; };
}); });