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
+284 -246

No files matched your search

+2 -1
View File
@@ -43,7 +43,8 @@
"@fullcalendar/multimonth": "^6.1.19", "@fullcalendar/multimonth": "^6.1.19",
"@fullcalendar/timegrid": "^6.1.19", "@fullcalendar/timegrid": "^6.1.19",
"@fullcalendar/list": "6.1.19", "@fullcalendar/list": "6.1.19",
"@fullcalendar/vue3": "^6.1.19" "@fullcalendar/vue3": "^6.1.19",
"@fullcalendar/rrule": "^6.1.15"
}, },
"devDependencies": { "devDependencies": {
"@commitlint/cli": "^19.7.1", "@commitlint/cli": "^19.7.1",
@@ -69,7 +69,7 @@
</v-col> </v-col>
</template> </template>
<script> <script>
import { ref, watch, nextTick, defineEmits } from 'vue'; import { ref, watch, nextTick, computed } from 'vue';
import { storeToRefs } from 'pinia'; import { storeToRefs } from 'pinia';
import dayGridPlugin from '@fullcalendar/daygrid'; import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid'; import timeGridPlugin from '@fullcalendar/timegrid';
@@ -77,8 +77,11 @@ import multiMonthPlugin from '@fullcalendar/multimonth';
import interactionPlugin from '@fullcalendar/interaction'; import interactionPlugin from '@fullcalendar/interaction';
import listPlugin from '@fullcalendar/list'; import listPlugin from '@fullcalendar/list';
import ruLocale from '@fullcalendar/core/locales/ru'; import ruLocale from '@fullcalendar/core/locales/ru';
import rrulePlugin from '@fullcalendar/rrule';
import { onMounted } from 'vue'; import { onMounted } from 'vue';
import { useCalendarStore } from '@/store/calendarStore'; import { useCalendarStore } from '@/store/calendarStore';
import { useAccountStore } from '@/store/AccountStore';
import { useRecurrence } from '@/components/calendar_of_events/composables/useReccurrence';
export default { export default {
name: 'CustomCalendar', name: 'CustomCalendar',
@@ -101,13 +104,23 @@ export default {
const calendarStore = useCalendarStore(); const calendarStore = useCalendarStore();
const { selectedDate, lastUpdatedBy, allEvents } = storeToRefs(calendarStore); const { selectedDate, lastUpdatedBy, allEvents } = storeToRefs(calendarStore);
const { parseRecurrenceOptions, isRecurringEvent } = useRecurrence();
const handleEventClick = (info) => { const handleEventClick = (info) => {
if (calendarStore.canEditEvent(info.event.id)) {
emit('openEventDialog', info); emit('openEventDialog', info);
}
}; };
const calendarOptions = ref({ const calendarOptions = ref({
plugins: [dayGridPlugin, timeGridPlugin, multiMonthPlugin, interactionPlugin, listPlugin], plugins: [
dayGridPlugin,
timeGridPlugin,
multiMonthPlugin,
interactionPlugin,
listPlugin,
rrulePlugin,
],
initialView: props.forHomePage ? props.view : currentView.value, initialView: props.forHomePage ? props.view : currentView.value,
locales: [ruLocale], locales: [ruLocale],
locale: 'ru', locale: 'ru',
@@ -289,17 +302,53 @@ export default {
const api = calendarRef.value.getApi(); const api = calendarRef.value.getApi();
api.removeAllEvents(); api.removeAllEvents();
allEvents.value.forEach((event) => { allEvents.value.forEach((event) => {
const eventColor = calendarColorMap.value.get(event.calendar) || '#3788d8';
// если событие не повторяется
if (!isRecurringEvent) {
api.addEvent({ api.addEvent({
id: event.id, id: event.id,
title: event.name, title: event.name,
start: event.date_start, start: event.date_start,
end: event.date_end, end: event.date_end,
allDay: event.all_day, 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(() => { onMounted(() => {
nextTick(() => { nextTick(() => {
if (calendarRef.value && calendarRef.value.getApi) { if (calendarRef.value && calendarRef.value.getApi) {
@@ -349,6 +398,7 @@ export default {
handleDateSelection, handleDateSelection,
updateCalendarEvents, updateCalendarEvents,
handleEventClick, 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> <template>
<dialog-create <dialog-create
:title="titleCard" :title="titleCard"
:newOrOld="newEvent" :newOrOld="isNewEvent"
@postData="postData" @postData="postData"
@closeDialog="$emit('closeDialog')" @closeDialog="$emit('closeDialog')"
@delObject="delEvent(propsEvent?.event?.id)" @delObject="delEvent(propsEvent?.event?.id)"
@@ -83,23 +83,23 @@
<v-col class="d-flex flex-column"> <v-col class="d-flex flex-column">
<v-row no-gutters class="gap"> <v-row no-gutters class="gap">
<time-select <time-select
:rule="returnPeriod != repeatRules[0].type ? returnPeriod.rule.freq : -1" :rule="selectedRule.rule ? selectedRule.rule.freq : -1"
:chek="propsEvent.event.allday" :chek="propsEvent.event.allday"
:order="[2, 1]" :order="[2, 1]"
:dateEvent="String(propsEvent.event.date_start)" :dateEvent="String(propsEvent.event.date_start)"
:limitation="String(propsEvent.event.date_end)" :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-col class="order-3 flex-grow-0">
<v-icon icon="mdi-minus pt-4" color="grey-darken-1" /> <v-icon icon="mdi-minus pt-4" color="grey-darken-1" />
</v-col> </v-col>
<time-select <time-select
:rule="returnPeriod != repeatRules[0].type ? returnPeriod.rule.freq : -1" :rule="selectedRule.rule ? selectedRule.rule.freq : -1"
:chek="propsEvent.event.allday" :chek="propsEvent.event.allday"
:order="[4, 5]" :order="[4, 5]"
:dateEvent="String(propsEvent.event.date_end)" :dateEvent="String(propsEvent.event.date_end)"
:limitation="String(propsEvent.event.date_start)" :limitation="String(propsEvent.event.date_start)"
@update:dateEvent="propsEvent.event.date_end = $event" @update:dateEvent="updateDateEnd"
/> />
</v-row> </v-row>
<v-row no-gutters> <v-row no-gutters>
@@ -109,28 +109,29 @@
/> />
<v-col lg="7" class="pt-2 ml-5"> <v-col lg="7" class="pt-2 ml-5">
<v-autocomplete <v-autocomplete
v-model="returnPeriod" v-model="selectedRule"
:items="repeatRules" :items="repeatRules"
variant="outlined" variant="outlined"
density="compact" density="compact"
return-object return-object
item-title="type" item-title="type"
item-value="id" item-value="id"
@update:model-value="updatePeriodRule"
> >
<template v-slot:item="{ props, item }"> <!-- <template v-slot:item="{ props, item }">
<v-list-item <v-list-item
v-bind="props" v-bind="props"
:key="item.title" :key="item.title"
:value="item" :value="item"
color="primary" color="primary"
:disabled="periodDisplayRule(item.raw.id)" @click="selectedRule = item.raw"
@click="returnPeriod = item.raw"
/> />
</template> </template> -->
</v-autocomplete> </v-autocomplete>
</v-col> </v-col>
</v-row> </v-col </v-row>
></v-row> </v-col></v-row
>
</v-col> </v-col>
<v-row no-gutters class="align-top flex-grow-0"> <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> <v-col class="text-body-2 text-text_grey pt-3 h-0" lg="2"> Напоминание </v-col>
@@ -178,13 +179,11 @@
</template> </template>
<script> <script>
import { computed, ref, watch } from 'vue'; import { computed, 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 { useCalendarStore } from '@/store/calendarStore';
import DialogCreate from '@/components/calendar_of_events/UI_calendar/dialogCreate.vue'; import DialogCreate from '@/components/calendar_of_events/UI_calendar/dialogCreate.vue';
import calendarCreateSelect from '@/components/calendar_of_events/calendar-create-select.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 TimeSelect from '@/components/calendar_of_events/UI_calendar/timeSelect.vue';
import UploadingFile from '@/components/UI/defaultportal/uploading-file.vue'; import UploadingFile from '@/components/UI/defaultportal/uploading-file.vue';
import ReminderEvent from '@/components/calendar_of_events/UI_calendar/reminderEvent.vue'; import ReminderEvent from '@/components/calendar_of_events/UI_calendar/reminderEvent.vue';
@@ -225,7 +224,6 @@ export default {
set: (value) => emit('update:eventCalendar', value), set: (value) => emit('update:eventCalendar', value),
}); });
// ВАЛИДАЦИЯ // ВАЛИДАЦИЯ
const rules = { const rules = {
name: [ name: [
@@ -237,99 +235,85 @@ export default {
}; };
const repeatRules = [ const repeatRules = [
{ type: 'Не повторять', rule: {}, id: 1 }, { type: 'Не повторять', rule: null, id: 1 },
{ type: 'Каждый день', rule: { freq: 3 }, id: 2 }, {
{ type: 'Каждую неделю', rule: { freq: 2 }, id: 3 }, type: 'Каждый день',
{ type: 'Каждый месяц', rule: { freq: 1 }, id: 4 }, rule: { freq: RRule.DAILY },
{ type: 'Каждый год', rule: { freq: 0 }, id: 5 }, 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({ const selectedRule = ref(repeatRules[0]);
get() { // Инициализация при редактировании
let select = ''; const initializeRule = () => {
if (propsEvent.value.event.period != null) { if (!propsEvent.value.event.period) {
let objRule = JSON.parse(propsEvent.value.event.period); selectedRule.value = repeatRules[0]; // "Не повторять"
if (objRule != null) { return;
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;
} }
calendarNewOrOld(); try {
const periodData = JSON.parse(propsEvent.value.event.period);
return select; if (periodData?.origOptions) {
}, const foundRule = repeatRules.find(
set(newValue) { (rule) => rule.rule?.freq === periodData.origOptions.freq,
drawingRule(newValue.rule); );
}, selectedRule.value = foundRule || repeatRules[0];
}); console.log('Initialized rule:', foundRule); // для дебага
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) {
if (value.freq == 2) { console.error('Error parsing period:', error, 'Raw period:', propsEvent.value.event.period);
newRulse = new RRule({ selectedRule.value = repeatRules[0];
...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 feedalert = useAlertStore().alert;
const req = (val) => { const titleCard = computed(() => {
return !!val || 'Поле обязательно';
};
const titleCard = ref('');
const newEvent = ref(false);
const calendarNewOrOld = () => {
if (propsEvent.value.event.hasOwnProperty('id')) { if (propsEvent.value.event.hasOwnProperty('id')) {
titleCard.value = 'Редактирование события'; return 'Редактирование события';
newEvent.value = false;
} else { } else {
titleCard.value = 'Новое событие'; return 'Новое событие';
newEvent.value = true;
} }
}; });
const isNewEvent = computed(() => !propsEvent.value.event.hasOwnProperty('id'));
const myCalendar = ref(null); 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 // Computed property с защитой от undefined
const safeCalendars = computed(() => props.myCalendars || []); const safeCalendars = computed(() => props.myCalendars || []);
@@ -337,11 +321,11 @@ export default {
const isCalendarsReady = computed(() => safeCalendars.value.length > 0); const isCalendarsReady = computed(() => safeCalendars.value.length > 0);
// Автовыбор при появлении данных // Автовыбор при появлении данных
// watch(isCalendarsReady, (ready) => { watch(isCalendarsReady, (ready) => {
// if (ready && !myCalendar.value && safeCalendars.value[0]) { if (ready && !myCalendar.value && safeCalendars.value[0]) {
// myCalendar.value = safeCalendars.value[0]; myCalendar.value = safeCalendars.value[0];
// } }
// }); });
watch( watch(
() => propsEvent.value, () => propsEvent.value,
@@ -462,37 +446,6 @@ export default {
files.value = f; 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) => { 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)) {
@@ -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 menudate = ref(false);
const postData = (validate) => { const postData = (validate) => {
if (validate) { if (validate) {
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();
@@ -557,111 +497,57 @@ export default {
} }
}; };
const getWeekNumbersBetweenDates = () => { const updateDateStart = (newDate) => {
const start = new Date(propsEvent.value.event.date_start); propsEvent.value.event.date_start = newDate;
const end = new Date(propsEvent.value.event.date_end); // При изменении даты начала - обновляем правило повторений
let s = start.getDay(); if (selectedRule.value.rule) {
let e = end.getDay(); updatePeriodRule(selectedRule.value);
const weekNumbers = [];
if (start.getDay() > end.getDay()) {
e = 6;
for (let x = s; x <= e; x++) {
weekNumbers.push(x);
} }
} };
if (start.getDay() != end.getDay() && start.getDay() > end.getDay()) {
s = 0;
for (let x = s; x <= end.getDay(); x++) { const updateDateEnd = (newDate) => {
weekNumbers.push(x); propsEvent.value.event.date_end = newDate;
};
// функция обновления периода
const updatePeriodRule = (rule) => {
selectedRule.value = rule;
if (!rule.rule) {
propsEvent.value.event.period = null;
return;
} }
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()) { if (rule.rule.freq === RRule.MONTHLY) {
for (let x = s; x <= end.getDay(); x++) { ruleOptions.bymonthday = [new Date(propsEvent.value.event.date_start).getDate()];
weekNumbers.push(x);
} }
if (rule.rule.freq === RRule.YEARLY) {
const date = new Date(propsEvent.value.event.date_start);
ruleOptions.bymonth = [date.getMonth() + 1];
ruleOptions.bymonthday = [date.getDate()];
} }
if (start.getDay() == end.getDay()) {
weekNumbers.push(start.getDay()); propsEvent.value.event.period = JSON.stringify({
} origOptions: ruleOptions,
let rulesWeek = [];
weekNumbers.forEach((i) => {
rulesWeek.push(rulleWeek[i]);
}); });
return rulesWeek;
}; };
const getMonthBetweenDates = () => { onMounted(() => {
const start = new Date(propsEvent.value.event.date_start); initializeRule();
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;
},
}); });
return { return {
menudate, menudate,
titleCard, titleCard,
newEvent,
propsEvent, propsEvent,
dateEvent,
staff, staff,
newStaff, newStaff,
returnIdParticant, returnIdParticant,
@@ -675,11 +561,12 @@ export default {
isNewEvent, isNewEvent,
repeatRules, repeatRules,
returnPeriod, updatePeriodRule,
periodDisplayRule, selectedRule,
updateDateEnd,
updateDateStart,
createDialog, createDialog,
getMonthBetweenDates,
}; };
}, },
}; };
+45 -4
View File
@@ -105,13 +105,51 @@ export const useCalendarStore = defineStore('calendarStore', () => {
const allEvents = computed(() => { const allEvents = computed(() => {
return calendars.value return calendars.value
.filter((calendar) => !hiddenCalendarIds.value.includes(calendar.id)) .filter((calendar) => !hiddenCalendarIds.value.includes(calendar.id))
.flatMap((calendar) => calendar.events) .flatMap((calendar) =>
.map((event) => ({ calendar.events.map((event) => ({
...event, ...event,
color: event.color || calendars.value.find((cal) => cal.id === event.calendar_id)?.cl_color, 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) => { const openEventDialog = (event = null) => {
selectedEvent.value = event; selectedEvent.value = event;
@@ -142,6 +180,9 @@ export const useCalendarStore = defineStore('calendarStore', () => {
eventsForSelectedDate, eventsForSelectedDate,
visibleCalendars, visibleCalendars,
allEvents, allEvents,
editableCalendars,
editableEvents,
canEditEvent,
// Actions // Actions
setSelectedDate, setSelectedDate,
+2 -2
View File
@@ -8,12 +8,12 @@
</v-col> </v-col>
</v-row> </v-row>
<v-row class="fill-height"> <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" /> <CustomCalendar :view="'dayGridMonth'" :forHomePage="true" class="mini-calendar" />
</v-col> </v-col>
<v-col cols="12" md="6" lg="6"> <v-col cols="12" md="6" lg="6">
<CustomCalendar :view="'timeGridDay'" :forHomePage="true" class="mini-calendar" /> <CustomCalendar :view="'timeGridDay'" :forHomePage="true" class="mini-calendar" />
</v-col> </v-col> -->
</v-row> </v-row>
</v-col> </v-col>
<v-col class="d-flex flex-column" lg="5" md="12" cols="12"> <v-col class="d-flex flex-column" lg="5" md="12" cols="12">