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

This commit is contained in:
Inna authored and denzel committed 2026-05-29 09:16:00 +03:00
1 parent 751538189d
commit 472d67d50c
9 files changed
+222 -1096

No files matched your search

@@ -4,225 +4,41 @@
<mini-calendar /> <mini-calendar />
</v-col> </v-col>
<v-col class="d-flex flex-column"> <v-col class="d-flex flex-column">
<custom-calendar <custom-calendar :key="calendarKey" />
:key="calendarKey"
@openEventDialog="openEventDialog"
@openEventView="openEventView"
/>
</v-col> </v-col>
<v-dialog v-model="showEventDialog" max-width="700">
<event-create
@closeDialog="closeEventDialog"
:eventCalendar="eventFromCalendar"
:allCalendars="allCalendars"
@getCalendar="getCalendar"
@update:eventCalendar="eventFromCalendar = $event"
ref="createEvents"
:key="eventKey"
/>
</v-dialog>
<event-calendar-show
v-model:show="showViewDialog"
:all-calendars="allCalendars"
:event-data="selectedEventForView"
@close="handleViewDialogClose"
:employees="calendarStore.employees"
/>
</v-row> </v-row>
</template> </template>
<script> <script>
import { ref, onMounted, watch, computed, provide } from 'vue'; import { ref, onMounted, watch } from 'vue';
import EventCreate from '@/components/calendar_of_events/event-create.vue';
import CustomCalendar from '@/components/calendar_of_events/UI_calendar/CustomCalendar.vue'; import CustomCalendar from '@/components/calendar_of_events/UI_calendar/CustomCalendar.vue';
import { useCalendarStore } from '@/store/calendarStore';
import { storeToRefs } from 'pinia';
import MiniCalendar from '@/components/calendar_of_events/UI_calendar/MiniCalendar.vue'; import MiniCalendar from '@/components/calendar_of_events/UI_calendar/MiniCalendar.vue';
import { axiosApiInstance } from '@/utils/axios-api'; import { useCalendarStore } from '@/store/calendarStore';
import { useAccountStore } from '@/store/AccountStore'; import { useAccountStore } from '@/store/AccountStore';
import EventCalendarShow from '@/components/calendar_of_events/event-calendar-show.vue';
export default { export default {
components: { EventCreate, MiniCalendar, CustomCalendar, EventCalendarShow }, components: { MiniCalendar, CustomCalendar },
setup() { setup() {
const selectdate = ref(new Date());
const MyYear = ref(selectdate.value.getFullYear());
const MyMonth = ref(selectdate.value.getMonth() + 1);
const calendarForMy = ref([]);
const eventFromCalendar = ref({});
const eventKey = ref(0);
const calendarKey = ref(0);
const miniCalendarRef = ref(null);
const calendarStore = useCalendarStore(); const calendarStore = useCalendarStore();
const accountStore = useAccountStore(); const accountStore = useAccountStore();
const showViewDialog = ref(false); const calendarKey = ref(0);
const selectedEventForView = ref({});
const { selectedDate, showEventDialog } = storeToRefs(calendarStore); // синхронизируем с date-picker
const getMonth = (month) => {
MyMonth.value = month + 1;
};
const getYear = (year) => {
MyYear.value = year;
};
const getCalendar = () => {
calendarStore.loadCalendars();
};
const getDictEmployee = () => {
calendarStore.loadDictEmployees();
};
const getEmployees = () => {
calendarStore.loadEmployees();
};
const allCalendars = computed(() => [
...calendarStore.myCalendars,
...calendarStore.subscribedCalendars,
]);
const getEvent = (idEvent) => {
if (!idEvent) {
eventFromCalendar.value = createEmptyEvent();
return;
} else {
axiosApiInstance.get(`api/calendar_of_events/my_events/?id=${idEvent}`).then((res) => {
eventFromCalendar.value = res.data;
calendarStore.openEventDialog();
});
}
};
const createEmptyEvent = () => ({
event: {
name: '',
participant: [accountStore.user.is_idEmployee],
files: [],
date_start: new Date().toISOString(),
date_end: new Date().toISOString(),
period: null,
description: '',
calendar: null,
},
});
const openEventDialog = (selectedEvent) => {
// Всегда сбрасываем данные перед открытием нового диалога
if (!selectedEvent) {
eventFromCalendar.value = createEmptyEvent();
eventKey.value++;
}
getEvent(selectedEvent?.event?.id);
calendarStore.openEventDialog();
};
onMounted(() => { onMounted(() => {
getEvent(); const currentYear = new Date().getFullYear();
calendarStore.fetchHolidays(MyYear.value); calendarStore.fetchHolidays(currentYear);
getDictEmployee(); calendarStore.loadCalendars();
getCalendar(); calendarStore.loadDictEmployees();
getEmployees(); calendarStore.loadEmployees();
}); });
const closeEventDialog = () => {
calendarStore.closeEventDialog();
// При ручном закрытии сбрасываем данные сразу
setTimeout(() => {
eventFromCalendar.value = createEmptyEvent();
eventKey.value++;
}, 200);
};
const openCalendarCreate = () => {
miniCalendarRef.value?.openCalendarCreate();
};
provide('openCalendarCreate', openCalendarCreate);
watch(
() => calendarStore.showEventDialog,
(newValue, oldValue) => {
if (!newValue && oldValue) {
// Диалог был открыт и закрыт не через нашу кнопку
// Добавляем проверку чтобы не сбрасывать при инициализации
if (eventFromCalendar.value.event?.id) {
setTimeout(() => {
eventFromCalendar.value = createEmptyEvent();
eventKey.value++;
}, 200);
}
}
},
);
watch( watch(
() => accountStore.user?.id, () => accountStore.user?.id,
(newUserId, oldUserId) => { (newId, oldId) => {
if (newUserId !== oldUserId) { if (newId !== oldId) calendarKey.value += 1;
console.log('User changed, forcing calendar recreation...');
calendarKey.value += 1; // Изменяем key для пересоздания компонента
}
}, },
); );
const getEventForView = (idEvent) => { return { calendarKey };
if (!idEvent) {
selectedEventForView.value = {};
return;
}
axiosApiInstance.get(`api/calendar_of_events/my_events/?id=${idEvent}`).then((res) => {
selectedEventForView.value = res.data;
showViewDialog.value = true;
});
};
const openEventView = (eventId) => {
if (eventId) {
getEventForView(eventId);
} else {
console.log('❌ No event ID provided');
}
};
// Закрытие модалки
const handleViewDialogClose = () => {
showViewDialog.value = false;
};
return {
selectedDate,
getMonth,
getYear,
showEventDialog,
calendarForMy,
getCalendar,
getEvent,
eventFromCalendar,
calendarStore,
accountStore,
closeEventDialog,
openEventDialog,
createEmptyEvent,
eventKey,
getDictEmployee,
openEventView,
handleViewDialogClose,
showViewDialog,
selectedEventForView,
allCalendars,
eventKey,
calendarKey,
openCalendarCreate,
};
}, },
}; };
</script> </script>
+9 -12
View File
@@ -531,18 +531,15 @@ watch(eventCalendar, (newCalendar) => {
} }
}); });
const delEvent = async (idev) => { const delEvent = (idev) => {
try { axiosApiInstance.delete(`api/calendar_of_events/my_events/?delid=${idev}`).then((result) => {
const result = await axiosApiInstance.delete(`api/calendar_of_events/my_events/?delid=${idev}`) feedalert.alert = true;
feedalert.alert = true feedalert.text = result.data.mess;
feedalert.text = result.data.mess feedalert.ico = 'mdi-check';
feedalert.ico = 'mdi-check' feedalert.color = 'orange-accent-1';
feedalert.color = 'orange-accent-1' emit('getCalendar');
emit('getCalendar') });
emit('closeDialog') emit('closeDialog');
} catch (e) {
console.error('Ошибка удаления события:', e);
}
}; };
const newFiles = ref([]); const newFiles = ref([]);
@@ -91,7 +91,9 @@
class="align-center pb-3 mb-3 border-bottom" class="align-center pb-3 mb-3 border-bottom"
v-if="eventData.event?.period" v-if="eventData.event?.period"
> >
<v-col class="text-body-1 text-text_grey font-weight-medium" lg="3"> Повтор события </v-col> <v-col class="text-body-1 text-text_grey font-weight-medium" lg="3">
Повтор события
</v-col>
<v-col> <v-col>
<div class="text-body-1">{{ recurrenceText }}</div> <div class="text-body-1">{{ recurrenceText }}</div>
</v-col> </v-col>
@@ -155,6 +157,17 @@
<!-- Кнопки --> <!-- Кнопки -->
<v-card-actions class="justify-end pa-4 pt-0"> <v-card-actions class="justify-end pa-4 pt-0">
<v-btn
v-if="canEdit"
width="140"
color="btn_text"
variant="elevated"
prepend-icon="mdi-pencil"
class="text-body-1"
@click="onEdit"
>
Редактировать
</v-btn>
<v-btn <v-btn
width="120" width="120"
@click="closeDialog" @click="closeDialog"
@@ -173,6 +186,7 @@
import { computed, ref, watch } from 'vue'; import { computed, ref, watch } from 'vue';
import { useRecurrence } from '@/components/calendar_of_events/composables/useReccurrence'; import { useRecurrence } from '@/components/calendar_of_events/composables/useReccurrence';
import { RRule } from 'rrule'; import { RRule } from 'rrule';
import { useCalendarStore } from '../../store/calendarStore';
export default { export default {
name: 'EventCalendarShow', name: 'EventCalendarShow',
@@ -201,6 +215,7 @@ export default {
setup(props, { emit }) { setup(props, { emit }) {
const internalShow = ref(props.show); const internalShow = ref(props.show);
const { parseRecurrenceOptions, isRecurringEvent } = useRecurrence(); const { parseRecurrenceOptions, isRecurringEvent } = useRecurrence();
const calendarStore = useCalendarStore();
// Синхронизация с внешним состоянием // Синхронизация с внешним состоянием
watch( watch(
@@ -456,6 +471,15 @@ export default {
return `${nameWithoutExt.slice(0, 20)}...${extension ? '.' + extension : ''}`; return `${nameWithoutExt.slice(0, 20)}...${extension ? '.' + extension : ''}`;
}; };
const canEdit = computed(() => {
const id = props.eventData?.event?.id;
return id ? calendarStore.canEditEvent(id) : false;
});
const onEdit = () => {
calendarStore.editFromView();
};
return { return {
internalShow, internalShow,
closeDialog, closeDialog,
@@ -470,6 +494,8 @@ export default {
truncateFileName, truncateFileName,
showRepeatEnd, showRepeatEnd,
formatRepeatEndDate, formatRepeatEndDate,
canEdit,
onEdit
}; };
}, },
}; };
@@ -10,15 +10,13 @@
/> />
</v-dialog> </v-dialog>
<v-dialog v-model="calendarStore.showViewDialog" max-width="700"> <event-show
<event-show v-model:show="calendarStore.showViewDialog"
v-if="calendarStore.showViewDialog" :all-calendars="calendarStore.calendars"
:event-data="calendarStore.selectedEventForView" :event-data="calendarStore.selectedEventForView"
:all-calendars="calendarStore.calendars" :employees="calendarStore.employees"
:employees="calendarStore.employees" @close="calendarStore.closeEventView"
@close="calendarStore.closeEventView" />
/>
</v-dialog>
</template> </template>
<script setup> <script setup>
@@ -107,8 +107,6 @@ import { useEventListFilters } from '../composables/useEventListFilters';
export default { export default {
name: 'CustomCalendar', name: 'CustomCalendar',
emits: ['openEventDialog', 'openEventView'],
components: { components: {
EventsListView, EventsListView,
EventListFilters, EventListFilters,
@@ -119,7 +117,7 @@ export default {
view: { type: String, default: 'dayGridMonth' }, view: { type: String, default: 'dayGridMonth' },
}, },
setup(props, { emit }) { setup(props) {
const currentView = ref('dayGridMonth'); const currentView = ref('dayGridMonth');
const currentTitle = ref('Календарь'); const currentTitle = ref('Календарь');
const calendarRef = ref(null); const calendarRef = ref(null);
@@ -142,11 +140,7 @@ export default {
})); }));
const handleEventClick = (info) => { const handleEventClick = (info) => {
if (calendarStore.canEditEvent(info.event.id)) { calendarStore.handleEventClick(info);
emit('openEventDialog', info);
} else {
emit('openEventView', info.event.id);
}
}; };
const calendarOptions = ref({ const calendarOptions = ref({
@@ -433,7 +427,7 @@ export default {
} }
}; };
onMounted(async () => { onMounted(async () => {
const currentYear = new Date().getFullYear(); const currentYear = new Date().getFullYear();
calendarStore.fetchHolidays(currentYear); calendarStore.fetchHolidays(currentYear);
// Ждем следующего тика для гарантии, что календарь инициализирован // Ждем следующего тика для гарантии, что календарь инициализирован
@@ -621,6 +615,7 @@ export default {
} }
:deep(.grey-background), :deep(.grey-background),
:deep(.fc-daygrid-day),
:deep(.fc-day.grey-background) { :deep(.fc-day.grey-background) {
background-color: rgb(var(--v-theme-weekend_bg)) !important; background-color: rgb(var(--v-theme-weekend_bg)) !important;
} }
@@ -69,6 +69,7 @@
:key="event.id" :key="event.id"
class="schedule-item" class="schedule-item"
:class="{ 'current-event': isCurrentEvent(event) }" :class="{ 'current-event': isCurrentEvent(event) }"
@click="handleEventClick(event)"
> >
<template #prepend> <template #prepend>
<div <div
@@ -348,6 +349,10 @@ export default {
return dayInfo.isHoliday || dayInfo.isWeekendForStyling; return dayInfo.isHoliday || dayInfo.isWeekendForStyling;
}; };
const handleEventClick = (event) => {
calendarStore.handleEventClick({ event: { id: event.id } });
};
onMounted(async () => { onMounted(async () => {
selectedDate.value = formatToLocalDate(new Date()); selectedDate.value = formatToLocalDate(new Date());
await calendarStore.fetchHolidays(currentYear); await calendarStore.fetchHolidays(currentYear);
@@ -381,6 +386,7 @@ export default {
allEvents, allEvents,
expandMultiDayInstance, expandMultiDayInstance,
formatForWidget, formatForWidget,
handleEventClick,
}; };
}, },
}; };
@@ -455,19 +461,6 @@ export default {
opacity: 0.5; opacity: 0.5;
} }
.day-cell.today {
background-color: rgba(var(--v-theme-primary), 0.15);
}
.day-cell.selected {
background-color: rgb(var(--v-theme-btn_text));
color: rgb(var(--v-theme-bg_white));
}
.day-cell.selected .day-number {
color: rgb(var(--v-theme-bg_white));
}
.day-content { .day-content {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -547,7 +540,6 @@ export default {
.event-time { .event-time {
font-size: 0.8rem; font-size: 0.8rem;
font-weight: 600; font-weight: 600;
color: #302f2f;
color: rgb(var(--v-theme-text_carous)); color: rgb(var(--v-theme-text_carous));
margin-bottom: 2px; margin-bottom: 2px;
} }
@@ -573,17 +565,17 @@ export default {
} }
.day-schedule::-webkit-scrollbar-track { .day-schedule::-webkit-scrollbar-track {
background: #f1f1f1; background: rgba(var(--v-theme-on-surface), 0.05);
border-radius: 0 8px 8px 0; border-radius: 0 8px 8px 0;
} }
.day-schedule::-webkit-scrollbar-thumb { .day-schedule::-webkit-scrollbar-thumb {
background: #c1c1c1; background: rgba(var(--v-theme-on-surface), 0.25);
border-radius: 3px; border-radius: 3px;
} }
.day-schedule::-webkit-scrollbar-thumb:hover { .day-schedule::-webkit-scrollbar-thumb:hover {
background: #a8a8a8; background: rgba(var(--v-theme-on-surface), 0.4);
} }
.non-working-day { .non-working-day {
@@ -598,4 +590,15 @@ export default {
.day-cell:not(.current-month).non-working-day { .day-cell:not(.current-month).non-working-day {
color: inherit !important; color: inherit !important;
} }
.day-cell.selected,
.day-cell.selected.grey-background,
.day-cell.selected.non-working-day {
background-color: rgb(var(--v-theme-btn_text)) !important;
color: rgb(var(--v-theme-bg_white)) !important;
}
.day-cell.selected .day-number {
color: rgb(var(--v-theme-bg_white)) !important;
}
</style> </style>
@@ -27,16 +27,10 @@
<v-col v-for="(x, key) in color" :key="key"> <v-col v-for="(x, key) in color" :key="key">
<v-avatar <v-avatar
class="cursor-pointer" class="cursor-pointer"
:class="{ 'avatar-dimmed': propsCalendar.cl_color && propsCalendar.cl_color !== x }"
@click="colorPik(x, key)" @click="colorPik(x, key)"
size="x-small" size="x-small"
:color="x" :color="x"
:variant="
propsCalendar.cl_color === null
? 'flat'
: propsCalendar.cl_color === x
? 'flat'
: 'tonal'
"
/> </v-col /> </v-col
></v-row> ></v-row>
@@ -235,23 +229,6 @@ export default {
'#22c55e', // Зеленый '#22c55e', // Зеленый
]; ];
// const color = [
// '#3b82f6', // Синий
// '#10b981', // Зеленый
// '#dc2626', // Красный
// '#d97706', // Оранжевый
// '#7c3aed', // Фиолетовый
// '#0ea5e9', // Голубой
// '#84cc16', // Лаймовый
// '#f59e0b', // Янтарный
// '#8b5cf6', // Пурпурный
// '#06b6d4', // Бирюзовый
// '#f97316', // Теплый оранжевый
// '#6366f1', // Фиолетово-синий
// '#14b8a6', // Морской волны
// '#ec4899', // Розовый
// '#64748b', // Серо-синий
// ];
const colorPik = (col) => { const colorPik = (col) => {
if (propsCalendar.value.cl_color === col) { if (propsCalendar.value.cl_color === col) {
propsCalendar.value.cl_color = null; propsCalendar.value.cl_color = null;
@@ -299,4 +276,13 @@ export default {
.custom-tooltip { .custom-tooltip {
max-width: 350px; /* Установка максимальной ширины для подсказки */ max-width: 350px; /* Установка максимальной ширины для подсказки */
} }
.avatar-dimmed {
opacity: 0.45;
transition: opacity 0.15s ease;
}
.avatar-dimmed:hover {
opacity: 0.8;
}
</style> </style>
@@ -1,786 +0,0 @@
<template>
<dialog-create
:title="titleCard"
:newOrOld="isNewEvent"
@postData="postData"
@closeDialog="$emit('closeDialog')"
@delObject="delEvent(propsEvent?.event?.id)"
ref="createDialog"
>
<template v-slot:card_text>
<v-row no-gutters class="flex-column">
<v-col class="d-flex flex-column">
<v-row no-gutters class="align-center">
<v-col class="text-body-2 text-text_grey pb-5" lg="2"> Название </v-col>
<v-col>
<v-textarea
density="compact"
label="Добавить название"
row-height="25"
rows="1"
variant="outlined"
v-model="propsEvent.event.name"
:rules="rules.name"
></v-textarea> </v-col
></v-row>
<v-row no-gutters class="align-center">
<v-col class="text-body-2 text-text_grey pb-5" lg="2"> Участники </v-col>
<v-col>
<calendar-create-select
:staff="newStaff"
@returnIdParticant="returnIdParticant"
:authorID="currentCalendarAuthorId"
/> </v-col
></v-row>
<v-row no-gutters class="align-center pb-3">
<v-col class="text-body-2 text-text_grey" lg="2"> Календарь</v-col>
<v-col>
<v-autocomplete
v-model="myCalendar"
:items="safeCalendars"
label="Выберите календарь или найдите по названию"
item-title="cl_name"
item-value="id"
hide-details
variant="outlined"
density="compact"
class="py-3 my-select"
return-object
:rules="rules.calendar"
:disabled="'id' in propsEvent.event"
auto-select-first
>
<template v-slot:selection="{ item }">
<v-avatar class="cursor-pointer" size="8" :color="item.raw.cl_color" />
<span class="pl-2">
{{ item.title }}
</span>
</template>
<template v-slot:item="{ item, props }">
<v-list-item
:key="item.raw.id"
:value="item"
color="primary"
v-bind="props"
@click.stop="handleCalendarSelect(item.raw)"
:data-calendar-id="item.raw.id"
>
<template v-slot:prepend>
<v-avatar class="cursor-pointer" size="8" :color="item.raw.cl_color" />
</template>
<!-- {{ item.title }} -->
</v-list-item>
</template>
</v-autocomplete>
</v-col></v-row
>
<v-row no-gutters class="align-top">
<v-col class="text-body-2 text-text_grey pt-3" lg="2"> Дата и время </v-col>
<v-col class="d-flex flex-column">
<v-row no-gutters class="gap">
<time-select
:rule="selectedRule.rule ? selectedRule.rule.freq : -1"
:isAllDay="propsEvent.event.allday"
:order="[2, 1]"
:dateEvent="String(propsEvent.event.date_start)"
:limitation="String(propsEvent.event.date_end)"
@update:dateEvent="updateDateStart"
@adjustEndDate="handleAutoAdjustEnd"
/>
<v-col class="order-3 flex-grow-0">
<v-icon icon="mdi-minus pt-4" color="grey-darken-1" />
</v-col>
<time-select
:rule="selectedRule.rule ? selectedRule.rule.freq : -1"
:isAllDay="propsEvent.event.allday"
:order="[4, 5]"
:dateEvent="String(propsEvent.event.date_end)"
:limitation="String(propsEvent.event.date_start)"
@update:dateEvent="updateDateEnd"
@adjustEndDate="handleAutoAdjustEnd"
/>
</v-row>
<v-row no-gutters>
<period-events
:dateEvent="propsEvent.event"
@update:dateEvent="propsEvent.event = $event"
/>
</v-row>
</v-col>
</v-row>
</v-col>
<v-row no-gutters class="align-top mt-3">
<v-col class="text-body-2 text-text_grey" lg="2"> Повтор события </v-col>
<v-col class="d-flex flex-column">
<!-- Выбор типа повторения -->
<v-autocomplete
v-model="selectedRule"
:items="repeatRules"
variant="outlined"
density="compact"
return-object
item-title="type"
item-value="id"
@update:model-value="updatePeriodRule"
hide-details
/>
<!-- Окончание повторения -->
<v-row class="align-center mt-2" style="height: 54px" no-gutters>
<v-col cols="5">
<v-checkbox
v-model="showRepeatEnd"
:disabled="isRepeatEndDisabled"
density="compact"
hide-details
label="Окончание повторения"
/>
</v-col>
<v-col cols="4">
<time-select
:showTime="false"
:order="[1, 2]"
:dateEvent="repeatEndDate ? String(repeatEndDate) : String(new Date())"
@update:dateEvent="updateRepeatEndDate"
class="wide-time-select"
:limitation="String(propsEvent.event.date_start)"
:isEndDateEnabled="!showRepeatEnd"
/>
</v-col>
</v-row>
</v-col>
</v-row>
<v-row
no-gutters
class="align-start d-flex pt-3 mb-3"
style="height: auto; min-height: 100px; max-height: 300px"
>
<v-col class="text-body-2 text-text_grey pb-5 pt-3" lg="2"> Файлы </v-col>
<uploading-file
v-model:new-files="newFiles"
:files="propsEvent.event.files"
@update:files="handleFilesUpdate"
@postFiles="postFiles"
/>
</v-row>
<v-row no-gutters class="align-center pt-6">
<v-col>
<v-textarea
density="compact"
label="Дополнительное описание"
rows="3"
variant="outlined"
auto-grow
v-model="propsEvent.event.description"
class="scrollable-textarea pt-3"
></v-textarea> </v-col
></v-row>
</v-row>
</template>
</dialog-create>
</template>
<script setup>
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import { axiosApiInstance } from '@/utils/axios-api';
import { useAccountStore } from '@/store/AccountStore';
import DialogCreate from '@/components/calendar_of_events/UI_calendar/dialogCreate.vue';
import calendarCreateSelect from '@/components/calendar_of_events/calendar-create-select.vue';
import TimeSelect from '@/components/calendar_of_events/UI_calendar/timeSelect.vue';
import UploadingFile from '@/components/UI/defaultportal/uploading-file.vue';
import ReminderEvent from '@/components/calendar_of_events/UI_calendar/reminderEvent.vue';
import PeriodEvents from '@/components/calendar_of_events/UI_calendar/periodEvents.vue';
import { useAlertStore } from '@/store/UseAlertStore';
import { RRule } from 'rrule';
import { useRecurrence } from '@/components/calendar_of_events/composables/useReccurrence';
import { useCalendarStore } from '../../store/calendarStore';
const props = defineProps({
eventCalendar: Object,
allCalendars: Array,
selectedRule: Object,
});
const emit = defineEmits(['update:eventCalendar', 'getCalendar', 'closeDialog']);
const accountStore = useAccountStore();
const calendarStore = useCalendarStore();
const createDialog = ref(null);
const { parseRecurrenceOptions, isRecurringEvent } = useRecurrence();
const propsEvent = computed({
get: () => {
return props.eventCalendar;
},
set: (value) => emit('update:eventCalendar', value),
});
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;
}
});
const newStaff = computed({
get() {
let filteredStaff = [];
if (isNewEvent.value) {
if (myCalendar.value == null) return [];
const participants = myCalendar.value.participant || [];
const calendarParticipantIds = new Set(participants.map((p) => p.participant_calendar));
// Мутируем И фильтруем для НОВОГО события
filteredStaff = calendarStore.employees
.map((department) => {
// ФИЛЬТРУЕМ сотрудников - оставляем только тех, кто в календаре
const filteredEmployees = department.employees.filter((employee) =>
calendarParticipantIds.has(employee.id),
);
// МУТАЦИЯ: устанавливаем selected=true для отфильтрованных сотрудников
filteredEmployees.forEach((employee) => {
employee.selected = true;
});
return {
...department,
employees: filteredEmployees,
};
})
.filter((dept) => dept.employees.length > 0);
} else {
// СУЩЕСТВУЮЩЕЕ СОБЫТИЕ - фильтр по календарю
const eventCalendarId = propsEvent.value.event.calendar;
const currentCalendar = propsEvent.value.mycalendars?.find(
(cal) => parseInt(cal.id) === parseInt(eventCalendarId),
);
if (!currentCalendar?.participant) return [];
const calendarParticipantIds = new Set(currentCalendar.participant.map((p) => p.id));
const eventParticipantIds = new Set(propsEvent.value.event.participant || []);
// Мутируем И фильтруем для СУЩЕСТВУЮЩЕГО события
filteredStaff = calendarStore.employees
.map((department) => {
// ФИЛЬТРУЕМ сотрудников - оставляем только тех, кто в календаре
const filteredEmployees = department.employees.filter((employee) =>
calendarParticipantIds.has(employee.id),
);
// МУТАЦИЯ: устанавливаем selected на основе участников события
filteredEmployees.forEach((employee) => {
employee.selected =
employee.id === accountStore.user.is_idEmployee ||
eventParticipantIds.has(employee.id);
});
return {
...department,
employees: filteredEmployees,
};
})
.filter((dept) => dept.employees.length > 0);
}
return filteredStaff;
},
});
// ВАЛИДАЦИЯ
const rules = {
name: [
(val) => !!val || 'Поле обязательно для заполнения',
(val) => (val && val.length >= 3) || 'Минимум 3 символа',
(val) => (val && val.length <= 100) || 'Максимум 100 символов',
],
calendar: [(val) => !!val || 'Выберите календарь'],
};
const repeatRules = [
{ type: 'Не повторять', rule: null, id: 1 },
{
type: 'Каждый день',
rule: { freq: RRule.DAILY },
id: 2,
},
{
type: 'Каждую неделю',
rule: { freq: RRule.WEEKLY },
// По умолчанию - в тот же день недели, что и начальная дата
getRule: (startDate) => {
const day = new Date(startDate).getDay();
// Преобразуем день недели в формат RRule (0 — понедельник)
const byweekday = [day === 0 ? RRule.SU : day - 1];
return { freq: RRule.WEEKLY, byweekday };
},
id: 3,
},
{
type: 'Каждый месяц',
rule: { freq: RRule.MONTHLY },
// По умолчанию - в тот же день месяца
getRule: (startDate) => ({
freq: RRule.MONTHLY,
bymonthday: [new Date(startDate).getDate()],
}),
id: 4,
},
{
type: 'Каждый квартал',
rule: { freq: RRule.MONTHLY, interval: 3 },
getRule: (startDate) => {
const date = new Date(startDate);
return {
freq: RRule.MONTHLY,
interval: 3, // каждые 3 месяца
bymonthday: [date.getDate()],
};
},
id: 6,
},
{
type: 'Каждый год',
rule: { freq: RRule.YEARLY },
// По умолчанию - в тот же день и месяц
getRule: (startDate) => {
const date = new Date(startDate);
return {
freq: RRule.YEARLY,
bymonth: [date.getMonth() + 1],
bymonthday: [date.getDate()],
};
},
id: 5,
},
];
const selectedRule = ref(repeatRules[0]);
const showRepeatEnd = ref(false);
const repeatEndDate = ref(new Date());
// Инициализация повторов при редактировании
const initializeRule = () => {
if (!propsEvent.value.event.period) {
selectedRule.value = repeatRules[0]; // "Не повторять"
repeatEndDate.value = propsEvent.value.event.date_end
? new Date(propsEvent.value.event.date_end)
: new Date();
return;
}
try {
// Используем isRecurringEvent для проверки
if (isRecurringEvent(propsEvent.value.event)) {
// Парсим period с использованием parseRecurrenceOptions
const rruleOptions = parseRecurrenceOptions(
propsEvent.value.event.period,
propsEvent.value.event.date_start,
);
if (rruleOptions) {
// ОБНОВЛЕННЫЙ ПОИСК ПРАВИЛА С ПОДДЕРЖКОЙ КВАРТАЛОВ
let foundRule;
// Для квартальных событий (MONTHLY с interval=3)
if (rruleOptions.freq === RRule.MONTHLY && rruleOptions.interval === 3) {
foundRule = repeatRules.find((rule) => rule.id === 6); // ID квартального правила
} else {
// Для остальных типов - ищем по freq
foundRule = repeatRules.find((rule) => rule.rule?.freq === rruleOptions.freq);
}
selectedRule.value = foundRule || repeatRules[0];
// ВАЖНО: инициализируем repeatEndDate и showRepeatEnd
if (rruleOptions.until) {
// Если в RRULE есть UNTIL, используем эту дату
repeatEndDate.value = new Date(rruleOptions.until);
showRepeatEnd.value = true;
} else {
// Если нет UNTIL, используем date_end события
repeatEndDate.value = propsEvent.value.event.date_end
? new Date(propsEvent.value.event.date_end)
: new Date();
showRepeatEnd.value = false;
}
}
} else {
selectedRule.value = repeatRules[0];
showRepeatEnd.value = false;
repeatEndDate.value = propsEvent.value.event.date_end
? new Date(propsEvent.value.event.date_end)
: new Date();
}
} catch (error) {
console.error('Error parsing period:', error, 'Raw period:', propsEvent.value.event.period);
selectedRule.value = repeatRules[0];
showRepeatEnd.value = false;
repeatEndDate.value = propsEvent.value.event.date_end
? new Date(propsEvent.value.event.date_end)
: new Date();
}
};
const isRepeatEndDisabled = computed(() => {
return !selectedRule.value.rule; // disabled если правило null (не повторять)
});
const feedalert = useAlertStore().alert;
const titleCard = computed(() => {
if (propsEvent.value.event.hasOwnProperty('id')) {
return 'Редактирование события';
} else {
return 'Новое событие';
}
});
const isNewEvent = computed(() => !propsEvent.value.event.hasOwnProperty('id'));
const myCalendar = ref(null);
const safeCalendars = computed(() => {
const userId = accountStore.user.is_idEmployee;
// return (props.allCalendars || []).filter((calendar) => {
// // Пользователь - автор календаря (полные права)
// if (calendar.author === userId) {
// return true;
// }
// // Пользователь - участник с правами редактора
// const participant = calendar.participant?.find((p) => p.participant_calendar === userId);
// return participant?.editor === true;
// });
let filtered = (props.allCalendars || []).filter((calendar) => {
if (calendar.author === userId) return true;
const participant = calendar.participant?.find((p) => p.participant_calendar === userId);
return participant?.editor === true;
});
// Добавляем пункт "Создать календарь"
filtered.push({
id: 'create_new',
cl_name: '➕ Создать календарь',
isFake: true,
});
return filtered;
});
const isCalendarsReady = computed(() => safeCalendars.value.length > 0);
// Computed для календаря события
const eventCalendar = computed(() => {
if (!propsEvent.value?.event?.calendar || !safeCalendars.value.length) return null;
return safeCalendars.value.find((cal) => cal.id === propsEvent.value.event.calendar);
});
// Единоразовая инициализация при монтировании/получении данных
const initializeCalendar = () => {
if (myCalendar.value) return; // Уже инициализирован
// Приоритет 1: календарь из события (редактирование)
if (eventCalendar.value) {
myCalendar.value = eventCalendar.value;
return;
}
// Приоритет 2: первый доступный календарь (создание)
if (safeCalendars.value.length > 0) {
// myCalendar.value = safeCalendars.value[0];
const firstRealCalendar = safeCalendars.value.find((cal) => cal.id !== 'create_new');
if (firstRealCalendar) {
myCalendar.value = firstRealCalendar;
}
}
};
// Инициализируем когда все готово
watch(
[() => safeCalendars.value.length, () => propsEvent.value],
(newCalendar) => {
initializeCalendar();
},
{ immediate: true, deep: true },
);
// Дополнительная защита - вотчер только на смену самого календаря
watch(eventCalendar, (newCalendar) => {
if (newCalendar && newCalendar.id !== myCalendar.value?.id) {
myCalendar.value = newCalendar;
}
});
const delEvent = (idev) => {
axiosApiInstance.delete(`api/calendar_of_events/my_events/?delid=${idev}`).then((result) => {
feedalert.alert = true;
feedalert.text = result.data.mess;
feedalert.ico = 'mdi-check';
feedalert.color = 'orange-accent-1';
emit('getCalendar');
});
emit('closeDialog');
};
const newFiles = ref([]);
const handleFilesUpdate = (updatedExistingFiles) => {
// Сохраняем новые файлы во временную переменную
const currentNewFiles = [...newFiles.value];
// Обновляем существующие файлы
propsEvent.value.event.files = updatedExistingFiles;
// Восстанавливаем новые файлы
newFiles.value = currentNewFiles;
};
const postFiles = (updatedFiles) => {
newFiles.value = updatedFiles;
};
const returnIdParticant = (idPart) => {
idPart.staff.forEach((e) => {
if (e.selected == true && !propsEvent.value.event.participant.includes(e.id)) {
propsEvent.value.event.participant.push(e.id);
} else {
let ind = propsEvent.value.event.participant.findIndex((l) => l == e.id);
if (ind != -1) {
propsEvent.value.event.participant.splice(ind, 1);
}
}
});
};
const cbSelect = (item, arr) => {
item.forEach((e) => {
if (!('employees' in e)) {
if (!propsEvent.value.event.participant.includes(e.id)) {
propsEvent.value.event.participant.push(e.id);
}
}
if ('employees' in e) {
cbSelect(e.employees);
}
});
};
const postData = async (validate) => {
if (validate) {
await nextTick();
updatePeriodRule(selectedRule.value);
propsEvent.value.event.calendar = myCalendar.value.id;
let postEvent = new FormData();
postEvent.append(
'event',
JSON.stringify({ ...propsEvent.value.event, files: propsEvent.value.event.files }),
);
if (propsEvent.value.event.files !== null) {
// 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) => {
feedalert.alert = true;
feedalert.text = result.data.mess;
feedalert.ico = 'mdi-check';
feedalert.color = 'green-darken-4';
emit('getCalendar');
emit('closeDialog');
});
}
};
const handleAutoAdjustEnd = (newEndDate) => {
propsEvent.value.event.date_end = newEndDate;
};
const updateRepeatEndDate = (date) => {
repeatEndDate.value = date;
updatePeriodRule(selectedRule.value); // Пересоздаем правило с новой датой
};
watch(selectedRule, (newRule) => {
if (!newRule.rule) {
showRepeatEnd.value = false;
repeatEndDate.value = null;
}
});
const updateDateStart = (newDate) => {
// Нормализуем к ISO строке
const normalizedDate = new Date(newDate).toISOString();
propsEvent.value.event.date_start = normalizedDate;
// При изменении даты начала - обновляем правило повторений
const startDate = new Date(normalizedDate);
const endDate = new Date(propsEvent.value.event.date_end);
if (startDate > endDate) {
const adjustedEnd = new Date(startDate);
adjustedEnd.setHours(startDate.getHours() + 1);
propsEvent.value.event.date_end = adjustedEnd.toISOString(); // Тоже ISO
}
if (selectedRule.value.rule) {
updatePeriodRule(selectedRule.value);
}
};
const updateDateEnd = (newDate) => {
// Нормализуем к ISO строке
propsEvent.value.event.date_end = new Date(newDate).toISOString();
};
// функция обновления периода
const updatePeriodRule = (rule) => {
selectedRule.value = rule;
if (!rule.rule) {
propsEvent.value.event.period = null;
return;
}
const dtstart = new Date(propsEvent.value.event.date_start);
const localDtstart = new Date(
dtstart.getFullYear(),
dtstart.getMonth(),
dtstart.getDate(),
dtstart.getHours(),
dtstart.getMinutes(),
dtstart.getSeconds(),
);
const ruleOptions = {
...rule.rule,
dtstart: localDtstart,
};
if (showRepeatEnd.value && repeatEndDate.value) {
const untilDate = new Date(repeatEndDate.value);
ruleOptions.until = new Date(
untilDate.getFullYear(),
untilDate.getMonth(),
untilDate.getDate(),
untilDate.getHours(),
untilDate.getMinutes(),
untilDate.getSeconds(),
);
}
if (rule.rule.freq === RRule.WEEKLY) {
const day = new Date(propsEvent.value.event.date_start).getDay();
// Преобразуем день недели в формат RRule (0 — понедельник)
const byweekday = [day === 0 ? RRule.SU : day - 1];
ruleOptions.byweekday = byweekday;
}
if (rule.rule.freq === RRule.MONTHLY) {
ruleOptions.bymonthday = [new Date(propsEvent.value.event.date_start).getDate()];
}
if (rule.rule.freq === RRule.YEARLY) {
const date = new Date(propsEvent.value.event.date_start);
ruleOptions.bymonth = [date.getMonth() + 1];
ruleOptions.bymonthday = [date.getDate()];
}
const rrule = new RRule(ruleOptions);
propsEvent.value.event.period = rrule.toString();
};
watch(
() => propsEvent.value.event?.period,
(newPeriod) => {
if (newPeriod) {
initializeRule();
}
},
{ immediate: true },
);
watch([safeCalendars, myCalendar], (newCalendar) => {}, { deep: true, immediate: true });
function handleCalendarSelect(calendar) {
if (calendar.id === 'create_new') {
if (window.$createCalendar) {
// Запоминаем максимальный ID до создания
const maxIdBefore = Math.max(
...safeCalendars.value.filter((cal) => cal.id !== 'create_new').map((cal) => cal.id),
);
window.$createCalendar();
// Следим за появлением календаря с ID больше максимального
const unwatch = watch(
safeCalendars,
(newCalendars) => {
const realCalendars = newCalendars.filter((cal) => cal.id !== 'create_new');
const newCalendar = realCalendars.find((cal) => cal.id > maxIdBefore);
if (newCalendar) {
myCalendar.value = newCalendar;
unwatch();
}
},
{ deep: true },
);
setTimeout(() => unwatch(), 5000);
}
return;
}
myCalendar.value = calendar;
}
</script>
<style>
.scrollable-textarea {
overflow-y: auto;
max-height: 160px;
}
.scrollable-textarea::-webkit-scrollbar {
width: 6px;
}
.scrollable-textarea::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 3px;
}
.scrollable-textarea::-webkit-scrollbar-thumb {
background: #c1c1c1;
border-radius: 1px;
}
.scrollable-textarea::-webkit-scrollbar-thumb:hover {
background: #a8a8a8;
}
</style>
+132 -41
View File
@@ -9,8 +9,6 @@ export const useCalendarStore = defineStore('calendarStore', () => {
// State // State
const selectedDate = ref(new Date()); const selectedDate = ref(new Date());
const events = ref([]); const events = ref([]);
const selectedEvent = ref(null);
const showEventDialog = ref(false);
const currentView = ref('dayGridMonth'); // Текущий вид календаря const currentView = ref('dayGridMonth'); // Текущий вид календаря
const calendars = ref([]); // Список календарей пользователя const calendars = ref([]); // Список календарей пользователя
const lastUpdatedBy = ref(null); const lastUpdatedBy = ref(null);
@@ -20,6 +18,11 @@ export const useCalendarStore = defineStore('calendarStore', () => {
const dictEmployeesLoaded = ref(false); const dictEmployeesLoaded = ref(false);
const employees = ref([]); const employees = ref([]);
const selectedEvent = ref(null);
const showEventDialog = ref(false);
const selectedEventForView = ref(null);
const showViewDialog = ref(false);
// Массив ID скрытых календарей. Загружаем из localStorage при инициализации. // Массив ID скрытых календарей. Загружаем из localStorage при инициализации.
const hiddenCalendarIds = ref([]); const hiddenCalendarIds = ref([]);
@@ -175,60 +178,141 @@ export const useCalendarStore = defineStore('calendarStore', () => {
return editableEvents.value.some((e) => e.id === id); return editableEvents.value.some((e) => e.id === id);
}; };
const fetchHolidays = async (year) => { const fetchHolidays = async (year) => {
if (holidays.value[year] || loadingYears.value.has(year)) { if (holidays.value[year] || loadingYears.value.has(year)) {
return holidays.value[year]; return holidays.value[year];
} }
loadingYears.value.add(year); loadingYears.value.add(year);
try { try {
const { data } = await axiosApiInstance.get( const { data } = await axiosApiInstance.get(
`api/calendar_of_events/exclusion_dates/?year=${year}`, `api/calendar_of_events/exclusion_dates/?year=${year}`,
); );
holidays.value = { ...holidays.value, ...data }; holidays.value = { ...holidays.value, ...data };
return holidays.value[year]; return holidays.value[year];
} catch (err) { } catch (err) {
console.error('Ошибка загрузки праздников:', err); console.error('Ошибка загрузки праздников:', err);
throw err; throw err;
} finally { } finally {
loadingYears.value.delete(year); loadingYears.value.delete(year);
} }
}; };
// Метод для проверки, является ли день выходным или праздничным // Метод для проверки, является ли день выходным или праздничным
const isNonWorkingDay = (dateInput) => { const isNonWorkingDay = (dateInput) => {
const date = dateInput instanceof Date ? dateInput : new Date(dateInput); const date = dateInput instanceof Date ? dateInput : new Date(dateInput);
if (isNaN(date.getTime())) { if (isNaN(date.getTime())) {
return { isNonWorking: false, isWeekendForStyling: false, isHoliday: false }; return { isNonWorking: false, isWeekendForStyling: false, isHoliday: false };
} }
const year = date.getFullYear(); const year = date.getFullYear();
const month = date.getMonth() + 1; const month = date.getMonth() + 1;
const iso = `${year}-${String(month).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`; const iso = `${year}-${String(month).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
const day = date.getDay(); const day = date.getDay();
const isWeekend = day === 0 || day === 6; const isWeekend = day === 0 || day === 6;
const isHoliday = (holidays.value[year]?.[month] ?? []).includes(iso); const isHoliday = (holidays.value[year]?.[month] ?? []).includes(iso);
return { return {
isNonWorking: isWeekend || isHoliday, isNonWorking: isWeekend || isHoliday,
isWeekendForStyling: isWeekend, isWeekendForStyling: isWeekend,
isHoliday, isHoliday,
};
};
const setSelectedEvent = (event) => {
selectedEvent.value = event;
};
// Шаблон пустого события (создание)
const getEmptyEventWrapper = () => {
const now = new Date();
const inHour = new Date(now.getTime() + 60 * 60 * 1000);
return {
event: {
name: '',
description: '',
date_start: now.toISOString(),
date_end: inHour.toISOString(),
allday: false,
period: null,
participant: [accountStore.user.is_idEmployee],
calendar: null,
files: [],
},
mycalendars: calendars.value,
};
};
// Шаблон обёртки для редактирования
const buildEventWrapper = (fullEvent) => {
return {
event: {
...fullEvent,
participant: Array.isArray(fullEvent.participant)
? fullEvent.participant.map((p) => (typeof p === 'object' ? p.id : p))
: [],
},
mycalendars: calendars.value,
};
}; };
};
// Открыть диалог создания/редактирования // Открыть диалог создания/редактирования
const openEventDialog = (event = null) => { const openEventDialog = async (eventOrInfo = null) => {
selectedEvent.value = event; if (eventOrInfo === null) {
showEventDialog.value = true; selectedEvent.value = getEmptyEventWrapper();
showEventDialog.value = true;
return;
}
const id = eventOrInfo?.event?.id ?? eventOrInfo?.id;
if (!id) {
selectedEvent.value = getEmptyEventWrapper();
showEventDialog.value = true;
return;
}
try {
const { data } = await axiosApiInstance.get(`api/calendar_of_events/my_events/?id=${id}`);
selectedEvent.value = data;
showEventDialog.value = true;
} catch (error) {
console.error('Ошибка загрузки события:', error);
}
}; };
// Закрыть диалог
const closeEventDialog = () => { const closeEventDialog = () => {
showEventDialog.value = false; showEventDialog.value = false;
selectedEvent.value = null; selectedEvent.value = null;
}; };
const openEventView = async (eventId) => {
if (!eventId) return;
try {
const { data } = await axiosApiInstance.get(
`api/calendar_of_events/my_events/?id=${eventId}`,
);
selectedEventForView.value = data;
showViewDialog.value = true;
} catch (error) {
console.error('Ошибка загрузки события:', error);
}
};
const closeEventView = () => {
showViewDialog.value = false;
selectedEventForView.value = null;
};
const handleEventClick = (info) => {
const id = info.event?.id ?? info.id;
if (canEditEvent(id)) {
openEventDialog(info);
} else {
openEventView(id);
}
};
return { return {
// State // State
selectedDate, selectedDate,
@@ -262,6 +346,9 @@ const isNonWorkingDay = (dateInput) => {
loadCalendars, loadCalendars,
openEventDialog, openEventDialog,
closeEventDialog, closeEventDialog,
openEventView,
closeEventView,
handleEventClick,
setSelectedDateFromCalendar, setSelectedDateFromCalendar,
setSelectedDateFromPicker, setSelectedDateFromPicker,
toggleCalendarVisibility, toggleCalendarVisibility,
@@ -269,5 +356,9 @@ const isNonWorkingDay = (dateInput) => {
isNonWorkingDay, isNonWorkingDay,
loadDictEmployees, loadDictEmployees,
loadEmployees, loadEmployees,
setSelectedEvent,
getEmptyEventWrapper,
buildEventWrapper,
}; };
}); });