fix [P-293]: создание календаря при создании события

This commit is contained in:
Inna authored and denzel committed 2026-05-29 09:16:03 +03:00
1 parent 6cb204b3ac
commit ceb398c070
5 files changed
+481 -260

No files matched your search

@@ -4,46 +4,237 @@
<mini-calendar /> <mini-calendar />
</v-col> </v-col>
<v-col class="d-flex flex-column"> <v-col class="d-flex flex-column">
<custom-calendar :key="calendarKey" /> <custom-calendar
: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 } from 'vue'; import { ref, onMounted, watch, computed, provide } from 'vue';
import { useWeekendsStore } from '@/store/WeekendsStore';
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 MiniCalendar from '@/components/calendar_of_events/UI_calendar/MiniCalendar.vue';
import { useCalendarStore } from '@/store/calendarStore'; import { useCalendarStore } from '@/store/calendarStore';
import { storeToRefs } from 'pinia';
import MiniCalendar from '@/components/calendar_of_events/UI_calendar/MiniCalendar.vue';
import { axiosApiInstance } from '@/utils/axios-api';
import { useAccountStore } from '@/store/AccountStore'; import { useAccountStore } from '@/store/AccountStore';
import { useRoute } from 'vue-router'; import EventCalendarShow from '@/components/calendar_of_events/event-calendar-show.vue';
export default { export default {
components: { MiniCalendar, CustomCalendar }, components: { EventCreate, MiniCalendar, CustomCalendar, EventCalendarShow },
setup() { setup() {
const week = useWeekendsStore();
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 calendarKey = ref(0); const showViewDialog = ref(false);
const route = useRoute(); const selectedEventForView = ref({});
onMounted(() => { const { selectedDate, showEventDialog } = storeToRefs(calendarStore); // синхронизируем с date-picker
const currentYear = new Date().getFullYear();
calendarStore.fetchHolidays(currentYear); const getMonth = (month) => {
MyMonth.value = month + 1;
};
const getYear = (year) => {
MyYear.value = year;
};
const getCalendar = () => {
calendarStore.loadCalendars(); calendarStore.loadCalendars();
};
const getDictEmployee = () => {
calendarStore.loadDictEmployees(); calendarStore.loadDictEmployees();
};
const getEmployees = () => {
calendarStore.loadEmployees(); calendarStore.loadEmployees();
if (route.query.date) { };
calendarStore.setSelectedDate(route.query.date);
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(() => {
getEvent();
week.getWeekend(MyYear.value);
getDictEmployee();
getCalendar();
getEmployees();
});
const closeEventDialog = () => {
calendarStore.closeEventDialog();
// При ручном закрытии сбрасываем данные сразу
setTimeout(() => {
eventFromCalendar.value = createEmptyEvent();
eventKey.value++;
}, 200);
};
const CheckingStore = () => {
if (MyYear.value in week.week) {
weekendsData();
} else {
week.getWeekend(MyYear.value);
}
};
const openCalendarCreate = () => {
miniCalendarRef.value?.openCalendarCreate();
};
provide('openCalendarCreate', openCalendarCreate);
watch( watch(
() => accountStore.user?.id, () => calendarStore.showEventDialog,
(newId, oldId) => { (newValue, oldValue) => {
if (newId !== oldId) calendarKey.value += 1; if (!newValue && oldValue) {
// Диалог был открыт и закрыт не через нашу кнопку
// Добавляем проверку чтобы не сбрасывать при инициализации
if (eventFromCalendar.value.event?.id) {
setTimeout(() => {
eventFromCalendar.value = createEmptyEvent();
eventKey.value++;
}, 200);
}
}
}, },
); );
return { calendarKey }; watch(
() => accountStore.user?.id,
(newUserId, oldUserId) => {
if (newUserId !== oldUserId) {
console.log('User changed, forcing calendar recreation...');
calendarKey.value += 1; // Изменяем key для пересоздания компонента
}
},
);
const getEventForView = (idEvent) => {
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,
week,
CheckingStore,
showEventDialog,
calendarForMy,
getCalendar,
getEvent,
eventFromCalendar,
calendarStore,
accountStore,
closeEventDialog,
openEventDialog,
createEmptyEvent,
eventKey,
getDictEmployee,
openEventView,
handleViewDialogClose,
showViewDialog,
selectedEventForView,
allCalendars,
eventKey,
calendarKey,
openCalendarCreate,
};
}, },
}; };
</script> </script>
@@ -1,5 +1,5 @@
<template> <template>
<v-card class="h-100 rounded-0 d-flex flex-column"> <v-card class="h-100 rounded-0 d-flex flex-colmn">
<v-row no-gutters class="flex-column"> <v-row no-gutters class="flex-column">
<v-col class="flex-grow-0 px-2 pt-1"> <v-col class="flex-grow-0 px-2 pt-1">
<SearchEvents /> <SearchEvents />
@@ -56,7 +56,7 @@ import { useCalendarStore } from '@/store/calendarStore';
import { useAccountStore } from '@/store/AccountStore'; import { useAccountStore } from '@/store/AccountStore';
import CalendarMy from '@/components/calendar_of_events/calendar-my.vue'; import CalendarMy from '@/components/calendar_of_events/calendar-my.vue';
import SearchEvents from '@/components/calendar_of_events/UI_calendar/SearchEvents.vue'; import SearchEvents from '@/components/calendar_of_events/UI_calendar/SearchEvents.vue';
import { onMounted, watch, nextTick, ref, onBeforeUnmount } from 'vue'; import { onMounted, watch, nextTick, ref } from 'vue';
import { storeToRefs } from 'pinia'; import { storeToRefs } from 'pinia';
export default { export default {
@@ -67,10 +67,14 @@ export default {
const accountStore = useAccountStore(); const accountStore = useAccountStore();
const { selectedDate, myCalendars, subscribedCalendars } = storeToRefs(calendarStore); const { selectedDate, myCalendars, subscribedCalendars } = storeToRefs(calendarStore);
// const selectedDate = computed(() => calendarStore.selectedDate);
// const myCalendars = computed(() => calendarStore.myCalendars);
// const subscribedCalendars = computed(() => calendarStore.subscribedCalendars);
const { user } = storeToRefs(accountStore); const { user } = storeToRefs(accountStore);
const currentDisplay = ref(null); const currentDisplay = ref(null);
let observer = null;
const handleDateClick = (date) => { const handleDateClick = (date) => {
calendarStore.setSelectedDateFromPicker(date); calendarStore.setSelectedDateFromPicker(date);
@@ -85,6 +89,12 @@ export default {
calendarStore.loadCalendars(); calendarStore.loadCalendars();
}; };
onMounted(() => {
loadCalendars();
updateCalendarDays();
});
// Реакция на изменения пользователя // Реакция на изменения пользователя
watch(user, (newUser) => { watch(user, (newUser) => {
if (newUser) { if (newUser) {
@@ -182,24 +192,25 @@ export default {
{ deep: true }, { deep: true },
); );
onMounted(() => { // При смене месяца через кнопки навигации
loadCalendars(); const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === 'childList') {
updateCalendarDays(); updateCalendarDays();
}
});
});
onMounted(() => {
// Наблюдаем за изменениями в DOM date-picker // Наблюдаем за изменениями в DOM date-picker
const datePicker = document.querySelector('.minCal'); const datePicker = document.querySelector('.minCal');
if (datePicker) { if (datePicker) {
observer = new MutationObserver(() => updateCalendarDays());
observer.observe(datePicker, { childList: true, subtree: true }); observer.observe(datePicker, { childList: true, subtree: true });
} }
}); });
onBeforeUnmount(() => {
observer?.disconnect();
});
return { return {
accountStore, accountStore,
calendarStore,
user, user,
myCalendars, myCalendars,
subscribedCalendars, subscribedCalendars,
@@ -214,7 +225,16 @@ export default {
}; };
</script> </script>
<style scoped> <style scoped>
.minCal .v-date-picker-month__day { /* .minCal:deep(.v-date-picker-month__days) {
display: grid !important;
grid-template-columns: repeat(7, 40px) !important;
gap: 3px !important;
width: 250px !important;
justify-content: center !important;
margin: 0 auto !important;
} */
.minCal .v-date-picker-monWth__day {
height: 31px; height: 31px;
width: 31px; width: 31px;
} }
@@ -235,24 +255,23 @@ export default {
/* СТИЛИ ДЛЯ ВЫХОДНЫХ И ПРАЗДНИКОВ */ /* СТИЛИ ДЛЯ ВЫХОДНЫХ И ПРАЗДНИКОВ */
.minCal:deep(.weekend-day .v-btn__content) { .minCal:deep(.weekend-day .v-btn__content) {
color: rgb(var(--v-theme-weekend_text)) !important; color: #666 !important;
} }
.minCal:deep(.holiday-day .v-btn__content) { .minCal:deep(.holiday-day .v-btn__content) {
color: rgb(var(--v-theme-holiday_text)) !important; color: #ff4444 !important;
font-weight: 600 !important; font-weight: bold !important;
} }
.minCal:deep(.weekend-day.holiday-day) .v-btn { .minCal:deep(.weekend-day.holiday-day) {
background-color: rgba(var(--v-theme-holiday_text), 0.12) !important; background-color: #ffe0e0 !important;
} }
.minCal:deep(.weekend-day.holiday-day .v-btn__content) { .minCal:deep(.weekend-day.holiday-day .v-btn__content) {
color: rgb(var(--v-theme-holiday_text)) !important; color: #cc0000 !important;
font-weight: 600 !important;
} }
.search-dropdown { search-dropdown {
max-height: 300px; max-height: 300px;
overflow-y: auto; overflow-y: auto;
} }
@@ -27,10 +27,16 @@
<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>
@@ -229,6 +235,23 @@ 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;
@@ -276,13 +299,4 @@ 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>
@@ -8,11 +8,8 @@
<v-btn <v-btn
v-if="title === 'Мои календари'" v-if="title === 'Мои календари'"
size="x-regular"
icon="mdi-plus" icon="mdi-plus"
variant="outlined" class="simple-hover"
color="btn_text"
class="pa-1 ml-2 simple-hover"
@click.stop="editCreatedCalendar()" @click.stop="editCreatedCalendar()"
></v-btn> ></v-btn>
</v-expansion-panel-title> </v-expansion-panel-title>
@@ -76,41 +73,32 @@
</v-expansion-panels> </v-expansion-panels>
</template> </template>
<script> <script setup>
import { ref, watch } from 'vue'; import { onMounted, ref, watch } from 'vue';
import calendarCreate from '@/components/calendar_of_events/calendar-create.vue'; import calendarCreate from '@/components/calendar_of_events/calendar-create.vue';
import { useAccountStore } from '@/store/AccountStore'; import { useAccountStore } from '@/store/AccountStore';
import { storeToRefs } from 'pinia'; import { storeToRefs } from 'pinia';
import { useCalendarStore } from '@/store/calendarStore'; import { useCalendarStore } from '@/store/calendarStore';
export default { const props = defineProps({
components: { calendarCreate }, calendars: Array,
title: String,
});
props: { const emit = defineEmits(['getCalendar']);
calendars: {
type: Array,
default: () => [],
},
title: { const showDialog = ref(false);
type: String, const accountStore = useAccountStore();
default: '', const { user } = storeToRefs(accountStore);
}, const calendarStore = useCalendarStore();
}, const { toggleCalendarVisibility, hiddenCalendarIds } = calendarStore;
setup(props) { const calendar = ref(null);
const showDialog = ref(false); const openGroup = ref([0]);
const accountStore = useAccountStore(); // const trans = ref(false);
const { user } = storeToRefs(accountStore); const hover = ref(0);
const calendarStore = useCalendarStore();
const { toggleCalendarVisibility, hiddenCalendarIds } = calendarStore;
const calendar = ref(null); const editCreatedCalendar = (cal) => {
const openGroup = ref([0]);
const trans = ref(false);
const hover = ref(0);
const editCreatedCalendar = (cal) => {
if (cal === undefined) { if (cal === undefined) {
calendar.value = { calendar.value = {
cl_name: '', cl_name: '',
@@ -122,56 +110,58 @@ export default {
calendar.value = { ...cal }; calendar.value = { ...cal };
} }
showDialog.value = true; showDialog.value = true;
}; };
const handleCloseDialog = () => { onMounted(() => {
window.$createCalendar = () => {
editCreatedCalendar();
};
});
const handleCloseDialog = () => {
if (calendar.value.cl_name.length > 1) {
const calendarData = JSON.parse(JSON.stringify(calendar.value));
window.dispatchEvent(
new CustomEvent('calendarCreated', {
detail: calendarData,
}),
);
}
showDialog.value = false; showDialog.value = false;
}; };
const resetCalendar = () => { const resetCalendar = () => {
calendar.value = {}; calendar.value = {};
}; };
const toggleVisiblityEvents = (cal) => { const toggleVisiblityEvents = (cal) => {
toggleCalendarVisibility(cal.id); toggleCalendarVisibility(cal.id);
}; };
watch(hiddenCalendarIds, (newHiddenIds) => {}, { deep: true }); watch(hiddenCalendarIds, (newHiddenIds) => {}, { deep: true });
watch( watch(
() => props.calendars, () => props.calendars,
(newCalendars) => {}, (newCalendars) => {},
{ deep: true }, { deep: true },
); );
return {
accountStore,
user,
calendar,
showDialog,
editCreatedCalendar,
toggleVisiblityEvents,
openGroup,
trans,
hover,
handleCloseDialog,
resetCalendar,
};
},
};
</script> </script>
<style> <style>
.simple-hover { .simple-hover {
opacity: 0.6;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
min-width: 30px !important; width: 22px !important;
height: 30px !important; height: 22px !important;
border-radius: 3px !important;
margin-left: 0.5rem;
background-color: #00897b !important;
color: white;
margin-bottom: 2px;
padding: 0;
} }
.simple-hover:hover { .simple-hover:hover {
opacity: 1; background-color: #004d40 !important;
background-color: rgba(0, 137, 123, 0.1) !important;
transform: scale(1.1); transform: scale(1.1);
} }
.fade-enter-active, .fade-enter-active,
@@ -47,7 +47,7 @@
hide-details hide-details
variant="outlined" variant="outlined"
density="compact" density="compact"
class="py-3" class="py-3 my-select"
return-object return-object
:rules="rules.calendar" :rules="rules.calendar"
:disabled="'id' in propsEvent.event" :disabled="'id' in propsEvent.event"
@@ -65,7 +65,8 @@
:value="item" :value="item"
color="primary" color="primary"
v-bind="props" v-bind="props"
@click.stop="myCalendar = item.raw" @click.stop="handleCalendarSelect(item.raw)"
:data-calendar-id="item.raw.id"
> >
<template v-slot:prepend> <template v-slot:prepend>
<v-avatar class="cursor-pointer" size="8" :color="item.raw.cl_color" /> <v-avatar class="cursor-pointer" size="8" :color="item.raw.cl_color" />
@@ -183,8 +184,8 @@
</dialog-create> </dialog-create>
</template> </template>
<script> <script setup>
import { computed, ref, watch } from 'vue'; import { computed, nextTick, onMounted, ref, watch } from 'vue';
import { axiosApiInstance } from '@/utils/axios-api'; import { axiosApiInstance } from '@/utils/axios-api';
import { useAccountStore } from '@/store/AccountStore'; import { useAccountStore } from '@/store/AccountStore';
import DialogCreate from '@/components/calendar_of_events/UI_calendar/dialogCreate.vue'; import DialogCreate from '@/components/calendar_of_events/UI_calendar/dialogCreate.vue';
@@ -198,47 +199,29 @@ import { RRule } from 'rrule';
import { useRecurrence } from '@/components/calendar_of_events/composables/useReccurrence'; import { useRecurrence } from '@/components/calendar_of_events/composables/useReccurrence';
import { useCalendarStore } from '../../store/calendarStore'; import { useCalendarStore } from '../../store/calendarStore';
export default { const props = defineProps({
components: { eventCalendar: Object,
calendarCreateSelect, allCalendars: Array,
DialogCreate, selectedRule: Object,
TimeSelect, });
UploadingFile,
ReminderEvent,
PeriodEvents,
},
props: { const emit = defineEmits(['update:eventCalendar', 'getCalendar', 'closeDialog']);
eventCalendar: {
type: Object,
default: () => {},
},
allCalendars: {
type: Array,
default: () => [],
},
selectedRule: {
type: Object,
default: null,
},
},
setup(props, { emit }) { const accountStore = useAccountStore();
const accountStore = useAccountStore(); const calendarStore = useCalendarStore();
const calendarStore = useCalendarStore(); const createDialog = ref(null);
const createDialog = ref(null);
const { parseRecurrenceOptions, isRecurringEvent } = useRecurrence(); const { parseRecurrenceOptions, isRecurringEvent } = useRecurrence();
const propsEvent = computed({ const propsEvent = computed({
get: () => { get: () => {
return props.eventCalendar; return props.eventCalendar;
}, },
set: (value) => emit('update:eventCalendar', value), set: (value) => emit('update:eventCalendar', value),
}); });
const currentCalendarAuthorId = computed(() => { const currentCalendarAuthorId = computed(() => {
if (isNewEvent.value) { if (isNewEvent.value) {
// Для нового события - автор текущего выбранного календаря // Для нового события - автор текущего выбранного календаря
return myCalendar.value?.author; return myCalendar.value?.author;
@@ -250,9 +233,9 @@ export default {
); );
return currentCalendar?.author; return currentCalendar?.author;
} }
}); });
const newStaff = computed({ const newStaff = computed({
get() { get() {
let filteredStaff = []; let filteredStaff = [];
@@ -317,19 +300,19 @@ export default {
return filteredStaff; return filteredStaff;
}, },
}); });
// ВАЛИДАЦИЯ // ВАЛИДАЦИЯ
const rules = { const rules = {
name: [ name: [
(val) => !!val || 'Поле обязательно для заполнения', (val) => !!val || 'Поле обязательно для заполнения',
(val) => (val && val.length >= 3) || 'Минимум 3 символа', (val) => (val && val.length >= 3) || 'Минимум 3 символа',
(val) => (val && val.length <= 100) || 'Максимум 100 символов', (val) => (val && val.length <= 100) || 'Максимум 100 символов',
], ],
calendar: [(val) => !!val || 'Выберите календарь'], calendar: [(val) => !!val || 'Выберите календарь'],
}; };
const repeatRules = [ const repeatRules = [
{ type: 'Не повторять', rule: null, id: 1 }, { type: 'Не повторять', rule: null, id: 1 },
{ {
type: 'Каждый день', type: 'Каждый день',
@@ -387,14 +370,14 @@ export default {
}, },
id: 5, id: 5,
}, },
]; ];
const selectedRule = ref(repeatRules[0]); const selectedRule = ref(repeatRules[0]);
const showRepeatEnd = ref(false); const showRepeatEnd = ref(false);
const repeatEndDate = ref(new Date()); const repeatEndDate = ref(new Date());
// Инициализация повторов при редактировании // Инициализация повторов при редактировании
const initializeRule = () => { const initializeRule = () => {
if (!propsEvent.value.event.period) { if (!propsEvent.value.event.period) {
selectedRule.value = repeatRules[0]; // "Не повторять" selectedRule.value = repeatRules[0]; // "Не повторять"
repeatEndDate.value = propsEvent.value.event.date_end repeatEndDate.value = propsEvent.value.event.date_end
@@ -453,56 +436,67 @@ export default {
? new Date(propsEvent.value.event.date_end) ? new Date(propsEvent.value.event.date_end)
: new Date(); : new Date();
} }
}; };
const isRepeatEndDisabled = computed(() => { const isRepeatEndDisabled = computed(() => {
return !selectedRule.value.rule; // disabled если правило null (не повторять) return !selectedRule.value.rule; // disabled если правило null (не повторять)
}); });
const feedalert = useAlertStore().alert; const feedalert = useAlertStore().alert;
const titleCard = computed(() => { const titleCard = computed(() => {
if (propsEvent.value.event.hasOwnProperty('id')) { if (propsEvent.value.event.hasOwnProperty('id')) {
return 'Редактирование события'; return 'Редактирование события';
} else { } else {
return 'Новое событие'; return 'Новое событие';
} }
}); });
const isNewEvent = computed(() => !propsEvent.value.event.hasOwnProperty('id')); const isNewEvent = computed(() => !propsEvent.value.event.hasOwnProperty('id'));
const myCalendar = ref(null); const myCalendar = ref(null);
// const isNewEvent = computed(() => !propsEvent.value.event.id);
// Computed property с защитой от undefined const safeCalendars = computed(() => {
// const safeCalendars = computed(() => props.allCalendars || []);
const safeCalendars = computed(() => {
const userId = accountStore.user.is_idEmployee; const userId = accountStore.user.is_idEmployee;
return (props.allCalendars || []).filter((calendar) => { // return (props.allCalendars || []).filter((calendar) => {
// Пользователь - автор календаря (полные права) // // Пользователь - автор календаря (полные права)
if (calendar.author === userId) { // if (calendar.author === userId) {
return true; // 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); const participant = calendar.participant?.find((p) => p.participant_calendar === userId);
return participant?.editor === true; return participant?.editor === true;
}); });
// Добавляем пункт "Создать календарь"
filtered.push({
id: 'create_new',
cl_name: '➕ Создать календарь',
isFake: true,
}); });
const isCalendarsReady = computed(() => safeCalendars.value.length > 0); return filtered;
});
// Computed для календаря события const isCalendarsReady = computed(() => safeCalendars.value.length > 0);
const eventCalendar = computed(() => {
// Computed для календаря события
const eventCalendar = computed(() => {
if (!propsEvent.value?.event?.calendar || !safeCalendars.value.length) return null; if (!propsEvent.value?.event?.calendar || !safeCalendars.value.length) return null;
return safeCalendars.value.find((cal) => cal.id === propsEvent.value.event.calendar); return safeCalendars.value.find((cal) => cal.id === propsEvent.value.event.calendar);
}); });
// Единоразовая инициализация при монтировании/получении данных // Единоразовая инициализация при монтировании/получении данных
const initializeCalendar = () => { const initializeCalendar = () => {
if (myCalendar.value) return; // Уже инициализирован if (myCalendar.value) return; // Уже инициализирован
// Приоритет 1: календарь из события (редактирование) // Приоритет 1: календарь из события (редактирование)
@@ -513,27 +507,31 @@ export default {
// Приоритет 2: первый доступный календарь (создание) // Приоритет 2: первый доступный календарь (создание)
if (safeCalendars.value.length > 0) { if (safeCalendars.value.length > 0) {
myCalendar.value = safeCalendars.value[0]; // myCalendar.value = safeCalendars.value[0];
const firstRealCalendar = safeCalendars.value.find((cal) => cal.id !== 'create_new');
if (firstRealCalendar) {
myCalendar.value = firstRealCalendar;
} }
}; }
};
// Инициализируем когда все готово // Инициализируем когда все готово
watch( watch(
[() => safeCalendars.value.length, () => propsEvent.value], [() => safeCalendars.value.length, () => propsEvent.value],
() => { (newCalendar) => {
initializeCalendar(); initializeCalendar();
}, },
{ immediate: true }, { immediate: true, deep: true },
); );
// Дополнительная защита - вотчер только на смену самого календаря // Дополнительная защита - вотчер только на смену самого календаря
watch(eventCalendar, (newCalendar) => { watch(eventCalendar, (newCalendar) => {
if (newCalendar && newCalendar.id !== myCalendar.value?.id) { if (newCalendar && newCalendar.id !== myCalendar.value?.id) {
myCalendar.value = newCalendar; myCalendar.value = newCalendar;
} }
}); });
const delEvent = (idev) => { const delEvent = (idev) => {
axiosApiInstance.delete(`api/calendar_of_events/my_events/?delid=${idev}`).then((result) => { axiosApiInstance.delete(`api/calendar_of_events/my_events/?delid=${idev}`).then((result) => {
feedalert.alert = true; feedalert.alert = true;
feedalert.text = result.data.mess; feedalert.text = result.data.mess;
@@ -542,11 +540,11 @@ export default {
emit('getCalendar'); emit('getCalendar');
}); });
emit('closeDialog'); emit('closeDialog');
}; };
const newFiles = ref([]); const newFiles = ref([]);
const handleFilesUpdate = (updatedExistingFiles) => { const handleFilesUpdate = (updatedExistingFiles) => {
// Сохраняем новые файлы во временную переменную // Сохраняем новые файлы во временную переменную
const currentNewFiles = [...newFiles.value]; const currentNewFiles = [...newFiles.value];
@@ -555,13 +553,13 @@ export default {
// Восстанавливаем новые файлы // Восстанавливаем новые файлы
newFiles.value = currentNewFiles; newFiles.value = currentNewFiles;
}; };
const postFiles = (updatedFiles) => { const postFiles = (updatedFiles) => {
newFiles.value = updatedFiles; newFiles.value = updatedFiles;
}; };
const returnIdParticant = (idPart) => { const returnIdParticant = (idPart) => {
idPart.staff.forEach((e) => { idPart.staff.forEach((e) => {
if (e.selected == true && !propsEvent.value.event.participant.includes(e.id)) { if (e.selected == true && !propsEvent.value.event.participant.includes(e.id)) {
propsEvent.value.event.participant.push(e.id); propsEvent.value.event.participant.push(e.id);
@@ -573,9 +571,9 @@ export default {
} }
} }
}); });
}; };
const cbSelect = (item, arr) => { const cbSelect = (item, arr) => {
item.forEach((e) => { item.forEach((e) => {
if (!('employees' in e)) { if (!('employees' in e)) {
if (!propsEvent.value.event.participant.includes(e.id)) { if (!propsEvent.value.event.participant.includes(e.id)) {
@@ -586,25 +584,17 @@ export default {
cbSelect(e.employees); cbSelect(e.employees);
} }
}); });
}; };
const menudate = ref(false); const postData = async (validate) => {
const postData = (validate) => {
if (validate) { if (validate) {
await nextTick();
updatePeriodRule(selectedRule.value); updatePeriodRule(selectedRule.value);
propsEvent.value.event.calendar = myCalendar.value.id; propsEvent.value.event.calendar = myCalendar.value.id;
let postEvent = new FormData(); let postEvent = new FormData();
// if (propsEvent.value.event.allday && propsEvent.value.event.period?.includes('DTSTART')) {
// // убираем суффикс Z (UTC), чтобы не было смещения на день
// propsEvent.value.event.period = propsEvent.value.event.period.replace(
// 'Z\nRRULE',
// '\nRRULE',
// );
// }
postEvent.append( postEvent.append(
'event', 'event',
JSON.stringify({ ...propsEvent.value.event, files: propsEvent.value.event.files }), JSON.stringify({ ...propsEvent.value.event, files: propsEvent.value.event.files }),
@@ -626,25 +616,25 @@ export default {
emit('closeDialog'); emit('closeDialog');
}); });
} }
}; };
const handleAutoAdjustEnd = (newEndDate) => { const handleAutoAdjustEnd = (newEndDate) => {
propsEvent.value.event.date_end = newEndDate; propsEvent.value.event.date_end = newEndDate;
}; };
const updateRepeatEndDate = (date) => { const updateRepeatEndDate = (date) => {
repeatEndDate.value = date; repeatEndDate.value = date;
updatePeriodRule(selectedRule.value); // Пересоздаем правило с новой датой updatePeriodRule(selectedRule.value); // Пересоздаем правило с новой датой
}; };
watch(selectedRule, (newRule) => { watch(selectedRule, (newRule) => {
if (!newRule.rule) { if (!newRule.rule) {
showRepeatEnd.value = false; showRepeatEnd.value = false;
repeatEndDate.value = null; repeatEndDate.value = null;
} }
}); });
const updateDateStart = (newDate) => { const updateDateStart = (newDate) => {
// Нормализуем к ISO строке // Нормализуем к ISO строке
const normalizedDate = new Date(newDate).toISOString(); const normalizedDate = new Date(newDate).toISOString();
propsEvent.value.event.date_start = normalizedDate; propsEvent.value.event.date_start = normalizedDate;
@@ -662,15 +652,15 @@ export default {
if (selectedRule.value.rule) { if (selectedRule.value.rule) {
updatePeriodRule(selectedRule.value); updatePeriodRule(selectedRule.value);
} }
}; };
const updateDateEnd = (newDate) => { const updateDateEnd = (newDate) => {
// Нормализуем к ISO строке // Нормализуем к ISO строке
propsEvent.value.event.date_end = new Date(newDate).toISOString(); propsEvent.value.event.date_end = new Date(newDate).toISOString();
}; };
// функция обновления периода // функция обновления периода
const updatePeriodRule = (rule) => { const updatePeriodRule = (rule) => {
selectedRule.value = rule; selectedRule.value = rule;
if (!rule.rule) { if (!rule.rule) {
@@ -723,9 +713,9 @@ export default {
const rrule = new RRule(ruleOptions); const rrule = new RRule(ruleOptions);
propsEvent.value.event.period = rrule.toString(); propsEvent.value.event.period = rrule.toString();
}; };
watch( watch(
() => propsEvent.value.event?.period, () => propsEvent.value.event?.period,
(newPeriod) => { (newPeriod) => {
if (newPeriod) { if (newPeriod) {
@@ -733,43 +723,60 @@ export default {
} }
}, },
{ immediate: true }, { immediate: true },
);
watch([safeCalendars, myCalendar], (newCalendar) => {}, { deep: true, immediate: true });
// function handleCalendarSelect(calendar) {
// if (calendar.id === 'create_new') {
// if (window.$createCalendar) {
// // Создаем слушатель события
// const handleCalendarCreated = (event) => {
// // myCalendar.value = JSON.parse(JSON.stringify(event.detail));
// propsEvent.value.event.calendar = event.detail.id;
// myCalendar.value = event.detail;
// window.removeEventListener('calendarCreated', handleCalendarCreated);
// };
// window.addEventListener('calendarCreated', handleCalendarCreated);
// window.$createCalendar();
// }
// return;
// }
// myCalendar.value = calendar;
// }
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),
); );
return { window.$createCalendar();
menudate,
titleCard, // Следим за появлением календаря с ID больше максимального
propsEvent, const unwatch = watch(
newStaff,
returnIdParticant,
postFiles,
postData,
rules,
delEvent,
myCalendar,
safeCalendars, safeCalendars,
isCalendarsReady, (newCalendars) => {
isNewEvent, const realCalendars = newCalendars.filter((cal) => cal.id !== 'create_new');
currentCalendarAuthorId, const newCalendar = realCalendars.find((cal) => cal.id > maxIdBefore);
isRepeatEndDisabled,
repeatRules, if (newCalendar) {
updatePeriodRule, myCalendar.value = newCalendar;
selectedRule, unwatch();
updateDateEnd, }
updateDateStart,
initializeRule,
createDialog,
handleAutoAdjustEnd,
newFiles,
handleFilesUpdate,
initializeCalendar,
updateRepeatEndDate,
showRepeatEnd,
repeatEndDate,
};
}, },
}; { deep: true },
);
setTimeout(() => unwatch(), 5000);
}
return;
}
myCalendar.value = calendar;
}
</script> </script>
<style> <style>