fix [P-290]: фикс повтора событий

This commit is contained in:
Inna committed 2025-09-25 14:50:18 +03:00
1 parent 51ab449c33
commit 225f2fa50a
4 files changed
+160 -152

No files matched your search

@@ -80,7 +80,6 @@ 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 {
@@ -303,40 +302,36 @@ export default {
api.removeAllEvents();
allEvents.value.forEach((event) => {
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 rruleOptions = isRecurringEvent(event)
? parseRecurrenceOptions(event.period, event.date_start)
: null;
const baseEvent = {
id: event.id,
title: event.name,
start: new Date(event.date_start),
end: new Date(event.date_end),
allDay: event.all_day,
textColor: '#ffffff',
backgroundColor: eventColor,
borderColor: eventColor,
};
if (!rruleOptions) {
api.addEvent(baseEvent);
return;
}
api.addEvent({
...baseEvent,
rrule: {
...rruleOptions,
},
extendedProps: {
originalEvent: event,
isRecurring: true,
},
});
});
}
};
@@ -376,15 +371,24 @@ export default {
calendarApi.value.changeView(newView);
}
});
watch(
allEvents,
(newEvents) => {
// Обновляем события в календаре при каждом изменении allEvents
updateCalendarEvents();
},
{ deep: true },
); // deep: true на случай, если меняются свойства внутри событий
);
watch(
() => props.eventCalendar,
(newEvent) => {
if (calendarRef.value) {
const api = calendarRef.value.getApi();
api.refetchEvents(); // Обновляем события в календаре
}
},
{ deep: true },
);
return {
currentTitle,
@@ -68,7 +68,7 @@
<script>
import { ref, computed } from 'vue';
import { formatComa, formatDash } from '@/utils/universal_functions';
import { formatComa } from '@/utils/universal_functions';
export default {
props: {
dateEvent: {
@@ -93,8 +93,14 @@ export default {
type: Number,
default: -1,
},
isStart: {
type: Boolean,
default: false,
},
},
emits: ['update:dateEvent', 'adjustEndDate'],
setup(props, { emit }) {
const menudate = ref(false);
const menutime = ref(false);
@@ -125,23 +131,6 @@ export default {
},
});
// const creatwdDate = (date, time) => {
// let tzero = time.split(':');
// time = tzero[0].padStart(2, '0') + ':' + tzero[1];
// if (props.order[0] == 4) {
// if (time == '0:00') {
// propsDateEvent.value = date;
// } else if (new Date(formatDash(date) + 'T' + time) >= new Date(props.limitation)) {
// propsDateEvent.value = new Date(formatDash(date) + 'T' + time);
// } else {
// propsDateEvent.value = new Date(props.limitation);
// }
// } else {
// propsDateEvent.value = time == '0:00' ? date : new Date(formatDash(date) + 'T' + time);
// }
// };
const createdDate = (date, time) => {
const [hours, minutes] = time.split(':').map(Number);
const newDate = new Date(date);
@@ -150,10 +139,27 @@ export default {
if (props.order[0] == 4) {
// Для окончания: проверяем чтобы не было раньше начала
const startDate = new Date(props.limitation);
propsDateEvent.value = newDate >= startDate ? newDate : startDate;
if (newDate <= startDate) {
const correctedDate = new Date(startDate);
correctedDate.setHours(startDate.getHours() + 1);
propsDateEvent.value = newDate;
} else {
propsDateEvent.value = newDate;
}
// propsDateEvent.value = newDate >= startDate ? newDate : startDate;
} else {
// Для начала: просто устанавливаем дату
propsDateEvent.value = newDate;
// Автоматически двигаем окончание, если оно стало раньше начала
const currentEnd = new Date(props.limitation);
if (newDate > currentEnd) {
// Ставим окончание на 1 час позже нового начала
const newEnd = new Date(newDate);
newEnd.setHours(newDate.getHours() + 1);
emit('adjustEndDate', newEnd.toISOString()); // Новый emit
}
}
menudate.value = false;
@@ -161,48 +167,15 @@ export default {
};
const minData = () => {
// let h = `${new Date(props.limitation).getHours()}:${String(
// new Date(props.limitation).getMinutes()
// ).padStart(2, "0")}`;
// let min =
// h == "0:00"
// ? new Date(props.limitation)
// : new Date(
// new Date(props.limitation).setDate(
// new Date(props.limitation).getDate() - 1
// )
// );
// return new Date(min);
return new Date(props.limitation);
};
const startMin = () => {
// if (props.rule == 2) {
// return new Date(
// new Date(props.limitation).setDate(
// new Date(props.limitation).getDate() - 7
// )
// );
// }
// return false;
return new Date(); // ← По умолчанию: нельзя выбрать прошедшие даты
};
const endMax = () => {
// if (props.rule == 2) {
// return new Date(
// new Date(props.limitation).setDate(new Date(props.limitation).getDate() + 6),
// );
// }
// return false;
if (props.order[0] == 2 && props.rule == 2) {
// Для недельного повторения: ограничение сверху +6 дней от начала
return new Date(
new Date(props.limitation).setDate(new Date(props.limitation).getDate() + 6),
);
}
return false; // ← Без ограничения сверху
return null; // ← Без ограничения сверху
};
return {
@@ -1,54 +1,51 @@
import { RRule } from 'rrule';
export function useRecurrence() {
/**
* Парсит строку периода из БД и возвращает опции для RRule
*/
const parseRecurrenceOptions = (periodString) => {
const parseRecurrenceOptions = (periodString, eventDateStart) => {
if (!periodString || periodString === 'null') return null;
try {
// Проверяем, что periodString не пустой и не null
if (!periodString || periodString === 'null' || periodString === 'undefined') {
return null;
// Пробуем распарсить как RRULE-строку
if (periodString.includes('RRULE:')) {
const rrule = RRule.fromString(periodString);
return { ...rrule.origOptions, dtstart: new Date(eventDateStart) };
}
// Пробуем распарсить как JSON
const periodData = JSON.parse(periodString);
// Проверяем, что periodData существует и имеет origOptions
if (!periodData || !periodData.origOptions) {
console.warn('Invalid period data structure:', periodData);
return null;
if (periodData?.origOptions) {
const options = { ...periodData.origOptions };
if (options.dtstart && typeof options.dtstart === 'string') {
options.dtstart = new Date(eventDateStart);
}
return options;
}
return periodData.origOptions;
} catch (error) {
console.error('Failed to parse recurrence rule:', error, 'String:', periodString);
return null;
console.error('Parse recurrence error:', error);
}
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;
}
if (!event.period || event.period === 'null') return false;
return event.period.includes('RRULE:') || JSON.parse(event.period)?.origOptions;
};
/**
* Создает объект правила для нового события
*/
const createRecurrenceRule = (options) => {
const serializableData = {
origOptions: options,
};
return JSON.stringify(serializableData);
const rrule = new RRule({
...options,
dtstart: new Date(options.dtstart),
});
return rrule.toString(); // Возвращаем строку RRULE
};
return {
@@ -89,6 +89,7 @@
: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" />
@@ -100,6 +101,7 @@
:dateEvent="String(propsEvent.event.date_end)"
:limitation="String(propsEvent.event.date_start)"
@update:dateEvent="updateDateEnd"
@adjustEndDate="handleAutoAdjustEnd"
/>
</v-row>
<v-row no-gutters>
@@ -118,20 +120,10 @@
item-value="id"
@update:model-value="updatePeriodRule"
>
<!-- <template v-slot:item="{ props, item }">
<v-list-item
v-bind="props"
:key="item.title"
:value="item"
color="primary"
@click="selectedRule = item.raw"
/>
</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>
@@ -154,7 +146,7 @@
</v-col></v-row
>
<v-row no-gutters class="align-start d-flex pt-3" style="min-height: 150px">
<v-col class="text-body-2 text-text_grey align-start" lg="2"> Файлы </v-col>
<v-col class="text-body-2 text-text_grey pb-5 pt-3" lg="2"> Файлы </v-col>
<uploading-file
:files="propsEvent.event.files"
@@ -179,7 +171,7 @@
</template>
<script>
import { computed, onMounted, ref, watch } from 'vue';
import { computed, 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';
@@ -190,6 +182,7 @@ import ReminderEvent from '@/components/calendar_of_events/UI_calendar/reminderE
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';
export default {
components: {
@@ -215,6 +208,9 @@ export default {
setup(props, { emit }) {
const accountStore = useAccountStore();
const createDialog = ref(null);
const { parseRecurrenceOptions, isRecurringEvent } = useRecurrence();
const propsEvent = computed({
get: () => {
return props.eventCalendar;
@@ -244,10 +240,12 @@ export default {
type: 'Каждую неделю',
rule: { freq: RRule.WEEKLY },
// По умолчанию - в тот же день недели, что и начальная дата
getRule: (startDate) => ({
freq: RRule.WEEKLY,
byweekday: [new Date(startDate).getDay()],
}),
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,
},
{
@@ -284,14 +282,22 @@ export default {
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,
// Используем isRecurringEvent для проверки
if (isRecurringEvent(propsEvent.value.event)) {
// Парсим period с использованием parseRecurrenceOptions
const rruleOptions = parseRecurrenceOptions(
propsEvent.value.event.period,
propsEvent.value.event.date_start,
);
selectedRule.value = foundRule || repeatRules[0];
if (rruleOptions) {
// Находим правило в repeatRules по freq
const foundRule = repeatRules.find((rule) => rule.rule?.freq === rruleOptions.freq);
selectedRule.value = foundRule || repeatRules[0];
}
} else {
selectedRule.value = repeatRules[0];
}
} catch (error) {
console.error('Error parsing period:', error, 'Raw period:', propsEvent.value.event.period);
@@ -312,6 +318,7 @@ export default {
const isNewEvent = computed(() => !propsEvent.value.event.hasOwnProperty('id'));
const myCalendar = ref(null);
// const isNewEvent = computed(() => !propsEvent.value.event.id);
// Computed property с защитой от undefined
const safeCalendars = computed(() => props.myCalendars || []);
@@ -332,7 +339,10 @@ export default {
const isNewEvent = !newEvent.event.id;
if (!isNewEvent) {
if (isNewEvent) {
// НОВОЕ СОБЫТИЕ - первый календарь из списка или календарь по умолчанию
myCalendar.value = safeCalendars.value[0];
} else {
// РЕДАКТИРОВАНИЕ - календарь из события
const eventCalendar = safeCalendars.value.find(
(cal) => cal.id === newEvent.event.calendar,
@@ -498,9 +508,22 @@ export default {
}
};
const handleAutoAdjustEnd = (newEndDate) => {
propsEvent.value.event.date_end = newEndDate;
};
const updateDateStart = (newDate) => {
propsEvent.value.event.date_start = newDate;
// При изменении даты начала - обновляем правило повторений
const startDate = new Date(newDate);
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();
}
if (selectedRule.value.rule) {
updatePeriodRule(selectedRule.value);
}
@@ -519,13 +542,18 @@ export default {
return;
}
const dtstart = new Date(propsEvent.value.event.date_start);
const ruleOptions = {
...rule.rule,
dtstart: new Date(propsEvent.value.event.date_start),
dtstart: dtstart,
};
if (rule.rule.freq === RRule.WEEKLY) {
ruleOptions.byweekday = [new Date(propsEvent.value.event.date_start).getDay()];
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()];
@@ -535,15 +563,20 @@ export default {
ruleOptions.bymonth = [date.getMonth() + 1];
ruleOptions.bymonthday = [date.getDate()];
}
const rrule = new RRule(ruleOptions);
propsEvent.value.event.period = JSON.stringify({
origOptions: ruleOptions,
});
propsEvent.value.event.period = rrule.toString();
};
onMounted(() => {
initializeRule();
});
watch(
() => propsEvent.value.event?.period,
(newPeriod) => {
if (newPeriod) {
initializeRule();
}
},
{ immediate: true }, // Вызовется сразу при создании watch
);
return {
menudate,
@@ -569,6 +602,7 @@ export default {
initializeRule,
createDialog,
handleAutoAdjustEnd,
};
},
};