fix [P-304]: переделка компонентов от мутаций стора, переход на Pinia для диалогов

This commit is contained in:
Inna committed 2026-05-29 11:55:09 +03:00
1 parent 1f7dc86728
commit 27a2e3680b
12 files changed
+1060 -1222

No files matched your search

@@ -4,7 +4,7 @@
<span class="text-h4">Откликнуться на вакансию</span>
</v-card-text>
<v-card-text class="d-flex flex-column pt-0">
<v-form ref="form_vacancies" @submit.prevent="submit">
<v-form ref="form_vacancies" @submit.prevent="submit">
<v-row no-gutters class="justify-center">
<v-col lg="8">
<v-text-field
@@ -22,25 +22,13 @@
/>
</v-col>
<v-col>
<v-text-field
v-model="form.tel"
:counter="7"
:rules="rules.tel"
label="Телефон"
/>
<v-text-field v-model="form.tel" :counter="7" :rules="rules.tel" label="Телефон" />
</v-col>
</v-row>
<v-textarea
v-model="form.text"
no-resize
rows="4"
label="Сопроводительное письмо"
/>
<v-textarea v-model="form.text" no-resize rows="4" label="Сопроводительное письмо" />
<v-file-input label="Резюме" hide-details v-model="file" />
<v-btn block type="submit" class="mt-4 text-none" color="btn_text">
Отправить
</v-btn>
<v-btn block type="submit" class="mt-4 text-none" color="btn_text"> Отправить </v-btn>
</v-col>
</v-row>
</v-form>
@@ -48,77 +36,60 @@
</div>
</template>
<script>
import { ref } from "vue";
import { useAlertStore } from "@/store/UseAlertStore";
import { clearAxios } from "@/utils/axios-api";
<script setup>
import { ref } from 'vue';
import { useAlertStore } from '@/store/UseAlertStore';
import { clearAxios } from '@/utils/axios-api';
export default {
props: {
idVacations: {
type: Number,
default: -1,
},
const props = defineProps({
idVacations: {
type: Number,
default: -1,
},
setup(props) {
const form = ref({ fio: "", email: "", tel: "", text: "" });
const feedalert = useAlertStore().alert;
});
const req = (val) => {
return !!val || "Поле обязательно";
};
const alertStore = useAlertStore();
const rules = {
fio: [
(val) => req(val),
(val) =>
val.match(/^[а-яА-ЯЁё ]+$/) !== null || "Имя должно содержать русские буквы",
],
email: [(val) => req(val)],
tel: [
(val) => req(val),
(val) => val.match(/^[[\d-]*\d[\d-]*$/) !== null || "Номер должен содержать цифры",
],
text: "",
};
const form = ref({ fio: '', email: '', tel: '', text: '' });
const file = ref(null);
const form_vacancies = ref(null);
const file = ref(null);
const form_vacancies = ref(null)
const rules = {
fio: [
(val) => !!val || 'Поле обязательно',
(val) => /^[а-яА-ЯЁё ]+$/.test(val) || 'Имя должно содержать русские буквы',
],
email: [(val) => !!val || 'Поле обязательно'],
tel: [
(val) => !!val || 'Поле обязательно',
(val) => /^[\d-]+$/.test(val) || 'Номер должен содержать только цифры и дефисы',
],
};
const submit = () => {
const submit = async () => {
const { valid } = await form_vacancies.value.validate();
if (!valid) return;
if(form_vacancies.value.isValid) {
const postFile = new FormData();
postFile.append(
"data",
JSON.stringify({ ...form.value, vacancy_id: props.idVacations })
);
if (file.value !== null) {
const postFile = new FormData();
postFile.append('data', JSON.stringify({ ...form.value, vacancy_id: props.idVacations }));
postFile.append("file", file.value[0]);
}
if (file.value) {
const fileToAppend = Array.isArray(file.value) ? file.value[0] : file.value;
postFile.append('file', fileToAppend);
}
clearAxios
.post(`api/about_inspection/postresponsevacancy/`, postFile)
.then((data) => {
feedalert.alert = true;
feedalert.text = data.data;
feedalert.color = "teal-lighten-4";
feedalert.ico = "mdi-email-outline";
});
}
};
try {
const result = await clearAxios.post(`api/about_inspection/postresponsevacancy/`, postFile);
const message =
typeof result.data === 'string' ? result.data : (result.data?.mess ?? 'Отклик отправлен');
alertStore.showSuccess(message);
return {
form,
file,
rules,
submit,
form_vacancies
};
},
form.value = { fio: '', email: '', tel: '', text: '' };
file.value = null;
form_vacancies.value.resetValidation();
} catch (e) {
alertStore.showError('Не удалось отправить отклик');
console.error(e);
}
};
</script>
@@ -5,7 +5,6 @@
@postData="postData"
@closeDialog="$emit('closeDialog')"
@delObject="delEvent(propsEvent?.event?.id)"
ref="createDialog"
>
<template v-slot:card_text>
<v-row no-gutters class="flex-column">
@@ -30,8 +29,9 @@
<v-col>
<calendar-create-select
:staff="newStaff"
@returnIdParticant="returnIdParticant"
:selectedIds="selectedIds"
:authorID="currentCalendarAuthorId"
@change="onParticipantsChange"
/> </v-col
></v-row>
@@ -71,12 +71,10 @@
<template v-slot:prepend>
<v-avatar class="cursor-pointer" size="8" :color="item.raw.cl_color" />
</template>
<!-- {{ item.title }} -->
</v-list-item>
</template>
</v-autocomplete>
</v-col></v-row
>
</v-autocomplete> </v-col
></v-row>
<v-row no-gutters class="align-top">
<v-col class="text-body-2 text-text_grey pt-3" lg="2"> Дата и время </v-col>
<v-col class="d-flex flex-column">
@@ -185,14 +183,13 @@
</template>
<script setup>
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import { computed, nextTick, 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';
import calendarCreateSelect from '@/components/calendar_of_events/calendar-create-select.vue';
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';
import PeriodEvents from '@/components/calendar_of_events/UI_calendar/periodEvents.vue';
import { useAlertStore } from '@/store/UseAlertStore';
import { RRule } from 'rrule';
@@ -209,17 +206,14 @@ const emit = defineEmits(['update:eventCalendar', 'getCalendar', 'closeDialog'])
const accountStore = useAccountStore();
const calendarStore = useCalendarStore();
const createDialog = ref(null);
const alertStore = useAlertStore();
const selectedIds = ref(new Set());
const { parseRecurrenceOptions, isRecurringEvent } = useRecurrence();
const { requestCreateCalendar } = calendarStore;
const propsEvent = computed({
get: () => {
return props.eventCalendar;
},
set: (value) => emit('update:eventCalendar', value),
});
const propsEvent = computed(() => props.eventCalendar);
const currentCalendarAuthorId = computed(() => {
if (isNewEvent.value) {
@@ -229,77 +223,34 @@ const currentCalendarAuthorId = computed(() => {
// Для существующего события - автор календаря события
const eventCalendarId = propsEvent.value.event.calendar;
const currentCalendar = propsEvent.value.mycalendars?.find(
(cal) => parseInt(cal.id) === parseInt(eventCalendarId),
(cal) => Number(cal.id) === Number(eventCalendarId),
);
return currentCalendar?.author;
}
});
const newStaff = computed({
get() {
let filteredStaff = [];
if (isNewEvent.value) {
if (myCalendar.value == null) return [];
const participants = myCalendar.value.participant || [];
const calendarParticipantIds = new Set(participants.map((p) => p.participant_calendar));
// Мутируем И фильтруем для НОВОГО события
filteredStaff = calendarStore.employees
.map((department) => {
// ФИЛЬТРУЕМ сотрудников - оставляем только тех, кто в календаре
const filteredEmployees = department.employees.filter((employee) =>
calendarParticipantIds.has(employee.id),
);
// МУТАЦИЯ: устанавливаем selected=true для отфильтрованных сотрудников
filteredEmployees.forEach((employee) => {
employee.selected = true;
});
return {
...department,
employees: filteredEmployees,
};
})
.filter((dept) => dept.employees.length > 0);
} else {
// СУЩЕСТВУЮЩЕЕ СОБЫТИЕ - фильтр по календарю
const eventCalendarId = propsEvent.value.event.calendar;
const currentCalendar = propsEvent.value.mycalendars?.find(
(cal) => parseInt(cal.id) === parseInt(eventCalendarId),
const newStaff = computed(() => {
const calendarSource = isNewEvent.value
? myCalendar.value
: propsEvent.value.mycalendars?.find(
(cal) => Number(cal.id) === Number(propsEvent.value.event.calendar),
);
if (!currentCalendar?.participant) return [];
if (!calendarSource) return [];
const calendarParticipantIds = new Set(currentCalendar.participant.map((p) => p.id));
const eventParticipantIds = new Set(propsEvent.value.event.participant || []);
const allowedIds = new Set(
(calendarSource.participant ?? []).map((p) =>
isNewEvent.value ? p.participant_calendar : p.id,
),
);
// Мутируем И фильтруем для СУЩЕСТВУЮЩЕГО события
filteredStaff = calendarStore.employees
.map((department) => {
// ФИЛЬТРУЕМ сотрудников - оставляем только тех, кто в календаре
const filteredEmployees = department.employees.filter((employee) =>
calendarParticipantIds.has(employee.id),
);
// МУТАЦИЯ: устанавливаем selected на основе участников события
filteredEmployees.forEach((employee) => {
employee.selected =
employee.id === accountStore.user.is_idEmployee ||
eventParticipantIds.has(employee.id);
});
return {
...department,
employees: filteredEmployees,
};
})
.filter((dept) => dept.employees.length > 0);
}
return filteredStaff;
},
if (!allowedIds.size) return [];
return calendarStore.employees
.map((dept) => ({
...dept,
employees: dept.employees.filter((e) => allowedIds.has(e.id)),
}))
.filter((dept) => dept.employees.length > 0);
});
// ВАЛИДАЦИЯ
@@ -442,35 +393,18 @@ const isRepeatEndDisabled = computed(() => {
return !selectedRule.value.rule; // disabled если правило null (не повторять)
});
const feedalert = useAlertStore().alert;
const titleCard = computed(() => {
if (propsEvent.value.event.hasOwnProperty('id')) {
return 'Редактирование события';
} else {
return 'Новое событие';
}
});
const titleCard = computed(() =>
'id' in propsEvent.value.event ? 'Редактирование события' : 'Новое событие',
);
const isNewEvent = computed(() => !propsEvent.value.event.hasOwnProperty('id'));
const isNewEvent = computed(() => !('id' in propsEvent.value.event));
const myCalendar = ref(null);
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;
// });
let filtered = (props.allCalendars || []).filter((calendar) => {
if (calendar.author === userId) return true;
const participant = calendar.participant?.find((p) => p.participant_calendar === userId);
@@ -487,74 +421,39 @@ const safeCalendars = computed(() => {
return filtered;
});
const isCalendarsReady = computed(() => safeCalendars.value.length > 0);
// Computed для календаря события
const eventCalendar = computed(() => {
if (!propsEvent.value?.event?.calendar || !safeCalendars.value.length) return null;
return safeCalendars.value.find((cal) => cal.id === propsEvent.value.event.calendar);
});
// Единоразовая инициализация при монтировании/получении данных
const initializeCalendar = () => {
if (myCalendar.value) return; // Уже инициализирован
if (myCalendar.value) return;
// Приоритет 1: календарь из события (редактирование)
if (eventCalendar.value) {
myCalendar.value = eventCalendar.value;
const fromEvent = propsEvent.value?.event?.calendar
? safeCalendars.value.find((cal) => cal.id === propsEvent.value.event.calendar)
: null;
if (fromEvent) {
myCalendar.value = fromEvent;
return;
}
// Приоритет 2: первый доступный календарь (создание)
if (safeCalendars.value.length > 0) {
// myCalendar.value = safeCalendars.value[0];
const firstRealCalendar = safeCalendars.value.find((cal) => cal.id !== 'create_new');
if (firstRealCalendar) {
myCalendar.value = firstRealCalendar;
}
}
const firstRealCalendar = safeCalendars.value.find((cal) => cal.id !== 'create_new');
if (firstRealCalendar) myCalendar.value = firstRealCalendar;
};
// Инициализируем когда все готово
watch(
[() => safeCalendars.value.length, () => propsEvent.value],
(newCalendar) => {
initializeCalendar();
},
{ immediate: true, deep: true },
);
// Дополнительная защита - вотчер только на смену самого календаря
watch(eventCalendar, (newCalendar) => {
if (newCalendar && newCalendar.id !== myCalendar.value?.id) {
myCalendar.value = newCalendar;
}
});
const delEvent = async (idev) => {
try {
const result = await axiosApiInstance.delete(`api/calendar_of_events/my_events/?delid=${idev}`)
feedalert.alert = true
feedalert.text = result.data.mess
feedalert.ico = 'mdi-check'
feedalert.color = 'orange-accent-1'
emit('getCalendar')
emit('closeDialog')
const result = await axiosApiInstance.delete(`api/calendar_of_events/my_events/?delid=${idev}`);
alertStore.showSuccess(result.data.mess)
emit('getCalendar');
emit('closeDialog');
} catch (e) {
console.error('Ошибка удаления события:', e);
alertStore.showError('Ошибка удаления события');
console.error(e);
}
};
const newFiles = ref([]);
const handleFilesUpdate = (updatedExistingFiles) => {
// Сохраняем новые файлы во временную переменную
const currentNewFiles = [...newFiles.value];
// Обновляем существующие файлы
propsEvent.value.event.files = updatedExistingFiles;
// Восстанавливаем новые файлы
newFiles.value = currentNewFiles;
};
@@ -562,31 +461,25 @@ const postFiles = (updatedFiles) => {
newFiles.value = updatedFiles;
};
const returnIdParticant = (idPart) => {
idPart.staff.forEach((e) => {
if (e.selected == true && !propsEvent.value.event.participant.includes(e.id)) {
propsEvent.value.event.participant.push(e.id);
} else {
let ind = propsEvent.value.event.participant.findIndex((l) => l == e.id);
const onParticipantsChange = ({ ids, action }) => {
const next = new Set(selectedIds.value);
if (ind != -1) {
propsEvent.value.event.participant.splice(ind, 1);
}
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);
}
});
};
const cbSelect = (item, arr) => {
item.forEach((e) => {
if (!('employees' in e)) {
if (!propsEvent.value.event.participant.includes(e.id)) {
propsEvent.value.event.participant.push(e.id);
}
}
if ('employees' in e) {
cbSelect(e.employees);
}
});
// Автор всегда участник
next.add(accountStore.user.is_idEmployee);
selectedIds.value = next;
propsEvent.value.event.participant = Array.from(next);
};
const postData = async (validate) => {
@@ -610,14 +503,15 @@ const postData = async (validate) => {
});
}
axiosApiInstance.post('api/calendar_of_events/my_events/', postEvent).then((result) => {
feedalert.alert = true;
feedalert.text = result.data.mess;
feedalert.ico = 'mdi-check';
feedalert.color = 'green-darken-4';
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('Ошибка сохранения события');
}
}
};
@@ -728,39 +622,89 @@ watch(
{ immediate: true },
);
watch([safeCalendars, myCalendar], (newCalendar) => {}, { deep: true, immediate: true });
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),
);
window.$createCalendar();
// Следим за появлением календаря с ID больше максимального
const unwatch = watch(
safeCalendars,
(newCalendars) => {
const realCalendars = newCalendars.filter((cal) => cal.id !== 'create_new');
const newCalendar = realCalendars.find((cal) => cal.id > maxIdBefore);
if (newCalendar) {
myCalendar.value = newCalendar;
unwatch();
}
},
{ deep: true },
);
setTimeout(() => unwatch(), 5000);
}
async function handleCalendarSelect(calendar) {
if (calendar.id !== 'create_new') {
myCalendar.value = calendar;
return;
}
myCalendar.value = calendar;
// Запоминаем id существующих календарей ДО создания
const idsBefore = new Set(
safeCalendars.value.filter((cal) => cal.id !== 'create_new').map((cal) => cal.id),
);
// Открываем диалог создания через store и ждём результат
const created = await requestCreateCalendar();
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),
);
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));
if (fresh) {
myCalendar.value = fresh;
stop();
clearTimeout(timer);
resolve(fresh);
}
},
{ deep: true },
);
const timer = setTimeout(() => {
stop();
resolve(null);
}, timeoutMs);
});
}
watch(
[myCalendar, () => propsEvent.value?.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);
} else {
const ids = propsEvent.value.event.participant ?? [];
selectedIds.value = new Set([accountStore.user.is_idEmployee, ...ids]);
}
},
{ immediate: true },
);
watch(
[
() => safeCalendars.value.length,
() => propsEvent.value?.event?.calendar,
() => propsEvent.value?.event?.id,
],
() => {
initializeCalendar();
},
{ immediate: true },
);
</script>
<style>
@@ -1,446 +1,327 @@
<template>
<div>
<!-- -->
<v-autocomplete
v-model="selectedStaff"
:items="staffed"
v-model="selectedItems"
:items="visibleDepartments"
label="Выберите из списка или найдите по ФИО"
item-title="title"
item-value="id"
:search-input.sync="filtered"
@update:search="(val) => (filtered = val)"
@update:search="(val) => (searchQuery = val ?? '')"
multiple
hide-details
variant="outlined"
density="compact"
class="max-height-select py-3"
return-object
:custom-filter="customFilterFn"
:custom-filter="searchInDepartment"
>
<!-- :custom-filter="onFilter" -->
<template v-slot:selection="{ item }">
<v-chip class="me-2" color="teal-darken-3" size="small" label>
<span> {{ item.title }}</span>
<span>{{ item.title }}</span>
<v-icon
v-if="!isAuthor(item.raw)"
icon="mdi-close-circle"
size="x-small"
class="ml-3"
@click.stop="selectedStaff = item.raw"
@click.stop="selectedItems = item.raw"
/>
</v-chip>
</template>
<template v-slot:prepend-item>
<v-list-item
:disabled="staffed.length == 1 && staffed[0].employees.length == 1"
:disabled="isOnlyOneEmployee"
class="text-body-2"
@click.stop="allUser()"
@click.stop="toggleAllEmployees"
>
<span class="text-body-2"> ВСЕ СОТРУДНИКИ </span>
<span class="text-body-2">ВСЕ СОТРУДНИКИ</span>
<template v-slot:prepend>
<v-checkbox-btn
:model-value="staffed.every((e) => e[okey] == true)"
:disabled="staffed.length == 1 && staffed[0].employees.length == 1"
></v-checkbox-btn>
<v-checkbox-btn :model-value="areAllSelected" :disabled="isOnlyOneEmployee" />
</template>
</v-list-item>
<!-- ВСЕ НАЧАЛЬНИКИ -->
<v-list-item
:disabled="!hasBossesInStaff"
class="text-body-2"
@click.stop="toggleByPosition('начальник')"
@click.stop="toggleByPosition('boss')"
>
<span class="text-body-2"> ВСЕ НАЧАЛЬНИКИ </span>
<span class="text-body-2">ВСЕ НАЧАЛЬНИКИ</span>
<template v-slot:prepend>
<v-checkbox-btn
:model-value="hasBossesSelected"
:disabled="!hasBossesInStaff"
></v-checkbox-btn>
<v-checkbox-btn :model-value="areAllBossesSelected" :disabled="!hasBossesInStaff" />
</template>
</v-list-item>
<!-- ВСЕ ЗАМЕСТИТЕЛИ -->
<v-list-item
:disabled="!hasDeputiesInStaff"
class="text-body-2"
@click.stop="toggleByPosition('заместитель')"
@click.stop="toggleByPosition('deputy')"
>
<span class="text-body-2"> ВСЕ ЗАМЕСТИТЕЛИ </span>
<span class="text-body-2">ВСЕ ЗАМЕСТИТЕЛИ</span>
<template v-slot:prepend>
<v-checkbox-btn
:model-value="hasDeputiesSelected"
:disabled="!hasDeputiesInStaff"
></v-checkbox-btn>
<v-checkbox-btn :model-value="areAllDeputiesSelected" :disabled="!hasDeputiesInStaff" />
</template>
</v-list-item>
<v-divider class="mt-2"></v-divider>
<v-divider class="mt-2" />
</template>
<template v-slot:item="{ props, item }">
<v-list-group v-bind="props" :value="item.raw.title">
<template v-slot:activator="{ props }">
<v-list-item v-bind="props" @click.stop="" density="compact" class="text-body-2">
<template v-slot:item="{ props: itemProps, item }">
<v-list-group v-bind="itemProps" :value="item.raw.title">
<template v-slot:activator="{ props: activatorProps }">
<v-list-item v-bind="activatorProps" density="compact" class="text-body-2" @click.stop>
<template v-slot:prepend>
<v-checkbox-btn
@click.stop="selectedStaff = item.raw"
:color="'indigo-darken-4'"
color="indigo-darken-4"
:true-value="true"
:false-value="false"
:disabled="disable(item.raw) || isAuthor(item.raw)"
:indeterminate="
item.raw.employees.some((e) => e[okey] == true) &&
!item.raw.employees.every((e) => e[okey] == true)
"
:model-value="item.raw[okey]"
></v-checkbox-btn>
:disabled="isDepartmentLocked(item.raw)"
:indeterminate="isDepartmentIndeterminate(item.raw)"
:model-value="isSelected(item.raw)"
@click.stop="selectedItems = item.raw"
/>
</template>
</v-list-item>
</template>
<v-list-item
v-for="x in item.raw.employees.filter((e) =>
e.title.toLowerCase().includes(filtered.toLowerCase()),
)"
:key="x.id"
:value="x.title"
@click.stop="selectedStaff = x"
:disabled=" isAuthor(x)"
v-for="employee in filterEmployees(item.raw.employees)"
:key="employee.id"
:value="employee.title"
density="compact"
:disabled="isAuthor(employee)"
@click.stop="selectedItems = employee"
>
<template v-slot:prepend>
<v-checkbox-btn
:disabled="isAuthor(x)"
:disabled="isAuthor(employee)"
color="indigo-darken-4"
:model-value="x[okey]"
></v-checkbox-btn>
:model-value="isSelected(employee)"
/>
</template>
<span class="text-body-2"> {{ x.title }} </span>
<span class="text-body-2">{{ employee.title }}</span>
</v-list-item>
</v-list-group>
</template>
</v-autocomplete>
</div>
</template>
<script>
import { ref, computed } from 'vue';
import { storeToRefs } from 'pinia';
import { splitname } from '@/utils/universal_functions';
<script setup>
import { computed, ref } from 'vue';
import { useAccountStore } from '@/store/AccountStore';
import { useCalendarStore } from '@/store/calendarStore';
export default {
props: {
staff: {
type: Array,
default: () => [],
},
okey: {
type: String,
default: 'selected',
},
authorID: {
type: Number,
default: null,
},
const props = defineProps({
staff: {
type: Array,
default: () => [],
},
mode: {
type: String,
default: 'participants',
validator: (val) => ['participants', 'editors'].includes(val),
},
authorID: {
type: Number,
default: null,
},
selectedIds: {
type: Set,
default: null,
},
editorIds: {
type: Set,
default: null,
},
});
setup(props, { emit }) {
const filtered = ref('');
const emit = defineEmits(['change']);
const accountStore = useAccountStore();
const calendarStore = useCalendarStore();
const { dictEmployeesLoaded } = storeToRefs(calendarStore);
const accountStore = useAccountStore();
const calendarStore = useCalendarStore();
const back = ref([]);
const searchQuery = ref('');
const staffed = computed({
get() {
if (props.okey == 'editor') {
let ns = [];
props.staff.forEach((e) => {
let emp = { ...e };
emp.employees = e.employees.filter(
(n) => n.selected == true || n.isCurrentUser == true,
);
if (emp.employees.length > 0) ns.push(emp);
});
const isSelected = (item) => {
if ('employees' in item) {
if (item.employees.length === 0) return false;
return item.employees.every((e) => isSelected(e));
}
const targetSet = props.mode === 'editors' ? props.editorIds : props.selectedIds;
return targetSet?.has(item.id) ?? false;
};
ns.forEach((e) => {
if (e.employees.every((w) => w.editor == true)) {
e.editor = true;
}
});
const visibleDepartments = computed(() => {
if (props.mode !== 'editors') return props.staff;
return ns;
}
const isInParticipants = (employee) => props.selectedIds?.has(employee.id) ?? false;
return props.staff
.map((dept) => ({
...dept,
employees: dept.employees.filter(isInParticipants),
}))
.filter((dept) => dept.employees.length > 0);
});
return props.staff;
},
});
const selectedStaff = computed({
get() {
let selected = [];
props.staff.forEach((e) => {
if (e.employees.length != 1 && e.employees.every((n) => n[props.okey] == true)) {
e[props.okey] = true;
selected.push(e);
} else if (e.employees.length == 1) {
const singleEmployee = e.employees[0];
if (singleEmployee[props.okey] === true) {
selected.push(singleEmployee);
}
// Состояние отдела должно вычисляться на основе сотрудника
e[props.okey] = singleEmployee[props.okey] === true;
// e[props.okey] = true;
// selected.push(...e.employees.filter((n) => n[props.okey] == true));
} else {
e[props.okey] = false;
selected.push(...e.employees.filter((n) => n[props.okey] == true));
}
});
return selected;
},
set(item) {
// Если нажимать на пользователя с disable, то срабатывает
// set и отправляет данные которые не нужны, но выдает только в виде массива.
// Остальные данные передаются объектом, кроме выбора ВСЕХ ПОЛЬЗОВАТЕЛЕЙ, для него написан отдельный клик на обработку
// Таким образом предотсвращаем клик на автокомплид (хз понятно или нет)
if (!Array.isArray(item)) {
emitUp(item);
}
},
});
const emitUp = (part) => {
if ('employees' in part) {
part.employees.forEach((e) => {
if (e.id != accountStore.user.is_idEmployee) {
e[props.okey] = !part[props.okey];
}
});
emit('returnIdParticant', {
okey: props.okey,
staff: part.employees,
select: [],
});
} else if (part.length) {
if (part[0].id != accountStore.user.is_idEmployee) {
let val = part.every((e) => e[props.okey] == true) ? false : true;
cbstaff(part, val);
emit('returnIdParticant', {
okey: props.okey,
staff: back.value,
select: [],
});
back.value = [];
}
const selectedItems = computed({
get() {
const chips = [];
props.staff.forEach((dept) => {
if (dept.employees.length > 1 && isSelected(dept)) {
chips.push(dept);
} else if (dept.employees.length === 1) {
const only = dept.employees[0];
if (isSelected(only)) chips.push(only);
} else {
part[props.okey] = !part[props.okey];
emit('returnIdParticant', {
okey: props.okey,
staff: [part],
select: [],
});
chips.push(...dept.employees.filter((e) => isSelected(e)));
}
};
const cbstaff = (item, value) => {
item.forEach((e) => {
if (e.id !== accountStore.user.is_idEmployee) {
e[props.okey] = value;
}
if (!('employees' in e)) {
back.value.push(e);
}
if ('employees' in e) {
cbstaff(e.employees, value);
}
});
};
const customFilterFn = (item, queryText, itemText) => {
if (!queryText) return true;
const searchText = queryText.toLowerCase();
const target = item.raw || item;
// Создаем Map для быстрого поиска отделов по названию
const departmentMap = new Map(staffed.value.map((dept) => [dept.title, dept]));
let department;
if (typeof target === 'string') {
// Ищем отдел по названию
department = departmentMap.get(target);
} else if (target.title) {
// Уже имеем объект отдела
department = target;
}
if (department && department.employees) {
return department.employees.some((employee) =>
employee.title?.toLowerCase().includes(searchText),
);
}
return false;
};
const disable = (department) => {
return department.id == accountStore.user.id_dict_department &&
department.employees.length == 1
? true
: false;
};
// Функция проверки является ли сотрудник создателем
const isAuthor = (item) => {
if (!props.authorID) return false;
// Если это отдел - проверяем всех сотрудников
if ('employees' in item) {
return item.employees.some((emp) => emp.id === props.authorID);
}
// Если это сотрудник - проверяем напрямую
return item.id === props.authorID;
};
const allUser = () => {
emitUp(staffed.value);
};
// Проверяем выбраны ли все начальники (с исключениями)
const hasBossesSelected = computed(() => {
const bosses = findEmployeesByPosition(['начальник', 'и.о'], ['заместитель', 'зам.']);
return bosses.length > 0 && bosses.every((emp) => emp[props.okey] === true);
});
// Проверяем выбраны ли все заместители (с исключениями)
const hasDeputiesSelected = computed(() => {
const deputies = findEmployeesByPosition(['заместитель', 'зам.'], []);
return deputies.length > 0 && deputies.every((emp) => emp[props.okey] === true);
});
// Toggle функция с исключением
const toggleByPosition = (positionType) => {
let keywords = [];
let excludeKeywords = [];
if (positionType === 'начальник') {
keywords = ['начальник', 'и.о'];
excludeKeywords = ['заместитель', 'зам.'];
} else if (positionType === 'заместитель') {
keywords = ['заместитель', 'зам.'];
excludeKeywords = [];
}
const employeesToToggle = findEmployeesByPosition(keywords, excludeKeywords);
const shouldSelect = !employeesToToggle.every((emp) => emp[props.okey] === true);
// if (employeesToToggle.length > 0) {
// employeesToToggle.forEach((employee) => {
// if (employee[props.okey] !== shouldSelect) {
// emitUp(employee);
// }
// });
// }
if (employeesToToggle.length > 0) {
// ФИЛЬТРУЕМ - убираем создателя события из массовых операций
const filteredEmployees = employeesToToggle.filter(
(employee) => employee.id !== props.authorID, //
);
if (filteredEmployees.length > 0) {
filteredEmployees.forEach((employee) => {
if (employee[props.okey] !== shouldSelect) {
selectedStaff.value = employee;
}
});
}
}
};
// Обновленная функция поиска с исключением
const findEmployeesByPosition = (positionKeywords, excludeKeywords = []) => {
const foundEmployees = [];
props.staff.forEach((department) => {
department.employees.forEach((employee) => {
if (department.id == 1) {
return;
}
if (employee.id === accountStore.user.is_idEmployee) {
return;
}
if (props.okey === 'editor' && employee.selected !== true) {
return;
}
const employeeData = calendarStore.dictEmployees.find((de) => de.id === employee.id);
if (employeeData && employeeData.post) {
const post = employeeData.post.toLowerCase();
// Ищем включения и исключения
const hasInclude = positionKeywords.some((keyword) =>
post.includes(keyword.toLowerCase()),
);
const hasExclude = excludeKeywords.some((exclude) =>
post.includes(exclude.toLowerCase()),
);
if (hasInclude && !hasExclude) {
foundEmployees.push(employee);
}
}
});
});
return foundEmployees;
};
// Проверяем есть ли начальники в staff
const hasBossesInStaff = computed(() => {
return (
findEmployeesByPosition(['начальник', 'и.о. начальника'], ['заместитель', 'зам.']).length >
0
);
});
// Проверяем есть ли заместители в staff
const hasDeputiesInStaff = computed(() => {
return (
findEmployeesByPosition(['заместитель начальника', 'зам. начальника', 'заместитель'])
.length > 0
);
});
return {
isAuthor,
staffed,
filtered,
accountStore,
selectedStaff,
splitname,
disable,
allUser,
customFilterFn,
findEmployeesByPosition,
toggleByPosition,
hasBossesInStaff,
hasBossesSelected,
hasDeputiesInStaff,
hasDeputiesSelected,
dictEmployeesLoaded,
};
return chips;
},
set(value) {
if (!Array.isArray(value)) {
emitChange(value);
}
},
});
const emitChange = (item) => {
// Клик по отделу
if ('employees' in item) {
const wasSelected = isSelected(item);
const action = wasSelected ? 'remove' : 'add';
const ids = item.employees.filter((e) => e.id !== props.authorID).map((e) => e.id);
if (ids.length) emit('change', { ids, action });
return;
}
// Массив (групповые операции типа "Все сотрудники")
if (Array.isArray(item)) {
if (!item.length) return;
// Собираем плоский список всех сотрудников из массива департаментов
const allEmployees = [];
item.forEach((entry) => {
if ('employees' in entry) {
allEmployees.push(...entry.employees);
} else {
allEmployees.push(entry);
}
});
const targets = allEmployees.filter((e) => e.id !== props.authorID);
if (!targets.length) return;
const wasAllSelected = targets.every((e) => isSelected(e));
const action = wasAllSelected ? 'remove' : 'add';
const ids = targets.map((e) => e.id);
emit('change', { ids, action });
return;
}
// Клик по отдельному сотруднику
if (item.id === props.authorID) return;
emit('change', { ids: [item.id], action: 'toggle' });
};
const searchInDepartment = (_value, queryText, item) => {
if (!queryText) return true;
const query = queryText.toLowerCase();
const target = item.raw ?? item;
const dept = visibleDepartments.value.find((d) => d.title === target.title) ?? target;
return dept.employees?.some((e) => e.title?.toLowerCase().includes(query)) ?? false;
};
const filterEmployees = (employees) => {
if (!searchQuery.value) return employees;
const query = searchQuery.value.toLowerCase();
return employees.filter((e) => e.title?.toLowerCase().includes(query));
};
const isAuthor = (item) => {
if (!props.authorID) return false;
if ('employees' in item) {
return item.employees.some((e) => e.id === props.authorID);
}
return item.id === props.authorID;
};
const isDepartmentLocked = (dept) =>
dept.id === accountStore.user.id_dict_department && dept.employees.length === 1;
const isOnlyOneEmployee = computed(
() => visibleDepartments.value.length === 1 && visibleDepartments.value[0].employees.length === 1,
);
const isDepartmentIndeterminate = (dept) => {
const some = dept.employees.some((e) => isSelected(e));
const all = dept.employees.every((e) => isSelected(e));
return some && !all;
};
const areAllSelected = computed(
() =>
visibleDepartments.value.length > 0 &&
visibleDepartments.value.every((dept) => isSelected(dept)),
);
const areAllBossesSelected = computed(
() => bosses.value.length > 0 && bosses.value.every((e) => isSelected(e)),
);
const areAllDeputiesSelected = computed(
() => deputies.value.length > 0 && deputies.value.every((e) => isSelected(e)),
);
const toggleAllEmployees = () => {
emitChange(visibleDepartments.value);
};
// Все начальники / Все заместители
const findEmployeesByPosition = (includeKeywords, excludeKeywords = []) => {
const found = [];
props.staff.forEach((dept) => {
if (dept.id === 1) return;
dept.employees.forEach((employee) => {
if (employee.id === accountStore.user.is_idEmployee) return;
if (props.mode === 'editors' && !props.selectedIds?.has(employee.id)) return;
const meta = calendarStore.dictEmployees.find((d) => d.id === employee.id);
if (!meta?.post) return;
const post = meta.post.toLowerCase();
const hasInclude = includeKeywords.some((k) => post.includes(k.toLowerCase()));
const hasExclude = excludeKeywords.some((k) => post.includes(k.toLowerCase()));
if (hasInclude && !hasExclude) found.push(employee);
});
});
return found;
};
const bosses = computed(() =>
findEmployeesByPosition(['начальник', 'и.о'], ['заместитель', 'зам.']),
);
const deputies = computed(() => findEmployeesByPosition(['заместитель', 'зам.'], []));
const hasBossesInStaff = computed(() => bosses.value.length > 0);
const hasDeputiesInStaff = computed(() => deputies.value.length > 0);
const toggleByPosition = (type) => {
const list = type === 'boss' ? bosses.value : deputies.value;
const targets = list.filter((e) => e.id !== props.authorID);
if (!targets.length) return;
const wasAllSelected = targets.every((e) => isSelected);
const action = wasAllSelected ? 'remove' : 'add';
const ids = targets.map((e) => e.id);
emit('change', { ids, action });
};
</script>
@@ -27,7 +27,7 @@
<v-col v-for="(x, key) in color" :key="key">
<v-avatar
class="cursor-pointer"
:class="{ 'avatar-dimmed': propsCalendar.cl_color && propsCalendar.cl_color !== x }"
:class="{ 'avatar-dimmed': propsCalendar.cl_color && propsCalendar.cl_color !== x }"
@click="colorPik(x, key)"
size="x-small"
:color="x"
@@ -38,9 +38,10 @@
<v-col class="text-body-2 text-text_grey" lg="2"> Участники </v-col>
<v-col>
<calendar-create-select
:staff="newStaff"
@returnIdParticant="returnIdParticant"
:staff="staff"
:selectedIds="selectedIds"
:authorID="calendarAuthorId"
@change="onParticipantsChange"
/> </v-col
></v-row>
</v-col>
@@ -61,10 +62,12 @@
<v-col class="text-body-2 text-text_grey" lg="2"> Редакторы </v-col>
<v-col>
<calendar-create-select
:staff="newStaff"
:okey="'editor'"
@returnIdParticant="returnIdParticant"
:staff="staff"
mode="editors"
:selectedIds="selectedIds"
:editorIds="editorIds"
:authorID="calendarAuthorId"
@change="onEditorsChange"
/>
</v-col>
<v-col lg="1" class="text-center">
@@ -84,192 +87,178 @@
</dialog-create>
</template>
<script>
import { computed, ref } from 'vue';
<script setup>
import { computed, ref, onMounted } from 'vue';
import { axiosApiInstance } from '@/utils/axios-api';
import calendarCreateSelect from '@/components/calendar_of_events/calendar-create-select.vue';
import { useAlertStore } from '@/store/UseAlertStore';
import DialogCreate from './UI_calendar/dialogCreate.vue';
import { useAccountStore } from '@/store/AccountStore';
export default {
components: { calendarCreateSelect, DialogCreate },
props: {
calendar: {
type: Object,
default: () => {},
},
const props = defineProps({
calendar: {
type: Object,
default: () => ({}),
},
});
setup(props, { emit }) {
const accountStore = useAccountStore();
const emit = defineEmits(['update:calendar', 'getCalendar', 'closeDialog']);
const calendarAuthorId = computed(() => {
// Для нового календаря - текущий пользователь
if (isNewCalendar.value) {
return accountStore.user.is_idEmployee;
}
// Для существующего - автор из props
return propsCalendar.value.author;
});
const accountStore = useAccountStore();
const staff = ref([]);
const returnIdParticant = (idPart) => {
idPart.staff.forEach((e) => {
let indx = propsCalendar.value.participant.findIndex((l) => l.participant_calendar == e.id);
let ind = propsCalendar.value.participant.find((l) => l.participant_calendar == e.id);
if (idPart.okey == 'editor') {
ind.editor = e.editor;
} else {
if (e.selected == true) {
if (e.id != accountStore.user.is_idEmployee) {
if (indx == -1) {
propsCalendar.value.participant.push({
editor: false,
participant_calendar: e.id,
});
}
}
} else {
let ind = propsCalendar.value.participant.findIndex(
(l) => l.participant_calendar == e.id,
);
const calendarAuthorId = computed(() => {
// Для нового календаря - текущий пользователь
if (isNewCalendar.value) {
return accountStore.user.is_idEmployee;
}
// Для существующего - автор из props
return propsCalendar.value.author;
});
if (ind != -1) {
propsCalendar.value.participant.splice(ind, 1);
}
}
}
});
};
const propsCalendar = computed(() => props.calendar);
const propsCalendar = computed({
get: () => props.calendar,
set: (value) => emit('update:calendar', value),
});
const alertStore = useAlertStore();
const feedalert = useAlertStore().alert;
const req = (val) => {
return !!val || 'Поле обязательно';
};
const rules = {
cl_name: [(val) => req(val)],
cl_descr: [(val) => req(val)],
};
const rules = {
cl_name: [(val) => req(val)],
cl_descr: [(val) => req(val)],
};
const isNewCalendar = computed(() => !propsCalendar.value?.id);
const isAuthor = computed(() => propsCalendar.value.author === accountStore.user.is_idEmployee);
const titleCard = computed(() =>
isNewCalendar.value ? 'Новый календарь' : 'Редактирование календаря',
const isNewCalendar = computed(() => !propsCalendar.value?.id);
const titleCard = computed(() =>
isNewCalendar.value ? 'Новый календарь' : 'Редактирование календаря',
);
const loadStaff = async () => {
try {
const res = await axiosApiInstance.get('api/calendar_of_events/get_employees/');
staff.value = res.data.filter((e) => e.employees.length > 0);
} catch (e) {
console.error('Ошибка загрузки сотрудников, ', e);
}
};
const selectedIds = computed(
() => new Set((propsCalendar.value?.participant ?? []).map((p) => p.participant_calendar)),
);
const editorIds = computed(
() =>
new Set(
(propsCalendar.value?.participant ?? [])
.filter((p) => p.editor === true)
.map((p) => p.participant_calendar),
),
);
const onParticipantsChange = ({ ids, action }) => {
ids.forEach((id) => {
if (id === accountStore.user.is_idEmployee) return;
const existingIdx = propsCalendar.value.participant.findIndex(
(p) => p.participant_calendar === id,
);
const newCalendar = computed(() => (isNewCalendar.value ? true : !isAuthor.value));
const postCalendar = (val) => {
if (val) {
axiosApiInstance
.post(`api/calendar_of_events/my_calendars/`, {
...props.calendar,
participant: propsCalendar.value.participant,
})
.then((result) => {
feedalert.alert = true;
feedalert.text = result.data.mess;
feedalert.ico = 'mdi-check';
feedalert.color = 'green-darken-4';
emit('getCalendar');
emit('closeDialog');
});
if (action === 'add') {
if (existingIdx === -1) {
propsCalendar.value.participant.push({
editor: false,
participant_calendar: id,
});
}
};
const staff = ref([]);
axiosApiInstance.get('api/calendar_of_events/get_employees/').then((res) => {
staff.value = res.data.filter((e) => e.employees.length > 0);
});
const newStaff = computed({
get() {
staff.value.forEach((e) => {
if (propsCalendar.value.participant.length > 0) {
e.employees.forEach((empl) => {
let ab = propsCalendar.value.participant.find(
(a) => a.participant_calendar === empl.id,
);
if (ab) {
empl.selected = true;
empl.editor = ab.editor;
} else {
empl.selected = false;
empl.editor = false;
}
});
}
} else if (action === 'remove') {
if (existingIdx !== -1) {
propsCalendar.value.participant.splice(existingIdx, 1);
}
} else if (action === 'toggle') {
if (existingIdx === -1) {
propsCalendar.value.participant.push({
editor: false,
participant_calendar: id,
});
return staff.value;
},
});
const color = [
'#0ea5e9', // Яркий голубой
'#3b82f6', // Королевский синий
'#10b981', // Изумрудно-зеленый
'#f59e0b', // Теплый янтарный
'#ef4444', // Акцентный красный
'#8b5cf6', // Фиолетовый
'#4f46e5', // Индиго (профессиональный синий)
'#06b6d4', // Бирюзовый
'#84cc16', // Лаймовый
'#f97316', // Оранжевый
'#ec4899', // Розовый
'#6366f1', // Фиолетово-синий
'#14b8a6', // Бирюзово-зеленый
'#eab308', // Золотисто-желтый
'#22c55e', // Зеленый
];
const colorPik = (col) => {
if (propsCalendar.value.cl_color === col) {
propsCalendar.value.cl_color = null;
} else {
propsCalendar.value.cl_color = col;
propsCalendar.value.participant.splice(existingIdx, 1);
}
};
const delCalendar = (idcal) => {
axiosApiInstance
.delete(`api/calendar_of_events/my_calendars/?delid=${idcal}`)
.then((result) => {
feedalert.alert = true;
feedalert.text = result.data.mess;
feedalert.ico = 'mdi-check';
feedalert.color = 'orange-accent-1';
emit('getCalendar');
});
emit('closeDialog');
};
const req = (val) => {
return !!val || 'Поле обязательно';
};
return {
postCalendar,
color,
colorPik,
returnIdParticant,
propsCalendar,
delCalendar,
rules,
titleCard,
newCalendar,
newStaff,
isNewCalendar,
calendarAuthorId,
};
},
}
});
};
const onEditorsChange = ({ ids, action }) => {
ids.forEach((id) => {
const existing = propsCalendar.value.participant.find((p) => p.participant_calendar === id);
if (!existing) return; // нельзя быть редактором, не будучи участником
if (action === 'add') existing.editor = true;
else if (action === 'remove') existing.editor = false;
else if (action === 'toggle') existing.editor = !existing.editor;
});
};
const color = [
'#0ea5e9', // Яркий голубой
'#3b82f6', // Королевский синий
'#10b981', // Изумрудно-зеленый
'#f59e0b', // Теплый янтарный
'#ef4444', // Акцентный красный
'#8b5cf6', // Фиолетовый
'#4f46e5', // Индиго (профессиональный синий)
'#06b6d4', // Бирюзовый
'#84cc16', // Лаймовый
'#f97316', // Оранжевый
'#ec4899', // Розовый
'#6366f1', // Фиолетово-синий
'#14b8a6', // Бирюзово-зеленый
'#eab308', // Золотисто-желтый
'#22c55e', // Зеленый
];
const colorPik = (col) => {
if (propsCalendar.value.cl_color === col) {
propsCalendar.value.cl_color = null;
} else {
propsCalendar.value.cl_color = col;
}
};
const postCalendar = async (val) => {
if (!val) return;
try {
const result = await axiosApiInstance.post(`api/calendar_of_events/my_calendars/`, {
...props.calendar,
participant: propsCalendar.value.participant,
});
alertStore.showSuccess(result.data.mess);
emit('getCalendar');
emit('closeDialog');
} catch (e) {
alertStore.showError('Ошибка сохранения календаря');
console.error(e);
}
};
const delCalendar = async (idcal) => {
try {
const result = await axiosApiInstance.delete(
`api/calendar_of_events/my_calendars/?delid=${idcal}`,
);
alertStore.showWarning(result.data.mess);
emit('getCalendar');
emit('closeDialog');
} catch (e) {
alertStore.showError('Ошибка удаления календаря');
console.error(e);
}
};
onMounted(() => {
loadStaff();
});
</script>
<style>
@@ -74,7 +74,7 @@
</template>
<script setup>
import { onMounted, ref, watch } from 'vue';
import { ref, watch } from 'vue';
import calendarCreate from '@/components/calendar_of_events/calendar-create.vue';
import { useAccountStore } from '@/store/AccountStore';
import { storeToRefs } from 'pinia';
@@ -91,15 +91,18 @@ const showDialog = ref(false);
const accountStore = useAccountStore();
const { user } = storeToRefs(accountStore);
const calendarStore = useCalendarStore();
const { toggleCalendarVisibility, hiddenCalendarIds } = calendarStore;
const { hiddenCalendarIds, showCreateCalendarDialog, createCalendarInitial } =
storeToRefs(calendarStore);
const { toggleCalendarVisibility, resolveCreateCalendar } = calendarStore;
const calendar = ref(null);
const openGroup = ref([0]);
// const trans = ref(false);
const hover = ref(0);
const editCreatedCalendar = (cal) => {
if (cal === undefined) {
if (!cal) {
calendar.value = {
cl_name: '',
participant: [{ editor: true, participant_calendar: user.value.is_idEmployee }],
@@ -112,39 +115,36 @@ const editCreatedCalendar = (cal) => {
showDialog.value = true;
};
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,
}),
);
const isValid = calendar.value?.cl_name?.length > 1;
if (showCreateCalendarDialog.value) {
resolveCreateCalendar(isValid ? JSON.parse(JSON.stringify(calendar.value)) : null);
}
showDialog.value = false;
};
const resetCalendar = () => {
calendar.value = {};
showDialog.value = false;
};
const toggleVisiblityEvents = (cal) => {
toggleCalendarVisibility(cal.id);
};
watch(hiddenCalendarIds, (newHiddenIds) => {}, { deep: true });
watch(
() => props.calendars,
(newCalendars) => {},
{ deep: true },
);
watch(showDialog, (open) => {
if (!open && showCreateCalendarDialog.value) {
resolveCreateCalendar(null);
}
});
watch(showCreateCalendarDialog, (open) => {
if (open && props.title === 'Мои календари') {
editCreatedCalendar(createCalendarInitial.value);
}
});
</script>
<style>
+95 -130
View File
@@ -3,22 +3,21 @@
<v-card-title>
<span class="text-h5">Обратная связь</span>
</v-card-title>
<v-card-text class="px-2 py-0">
<v-card-text class="px-2 py-0">
<v-container>
<v-row>
<v-col class="flex-grow-0 py-0 text-no-wrap align-self-center text-button">
Оцените сайт
<v-col class="flex-grow-0 py-0 text-no-wrap align-self-center text-button">
Оцените сайт
</v-col>
<v-divider class="pb-3"/>
<v-divider class="pb-3" />
</v-row>
<feedstar-like
:rating=feedbackdata
@update:rating="feedbackdata.nowrating = $event"
/>
<feedstar-like :rating="feedbackdata" @update:rating="feedbackdata.nowrating = $event" />
<v-row class="mt-6">
<v-col class="pa-0 px-3">
<v-textarea
<v-textarea
label="Ваши комментарии сделают портал лучше"
hide-details
variant="outlined"
@@ -30,149 +29,115 @@
</v-row>
</v-container>
</v-card-text>
<v-card-actions class="pt-0">
<small v-if="average < 5 || feedbackdata.nowcomment.id!=null" class="pl-5">
Вы оценили сайт на <span class="font-weight-black">{{average}}</span> {{myLabel()}}
<small v-if="average < 5 || feedbackdata.nowcomment.id !== null" class="pl-5">
Вы оценили сайт на <span class="font-weight-black">{{ average }}</span>
{{ ratingLabel }}
</small>
<v-spacer/>
<v-btn
color="modal_btn"
rounded="xl"
text="Закрыть"
@click="menusCloses"
/>
<v-spacer />
<v-btn color="modal_btn" rounded="xl" text="Закрыть" @click="closeMenu" />
<v-btn
color="modal_btn"
variant="text"
:text="feedbackdata.nowcomment.id==null?'Отправить':'Обновить'"
@click="feedSend"
:text="feedbackdata.nowcomment.id === null ? 'Отправить' : 'Обновить'"
@click="sendFeedback"
/>
</v-card-actions>
</v-card>
</template>
<script>
import { ref, onMounted, computed } from 'vue'
import { axiosApiInstance } from '@/utils/axios-api'
<script setup>
import { ref, computed, onMounted } from 'vue';
import { axiosApiInstance } from '@/utils/axios-api';
import FeedstarLike from '@/components/UI/feedback/feedstar-like.vue';
import { useAlertStore } from '@/store/UseAlertStore';
import FeedstarLike from '@/components/UI/feedback/feedstar-like.vue'
import { useAlertStore } from '@/store/UseAlertStore'
defineProps({
LikeDialog: { type: Boolean, default: false },
});
export default {
components: { FeedstarLike },
const emit = defineEmits(['menusClose']);
props: {
LikeDialog: {
type: Boolean,
default: false
}
},
const alertStore = useAlertStore();
const feedbackdata = ref({
nowcomment: { comment: '', id: null },
nowrating: [],
});
setup(props, {emit}) {
const feedalert = useAlertStore().alert
const feedbackdata= ref({nowcomment: {comment: '' }, nowrating: []})
const loadFeedback = async () => {
try {
const { data } = await axiosApiInstance.get('api/feedback/feedbackdata/');
feedbackdata.value = data;
function f_feedbackdata() {
axiosApiInstance.get('api/feedback/feedbackdata/')
.then(data => {
feedbackdata.value = data.data
if (feedbackdata.value.nowrating.length == 0) {
for (let x of feedbackdata.value.basecrit) {
feedbackdata.value.nowrating.push({rating: x.rating, crit: x.id, id: null})
}
if (feedbackdata.value.nowrating.length === 0) {
for (const x of feedbackdata.value.basecrit) {
feedbackdata.value.nowrating.push({
rating: x.rating,
crit: x.id,
id: null,
});
}
if (feedbackdata.value.nowcomment === null) {
feedbackdata.value.nowcomment = { comment: '', id: null}
}
})
}
onMounted(() => {
f_feedbackdata()
})
const average = computed(()=> {
const sum = feedbackdata.value.nowrating.reduce((total, obj)=> total + obj.rating, 0)
const sumlen = sum/feedbackdata.value.nowrating.length
const ukr = Number.isInteger(sumlen)?sumlen:sumlen.toFixed(1)
return ukr
})
function myLabel() {
let labels = ''
if (average.value > 0 && average.value <= 3)
labels = 'УПС-С! Мы обязательно все исправим'
else if (average.value > 2 && average.value <= 4)
labels = 'Спасибо за обратную связь, мы обратим на это внимание'
else if (average.value > 4 && average.value < 5)
labels = 'Класс, будем стараться до 5'
else
labels = "Спасибо за отзыв и высокую оценку ^__^"
return labels
}
function menusCloses() {
emit('menusClose')
}
function feedSend() {
axiosApiInstance.post(`api/feedback/feedbackdata/`, {
nowrating: feedbackdata.value.nowrating,
nowcomment: feedbackdata.value.nowcomment
}).then(data => {})
feedalert.alert = true
textFromAlert()
menusCloses()
}
const textFromAlert = () => {
if (feedbackdata.value.nowcomment.id ==null) {
feedalert.text = "Оценка отправлена, спасибо за участие"
feedalert.ico = "mdi-redo-variant"
feedalert.color = "green-darken-4"
}
else {
feedalert.text = "Оценка обновлена"
feedalert.ico = "mdi-refresh"
feedalert.color="light-blue-darken-4"
if (feedbackdata.value.nowcomment === null) {
feedbackdata.value.nowcomment = { comment: '', id: null };
}
} catch (e) {
console.error('Ошибка загрузки фидбэка:', e);
alertStore.showError('Не удалось загрузить данные обратной связи');
}
};
return {
feedbackdata,
average,
menusCloses,
myLabel,
feedSend,
feedalert
const average = computed(() => {
const ratings = feedbackdata.value.nowrating;
if (!ratings.length) return 0;
const sum = ratings.reduce((total, obj) => total + obj.rating, 0);
const avg = sum / ratings.length;
return Number.isInteger(avg) ? avg : Number(avg.toFixed(1));
});
const ratingLabel = computed(() => {
const avg = average.value;
if (avg > 0 && avg <= 3) return 'УПС-С! Мы обязательно все исправим';
if (avg > 2 && avg <= 4) return 'Спасибо за обратную связь, мы обратим на это внимание';
if (avg > 4 && avg < 5) return 'Класс, будем стараться до 5';
return 'Спасибо за отзыв и высокую оценку ^__^';
});
const closeMenu = () => emit('menusClose');
const sendFeedback = async () => {
const isUpdate = feedbackdata.value.nowcomment.id !== null;
try {
await axiosApiInstance.post('api/feedback/feedbackdata/', {
nowrating: feedbackdata.value.nowrating,
nowcomment: feedbackdata.value.nowcomment,
});
if (isUpdate) {
alertStore.show({
text: 'Оценка обновлена',
ico: 'mdi-refresh',
color: 'light-blue-darken-4',
});
} else {
alertStore.show({
text: 'Оценка отправлена, спасибо за участие',
ico: 'mdi-redo-variant',
color: 'green-darken-4',
});
}
closeMenu();
} catch (e) {
console.error('Ошибка отправки фидбэка:', e);
alertStore.showError('Не удалось отправить отзыв');
}
};
}
onMounted(loadFeedback);
</script>
<style>
.custom_subtitle {
opacity: 1;
}
.v-selection-control__input {
width: 46%!important;
height: 46%!important;
border-radius: 0!important;
}
</style>
+5 -7
View File
@@ -15,8 +15,8 @@
<template v-for="(x, i) in carous" :key="i">
<v-carousel-item v-if="!x.link.endsWith('mp4')" :src="`${burl}${x.link}`" cover eager>
<v-container fill-height fluid pa-0 ma-0 pb-3 class="flex-column h-100 d-flex">
<v-card
v-if="x.text !== '' || x.title != null"
<v-card
v-if="x.text !== '' || x.title != null"
class="bgCard h-100 d-flex flex-column"
style="background: rgba(255, 255, 255, 0.3) !important; background-color: rgba(255, 255, 255, 0.3) !important;"
>
@@ -102,7 +102,7 @@ export default {
/**
* Получает объект alert из хранилища alert для уведомлений.
*/
const feedalert = useAlertStore().alert;
const alertStore = useAlertStore();
/**
* Интервал переключения слайдов в миллисекундах.
@@ -116,10 +116,8 @@ export default {
const getfromserver = () => {
axiosApiInstance.get('api/navigation/carousels/').then((result) => {
if (result.data.mess !== '') {
feedalert.alert = true;
feedalert.text = result.data.mess;
feedalert.color = 'red-darken-2';
feedalert.ico = 'mdi-alert-outline';
alertStore.showSuccess(result.data.mess);
}
if (result.data.result.length > 0) {
+88 -100
View File
@@ -1,118 +1,106 @@
<template>
<v-row no-gutters class="gap ma-3 flex-column">
<v-col lg=2 class='w100 d-flex flex-column'>
<v-row no-gutters class="gap ma-3 flex-column">
<v-col lg="2" class="w100 d-flex flex-column">
<v-row no-gutters class="gap">
<v-col lg="4">
<v-card class="h-100">
<v-card-title> Ежедневная статистика по сотрудникам </v-card-title>
<v-row no-gutters class="gap">
<v-col lg=4>
<v-card class="h-100">
<v-card-title>
Ежедневная статистика по сотрудникам
</v-card-title>
<v-row no-gutters class="gap">
<v-col class="flex-grow-0">
<v-card-subtitle class="mt-2 align-self-end">
1. Скачать файл ежедневной статистики
</v-card-subtitle>
</v-col>
<v-col class="flex-grow-0">
<v-icon
icon="mdi-file-excel"
color="green-darken-3"
@click="excelOp('excround')"
/>
</v-col>
</v-row>
<v-row no-gutters class="gap mt-5">
<v-col class="flex-grow-0">
<v-card-subtitle class="mt-3 align-self-end">
2. Загрузить данные на сервер
</v-card-subtitle>
</v-col>
<v-col >
<v-file-input
accept=".xlsx"
v-model="dailyfiles"
variant="underlined"
density="compact"
label="Прикрепить файл"
hide-details
/>
</v-col>
<v-col class="flex-grow-0 pr-2">
<v-icon
icon="mdi-chevron-double-right"
color="blue-grey-darken-2"
@click="onPickFile('roundfilse')"
/>
</v-col>
</v-row>
</v-card>
</v-col>
<v-col class="flex-grow-0">
<v-card-subtitle class="mt-2 align-self-end">
1. Скачать файл ежедневной статистики
</v-card-subtitle>
</v-col>
<v-col class="flex-grow-0">
<v-icon icon="mdi-file-excel" color="green-darken-3" @click="excelOp('excround')" />
</v-col>
</v-row>
<v-row no-gutters class="gap mt-5">
<v-col class="flex-grow-0">
<v-card-subtitle class="mt-3 align-self-end">
2. Загрузить данные на сервер
</v-card-subtitle>
</v-col>
<v-col>
<v-file-input
accept=".xlsx"
v-model="dailyfiles"
variant="underlined"
density="compact"
label="Прикрепить файл"
hide-details
/>
</v-col>
<v-col class="flex-grow-0 pr-2">
<v-icon
icon="mdi-chevron-double-right"
color="blue-grey-darken-2"
@click="onPickFile('roundfilse')"
/>
</v-col>
</v-row>
</v-card>
</v-col>
</v-row>
</v-row>
</v-col>
</v-row>
</template>
<script>
import { ref } from 'vue'
import { baseURL } from '@/utils/axios-api'
import { axiosApiInstance } from '@/utils/axios-api'
import { useAlertStore } from '@/store/UseAlertStore'
<script setup>
import { ref } from 'vue';
import { baseURL, axiosApiInstance } from '@/utils/axios-api';
import { useAlertStore } from '@/store/UseAlertStore';
export default {
const dailyfiles = ref([]);
const alertStore = useAlertStore();
setup(){
const excelOp = async (ex) => {
try {
const result = await axiosApiInstance.get(`api/general_vacation/dailyroundup/?excel=${ex}`);
const link = document.createElement('a');
link.href = baseURL + result.data.path;
link.click();
link.remove();
} catch (e) {
alertStore.showError('Не удалось получить файл');
console.error(e);
}
};
const dailyfiles = ref([])
const feedalert = useAlertStore().alert
const onPickFile = async (ex) => {
const sdata = new FormData();
sdata.append('dailyfiles', dailyfiles.value);
const excelOp = (ex) => {
axiosApiInstance.get(`api/general_vacation/dailyroundup/?excel=${ex}`).then(result => {
let link = document.createElement("a")
link.href = baseURL+result.data.path
link.click()
link.remove()
})
}
try {
const result = await axiosApiInstance.post(
`api/general_vacation/dailyroundup/?excel=${ex}`,
sdata,
);
const onPickFile = (ex) => {
const sdata = new FormData()
sdata.append('dailyfiles', dailyfiles.value)
axiosApiInstance.post(`api/general_vacation/dailyroundup/?excel=${ex}`, sdata).then(result => {
textFromAlert(result.data['mess'])
})
dailyfiles.value = []
}
const textFromAlert = (info) => {
feedalert.alert = true
if (info == "Файл загружен") {
feedalert.text = "Файл загружен"
feedalert.ico = "mdi-check"
feedalert.color ="green-darken-4"
}
else {
feedalert.text = "Ошибка загрузки"
feedalert.ico = "mdi-alert-circle-outline"
feedalert.color="pink-accent-4"
}
}
return {
excelOp,
baseURL,
dailyfiles,
onPickFile,
feedalert
}
if (result.data.mess === 'Файл загружен') {
alertStore.showSuccess('Файл загружен');
} else {
alertStore.showError(result.data.mess ?? 'Ошибка загрузки');
}
} catch (e) {
alertStore.showError('Ошибка загрузки');
console.error(e);
} finally {
dailyfiles.value = [];
}
};
}
defineExpose({
excelOp,
baseURL,
dailyfiles,
onPickFile,
alertStore,
});
</script>
<style>
.mhight {
height: 150px;
height: 150px;
}
</style>
</style>
+175 -97
View File
@@ -1,11 +1,30 @@
<template>
<v-app>
<v-app-bar :elevation="accountStore.cod2user ? 2 : 0" density="compact" color="app_bar" class="pl-4">
<v-icon v-if="accountStore.cod2user" class="px-3" size="20" color="black_and_white"
:icon="rail ? 'mdi-chevron-right' : 'mdi-chevron-left'" @click="rail = !rail" />
<v-app-bar
:elevation="accountStore.cod2user ? 2 : 0"
density="compact"
color="app_bar"
class="pl-4"
>
<v-icon
v-if="accountStore.cod2user"
class="px-3"
size="20"
color="black_and_white"
:icon="rail ? 'mdi-chevron-right' : 'mdi-chevron-left'"
@click="rail = !rail"
/>
<v-card v-if="accountStore.cod2user" class="bg-transparent py" color="black_and_white" density="compact"
:prepend-avatar="imageSrc" title="Портал МИ ФНС России по ЦОД № 2" variant="text" :to="'/'" />
<v-card
v-if="accountStore.cod2user"
class="bg-transparent py"
color="black_and_white"
density="compact"
:prepend-avatar="imageSrc"
title="Портал МИ ФНС России по ЦОД № 2"
variant="text"
:to="'/'"
/>
<template v-slot:image>
<v-img class="bggrad" />
</template>
@@ -13,15 +32,18 @@
<template v-if="accountStore.cod2user">
<vcard-user :author="accountStore.user" />
<v-tooltip location="bottom">
<template v-slot:activator="{ props }">
<v-btn color="black_and_white" v-bind="props" dark to="/faq" icon="mdi-comment-question-outline" />
<v-btn
color="black_and_white"
v-bind="props"
dark
to="/faq"
icon="mdi-comment-question-outline"
/>
</template>
<span>F.A.Q.</span>
</v-tooltip>
<v-dialog v-model="LikeDialog" persistent width="800">
<template v-slot:activator="{ props }">
<v-btn color="black_and_white" v-bind="props" dark icon="mdi-thumb-up-outline">
@@ -36,7 +58,11 @@
<v-tooltip location="bottom">
<template v-slot:activator="{ props }">
<v-btn icon @click="toggleTheme">
<v-icon v-bind="props" class="mr-1" :color="theme.global.current.value.dark ? 'yellow' : 'lampa'">
<v-icon
v-bind="props"
class="mr-1"
:color="theme.global.current.value.dark ? 'yellow' : 'lampa'"
>
mdi-lightbulb-outline
</v-icon>
</v-btn>
@@ -48,20 +74,25 @@
<v-tooltip location="bottom">
<template v-slot:activator="{ props }">
<v-btn color="black_and_white" icon="mdi-account-multiple-outline" @click="drawer_right = !drawer_right"
v-bind="props" />
<v-btn
color="black_and_white"
icon="mdi-account-multiple-outline"
@click="drawer_right = !drawer_right"
v-bind="props"
/>
</template>
<span>
{{
drawer_right == true
? "Скрыть пользователей"
: "Показать пользователей"
}}
{{ drawer_right == true ? 'Скрыть пользователей' : 'Показать пользователей' }}
</span>
</v-tooltip>
<v-tooltip location="bottom">
<template v-slot:activator="{ props }">
<v-btn color="black_and_white" icon="mdi-logout" @click="accountStore.logout" v-bind="props" />
<v-btn
color="black_and_white"
icon="mdi-logout"
@click="accountStore.logout"
v-bind="props"
/>
</template>
<span> Выход </span>
</v-tooltip>
@@ -74,20 +105,34 @@
</template>
</template>
</v-app-bar>
<v-navigation-drawer v-if="accountStore.cod2user" :width="245" :rail="rail" permanent v-model="drawer">
<v-navigation-drawer
v-if="accountStore.cod2user"
:width="245"
:rail="rail"
permanent
v-model="drawer"
>
<v-row class="my-0 h-100">
<v-col class="flex-column d-flex">
<v-row><v-col>
<v-row
><v-col>
<v-list nav density="compact">
<template v-for="(x, key) in navigations" :key="key">
<!-- v-if="!('submenu' in x) || (x.path== '/portal' && accountStore.user.is_staff)" -->
<v-list-item v-if="(x.path == '/portal'? accountStore.user.is_superuser : true) && !('submenu' in x)
" :key="x.key" :title="x.name" :value="x.name" :href="x.link" :disabled="x.path == ''" :to="x.path"
<v-list-item
v-if="
(x.path == '/portal' ? accountStore.user.is_superuser : true) &&
!('submenu' in x)
"
:key="x.key"
:title="x.name"
:value="x.name"
:href="x.link"
:disabled="x.path == ''"
:to="x.path"
:target="x.link ? '_blank' : ''"
color="navigation"
>
>
<template v-slot:prepend>
<v-icon :icon="x.ico" />
<v-tooltip v-if="rail" activator="parent" location="top">
@@ -96,18 +141,34 @@
</template>
</v-list-item>
<v-list-group v-if="x.path != '/portal' && 'submenu' in x" :class="rail ? 'railmenu' : ''" :key="key"
:value="x.name">
<v-list-group
v-if="x.path != '/portal' && 'submenu' in x"
:class="rail ? 'railmenu' : ''"
:key="key"
:value="x.name"
>
<template v-slot:activator="{ props }">
<v-list-item v-bind="props" :title="x.name" :prepend-icon="x.ico" color="navigation">
<v-list-item
v-bind="props"
:title="x.name"
:prepend-icon="x.ico"
color="navigation"
>
<v-tooltip v-if="rail" activator="parent" location="top">
{{ x.name }}
</v-tooltip>
</v-list-item>
</template>
<v-list-item v-for="(child, k) in x.submenu" color="navigation" :href="child.link" :key="k"
:value="child.name" :title="!rail ? child.name : menuTruncated(child.name)" :to="child.path"
:target="child.link ? '_blank' : ''">
<v-list-item
v-for="(child, k) in x.submenu"
color="navigation"
:href="child.link"
:key="k"
:value="child.name"
:title="!rail ? child.name : menuTruncated(child.name)"
:to="child.path"
:target="child.link ? '_blank' : ''"
>
<v-tooltip v-if="rail" activator="parent" location="top">
{{ child.name }}
</v-tooltip>
@@ -117,8 +178,15 @@
</v-list>
<v-list nav density="compact">
<v-list-item v-for="x of mainmenuStore.portallinks" :key="x.name" :title="x.name" :value="x.name"
:href="x.link" color="app_bar" :target="x.link ? '_blank' : ''">
<v-list-item
v-for="x of mainmenuStore.portallinks"
:key="x.name"
:title="x.name"
:value="x.name"
:href="x.link"
color="app_bar"
:target="x.link ? '_blank' : ''"
>
<template v-slot:prepend>
<v-icon :icon="x.imagecode" />
<v-tooltip v-if="rail" activator="parent" location="top">
@@ -133,7 +201,6 @@
<v-row class="flex-grow-0" v-if="accountStore.user.is_staff">
<v-col>
<AdminMenu :rail="rail" />
</v-col>
</v-row>
<v-row no-gutters class="flex-grow-0">
@@ -148,18 +215,26 @@
<v-main v-if="accountStore.cod2user" class="d-flex bg-main_theme">
<router-view />
<alert-default />
</v-main>
<v-main v-else class="d-flex align-center text-h3 bg-teal-lighten-2">
<v-card class="h-100 w-100 d-flex justify-center rounded-0 flex-column" :image="`${burl}${scrimg}`">
<v-card
class="h-100 w-100 d-flex justify-center rounded-0 flex-column"
:image="`${burl}${scrimg}`"
>
<v-card-text
class="justify-center bgCard h-100 ma-3 d-flex flex-column"
style="background: rgba(255, 255, 255, 0.3) !important; background-color: rgba(255, 255, 255, 0.3) !important;"
style="
background: rgba(255, 255, 255, 0.3) !important;
background-color: rgba(255, 255, 255, 0.3) !important;
"
>
<v-row
class="bgText flex-grow-0"
style="background: rgba(255, 255, 255, 0.5) !important; background-color: rgba(255, 255, 255, 0.5) !important;"
style="
background: rgba(255, 255, 255, 0.5) !important;
background-color: rgba(255, 255, 255, 0.5) !important;
"
>
<v-col class="text-center textcolor font-weight-black text-h3 pb-0">
Добро пожаловать на портал МИ ФНС России по ЦОД № 2
@@ -167,7 +242,10 @@
</v-row>
<v-row
class="bgText flex-grow-0"
style="background: rgba(255, 255, 255, 0.5) !important; background-color: rgba(255, 255, 255, 0.5) !important;"
style="
background: rgba(255, 255, 255, 0.5) !important;
background-color: rgba(255, 255, 255, 0.5) !important;
"
>
<v-col class="text-subtitle-1 text-center textcolor pt-0">
Авторизуйтесь для получения доступа к контенту портала
@@ -178,30 +256,37 @@
<alert-default />
</v-main>
<v-navigation-drawer v-if="accountStore.cod2user" v-model="drawer_right" rail permanent location="right"
@click="rail = false">
<v-navigation-drawer
v-if="accountStore.cod2user"
v-model="drawer_right"
rail
permanent
location="right"
@click="rail = false"
>
<Online-users />
</v-navigation-drawer>
</v-app>
</template>
<script>
import { ref, computed } from "vue";
import uf from "@/utils/universal_functions";
import { useAccountStore } from "@/store/AccountStore";
import { useMainmenuStore } from "@/store/MainmenuStore";
import { useTheme } from "vuetify";
import AuthForm from "@/components/UI/Auth-form.vue";
import OnlineUsers from "@/components/UI/fiousercard/onlineUsers.vue";
import CardLike from "@/components/cardLike.vue";
import { axiosApiInstance, clearAxios } from "@/utils/axios-api";
import { ref, computed } from 'vue';
import uf from '@/utils/universal_functions';
import { useAccountStore } from '@/store/AccountStore';
import { useMainmenuStore } from '@/store/MainmenuStore';
import { useTheme } from 'vuetify';
import AuthForm from '@/components/UI/Auth-form.vue';
import OnlineUsers from '@/components/UI/fiousercard/onlineUsers.vue';
import CardLike from '@/components/cardLike.vue';
import { axiosApiInstance, clearAxios } from '@/utils/axios-api';
import { baseURL } from "@/utils/axios-api";
import VcardUser from "@/components/UI/fiousercard/vcardUser.vue";
import PageCounter from "@/components/UI/defaultportal/page-counter.vue";
import AdminMenu from "@/layouts/default/AdminMenu.vue";
import { baseURL } from '@/utils/axios-api';
import VcardUser from '@/components/UI/fiousercard/vcardUser.vue';
import PageCounter from '@/components/UI/defaultportal/page-counter.vue';
import AdminMenu from '@/layouts/default/AdminMenu.vue';
import alertDefault from './alertDefault.vue';
import { useDisplay } from "vuetify";
import { useDisplay } from 'vuetify';
export default {
components: {
@@ -211,6 +296,7 @@ export default {
VcardUser,
PageCounter,
AdminMenu,
alertDefault,
},
mixins: [uf],
@@ -232,13 +318,12 @@ export default {
const message = computed({
get: () => {
return process.env.NODE_ENV == "development" ? true : false;
return process.env.NODE_ENV == 'development' ? true : false;
},
});
const screenimg = () => {
if (!accountStore.cod2user) {
clearAxios.get(`api/navigation/screensaver/`).then((data) => {
scrimg.value = data.data.img;
});
@@ -252,38 +337,34 @@ export default {
};
const toggleTheme = () => {
theme.global.name.value = theme.global.current.value.dark
? "light"
: "dark";
theme.global.name.value = theme.global.current.value.dark ? 'light' : 'dark';
};
mainmenuStore.loadlinks();
const navigations = ref([
{
name: "Новости",
ico: "mdi-newspaper",
path: "/news",
name: 'Новости',
ico: 'mdi-newspaper',
path: '/news',
},
{
name: "Структура",
ico: "mdi-source-branch",
name: 'Структура',
ico: 'mdi-source-branch',
submenu: [
{
name: "ОКиБ",
path: "/okib",
name: 'ОКиБ',
path: '/okib',
},
],
},
{
name: "Сотрудники",
ico: "mdi-account-multiple-outline",
name: 'Сотрудники',
ico: 'mdi-account-multiple-outline',
submenu: [
{
name: "Справочник",
link: "http://10.252.44.33/accounting6/members.php",
name: 'Справочник',
link: 'http://10.252.44.33/accounting6/members.php',
},
// {
@@ -305,34 +386,32 @@ export default {
// },
{
name: "Календарь",
ico: "mdi-calendar",
path: "/ical",
name: 'Календарь',
ico: 'mdi-calendar',
path: '/ical',
},
{
name: "Голосование",
ico: "mdi-vote",
path: "/vote",
name: 'Голосование',
ico: 'mdi-vote',
path: '/vote',
},
{
name: "Тестирование",
ico: "mdi-book-open-blank-variant",
path: "/test",
name: 'Тестирование',
ico: 'mdi-book-open-blank-variant',
path: '/test',
},
{
name: "Об инспекции",
ico: "mdi-city",
path: "/inspection",
name: 'Об инспекции',
ico: 'mdi-city',
path: '/inspection',
},
{
name: "О портале",
ico: "mdi-information-variant",
path: "/portal",
name: 'О портале',
ico: 'mdi-information-variant',
path: '/portal',
},
]);
const imageSrc = computed(() => {
@@ -341,22 +420,21 @@ export default {
const closeinfo = () => {
LikeDialog.value = false;
// feedalert.value=true
};
const getSafetyChapter = () => {
axiosApiInstance.get("api/safety/gettypes/").then((response) => {
axiosApiInstance.get('api/safety/gettypes/').then((response) => {
response.data.forEach((item) => {
if (!item.path.startsWith("/")) {
item.path = "/" + item.path;
if (!item.path.startsWith('/')) {
item.path = '/' + item.path;
}
item.path = "/safety" + item.path;
item.path = '/safety' + item.path;
});
if (response.data.length > 0) {
let safetyMenu = {
name: "Безопасность",
ico: "mdi-security",
name: 'Безопасность',
ico: 'mdi-security',
submenu: response.data,
};
navigations.value.splice(4, 0, safetyMenu);
+15 -41
View File
@@ -1,52 +1,26 @@
<template>
<v-snackbar
v-model="isOpen"
:timeout="3000"
v-model="feedalert.alert"
:color="feedalert.color"
:icon="feedalert.ico"
:color="alert.color"
>
<v-icon :icon="feedalert.ico" />
<span class="pl-2 text-body-2">
{{ feedalert.text }}
</span>
<v-icon :icon="alert.ico" />
<span class="pl-2 text-body-2">{{ alert.text }}</span>
</v-snackbar>
</template>
<script>
import { watch } from "vue";
import { useAlertStore } from "@/store/UseAlertStore";
<script setup>
import { computed } from 'vue';
import { storeToRefs } from 'pinia';
import { useAlertStore } from '@/store/UseAlertStore';
export default {
name: "AlertDefault",
setup() {
const feedalert = useAlertStore().alert;
const alertStore = useAlertStore();
const { alert } = storeToRefs(alertStore);
watch(
() => feedalert,
() => {
setTimeout(function () {
feedalert.text = "";
feedalert.ico = "";
feedalert.color = "";
feedalert.alert = false;
}, 8000);
},
{ deep: true }
);
return {
feedalert,
};
const isOpen = computed({
get: () => alert.value.alert,
set: (value) => {
if (!value) alertStore.hide();
},
};
});
</script>
<style></style>
+29 -11
View File
@@ -1,14 +1,32 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { defineStore } from 'pinia';
import { ref } from 'vue';
export const useAlertStore = defineStore('uniAlert', () => {
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": ''
})
return { alert }
const show = ({ text, ico = 'mdi-information-outline', color = '#475569' }) => {
alert.value = { alert: true, text, ico, color };
};
})
const showSuccess = (text) => {
show({ text, ico: 'mdi-check-circle-outline', color: '#3F6B5C' });
};
const showError = (text = 'Произошла ошибка') => {
show({ text, ico: 'mdi-alert-circle-outline', color: '#8B3A3A' });
};
const showWarning = (text) => {
show({ text, ico: 'mdi-alert-outline', color: '#A66B2E' });
};
const showInfo = (text) => {
show({ text, ico: 'mdi-information-outline', color: '#3F5A7A' });
};
const hide = () => {
alert.value.alert = false;
};
return { alert, show, showSuccess, showError, showWarning, hide };
});
+32
View File
@@ -23,6 +23,10 @@ export const useCalendarStore = defineStore('calendarStore', () => {
const showEventDialog = ref(false);
const showViewDialog = ref(false);
const showCreateCalendarDialog = ref(false);
const createCalendarInitial = ref(null);
let createCalendarResolver = null;
// Массив ID скрытых календарей. Загружаем из localStorage при инициализации.
const hiddenCalendarIds = ref([]);
@@ -320,6 +324,30 @@ export const useCalendarStore = defineStore('calendarStore', () => {
showEventDialog.value = true;
};
const requestCreateCalendar = (initial = null) => {
// Если уже открыт — резолвим предыдущий запрос как отменённый
if (createCalendarResolver) {
createCalendarResolver(null);
createCalendarResolver = null;
}
createCalendarInitial.value = initial;
showCreateCalendarDialog.value = true;
return new Promise((resolve) => {
createCalendarResolver = resolve;
});
};
const resolveCreateCalendar = (createdCalendar = null) => {
if (createCalendarResolver) {
createCalendarResolver(createdCalendar);
createCalendarResolver = null;
}
showCreateCalendarDialog.value = false;
createCalendarInitial.value = null;
};
return {
// State
selectedDate,
@@ -334,6 +362,8 @@ export const useCalendarStore = defineStore('calendarStore', () => {
hiddenCalendarIds,
holidays,
dictEmployeesLoaded,
showCreateCalendarDialog,
createCalendarInitial,
// Getters
formattedSelectedDate,
@@ -367,5 +397,7 @@ export const useCalendarStore = defineStore('calendarStore', () => {
loadEmployees,
setSelectedEvent,
editFromView,
requestCreateCalendar,
resolveCreateCalendar,
};
});