24 Commits
Author SHA1 Message Date
cja 88c9403fa4 EventFiles 2025-10-01 13:06:13 +03:00
Inna f27037ebe5 fix [P-47]: фикс событий 2025-09-30 14:39:12 +03:00
Inna a839273951 fix [P-47]: фикс событий 2025-09-30 12:07:58 +03:00
Inna 2c609e2fd9 fix [P-51]: добавлены праздники к dare-picker 2025-09-29 15:51:16 +03:00
Inna 5edadc5ef7 fix [P-47]: прикрепление файлов 2025-09-29 13:19:37 +03:00
Inna b29e7eb535 fix [P-290]: добавление файла к событию 2025-09-29 08:25:21 +03:00
Inna 1e1311bb22 fix [P-51]: переход на расписание при клике на день 2025-09-26 14:54:11 +03:00
Inna 37b1f18c4c fix [P-51]: добавлено визуальное отображение праздничных дней 2025-09-26 14:34:20 +03:00
Inna 76a6d0ae20 fix [P-290]: исправлен виджет календаря на домашней странице 2025-09-26 08:41:29 +03:00
Inna 45f365f734 fix [P-290]: фикс повтора событий 2025-09-25 16:26:31 +03:00
Inna 76fb9316cd fix [P-290]: фикс повтора событий 2025-09-25 14:50:18 +03:00
Inna 22f9220a57 fix [P-290]: фикс ошибок 2025-09-25 12:37:53 +03:00
Inna 77d6679f39 refactor [P-52]: исправление функционала повторения событий 2025-09-24 11:19:35 +03:00
Inna f189636791 fix [P-47]: редактирование и удаление событий 2025-09-23 13:36:43 +03:00
Inna 1f898f9281 fix [P-47]: исправления выбора дат в форме 2025-09-23 09:45:33 +03:00
Inna 21ed19749e refactor [P-47]: упрощение логики, возможность выбора всех сотрудников для событий 2025-09-22 16:46:20 +03:00
Inna e8dbb47479 fix [P-56]: изменение логики отображения событий 2025-09-22 12:47:58 +03:00
Inna 65f76c65b7 fix [P-47]: отображение событий 2025-09-18 12:09:40 +03:00
cja 5a746ff4b0 MyEvents get 2025-09-17 16:02:04 +03:00
Inna dbb5799d7c fix [P-57]: тестовый запрос 2025-09-17 15:56:05 +03:00
Inna 0e2440d94e fix [P-57]: связка календарей 2025-09-16 14:13:21 +03:00
Inna d003ab12e7 fix [P-57]: фикс заголовков календаря 2025-09-11 16:27:00 +03:00
Inna ac9bb6dba1 refactor [P-57]: Merge branch 'develop' into inna-dev 2025-09-11 12:11:39 +03:00
Inna d77c9ec49b refactor [P-57]: add FullCalendar 2025-09-11 12:01:43 +03:00
21 changed files with 2752 additions and 927 deletions

No files matched your search

+2 -1
View File
@@ -94,7 +94,8 @@ class Event(models.Model):
return str(self.name) return str(self.name)
class EventFiles(models.Model): class EventFiles(models.Model):
event = models.ForeignKey(Event, on_delete=models.PROTECT, related_name='get_calendar_event_files',blank=True,null=True, verbose_name='Событие') # event = models.ForeignKey(Event, on_delete=models.PROTECT, related_name='get_calendar_event_files',blank=True,null=True, verbose_name='Событие')
event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='get_calendar_event_files',blank=True,null=True, verbose_name='Событие')
file = models.FileField(upload_to='calendar/%Y/%m/%d') file = models.FileField(upload_to='calendar/%Y/%m/%d')
class Meta: class Meta:
+4 -3
View File
@@ -20,11 +20,10 @@ class ExclusionDatesAPIView(APIView):
year = self.request.query_params.get('year', datetime.now().year) year = self.request.query_params.get('year', datetime.now().year)
exclude = ExclusionDates.objects.filter(exclusiondate__year=year) exclude = ExclusionDates.objects.filter(exclusiondate__year=year)
months = {} months = {}
for i in range(1,12): for i in range(1,13):
months[i] = exclude.filter(exclusiondate__month=i).values_list("exclusiondate", flat=True) months[i] = exclude.filter(exclusiondate__month=i).values_list("exclusiondate", flat=True)
return Response({year:months}) return Response({year:months})
class MyCalendars(APIView): class MyCalendars(APIView):
def get(self, request): def get(self, request):
@@ -104,7 +103,9 @@ class MyEvents(APIView):
resp = {'mycalendars':CalendarsSerializerForEventEdit(allcalendars, many=True).data } resp = {'mycalendars':CalendarsSerializerForEventEdit(allcalendars, many=True).data }
if request.query_params.get("id") is not None: if request.query_params.get("id") is not None:
event = Event.objects.get(id = request.query_params.get("id")) event = Event.objects.get(id = request.query_params.get("id"))
resp['event']=EventSerializerIdRequest(event).data resp['event']=EventSerializerIdRequest(event).data
# events = Event.objects.filter(calendar__id = request.query_params.get("id"))
# resp['events'] = EventSerializerIdRequest(events, many=True).data
return Response(resp) return Response(resp)
+9 -1
View File
@@ -36,7 +36,15 @@
"vue3-autocounter": "^1.0.8", "vue3-autocounter": "^1.0.8",
"vuelidate": "^0.7.7", "vuelidate": "^0.7.7",
"vuetify": "^3.7.8", "vuetify": "^3.7.8",
"webfontloader": "^1.6.28" "webfontloader": "^1.6.28",
"@fullcalendar/core": "^6.1.19",
"@fullcalendar/daygrid": "^6.1.19",
"@fullcalendar/interaction": "^6.1.19",
"@fullcalendar/multimonth": "^6.1.19",
"@fullcalendar/timegrid": "^6.1.19",
"@fullcalendar/list": "6.1.19",
"@fullcalendar/vue3": "^6.1.19",
"@fullcalendar/rrule": "^6.1.15"
}, },
"devDependencies": { "devDependencies": {
"@commitlint/cli": "^19.7.1", "@commitlint/cli": "^19.7.1",
@@ -1,150 +1,431 @@
<template> <template>
<v-col> <v-col>
<v-file-input <div class="custom-file-input-wrapper">
label="Файлы" <label class="v-label v-field-label v-field-label--floating">
chips Добавить файл (размер файла не должен превышать 2Мб)
multiple </label>
v-model="eventFiles"
density="compact"
variant="outlined"
@click.stop=""
>
<template v-slot:selection="{ fileNames }">
<template v-for="(fileName, index) in fileNames" :key="fileName">
<v-chip
v-if="index < 4"
class="me-2"
color="teal-darken-3"
size="small"
label
>
{{ fileName }}
</v-chip>
<span <!-- Область, куда можно перетащить файлы -->
v-else-if="index === 4" <div
class="text-overline text-grey-darken-3 mx-2" class="file-input-area"
> @click="triggerFileInput"
+{{ files.length - 4 }} файла(ов) @drop="handleDrop"
</span> @dragover.prevent
</template> @dragenter.prevent
</template> >
</v-file-input> <!-- Кастомные чипы новых файлов ВНУТРИ "инпута" -->
<div class="chips-container" v-if="localNewFiles.length > 0">
<template v-for="(file, index) in localNewFiles" :key="getFileKey(file, index)">
<v-chip
class="file-chip"
color="grey-darken-1"
size="small"
label
closable
@click:close="removeNewFile(index)"
>
<v-icon start size="small">mdi-file-plus</v-icon>
<span class="text-truncate" style="max-width: 100px">
{{ file.name }}({{ formatFileSize(file.size) }})
</span>
</v-chip>
</template>
<span class="file-counter text-caption text-grey">
{{ localNewFiles.length }}/{{ MAX_NEW_FILES }}
</span>
</div>
<!-- Плейсхолдер, когда файлов нет -->
<div v-else class="placeholder">
<v-icon class="me-1">mdi-paperclip</v-icon>
<span class="text-caption">Перетащите файлы сюда или кликните для выбора</span>
</div>
<!-- Скрытый настоящий input -->
<input
ref="fileInputRef"
type="file"
multiple
style="display: none"
@change="handleFileSelect"
/>
</div>
<!-- Область ошибок -->
<div class="error-messages" v-if="errorMessages.length">
<div v-for="(error, index) in errorMessages" :key="index" class="text-caption text-error">
{{ error }}
</div>
</div>
</div>
<!-- Существующие файлы из БД -->
<div class="existing-files-section mb-4">
<div class="text-caption text-grey mb-2">Прикрепленные файлы:</div>
<div>
<template v-if="existingFiles.length">
<v-chip
v-for="file in existingFiles"
:key="file.id"
class="me-2 mb-1 "
color="teal-darken-3"
label
@click:close="removeExistingFile(file.id)"
>
<v-icon start class="pb-1">{{ getFileIcon(file) }}</v-icon>
{{ getFileName(file) }}
<v-icon
class="ms-1 download-icon"
@click.stop="downloadExistingFile(file)"
title="Скачать файл"
>
mdi-download
</v-icon>
<v-icon
class="ms-1 close-icon"
@click.stop="removeExistingFile(file.id)"
title="Удалить файл"
>
mdi-close
</v-icon>
</v-chip>
</template>
<template v-else>
<span class="text-caption text-grey">Файлов нет</span>
</template>
</div>
</div>
</v-col> </v-col>
</template> </template>
<script> <script>
import { computed, ref } from "vue"; import { computed, ref, watch } from 'vue';
import { get_name } from "@/utils/universal_functions";
export default { export default {
props: { props: {
files: { files: {
type: Object, type: Array,
default: () => {}, default: () => [],
},
newFiles: {
type: Array,
default: [],
}, },
}, },
emits: ['update:files', 'update:newFiles', 'postFiles'],
setup(props, { emit }) { setup(props, { emit }) {
const localNewFiles = ref([]);
const errorMessages = ref([]);
const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2 МБ
const MAX_NEW_FILES = 5;
const propsFiles = computed({ const fileInputRef = ref(null);
get: () => props.files,
set: (value) => emit("update:files", value),
});
const arrFiles = ref([]); watch(
() => props.newFiles,
const eventFiles = computed({ (newVal) => {
get() { localNewFiles.value = Array.isArray(newVal) ? [...newVal] : [];
propsFiles.value.forEach((e) =>
{
arrFiles.value.push(
dataURLtoFile(
"data:text/plain;base64,aGVsbG8gd29ybGQ=",
get_name(decodeURI(e.file))
)
)}
);
return arrFiles.value;
}, },
{ immediate: true },
);
set(newValue) { // Существующие файлы из event.files
let newFile = [] const existingFiles = computed(() => (Array.isArray(props.files) ? props.files : []));
arrFiles.value = [];
if (newValue.length == 0) {
arrFiles.value = [];
propsFiles.value = [];
} else {
newValue.forEach((e) => {
arrFiles.value.push(e)
newFile.push(e)
});
}
emit("postFiles", newFile); const triggerFileInput = () => {
if (fileInputRef.value) {
fileInputRef.value.click();
}, }
}); };
//
function dataURLtoFile(dataurl, filename) { const handleFileSelect = (event) => {
var arr = dataurl.split(","), const files = Array.from(event.target.files || []);
mime = arr[0].match(/:(.*?);/)[1], if (files.length > 0) {
bstr = atob(arr[1]), handleFilesChange(files);
n = bstr.length, }
u8arr = new Uint8Array(n); // Очищаем input для возможности выбора тех же файлов снова
event.target.value = '';
};
while (n--) { // Обработка drag & drop
u8arr[n] = bstr.charCodeAt(n); const handleDrop = (event) => {
event.preventDefault();
const files = Array.from(event.dataTransfer.files || []);
if (files.length > 0) {
handleFilesChange(files);
}
};
const formatFileSize = (bytes) => {
if (bytes === 0) return '0 Б';
const k = 1024;
const sizes = ['Б', 'КБ', 'МБ', 'ГБ'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
};
const validateFiles = (files) => {
errorMessages.value = [];
const currentFiles = Array.isArray(localNewFiles.value) ? localNewFiles.value : [];
const totalFiles = currentFiles.length + files.length;
// Проверка количества
if (totalFiles > MAX_NEW_FILES) {
errorMessages.value.push(`Можно добавить не более ${MAX_NEW_FILES} файлов`);
return false;
} }
return new File([u8arr], filename, { type: mime }); // Проверка размера
} const oversizedFiles = files.filter((file) => file.size > MAX_FILE_SIZE);
if (oversizedFiles.length > 0) {
errorMessages.value.push(
// const eventFiles = computed({ `Следующие файлы превышают 2 МБ: ${oversizedFiles.map((f) => f.name).join(', ')}`,
// get() { );
// if (propsFiles.value.length > 0) { return false;
// propsFiles.value.forEach((e) => }
// files.value.push(
// dataURLtoFile(
// "data:text/plain;base64,aGVsbG8gd29ybGQ=",
// get_name(decodeURI(e.file))
// )
// )
// );
// // let file = dataURLtoFile(
// // "data:text/plain;base64,aGVsbG8gd29ybGQ=",
// // get_name(
// // decodeURI(propsFiles.value.event.files[0].file)
// // )
// // );
// // files.value.push(file); return true;
// } };
const getFileKey = (file, index) => {
return file instanceof File
? `${file.name}-${file.size}-${file.lastModified}`
: file.id || index;
};
// Получаем имя файла из объекта файла
const getFileName = (fileData) => {
if (fileData instanceof File) {
return cleanFileName(fileData.name);
}
// Для существующих файлов с бэка - извлекаем имя из пути
if (fileData.file) {
try {
const filePath = fileData.file.split('?')[0]; // Убираем параметры
const fileName = filePath.split('/').pop(); // Берем последнюю часть пути
return cleanFileName(fileName) || 'Файл';
} catch {
return 'Файл';
}
}
return cleanFileName(fileData.name || 'Файл');
};
const cleanFileName = (fileName) => {
// Убираем суффиксы в скобках (1), (2) и т.д.
return fileName.replace(/\s*\(\d+\)(?=\.\w+$|$)/, '');
};
// Иконка в зависимости от типа файла
const getFileIcon = (fileData) => {
let fileName = '';
if (fileData instanceof File) {
fileName = fileData.name;
} else {
fileName = getFileName(fileData);
}
const extension = fileName.split('.').pop()?.toLowerCase() || '';
const iconMap = {
pdf: 'mdi-file-pdf',
doc: 'mdi-file-word',
docx: 'mdi-file-word',
xls: 'mdi-file-excel',
xlsx: 'mdi-file-excel',
jpg: 'mdi-file-image',
jpeg: 'mdi-file-image',
png: 'mdi-file-image',
gif: 'mdi-file-image',
svg: 'mdi-file-image',
zip: 'mdi-folder-zip',
rar: 'mdi-folder-zip',
'7z': 'mdi-folder-zip',
txt: 'mdi-file-document',
json: 'mdi-code-json',
js: 'mdi-language-javascript',
vue: 'mdi-vuejs',
html: 'mdi-language-html5',
css: 'mdi-language-css3',
};
return iconMap[extension] || 'mdi-file';
};
// Обработка изменения новых файлов
const handleFilesChange = (newFiles) => {
if (!newFiles || newFiles.length === 0) {
return;
}
const validFiles = newFiles.filter((file) => file instanceof File);
if (validFiles.length === 0) {
return;
}
// Валидация
if (!validateFiles(validFiles)) {
return;
}
// localNewFiles.value = [...validFiles];
const currentFiles = Array.isArray(localNewFiles.value) ? localNewFiles.value : [];
const updatedFiles = [...currentFiles, ...validFiles];
localNewFiles.value = updatedFiles;
emit('update:newFiles', updatedFiles);
emit('postFiles', updatedFiles);
};
// Удаление существующего файла
const removeExistingFile = (fileId) => {
try {
// Создаем копию event и удаляем файл
const updatedFiles = existingFiles.value.filter((file) => file.id !== fileId);
// props.files = updatedFiles;
emit('update:files', updatedFiles);
} catch (error) {
console.error('Ошибка при удалении файла:', error);
}
};
// Удаление нового файла (еще не загруженного)
const removeNewFile = (index) => {
const updatedFiles = localNewFiles.value.filter((_, i) => i !== index);
localNewFiles.value = updatedFiles;
// localNewFiles.value.splice(index, 1);
// emit('postFiles', localNewFiles.value);
emit('update:newFiles', updatedFiles);
emit('postFiles', updatedFiles);
};
const downloadExistingFile = async (file) => {
try {
const getOriginalFileName = (filePath) => {
try {
const pathParts = filePath.split('/');
return pathParts[pathParts.length - 1];
} catch {
return 'file';
}
};
const fileName = getOriginalFileName(file.file);
const fileUrl = file.file;
// Создаем временную ссылку для скачивания
const link = document.createElement('a');
link.href = fileUrl;
link.download = fileName; // Указываем имя файла при скачивании
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} catch (error) {
console.error('Ошибка при скачивании файла:', error);
}
};
// return files.value;
// },
// set(newValue) {
// newValue.forEach((e) => {
// if (!files.value.some((l) => l.name == e.name.split(" ").join("_"))) {
// files.value.push(e);
// }
// });
// if (newValue.length == 0) {
// files.value = [];
// propsFiles.value = [];
// }
// },
// });
return { return {
eventFiles, localNewFiles,
arrFiles, existingFiles,
handleFilesChange,
removeExistingFile,
removeNewFile,
getFileName,
getFileIcon,
formatFileSize,
errorMessages,
validateFiles,
getFileKey,
MAX_NEW_FILES,
fileInputRef,
handleFileSelect,
triggerFileInput,
handleDrop,
cleanFileName,
downloadExistingFile,
}; };
}, },
}; };
</script> </script>
<style></style> <style scoped>
:deep(.v-chip) {
border-radius: 6px;
}
.custom-file-input-wrapper {
border: 1px solid rgba(0, 0, 0, 0.38);
border-radius: 4px;
padding: 12px;
position: relative;
background-color: white;
}
.custom-file-input-wrapper:focus-within {
border-color: #1976d2;
border-width: 2px;
}
.file-input-area {
min-height: 40px;
cursor: pointer;
padding: 4px;
}
.chips-container {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px;
}
.file-chip {
max-width: 150px;
}
.file-counter {
margin-left: 8px;
}
.placeholder {
display: flex;
align-items: center;
color: rgba(0, 0, 0, 0.6);
padding: 8px 0;
}
.error-messages {
margin-top: 4px;
}
.text-error {
color: #d32f2f;
}
.existing-files-section {
border-top: 1px solid #e0e0e0;
padding-top: 16px;
}
.download-icon {
cursor: pointer;
opacity: 0.7;
transition: opacity 0.2s;
}
.download-icon:hover {
opacity: 1;
color: #024e45;
}
.close-icon:hover {
opacity: 1;
color: #024e45 ;
}
</style>
@@ -1,98 +1,21 @@
<template> <template>
<v-row no-gutters> <v-row no-gutters>
<v-col class="flex-grow-0 d-flex flex-column"> <v-col class="flex-grow-0 d-flex flex-column">
<v-card class="h-100 rounded-0 d-flex flex-colmn" width="250"> <mini-calendar />
<v-row no-gutters class="flex-column">
<v-col class="flex-grow-0 px-2 pt-1">
<v-text-field
density="compact"
clearable
append-inner-icon="mdi-magnify"
hide-details
class="py-3"
label="Найти событие"
rows="1"
no-resize
variant="outlined"
/>
</v-col>
<v-col class="flex-grow-0 px-2">
<v-btn
type="submit"
class="text-subtitle-1 font-weight-light"
color="btn_text"
block
elevation="1"
@click="createEvent()"
>Создать событие</v-btn
>
<!-- {{eventFromCalendar}} -->
</v-col>
<v-col class="w100" lg="3">
<v-locale-provider locale="ru">
<v-date-picker
ref="cal"
v-model="selectdate"
color="btn_text"
class="rounded-0 minCal"
max-width="250"
hide-header
show-adjacent-months
@click="CheckingStore"
@update:month="getMonth"
@update:year="getYear"
>
</v-date-picker>
</v-locale-provider>
</v-col>
<v-col class="flex-column d-flex">
<v-row no-gutters class="h-0 overflow-auto flex-column flex-nowrap">
<v-col>
<calendar-my
:calendars="
calendarForMy.filter((e) => e.author == accountStore.user.is_idEmployee)
"
title="Мои календари"
@getCalendar="getCalendar"
/>
<calendar-my
:calendars="
calendarForMy.filter((e) => e.author != accountStore.user.is_idEmployee)
"
title="Подписки"
/>
</v-col>
</v-row>
</v-col>
</v-row>
</v-card>
</v-col> </v-col>
<v-col class="d-flex flex-column"> <v-col class="d-flex flex-column">
<calendar-full <custom-calendar @openEventDialog="openEventDialog" />
:allEvent="calendarForMy.filter((e) => e.events.length > 0)"
@getEvent="createEvent"
@update:allEvent="infoEvent($event)"
/>
</v-col> </v-col>
<!-- <v-navigation-drawer <v-dialog v-model="showEventDialog" max-width="700">
v-model="drawer_right"
floating
permanent
location="right"
rail-width="400"
rail
>
</v-navigation-drawer> -->
<v-dialog v-model="showDialog" max-width="700">
<event-create <event-create
@closeDialog="showDialog = false" @closeDialog="closeEventDialog"
:eventCalendar="eventFromCalendar" :eventCalendar="eventFromCalendar"
@update:eventCalendar="eventFromCalendar = $event" :myCalendars="calendarStore.myCalendars"
@getCalendar="getCalendar" @getCalendar="getCalendar"
@update:eventCalendar="eventFromCalendar = $event"
ref="createEvents" ref="createEvents"
:key="eventKey"
/> />
</v-dialog> </v-dialog>
</v-row> </v-row>
@@ -102,26 +25,29 @@
import { ref, onMounted, watch } from 'vue'; import { ref, onMounted, watch } from 'vue';
import { useWeekendsStore } from '@/store/WeekendsStore'; import { useWeekendsStore } from '@/store/WeekendsStore';
import EventCreate from '@/components/calendar_of_events/event-create.vue'; import EventCreate from '@/components/calendar_of_events/event-create.vue';
import CalendarMy from '@/components/calendar_of_events/calendar-my.vue'; import CustomCalendar from '@/components/calendar_of_events/UI_calendar/CustomCalendar.vue';
import { useCalendarStore } from '@/store/calendarStore';
import { storeToRefs } from 'pinia';
import MiniCalendar from '@/components/calendar_of_events/UI_calendar/MiniCalendar.vue';
import { axiosApiInstance } from '@/utils/axios-api'; import { axiosApiInstance } from '@/utils/axios-api';
import { useAccountStore } from '@/store/AccountStore'; import { useAccountStore } from '@/store/AccountStore';
import CalendarFull from '@/components/calendar_of_events/UI_calendar/calendarFull.vue';
export default { export default {
components: { EventCreate, CalendarMy, CalendarFull }, components: { EventCreate, MiniCalendar, CustomCalendar },
setup() { setup() {
const accountStore = useAccountStore();
const showDialog = ref(false);
const week = useWeekendsStore(); const week = useWeekendsStore();
const drawer_right = ref(false);
const cal = ref(null);
const selectdate = ref(new Date()); const selectdate = ref(new Date());
const MyYear = ref(selectdate.value.getFullYear()); const MyYear = ref(selectdate.value.getFullYear());
const MyMonth = ref(selectdate.value.getMonth() + 1); const MyMonth = ref(selectdate.value.getMonth() + 1);
const calendarForMy = ref([]); const calendarForMy = ref([]);
const eventFromCalendar = ref({}); const eventFromCalendar = ref({});
const createEvents = ref(null); const eventKey = ref(0);
const isClosingDialog = ref(false);
const calendarStore = useCalendarStore();
const accountStore = useAccountStore();
const { selectedDate, showEventDialog } = storeToRefs(calendarStore); // синхронизируем с date-picker
const getMonth = (month) => { const getMonth = (month) => {
MyMonth.value = month + 1; MyMonth.value = month + 1;
@@ -131,79 +57,59 @@ export default {
}; };
const getCalendar = () => { const getCalendar = () => {
axiosApiInstance.get(`api/calendar_of_events/my_calendars/`).then((res) => { calendarStore.loadCalendars();
res.data.forEach((e) => (e.visible = accountStore.calendar.includes(e.id) ? false : true));
calendarForMy.value = res.data;
});
}; };
getCalendar(); const getEvent = (idEvent) => {
if (!idEvent) {
const getEvents = (idEvent, clik) => { eventFromCalendar.value = createEmptyEvent();
axiosApiInstance return;
.get(`api/calendar_of_events/my_events/${idEvent === undefined ? '' : `?id=${idEvent}`}`) } else {
.then((res) => { axiosApiInstance.get(`api/calendar_of_events/my_events/?id=${idEvent}`).then((res) => {
if (idEvent === undefined) {
res.data.event = {
name: '',
participant: [accountStore.user.is_idEmployee],
files: [],
date_start: new Date(),
date_end: new Date(),
period: null,
description: '',
calendar: null,
};
}
eventFromCalendar.value = res.data; eventFromCalendar.value = res.data;
calendarStore.openEventDialog();
if (clik) showDialog.value = true;
}); });
};
getEvents();
const createEvent = (idEv) => {
getEvents(idEv, true);
if (idEv) {
getCalendar();
} }
}; };
const weekendsData = () => { const createEmptyEvent = () => ({
cal.value.$el.querySelectorAll('.v-date-picker-month__day').forEach((e) => { event: {
let datas = e.getAttribute('data-v-date'); name: '',
let weeks = new Date(datas).getDay() === 6 || new Date(datas).getDay() === 0; participant: [accountStore.user.is_idEmployee],
if (weeks) { files: [],
e.querySelectorAll('span').forEach((n) => { date_start: new Date().toISOString(),
n.classList.add('text-red'); date_end: new Date().toISOString(),
}); period: null,
} description: '',
if (MyMonth.value in week.week[MyYear.value]) { calendar: null,
if (week.week[MyYear.value][MyMonth.value].includes(datas)) { },
e.querySelectorAll('span').forEach((n) => { });
n.classList.add('text-red');
if (n.classList.contains('text-red') && weeks) { const openEventDialog = (selectedEvent) => {
n.classList.replace('text-red', 'text-black'); // Всегда сбрасываем данные перед открытием нового диалога
} if (!selectedEvent) {
}); eventFromCalendar.value = createEmptyEvent();
} eventKey.value++;
} }
});
getEvent(selectedEvent?.event?.id);
calendarStore.openEventDialog();
}; };
onMounted(() => { onMounted(() => {
getEvent();
week.getWeekend(MyYear.value); week.getWeekend(MyYear.value);
}); });
watch( const closeEventDialog = () => {
() => week.week, calendarStore.closeEventDialog();
(newValue) => {
if (newValue) { // При ручном закрытии сбрасываем данные сразу
weekendsData(); setTimeout(() => {
} eventFromCalendar.value = createEmptyEvent();
}, eventKey.value++;
); }, 200);
};
const CheckingStore = () => { const CheckingStore = () => {
if (MyYear.value in week.week) { if (MyYear.value in week.week) {
@@ -213,44 +119,42 @@ export default {
} }
}; };
const infoEvent = (i) => { watch(
console.log(i, 'iiiiiiiiii'); () => calendarStore.showEventDialog,
}; (newValue, oldValue) => {
if (!newValue && oldValue) {
// Диалог был открыт и закрыт не через нашу кнопку
// Добавляем проверку чтобы не сбрасывать при инициализации
if (eventFromCalendar.value.event?.id) {
setTimeout(() => {
eventFromCalendar.value = createEmptyEvent();
eventKey.value++;
}, 200);
}
}
},
);
return { return {
drawer_right, selectedDate,
selectdate,
cal,
getMonth, getMonth,
getYear, getYear,
weekendsData,
week, week,
CheckingStore, CheckingStore,
showDialog, showEventDialog,
calendarForMy, calendarForMy,
accountStore,
getCalendar, getCalendar,
getEvent,
eventFromCalendar, eventFromCalendar,
createEvent, calendarStore,
infoEvent, accountStore,
createEvents, closeEventDialog,
openEventDialog,
createEmptyEvent,
eventKey,
}; };
}, },
}; };
</script> </script>
<style> <style scoped></style>
.minCal .v-date-picker-month__day {
height: 31px;
width: 31px;
}
.minCal .v-btn--icon.v-btn--density-default {
width: calc(var(--v-btn-height) + 12px);
height: calc(var(--v-btn-height) + 6px);
}
.minCal .v-btn__content {
font-weight: 410;
}
</style>
@@ -0,0 +1,543 @@
<template>
<v-col cols="12">
<v-card>
<v-card-text>
<!-- Контролы навигации -->
<v-row no-gutters class="mb-4" align="center" justify="space-between">
<v-col md="4" class="flex-grow-0 d-flex align-center">
<v-btn
v-show="!forHomePage"
variant="outlined"
class="text-subtitle-2 mr-2"
@click="handleToday"
density="comfortable"
>
Сегодня
</v-btn>
<v-btn
variant="text"
@click="handlePrev"
:elevation="0"
style="border-radius: 4px"
density="compact"
icon
>
<v-icon size="large">mdi-chevron-left</v-icon>
</v-btn>
<v-btn
variant="text"
@click="handleNext"
:elevation="0"
style="border-radius: 4px"
density="compact"
icon
>
<v-icon size="large">mdi-chevron-right</v-icon>
</v-btn>
<span v-if="!forHomePage" class="text-h6 text-no-wrap ml-2">
{{ currentTitle }}
</span>
<span v-else class="text-caption text-no-wrap ml-2">
{{ currentTitle }}
</span>
</v-col>
<v-col class="flex-grow-0 d-flex justify-end">
<v-btn-toggle
v-show="!forHomePage"
v-model="currentView"
mandatory
divided
variant="plain"
density="comfortable"
>
<v-btn value="timeGridDay">День</v-btn>
<v-btn value="timeGridWeek">Неделя</v-btn>
<v-btn value="dayGridMonth">Месяц</v-btn>
<v-btn value="multiMonthYear">Год</v-btn>
<v-btn value="listWeek">Расписание</v-btn>
</v-btn-toggle>
</v-col>
</v-row>
<div class="flex-grow-1">
<!-- VCalendar -->
<FullCalendar ref="calendarRef" :options="calendarOptions" class="compact-calendar" />
</div>
</v-card-text>
</v-card>
</v-col>
</template>
<script>
import { ref, watch, nextTick, computed } from 'vue';
import { storeToRefs } from 'pinia';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import multiMonthPlugin from '@fullcalendar/multimonth';
import interactionPlugin from '@fullcalendar/interaction';
import listPlugin from '@fullcalendar/list';
import ruLocale from '@fullcalendar/core/locales/ru';
import rrulePlugin from '@fullcalendar/rrule';
import { onMounted } from 'vue';
import { useCalendarStore } from '@/store/calendarStore';
import { useRecurrence } from '@/components/calendar_of_events/composables/useReccurrence';
export default {
name: 'CustomCalendar',
props: {
view: {
type: String,
default: '',
},
forHomePage: {
type: Boolean,
default: false,
},
},
emits: ['openEventDialog'],
setup(props, { emit }) {
const calendarRef = ref(null);
const currentView = ref('dayGridMonth');
const calendarApi = ref(null);
const currentTitle = ref('Календарь');
const calendarStore = useCalendarStore();
const { selectedDate, lastUpdatedBy, allEvents, calendarColorMap } = storeToRefs(calendarStore);
const { parseRecurrenceOptions, isRecurringEvent } = useRecurrence();
const handleEventClick = (info) => {
if (calendarStore.canEditEvent(info.event.id)) {
emit('openEventDialog', info);
}
};
const calendarOptions = ref({
plugins: [
dayGridPlugin,
timeGridPlugin,
multiMonthPlugin,
interactionPlugin,
listPlugin,
rrulePlugin,
],
initialView: props.forHomePage ? props.view : currentView.value,
locales: [ruLocale],
locale: 'ru',
firstDay: 1,
headerToolbar: false,
height: '80vh',
aspectRatio: 1.5,
weekNumbers: true,
weekNumberFormat: {
week: 'numeric',
},
weekNumberCalculation: 'ISO', // ISO стандарт (понедельник - первый день)
selectable: true,
unselectAuto: false,
selectMirror: false,
dayCellDidMount: (arg) => {
const date = arg.date;
const dayInfo = calendarStore.isNonWorkingDay(date);
if (dayInfo.isHoliday === true) {
arg.el.classList.add('non-working-day');
}
if (dayInfo.isWeekendForStyling === true) {
arg.el.classList.add('grey-background');
}
},
views: {
timeGridDay: {
type: 'timeGrid',
duration: { days: 1 },
slotDuration: '01:00:00',
slotLabelInterval: '01:00:00',
slotLabelFormat: {
hour: '2-digit',
minute: '2-digit',
hour12: false,
meridiem: false,
},
allDaySlot: false,
allDaySlot: false,
slotMinTime: '07:00:00',
slotMaxTime: '22:00:00',
expandRows: true,
dayHeaderFormat: {
weekday: 'long',
day: 'numeric',
month: 'long',
omitCommas: true,
},
},
timeGridWeek: {
type: 'timeGrid',
duration: { weeks: 1 },
slotDuration: '01:00:00',
slotMinTime: '07:00:00',
slotMaxTime: '22:00:00',
allDaySlot: false,
expandRows: true,
dayHeaderFormat: { weekday: 'short', day: 'numeric' },
titleFormat: {
day: 'numeric',
month: 'long',
omitCommas: true,
},
},
dayGridMonth: {
type: 'dayGrid',
fixedWeekCount: false,
dayHeaderFormat: { weekday: 'short' },
weekNumbers: true,
weekNumberFormat: { week: 'numeric' },
weekNumberContent: (arg) => {
return arg.num;
},
weekText: 'Нед.',
},
multiMonthYear: {
type: 'multiMonth',
duration: { years: 1 },
multiMonthMaxColumns: 4,
fixedWeekCount: false,
weekNumbers: false,
},
listWeek: {
type: 'list',
duration: { weeks: 1 },
listDayFormat: {
weekday: 'long',
day: 'numeric',
month: 'long',
},
listDaySideFormat: false,
},
},
events: [],
editable: true,
selectable: true,
eventClick: handleEventClick,
dateClick: (info) => {
calendarStore.setSelectedDateFromCalendar(info);
handleDateSelection(info.dateStr);
handleCalendarDateClick(info);
calendarApi.value?.unselect();
},
datesSet: (info) => {
if (info.view.type === 'listWeek' && selectedDate.value) {
const date = new Date(selectedDate.value);
const options = {
weekday: 'long',
day: 'numeric',
month: 'long',
year: 'numeric',
};
const formattedDate = date.toLocaleDateString('ru-RU', options);
currentTitle.value = `Расписание на ${formattedDate}`;
} else {
currentTitle.value = info.view.title;
}
if (selectedDate?.value) {
handleDateSelection(selectedDate.value);
}
},
});
const handleCalendarDateClick = (info) => {
calendarStore.setSelectedDateFromCalendar(info);
currentTitle.value = info.view.title;
const calendarApi = calendarRef.value.getApi();
// Переходим к выбранной дате в дневном виде
calendarApi.gotoDate(info.date);
calendarApi.changeView('listWeek');
currentView.value = 'listWeek';
};
const handleToday = () => {
calendarApi.value?.today();
// Получаем текущую дату из календаря и передаем в стор
const currentDate = calendarApi.value?.getDate();
if (currentDate) {
// Создаем объект похожий на info из FullCalendar
const todayInfo = {
dateStr: currentDate.toISOString().split('T')[0],
};
calendarStore.setSelectedDateFromCalendar(todayInfo);
}
};
const handlePrev = () => {
calendarApi.value?.prev();
const currentDate = calendarApi.value?.getDate();
if (currentDate) {
const dateInfo = {
dateStr: currentDate.toISOString().split('T')[0],
};
calendarStore.setSelectedDateFromCalendar(dateInfo);
}
};
const handleNext = () => {
calendarApi.value?.next();
const currentDate = calendarApi.value?.getDate();
if (currentDate) {
const dateInfo = {
dateStr: currentDate.toISOString().split('T')[0],
};
calendarStore.setSelectedDateFromCalendar(dateInfo);
}
};
// Функция обновления выделения
const handleDateSelection = (dateStr) => {
// Убираем предыдущее выделение
const previousSelected = document.querySelectorAll('.fc-day-selected-custom');
previousSelected.forEach((el) => el.classList.remove('fc-day-selected-custom'));
// Добавляем новое выделение
const dayElements = document.querySelectorAll(`[data-date="${dateStr}"]`);
dayElements.forEach((el) => el.classList.add('fc-day-selected-custom'));
selectedDate.value = dateStr;
};
// const calendarColorMap = computed(() => {
// const map = new Map();
// calendarStore.myCalendars.forEach((calendar) => {
// map.set(calendar.id, calendar.cl_color);
// });
// return map;
// });
// Обновление событий в календаре
const updateCalendarEvents = () => {
if (calendarRef.value) {
const api = calendarRef.value.getApi();
api.removeAllEvents();
allEvents.value.forEach((event) => {
const eventColor = calendarColorMap.value.get(event.calendar) || '#3788d8';
const rruleOptions = isRecurringEvent(event)
? parseRecurrenceOptions(event.period, event.date_start)
: null;
const baseEvent = {
id: event.id,
title: event.name,
start:new Date(event.date_start),
end: new Date(event.date_end),
allDay: event.all_day,
textColor: '#ffffff',
backgroundColor: eventColor,
borderColor: eventColor,
};
if (!rruleOptions) {
api.addEvent(baseEvent);
return;
}
api.addEvent({
...baseEvent,
rrule: {
...rruleOptions,
},
extendedProps: {
originalEvent: event,
isRecurring: true,
},
});
});
}
};
onMounted(() => {
nextTick(() => {
if (calendarRef.value && calendarRef.value.getApi) {
calendarApi.value = calendarRef.value.getApi();
updateCalendarEvents();
}
if (selectedDate.value != undefined && selectedDate.value) {
handleDateSelection(selectedDate.value);
}
});
});
onMounted(async () => {
const currentYear = new Date().getFullYear();
calendarStore.fetchHolidays(currentYear);
});
watch(selectedDate, (newDate) => {
if (newDate && calendarApi.value && lastUpdatedBy.value !== 'calendar') {
nextTick(() => {
calendarApi.value.gotoDate(newDate);
handleDateSelection(newDate);
});
}
});
watch(currentView, (newView) => {
if (calendarApi.value) {
calendarApi.value.changeView(newView);
}
});
watch(
[allEvents],
([newEvents]) => {
if (newEvents.length > 0) {
updateCalendarEvents();
}
},
{ deep: true, immediate: true },
);
watch(
() => props.eventCalendar,
(newEvent) => {
if (calendarRef.value) {
const api = calendarRef.value.getApi();
api.refetchEvents(); // Обновляем события в календаре
}
},
{ deep: true },
);
return {
currentTitle,
calendarRef,
currentView,
calendarOptions,
handleToday,
handleNext,
handlePrev,
handleCalendarDateClick,
handleDateSelection,
updateCalendarEvents,
handleEventClick,
calendarStore,
};
},
};
</script>
<style scoped>
:deep(.fc-daygrid-day-number) {
display: flex !important;
justify-content: center !important;
align-items: center !important;
width: 100% !important;
height: 100% !important;
margin: 0 !important;
padding: 0.6rem !important;
}
/* текущая дата обводка */
:deep(.fc-day-today) {
background-color: transparent !important;
}
:deep(.fc-day-today .fc-daygrid-day-number) {
position: relative;
z-index: 1;
color: #00897b;
&::before {
content: '';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 32px;
height: 32px;
border: 1px solid #00897b;
border-radius: 50%;
z-index: -1;
}
}
/* Выбранная дата заливка */
:deep(.fc-day-selected-custom) {
background-color: transparent !important;
}
:deep(.fc-day-selected-custom .fc-daygrid-day-number) {
position: relative;
z-index: 1;
color: white !important;
}
:deep(.fc-day-selected-custom .fc-daygrid-day-number::before) {
content: '';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 32px;
height: 32px;
background-color: #00897b;
border-radius: 50%;
z-index: -1;
}
:deep(.fc-multiMonthYear-view) {
.fc-day-today .fc-daygrid-day-number::before,
.fc-day-selected-custom .fc-daygrid-day-number::before {
width: 24px;
height: 24px;
}
}
:deep(.v-btn--active) {
background-color: transparent !important;
color: #00897b !important;
}
:deep(.fc .fc-timegrid-col.fc-day-today) {
background-color: #e0f2f1 !important;
}
:deep(.fc-highlight) {
background-color: transparent !important;
}
:deep(.fc-day) {
cursor: pointer;
}
:deep(.fc-popover) {
background-color: rgb(248, 244, 244) !important;
}
.non-working-day {
color: red !important;
}
:global(.fc-daygrid-day.non-working-day .fc-daygrid-day-number) {
color: #d32f2f !important;
}
:global(.fc-daygrid-day.grey-background.fc-daygrid-day-number) {
background-color: rgb(196, 187, 187) !important;
}
.grey-background {
background-color: rgb(240, 229, 229) !important;
}
:deep(.fc-day.grey-background) {
background-color: #f5f5f5 !important;
}
</style>
@@ -0,0 +1,534 @@
<template>
<v-card class="home-calendar-widget" elevation="2" rounded="lg">
<v-card-text class="pa-4">
<v-row no-gutters class="calendar-pair">
<!-- Месячный календарь -->
<v-col cols="7" class="pr-2">
<div class="calendar-header">
<v-btn icon size="small" @click="prevMonth" class="nav-btn">
<v-icon>mdi-chevron-left</v-icon>
</v-btn>
<span class="month-title">{{ currentMonth }}</span>
<v-btn icon size="small" @click="nextMonth" class="nav-btn">
<v-icon>mdi-chevron-right</v-icon>
</v-btn>
</div>
<v-table class="month-table">
<thead>
<tr>
<th v-for="day in russianWeekdays" :key="day" class="weekday-header">
{{ day }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(week, weekIndex) in calendarWeeks" :key="weekIndex">
<td
v-for="day in week"
:key="day.date"
class="day-cell"
:class="{
'current-month': day.isCurrentMonth,
today: isToday(day.date),
selected: isSelected(day.date),
'non-working-day': calendarStore.isNonWorkingDay(day.date).isHoliday,
'grey-background': calendarStore.isNonWorkingDay(day.date).isWeekendForStyling,
}"
@click="onDateClick(day.date)"
>
<div class="day-content">
<span class="day-number">{{ day.day }}</span>
<div class="day-events">
<span
v-for="event in getDayEvents(day.date)"
:key="event.id"
class="event-indicator"
:style="{ backgroundColor: event.color }"
></span>
</div>
</div>
</td>
</tr>
</tbody>
</v-table>
</v-col>
<!-- Дневное расписание -->
<v-col cols="5" class="pl-2">
<div class="schedule-header">
<h3 class="day-title">Сегодня, {{ formattedSelectedDate }}</h3>
</div>
<v-card variant="outlined" class="day-schedule" elevation="0">
<v-list density="comfortable" class="py-0">
<v-list-item
v-for="event in dayEvents"
:key="event.id"
class="schedule-item"
:class="{ 'current-event': isCurrentEvent(event) }"
>
<template #prepend>
<div
class="event-color-indicator"
:style="{ backgroundColor: event.color }"
></div>
</template>
<v-list-item-title class="event-time">
{{ formatTime(event.start) }}
</v-list-item-title>
<v-list-item-subtitle class="event-title">
{{ event.title }}
</v-list-item-subtitle>
</v-list-item>
<v-list-item v-if="dayEvents.length === 0" class="no-events">
<v-list-item-title class="text-grey text-center">
На этот день событий нет
</v-list-item-title>
</v-list-item>
</v-list>
</v-card>
</v-col>
</v-row>
</v-card-text>
</v-card>
</template>
<script>
import { ref, computed, onMounted, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { useCalendarStore } from '@/store/calendarStore';
export default {
name: 'HomeCalendarWidget',
setup() {
// Реактивные данные
const currentDate = ref(new Date());
const selectedDate = ref(''); // Будет установлено в формате YYYY-MM-DD
const currentYear = new Date().getFullYear();
// Работа с хранилищем
const calendarStore = useCalendarStore();
const { allEvents, calendarColorMap } = storeToRefs(calendarStore);
// Утилиты для работы с датами (главный источник проблем!)
const formatToLocalDate = (date) => {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};
const getStartOfDay = (date) => {
const newDate = new Date(date);
newDate.setHours(0, 0, 0, 0);
return newDate;
};
const areDatesEqual = (date1, date2) => {
return getStartOfDay(date1).getTime() === getStartOfDay(date2).getTime();
};
// Преобразование событий с защитой от ошибок
const events = computed(() => {
const userEvents = allEvents.value.map((event) => {
const eventColor = calendarColorMap.value.get(event.calendar) || event.color || '#1976d2';
return {
id: event.id,
title: event.name || event.title || 'Без названия',
start: event.date_start || event.start,
end: event.date_end || event.end,
description: event.description,
color: eventColor || '#1976d2',
calendar: event.calendar,
isHoliday: false,
};
});
return [...userEvents];
});
const russianWeekdays = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'];
// Генерация календаря
const calendarWeeks = computed(() => {
const year = currentDate.value.getFullYear();
const month = currentDate.value.getMonth();
const firstDay = new Date(year, month, 1);
const lastDay = new Date(year, month + 1, 0);
const weeks = [];
let week = [];
// Находим понедельник первой недели
const startDay = new Date(firstDay);
startDay.setDate(startDay.getDate() - ((startDay.getDay() + 6) % 7));
// Генерируем 6 недель (фиксированное количество для стабильности)
for (let i = 0; i < 42; i++) {
const currentDay = new Date(startDay);
currentDay.setDate(startDay.getDate() + i);
week.push({
day: currentDay.getDate(),
date: formatToLocalDate(currentDay),
isCurrentMonth: currentDay.getMonth() === month,
});
if (week.length === 7) {
weeks.push([...week]);
week = [];
}
}
return weeks;
});
const currentMonth = computed(() => {
return currentDate.value.toLocaleDateString('ru-RU', {
month: 'long',
year: 'numeric',
});
});
const formattedSelectedDate = computed(() => {
if (!selectedDate.value) return '';
// Добавляем время для избежания смещения часовых поясов
const date = new Date(selectedDate.value + 'T12:00:00');
return date.toLocaleDateString('ru-RU', {
day: 'numeric',
month: 'long',
year: 'numeric',
});
});
const dayEvents = computed(() => {
if (!selectedDate.value) return [];
const selected = new Date(selectedDate.value + 'T12:00:00');
return events.value
.filter((event) => {
const eventDate = new Date(event.start);
return areDatesEqual(eventDate, selected);
})
.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime());
});
// Методы
const isToday = (date) => {
const today = new Date();
const checkDate = new Date(date + 'T12:00:00');
return areDatesEqual(today, checkDate);
};
const isSelected = (date) => {
return date === selectedDate.value;
};
const getDayEvents = (date) => {
const checkDate = new Date(date + 'T12:00:00');
return events.value.filter((event) => {
const eventDate = new Date(event.start);
return areDatesEqual(eventDate, checkDate);
});
};
const isCurrentEvent = (event) => {
const now = new Date();
const start = new Date(event.start);
const end = new Date(event.end);
return now >= start && now <= end;
};
const formatTime = (dateString) => {
return new Date(dateString).toLocaleTimeString('ru-RU', {
hour: '2-digit',
minute: '2-digit',
});
};
const onDateClick = (date) => {
selectedDate.value = date;
};
const prevMonth = () => {
const date = new Date(currentDate.value);
date.setMonth(date.getMonth() - 1);
currentDate.value = date;
};
const nextMonth = () => {
const date = new Date(currentDate.value);
date.setMonth(date.getMonth() + 1);
currentDate.value = date;
};
const isWeekendOrHoliday = (dateString) => {
const dayInfo = calendarStore.isNonWorkingDay(dateString);
return dayInfo.isHoliday || dayInfo.isWeekendForStyling;
};
onMounted(async () => {
selectedDate.value = formatToLocalDate(new Date());
calendarStore.fetchHolidays(currentYear);
});
watch(
calendarColorMap,
(newMap) => {
newMap.value;
},
{ deep: true },
);
return {
// Реактивные данные
currentDate,
selectedDate,
// Вычисляемые свойства
events,
russianWeekdays,
calendarWeeks,
currentMonth,
formattedSelectedDate,
dayEvents,
isWeekendOrHoliday,
// Методы
isToday,
isSelected,
getDayEvents,
isCurrentEvent,
formatTime,
onDateClick,
prevMonth,
nextMonth,
calendarStore,
allEvents,
};
},
};
</script>
<style scoped>
.home-calendar-widget {
width: 100%;
/* width: 700px; */
height: 100%;
font-family: 'Roboto', sans-serif;
}
.calendar-pair {
height: 100%;
}
/* Месячный календарь */
.calendar-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
padding: 0 8px;
}
.month-title {
font-size: 1.1rem;
font-weight: 600;
color: #333;
text-transform: capitalize;
}
.nav-btn {
width: 28px;
height: 28px;
}
.month-table {
width: 100%;
height: 100%;
}
.weekday-header {
font-size: 0.8rem;
font-weight: 600;
color: #666;
text-align: center;
padding: 8px 4px;
border-bottom: 1px solid #afadad;
}
.day-cell {
width: 14.28%;
height: 15%;
/* height: 50px; */
text-align: center;
cursor: pointer;
border: 1px solid transparent;
transition: all 0.2s ease;
}
.day-cell:hover {
background-color: #f5f5f5;
}
.day-cell.current-month {
color: #333;
}
.day-cell:not(.current-month) {
color: #ccc;
}
.day-cell.today {
background-color: #e3f2fd;
}
.day-cell.selected {
background-color: #00897b;
color: white;
}
.day-cell.selected .day-number {
color: white;
}
.day-content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
padding: 2px;
}
.day-number {
font-size: 0.9rem;
font-weight: 500;
margin-bottom: 2px;
}
.day-events {
display: flex;
gap: 2px;
justify-content: center;
}
.event-indicator {
width: 6px;
height: 6px;
border-radius: 50%;
display: block;
}
.event-color-indicator {
width: 10px;
height: 10px;
border-radius: 50%;
margin-right: 12px;
flex-shrink: 0;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1);
}
/* Дневное расписание */
.schedule-header {
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 12px;
padding: 0 4px;
}
.day-title {
font-size: 1.2rem;
font-weight: 600;
margin: 0;
color: #333;
}
.day-schedule {
height: 90%;
overflow-y: auto;
border: 1px solid #e0e0e0;
border-radius: 8px;
}
.schedule-item {
min-height: 48px;
padding: 8px 12px;
border-left: 4px solid transparent;
border-bottom: 1px solid #d3cecede;
}
.schedule-item:last-child {
border-bottom: none;
}
.schedule-item.current-event {
border-left-color: #2196f3;
background-color: #f8f9fa;
}
.event-time {
font-size: 0.8rem;
font-weight: 600;
color: #302f2f;
margin-bottom: 2px;
}
.event-title {
font-size: 0.9rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
color: #1b1b1b;
}
.no-events {
min-height: 120px;
display: flex;
align-items: center;
justify-content: center;
}
/* Скроллбар */
.day-schedule::-webkit-scrollbar {
width: 6px;
}
.day-schedule::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 0 8px 8px 0;
}
.day-schedule::-webkit-scrollbar-thumb {
background: #c1c1c1;
border-radius: 3px;
}
.day-schedule::-webkit-scrollbar-thumb:hover {
background: #a8a8a8;
}
.non-working-day {
color: red !important;
}
.grey-background {
background-color: rgb(243, 243, 243) !important;
}
.day-cell:not(.current-month).non-working-day {
color: inherit !important;
}
</style>
@@ -0,0 +1,239 @@
<template>
<v-card class="h-100 rounded-0 d-flex flex-colmn">
<v-row no-gutters class="flex-column">
<v-col class="flex-grow-0 px-2 pt-1">
<v-text-field
density="compact"
clearable
append-inner-icon="mdi-magnify"
hide-details
class="py-3"
label="Найти событие"
rows="1"
no-resize
variant="outlined"
/>
</v-col>
<v-col class="flex-grow-0 px-2">
<v-btn
type="submit"
class="text-subtitle-1 font-weight-light"
color="btn_text"
block
elevation="1"
@click="openEventDialog"
>Создать событие</v-btn
>
<!-- {{eventFromCalendar}} -->
</v-col>
<v-col lg="3">
<v-locale-provider locale="ru">
<v-date-picker
v-model="selectedDate"
color="btn_text"
class="rounded-0 minCal"
hide-header
show-adjacent-months
@update:modelValue="handleDateClick"
>
</v-date-picker>
</v-locale-provider>
</v-col>
<v-col class="flex-column d-flex">
<v-row no-gutters class="h-0 overflow-auto flex-column flex-nowrap">
<v-col>
<calendar-my
:calendars="myCalendars"
title="Мои календари"
@getCalendar="loadCalendars"
/>
<calendar-my :calendars="subscribedCalendars" title="Подписки" />
</v-col>
</v-row>
</v-col>
</v-row>
</v-card>
</template>
<script>
import { useCalendarStore } from '@/store/calendarStore';
import { useAccountStore } from '@/store/AccountStore';
import CalendarMy from '@/components/calendar_of_events/calendar-my.vue';
import { onMounted, watch, ref, nextTick } from 'vue';
import { storeToRefs } from 'pinia';
export default {
name: 'MiniCalendar',
components: { CalendarMy },
setup() {
const calendarStore = useCalendarStore();
const accountStore = useAccountStore();
const { selectedDate, myCalendars, subscribedCalendars } = storeToRefs(calendarStore);
const { user } = storeToRefs(accountStore);
const handleDateClick = (date) => {
calendarStore.setSelectedDateFromPicker(date);
setTimeout(updateCalendarDays, 200);
};
const openEventDialog = () => {
calendarStore.openEventDialog();
};
const loadCalendars = () => {
calendarStore.loadCalendars();
};
onMounted(() => {
loadCalendars();
updateCalendarDays();
setInterval(updateCalendarDays, 500);
});
// Реакция на изменения пользователя
watch(user, (newUser) => {
if (newUser) {
loadCalendars();
}
});
// Функция для добавления классов дням
const updateCalendarDays = () => {
nextTick(() => {
setTimeout(() => {
const dayButtons = document.querySelectorAll('.minCal .v-date-picker-month__day-btn');
dayButtons.forEach((button) => {
// Ищем дату в разных возможных атрибутах
const ariaLabel = button.getAttribute('aria-label');
if (ariaLabel) {
try {
// Парсим дату из aria-label "воскресенье, 28 сентября 2025 г."
const dayDate = parseDateFromAriaLabel(ariaLabel);
if (dayDate) {
const dayInfo = calendarStore.isNonWorkingDay(dayDate);
// Очищаем предыдущие классы
button.classList.remove('weekend-day', 'holiday-day');
// Добавляем классы по условию
if (dayInfo?.isWeekendForStyling) {
button.classList.add('weekend-day');
}
if (dayInfo?.isHoliday) {
button.classList.add('holiday-day');
}
}
} catch (error) {
console.error('Error processing day:', error);
}
}
});
}, 100);
});
};
const parseDateFromAriaLabel = (ariaLabel) => {
try {
// Убираем день недели и запятую, оставляем "28 сентября 2025 г."
const datePart = ariaLabel.replace(/^[^,]+,?\s*/, '');
// Заменяем русские названия месяцев на английские
const monthMap = {
января: 'January',
февраля: 'February',
марта: 'March',
апреля: 'April',
мая: 'May',
июня: 'June',
июля: 'July',
августа: 'August',
сентября: 'September',
октября: 'October',
ноября: 'November',
декабря: 'December',
};
let englishDateStr = datePart;
for (const [ru, en] of Object.entries(monthMap)) {
englishDateStr = englishDateStr.replace(ru, en);
}
// Убираем " г." в конце
englishDateStr = englishDateStr.replace(' г.', '');
const dayDate = new Date(englishDateStr);
return isNaN(dayDate.getTime()) ? null : dayDate;
} catch (error) {
console.error('Parse error:', error);
return null;
}
};
return {
accountStore,
user,
myCalendars,
subscribedCalendars,
selectedDate,
openEventDialog,
loadCalendars,
handleDateClick,
updateCalendarDays,
};
},
};
</script>
<style scoped>
/* .minCal:deep(.v-date-picker-month__days) {
display: grid !important;
grid-template-columns: repeat(7, 40px) !important;
gap: 3px !important;
width: 250px !important;
justify-content: center !important;
margin: 0 auto !important;
} */
.minCal .v-date-picker-monWth__day {
height: 31px;
width: 31px;
}
.minCal .v-btn--icon.v-btn--density-default {
width: calc(var(--v-btn-height) + 12px);
height: calc(var(--v-btn-height) + 6px);
}
.minCal .v-btn__content {
font-weight: 410;
}
.minCal:deep(.v-date-picker-years__content) {
gap: 0;
}
/* СТИЛИ ДЛЯ ВЫХОДНЫХ И ПРАЗДНИКОВ */
.minCal:deep(.weekend-day .v-btn__content) {
color: #666 !important;
}
.minCal:deep(.holiday-day .v-btn__content) {
color: #ff4444 !important;
font-weight: bold !important;
}
.minCal:deep(.weekend-day.holiday-day) {
background-color: #ffe0e0 !important;
}
.minCal:deep(.weekend-day.holiday-day .v-btn__content) {
color: #cc0000 !important;
}
</style>
@@ -93,7 +93,7 @@ export default {
{ type: "day", text: "День" }, { type: "day", text: "День" },
{ type: "week", text: "Неделя" }, { type: "week", text: "Неделя" },
{ type: "month", text: "Месяц" }, { type: "month", text: "Месяц" },
{ type: "modntdh", text: "Год" }, // { type: "modntdh", text: "Год" },
{ type: "modnth", text: "Расписание" }, { type: "modnth", text: "Расписание" },
]; ];
@@ -314,7 +314,7 @@ export default {
ev.rule.byweekday[ev.rule.byweekday.length - 1].weekday == 6 ev.rule.byweekday[ev.rule.byweekday.length - 1].weekday == 6
? 0 ? 0
: ev.rule.byweekday[ev.rule.byweekday.length - 1].weekday + 1; : ev.rule.byweekday[ev.rule.byweekday.length - 1].weekday + 1;
if (day.date.getDay() == weeknumS && weeknumS != weeknumE) { if (day.date.getDay() == weeknumS && weeknumS != weeknumE) {
return "rounded-e-lg"; return "rounded-e-lg";
} else if (day.date.getDay() == weeknumE && weeknumS != weeknumE) { } else if (day.date.getDay() == weeknumE && weeknumS != weeknumE) {
@@ -328,7 +328,7 @@ export default {
return "rounded-lg"; return "rounded-lg";
} }
} }
if (ev.rule.freq == 0) { if (ev.rule.freq == 0) {
if (zeroTime(day.date) == zeroTime(ev.start_event)) { if (zeroTime(day.date) == zeroTime(ev.start_event)) {
@@ -342,7 +342,7 @@ export default {
// ev.rule.byweekday[ev.rule.byweekday.length - 1].weekday == 6 // ev.rule.byweekday[ev.rule.byweekday.length - 1].weekday == 6
// ? 0 // ? 0
// : ev.rule.byweekday[ev.rule.byweekday.length - 1].weekday + 1; // : ev.rule.byweekday[ev.rule.byweekday.length - 1].weekday + 1;
// if (day.date.getDay() == weeknumS && weeknumS != weeknumE) { // if (day.date.getDay() == weeknumS && weeknumS != weeknumE) {
// return "rounded-e-lg"; // return "rounded-e-lg";
// } else if (day.date.getDay() == weeknumE && weeknumS != weeknumE) { // } else if (day.date.getDay() == weeknumE && weeknumS != weeknumE) {
@@ -2,10 +2,10 @@
<v-col lg="3" :class="`order-${order[0]}`"> <v-col lg="3" :class="`order-${order[0]}`">
<v-menu <v-menu
v-model="menudate" v-model="menudate"
:close-on-content-click="false"
:nudge-right="40" :nudge-right="40"
transition="scale-transition" transition="scale-transition"
offset-y offset-y
:close-on-content-click="false"
> >
<template v-slot:activator="{ props }"> <template v-slot:activator="{ props }">
<v-textarea <v-textarea
@@ -21,12 +21,7 @@
hide-details hide-details
> >
<template v-slot:prepend-inner> <template v-slot:prepend-inner>
<v-icon <v-icon v-bind="props" icon="mdi-calendar-today" color="cyan-darken-3" size="x-small" />
v-bind="props"
icon="mdi-calendar-today"
color="cyan-darken-3"
size="x-small"
/>
</template> </template>
</v-textarea> </v-textarea>
</template> </template>
@@ -38,7 +33,7 @@
hide-header hide-header
border border
no-time no-time
:max="order[0] == 2 ? new Date(limitation) : endMax()" :max="endMax()"
:min="order[0] == 2 ? startMin() : minData()" :min="order[0] == 2 ? startMin() : minData()"
/> />
</v-locale-provider> </v-locale-provider>
@@ -66,29 +61,24 @@
activator="parent" activator="parent"
transition="scale-transition" transition="scale-transition"
> >
<v-time-picker <v-time-picker v-if="menutime" v-model="timeEvent" full-width format="24hr"></v-time-picker>
v-if="menutime"
v-model="timeEvent"
full-width
format="24hr"
></v-time-picker>
</v-menu> </v-menu>
</v-col> </v-col>
</template> </template>
<script> <script>
import { ref, computed } from "vue"; import { ref, computed } from 'vue';
import { formatComa, formatDash } from "@/utils/universal_functions"; import { formatComa } from '@/utils/universal_functions';
export default { export default {
props: { props: {
dateEvent: { dateEvent: {
type: String, type: String,
default: "", default: '',
}, },
limitation: { limitation: {
type: String, type: String,
default: "", default: '',
}, },
order: { order: {
@@ -103,15 +93,21 @@ export default {
type: Number, type: Number,
default: -1, default: -1,
}, },
isStart: {
type: Boolean,
default: false,
},
}, },
emits: ['update:dateEvent', 'adjustEndDate'],
setup(props, { emit }) { setup(props, { emit }) {
const menudate = ref(false); const menudate = ref(false);
const menutime = ref(false); const menutime = ref(false);
const propsDateEvent = computed({ const propsDateEvent = computed({
get: () => new Date(props.dateEvent), get: () => new Date(props.dateEvent),
set: (value) => emit("update:dateEvent", value), set: (value) => emit('update:dateEvent', value),
}); });
const modelDate = computed({ const modelDate = computed({
@@ -119,77 +115,59 @@ export default {
return propsDateEvent.value; return propsDateEvent.value;
}, },
set(newValue) { set(newValue) {
creatwdDate(newValue, timeEvent.value); createdDate(newValue, timeEvent.value);
}, },
}); });
const timeEvent = computed({ const timeEvent = computed({
get() { get() {
return `${new Date(propsDateEvent.value).getHours()}:${String( return `${new Date(propsDateEvent.value).getHours()}:${String(
new Date(propsDateEvent.value).getMinutes() new Date(propsDateEvent.value).getMinutes(),
).padStart(2, "0")}`; ).padStart(2, '0')}`;
}, },
set(newValue) { set(newValue) {
creatwdDate(modelDate.value, newValue); createdDate(modelDate.value, newValue);
}, },
}); });
const creatwdDate = (date, time) => { const createdDate = (date, time) => {
let tzero = time.split(":"); const [hours, minutes] = time.split(':').map(Number);
time = tzero[0].padStart(2, "0") + ":" + tzero[1]; const newDate = new Date(date);
newDate.setHours(hours, minutes, 0, 0);
if (props.order[0] == 4) { if (props.order[0] == 4) {
if (time == "0:00") { const startDate = new Date(props.limitation);
propsDateEvent.value = date; if (newDate <= startDate) {
} else if ( const correctedDate = new Date(startDate);
new Date(formatDash(date) + "T" + time) >= new Date(props.limitation) correctedDate.setHours(startDate.getHours() + 1);
) { propsDateEvent.value = correctedDate;
propsDateEvent.value = new Date(formatDash(date) + "T" + time);
} else { } else {
propsDateEvent.value = new Date(props.limitation); propsDateEvent.value = newDate;
} }
} else { } else {
propsDateEvent.value = propsDateEvent.value = newDate;
time == "0:00" ? date : new Date(formatDash(date) + "T" + time); const currentEnd = new Date(props.limitation);
if (newDate > currentEnd) {
const newEnd = new Date(newDate);
newEnd.setHours(newDate.getHours() + 1);
emit('adjustEndDate', newEnd.toISOString());
}
} }
menudate.value = false;
menutime.value = false;
}; };
const minData = () => { const minData = () => {
let h = `${new Date(props.limitation).getHours()}:${String( return new Date(props.limitation);
new Date(props.limitation).getMinutes()
).padStart(2, "0")}`;
let min =
h == "0:00"
? new Date(props.limitation)
: new Date(
new Date(props.limitation).setDate(
new Date(props.limitation).getDate() - 1
)
);
return new Date(min);
}; };
const startMin = () => { const startMin = () => {
if (props.rule == 2) { return new Date(); // ← По умолчанию: нельзя выбрать прошедшие даты
return new Date(
new Date(props.limitation).setDate(
new Date(props.limitation).getDate() - 7
)
);
}
return false;
}; };
const endMax = () => { const endMax = () => {
if (props.rule == 2) { return null; // ← Без ограничения сверху
return new Date(
new Date(props.limitation).setDate(
new Date(props.limitation).getDate() + 6
)
);
}
return false;
}; };
return { return {
@@ -112,7 +112,6 @@ export default {
const filtered = ref(''); const filtered = ref('');
const accountStore = useAccountStore(); const accountStore = useAccountStore();
const back = ref([]); const back = ref([]);
const staffed = computed({ const staffed = computed({
get() { get() {
if (props.okey == 'editor') { if (props.okey == 'editor') {
@@ -1,7 +1,7 @@
<template> <template>
<dialog-create <dialog-create
:title="titleCard" :title="titleCard"
:newOrOld="newCalendar" :newOrOld="isNewCalendar"
@closeDialog="$emit('closeDialog')" @closeDialog="$emit('closeDialog')"
@delObject="delCalendar(propsCalendar.id)" @delObject="delCalendar(propsCalendar.id)"
@postData="postCalendar" @postData="postCalendar"
@@ -150,20 +150,14 @@ export default {
cl_descr: [(val) => req(val)], cl_descr: [(val) => req(val)],
}; };
const titleCard = ref(''); const isNewCalendar = computed(() => !propsCalendar.value.id);
const newCalendar = ref(false); const isAuthor = computed(() => propsCalendar.value.author === accountStore.user.is_idEmployee);
const calendarNewOrOld = () => { const titleCard = computed(() =>
if ('id' in propsCalendar.value) { isNewCalendar.value ? 'Новый календарь' : 'Редактирование календаря',
titleCard.value = 'Редактирование календаря'; );
if (propsCalendar.value.author != accountStore.user.is_idEmployee) newCalendar.value = true;
} else {
titleCard.value = 'Новый календарь';
newCalendar.value = true; const newCalendar = computed(() => (isNewCalendar.value ? true : !isAuthor.value));
}
};
calendarNewOrOld();
const postCalendar = (val) => { const postCalendar = (val) => {
if (val) { if (val) {
@@ -213,21 +207,21 @@ export default {
}); });
const color = [ const color = [
'red', '#3788d8', // Синий (аналог default FullCalendar)
'pink', '#4caf50', // Зеленый
'deep-orange', '#ff9800', // Оранжевый
'amber', '#9c27b0', // Фиолетовый
'yellow', '#2196f3', // Голубой
'lime', '#795548', // Коричневый
'light-green', '#607d8b', // Серо-голубой
'green', '#e91e63', // Розовый
'light-blue', '#00bcd4', // Бирюзовый
'blue', '#8bc34a', // Салатовый
'indigo', '#ff5722', // Красно-оранжевый
'deep-purple', '#673ab7', // Темно-фиолетовый
'purple', '#3f51b5', // Индиго
'blue-grey', '#009688', // Зелено-бирюзовый
'brown', '#ffc107', // Янтарный
]; ];
const colorPik = (col) => { const colorPik = (col) => {
@@ -266,6 +260,7 @@ export default {
titleCard, titleCard,
newCalendar, newCalendar,
newStaff, newStaff,
isNewCalendar,
}; };
}, },
}; };
@@ -1,12 +1,5 @@
<template> <template>
<v-expansion-panels <v-expansion-panels class="calendar" variant="accordion" flat tile static v-model="openGroup">
class="calendar"
variant="accordion"
flat
tile
static
v-model="openGroup"
>
<v-expansion-panel elevation="0" flat tile static> <v-expansion-panel elevation="0" flat tile static>
<v-expansion-panel-title flat tile static class="py-0 px-3"> <v-expansion-panel-title flat tile static class="py-0 px-3">
<div @click.stop=""> <div @click.stop="">
@@ -37,26 +30,23 @@
<v-checkbox-btn <v-checkbox-btn
class="text-caption" class="text-caption"
:class="`text-${x.cl_color}`" :class="`text-${x.cl_color}`"
v-model="x.visible"
:color="x.cl_color" :color="x.cl_color"
@update:modelValue="chekUpdate(x)" v-model="x.visible"
@update:modelValue="toggleVisiblityEvents(x)"
></v-checkbox-btn> ></v-checkbox-btn>
<!-- :model-value="x.visible" -->
</template> </template>
<template v-slot:title> <template v-slot:title>
<span class="text-body-2"> {{ x.cl_name }} </span> <span class="text-body-2"> {{ x.cl_name }} </span>
</template> </template>
<template v-slot:append> <template v-slot:append>
<transition name="fade"> <transition name="fade">
<v-btn <v-btn
v-if=" v-if="
x.author == accountStore.user.is_idEmployee || x.author == user.is_idEmployee ||
x.participant.some( x.participant.some(
(e) => (e) => e.editor === true && e.participant_calendar === user.is_idEmployee,
e.editor == true &&
e.participant_calendar ==
accountStore.user.is_idEmployee
) )
" "
size="x-small" size="x-small"
@@ -74,21 +64,24 @@
</template> </template>
</v-expansion-panel-text> </v-expansion-panel-text>
</v-expansion-panel> </v-expansion-panel>
<v-dialog v-model="showDialog" min-width="636" max-width="800"> <v-dialog v-model="showDialog" min-width="636" max-width="800">
<calendar-create <calendar-create
@closeDialog = "showDialog = false" @closeDialog="showDialog = false"
:calendar="calendar" :calendar="calendar"
@update:calendar="calendar = $event" @update:calendar="calendar = $event"
@getCalendar="$emit('getCalendar')" @getCalendar="$emit('getCalendar')"
/> />
</v-dialog> </v-dialog>
</v-expansion-panels> </v-expansion-panels>
</template> </template>
<script> <script>
import { ref } from "vue"; import { ref } from 'vue';
import calendarCreate from "@/components/calendar_of_events/calendar-create.vue"; import calendarCreate from '@/components/calendar_of_events/calendar-create.vue';
import { useAccountStore } from "@/store/AccountStore"; import { useAccountStore } from '@/store/AccountStore';
import { storeToRefs } from 'pinia';
import { useCalendarStore } from '@/store/calendarStore';
export default { export default {
components: { calendarCreate }, components: { calendarCreate },
@@ -99,51 +92,48 @@ export default {
}, },
title: { title: {
typr: String, type: String,
default: "", default: '',
}, },
}, },
setup(props, { emit }) { setup(props) {
const showDialog = ref(false); const showDialog = ref(false);
const accountStore = useAccountStore(); const accountStore = useAccountStore();
const { user } = storeToRefs(accountStore);
const calendarStore = useCalendarStore();
const { toggleCalendarVisibility } = calendarStore;
const calendar = ref({}); const calendar = ref({});
const openGroup = ref([0]); const openGroup = ref([0]);
const trans = ref(false); const trans = ref(false);
const hover = ref(0); const hover = ref(0);
const editCreatedCalendar = (cal) => { const editCreatedCalendar = (cal) => {
if (cal === undefined) { if (cal === undefined) {
calendar.value = { calendar.value = {
cl_name: "", cl_name: '',
participant: [{ editor: true, participant_calendar: accountStore.user.is_idEmployee }], participant: [{ editor: true, participant_calendar: user.value.is_idEmployee }],
cl_color: "red", cl_color: 'red',
cl_descr: "", cl_descr: '',
}; };
} else { } else {
calendar.value = cal; calendar.value = cal;
} }
showDialog.value = true; showDialog.value = true;
}; };
const chekUpdate = (cal) => { const toggleVisiblityEvents = (cal) => {
let setcal = new Set(accountStore.calendar); toggleCalendarVisibility(cal.id, cal.visible);
if (cal.visible == false) {
setcal.add(cal.id);
} else {
setcal.delete(cal.id);
}
accountStore.calendar = Array.from(setcal);
}; };
return { return {
showDialog,
calendar,
editCreatedCalendar,
chekUpdate,
accountStore, accountStore,
user,
calendar,
showDialog,
editCreatedCalendar,
toggleVisiblityEvents,
openGroup, openGroup,
trans, trans,
hover, hover,
@@ -0,0 +1,56 @@
import { RRule } from 'rrule';
export function useRecurrence() {
/**
* Парсит строку периода из БД и возвращает опции для RRule
*/
const parseRecurrenceOptions = (periodString, eventDateStart) => {
if (!periodString || periodString === 'null') return null;
try {
// Пробуем распарсить как RRULE-строку
if (periodString.includes('RRULE:')) {
const rrule = RRule.fromString(periodString);
return { ...rrule.origOptions, dtstart: new Date(eventDateStart) };
}
// Пробуем распарсить как JSON
const periodData = JSON.parse(periodString);
if (periodData?.origOptions) {
const options = { ...periodData.origOptions };
if (options.dtstart && typeof options.dtstart === 'string') {
options.dtstart = new Date(eventDateStart);
}
return options;
}
} catch (error) {
console.error('Parse recurrence error:', error);
}
return null;
};
/**
* Проверяет, является ли событие повторяющимся
*/
const isRecurringEvent = (event) => {
if (!event.period || event.period === 'null') return false;
return event.period.includes('RRULE:') || JSON.parse(event.period)?.origOptions;
};
/**
* Создает объект правила для нового события
*/
const createRecurrenceRule = (options) => {
const rrule = new RRule({
...options,
dtstart: new Date(options.dtstart),
});
return rrule.toString(); // Возвращаем строку RRULE
};
return {
parseRecurrenceOptions,
createRecurrenceRule,
isRecurringEvent,
};
}
@@ -1,10 +1,10 @@
<template> <template>
<dialog-create <dialog-create
:title="titleCard" :title="titleCard"
:newOrOld="newEvent" :newOrOld="isNewEvent"
@postData="postData" @postData="postData"
@closeDialog="$emit('closeDialog')" @closeDialog="$emit('closeDialog')"
@delObject="delEvent(propsEvent.event.id)" @delObject="delEvent(propsEvent?.event?.id)"
ref="createDialog" ref="createDialog"
> >
<template v-slot:card_text> <template v-slot:card_text>
@@ -13,9 +13,7 @@
<v-row no-gutters class="align-center"> <v-row no-gutters class="align-center">
<!-- <my-helper :pretext="propsEvent.event" /> --> <!-- <my-helper :pretext="propsEvent.event" /> -->
<v-col class="text-body-2 text-text_grey pb-5" lg="2"> <v-col class="text-body-2 text-text_grey pb-5" lg="2"> Название </v-col>
Название
</v-col>
<v-col> <v-col>
<v-textarea <v-textarea
@@ -30,9 +28,7 @@
></v-row> ></v-row>
<v-row no-gutters class="align-center"> <v-row no-gutters class="align-center">
<v-col class="text-body-2 text-text_grey pb-5" lg="2"> <v-col class="text-body-2 text-text_grey pb-5" lg="2"> Участники </v-col>
Участники
</v-col>
<v-col> <v-col>
<calendar-create-select <calendar-create-select
:staff="newStaff" :staff="newStaff"
@@ -44,8 +40,8 @@
<v-col class="text-body-2 text-text_grey" lg="2"> Календарь</v-col> <v-col class="text-body-2 text-text_grey" lg="2"> Календарь</v-col>
<v-col> <v-col>
<v-autocomplete <v-autocomplete
v-model="calendar" v-model="myCalendar"
:items="propsEvent.mycalendars" :items="safeCalendars"
label="Выберите календарь или найдите по названию" label="Выберите календарь или найдите по названию"
item-title="cl_name" item-title="cl_name"
item-value="id" item-value="id"
@@ -54,70 +50,58 @@
density="compact" density="compact"
class="py-3" class="py-3"
return-object return-object
:rules="rules.calendar"
:disabled="'id' in propsEvent.event" :disabled="'id' in propsEvent.event"
clearable
auto-select-first
> >
<template v-slot:selection="{ item }"> <template v-slot:selection="{ item }">
<v-avatar <v-avatar class="cursor-pointer" size="8" :color="item.raw.cl_color" />
class="cursor-pointer"
size="8"
:color="item.raw.cl_color"
/>
<span class="pl-2"> <span class="pl-2">
{{ item.title }} {{ item.title }}
</span> </span>
</template> </template>
<template v-slot:item="{ item }"> <template v-slot:item="{ item, props }">
<v-list-item <v-list-item
:key="item.title" :key="item.raw.id"
:value="item" :value="item"
color="primary" color="primary"
@click.stop="calendar = item" v-bind="props"
@click.stop="myCalendar = item.raw"
> >
<template v-slot:prepend> <template v-slot:prepend>
<v-avatar <v-avatar class="cursor-pointer" size="8" :color="item.raw.cl_color" />
class="cursor-pointer"
size="8"
:color="item.raw.cl_color"
/>
</template> </template>
{{ item.title }} <!-- {{ item.title }} -->
</v-list-item> </v-list-item>
</template> </template>
</v-autocomplete> </v-autocomplete>
</v-col></v-row </v-col></v-row
> >
<v-row no-gutters class="align-top"> <v-row no-gutters class="align-top">
<v-col class="text-body-2 text-text_grey pt-3" lg="2"> <v-col class="text-body-2 text-text_grey pt-3" lg="2"> Дата и время </v-col>
Дата и время
</v-col>
<v-col class="d-flex flex-column"> <v-col class="d-flex flex-column">
<v-row no-gutters class="gap"> <v-row no-gutters class="gap">
<time-select <time-select
:rule=" :rule="selectedRule.rule ? selectedRule.rule.freq : -1"
returnPeriod != repeatRules[0].type
? returnPeriod.rule.freq
: -1
"
:chek="propsEvent.event.allday" :chek="propsEvent.event.allday"
:order="[2, 1]" :order="[2, 1]"
:dateEvent="String(propsEvent.event.date_start)" :dateEvent="String(propsEvent.event.date_start)"
:limitation="String(propsEvent.event.date_end)" :limitation="String(propsEvent.event.date_end)"
@update:dateEvent="propsEvent.event.date_start = $event" @update:dateEvent="updateDateStart"
@adjustEndDate="handleAutoAdjustEnd"
/> />
<v-col class="order-3 flex-grow-0"> <v-col class="order-3 flex-grow-0">
<v-icon icon="mdi-minus pt-4" color="grey-darken-1" /> <v-icon icon="mdi-minus pt-4" color="grey-darken-1" />
</v-col> </v-col>
<time-select <time-select
:rule=" :rule="selectedRule.rule ? selectedRule.rule.freq : -1"
returnPeriod != repeatRules[0].type
? returnPeriod.rule.freq
: -1
"
:chek="propsEvent.event.allday" :chek="propsEvent.event.allday"
:order="[4, 5]" :order="[4, 5]"
:dateEvent="String(propsEvent.event.date_end)" :dateEvent="String(propsEvent.event.date_end)"
:limitation="String(propsEvent.event.date_start)" :limitation="String(propsEvent.event.date_start)"
@update:dateEvent="propsEvent.event.date_end = $event" @update:dateEvent="updateDateEnd"
@adjustEndDate="handleAutoAdjustEnd"
/> />
</v-row> </v-row>
<v-row no-gutters> <v-row no-gutters>
@@ -127,33 +111,22 @@
/> />
<v-col lg="7" class="pt-2 ml-5"> <v-col lg="7" class="pt-2 ml-5">
<v-autocomplete <v-autocomplete
v-model="returnPeriod" v-model="selectedRule"
:items="repeatRules" :items="repeatRules"
variant="outlined" variant="outlined"
density="compact" density="compact"
return-object return-object
item-title="type" item-title="type"
item-value="id" item-value="id"
@update:model-value="updatePeriodRule"
> >
<template v-slot:item="{ props, item }">
<v-list-item
v-bind="props"
:key="item.title"
:value="item"
color="primary"
:disabled="periodDisplayRule(item.raw.id)"
@click="returnPeriod = item.raw"
/>
</template>
</v-autocomplete> </v-autocomplete>
</v-col> </v-col>
</v-row> </v-col </v-row> </v-col
></v-row> ></v-row>
</v-col> </v-col>
<v-row no-gutters class="align-top flex-grow-0"> <v-row no-gutters class="align-top flex-grow-0">
<v-col class="text-body-2 text-text_grey pt-3 h-0" lg="2"> <v-col class="text-body-2 text-text_grey pt-3 h-0" lg="2"> Напоминание </v-col>
Напоминание
</v-col>
<v-col class="d-flex flex-column"> <v-col class="d-flex flex-column">
<v-row no-gutters class="gap flex-grow-0"> <v-row no-gutters class="gap flex-grow-0">
<reminder-event /> <reminder-event />
@@ -172,12 +145,17 @@
</v-row> </v-row>
</v-col></v-row </v-col></v-row
> >
<v-row no-gutters class="align-center"> <v-row
<v-col class="text-body-2 text-text_grey pb-5" lg="2"> Файлы </v-col> no-gutters
class="align-start d-flex pt-3 mb-3"
style="height: auto; min-height: 100px; max-height: 400px"
>
<v-col class="text-body-2 text-text_grey pb-5 pt-3" lg="2"> Файлы </v-col>
<uploading-file <uploading-file
v-model:new-files="newFiles"
:files="propsEvent.event.files" :files="propsEvent.event.files"
@update:files="propsEvent.event.files = $event" @update:files="handleFilesUpdate"
@postFiles="postFiles" @postFiles="postFiles"
/> />
</v-row> </v-row>
@@ -198,18 +176,18 @@
</template> </template>
<script> <script>
import { computed, ref } from "vue"; import { computed, ref, watch } from 'vue';
import { axiosApiInstance } from "@/utils/axios-api"; import { axiosApiInstance } from '@/utils/axios-api';
import DialogCreate from "@/components/calendar_of_events/UI_calendar/dialogCreate.vue"; import { useAccountStore } from '@/store/AccountStore';
import calendarCreateSelect from "@/components/calendar_of_events/calendar-create-select.vue"; import DialogCreate from '@/components/calendar_of_events/UI_calendar/dialogCreate.vue';
import { formatComa } from "@/utils/universal_functions"; import calendarCreateSelect from '@/components/calendar_of_events/calendar-create-select.vue';
import TimeSelect from "@/components/calendar_of_events/UI_calendar/timeSelect.vue"; import TimeSelect from '@/components/calendar_of_events/UI_calendar/timeSelect.vue';
import { useAccountStore } from "@/store/AccountStore"; import UploadingFile from '@/components/UI/defaultportal/uploading-file.vue';
import UploadingFile from "@/components/UI/defaultportal/uploading-file.vue"; import ReminderEvent from '@/components/calendar_of_events/UI_calendar/reminderEvent.vue';
import ReminderEvent from "@/components/calendar_of_events/UI_calendar/reminderEvent.vue"; import PeriodEvents from '@/components/calendar_of_events/UI_calendar/periodEvents.vue';
import PeriodEvents from "@/components/calendar_of_events/UI_calendar/periodEvents.vue"; import { useAlertStore } from '@/store/UseAlertStore';
import { useAlertStore } from "@/store/UseAlertStore"; import { RRule } from 'rrule';
import { RRule } from "rrule"; import { useRecurrence } from '@/components/calendar_of_events/composables/useReccurrence';
export default { export default {
components: { components: {
@@ -226,227 +204,285 @@ export default {
type: Object, type: Object,
default: () => {}, default: () => {},
}, },
myCalendars: {
type: Array,
default: () => [],
},
}, },
setup(props, { emit }) { setup(props, { emit }) {
const accountStore = useAccountStore();
const createDialog = ref(null); const createDialog = ref(null);
const { parseRecurrenceOptions, isRecurringEvent } = useRecurrence();
const propsEvent = computed({ const propsEvent = computed({
get: () => { get: () => {
return props.eventCalendar; return props.eventCalendar;
}, },
set: (value) => emit("update:eventCalendar", value), set: (value) => emit('update:eventCalendar', value),
}); });
// ВАЛИДАЦИЯ
const rules = {
name: [
(val) => !!val || 'Поле обязательно для заполнения',
(val) => (val && val.length >= 3) || 'Минимум 3 символа',
(val) => (val && val.length <= 100) || 'Максимум 100 символов',
],
calendar: [(val) => !!val || 'Выберите календарь'],
};
const repeatRules = [ const repeatRules = [
{ type: "Не повторять", rule: {}, id: 1 }, { type: 'Не повторять', rule: null, id: 1 },
{ type: "Каждый день", rule: { freq: 3 }, id: 2 }, {
{ type: "Каждую неделю", rule: { freq: 2 }, id: 3 }, type: 'Каждый день',
{ type: "Каждый месяц", rule: { freq: 1 }, id: 4 }, rule: { freq: RRule.DAILY },
{ type: "Каждый год", rule: { freq: 0 }, id: 5 }, id: 2,
},
{
type: 'Каждую неделю',
rule: { freq: RRule.WEEKLY },
// По умолчанию - в тот же день недели, что и начальная дата
getRule: (startDate) => {
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()],
}),
id: 4,
},
{
type: 'Каждый год',
rule: { freq: RRule.YEARLY },
// По умолчанию - в тот же день и месяц
getRule: (startDate) => {
const date = new Date(startDate);
return {
freq: RRule.YEARLY,
bymonth: [date.getMonth() + 1],
bymonthday: [date.getDate()],
};
},
id: 5,
},
]; ];
const returnPeriod = computed({ const selectedRule = ref(repeatRules[0]);
get() {
let select = ""; // Инициализация при редактировании
if (propsEvent.value.event.period != null) { const initializeRule = () => {
let objRule = JSON.parse(propsEvent.value.event.period); if (!propsEvent.value.event.period) {
if (objRule != null) { selectedRule.value = repeatRules[0]; // "Не повторять"
drawingRule(objRule.origOptions); return;
repeatRules.findIndex( }
(e) => e.rule.freq == objRule.origOptions.freq try {
); // Используем isRecurringEvent для проверки
select = if (isRecurringEvent(propsEvent.value.event)) {
repeatRules[ // Парсим period с использованием parseRecurrenceOptions
repeatRules.findIndex( const rruleOptions = parseRecurrenceOptions(
(e) => e.rule.freq == objRule.origOptions.freq propsEvent.value.event.period,
) propsEvent.value.event.date_start,
]; );
if (rruleOptions) {
// Находим правило в repeatRules по freq
const foundRule = repeatRules.find((rule) => rule.rule?.freq === rruleOptions.freq);
selectedRule.value = foundRule || repeatRules[0];
} }
} else { } else {
select = repeatRules[0].type; selectedRule.value = repeatRules[0];
} }
} catch (error) {
calendarNewOrOld(); console.error('Error parsing period:', error, 'Raw period:', propsEvent.value.event.period);
selectedRule.value = repeatRules[0];
return select;
},
set(newValue) {
drawingRule(newValue.rule);
},
});
const drawingRule = (value) => {
let newRulse;
if (value.freq == 3) {
newRulse = new RRule({
...value,
dtstart: new Date(propsEvent.value.event.date_start),
until: new Date(propsEvent.value.event.date_end),
});
} }
if (value.freq == 2) {
newRulse = new RRule({
...value,
dtstart: new Date(propsEvent.value.event.date_start),
byweekday: getWeekNumbersBetweenDates(),
});
}
if (value.freq == 1) {
newRulse = new RRule({
...value,
bymonthday: getMonthBetweenDates(),
dtstart: new Date(propsEvent.value.event.date_start),
});
}
if (value.freq == 0) {
newRulse = new RRule({
...value,
bymonthday: getYearBetweenDates(),
dtstart: new Date(propsEvent.value.event.date_start),
bymonth: getNumberMonth(),
});
}
// byweekday: getWeekNumbersBetweenDates(),
Object.keys(value).length == 0
? (propsEvent.value.event.period = null)
: (propsEvent.value.event.period = JSON.stringify(newRulse));
}; };
const rulleWeek = [
RRule.SU,
RRule.MO,
RRule.TU,
RRule.WE,
RRule.TH,
RRule.FR,
RRule.SA,
];
const feedalert = useAlertStore().alert; const feedalert = useAlertStore().alert;
const req = (val) => { const titleCard = computed(() => {
return !!val || "Поле обязательно"; if (propsEvent.value.event.hasOwnProperty('id')) {
return 'Редактирование события';
} else {
return 'Новое событие';
}
});
const isNewEvent = computed(() => !propsEvent.value.event.hasOwnProperty('id'));
const myCalendar = ref(null);
// const isNewEvent = computed(() => !propsEvent.value.event.id);
// Computed property с защитой от undefined
const safeCalendars = computed(() => props.myCalendars || []);
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; // Уже инициализирован
// Приоритет 1: календарь из события (редактирование)
if (eventCalendar.value) {
myCalendar.value = eventCalendar.value;
return;
}
// Приоритет 2: первый доступный календарь (создание)
if (safeCalendars.value.length > 0) {
myCalendar.value = safeCalendars.value[0];
}
}; };
const rules = { // Инициализируем когда все готово
name: [(val) => req(val)], watch(
}; [() => safeCalendars.value.length, () => propsEvent.value],
() => {
initializeCalendar();
},
{ immediate: true },
);
// Дополнительная защита - вотчер только на смену самого календаря
watch(eventCalendar, (newCalendar) => {
if (newCalendar && newCalendar.id !== myCalendar.value?.id) {
myCalendar.value = newCalendar;
}
});
const staff = ref([]); const staff = ref([]);
axiosApiInstance axiosApiInstance.get('api/calendar_of_events/get_employees/').then((res) => {
staff.value = res.data.filter((e) => e.employees.length > 0);
});
.get("api/calendar_of_events/get_employees/") // const newStaff = computed({
.then((res) => { // get() {
staff.value = res.data.filter((e) => e.employees.length > 0); // let ns = [];
});
const accountStore = useAccountStore(); // let indCal = safeCalendars.value.findIndex((e) => e.id == myCalendar.id);
const newStaff = computed({ // staff.value.forEach((e) => {
get() { // let emp = { ...e };
let ns = []; // emp.employees = e.employees.filter((n) => {
// if (
// n.id == accountStore.user.is_idEmployee ||
// propsEvent.value.event.participant.some((e) => n.id == e)
// ) {
// n.selected = true;
// }
let indCal = propsEvent.value.mycalendars.findIndex( // return propsEvent.value.mycalendars[indCal].participant.some(
(e) => e.id == calendar.value[0].id // (part) => part.id === n.id,
// );
// });
// if (emp.employees.length > 0) ns.push(emp);
// });
// return ns;
// },
// });
const newStaff = computed(() => {
// Для нового события - все сотрудники, для существующего - фильтр по календарю
// const isNewEvent = !propsEvent.value.event.id;
if (isNewEvent) {
// НОВОЕ СОБЫТИЕ - все сотрудники
const eventParticipantIds = propsEvent.value.event.participant || [];
return staff.value
.map((department) => ({
...department,
employees: department.employees.map((employee) => ({
...employee,
selected:
employee.id === accountStore.user.is_idEmployee ||
eventParticipantIds.includes(employee.id),
})),
}))
.filter((dept) => dept.employees.length > 0);
} else {
// СУЩЕСТВУЮЩЕЕ СОБЫТИЕ - фильтр по календарю
const eventCalendarId = propsEvent.value.event.calendar;
if (!eventCalendarId) return [];
const currentCalendar = propsEvent.value.mycalendars?.find(
(cal) => parseInt(cal.id) === parseInt(eventCalendarId),
); );
staff.value.forEach((e) => { if (!currentCalendar?.participant) return [];
let emp = { ...e };
emp.employees = e.employees.filter((n) => {
if (
n.id == accountStore.user.is_idEmployee ||
propsEvent.value.event.participant.some((e) => n.id == e)
) {
n.selected = true;
}
return propsEvent.value.mycalendars[indCal].participant.some( const calendarParticipantIds = new Set(currentCalendar.participant.map((p) => p.id));
(part) => part.id === n.id const eventParticipantIds = new Set(propsEvent.value.event.participant || []);
);
});
if (emp.employees.length > 0) ns.push(emp); return staff.value
}); .map((department) => ({
return ns; ...department,
}, employees: department.employees.map((employee) => ({
...employee,
selected: eventParticipantIds.has(employee.id),
// Дополнительная информация для UX
inCalendar: calendarParticipantIds.has(employee.id),
disabled: false, // Всех можно выбирать
})),
}))
.filter((dept) => dept.employees.length > 0);
}
}); });
const delEvent = (idev) => { const delEvent = (idev) => {
axiosApiInstance axiosApiInstance.delete(`api/calendar_of_events/my_events/?delid=${idev}`).then((result) => {
.delete(`api/calendar_of_events/my_events/?delid=${idev}`) feedalert.alert = true;
.then((result) => { feedalert.text = result.data.mess;
feedalert.alert = true; feedalert.ico = 'mdi-check';
feedalert.text = result.data.mess; feedalert.color = 'orange-accent-1';
feedalert.ico = "mdi-check"; emit('getCalendar');
feedalert.color = "orange-accent-1"; });
emit("getCalendar"); emit('closeDialog');
});
emit("closeDialog");
}; };
const files = ref([]); const newFiles = ref([]);
const postFiles = (f) => {
files.value = f; const handleFilesUpdate = (updatedExistingFiles) => {
// Сохраняем новые файлы во временную переменную
const currentNewFiles = [...newFiles.value];
// Обновляем существующие файлы
propsEvent.value.event.files = updatedExistingFiles;
// Восстанавливаем новые файлы
newFiles.value = currentNewFiles;
}; };
const calendar = computed({ const postFiles = (updatedFiles) => {
get() { newFiles.value = updatedFiles;
let selected = [];
if (propsEvent.value.event.calendar) {
let ind = propsEvent.value.mycalendars.findIndex(
(e) => e.id == propsEvent.value.event.calendar
);
selected.push({
cl_name: propsEvent.value.mycalendars[ind].cl_name,
cl_color: propsEvent.value.mycalendars[ind].cl_color,
id: propsEvent.value.mycalendars[ind].id,
});
} else {
selected.push({
cl_name: propsEvent.value.mycalendars[0].cl_name,
cl_color: propsEvent.value.mycalendars[0].cl_color,
id: propsEvent.value.mycalendars[0].id,
});
}
if (propsEvent.value.event.calendar == null)
propsEvent.value.event.calendar = propsEvent.value.mycalendars[0].id;
return selected;
},
set(newValue) {
propsEvent.value.event.calendar = newValue.value;
},
});
const titleCard = ref("");
const newEvent = ref(false);
const calendarNewOrOld = () => {
if (propsEvent.value.event.hasOwnProperty("id")) {
titleCard.value = "Редактирование события";
newEvent.value = false;
} else {
titleCard.value = "Новое событие";
newEvent.value = true;
}
}; };
const returnIdParticant = (idPart) => { const returnIdParticant = (idPart) => {
idPart.staff.forEach((e) => { idPart.staff.forEach((e) => {
if ( if (e.selected == true && !propsEvent.value.event.participant.includes(e.id)) {
e.selected == true &&
!propsEvent.value.event.participant.includes(e.id)
) {
propsEvent.value.event.participant.push(e.id); propsEvent.value.event.participant.push(e.id);
} else { } else {
let ind = propsEvent.value.event.participant.findIndex( let ind = propsEvent.value.event.participant.findIndex((l) => l == e.id);
(l) => l == e.id
);
if (ind != -1) { if (ind != -1) {
propsEvent.value.event.participant.splice(ind, 1); propsEvent.value.event.participant.splice(ind, 1);
@@ -457,167 +493,125 @@ export default {
const cbSelect = (item, arr) => { const cbSelect = (item, arr) => {
item.forEach((e) => { item.forEach((e) => {
if (!("employees" in e)) { if (!('employees' in e)) {
if (!propsEvent.value.event.participant.includes(e.id)) { if (!propsEvent.value.event.participant.includes(e.id)) {
propsEvent.value.event.participant.push(e.id); propsEvent.value.event.participant.push(e.id);
} }
} }
if ("employees" in e) { if ('employees' in e) {
cbSelect(e.employees); cbSelect(e.employees);
} }
}); });
}; };
const dateEvent = computed({
get() {
return formatComa(new Date(propsEvent.value.event.date_start));
},
set(newValue) {
let dateParts = newValue.split(".");
// let d = new Date(propsEvent.value.event.date_start).setFullYear(parseInt(dateParts[2], 10), parseInt(dateParts[1], 10), parseInt(dateParts[0], 10))
// let d = new Date(propsEvent.value.event.date_start).setDate(new Date(2024,01,01))
// propsEvent.value.event.date_start = new Date(2024,01,01);
},
});
const menudate = ref(false); const menudate = ref(false);
const postData = (validate) => { const postData = (validate) => {
if (validate) { if (validate) {
updatePeriodRule(selectedRule.value);
propsEvent.value.event.calendar = myCalendar.value.id;
let postEvent = new FormData(); let postEvent = new FormData();
postEvent.append( postEvent.append(
"event", 'event',
JSON.stringify({ ...propsEvent.value.event }) JSON.stringify({ ...propsEvent.value.event, files: propsEvent.value.event.files }),
); );
console.log([propsEvent.value]);
if (propsEvent.value.event.files !== null) { if (propsEvent.value.event.files !== null) {
files.value.forEach((e) => postEvent.append("files", e)); newFiles.value.forEach((e) => postEvent.append('files', e));
} }
axiosApiInstance axiosApiInstance.post('api/calendar_of_events/my_events/', postEvent).then((result) => {
.post("api/calendar_of_events/my_events/", postEvent) feedalert.alert = true;
.then((result) => { feedalert.text = result.data.mess;
feedalert.alert = true; feedalert.ico = 'mdi-check';
feedalert.text = result.data.mess; feedalert.color = 'green-darken-4';
feedalert.ico = "mdi-check"; emit('getCalendar');
feedalert.color = "green-darken-4"; emit('closeDialog');
emit("getCalendar"); });
emit("closeDialog");
});
} }
}; };
const getWeekNumbersBetweenDates = () => { const handleAutoAdjustEnd = (newEndDate) => {
const start = new Date(propsEvent.value.event.date_start); propsEvent.value.event.date_end = newEndDate;
const end = new Date(propsEvent.value.event.date_end); };
let s = start.getDay();
let e = end.getDay(); const updateDateStart = (newDate) => {
const weekNumbers = []; // Нормализуем к ISO строке
if (start.getDay() > end.getDay()) { const normalizedDate = new Date(newDate).toISOString();
e = 6; propsEvent.value.event.date_start = normalizedDate;
for (let x = s; x <= e; x++) {
weekNumbers.push(x); // При изменении даты начала - обновляем правило повторений
const startDate = new Date(normalizedDate);
const endDate = new Date(propsEvent.value.event.date_end);
if (startDate > endDate) {
const adjustedEnd = new Date(startDate);
adjustedEnd.setHours(startDate.getHours() + 1);
propsEvent.value.event.date_end = adjustedEnd.toISOString(); // Тоже ISO
}
if (selectedRule.value.rule) {
updatePeriodRule(selectedRule.value);
}
};
const updateDateEnd = (newDate) => {
// Нормализуем к ISO строке
propsEvent.value.event.date_end = new Date(newDate).toISOString();
};
// функция обновления периода
const updatePeriodRule = (rule) => {
selectedRule.value = rule;
if (!rule.rule) {
propsEvent.value.event.period = null;
return;
}
const dtstart = new Date(propsEvent.value.event.date_start);
const ruleOptions = {
...rule.rule,
dtstart: dtstart,
};
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();
};
watch(
() => propsEvent.value.event?.period,
(newPeriod) => {
if (newPeriod) {
initializeRule();
} }
}
if (start.getDay() != end.getDay() && start.getDay() > end.getDay()) {
s = 0;
for (let x = s; x <= end.getDay(); x++) {
weekNumbers.push(x);
}
}
if (start.getDay() < end.getDay()) {
for (let x = s; x <= end.getDay(); x++) {
weekNumbers.push(x);
}
}
if (start.getDay() == end.getDay()) {
weekNumbers.push(start.getDay());
}
let rulesWeek = [];
weekNumbers.forEach((i) => {
rulesWeek.push(rulleWeek[i]);
});
return rulesWeek;
};
const getMonthBetweenDates = () => {
const start = new Date(propsEvent.value.event.date_start);
const end = new Date(propsEvent.value.event.date_end);
let s = start.getDate();
let e = end.getDate();
const dateNumbers = [];
for (let x = s; x <= e; x++) {
dateNumbers.push(x);
}
return dateNumbers;
};
const getYearBetweenDates = () => {
const start = new Date(propsEvent.value.event.date_start);
const end = new Date(propsEvent.value.event.date_end);
let dates = getDatesBetweenDates(start, end);
let date = [];
dates.forEach((e) => date.push(new Date(e).getDate()));
return date;
};
const getNumberMonth = () => {
const start = new Date(propsEvent.value.event.date_start);
const end = new Date(propsEvent.value.event.date_end);
let sm = start.getMonth();
let em = end.getMonth();
let month = [];
month.push(sm + 1);
if (!month.includes(em + 1)) month.push(em + 1);
return month;
};
const getDatesBetweenDates = (startDate, endDate) => {
let dates = [];
let currentDate = new Date(startDate);
while (currentDate <= endDate) {
dates.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
return dates;
};
const what = (w) => {
console.log(w, "?????????????????????????????????");
};
const periodDisplayRule = (idItem) => {
if (getNumberOfDays.value >= 7 && idItem == 3) {
return true;
} else return false;
};
const getNumberOfDays = computed({
get() {
const start = new Date(propsEvent.value.event.date_start);
const end = new Date(propsEvent.value.event.date_end);
const oneDay = 1000 * 60 * 60 * 24;
const diffInTime = end.getTime() - start.getTime();
const diffInDays = Math.round(diffInTime / oneDay);
return diffInDays;
}, },
}); { immediate: true },
);
return { return {
menudate, menudate,
titleCard, titleCard,
newEvent,
propsEvent, propsEvent,
dateEvent,
calendar,
staff, staff,
newStaff, newStaff,
returnIdParticant, returnIdParticant,
@@ -625,14 +619,23 @@ export default {
postData, postData,
rules, rules,
delEvent, delEvent,
myCalendar,
safeCalendars,
isCalendarsReady,
isNewEvent,
repeatRules, repeatRules,
returnPeriod, updatePeriodRule,
periodDisplayRule, selectedRule,
what, updateDateEnd,
updateDateStart,
initializeRule,
createDialog, createDialog,
getMonthBetweenDates, handleAutoAdjustEnd,
newFiles,
handleFilesUpdate,
initializeCalendar,
}; };
}, },
}; };
+20 -19
View File
@@ -20,7 +20,7 @@
</template> </template>
<span>F.A.Q.</span> <span>F.A.Q.</span>
</v-tooltip> </v-tooltip>
<v-dialog v-model="LikeDialog" persistent width="800"> <v-dialog v-model="LikeDialog" persistent width="800">
<template v-slot:activator="{ props }"> <template v-slot:activator="{ props }">
@@ -83,11 +83,11 @@
<!-- v-if="!('submenu' in x) || (x.path== '/portal' && accountStore.user.is_staff)" --> <!-- 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) <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" " :key="x.key" :title="x.name" :value="x.name" :href="x.link" :disabled="x.path == ''" :to="x.path"
:target="x.link ? '_blank' : ''" :target="x.link ? '_blank' : ''"
color="navigation" color="navigation"
> >
<template v-slot:prepend> <template v-slot:prepend>
<v-icon :icon="x.ico" /> <v-icon :icon="x.ico" />
<v-tooltip v-if="rail" activator="parent" location="top"> <v-tooltip v-if="rail" activator="parent" location="top">
@@ -117,7 +117,7 @@
</v-list> </v-list>
<v-list nav density="compact"> <v-list nav density="compact">
<v-list-item v-for="x of mainmenuStore.portallinks" :key="x.name" :title="x.name" :value="x.name" <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' : ''"> :href="x.link" color="app_bar" :target="x.link ? '_blank' : ''">
<template v-slot:prepend> <template v-slot:prepend>
<v-icon :icon="x.imagecode" /> <v-icon :icon="x.imagecode" />
@@ -133,7 +133,7 @@
<v-row class="flex-grow-0" v-if="accountStore.user.is_staff"> <v-row class="flex-grow-0" v-if="accountStore.user.is_staff">
<v-col> <v-col>
<AdminMenu :rail="rail" /> <AdminMenu :rail="rail" />
</v-col> </v-col>
</v-row> </v-row>
<v-row no-gutters class="flex-grow-0"> <v-row no-gutters class="flex-grow-0">
@@ -147,16 +147,17 @@
<v-main v-if="accountStore.cod2user" class="d-flex bg-main_theme"> <v-main v-if="accountStore.cod2user" class="d-flex bg-main_theme">
<router-view /> <router-view />
<alert-default /> <alert-default />
</v-main> </v-main>
<v-main v-else class="d-flex align-center text-h3 bg-teal-lighten-2"> <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 <v-card-text
class="justify-center bgCard h-100 ma-3 d-flex flex-column" 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 <v-row
class="bgText flex-grow-0" 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;"
> >
@@ -164,7 +165,7 @@
Добро пожаловать на портал МИ ФНС России по ЦОД № 2 Добро пожаловать на портал МИ ФНС России по ЦОД № 2
</v-col> </v-col>
</v-row> </v-row>
<v-row <v-row
class="bgText flex-grow-0" 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;"
> >
@@ -258,7 +259,7 @@ export default {
mainmenuStore.loadlinks(); mainmenuStore.loadlinks();
const navigations = ref([ const navigations = ref([
{ {
@@ -303,11 +304,11 @@ export default {
// ], // ],
// }, // },
// { {
// name: "Календарь", name: "Календарь",
// ico: "mdi-calendar", ico: "mdi-calendar",
// path: "/ical", path: "/ical",
// }, },
{ {
name: "Голосование", name: "Голосование",
ico: "mdi-vote", ico: "mdi-vote",
@@ -331,7 +332,7 @@ export default {
path: "/portal", path: "/portal",
}, },
]); ]);
const imageSrc = computed(() => { const imageSrc = computed(() => {
@@ -375,7 +376,7 @@ export default {
navigations, navigations,
imageSrc, imageSrc,
LikeDialog, LikeDialog,
scrimg, scrimg,
rail, rail,
showTooltip, showTooltip,
menuTruncated, menuTruncated,
@@ -384,7 +385,7 @@ export default {
name, name,
closeinfo, closeinfo,
baseURL, baseURL,
message, message,
}; };
}, },
+27 -10
View File
@@ -5,15 +5,32 @@
*/ */
// Plugins // Plugins
import { loadFonts } from './webfontloader' import { loadFonts } from './webfontloader';
import vuetify from './vuetify' import vuetify from './vuetify';
import pinia from '../store' import pinia from '../store';
import router from '../router' import router from '../router';
export function registerPlugins (app) { // FullCalendar
loadFonts() import FullCalendar from '@fullcalendar/vue3';
app import dayGridPlugin from '@fullcalendar/daygrid';
.use(vuetify) import timeGridPlugin from '@fullcalendar/timegrid';
.use(pinia) import multiMonthPlugin from '@fullcalendar/multimonth';
.use(router) import interactionPlugin from '@fullcalendar/interaction';
import listPlugin from '@fullcalendar/list';
import ruLocale from '@fullcalendar/core/locales/ru';
export function registerPlugins(app) {
loadFonts();
app.use(vuetify).use(pinia).use(router);
app.component('FullCalendar', FullCalendar);
app.config.globalProperties.$fullCalendarPlugins = {
dayGridPlugin,
timeGridPlugin,
multiMonthPlugin,
interactionPlugin,
listPlugin,
ruLocale,
};
} }
+44 -59
View File
@@ -1,24 +1,19 @@
// Utilities // Utilities
import { defineStore } from "pinia"; import { defineStore } from 'pinia';
import { ref, watch, computed } from "vue"; import { ref, watch, computed } from 'vue';
import { clearAxios, spravURL } from "@/utils/axios-api"; import { clearAxios, spravURL } from '@/utils/axios-api';
import VueJwtDecode from "vue-jwt-decode"; import VueJwtDecode from 'vue-jwt-decode';
import { checkremote } from "@/utils/universal_functions"; import { checkremote } from '@/utils/universal_functions';
import { useAppStore } from "@/store/app.js"; import { useAppStore } from '@/store/app.js';
export const useAccountStore = defineStore("AccountStore", () => { export const useAccountStore = defineStore('AccountStore', () => {
const AppStore = useAppStore(); const AppStore = useAppStore();
const user = ref(getuserFromStorage()); const user = ref(getuserFromStorage());
const settingsStorage = computed({ const settingsStorage = computed({
get() { get() {
if (Object.keys(user.value).length==0){ if (Object.keys(user.value).length == 0) {
getuserFromStorage() getuserFromStorage();
} }
return JSON.parse(localStorage.getItem(user.value.is_idEmployee)); return JSON.parse(localStorage.getItem(user.value.is_idEmployee));
}, },
@@ -29,12 +24,11 @@ export const useAccountStore = defineStore("AccountStore", () => {
}; };
function get_setting(key) { function get_setting(key) {
return settingsStorage.value === null? defaultSettings[key]: settingsStorage.value[key]; return settingsStorage.value === null ? defaultSettings[key] : settingsStorage.value[key];
} }
const cod2user = ref(false); const cod2user = ref(false);
const calendar = ref(get_setting("calendar") const calendar = ref(get_setting('calendar'));
);
const setUser = (value) => { const setUser = (value) => {
value.photo = checkremote(`${spravURL}${value.login}.jpg`); value.photo = checkremote(`${spravURL}${value.login}.jpg`);
user.value = value; user.value = value;
@@ -43,66 +37,57 @@ export const useAccountStore = defineStore("AccountStore", () => {
// //
// геттер бывший // геттер бывший
// const getUser=computed(()=> uyser.value) // const getUser=computed(()=> uyser.value)
function getuserFromStorage(){ function getuserFromStorage() {
try{ try {
let u = VueJwtDecode.decode(localStorage.getItem("refresh")); let u = VueJwtDecode.decode(localStorage.getItem('refresh'));
u.user.photo = checkremote(`${spravURL}${u.user.login}.jpg`); u.user.photo = checkremote(`${spravURL}${u.user.login}.jpg`);
return u.user; return u.user;
}catch{ } catch {
return {}} return {};
}
} }
const logging = async (anon) => { const logging = async (anon) => {
AppStore.loading = true; AppStore.loading = true;
const result = await clearAxios.post("api/accounts/token/", anon); const result = await clearAxios.post('api/accounts/token/', anon);
localStorage.setItem("access", result.data.access); localStorage.setItem('access', result.data.access);
localStorage.setItem("refresh", result.data.refresh); localStorage.setItem('refresh', result.data.refresh);
user.value=getuserFromStorage() user.value = getuserFromStorage();
if (settingsStorage.value === null) { if (settingsStorage.value === null) {
settingsUp(defaultSettings) settingsUp(defaultSettings);
} }
AppStore.loading = false; AppStore.loading = false;
}; };
const logout = () => { const logout = () => {
user.value = {}; user.value = {};
localStorage.removeItem("access"); localStorage.removeItem('access');
localStorage.removeItem("refresh"); localStorage.removeItem('refresh');
}; };
watch( watch(
user, user,
(newValue, oldValue) => { (newValue, oldValue) => {
cod2user.value = cod2user.value = 'login' in newValue && newValue.login.startsWith('9966-') ? true : false;
"login" in newValue && newValue.login.startsWith("9966-")
? true
: false;
}, },
{ deep: true } { deep: true },
); );
function settingsUp(newSet) { function settingsUp(newSet) {
localStorage.setItem(user.value.is_idEmployee, JSON.stringify(newSet));
localStorage.setItem(user.value.is_idEmployee, JSON.stringify(newSet)
);
} }
watch(
() => calendar.value,
(newValue) => {
let settings = JSON.parse(localStorage.getItem(user.value.is_idEmployee));
settings.calendar = newValue;
settingsUp(settings);
},
{ deep: true },
);
watch(() => calendar.value, (newValue) => { return { user, setUser, cod2user, logging, logout, calendar, getuserFromStorage };
let settings = JSON.parse(localStorage.getItem(user.value.is_idEmployee))
settings.calendar = newValue
settingsUp(settings)
}, {deep: true})
return { user, setUser, cod2user, logging, logout, calendar,getuserFromStorage };
}); });
+274
View File
@@ -0,0 +1,274 @@
import { defineStore } from 'pinia';
import { ref, computed, watch } from 'vue';
import { axiosApiInstance } from '@/utils/axios-api';
import { useAccountStore } from '@/store/AccountStore';
export const useCalendarStore = defineStore('calendarStore', () => {
const accountStore = useAccountStore();
// State
const selectedDate = ref(new Date());
const events = ref([]);
const selectedEvent = ref(null);
const showEventDialog = ref(false);
const currentView = ref('dayGridMonth'); // Текущий вид календаря
const calendars = ref([]); // Список календарей пользователя
const lastUpdatedBy = ref(null);
const holidays = ref([]);
// Массив ID скрытых календарей. Загружаем из localStorage при инициализации.
const hiddenCalendarIds = ref(JSON.parse(localStorage.getItem('hiddenCalendars')) || []);
// Getters
const formattedSelectedDate = computed(() => selectedDate.value.toISOString().split('T')[0]);
const myCalendars = computed(() => {
const userId = accountStore.user.is_idEmployee;
return calendars.value
.map((calendar) => {
const isAuthor = calendar.author === userId;
const participant = calendar.participant.find((p) => p.participant_calendar === userId);
const isEditor = participant?.editor === true;
return {
calendar,
isAuthor,
isEditor,
hasAccess: isAuthor || isEditor,
};
})
.filter(({ hasAccess }) => hasAccess)
.map(({ calendar, isAuthor, isEditor }) => ({
...calendar,
isAuthor,
isEditor,
visible: !hiddenCalendarIds.value.includes(calendar.id),
}));
});
const subscribedCalendars = computed(() =>
calendars.value
.filter((e) => e.author !== accountStore.user.is_idEmployee)
.map((calendar) => ({
...calendar,
visible: !hiddenCalendarIds.value.includes(calendar.id),
})),
);
// Watcher: автоматически сохраняем hiddenCalendarIds в localStorage при изменении
watch(
() => {
hiddenCalendarIds.value;
},
(newValue) => {
localStorage.setItem('hiddenCalendars', JSON.stringify(newValue));
},
{ deep: true },
);
const eventsForSelectedDate = computed(() =>
events.value.filter((event) => event.date_start.split('T')[0] === formattedSelectedDate.value),
);
// Actions
const setSelectedDate = (date, source = 'unknown') => {
selectedDate.value = new Date(date);
lastUpdatedBy.value = source;
};
const setSelectedDateFromCalendar = (info) => {
const date = new Date(info.dateStr);
setSelectedDate(date, 'calendar');
};
const setSelectedDateFromPicker = (date) => {
setSelectedDate(date, 'datepicker');
};
const setCurrentView = (view) => {
currentView.value = view;
};
// Загрузка календарей пользователя
const loadCalendars = async () => {
try {
const response = await axiosApiInstance.get('api/calendar_of_events/my_calendars/');
calendars.value = response.data.map((calendar) => ({
...calendar,
// visible: true,
}));
} catch (error) {
console.error('Ошибка загрузки календарей:', error);
}
};
const toggleCalendarVisibility = (calendarId) => {
const index = hiddenCalendarIds.value.indexOf(calendarId);
if (index === -1) {
// Если ID нет в массиве скрытых, добавляем его (значит, календарь скрывается)
hiddenCalendarIds.value.push(calendarId);
} else {
// Если ID есть в массиве, удаляем его (значит, календарь показывается)
hiddenCalendarIds.value.splice(index, 1);
}
};
const visibleCalendars = computed(() =>
calendars.value.filter((calendar) => !hiddenCalendarIds.value.includes(calendar.id)),
);
const calendarColorMap = computed(() => {
const map = new Map();
myCalendars.value.forEach((calendar) => {
map.set(calendar.id, calendar.cl_color);
});
return map;
});
const allEvents = computed(() => {
return calendars.value
.filter((calendar) => !hiddenCalendarIds.value.includes(calendar.id))
.flatMap((calendar) =>
calendar.events.map((event) => ({
...event,
calendarData: calendar,
})),
);
});
const editableEvents = computed(() => {
const currentUserId = accountStore.user.is_idEmployee;
return allEvents.value.filter((event) => {
const calendar = event.calendarData;
if (!calendar) return false;
// Автор календаря
if (calendar.author === currentUserId) return true;
// Ищем участника с правами редактора
const isEditor = calendar.participant?.some(
(part) => part.participant_calendar === currentUserId && part.editor === true,
);
return isEditor;
});
});
const canEditEvent = (eventId) => {
const id = Number(eventId);
return editableEvents.value.some((e) => e.id === id);
};
const fetchHolidays = async (year) => {
try {
const response = await axiosApiInstance.get(
`api/calendar_of_events/exclusion_dates/?year=${year}`,
);
holidays.value = response.data;
return holidays.value;
} catch (err) {
console.error('Ошибка загрузки праздников:', err);
throw err;
}
};
// Метод для проверки, является ли день выходным или праздничным
const isNonWorkingDay = (dateInput) => {
let date;
// Если входные данные — это строка в формате 'YYYY-MM-DD'
if (typeof dateInput === 'string') {
date = new Date(dateInput);
}
// Если входные данные — это объект Date
else if (dateInput instanceof Date) {
date = new Date(dateInput);
}
// Если входные данные некорректны
else {
return false;
}
// Проверяем, что дата корректна
if (isNaN(date.getTime())) {
return false;
}
const day = date.getDay();
// Проверка на выходной (суббота или воскресенье)
const isWeekend = day === 0 || day === 6;
// Получаем год, месяц и день
const year = date.getFullYear();
const month = date.getMonth() + 1; // Месяцы в JS начинаются с 0
const dayOfMonth = date.getDate();
const normalizedCurrentDate = `${year}-${String(month).padStart(2, '0')}-${String(dayOfMonth).padStart(2, '0')}`;
// Проверяем, что данные о праздничных днях существуют для текущего года и месяца
const holidaysForYear = holidays.value[year] || {};
const holidaysForMonth = holidaysForYear[month] || [];
// Проверка на исключение (рабочая суббота или праздничный будний день)
const isExceptionDay = holidaysForMonth.includes(normalizedCurrentDate);
const result = {
isNonWorking: (isWeekend && !isExceptionDay) || (!isWeekend && isExceptionDay),
isWeekendForStyling: isWeekend && !isExceptionDay,
isHoliday: !isWeekend && isExceptionDay,
};
return result;
};
// Открыть диалог создания/редактирования
const openEventDialog = (event = null) => {
selectedEvent.value = event;
showEventDialog.value = true;
};
// Закрыть диалог
const closeEventDialog = () => {
showEventDialog.value = false;
selectedEvent.value = null;
};
return {
// State
selectedDate,
events,
selectedEvent,
showEventDialog,
currentView,
calendars,
lastUpdatedBy,
hiddenCalendarIds,
holidays,
// Getters
formattedSelectedDate,
myCalendars,
subscribedCalendars,
eventsForSelectedDate,
visibleCalendars,
allEvents,
calendarColorMap,
editableEvents,
canEditEvent,
// Actions
setSelectedDate,
setCurrentView,
loadCalendars,
openEventDialog,
closeEventDialog,
setSelectedDateFromCalendar,
setSelectedDateFromPicker,
toggleCalendarVisibility,
fetchHolidays,
isNonWorkingDay,
};
});
+7 -7
View File
@@ -32,7 +32,7 @@ export function checking_for_entry(where, what) {
if (!where.includes(what)) { if (!where.includes(what)) {
where.push(what); where.push(what);
} }
} }
export function getfromserver(path, reactive) { export function getfromserver(path, reactive) {
try { try {
@@ -63,7 +63,7 @@ export function checkremote(filecheck) {
export default str; export default str;
export function splitname(name) { export function splitname(name) {
return name.familyname + " " + name.name[0] + "." + name.parentname[0] + "."; return name.familyname + " " + name.name[0] + "." + name.parentname[0] + ".";
} }
@@ -71,7 +71,7 @@ export function pagecounter() {
// Функция записи посещения страницы сотрудникам. // Функция записи посещения страницы сотрудникам.
// В случае, если в роуте присутствует ключ мета и в нем ико - тогда производится запись // В случае, если в роуте присутствует ключ мета и в нем ико - тогда производится запись
const router = useRouter(); const router = useRouter();
if('meta' in router.currentRoute.value && 'ico' in router.currentRoute.value.meta){ if('meta' in router.currentRoute.value && 'ico' in router.currentRoute.value.meta){
const accountStore = useAccountStore(); const accountStore = useAccountStore();
const appStore = useAppStore(); const appStore = useAppStore();
@@ -95,7 +95,7 @@ export function pagecounter() {
export function useICalReader(url) { export function useICalReader(url) {
/// ///
const events = ref([]); const events = ref([]);
const loadICalFile = async () => { const loadICalFile = async () => {
try { try {
const response = await fetch(url); const response = await fetch(url);
@@ -120,13 +120,13 @@ export function useICalReader(url) {
location: event.location, location: event.location,
} }
}) })
return { return {
type: "calendar", type: "calendar",
title: name, title: name,
calendar: calendarEvents, calendar: calendarEvents,
} }
// const vevents = comp.getAllSubcomponents('vevent') // const vevents = comp.getAllSubcomponents('vevent')
// const eventsData = vevents.map(vevent => ({ // const eventsData = vevents.map(vevent => ({
// vevent: vevent, // vevent: vevent,
@@ -173,4 +173,4 @@ export function useICalReader(url) {
export function declOfNum(value, titles) { export function declOfNum(value, titles) {
const cases = [2, 0, 1, 1, 1, 2]; const cases = [2, 0, 1, 1, 1, 2];
return titles[(value % 100 > 4 && value % 100 < 20) ? 2 : cases[(value % 10 < 5) ? value % 10 : 5]]; return titles[(value % 100 > 4 && value % 100 < 20) ? 2 : cases[(value % 10 < 5) ? value % 10 : 5]];
} }
+24 -8
View File
@@ -7,11 +7,15 @@
<Carousel-list /> <Carousel-list />
</v-col> </v-col>
</v-row> </v-row>
<v-row style="height: 250px">
<v-col class="d-flex flex-column flex-grow-0 pa-1"> <v-row class="flex-grow-0" style="min-height: 300px">
<!-- <event-calendar/> --> <v-col class="pa-1 d-flex align-stretch">
<HomeCalendarWidget />
</v-col> </v-col>
</v-row> </v-row>
<!-- <v-row style="height: 250px">
<HomeCalendarWidget />
</v-row> -->
</v-col> </v-col>
<v-col class="d-flex flex-column" lg="5" md="12" cols="12"> <v-col class="d-flex flex-column" lg="5" md="12" cols="12">
<v-row> <v-row>
@@ -47,7 +51,12 @@
<v-btn-toggle v-model="toggle" divided variant="outlined" color="teal-darken-4"> <v-btn-toggle v-model="toggle" divided variant="outlined" color="teal-darken-4">
<v-tooltip :text="x.pages__page" location="top"> <v-tooltip :text="x.pages__page" location="top">
<template v-slot:activator="{ props }"> <template v-slot:activator="{ props }">
<v-btn v-bind="props" :icon="x.pages__ico" :to="x.pages__fullPath" color="teal-darken-4" /> <v-btn
v-bind="props"
:icon="x.pages__ico"
:to="x.pages__fullPath"
color="teal-darken-4"
/>
</template> </template>
</v-tooltip> </v-tooltip>
</v-btn-toggle> </v-btn-toggle>
@@ -74,14 +83,15 @@ import NewsHome from '@/components/news-home.vue';
import DigitalLetna from '@/components/digital-letna.vue'; import DigitalLetna from '@/components/digital-letna.vue';
import { axiosApiInstance } from '@/utils/axios-api'; import { axiosApiInstance } from '@/utils/axios-api';
import HomeCalendarWidget from '@/components/calendar_of_events/UI_calendar/HomeCalendarWidget.vue';
import { useCalendarStore } from '@/store/calendarStore';
export default { export default {
components: { components: {
CarouselList, CarouselList,
DigitalLetna, DigitalLetna,
NewsHome, NewsHome,
HomeCalendarWidget,
}, },
setup() { setup() {
@@ -90,11 +100,17 @@ export default {
const toggle = ref(null); const toggle = ref(null);
const accountStore = useAccountStore(); const accountStore = useAccountStore();
const calendarStore = useCalendarStore();
pagecounter(); pagecounter();
const fetchMyCalendars = () => {
calendarStore.loadCalendars();
};
onMounted(() => { onMounted(() => {
favoritLinks(); favoritLinks();
fetchMyCalendars();
}); });
const favoritLinks = () => { const favoritLinks = () => {
@@ -108,14 +124,14 @@ export default {
appStore, appStore,
favoritLinks, favoritLinks,
favorit, favorit,
fetchMyCalendars,
toggle, toggle,
}; };
}, },
}; };
</script> </script>
<style lang="scss"> <style lang="scss" scoped>
.v-picker-title, .v-picker-title,
.v-picker__header, .v-picker__header,
.v-picker__actions { .v-picker__actions {