refactor [P-52]: исправление функционала повторения событий

This commit is contained in:
Inna committed 2025-09-24 11:19:35 +03:00
1 parent 3a7d147c36
commit b6f534aaf7
6 files changed
+296 -258

No files matched your search

+2 -1
View File
@@ -43,7 +43,8 @@
"@fullcalendar/multimonth": "^6.1.19",
"@fullcalendar/timegrid": "^6.1.19",
"@fullcalendar/list": "6.1.19",
"@fullcalendar/vue3": "^6.1.19"
"@fullcalendar/vue3": "^6.1.19",
"@fullcalendar/rrule": "^6.1.15"
},
"devDependencies": {
"@commitlint/cli": "^19.7.1",
@@ -69,7 +69,7 @@
</v-col>
</template>
<script>
import { ref, watch, nextTick, defineEmits } from 'vue';
import { ref, watch, nextTick, computed } from 'vue';
import { storeToRefs } from 'pinia';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
@@ -77,8 +77,11 @@ import multiMonthPlugin from '@fullcalendar/multimonth';
import interactionPlugin from '@fullcalendar/interaction';
import listPlugin from '@fullcalendar/list';
import ruLocale from '@fullcalendar/core/locales/ru';
import rrulePlugin from '@fullcalendar/rrule';
import { onMounted } from 'vue';
import { useCalendarStore } from '@/store/calendarStore';
import { useAccountStore } from '@/store/AccountStore';
import { useRecurrence } from '@/components/calendar_of_events/composables/useReccurrence';
export default {
name: 'CustomCalendar',
@@ -101,13 +104,23 @@ export default {
const calendarStore = useCalendarStore();
const { selectedDate, lastUpdatedBy, allEvents } = storeToRefs(calendarStore);
const { parseRecurrenceOptions, isRecurringEvent } = useRecurrence();
const handleEventClick = (info) => {
emit('openEventDialog', info);
if (calendarStore.canEditEvent(info.event.id)) {
emit('openEventDialog', info);
}
};
const calendarOptions = ref({
plugins: [dayGridPlugin, timeGridPlugin, multiMonthPlugin, interactionPlugin, listPlugin],
plugins: [
dayGridPlugin,
timeGridPlugin,
multiMonthPlugin,
interactionPlugin,
listPlugin,
rrulePlugin,
],
initialView: props.forHomePage ? props.view : currentView.value,
locales: [ruLocale],
locale: 'ru',
@@ -289,17 +302,53 @@ export default {
const api = calendarRef.value.getApi();
api.removeAllEvents();
allEvents.value.forEach((event) => {
api.addEvent({
id: event.id,
title: event.name,
start: event.date_start,
end: event.date_end,
allDay: event.all_day,
});
const eventColor = calendarColorMap.value.get(event.calendar) || '#3788d8';
// если событие не повторяется
if (!isRecurringEvent) {
api.addEvent({
id: event.id,
title: event.name,
start: event.date_start,
end: event.date_end,
allDay: event.all_day,
textColor: '#ffffff',
});
} else {
const rruleOptions = parseRecurrenceOptions(event.period);
api.addEvent({
id: event.id,
title: event.name,
start: event.date_start,
end: event.date_end,
allDay: event.all_day,
textColor: '#ffffff',
rrule: rruleOptions,
duration: event.date_end
? {
days: Math.ceil(
(new Date(event.date_end) - new Date(event.date_start)) /
(1000 * 60 * 60 * 24),
),
}
: null,
extendedProps: {
originalEvent: event,
isRecurring: true,
},
});
}
});
}
};
const calendarColorMap = computed(() => {
const map = new Map();
calendarStore.myCalendars.forEach((calendar) => {
map.set(calendar.id, calendar.cl_color);
});
return map;
});
onMounted(() => {
nextTick(() => {
if (calendarRef.value && calendarRef.value.getApi) {
@@ -349,6 +398,7 @@ export default {
handleDateSelection,
updateCalendarEvents,
handleEventClick,
calendarColorMap,
};
},
};
@@ -0,0 +1,59 @@
export function useRecurrence() {
/**
* Парсит строку периода из БД и возвращает опции для RRule
*/
const parseRecurrenceOptions = (periodString) => {
try {
// Проверяем, что periodString не пустой и не null
if (!periodString || periodString === 'null' || periodString === 'undefined') {
return null;
}
const periodData = JSON.parse(periodString);
// Проверяем, что periodData существует и имеет origOptions
if (!periodData || !periodData.origOptions) {
console.warn('Invalid period data structure:', periodData);
return null;
}
return periodData.origOptions;
} catch (error) {
console.error('Failed to parse recurrence rule:', error, 'String:', periodString);
return null;
}
};
/**
* Проверяет, является ли событие повторяющимся
*/
const isRecurringEvent = (event) => {
if (!event.period || event.period === 'null' || event.period === 'undefined') {
return false;
}
try {
const periodData = JSON.parse(event.period);
return !!(periodData && periodData.origOptions);
} catch (error) {
console.warn('Invalid period string for event:', event.id, error);
return false;
}
};
/**
* Создает объект правила для нового события
*/
const createRecurrenceRule = (options) => {
const serializableData = {
origOptions: options,
};
return JSON.stringify(serializableData);
};
return {
parseRecurrenceOptions,
createRecurrenceRule,
isRecurringEvent,
};
}
@@ -1,7 +1,7 @@
<template>
<dialog-create
:title="titleCard"
:newOrOld="newEvent"
:newOrOld="isNewEvent"
@postData="postData"
@closeDialog="$emit('closeDialog')"
@delObject="delEvent(propsEvent?.event?.id)"
@@ -83,23 +83,23 @@
<v-col class="d-flex flex-column">
<v-row no-gutters class="gap">
<time-select
:rule="returnPeriod != repeatRules[0].type ? returnPeriod.rule.freq : -1"
:rule="selectedRule.rule ? selectedRule.rule.freq : -1"
:chek="propsEvent.event.allday"
:order="[2, 1]"
:dateEvent="String(propsEvent.event.date_start)"
:limitation="String(propsEvent.event.date_end)"
@update:dateEvent="propsEvent.event.date_start = $event"
@update:dateEvent="updateDateStart"
/>
<v-col class="order-3 flex-grow-0">
<v-icon icon="mdi-minus pt-4" color="grey-darken-1" />
</v-col>
<time-select
:rule="returnPeriod != repeatRules[0].type ? returnPeriod.rule.freq : -1"
:rule="selectedRule.rule ? selectedRule.rule.freq : -1"
:chek="propsEvent.event.allday"
:order="[4, 5]"
:dateEvent="String(propsEvent.event.date_end)"
:limitation="String(propsEvent.event.date_start)"
@update:dateEvent="propsEvent.event.date_end = $event"
@update:dateEvent="updateDateEnd"
/>
</v-row>
<v-row no-gutters>
@@ -109,28 +109,29 @@
/>
<v-col lg="7" class="pt-2 ml-5">
<v-autocomplete
v-model="returnPeriod"
v-model="selectedRule"
:items="repeatRules"
variant="outlined"
density="compact"
return-object
item-title="type"
item-value="id"
@update:model-value="updatePeriodRule"
>
<template v-slot:item="{ props, item }">
<!-- <template v-slot:item="{ props, item }">
<v-list-item
v-bind="props"
:key="item.title"
:value="item"
color="primary"
:disabled="periodDisplayRule(item.raw.id)"
@click="returnPeriod = item.raw"
@click="selectedRule = item.raw"
/>
</template>
</template> -->
</v-autocomplete>
</v-col>
</v-row> </v-col
></v-row>
</v-row>
</v-col></v-row
>
</v-col>
<v-row no-gutters class="align-top flex-grow-0">
<v-col class="text-body-2 text-text_grey pt-3 h-0" lg="2"> Напоминание </v-col>
@@ -178,13 +179,11 @@
</template>
<script>
import { computed, ref, watch } from 'vue';
import { computed, onMounted, ref, watch } from 'vue';
import { axiosApiInstance } from '@/utils/axios-api';
import { useAccountStore } from '@/store/AccountStore';
import { useCalendarStore } from '@/store/calendarStore';
import DialogCreate from '@/components/calendar_of_events/UI_calendar/dialogCreate.vue';
import calendarCreateSelect from '@/components/calendar_of_events/calendar-create-select.vue';
import { formatComa } from '@/utils/universal_functions';
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';
@@ -225,7 +224,6 @@ export default {
set: (value) => emit('update:eventCalendar', value),
});
// ВАЛИДАЦИЯ
const rules = {
name: [
@@ -237,99 +235,85 @@ export default {
};
const repeatRules = [
{ type: 'Не повторять', rule: {}, id: 1 },
{ type: 'Каждый день', rule: { freq: 3 }, id: 2 },
{ type: 'Каждую неделю', rule: { freq: 2 }, id: 3 },
{ type: 'Каждый месяц', rule: { freq: 1 }, id: 4 },
{ type: 'Каждый год', rule: { freq: 0 }, id: 5 },
{ type: 'Не повторять', rule: null, id: 1 },
{
type: 'Каждый день',
rule: { freq: RRule.DAILY },
id: 2,
},
{
type: 'Каждую неделю',
rule: { freq: RRule.WEEKLY },
// По умолчанию - в тот же день недели, что и начальная дата
getRule: (startDate) => ({
freq: RRule.WEEKLY,
byweekday: [new Date(startDate).getDay()],
}),
id: 3,
},
{
type: 'Каждый месяц',
rule: { freq: RRule.MONTHLY },
// По умолчанию - в тот же день месяца
getRule: (startDate) => ({
freq: RRule.MONTHLY,
bymonthday: [new Date(startDate).getDate()],
}),
id: 4,
},
{
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 returnPeriod = computed({
get() {
let select = '';
if (propsEvent.value.event.period != null) {
let objRule = JSON.parse(propsEvent.value.event.period);
if (objRule != null) {
drawingRule(objRule.origOptions);
repeatRules.findIndex((e) => e.rule.freq == objRule.origOptions.freq);
select =
repeatRules[repeatRules.findIndex((e) => e.rule.freq == objRule.origOptions.freq)];
}
} else {
select = repeatRules[0].type;
const selectedRule = ref(repeatRules[0]);
// Инициализация при редактировании
const initializeRule = () => {
if (!propsEvent.value.event.period) {
selectedRule.value = repeatRules[0]; // "Не повторять"
return;
}
try {
const periodData = JSON.parse(propsEvent.value.event.period);
if (periodData?.origOptions) {
const foundRule = repeatRules.find(
(rule) => rule.rule?.freq === periodData.origOptions.freq,
);
selectedRule.value = foundRule || repeatRules[0];
console.log('Initialized rule:', foundRule); // для дебага
}
calendarNewOrOld();
return select;
},
set(newValue) {
drawingRule(newValue.rule);
},
});
const drawingRule = (value) => {
let newRulse;
if (value.freq == 3) {
newRulse = new RRule({
...value,
dtstart: new Date(propsEvent.value.event.date_start),
until: new Date(propsEvent.value.event.date_end),
});
} catch (error) {
console.error('Error parsing period:', error, 'Raw period:', propsEvent.value.event.period);
selectedRule.value = repeatRules[0];
}
if (value.freq == 2) {
newRulse = new RRule({
...value,
dtstart: new Date(propsEvent.value.event.date_start),
byweekday: getWeekNumbersBetweenDates(),
});
}
if (value.freq == 1) {
newRulse = new RRule({
...value,
bymonthday: getMonthBetweenDates(),
dtstart: new Date(propsEvent.value.event.date_start),
});
}
if (value.freq == 0) {
newRulse = new RRule({
...value,
bymonthday: getYearBetweenDates(),
dtstart: new Date(propsEvent.value.event.date_start),
bymonth: getNumberMonth(),
});
}
// byweekday: getWeekNumbersBetweenDates(),
Object.keys(value).length == 0
? (propsEvent.value.event.period = null)
: (propsEvent.value.event.period = JSON.stringify(newRulse));
};
const rulleWeek = [RRule.SU, RRule.MO, RRule.TU, RRule.WE, RRule.TH, RRule.FR, RRule.SA];
const feedalert = useAlertStore().alert;
const req = (val) => {
return !!val || 'Поле обязательно';
};
const titleCard = ref('');
const newEvent = ref(false);
const calendarNewOrOld = () => {
const titleCard = computed(() => {
if (propsEvent.value.event.hasOwnProperty('id')) {
titleCard.value = 'Редактирование события';
newEvent.value = false;
return 'Редактирование события';
} else {
titleCard.value = 'Новое событие';
newEvent.value = true;
return 'Новое событие';
}
};
});
const isNewEvent = computed(() => !propsEvent.value.event.hasOwnProperty('id'));
const myCalendar = ref(null);
const selectedCalendar = ref(null);
const isNewEvent = computed(() => !propsEvent.value.event.id);
// const isNewEvent = computed(() => !propsEvent.value.event.id);
// Computed property с защитой от undefined
const safeCalendars = computed(() => props.myCalendars || []);
@@ -337,11 +321,11 @@ export default {
const isCalendarsReady = computed(() => safeCalendars.value.length > 0);
// Автовыбор при появлении данных
// watch(isCalendarsReady, (ready) => {
// if (ready && !myCalendar.value && safeCalendars.value[0]) {
// myCalendar.value = safeCalendars.value[0];
// }
// });
watch(isCalendarsReady, (ready) => {
if (ready && !myCalendar.value && safeCalendars.value[0]) {
myCalendar.value = safeCalendars.value[0];
}
});
watch(
() => propsEvent.value,
@@ -462,37 +446,6 @@ export default {
files.value = f;
};
// const calendar = computed({
// get() {
// let selected = [];
// console.log(propsEvent.value);
// if (propsEvent.value.event.calendar) {
// let ind = propsEvent.value.mycalendars.findIndex(
// (e) => e.id == propsEvent.value.event.calendar,
// );
// selected.push({
// cl_name: propsEvent.value.mycalendars[ind].cl_name,
// cl_color: propsEvent.value.mycalendars[ind].cl_color,
// id: propsEvent.value.mycalendars[ind].id,
// });
// } else {
// selected.push({
// cl_name: propsEvent.value.mycalendars[0].cl_name,
// cl_color: propsEvent.value.mycalendars[0].cl_color,
// id: propsEvent.value.mycalendars[0].id,
// });
// }
// if (propsEvent.value.event.calendar == null)
// propsEvent.value.event.calendar = propsEvent.value.mycalendars[0].id;
// return selected;
// },
// set(newValue) {
// propsEvent.value.event.calendar = newValue.value;
// },
// });
const returnIdParticant = (idPart) => {
idPart.staff.forEach((e) => {
if (e.selected == true && !propsEvent.value.event.participant.includes(e.id)) {
@@ -520,24 +473,11 @@ export default {
});
};
const dateEvent = computed({
get() {
return formatComa(new Date(propsEvent.value.event.date_start));
},
set(newValue) {
let dateParts = newValue.split('.');
// let d = new Date(propsEvent.value.event.date_start).setFullYear(parseInt(dateParts[2], 10), parseInt(dateParts[1], 10), parseInt(dateParts[0], 10))
// let d = new Date(propsEvent.value.event.date_start).setDate(new Date(2024,01,01))
// propsEvent.value.event.date_start = new Date(2024,01,01);
},
});
const menudate = ref(false);
const postData = (validate) => {
if (validate) {
updatePeriodRule(selectedRule.value);
propsEvent.value.event.calendar = myCalendar.value.id;
let postEvent = new FormData();
@@ -557,111 +497,57 @@ export default {
}
};
const getWeekNumbersBetweenDates = () => {
const start = new Date(propsEvent.value.event.date_start);
const end = new Date(propsEvent.value.event.date_end);
let s = start.getDay();
let e = end.getDay();
const weekNumbers = [];
if (start.getDay() > end.getDay()) {
e = 6;
for (let x = s; x <= e; x++) {
weekNumbers.push(x);
}
const updateDateStart = (newDate) => {
propsEvent.value.event.date_start = newDate;
// При изменении даты начала - обновляем правило повторений
if (selectedRule.value.rule) {
updatePeriodRule(selectedRule.value);
}
if (start.getDay() != end.getDay() && start.getDay() > end.getDay()) {
s = 0;
};
for (let x = s; x <= end.getDay(); x++) {
weekNumbers.push(x);
}
const updateDateEnd = (newDate) => {
propsEvent.value.event.date_end = newDate;
};
// функция обновления периода
const updatePeriodRule = (rule) => {
selectedRule.value = rule;
if (!rule.rule) {
propsEvent.value.event.period = null;
return;
}
if (start.getDay() < end.getDay()) {
for (let x = s; x <= end.getDay(); x++) {
weekNumbers.push(x);
}
const ruleOptions = {
...rule.rule,
dtstart: new Date(propsEvent.value.event.date_start),
};
if (rule.rule.freq === RRule.WEEKLY) {
ruleOptions.byweekday = [new Date(propsEvent.value.event.date_start).getDay()];
}
if (start.getDay() == end.getDay()) {
weekNumbers.push(start.getDay());
if (rule.rule.freq === RRule.MONTHLY) {
ruleOptions.bymonthday = [new Date(propsEvent.value.event.date_start).getDate()];
}
let rulesWeek = [];
weekNumbers.forEach((i) => {
rulesWeek.push(rulleWeek[i]);
if (rule.rule.freq === RRule.YEARLY) {
const date = new Date(propsEvent.value.event.date_start);
ruleOptions.bymonth = [date.getMonth() + 1];
ruleOptions.bymonthday = [date.getDate()];
}
propsEvent.value.event.period = JSON.stringify({
origOptions: ruleOptions,
});
return rulesWeek;
};
const getMonthBetweenDates = () => {
const start = new Date(propsEvent.value.event.date_start);
const end = new Date(propsEvent.value.event.date_end);
let s = start.getDate();
let e = end.getDate();
const dateNumbers = [];
for (let x = s; x <= e; x++) {
dateNumbers.push(x);
}
return dateNumbers;
};
const getYearBetweenDates = () => {
const start = new Date(propsEvent.value.event.date_start);
const end = new Date(propsEvent.value.event.date_end);
let dates = getDatesBetweenDates(start, end);
let date = [];
dates.forEach((e) => date.push(new Date(e).getDate()));
return date;
};
const getNumberMonth = () => {
const start = new Date(propsEvent.value.event.date_start);
const end = new Date(propsEvent.value.event.date_end);
let sm = start.getMonth();
let em = end.getMonth();
let month = [];
month.push(sm + 1);
if (!month.includes(em + 1)) month.push(em + 1);
return month;
};
const getDatesBetweenDates = (startDate, endDate) => {
let dates = [];
let currentDate = new Date(startDate);
while (currentDate <= endDate) {
dates.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
return dates;
};
const periodDisplayRule = (idItem) => {
if (getNumberOfDays.value >= 7 && idItem == 3) {
return true;
} else return false;
};
const getNumberOfDays = computed({
get() {
const start = new Date(propsEvent.value.event.date_start);
const end = new Date(propsEvent.value.event.date_end);
const oneDay = 1000 * 60 * 60 * 24;
const diffInTime = end.getTime() - start.getTime();
const diffInDays = Math.round(diffInTime / oneDay);
return diffInDays;
},
onMounted(() => {
initializeRule();
});
return {
menudate,
titleCard,
newEvent,
propsEvent,
dateEvent,
staff,
newStaff,
returnIdParticant,
@@ -675,11 +561,12 @@ export default {
isNewEvent,
repeatRules,
returnPeriod,
periodDisplayRule,
updatePeriodRule,
selectedRule,
updateDateEnd,
updateDateStart,
createDialog,
getMonthBetweenDates,
};
},
};
+46 -5
View File
@@ -105,13 +105,51 @@ export const useCalendarStore = defineStore('calendarStore', () => {
const allEvents = computed(() => {
return calendars.value
.filter((calendar) => !hiddenCalendarIds.value.includes(calendar.id))
.flatMap((calendar) => calendar.events)
.map((event) => ({
...event,
color: event.color || calendars.value.find((cal) => cal.id === event.calendar_id)?.cl_color,
}));
.flatMap((calendar) =>
calendar.events.map((event) => ({
...event,
calendarData: calendar,
})),
);
});
const editableEvents = computed(() => {
return allEvents.value.filter((event) => {
const calendar = myCalendars.value.find((cal) => cal.id == event.calendar);
if (!calendar) return false;
// Пользователь - автор календаря
if (calendar.author == accountStore.user.is_idEmployee) return true;
// Ищем участника с правами редактора
const participant = calendar.participant.find(
(p) => p.participant_calendar == accountStore.user.is_idEmployee,
);
return participant?.editor === true;
});
});
// Календари, где пользователь имеет права редактора
const editableCalendars = computed(() => {
return myCalendars.value
.filter((calendar) => {
if (calendar.author == accountStore.user.is_idEmployee) return true;
const participant = calendar.participant.find(
(p) => p.participant_calendar === accountStore.user.is_idEmployee,
);
return participant?.editor == true;
})
.map((calendar) => calendar.id);
});
const canEditEvent = (eventId) => {
const id = Number(eventId);
return editableEvents.value.some((e) => e.id === id);
};
// Открыть диалог создания/редактирования
const openEventDialog = (event = null) => {
selectedEvent.value = event;
@@ -142,6 +180,9 @@ export const useCalendarStore = defineStore('calendarStore', () => {
eventsForSelectedDate,
visibleCalendars,
allEvents,
editableCalendars,
editableEvents,
canEditEvent,
// Actions
setSelectedDate,
+2 -2
View File
@@ -8,12 +8,12 @@
</v-col>
</v-row>
<v-row class="fill-height">
<v-col cols="12" md="6" lg="6">
<!-- <v-col cols="12" md="6" lg="6">
<CustomCalendar :view="'dayGridMonth'" :forHomePage="true" class="mini-calendar" />
</v-col>
<v-col cols="12" md="6" lg="6">
<CustomCalendar :view="'timeGridDay'" :forHomePage="true" class="mini-calendar" />
</v-col>
</v-col> -->
</v-row>
</v-col>
<v-col class="d-flex flex-column" lg="5" md="12" cols="12">