refactor [P-304]: убраны мутации пропса из EventCreate , чистка правил и вотчеров
This commit is contained in:
1 parent
27a2e3680b
commit
a89279337c
4 files changed
+159
-282
No files matched your search
@@ -4,7 +4,7 @@
|
||||
:newOrOld="isNewEvent"
|
||||
@postData="postData"
|
||||
@closeDialog="$emit('closeDialog')"
|
||||
@delObject="delEvent(propsEvent?.event?.id)"
|
||||
@delObject="delEvent(form.id)"
|
||||
>
|
||||
<template v-slot:card_text>
|
||||
<v-row no-gutters class="flex-column">
|
||||
@@ -19,7 +19,7 @@
|
||||
row-height="25"
|
||||
rows="1"
|
||||
variant="outlined"
|
||||
v-model="propsEvent.event.name"
|
||||
v-model="form.name"
|
||||
:rules="rules.name"
|
||||
></v-textarea> </v-col
|
||||
></v-row>
|
||||
@@ -50,7 +50,7 @@
|
||||
class="py-3 my-select"
|
||||
return-object
|
||||
:rules="rules.calendar"
|
||||
:disabled="'id' in propsEvent.event"
|
||||
:disabled="'id' in form"
|
||||
auto-select-first
|
||||
>
|
||||
<template v-slot:selection="{ item }">
|
||||
@@ -65,7 +65,6 @@
|
||||
:value="item"
|
||||
color="primary"
|
||||
v-bind="props"
|
||||
@click.stop="handleCalendarSelect(item.raw)"
|
||||
:data-calendar-id="item.raw.id"
|
||||
>
|
||||
<template v-slot:prepend>
|
||||
@@ -73,6 +72,18 @@
|
||||
</template>
|
||||
</v-list-item>
|
||||
</template>
|
||||
|
||||
<template v-slot:append-item>
|
||||
<v-divider class="mb-1" />
|
||||
<v-list-item
|
||||
title="➕ Создать календарь"
|
||||
class="text-primary cursor-pointer"
|
||||
@mousedown.prevent="handleCreateCalendar"
|
||||
/></template>
|
||||
|
||||
<template v-slot:no-data>
|
||||
<v-list-item title="Календарей нет" class="text-medium-emphasis text-body-2" />
|
||||
</template>
|
||||
</v-autocomplete> </v-col
|
||||
></v-row>
|
||||
<v-row no-gutters class="align-top">
|
||||
@@ -81,10 +92,10 @@
|
||||
<v-row no-gutters class="gap">
|
||||
<time-select
|
||||
:rule="selectedRule.rule ? selectedRule.rule.freq : -1"
|
||||
:isAllDay="propsEvent.event.allday"
|
||||
:isAllDay="form.allday"
|
||||
:order="[2, 1]"
|
||||
:dateEvent="String(propsEvent.event.date_start)"
|
||||
:limitation="String(propsEvent.event.date_end)"
|
||||
:dateEvent="String(form.date_start)"
|
||||
:limitation="String(form.date_end)"
|
||||
@update:dateEvent="updateDateStart"
|
||||
@adjustEndDate="handleAutoAdjustEnd"
|
||||
/>
|
||||
@@ -93,18 +104,18 @@
|
||||
</v-col>
|
||||
<time-select
|
||||
:rule="selectedRule.rule ? selectedRule.rule.freq : -1"
|
||||
:isAllDay="propsEvent.event.allday"
|
||||
:isAllDay="form.allday"
|
||||
:order="[4, 5]"
|
||||
:dateEvent="String(propsEvent.event.date_end)"
|
||||
:limitation="String(propsEvent.event.date_start)"
|
||||
:dateEvent="String(form.date_end)"
|
||||
:limitation="String(form.date_start)"
|
||||
@update:dateEvent="updateDateEnd"
|
||||
@adjustEndDate="handleAutoAdjustEnd"
|
||||
/>
|
||||
</v-row>
|
||||
<v-row no-gutters>
|
||||
<period-events
|
||||
:dateEvent="propsEvent.event"
|
||||
@update:dateEvent="propsEvent.event = $event"
|
||||
:dateEvent="form"
|
||||
@update:dateEvent="form = $event"
|
||||
/>
|
||||
</v-row>
|
||||
</v-col>
|
||||
@@ -144,7 +155,7 @@
|
||||
:dateEvent="repeatEndDate ? String(repeatEndDate) : String(new Date())"
|
||||
@update:dateEvent="updateRepeatEndDate"
|
||||
class="wide-time-select"
|
||||
:limitation="String(propsEvent.event.date_start)"
|
||||
:limitation="String(form.date_start)"
|
||||
:isEndDateEnabled="!showRepeatEnd"
|
||||
/>
|
||||
</v-col>
|
||||
@@ -160,7 +171,7 @@
|
||||
|
||||
<uploading-file
|
||||
v-model:new-files="newFiles"
|
||||
:files="propsEvent.event.files"
|
||||
:files="form.files"
|
||||
@update:files="handleFilesUpdate"
|
||||
@postFiles="postFiles"
|
||||
/>
|
||||
@@ -173,7 +184,7 @@
|
||||
rows="3"
|
||||
variant="outlined"
|
||||
auto-grow
|
||||
v-model="propsEvent.event.description"
|
||||
v-model="form.description"
|
||||
class="scrollable-textarea pt-3"
|
||||
></v-textarea> </v-col
|
||||
></v-row>
|
||||
@@ -183,7 +194,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
import { computed, nextTick, ref, toRaw, 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';
|
||||
@@ -199,42 +210,44 @@ import { useCalendarStore } from '../../store/calendarStore';
|
||||
const props = defineProps({
|
||||
eventCalendar: Object,
|
||||
allCalendars: Array,
|
||||
selectedRule: Object,
|
||||
});
|
||||
|
||||
const emit = defineEmits(['update:eventCalendar', 'getCalendar', 'closeDialog']);
|
||||
const emit = defineEmits(['getCalendar', 'closeDialog']);
|
||||
|
||||
const accountStore = useAccountStore();
|
||||
const calendarStore = useCalendarStore();
|
||||
const alertStore = useAlertStore();
|
||||
|
||||
const selectedIds = ref(new Set());
|
||||
|
||||
const { parseRecurrenceOptions, isRecurringEvent } = useRecurrence();
|
||||
const { requestCreateCalendar } = calendarStore;
|
||||
|
||||
const propsEvent = computed(() => props.eventCalendar);
|
||||
const form = ref({});
|
||||
const mycalendars = computed(() => props.eventCalendar?.mycalendars ?? []);
|
||||
|
||||
const selectedIds = ref(new Set());
|
||||
const newFiles = ref([]);
|
||||
const myCalendar = ref(null);
|
||||
const selectedRule = ref(null);
|
||||
const showRepeatEnd = ref(false);
|
||||
const repeatEndDate = ref(new Date());
|
||||
|
||||
const isNewEvent = computed(() => !('id' in form.value));
|
||||
const titleCard = computed(() => ('id' in form.value ? 'Редактирование события' : 'Новое событие'));
|
||||
|
||||
const currentCalendarAuthorId = computed(() => {
|
||||
if (isNewEvent.value) {
|
||||
// Для нового события - автор текущего выбранного календаря
|
||||
return myCalendar.value?.author;
|
||||
} else {
|
||||
// Для существующего события - автор календаря события
|
||||
const eventCalendarId = propsEvent.value.event.calendar;
|
||||
const currentCalendar = propsEvent.value.mycalendars?.find(
|
||||
(cal) => Number(cal.id) === Number(eventCalendarId),
|
||||
);
|
||||
return currentCalendar?.author;
|
||||
}
|
||||
const currentCalendar = mycalendars.value.find(
|
||||
(cal) => Number(cal.id) === Number(form.value.calendar),
|
||||
);
|
||||
return currentCalendar?.author;
|
||||
});
|
||||
|
||||
const newStaff = computed(() => {
|
||||
const calendarSource = isNewEvent.value
|
||||
? myCalendar.value
|
||||
: propsEvent.value.mycalendars?.find(
|
||||
(cal) => Number(cal.id) === Number(propsEvent.value.event.calendar),
|
||||
);
|
||||
: mycalendars.value.find((cal) => Number(cal.id) === Number(form.value.calendar));
|
||||
|
||||
if (!calendarSource) return [];
|
||||
|
||||
@@ -253,7 +266,6 @@ const newStaff = computed(() => {
|
||||
.filter((dept) => dept.employees.length > 0);
|
||||
});
|
||||
|
||||
// ВАЛИДАЦИЯ
|
||||
const rules = {
|
||||
name: [
|
||||
(val) => !!val || 'Поле обязательно для заполнения',
|
||||
@@ -265,28 +277,20 @@ const rules = {
|
||||
|
||||
const repeatRules = [
|
||||
{ type: 'Не повторять', rule: null, id: 1 },
|
||||
{
|
||||
type: 'Каждый день',
|
||||
rule: { freq: RRule.DAILY },
|
||||
id: 2,
|
||||
},
|
||||
{ type: 'Каждый день', rule: { freq: RRule.DAILY }, id: 2 },
|
||||
{
|
||||
type: 'Каждую неделю',
|
||||
rule: { freq: RRule.WEEKLY },
|
||||
// По умолчанию - в тот же день недели, что и начальная дата
|
||||
getRule: (startDate) => {
|
||||
const day = new Date(startDate).getDay();
|
||||
// Преобразуем день недели в формат RRule (0 — понедельник)
|
||||
const byweekday = [day === 0 ? RRule.SU : day - 1];
|
||||
return { freq: RRule.WEEKLY, byweekday };
|
||||
},
|
||||
id: 3,
|
||||
},
|
||||
|
||||
{
|
||||
type: 'Каждый месяц',
|
||||
rule: { freq: RRule.MONTHLY },
|
||||
// По умолчанию - в тот же день месяца
|
||||
getRule: (startDate) => ({
|
||||
freq: RRule.MONTHLY,
|
||||
bymonthday: [new Date(startDate).getDate()],
|
||||
@@ -296,21 +300,16 @@ const repeatRules = [
|
||||
{
|
||||
type: 'Каждый квартал',
|
||||
rule: { freq: RRule.MONTHLY, interval: 3 },
|
||||
getRule: (startDate) => {
|
||||
const date = new Date(startDate);
|
||||
return {
|
||||
freq: RRule.MONTHLY,
|
||||
interval: 3, // каждые 3 месяца
|
||||
bymonthday: [date.getDate()],
|
||||
};
|
||||
},
|
||||
getRule: (startDate) => ({
|
||||
freq: RRule.MONTHLY,
|
||||
interval: 3,
|
||||
bymonthday: [new Date(startDate).getDate()],
|
||||
}),
|
||||
id: 6,
|
||||
},
|
||||
|
||||
{
|
||||
type: 'Каждый год',
|
||||
rule: { freq: RRule.YEARLY },
|
||||
// По умолчанию - в тот же день и месяц
|
||||
getRule: (startDate) => {
|
||||
const date = new Date(startDate);
|
||||
return {
|
||||
@@ -323,137 +322,89 @@ const repeatRules = [
|
||||
},
|
||||
];
|
||||
|
||||
const selectedRule = ref(repeatRules[0]);
|
||||
const showRepeatEnd = ref(false);
|
||||
const repeatEndDate = ref(new Date());
|
||||
selectedRule.value = repeatRules[0];
|
||||
|
||||
const isRepeatEndDisabled = computed(() => !selectedRule.value.rule);
|
||||
|
||||
const safeCalendars = computed(() => {
|
||||
const userId = accountStore.user.is_idEmployee;
|
||||
return (props.allCalendars || []).filter((calendar) => {
|
||||
if (calendar.author === userId) return true;
|
||||
const participant = calendar.participant?.find((p) => p.participant_calendar === userId);
|
||||
return participant?.editor === true;
|
||||
});
|
||||
});
|
||||
|
||||
// Инициализация повторов при редактировании
|
||||
const initializeRule = () => {
|
||||
if (!propsEvent.value.event.period) {
|
||||
selectedRule.value = repeatRules[0]; // "Не повторять"
|
||||
repeatEndDate.value = propsEvent.value.event.date_end
|
||||
? new Date(propsEvent.value.event.date_end)
|
||||
: new Date();
|
||||
if (!form.value.period) {
|
||||
selectedRule.value = repeatRules[0];
|
||||
repeatEndDate.value = form.value.date_end ? new Date(form.value.date_end) : new Date();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
// Используем isRecurringEvent для проверки
|
||||
if (isRecurringEvent(propsEvent.value.event)) {
|
||||
// Парсим period с использованием parseRecurrenceOptions
|
||||
const rruleOptions = parseRecurrenceOptions(
|
||||
propsEvent.value.event.period,
|
||||
propsEvent.value.event.date_start,
|
||||
);
|
||||
|
||||
if (isRecurringEvent(form.value)) {
|
||||
const rruleOptions = parseRecurrenceOptions(form.value.period, form.value.date_start);
|
||||
if (rruleOptions) {
|
||||
// ОБНОВЛЕННЫЙ ПОИСК ПРАВИЛА С ПОДДЕРЖКОЙ КВАРТАЛОВ
|
||||
let foundRule;
|
||||
|
||||
// Для квартальных событий (MONTHLY с interval=3)
|
||||
if (rruleOptions.freq === RRule.MONTHLY && rruleOptions.interval === 3) {
|
||||
foundRule = repeatRules.find((rule) => rule.id === 6); // ID квартального правила
|
||||
} else {
|
||||
// Для остальных типов - ищем по freq
|
||||
foundRule = repeatRules.find((rule) => rule.rule?.freq === rruleOptions.freq);
|
||||
}
|
||||
const foundRule =
|
||||
rruleOptions.freq === RRule.MONTHLY && rruleOptions.interval === 3
|
||||
? repeatRules.find((r) => r.id === 6)
|
||||
: repeatRules.find((r) => r.rule?.freq === rruleOptions.freq);
|
||||
|
||||
selectedRule.value = foundRule || repeatRules[0];
|
||||
|
||||
// ВАЖНО: инициализируем repeatEndDate и showRepeatEnd
|
||||
if (rruleOptions.until) {
|
||||
// Если в RRULE есть UNTIL, используем эту дату
|
||||
repeatEndDate.value = new Date(rruleOptions.until);
|
||||
showRepeatEnd.value = true;
|
||||
} else {
|
||||
// Если нет UNTIL, используем date_end события
|
||||
repeatEndDate.value = propsEvent.value.event.date_end
|
||||
? new Date(propsEvent.value.event.date_end)
|
||||
: new Date();
|
||||
repeatEndDate.value = form.value.date_end ? new Date(form.value.date_end) : new Date();
|
||||
showRepeatEnd.value = false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
selectedRule.value = repeatRules[0];
|
||||
showRepeatEnd.value = false;
|
||||
repeatEndDate.value = propsEvent.value.event.date_end
|
||||
? new Date(propsEvent.value.event.date_end)
|
||||
: new Date();
|
||||
repeatEndDate.value = form.value.date_end ? new Date(form.value.date_end) : new Date();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error parsing period:', error, 'Raw period:', propsEvent.value.event.period);
|
||||
console.error('Error parsing period:', error, 'Raw period:', form.value.period);
|
||||
selectedRule.value = repeatRules[0];
|
||||
showRepeatEnd.value = false;
|
||||
repeatEndDate.value = propsEvent.value.event.date_end
|
||||
? new Date(propsEvent.value.event.date_end)
|
||||
: new Date();
|
||||
repeatEndDate.value = form.value.date_end ? new Date(form.value.date_end) : new Date();
|
||||
}
|
||||
};
|
||||
|
||||
const isRepeatEndDisabled = computed(() => {
|
||||
return !selectedRule.value.rule; // disabled если правило null (не повторять)
|
||||
});
|
||||
|
||||
|
||||
const titleCard = computed(() =>
|
||||
'id' in propsEvent.value.event ? 'Редактирование события' : 'Новое событие',
|
||||
);
|
||||
|
||||
const isNewEvent = computed(() => !('id' in propsEvent.value.event));
|
||||
|
||||
const myCalendar = ref(null);
|
||||
|
||||
const safeCalendars = computed(() => {
|
||||
const userId = accountStore.user.is_idEmployee;
|
||||
|
||||
let filtered = (props.allCalendars || []).filter((calendar) => {
|
||||
if (calendar.author === userId) return true;
|
||||
const participant = calendar.participant?.find((p) => p.participant_calendar === userId);
|
||||
return participant?.editor === true;
|
||||
});
|
||||
|
||||
// Добавляем пункт "Создать календарь"
|
||||
filtered.push({
|
||||
id: 'create_new',
|
||||
cl_name: '➕ Создать календарь',
|
||||
isFake: true,
|
||||
});
|
||||
|
||||
return filtered;
|
||||
});
|
||||
|
||||
const initializeCalendar = () => {
|
||||
if (myCalendar.value) return;
|
||||
|
||||
const fromEvent = propsEvent.value?.event?.calendar
|
||||
? safeCalendars.value.find((cal) => cal.id === propsEvent.value.event.calendar)
|
||||
const fromEvent = form.value?.calendar
|
||||
? safeCalendars.value.find((cal) => cal.id === form.value.calendar)
|
||||
: null;
|
||||
|
||||
if (fromEvent) {
|
||||
myCalendar.value = fromEvent;
|
||||
return;
|
||||
}
|
||||
myCalendar.value = fromEvent ?? safeCalendars.value[0] ?? null;
|
||||
};
|
||||
|
||||
const firstRealCalendar = safeCalendars.value.find((cal) => cal.id !== 'create_new');
|
||||
if (firstRealCalendar) myCalendar.value = firstRealCalendar;
|
||||
const initForm = () => {
|
||||
form.value = structuredClone(toRaw(props.eventCalendar?.event ?? {}));
|
||||
newFiles.value = [];
|
||||
myCalendar.value = null;
|
||||
initializeRule();
|
||||
};
|
||||
|
||||
const delEvent = async (idev) => {
|
||||
try {
|
||||
const result = await axiosApiInstance.delete(`api/calendar_of_events/my_events/?delid=${idev}`);
|
||||
alertStore.showSuccess(result.data.mess)
|
||||
alertStore.showSuccess(result.data.mess);
|
||||
emit('getCalendar');
|
||||
emit('closeDialog');
|
||||
} catch (e) {
|
||||
alertStore.showError('Ошибка удаления события');
|
||||
alertStore.showError('Ошибка удаления события');
|
||||
console.error(e);
|
||||
}
|
||||
};
|
||||
|
||||
const newFiles = ref([]);
|
||||
|
||||
const handleFilesUpdate = (updatedExistingFiles) => {
|
||||
const currentNewFiles = [...newFiles.value];
|
||||
propsEvent.value.event.files = updatedExistingFiles;
|
||||
form.value.files = updatedExistingFiles;
|
||||
newFiles.value = currentNewFiles;
|
||||
};
|
||||
|
||||
@@ -463,110 +414,84 @@ const postFiles = (updatedFiles) => {
|
||||
|
||||
const onParticipantsChange = ({ ids, action }) => {
|
||||
const next = new Set(selectedIds.value);
|
||||
|
||||
ids.forEach((id) => {
|
||||
if (action === 'add') {
|
||||
next.add(id);
|
||||
} else if (action === 'remove') {
|
||||
next.delete(id);
|
||||
} else if (action === 'toggle') {
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
}
|
||||
if (action === 'add') next.add(id);
|
||||
else if (action === 'remove') next.delete(id);
|
||||
else if (action === 'toggle') next.has(id) ? next.delete(id) : next.add(id);
|
||||
});
|
||||
|
||||
// Автор всегда участник
|
||||
next.add(accountStore.user.is_idEmployee);
|
||||
|
||||
selectedIds.value = next;
|
||||
propsEvent.value.event.participant = Array.from(next);
|
||||
form.value.participant = Array.from(next);
|
||||
};
|
||||
|
||||
const postData = async (validate) => {
|
||||
if (validate) {
|
||||
await nextTick();
|
||||
if (!validate) return;
|
||||
if (!myCalendar.value) {
|
||||
alertStore.showError('Выберите календарь');
|
||||
return;
|
||||
}
|
||||
|
||||
updatePeriodRule(selectedRule.value);
|
||||
propsEvent.value.event.calendar = myCalendar.value.id;
|
||||
await nextTick();
|
||||
updatePeriodRule(selectedRule.value);
|
||||
form.value.calendar = myCalendar.value.id;
|
||||
|
||||
let postEvent = new FormData();
|
||||
const postEvent = new FormData();
|
||||
postEvent.append('event', JSON.stringify({ ...form.value, files: form.value.files }));
|
||||
|
||||
postEvent.append(
|
||||
'event',
|
||||
JSON.stringify({ ...propsEvent.value.event, files: propsEvent.value.event.files }),
|
||||
);
|
||||
if (newFiles.value.length) {
|
||||
newFiles.value.forEach((file) => postEvent.append('files', file, file.name));
|
||||
}
|
||||
|
||||
if (propsEvent.value.event.files !== null) {
|
||||
// newFiles.value.forEach((e) => postEvent.append('files', e));
|
||||
newFiles.value.forEach((file) => {
|
||||
postEvent.append('files', file, file.name);
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await axiosApiInstance.post('api/calendar_of_events/my_events/', postEvent);
|
||||
console.log(alertStore)
|
||||
alertStore.showSuccess(result.data.mess);
|
||||
emit('getCalendar');
|
||||
emit('closeDialog');
|
||||
} catch (e) {
|
||||
alertStore.showError('Ошибка сохранения события');
|
||||
}
|
||||
try {
|
||||
const result = await axiosApiInstance.post('api/calendar_of_events/my_events/', postEvent);
|
||||
alertStore.showSuccess(result.data.mess);
|
||||
emit('getCalendar');
|
||||
emit('closeDialog');
|
||||
} catch (e) {
|
||||
alertStore.showError('Ошибка сохранения события');
|
||||
console.error(e);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAutoAdjustEnd = (newEndDate) => {
|
||||
propsEvent.value.event.date_end = newEndDate;
|
||||
form.value.date_end = newEndDate;
|
||||
};
|
||||
|
||||
const updateRepeatEndDate = (date) => {
|
||||
repeatEndDate.value = date;
|
||||
updatePeriodRule(selectedRule.value); // Пересоздаем правило с новой датой
|
||||
updatePeriodRule(selectedRule.value);
|
||||
};
|
||||
|
||||
watch(selectedRule, (newRule) => {
|
||||
if (!newRule.rule) {
|
||||
showRepeatEnd.value = false;
|
||||
repeatEndDate.value = null;
|
||||
}
|
||||
});
|
||||
|
||||
const updateDateStart = (newDate) => {
|
||||
// Нормализуем к ISO строке
|
||||
const normalizedDate = new Date(newDate).toISOString();
|
||||
propsEvent.value.event.date_start = normalizedDate;
|
||||
form.value.date_start = normalizedDate;
|
||||
|
||||
// При изменении даты начала - обновляем правило повторений
|
||||
const startDate = new Date(normalizedDate);
|
||||
const endDate = new Date(propsEvent.value.event.date_end);
|
||||
|
||||
const endDate = new Date(form.value.date_end);
|
||||
if (startDate > endDate) {
|
||||
const adjustedEnd = new Date(startDate);
|
||||
adjustedEnd.setHours(startDate.getHours() + 1);
|
||||
propsEvent.value.event.date_end = adjustedEnd.toISOString(); // Тоже ISO
|
||||
form.value.date_end = adjustedEnd.toISOString();
|
||||
}
|
||||
|
||||
if (selectedRule.value.rule) {
|
||||
updatePeriodRule(selectedRule.value);
|
||||
}
|
||||
if (selectedRule.value.rule) updatePeriodRule(selectedRule.value);
|
||||
};
|
||||
|
||||
const updateDateEnd = (newDate) => {
|
||||
// Нормализуем к ISO строке
|
||||
propsEvent.value.event.date_end = new Date(newDate).toISOString();
|
||||
form.value.date_end = new Date(newDate).toISOString();
|
||||
};
|
||||
|
||||
// функция обновления периода
|
||||
const updatePeriodRule = (rule) => {
|
||||
selectedRule.value = rule;
|
||||
|
||||
if (!rule.rule) {
|
||||
propsEvent.value.event.period = null;
|
||||
showRepeatEnd.value = false;
|
||||
repeatEndDate.value = null;
|
||||
form.value.period = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const dtstart = new Date(propsEvent.value.event.date_start);
|
||||
|
||||
const dtstart = new Date(form.value.date_start);
|
||||
const localDtstart = new Date(
|
||||
dtstart.getFullYear(),
|
||||
dtstart.getMonth(),
|
||||
@@ -576,87 +501,45 @@ const updatePeriodRule = (rule) => {
|
||||
dtstart.getSeconds(),
|
||||
);
|
||||
|
||||
const ruleOptions = {
|
||||
...rule.rule,
|
||||
dtstart: localDtstart,
|
||||
};
|
||||
const base = rule.getRule ? rule.getRule(form.value.date_start) : { ...rule.rule };
|
||||
const ruleOptions = { ...base, dtstart: localDtstart };
|
||||
|
||||
if (showRepeatEnd.value && repeatEndDate.value) {
|
||||
const untilDate = new Date(repeatEndDate.value);
|
||||
const u = new Date(repeatEndDate.value);
|
||||
ruleOptions.until = new Date(
|
||||
untilDate.getFullYear(),
|
||||
untilDate.getMonth(),
|
||||
untilDate.getDate(),
|
||||
untilDate.getHours(),
|
||||
untilDate.getMinutes(),
|
||||
untilDate.getSeconds(),
|
||||
u.getFullYear(),
|
||||
u.getMonth(),
|
||||
u.getDate(),
|
||||
u.getHours(),
|
||||
u.getMinutes(),
|
||||
u.getSeconds(),
|
||||
);
|
||||
}
|
||||
|
||||
if (rule.rule.freq === RRule.WEEKLY) {
|
||||
const day = new Date(propsEvent.value.event.date_start).getDay();
|
||||
// Преобразуем день недели в формат RRule (0 — понедельник)
|
||||
const byweekday = [day === 0 ? RRule.SU : day - 1];
|
||||
ruleOptions.byweekday = byweekday;
|
||||
}
|
||||
if (rule.rule.freq === RRule.MONTHLY) {
|
||||
ruleOptions.bymonthday = [new Date(propsEvent.value.event.date_start).getDate()];
|
||||
}
|
||||
if (rule.rule.freq === RRule.YEARLY) {
|
||||
const date = new Date(propsEvent.value.event.date_start);
|
||||
ruleOptions.bymonth = [date.getMonth() + 1];
|
||||
ruleOptions.bymonthday = [date.getDate()];
|
||||
}
|
||||
const rrule = new RRule(ruleOptions);
|
||||
|
||||
propsEvent.value.event.period = rrule.toString();
|
||||
form.value.period = new RRule(ruleOptions).toString();
|
||||
};
|
||||
|
||||
watch(
|
||||
() => propsEvent.value.event?.period,
|
||||
(newPeriod) => {
|
||||
if (newPeriod) {
|
||||
initializeRule();
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
async function handleCalendarSelect(calendar) {
|
||||
if (calendar.id !== 'create_new') {
|
||||
myCalendar.value = calendar;
|
||||
return;
|
||||
}
|
||||
// Запоминаем id существующих календарей ДО создания
|
||||
const idsBefore = new Set(
|
||||
safeCalendars.value.filter((cal) => cal.id !== 'create_new').map((cal) => cal.id),
|
||||
);
|
||||
// Открываем диалог создания через store и ждём результат
|
||||
async function handleCreateCalendar() {
|
||||
const idsBefore = new Set(safeCalendars.value.map((cal) => cal.id));
|
||||
const created = await requestCreateCalendar();
|
||||
if (!created) return; // отменили создание
|
||||
if (!created) return;
|
||||
|
||||
// Просим родителя обновить список календарей
|
||||
emit('getCalendar');
|
||||
// Ждём, пока allCalendars обновится и появится новый календарь
|
||||
await waitForNewCalendar(idsBefore);
|
||||
}
|
||||
|
||||
function waitForNewCalendar(idsBefore, timeoutMs = 5000) {
|
||||
return new Promise((resolve) => {
|
||||
// Вдруг уже появился (getCalendar отработал синхронно)
|
||||
const checkNow = safeCalendars.value.find(
|
||||
(cal) => cal.id !== 'create_new' && !idsBefore.has(cal.id),
|
||||
);
|
||||
const checkNow = safeCalendars.value.find((cal) => !idsBefore.has(cal.id));
|
||||
if (checkNow) {
|
||||
myCalendar.value = checkNow;
|
||||
resolve(checkNow);
|
||||
return;
|
||||
}
|
||||
|
||||
const stop = watch(
|
||||
safeCalendars,
|
||||
(list) => {
|
||||
const fresh = list.find((cal) => cal.id !== 'create_new' && !idsBefore.has(cal.id));
|
||||
const fresh = list.find((cal) => !idsBefore.has(cal.id));
|
||||
if (fresh) {
|
||||
myCalendar.value = fresh;
|
||||
stop();
|
||||
@@ -666,7 +549,6 @@ function waitForNewCalendar(idsBefore, timeoutMs = 5000) {
|
||||
},
|
||||
{ deep: true },
|
||||
);
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
stop();
|
||||
resolve(null);
|
||||
@@ -674,39 +556,34 @@ function waitForNewCalendar(idsBefore, timeoutMs = 5000) {
|
||||
});
|
||||
}
|
||||
|
||||
// Загрузка/переинициализация при смене редактируемого события
|
||||
watch(() => props.eventCalendar?.event?.id, initForm, { immediate: true });
|
||||
|
||||
// Участники: при смене календаря (новое событие) и при загрузке
|
||||
watch(
|
||||
[myCalendar, () => propsEvent.value?.event?.id],
|
||||
[myCalendar, () => props.eventCalendar?.event?.id],
|
||||
() => {
|
||||
if (isNewEvent.value) {
|
||||
const participantIds = (myCalendar.value?.participant ?? []).map(
|
||||
(p) => p.participant_calendar,
|
||||
);
|
||||
|
||||
const ids = new Set([accountStore.user.is_idEmployee, ...participantIds]);
|
||||
|
||||
selectedIds.value = ids;
|
||||
propsEvent.value.event.participant = Array.from(ids);
|
||||
selectedIds.value = new Set([accountStore.user.is_idEmployee, ...participantIds]);
|
||||
form.value.participant = Array.from(selectedIds.value);
|
||||
} else {
|
||||
const ids = propsEvent.value.event.participant ?? [];
|
||||
const ids = form.value.participant ?? [];
|
||||
selectedIds.value = new Set([accountStore.user.is_idEmployee, ...ids]);
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
// Дефолтный календарь при асинхронном приходе allCalendars
|
||||
watch(
|
||||
[
|
||||
() => safeCalendars.value.length,
|
||||
() => propsEvent.value?.event?.calendar,
|
||||
() => propsEvent.value?.event?.id,
|
||||
],
|
||||
() => {
|
||||
initializeCalendar();
|
||||
},
|
||||
[() => safeCalendars.value.length, () => props.eventCalendar?.event?.id],
|
||||
initializeCalendar,
|
||||
{ immediate: true },
|
||||
);
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.scrollable-textarea {
|
||||
overflow-y: auto;
|
||||
|
||||
@@ -14,8 +14,8 @@
|
||||
elevation="1"
|
||||
@click="openEventDialog"
|
||||
>Создать событие</v-btn
|
||||
>
|
||||
<!-- :disabled="!myCalendars || myCalendars.length === 0" -->
|
||||
>
|
||||
<!-- :disabled="!myCalendars || myCalendars.length === 0" -->
|
||||
</v-col>
|
||||
<v-col lg="3">
|
||||
<v-locale-provider locale="ru">
|
||||
|
||||
@@ -131,7 +131,7 @@ const sendFeedback = async () => {
|
||||
color: 'green-darken-4',
|
||||
});
|
||||
}
|
||||
|
||||
await loadFeedback();
|
||||
closeMenu();
|
||||
} catch (e) {
|
||||
console.error('Ошибка отправки фидбэка:', e);
|
||||
|
||||
@@ -2,26 +2,26 @@ import { defineStore } from 'pinia';
|
||||
import { ref } from 'vue';
|
||||
|
||||
export const useAlertStore = defineStore('uniAlert', () => {
|
||||
const alert = ref({ alert: false, text: '', ico: 'mdi-plus', color: '' });
|
||||
const alert = ref({ alert: false, text: '', ico: 'mdi-plus', color: '#6366F1' });
|
||||
|
||||
const show = ({ text, ico = 'mdi-information-outline', color = '#475569' }) => {
|
||||
const show = ({ text, ico = 'mdi-information-outline', color = '' }) => {
|
||||
alert.value = { alert: true, text, ico, color };
|
||||
};
|
||||
|
||||
const showSuccess = (text) => {
|
||||
show({ text, ico: 'mdi-check-circle-outline', color: '#3F6B5C' });
|
||||
show({ text, ico: 'mdi-check-circle-outline', color: '#10B981' });
|
||||
};
|
||||
|
||||
const showError = (text = 'Произошла ошибка') => {
|
||||
show({ text, ico: 'mdi-alert-circle-outline', color: '#8B3A3A' });
|
||||
show({ text, ico: 'mdi-alert-circle-outline', color: '#EF4444' });
|
||||
};
|
||||
|
||||
const showWarning = (text) => {
|
||||
show({ text, ico: 'mdi-alert-outline', color: '#A66B2E' });
|
||||
show({ text, ico: 'mdi-alert-outline', color: '#F59E0B' });
|
||||
};
|
||||
|
||||
const showInfo = (text) => {
|
||||
show({ text, ico: 'mdi-information-outline', color: '#3F5A7A' });
|
||||
show({ text, ico: 'mdi-information-outline', color: '#6366F1' });
|
||||
};
|
||||
|
||||
const hide = () => {
|
||||
|
||||
Reference in new issue
Block a user