22 Commits
Author SHA1 Message Date
lexxik753 03631ec134 refactor [X-08]: рефакторинг завершен 2025-10-03 16:12:29 +03:00
lexxik753 2a88a3da58 refactor [X-07]: надо доделать страницу авторизации 2025-10-02 13:02:33 +03:00
lexxik753 fff189a514 refactor [X-07]: доработка страницы авторизации 2025-09-24 11:49:36 +03:00
lexxik753 31a2905dcf refactor [X-06]: переделаны пользователи онлайн, кнопка скрыть/показать 2025-09-23 16:50:49 +03:00
lexxik753 e519dc1c85 refactor [X-00]: втянуть свежие изменения 2025-09-23 13:05:14 +03:00
lexxik753 c7a6eb9b00 refactor [X-05]: переделана авторизация 2025-09-23 13:02:40 +03:00
lexxik753 8226fb74e6 refactor [X-04]: удалена портянка кода старого, переработан Default Portla.vue, разбито на компоненты 2025-09-22 15:49:20 +03:00
lexxik753 1dd6959f0b refactor [X-03]: переделана левая навигационная панель, добавлены тултипы. Нужно вывести счетчик и админку 2025-09-19 16:06:56 +03:00
lexxik753 08b36bd65b refactor [X-02]: переделываю сайдбары 2025-09-18 17:24:31 +03:00
lexxik753 049c4a1915 refactor [X-01]: надо доделать еще скрытие пользователей онлайн 2025-09-17 17:37:10 +03:00
lexxik753 3b8e67c83b refactor [X-01]: переходим на layouts до обновления vuetify 2025-09-17 14:25:55 +03:00
lexxik753 b4d19770b8 feat [X-01]: я тут накоммитил 2025-09-17 11:51:17 +03:00
lexxik753 d72a30d368 fix [P-0]: правки 2025-08-18 13:40:38 +03:00
lexxik753 225f4cbc8a fix [P-0]: правки 2025-08-18 13:39:35 +03:00
Nukeap 10520599b6 feat [P-282]: надо править бэк2 2025-08-07 10:17:15 +03:00
Nukeap a07891d67b feat [P-282]: надо править бэк 2025-07-28 10:07:55 +03:00
lexxik753 fdfd00e04f feat [P-282]: надо править бэк 2025-07-28 10:06:28 +03:00
lexxik753 a1ef02283b refactor [P-282]: изменил цвет названия отделов, добавил полоску к подписи 2025-07-15 17:22:51 +03:00
lexxik753 838f43a710 feat [P-282]: сделаны и отображены карточки, реализован функционал поиска, внесены правки в бэк - в части запроса данных 2025-07-15 15:07:05 +03:00
lexxik753 c4feb6aee7 feat [P-282]: размечены карточки сотрудников, исправлен запрос на бэке, данные передаются через пропсы 2025-07-14 17:09:45 +03:00
lexxik753 02e7ed4ceb feat [P-281]: переделана шапка, список отделов получен и отрисован в селекте 2025-07-14 13:47:15 +03:00
lexxik753 1051b69dd5 feat [P-279]: сделана шапка, добавлены пути в левом списке меню для отображения справочника 2025-07-11 16:09:23 +03:00
42 changed files with 1446 additions and 3065 deletions

No files matched your search

+1 -2
View File
@@ -94,8 +94,7 @@ class Event(models.Model):
return str(self.name)
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.CASCADE, 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='Событие')
file = models.FileField(upload_to='calendar/%Y/%m/%d')
class Meta:
+3 -4
View File
@@ -20,10 +20,11 @@ class ExclusionDatesAPIView(APIView):
year = self.request.query_params.get('year', datetime.now().year)
exclude = ExclusionDates.objects.filter(exclusiondate__year=year)
months = {}
for i in range(1,13):
for i in range(1,12):
months[i] = exclude.filter(exclusiondate__month=i).values_list("exclusiondate", flat=True)
return Response({year:months})
class MyCalendars(APIView):
def get(self, request):
@@ -103,9 +104,7 @@ class MyEvents(APIView):
resp = {'mycalendars':CalendarsSerializerForEventEdit(allcalendars, many=True).data }
if request.query_params.get("id") is not None:
event = Event.objects.get(id = request.query_params.get("id"))
resp['event']=EventSerializerIdRequest(event).data
# events = Event.objects.filter(calendar__id = request.query_params.get("id"))
# resp['events'] = EventSerializerIdRequest(events, many=True).data
resp['event']=EventSerializerIdRequest(event).data
return Response(resp)
@@ -0,0 +1,31 @@
# Generated by Django 5.2.4 on 2025-07-18 09:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("commeteresp", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="OrderResponsibilityEmployee",
fields=[
(
"id",
models.PositiveIntegerField(
db_comment="╥рсхы№э√щ эюьхЁ", primary_key=True, serialize=False
),
),
],
options={
"verbose_name": "Ответственный сотрудник",
"verbose_name_plural": "Ответственные сотрудники",
"db_table": "order_responsibility_employee",
"managed": False,
},
),
]
+1
View File
@@ -70,4 +70,5 @@ urlpatterns = [
path('api/safety/', include('safety.urls')),
path('api/tests/', include('tests.urls')),
path('api/vote/', include('vote.urls')),
path('api/userauth/', include('userauth.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
+12 -1
View File
@@ -132,6 +132,17 @@ class InfoUserCardSerializer(serializers.ModelSerializer):
""" Собирает необходимую информацию о пользователе, содержит необходимые
поля для отрисовки карточки информации о пользователе при клике на фамилию
Необходим для компонента infoUserCard"""
position = serializers.IntegerField(source='id_dict_position.order_position')
department = serializers.CharField(source='id_dict_department.name')
class Meta:
model = DictEmployee
fields = ['department', 'fio', 'post', 'email', 'tel', 'room', 'login', 'familyname', 'name', 'parentname', 'id']
fields = ['department', 'fio', 'post', 'email', 'tel', 'room', 'login', 'familyname', 'name', 'parentname', 'id', 'deleted','position']
class DepartmentsSerializer(serializers.ModelSerializer):
persons = InfoUserCardSerializer(source='dep_user', many=True)
class Meta:
model = DictDepartment
fields = ['id','name','persons']
+6
View File
@@ -0,0 +1,6 @@
from django.urls import path
from .views import *
urlpatterns = [
path('getdepartments', GetDepartment.as_view(), name= "GetDepartment")
]
+14 -1
View File
@@ -1,3 +1,16 @@
from django.shortcuts import render
from .models import DictDepartment
from .serializers import DepartmentsSerializer
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
# Create your views here.
class GetDepartment(APIView):
permission_classes = (AllowAny,)
"""
Получаем отделы
"""
def get(self,request):
department = DictDepartment.objects.all()
return Response(DepartmentsSerializer(department, many=True).data)
+1 -9
View File
@@ -36,15 +36,7 @@
"vue3-autocounter": "^1.0.8",
"vuelidate": "^0.7.7",
"vuetify": "^3.7.8",
"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"
"webfontloader": "^1.6.28"
},
"devDependencies": {
"@commitlint/cli": "^19.7.1",
@@ -0,0 +1,43 @@
<template>
<div v-for="(sort, depart) in grouped" class="mt-2">
<h2 class="text-teal">{{ depart }}</h2>
<v-divider :thickness="4" color="teal"/>
<v-row class="mt-1">
<v-col v-for="person in sort.sort((a,b)=>a.position-b.position)" cols="4" :key="person.id" class="cursor-pointer">
<CardDictEmployee :person="person" v-model:moreInformation="moreInformation"/>
</v-col>
</v-row>
</div>
<v-dialog v-model="moreInformation" transition="dialog-top-transition">
<DialogEmployeeDirection />
</v-dialog>
</template>
<script setup>
import DialogEmployeeDirection from "./DialogEmployeeDirection.vue";
import CardDictEmployee from "../UI/DictEmployee/CardDictEmployee.vue";
import { ref, computed } from 'vue'
const props = defineProps({
selectedDep: {
name: String,
},
isWork: Number,
search: String,
})
const moreInformation = ref(false)
const filteredPerson = computed(() => {
return props.selectedDep.persons.filter(item => item.deleted == props.isWork && item.fio.toLowerCase().includes(props.search.toLowerCase()))
})
const grouped = computed(() => {
let group = []
group = Object.groupBy(filteredPerson.value, (item) => item.department)
return group
})
</script>
@@ -0,0 +1,39 @@
<template>
<v-card>
<v-row class="bg-red">
<v-col class="bg-blue">
Общие данные
<!-- <CardDictEmployee /> -->
</v-col>
<v-col class="bg-purple">Участия в комиссиях</v-col>
</v-row>
<v-row class="bg-green">
<v-col class="bg-orange">Сферы ответственности</v-col>
</v-row>
</v-card>
</template>
<script setup>
import CardDictEmployee from '../UI/DictEmployee/CardDictEmployee.vue';
import { axiosApiInstance } from '@/utils/axios-api'
import { onMounted } from 'vue'
const props = defineProps({
fullListInfo: {
}
})
async function getFullInfoList() {
try {
const response = await axiosApiInstance.get('api/userauth/getdepartments')
} catch (error) {
console.log('Ошибка получения полной информации из справоника', error);
}
}
onMounted(async () => {
await getFullInfoList();
})
</script>
@@ -0,0 +1,55 @@
<template>
<v-card class="pa-2">
<v-row align="center">
<v-col cols="6">
<v-select
return-object
item-title="name"
:items="props.department"
v-model="selectedDep"
variant="outlined"
density="compact"
hide-details bg-color="grey-lighten-5"
label="Список отделов">
</v-select>
</v-col>
<v-col cols="2">
<v-switch
v-model="isWork"
:false-value="0"
:true-value="1"
color="teal"
label="Уволенные"
hide-details>
</v-switch>
</v-col>
<v-col class="ml-auto" cols="2">
<v-text-field
v-model="search"
append-inner-icon="mdi-magnify"
label="Поиск сотрудников"
variant="outlined"
density="compact"
bg-color="grey-lighten-5"
hide-details
clearable
@click:clear="handleClear"
/>
</v-col>
</v-row>
</v-card>
</template>
<script setup>
const props = defineProps({
department: Array,
})
const selectedDep = defineModel('selectedDep')
const isWork = defineModel('isWork')
const search = defineModel('search')
const handleClear = () => {
search.value = '';
};
</script>
@@ -0,0 +1,60 @@
<template>
<!-- добавить проверку пользователи скрыты или нет (смена текста) от состояния -->
<v-tooltip v-for="itemMenu in navMenu" :text="itemMenu.text" location="bottom">
<template v-slot:activator="{ props }">
<v-btn :icon="itemMenu.icon" v-bind="props" @click="itemMenu.event" :color="itemMenu.color"/>
</template>
</v-tooltip>
<v-dialog v-model="isDialog" width="800">
<card-like :LikeDialog="isDialog" @menusClose="isDialog = false"/>
</v-dialog>
</template>
<script setup>
import router from '@/router';
import { useTheme } from "vuetify";
import { useAccountStore } from '@/store/AccountStore';
import { ref, computed } from 'vue';
import CardLike from '@/components/cardLike.vue'
const userStore = useAccountStore()
const theme = useTheme()
const isDialog = ref(null)
const rightRail = ref(true)
const emit = defineEmits(['showUser'])
const navMenu = computed(() => {
return [
{
text: 'F.A.Q.',
icon: 'mdi-comment-question-outline',
event: () => router.push('/faq'),
},
{
text: 'Обратная связь',
icon: 'mdi-thumb-up-outline',
event: () => isDialog.value = true,
},
{
text: 'Сменить тему',
icon: 'mdi-lightbulb-outline',
color: 'lampa',
event: () => theme.toggle(),
},
{
text: `${rightRail.value == true ? 'Скрыть ' : 'Показать '} пользователей`,
icon: 'mdi-account-multiple-outline',
event: () => {
rightRail.value = !rightRail.value
emit('showUser', rightRail.value)
},
},
{
text: 'Выход',
icon: 'mdi-logout',
event: () => userStore.logout(),
},
]})
</script>
+5 -2
View File
@@ -109,6 +109,7 @@ import {useAppStore} from '@/store/app'
import { useVuelidate } from '@vuelidate/core'
import { required, helpers } from '@vuelidate/validators'
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router';
const req= helpers.withMessage('Обязательное поле', required)
@@ -122,7 +123,7 @@ export default {
const err = ref('')
const alert = ref(false)
const eyeshow = ref(false)
const router = useRouter()
const anon=reactive({
username:"9966-00-",
@@ -158,7 +159,9 @@ export default {
}
finally {
router.push('/')
}
}
}
@@ -0,0 +1,27 @@
<template>
<v-card v-model="moreInformation" @click="moreInformation = true">
<v-avatar :image="checkremote(`${spravURL}.jpg`)" rounded="0" size="100"></v-avatar>
<v-card-item>
<v-card-title>{{ props.person.familyname }} {{ props.person.name }} {{ props.person.parentname }}</v-card-title>
<v-card-title class="text-subtitle-1">{{ props.person.post }}</v-card-title>
<v-card-subtitle>{{ props.person.tel }}</v-card-subtitle>
</v-card-item>
</v-card>
</template>
<script setup>
import { checkremote } from "@/utils/universal_functions";
import { spravURL } from "@/utils/axios-api";
const props = defineProps({
person: {
familyname: String,
name: String,
parentname: String,
tel: String,
post: String,
}
})
const moreInformation = defineModel('moreInformation')
</script>
@@ -1,431 +1,150 @@
<template>
<v-col>
<div class="custom-file-input-wrapper">
<label class="v-label v-field-label v-field-label--floating">
Добавить файл (размер файла не должен превышать 2Мб)
</label>
<v-file-input
label="Файлы"
chips
multiple
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>
<!-- Область, куда можно перетащить файлы -->
<div
class="file-input-area"
@click="triggerFileInput"
@drop="handleDrop"
@dragover.prevent
@dragenter.prevent
>
<!-- Кастомные чипы новых файлов ВНУТРИ "инпута" -->
<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>
<span
v-else-if="index === 4"
class="text-overline text-grey-darken-3 mx-2"
>
+{{ files.length - 4 }} файла(ов)
</span>
</template>
</template>
</v-file-input>
</v-col>
</template>
<script>
import { computed, ref, watch } from 'vue';
import { computed, ref } from "vue";
import { get_name } from "@/utils/universal_functions";
export default {
props: {
files: {
type: Array,
default: () => [],
},
newFiles: {
type: Array,
default: [],
type: Object,
default: () => {},
},
},
emits: ['update:files', 'update:newFiles', 'postFiles'],
setup(props, { emit }) {
const localNewFiles = ref([]);
const errorMessages = ref([]);
const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2 МБ
const MAX_NEW_FILES = 5;
const fileInputRef = ref(null);
const propsFiles = computed({
get: () => props.files,
set: (value) => emit("update:files", value),
});
watch(
() => props.newFiles,
(newVal) => {
localNewFiles.value = Array.isArray(newVal) ? [...newVal] : [];
},
{ immediate: true },
);
const arrFiles = ref([]);
// Существующие файлы из event.files
const existingFiles = computed(() => (Array.isArray(props.files) ? props.files : []));
const triggerFileInput = () => {
if (fileInputRef.value) {
fileInputRef.value.click();
}
};
const handleFileSelect = (event) => {
const files = Array.from(event.target.files || []);
if (files.length > 0) {
handleFilesChange(files);
}
// Очищаем input для возможности выбора тех же файлов снова
event.target.value = '';
};
// Обработка drag & drop
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;
}
// Проверка размера
const oversizedFiles = files.filter((file) => file.size > MAX_FILE_SIZE);
if (oversizedFiles.length > 0) {
errorMessages.value.push(
`Следующие файлы превышают 2 МБ: ${oversizedFiles.map((f) => f.name).join(', ')}`,
const eventFiles = computed({
get() {
propsFiles.value.forEach((e) =>
{
arrFiles.value.push(
dataURLtoFile(
"data:text/plain;base64,aGVsbG8gd29ybGQ=",
get_name(decodeURI(e.file))
)
)}
);
return false;
}
return arrFiles.value;
},
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 'Файл';
set(newValue) {
let newFile = []
arrFiles.value = [];
if (newValue.length == 0) {
arrFiles.value = [];
propsFiles.value = [];
} else {
newValue.forEach((e) => {
arrFiles.value.push(e)
newFile.push(e)
});
}
emit("postFiles", newFile);
},
});
//
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(","),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return cleanFileName(fileData.name || 'Файл');
};
return new File([u8arr], filename, { type: mime });
}
// const eventFiles = computed({
// get() {
// if (propsFiles.value.length > 0) {
// 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)
// // )
// // );
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);
}
};
// // files.value.push(file);
// }
// 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 {
localNewFiles,
existingFiles,
handleFilesChange,
removeExistingFile,
removeNewFile,
getFileName,
getFileIcon,
formatFileSize,
errorMessages,
validateFiles,
getFileKey,
MAX_NEW_FILES,
fileInputRef,
handleFileSelect,
triggerFileInput,
handleDrop,
cleanFileName,
downloadExistingFile,
eventFiles,
arrFiles,
};
},
};
</script>
<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>
<style></style>
@@ -1,21 +1,98 @@
<template>
<v-row no-gutters>
<v-col class="flex-grow-0 d-flex flex-column">
<mini-calendar />
<v-card class="h-100 rounded-0 d-flex flex-colmn" width="250">
<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 class="d-flex flex-column">
<custom-calendar @openEventDialog="openEventDialog" />
<calendar-full
:allEvent="calendarForMy.filter((e) => e.events.length > 0)"
@getEvent="createEvent"
@update:allEvent="infoEvent($event)"
/>
</v-col>
<v-dialog v-model="showEventDialog" max-width="700">
<!-- <v-navigation-drawer
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
@closeDialog="closeEventDialog"
@closeDialog="showDialog = false"
:eventCalendar="eventFromCalendar"
:myCalendars="calendarStore.myCalendars"
@getCalendar="getCalendar"
@update:eventCalendar="eventFromCalendar = $event"
@getCalendar="getCalendar"
ref="createEvents"
:key="eventKey"
/>
</v-dialog>
</v-row>
@@ -25,29 +102,26 @@
import { ref, onMounted, watch } from 'vue';
import { useWeekendsStore } from '@/store/WeekendsStore';
import EventCreate from '@/components/calendar_of_events/event-create.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 CalendarMy from '@/components/calendar_of_events/calendar-my.vue';
import { axiosApiInstance } from '@/utils/axios-api';
import { useAccountStore } from '@/store/AccountStore';
import CalendarFull from '@/components/calendar_of_events/UI_calendar/calendarFull.vue';
export default {
components: { EventCreate, MiniCalendar, CustomCalendar },
components: { EventCreate, CalendarMy, CalendarFull },
setup() {
const accountStore = useAccountStore();
const showDialog = ref(false);
const week = useWeekendsStore();
const drawer_right = ref(false);
const cal = ref(null);
const selectdate = ref(new Date());
const MyYear = ref(selectdate.value.getFullYear());
const MyMonth = ref(selectdate.value.getMonth() + 1);
const calendarForMy = ref([]);
const eventFromCalendar = ref({});
const eventKey = ref(0);
const isClosingDialog = ref(false);
const calendarStore = useCalendarStore();
const accountStore = useAccountStore();
const { selectedDate, showEventDialog } = storeToRefs(calendarStore); // синхронизируем с date-picker
const createEvents = ref(null);
const getMonth = (month) => {
MyMonth.value = month + 1;
@@ -57,59 +131,79 @@ export default {
};
const getCalendar = () => {
calendarStore.loadCalendars();
axiosApiInstance.get(`api/calendar_of_events/my_calendars/`).then((res) => {
res.data.forEach((e) => (e.visible = accountStore.calendar.includes(e.id) ? false : true));
calendarForMy.value = res.data;
});
};
const getEvent = (idEvent) => {
if (!idEvent) {
eventFromCalendar.value = createEmptyEvent();
return;
} else {
axiosApiInstance.get(`api/calendar_of_events/my_events/?id=${idEvent}`).then((res) => {
getCalendar();
const getEvents = (idEvent, clik) => {
axiosApiInstance
.get(`api/calendar_of_events/my_events/${idEvent === undefined ? '' : `?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;
calendarStore.openEventDialog();
if (clik) showDialog.value = true;
});
};
getEvents();
const createEvent = (idEv) => {
getEvents(idEv, true);
if (idEv) {
getCalendar();
}
};
const createEmptyEvent = () => ({
event: {
name: '',
participant: [accountStore.user.is_idEmployee],
files: [],
date_start: new Date().toISOString(),
date_end: new Date().toISOString(),
period: null,
description: '',
calendar: null,
},
});
const openEventDialog = (selectedEvent) => {
// Всегда сбрасываем данные перед открытием нового диалога
if (!selectedEvent) {
eventFromCalendar.value = createEmptyEvent();
eventKey.value++;
}
getEvent(selectedEvent?.event?.id);
calendarStore.openEventDialog();
const weekendsData = () => {
cal.value.$el.querySelectorAll('.v-date-picker-month__day').forEach((e) => {
let datas = e.getAttribute('data-v-date');
let weeks = new Date(datas).getDay() === 6 || new Date(datas).getDay() === 0;
if (weeks) {
e.querySelectorAll('span').forEach((n) => {
n.classList.add('text-red');
});
}
if (MyMonth.value in week.week[MyYear.value]) {
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) {
n.classList.replace('text-red', 'text-black');
}
});
}
}
});
};
onMounted(() => {
getEvent();
week.getWeekend(MyYear.value);
});
const closeEventDialog = () => {
calendarStore.closeEventDialog();
// При ручном закрытии сбрасываем данные сразу
setTimeout(() => {
eventFromCalendar.value = createEmptyEvent();
eventKey.value++;
}, 200);
};
watch(
() => week.week,
(newValue) => {
if (newValue) {
weekendsData();
}
},
);
const CheckingStore = () => {
if (MyYear.value in week.week) {
@@ -119,42 +213,44 @@ export default {
}
};
watch(
() => calendarStore.showEventDialog,
(newValue, oldValue) => {
if (!newValue && oldValue) {
// Диалог был открыт и закрыт не через нашу кнопку
// Добавляем проверку чтобы не сбрасывать при инициализации
if (eventFromCalendar.value.event?.id) {
setTimeout(() => {
eventFromCalendar.value = createEmptyEvent();
eventKey.value++;
}, 200);
}
}
},
);
const infoEvent = (i) => {
console.log(i, 'iiiiiiiiii');
};
return {
selectedDate,
drawer_right,
selectdate,
cal,
getMonth,
getYear,
weekendsData,
week,
CheckingStore,
showEventDialog,
showDialog,
calendarForMy,
getCalendar,
getEvent,
eventFromCalendar,
calendarStore,
accountStore,
closeEventDialog,
openEventDialog,
createEmptyEvent,
eventKey,
getCalendar,
eventFromCalendar,
createEvent,
infoEvent,
createEvents,
};
},
};
</script>
<style scoped></style>
<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>
@@ -1,543 +0,0 @@
<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>
@@ -1,534 +0,0 @@
<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>
@@ -1,239 +0,0 @@
<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: "week", text: "Неделя" },
{ type: "month", text: "Месяц" },
// { type: "modntdh", text: "Год" },
{ type: "modntdh", text: "Год" },
{ type: "modnth", text: "Расписание" },
];
@@ -314,7 +314,7 @@ export default {
ev.rule.byweekday[ev.rule.byweekday.length - 1].weekday == 6
? 0
: ev.rule.byweekday[ev.rule.byweekday.length - 1].weekday + 1;
if (day.date.getDay() == weeknumS && weeknumS != weeknumE) {
return "rounded-e-lg";
} else if (day.date.getDay() == weeknumE && weeknumS != weeknumE) {
@@ -328,7 +328,7 @@ export default {
return "rounded-lg";
}
}
if (ev.rule.freq == 0) {
if (zeroTime(day.date) == zeroTime(ev.start_event)) {
@@ -342,7 +342,7 @@ export default {
// ev.rule.byweekday[ev.rule.byweekday.length - 1].weekday == 6
// ? 0
// : ev.rule.byweekday[ev.rule.byweekday.length - 1].weekday + 1;
// if (day.date.getDay() == weeknumS && weeknumS != weeknumE) {
// return "rounded-e-lg";
// } else if (day.date.getDay() == weeknumE && weeknumS != weeknumE) {
@@ -2,10 +2,10 @@
<v-col lg="3" :class="`order-${order[0]}`">
<v-menu
v-model="menudate"
:close-on-content-click="false"
:nudge-right="40"
transition="scale-transition"
offset-y
:close-on-content-click="false"
>
<template v-slot:activator="{ props }">
<v-textarea
@@ -21,7 +21,12 @@
hide-details
>
<template v-slot:prepend-inner>
<v-icon v-bind="props" icon="mdi-calendar-today" color="cyan-darken-3" size="x-small" />
<v-icon
v-bind="props"
icon="mdi-calendar-today"
color="cyan-darken-3"
size="x-small"
/>
</template>
</v-textarea>
</template>
@@ -33,7 +38,7 @@
hide-header
border
no-time
:max="endMax()"
:max="order[0] == 2 ? new Date(limitation) : endMax()"
:min="order[0] == 2 ? startMin() : minData()"
/>
</v-locale-provider>
@@ -61,24 +66,29 @@
activator="parent"
transition="scale-transition"
>
<v-time-picker v-if="menutime" v-model="timeEvent" full-width format="24hr"></v-time-picker>
<v-time-picker
v-if="menutime"
v-model="timeEvent"
full-width
format="24hr"
></v-time-picker>
</v-menu>
</v-col>
</template>
<script>
import { ref, computed } from 'vue';
import { formatComa } from '@/utils/universal_functions';
import { ref, computed } from "vue";
import { formatComa, formatDash } from "@/utils/universal_functions";
export default {
props: {
dateEvent: {
type: String,
default: '',
default: "",
},
limitation: {
type: String,
default: '',
default: "",
},
order: {
@@ -93,21 +103,15 @@ export default {
type: Number,
default: -1,
},
isStart: {
type: Boolean,
default: false,
},
},
emits: ['update:dateEvent', 'adjustEndDate'],
setup(props, { emit }) {
const menudate = ref(false);
const menutime = ref(false);
const propsDateEvent = computed({
get: () => new Date(props.dateEvent),
set: (value) => emit('update:dateEvent', value),
set: (value) => emit("update:dateEvent", value),
});
const modelDate = computed({
@@ -115,59 +119,77 @@ export default {
return propsDateEvent.value;
},
set(newValue) {
createdDate(newValue, timeEvent.value);
creatwdDate(newValue, timeEvent.value);
},
});
const timeEvent = computed({
get() {
return `${new Date(propsDateEvent.value).getHours()}:${String(
new Date(propsDateEvent.value).getMinutes(),
).padStart(2, '0')}`;
new Date(propsDateEvent.value).getMinutes()
).padStart(2, "0")}`;
},
set(newValue) {
createdDate(modelDate.value, newValue);
creatwdDate(modelDate.value, newValue);
},
});
const createdDate = (date, time) => {
const [hours, minutes] = time.split(':').map(Number);
const newDate = new Date(date);
newDate.setHours(hours, minutes, 0, 0);
const creatwdDate = (date, time) => {
let tzero = time.split(":");
time = tzero[0].padStart(2, "0") + ":" + tzero[1];
if (props.order[0] == 4) {
const startDate = new Date(props.limitation);
if (newDate <= startDate) {
const correctedDate = new Date(startDate);
correctedDate.setHours(startDate.getHours() + 1);
propsDateEvent.value = correctedDate;
if (time == "0:00") {
propsDateEvent.value = date;
} else if (
new Date(formatDash(date) + "T" + time) >= new Date(props.limitation)
) {
propsDateEvent.value = new Date(formatDash(date) + "T" + time);
} else {
propsDateEvent.value = newDate;
propsDateEvent.value = new Date(props.limitation);
}
} else {
propsDateEvent.value = newDate;
const currentEnd = new Date(props.limitation);
if (newDate > currentEnd) {
const newEnd = new Date(newDate);
newEnd.setHours(newDate.getHours() + 1);
emit('adjustEndDate', newEnd.toISOString());
}
propsDateEvent.value =
time == "0:00" ? date : new Date(formatDash(date) + "T" + time);
}
menudate.value = false;
menutime.value = false;
};
const minData = () => {
return new Date(props.limitation);
let h = `${new Date(props.limitation).getHours()}:${String(
new Date(props.limitation).getMinutes()
).padStart(2, "0")}`;
let min =
h == "0:00"
? new Date(props.limitation)
: new Date(
new Date(props.limitation).setDate(
new Date(props.limitation).getDate() - 1
)
);
return new Date(min);
};
const startMin = () => {
return new Date(); // ← По умолчанию: нельзя выбрать прошедшие даты
if (props.rule == 2) {
return new Date(
new Date(props.limitation).setDate(
new Date(props.limitation).getDate() - 7
)
);
}
return false;
};
const endMax = () => {
return null; // ← Без ограничения сверху
if (props.rule == 2) {
return new Date(
new Date(props.limitation).setDate(
new Date(props.limitation).getDate() + 6
)
);
}
return false;
};
return {
@@ -112,6 +112,7 @@ export default {
const filtered = ref('');
const accountStore = useAccountStore();
const back = ref([]);
const staffed = computed({
get() {
if (props.okey == 'editor') {
@@ -1,7 +1,7 @@
<template>
<dialog-create
:title="titleCard"
:newOrOld="isNewCalendar"
:newOrOld="newCalendar"
@closeDialog="$emit('closeDialog')"
@delObject="delCalendar(propsCalendar.id)"
@postData="postCalendar"
@@ -150,14 +150,20 @@ export default {
cl_descr: [(val) => req(val)],
};
const isNewCalendar = computed(() => !propsCalendar.value.id);
const isAuthor = computed(() => propsCalendar.value.author === accountStore.user.is_idEmployee);
const titleCard = ref('');
const newCalendar = ref(false);
const titleCard = computed(() =>
isNewCalendar.value ? 'Новый календарь' : 'Редактирование календаря',
);
const calendarNewOrOld = () => {
if ('id' in propsCalendar.value) {
titleCard.value = 'Редактирование календаря';
if (propsCalendar.value.author != accountStore.user.is_idEmployee) newCalendar.value = true;
} else {
titleCard.value = 'Новый календарь';
const newCalendar = computed(() => (isNewCalendar.value ? true : !isAuthor.value));
newCalendar.value = true;
}
};
calendarNewOrOld();
const postCalendar = (val) => {
if (val) {
@@ -207,21 +213,21 @@ export default {
});
const color = [
'#3788d8', // Синий (аналог default FullCalendar)
'#4caf50', // Зеленый
'#ff9800', // Оранжевый
'#9c27b0', // Фиолетовый
'#2196f3', // Голубой
'#795548', // Коричневый
'#607d8b', // Серо-голубой
'#e91e63', // Розовый
'#00bcd4', // Бирюзовый
'#8bc34a', // Салатовый
'#ff5722', // Красно-оранжевый
'#673ab7', // Темно-фиолетовый
'#3f51b5', // Индиго
'#009688', // Зелено-бирюзовый
'#ffc107', // Янтарный
'red',
'pink',
'deep-orange',
'amber',
'yellow',
'lime',
'light-green',
'green',
'light-blue',
'blue',
'indigo',
'deep-purple',
'purple',
'blue-grey',
'brown',
];
const colorPik = (col) => {
@@ -260,7 +266,6 @@ export default {
titleCard,
newCalendar,
newStaff,
isNewCalendar,
};
},
};
@@ -1,5 +1,12 @@
<template>
<v-expansion-panels class="calendar" variant="accordion" flat tile static v-model="openGroup">
<v-expansion-panels
class="calendar"
variant="accordion"
flat
tile
static
v-model="openGroup"
>
<v-expansion-panel elevation="0" flat tile static>
<v-expansion-panel-title flat tile static class="py-0 px-3">
<div @click.stop="">
@@ -30,23 +37,26 @@
<v-checkbox-btn
class="text-caption"
:class="`text-${x.cl_color}`"
:color="x.cl_color"
v-model="x.visible"
@update:modelValue="toggleVisiblityEvents(x)"
:color="x.cl_color"
@update:modelValue="chekUpdate(x)"
></v-checkbox-btn>
<!-- :model-value="x.visible" -->
</template>
<template v-slot:title>
<span class="text-body-2"> {{ x.cl_name }} </span>
</template>
<template v-slot:append>
<transition name="fade">
<v-btn
v-if="
x.author == user.is_idEmployee ||
x.author == accountStore.user.is_idEmployee ||
x.participant.some(
(e) => e.editor === true && e.participant_calendar === user.is_idEmployee,
(e) =>
e.editor == true &&
e.participant_calendar ==
accountStore.user.is_idEmployee
)
"
size="x-small"
@@ -64,24 +74,21 @@
</template>
</v-expansion-panel-text>
</v-expansion-panel>
<v-dialog v-model="showDialog" min-width="636" max-width="800">
<calendar-create
@closeDialog="showDialog = false"
:calendar="calendar"
@update:calendar="calendar = $event"
@getCalendar="$emit('getCalendar')"
/>
<v-dialog v-model="showDialog" min-width="636" max-width="800">
<calendar-create
@closeDialog = "showDialog = false"
:calendar="calendar"
@update:calendar="calendar = $event"
@getCalendar="$emit('getCalendar')"
/>
</v-dialog>
</v-expansion-panels>
</template>
<script>
import { ref } from 'vue';
import calendarCreate from '@/components/calendar_of_events/calendar-create.vue';
import { useAccountStore } from '@/store/AccountStore';
import { storeToRefs } from 'pinia';
import { useCalendarStore } from '@/store/calendarStore';
import { ref } from "vue";
import calendarCreate from "@/components/calendar_of_events/calendar-create.vue";
import { useAccountStore } from "@/store/AccountStore";
export default {
components: { calendarCreate },
@@ -92,48 +99,51 @@ export default {
},
title: {
type: String,
default: '',
typr: String,
default: "",
},
},
setup(props) {
setup(props, { emit }) {
const showDialog = ref(false);
const accountStore = useAccountStore();
const { user } = storeToRefs(accountStore);
const calendarStore = useCalendarStore();
const { toggleCalendarVisibility } = calendarStore;
const calendar = ref({});
const openGroup = ref([0]);
const trans = ref(false);
const hover = ref(0);
const editCreatedCalendar = (cal) => {
if (cal === undefined) {
calendar.value = {
cl_name: '',
participant: [{ editor: true, participant_calendar: user.value.is_idEmployee }],
cl_color: 'red',
cl_descr: '',
cl_name: "",
participant: [{ editor: true, participant_calendar: accountStore.user.is_idEmployee }],
cl_color: "red",
cl_descr: "",
};
} else {
calendar.value = cal;
}
showDialog.value = true;
};
const toggleVisiblityEvents = (cal) => {
toggleCalendarVisibility(cal.id, cal.visible);
const chekUpdate = (cal) => {
let setcal = new Set(accountStore.calendar);
if (cal.visible == false) {
setcal.add(cal.id);
} else {
setcal.delete(cal.id);
}
accountStore.calendar = Array.from(setcal);
};
return {
accountStore,
user,
calendar,
showDialog,
calendar,
editCreatedCalendar,
toggleVisiblityEvents,
chekUpdate,
accountStore,
openGroup,
trans,
hover,
@@ -1,56 +0,0 @@
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>
<dialog-create
:title="titleCard"
:newOrOld="isNewEvent"
:newOrOld="newEvent"
@postData="postData"
@closeDialog="$emit('closeDialog')"
@delObject="delEvent(propsEvent?.event?.id)"
@delObject="delEvent(propsEvent.event.id)"
ref="createDialog"
>
<template v-slot:card_text>
@@ -13,7 +13,9 @@
<v-row no-gutters class="align-center">
<!-- <my-helper :pretext="propsEvent.event" /> -->
<v-col class="text-body-2 text-text_grey pb-5" lg="2"> Название </v-col>
<v-col class="text-body-2 text-text_grey pb-5" lg="2">
Название
</v-col>
<v-col>
<v-textarea
@@ -28,7 +30,9 @@
></v-row>
<v-row no-gutters class="align-center">
<v-col class="text-body-2 text-text_grey pb-5" lg="2"> Участники </v-col>
<v-col class="text-body-2 text-text_grey pb-5" lg="2">
Участники
</v-col>
<v-col>
<calendar-create-select
:staff="newStaff"
@@ -40,8 +44,8 @@
<v-col class="text-body-2 text-text_grey" lg="2"> Календарь</v-col>
<v-col>
<v-autocomplete
v-model="myCalendar"
:items="safeCalendars"
v-model="calendar"
:items="propsEvent.mycalendars"
label="Выберите календарь или найдите по названию"
item-title="cl_name"
item-value="id"
@@ -50,58 +54,70 @@
density="compact"
class="py-3"
return-object
:rules="rules.calendar"
:disabled="'id' in propsEvent.event"
clearable
auto-select-first
>
<template v-slot:selection="{ item }">
<v-avatar class="cursor-pointer" size="8" :color="item.raw.cl_color" />
<v-avatar
class="cursor-pointer"
size="8"
:color="item.raw.cl_color"
/>
<span class="pl-2">
{{ item.title }}
</span>
</template>
<template v-slot:item="{ item, props }">
<template v-slot:item="{ item }">
<v-list-item
:key="item.raw.id"
:key="item.title"
:value="item"
color="primary"
v-bind="props"
@click.stop="myCalendar = item.raw"
@click.stop="calendar = item"
>
<template v-slot:prepend>
<v-avatar class="cursor-pointer" size="8" :color="item.raw.cl_color" />
<v-avatar
class="cursor-pointer"
size="8"
:color="item.raw.cl_color"
/>
</template>
<!-- {{ item.title }} -->
{{ item.title }}
</v-list-item>
</template>
</v-autocomplete>
</v-col></v-row
>
<v-row no-gutters class="align-top">
<v-col class="text-body-2 text-text_grey pt-3" lg="2"> Дата и время </v-col>
<v-col class="text-body-2 text-text_grey pt-3" lg="2">
Дата и время
</v-col>
<v-col class="d-flex flex-column">
<v-row no-gutters class="gap">
<time-select
:rule="selectedRule.rule ? selectedRule.rule.freq : -1"
:rule="
returnPeriod != repeatRules[0].type
? returnPeriod.rule.freq
: -1
"
:chek="propsEvent.event.allday"
:order="[2, 1]"
:dateEvent="String(propsEvent.event.date_start)"
:limitation="String(propsEvent.event.date_end)"
@update:dateEvent="updateDateStart"
@adjustEndDate="handleAutoAdjustEnd"
@update:dateEvent="propsEvent.event.date_start = $event"
/>
<v-col class="order-3 flex-grow-0">
<v-icon icon="mdi-minus pt-4" color="grey-darken-1" />
</v-col>
<time-select
:rule="selectedRule.rule ? selectedRule.rule.freq : -1"
:rule="
returnPeriod != repeatRules[0].type
? returnPeriod.rule.freq
: -1
"
:chek="propsEvent.event.allday"
:order="[4, 5]"
:dateEvent="String(propsEvent.event.date_end)"
:limitation="String(propsEvent.event.date_start)"
@update:dateEvent="updateDateEnd"
@adjustEndDate="handleAutoAdjustEnd"
@update:dateEvent="propsEvent.event.date_end = $event"
/>
</v-row>
<v-row no-gutters>
@@ -111,22 +127,33 @@
/>
<v-col lg="7" class="pt-2 ml-5">
<v-autocomplete
v-model="selectedRule"
v-model="returnPeriod"
:items="repeatRules"
variant="outlined"
density="compact"
return-object
item-title="type"
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-col>
</v-row> </v-col
></v-row>
</v-col>
<v-row no-gutters class="align-top flex-grow-0">
<v-col class="text-body-2 text-text_grey pt-3 h-0" lg="2"> Напоминание </v-col>
<v-col class="text-body-2 text-text_grey pt-3 h-0" lg="2">
Напоминание
</v-col>
<v-col class="d-flex flex-column">
<v-row no-gutters class="gap flex-grow-0">
<reminder-event />
@@ -145,17 +172,12 @@
</v-row>
</v-col></v-row
>
<v-row
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>
<v-row no-gutters class="align-center">
<v-col class="text-body-2 text-text_grey pb-5" lg="2"> Файлы </v-col>
<uploading-file
v-model:new-files="newFiles"
:files="propsEvent.event.files"
@update:files="handleFilesUpdate"
@update:files="propsEvent.event.files = $event"
@postFiles="postFiles"
/>
</v-row>
@@ -176,18 +198,18 @@
</template>
<script>
import { computed, ref, watch } from 'vue';
import { axiosApiInstance } from '@/utils/axios-api';
import { useAccountStore } from '@/store/AccountStore';
import DialogCreate from '@/components/calendar_of_events/UI_calendar/dialogCreate.vue';
import calendarCreateSelect from '@/components/calendar_of_events/calendar-create-select.vue';
import TimeSelect from '@/components/calendar_of_events/UI_calendar/timeSelect.vue';
import UploadingFile from '@/components/UI/defaultportal/uploading-file.vue';
import ReminderEvent from '@/components/calendar_of_events/UI_calendar/reminderEvent.vue';
import PeriodEvents from '@/components/calendar_of_events/UI_calendar/periodEvents.vue';
import { useAlertStore } from '@/store/UseAlertStore';
import { RRule } from 'rrule';
import { useRecurrence } from '@/components/calendar_of_events/composables/useReccurrence';
import { computed, ref } from "vue";
import { axiosApiInstance } from "@/utils/axios-api";
import DialogCreate from "@/components/calendar_of_events/UI_calendar/dialogCreate.vue";
import calendarCreateSelect from "@/components/calendar_of_events/calendar-create-select.vue";
import { formatComa } from "@/utils/universal_functions";
import TimeSelect from "@/components/calendar_of_events/UI_calendar/timeSelect.vue";
import { useAccountStore } from "@/store/AccountStore";
import UploadingFile from "@/components/UI/defaultportal/uploading-file.vue";
import ReminderEvent from "@/components/calendar_of_events/UI_calendar/reminderEvent.vue";
import PeriodEvents from "@/components/calendar_of_events/UI_calendar/periodEvents.vue";
import { useAlertStore } from "@/store/UseAlertStore";
import { RRule } from "rrule";
export default {
components: {
@@ -204,285 +226,227 @@ export default {
type: Object,
default: () => {},
},
myCalendars: {
type: Array,
default: () => [],
},
},
setup(props, { emit }) {
const accountStore = useAccountStore();
const createDialog = ref(null);
const { parseRecurrenceOptions, isRecurringEvent } = useRecurrence();
const propsEvent = computed({
get: () => {
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 = [
{ type: 'Не повторять', rule: null, id: 1 },
{
type: 'Каждый день',
rule: { freq: RRule.DAILY },
id: 2,
},
{
type: 'Каждую неделю',
rule: { freq: RRule.WEEKLY },
// По умолчанию - в тот же день недели, что и начальная дата
getRule: (startDate) => {
const day = new Date(startDate).getDay();
// Преобразуем день недели в формат RRule (0 — понедельник)
const byweekday = [day === 0 ? RRule.SU : day - 1];
return { freq: RRule.WEEKLY, byweekday };
},
id: 3,
},
{
type: 'Каждый месяц',
rule: { freq: RRule.MONTHLY },
// По умолчанию - в тот же день месяца
getRule: (startDate) => ({
freq: RRule.MONTHLY,
bymonthday: [new Date(startDate).getDate()],
}),
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,
},
{ type: "Не повторять", rule: {}, id: 1 },
{ type: "Каждый день", rule: { freq: 3 }, id: 2 },
{ type: "Каждую неделю", rule: { freq: 2 }, id: 3 },
{ type: "Каждый месяц", rule: { freq: 1 }, id: 4 },
{ type: "Каждый год", rule: { freq: 0 }, id: 5 },
];
const selectedRule = ref(repeatRules[0]);
// Инициализация при редактировании
const initializeRule = () => {
if (!propsEvent.value.event.period) {
selectedRule.value = repeatRules[0]; // "Не повторять"
return;
}
try {
// Используем isRecurringEvent для проверки
if (isRecurringEvent(propsEvent.value.event)) {
// Парсим period с использованием parseRecurrenceOptions
const rruleOptions = parseRecurrenceOptions(
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];
const returnPeriod = computed({
get() {
let select = "";
if (propsEvent.value.event.period != null) {
let objRule = JSON.parse(propsEvent.value.event.period);
if (objRule != null) {
drawingRule(objRule.origOptions);
repeatRules.findIndex(
(e) => e.rule.freq == objRule.origOptions.freq
);
select =
repeatRules[
repeatRules.findIndex(
(e) => e.rule.freq == objRule.origOptions.freq
)
];
}
} else {
selectedRule.value = repeatRules[0];
select = repeatRules[0].type;
}
} catch (error) {
console.error('Error parsing period:', error, 'Raw period:', propsEvent.value.event.period);
selectedRule.value = repeatRules[0];
calendarNewOrOld();
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 titleCard = computed(() => {
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 req = (val) => {
return !!val || "Поле обязательно";
};
// Инициализируем когда все готово
watch(
[() => safeCalendars.value.length, () => propsEvent.value],
() => {
initializeCalendar();
},
{ immediate: true },
);
// Дополнительная защита - вотчер только на смену самого календаря
watch(eventCalendar, (newCalendar) => {
if (newCalendar && newCalendar.id !== myCalendar.value?.id) {
myCalendar.value = newCalendar;
}
});
const rules = {
name: [(val) => req(val)],
};
const staff = ref([]);
axiosApiInstance.get('api/calendar_of_events/get_employees/').then((res) => {
staff.value = res.data.filter((e) => e.employees.length > 0);
});
axiosApiInstance
// const newStaff = computed({
// get() {
// let ns = [];
.get("api/calendar_of_events/get_employees/")
.then((res) => {
staff.value = res.data.filter((e) => e.employees.length > 0);
});
// let indCal = safeCalendars.value.findIndex((e) => e.id == myCalendar.id);
const accountStore = useAccountStore();
// staff.value.forEach((e) => {
// 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;
// }
const newStaff = computed({
get() {
let ns = [];
// return propsEvent.value.mycalendars[indCal].participant.some(
// (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),
let indCal = propsEvent.value.mycalendars.findIndex(
(e) => e.id == calendar.value[0].id
);
if (!currentCalendar?.participant) return [];
staff.value.forEach((e) => {
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;
}
const calendarParticipantIds = new Set(currentCalendar.participant.map((p) => p.id));
const eventParticipantIds = new Set(propsEvent.value.event.participant || []);
return propsEvent.value.mycalendars[indCal].participant.some(
(part) => part.id === n.id
);
});
return staff.value
.map((department) => ({
...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);
}
if (emp.employees.length > 0) ns.push(emp);
});
return ns;
},
});
const delEvent = (idev) => {
axiosApiInstance.delete(`api/calendar_of_events/my_events/?delid=${idev}`).then((result) => {
feedalert.alert = true;
feedalert.text = result.data.mess;
feedalert.ico = 'mdi-check';
feedalert.color = 'orange-accent-1';
emit('getCalendar');
});
emit('closeDialog');
axiosApiInstance
.delete(`api/calendar_of_events/my_events/?delid=${idev}`)
.then((result) => {
feedalert.alert = true;
feedalert.text = result.data.mess;
feedalert.ico = "mdi-check";
feedalert.color = "orange-accent-1";
emit("getCalendar");
});
emit("closeDialog");
};
const newFiles = ref([]);
const handleFilesUpdate = (updatedExistingFiles) => {
// Сохраняем новые файлы во временную переменную
const currentNewFiles = [...newFiles.value];
// Обновляем существующие файлы
propsEvent.value.event.files = updatedExistingFiles;
// Восстанавливаем новые файлы
newFiles.value = currentNewFiles;
const files = ref([]);
const postFiles = (f) => {
files.value = f;
};
const postFiles = (updatedFiles) => {
newFiles.value = updatedFiles;
const calendar = computed({
get() {
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) => {
idPart.staff.forEach((e) => {
if (e.selected == true && !propsEvent.value.event.participant.includes(e.id)) {
if (
e.selected == true &&
!propsEvent.value.event.participant.includes(e.id)
) {
propsEvent.value.event.participant.push(e.id);
} else {
let ind = propsEvent.value.event.participant.findIndex((l) => l == e.id);
let ind = propsEvent.value.event.participant.findIndex(
(l) => l == e.id
);
if (ind != -1) {
propsEvent.value.event.participant.splice(ind, 1);
@@ -493,125 +457,167 @@ export default {
const cbSelect = (item, arr) => {
item.forEach((e) => {
if (!('employees' in e)) {
if (!("employees" in e)) {
if (!propsEvent.value.event.participant.includes(e.id)) {
propsEvent.value.event.participant.push(e.id);
}
}
if ('employees' in e) {
if ("employees" in e) {
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 postData = (validate) => {
if (validate) {
updatePeriodRule(selectedRule.value);
propsEvent.value.event.calendar = myCalendar.value.id;
let postEvent = new FormData();
postEvent.append(
'event',
JSON.stringify({ ...propsEvent.value.event, files: propsEvent.value.event.files }),
"event",
JSON.stringify({ ...propsEvent.value.event })
);
console.log([propsEvent.value]);
if (propsEvent.value.event.files !== null) {
newFiles.value.forEach((e) => postEvent.append('files', e));
files.value.forEach((e) => postEvent.append("files", e));
}
axiosApiInstance.post('api/calendar_of_events/my_events/', postEvent).then((result) => {
feedalert.alert = true;
feedalert.text = result.data.mess;
feedalert.ico = 'mdi-check';
feedalert.color = 'green-darken-4';
emit('getCalendar');
emit('closeDialog');
});
axiosApiInstance
.post("api/calendar_of_events/my_events/", postEvent)
.then((result) => {
feedalert.alert = true;
feedalert.text = result.data.mess;
feedalert.ico = "mdi-check";
feedalert.color = "green-darken-4";
emit("getCalendar");
emit("closeDialog");
});
}
};
const handleAutoAdjustEnd = (newEndDate) => {
propsEvent.value.event.date_end = newEndDate;
};
const updateDateStart = (newDate) => {
// Нормализуем к ISO строке
const normalizedDate = new Date(newDate).toISOString();
propsEvent.value.event.date_start = normalizedDate;
// При изменении даты начала - обновляем правило повторений
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();
const getWeekNumbersBetweenDates = () => {
const start = new Date(propsEvent.value.event.date_start);
const end = new Date(propsEvent.value.event.date_end);
let s = start.getDay();
let e = end.getDay();
const weekNumbers = [];
if (start.getDay() > end.getDay()) {
e = 6;
for (let x = s; x <= e; x++) {
weekNumbers.push(x);
}
}
if (start.getDay() != end.getDay() && start.getDay() > end.getDay()) {
s = 0;
for (let x = s; x <= end.getDay(); x++) {
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 {
menudate,
titleCard,
newEvent,
propsEvent,
dateEvent,
calendar,
staff,
newStaff,
returnIdParticant,
@@ -619,23 +625,14 @@ export default {
postData,
rules,
delEvent,
myCalendar,
safeCalendars,
isCalendarsReady,
isNewEvent,
repeatRules,
updatePeriodRule,
selectedRule,
updateDateEnd,
updateDateStart,
initializeRule,
returnPeriod,
periodDisplayRule,
what,
createDialog,
handleAutoAdjustEnd,
newFiles,
handleFilesUpdate,
initializeCalendar,
getMonthBetweenDates,
};
},
};
@@ -0,0 +1,38 @@
<template>
<v-app-bar density="compact" color="teal-darken-4" elevation="1">
<template v-slot:image>
<v-img gradient="to top right, rgba(19,84,122,.8), rgba(128,208,199,.8)" />
</template>
<v-icon :icon="props.showSideBar ? 'mdi-chevron-right' : 'mdi-chevron-left'" rounded="0" @click="$emit('showSide')" class="pl-7" size="small"/>
<v-col cols="3" class="d-flex align-center ml-3 cursor-pointer" @click="router.push('/')">
<v-img :src="props.logo" max-height="45" max-width="45"/>
<v-app-bar-title class="pl-2 text-h6 font-weight-bold">Портал МИ ФНС России по ЦОД № 2</v-app-bar-title>
</v-col>
<v-col class="d-flex justify-end align-center">
<vcard-user :author="accountStore.user"/>
<AppNavigation @showUser="showUser"/>
</v-col>
</v-app-bar>
</template>
<script setup>
import router from '@/router';
import { useAccountStore } from '@/store/AccountStore';
import vcardUser from '@/components/UI/fiousercard/vcardUser.vue';
import AppNavigation from '@/components/UI/AppHeader/AppNavigation.vue';
const accountStore = useAccountStore()
const props = defineProps({
showSideBar: Boolean,
logo: String,
})
const emit = defineEmits(['showSide', 'showUser'])
const showUser = (val) => {
emit('showUser', val)
}
</script>
@@ -0,0 +1,86 @@
<template>
<v-navigation-drawer :rail="props.isRail" permanent class="text-body-2">
<div class="d-flex flex-column h-100">
<v-list v-for="(nav, index) in props.asideNavigation" :key="index" density="compact" nav>
<v-list-item v-if="!('submenu' in nav)" :prepend-icon="nav.ico" @click="router.push(`${nav.path}`)">
{{ nav.name }}
<v-tooltip v-if="props.isRail" location="top" activator="parent">
{{ nav.name }}
</v-tooltip>
</v-list-item>
<v-list-group v-else :fluid="props.isRail ? true : false">
<template v-slot:activator="{ props: groupProps }">
<v-list-item v-bind="groupProps" :prepend-icon="nav.ico">
{{ nav.name }}
<v-tooltip v-if="props.isRail" location="top" activator="parent">
{{ nav.name }}
</v-tooltip>
</v-list-item>
</template>
<v-list-item v-for="(sub, index) in nav.submenu" :key="index" @click="router.push(`${sub.path}`)">
{{ props.isRail ? getAbbreviation(sub.name) : sub.name }}
<v-tooltip v-if="props.isRail" location="top" activator="parent">
{{ sub.name }}
</v-tooltip>
</v-list-item>
</v-list-group>
</v-list>
<v-list class="flex-grow-1" nav>
<v-list-item v-for="links in store.portallinks" :key="links.id" :href="links.link" target="_blank"
:prepend-icon="links.imagecode" link>
{{ links.name }}
<v-tooltip v-if="props.isRail" location="top" activator="parent">
{{ links.name }}
</v-tooltip>
</v-list-item>
</v-list>
<v-list v-if="accountUser.user.is_staff" class="text-blue-grey-lighten-1" nav>
<v-list-item prepend-icon="mdi-wrench" title="Панель администратора" :href="baseURL + 'admin'" target="_blank" link>
<v-tooltip v-if="props.isRail" location="top" activator="parent">
Панель администратора
</v-tooltip>
</v-list-item>
</v-list>
<page-counter :rail="props.isRail"/>
</div>
</v-navigation-drawer>
<v-navigation-drawer v-model="props.showUser" rail location="right">
<online-users />
</v-navigation-drawer>
</template>
<script setup>
import router from "@/router";
import { useMainmenuStore } from "@/store/MainmenuStore";
import { useAccountStore } from "@/store/AccountStore";
import { baseURL } from '@/utils/axios-api';
import pageCounter from "@/components/UI/defaultportal/page-counter.vue";
import onlineUsers from "@/components/UI/fiousercard/onlineUsers.vue";
const store = useMainmenuStore()
const accountUser = useAccountStore()
store.loadlinks()
defineEmits(['showUser'])
const props = defineProps({
isRail: Boolean,
showUser: Boolean,
asideNavigation: {
type: Array,
default: () => [{
name: "",
ico: "",
path: "",
submenu: [{
name: "",
path: "",
}],
}]
}
})
const getAbbreviation = (text) => {
return text.substring(0, 2).toUpperCase();
};
</script>
+23 -283
View File
@@ -1,235 +1,42 @@
<template>
<v-app>
<v-app-bar :elevation="accountStore.cod2user ? 2 : 0" density="compact" color="app_bar" class="pl-4">
<v-icon v-if="accountStore.cod2user" class="px-3" size="20" color="black_and_white"
:icon="rail ? 'mdi-chevron-right' : 'mdi-chevron-left'" @click="rail = !rail" />
<v-card v-if="accountStore.cod2user" class="bg-transparent py" color="black_and_white" density="compact"
:prepend-avatar="imageSrc" title="Портал МИ ФНС России по ЦОД № 2" variant="text" :to="'/'" />
<template v-slot:image>
<v-img class="bggrad" />
</template>
<template v-slot:append>
<template v-if="accountStore.cod2user">
<vcard-user :author="accountStore.user" />
<v-tooltip location="bottom">
<template v-slot:activator="{ props }">
<v-btn color="black_and_white" v-bind="props" dark to="/faq" icon="mdi-comment-question-outline" />
</template>
<span>F.A.Q.</span>
</v-tooltip>
<v-dialog v-model="LikeDialog" persistent width="800">
<template v-slot:activator="{ props }">
<v-btn color="black_and_white" v-bind="props" dark icon="mdi-thumb-up-outline">
<v-icon></v-icon>
<v-tooltip activator="parent" location="bottom">Обратная связь</v-tooltip>
</v-btn>
</template>
<Card-like :LikeDialog="LikeDialog" @menusClose="closeinfo()" />
</v-dialog>
<v-tooltip location="bottom">
<template v-slot:activator="{ props }">
<v-btn icon @click="toggleTheme">
<v-icon v-bind="props" class="mr-1" :color="theme.global.current.value.dark ? 'yellow' : 'lampa'">
mdi-lightbulb-outline
</v-icon>
</v-btn>
</template>
<span> Сменить тему</span>
</v-tooltip>
<v-card v-show="message" class="" width="50">{{ name }}</v-card>
<v-tooltip location="bottom">
<template v-slot:activator="{ props }">
<v-btn color="black_and_white" icon="mdi-account-multiple-outline" @click="drawer_right = !drawer_right"
v-bind="props" />
</template>
<span>
{{
drawer_right == true
? "Скрыть пользователей"
: "Показать пользователей"
}}
</span>
</v-tooltip>
<v-tooltip location="bottom">
<template v-slot:activator="{ props }">
<v-btn color="black_and_white" icon="mdi-logout" @click="accountStore.logout" v-bind="props" />
</template>
<span> Выход </span>
</v-tooltip>
</template>
<template v-else>
<v-row justify="center">
<Auth-form @challengealert="alert = true" />
</v-row>
</template>
</template>
</v-app-bar>
<v-navigation-drawer v-if="accountStore.cod2user" :width="245" :rail="rail" permanent v-model="drawer">
<v-row class="my-0 h-100">
<v-col class="flex-column d-flex">
<v-row><v-col>
<v-list nav density="compact">
<template v-for="(x, key) in navigations" :key="key">
<!-- v-if="!('submenu' in x) || (x.path== '/portal' && accountStore.user.is_staff)" -->
<v-list-item v-if="(x.path == '/portal'? accountStore.user.is_superuser : true) && !('submenu' in x)
" :key="x.key" :title="x.name" :value="x.name" :href="x.link" :disabled="x.path == ''" :to="x.path"
:target="x.link ? '_blank' : ''"
color="navigation"
>
<template v-slot:prepend>
<v-icon :icon="x.ico" />
<v-tooltip v-if="rail" activator="parent" location="top">
{{ x.name }}
</v-tooltip>
</template>
</v-list-item>
<v-list-group v-if="x.path != '/portal' && 'submenu' in x" :class="rail ? 'railmenu' : ''" :key="key"
:value="x.name">
<template v-slot:activator="{ props }">
<v-list-item v-bind="props" :title="x.name" :prepend-icon="x.ico" color="navigation">
<v-tooltip v-if="rail" activator="parent" location="top">
{{ x.name }}
</v-tooltip>
</v-list-item>
</template>
<v-list-item v-for="(child, k) in x.submenu" color="navigation" :href="child.link" :key="k"
:value="child.name" :title="!rail ? child.name : menuTruncated(child.name)" :to="child.path"
:target="child.link ? '_blank' : ''">
<v-tooltip v-if="rail" activator="parent" location="top">
{{ child.name }}
</v-tooltip>
</v-list-item>
</v-list-group>
</template>
</v-list>
<v-list nav density="compact">
<v-list-item v-for="x of mainmenuStore.portallinks" :key="x.name" :title="x.name" :value="x.name"
:href="x.link" color="app_bar" :target="x.link ? '_blank' : ''">
<template v-slot:prepend>
<v-icon :icon="x.imagecode" />
<v-tooltip v-if="rail" activator="parent" location="top">
{{ x.name }}
</v-tooltip>
</template>
</v-list-item>
</v-list>
</v-col>
</v-row>
<v-row class="flex-grow-0" v-if="accountStore.user.is_staff">
<v-col>
<AdminMenu :rail="rail" />
</v-col>
</v-row>
<v-row no-gutters class="flex-grow-0">
<v-col>
<page-counter :rail="rail" />
</v-col>
</v-row>
</v-col>
</v-row>
</v-navigation-drawer>
<v-main v-if="accountStore.cod2user" class="d-flex bg-main_theme">
<AppHeader @show-side="rail = !rail" :logo="imageSrc" @showUser="usersOnline" />
<AsideNav :asideNavigation="navigations" :isRail="rail" :showUser="showUser" />
<v-main class="d-flex">
<router-view />
<alert-default />
</v-main>
<v-main v-else class="d-flex align-center text-h3 bg-teal-lighten-2">
<v-card class="h-100 w-100 d-flex justify-center rounded-0 flex-column" :image="`${burl}${scrimg}`">
<v-card-text
class="justify-center bgCard h-100 ma-3 d-flex flex-column"
style="background: rgba(255, 255, 255, 0.3) !important; background-color: rgba(255, 255, 255, 0.3) !important;"
>
<v-row
class="bgText flex-grow-0"
style="background: rgba(255, 255, 255, 0.5) !important; background-color: rgba(255, 255, 255, 0.5) !important;"
>
<v-col class="text-center textcolor font-weight-black text-h3 pb-0">
Добро пожаловать на портал МИ ФНС России по ЦОД № 2
</v-col>
</v-row>
<v-row
class="bgText flex-grow-0"
style="background: rgba(255, 255, 255, 0.5) !important; background-color: rgba(255, 255, 255, 0.5) !important;"
>
<v-col class="text-subtitle-1 text-center textcolor pt-0">
Авторизуйтесь для получения доступа к контенту портала
</v-col>
</v-row>
</v-card-text>
</v-card>
<alert-default />
</v-main>
<v-navigation-drawer v-if="accountStore.cod2user" v-model="drawer_right" rail permanent location="right"
@click="rail = false">
<Online-users />
</v-navigation-drawer>
</v-app>
</template>
<script>
import { ref, computed } from "vue";
import uf from "@/utils/universal_functions";
import { useAccountStore } from "@/store/AccountStore";
import { useMainmenuStore } from "@/store/MainmenuStore";
import { useTheme } from "vuetify";
import AuthForm from "@/components/UI/Auth-form.vue";
import OnlineUsers from "@/components/UI/fiousercard/onlineUsers.vue";
import CardLike from "@/components/cardLike.vue";
import { axiosApiInstance, clearAxios } from "@/utils/axios-api";
import { baseURL } from "@/utils/axios-api";
import VcardUser from "@/components/UI/fiousercard/vcardUser.vue";
import PageCounter from "@/components/UI/defaultportal/page-counter.vue";
import AdminMenu from "@/layouts/default/AdminMenu.vue";
import { useDisplay } from "vuetify";
import AppHeader from "./AppHeader.vue";
import AsideNav from "./AsideNav.vue";
import alertDefault from "./alertDefault.vue"
export default {
components: {
AuthForm,
OnlineUsers,
CardLike,
VcardUser,
PageCounter,
AdminMenu,
AppHeader,
AsideNav,
alertDefault,
},
mixins: [uf],
emits: ['showUser'],
setup() {
const { name } = useDisplay();
const theme = useTheme();
const mainmenuStore = useMainmenuStore();
const accountStore = useAccountStore();
const drawer = ref(true);
const drawer_right = ref(true);
const LikeDialog = ref(false);
const showUser = ref(true);
const rail = ref(false);
const showTooltip = ref(false);
const alert = ref(false);
const burl = baseURL.slice(0, -1);
const scrimg = ref([]);
const usersOnline = (val) => {
showUser.value = val;
}
const message = computed({
get: () => {
return process.env.NODE_ENV == "development" ? true : false;
@@ -247,20 +54,6 @@ export default {
screenimg();
const menuTruncated = (menus) => {
return menus.slice(0, 2).toUpperCase();
};
const toggleTheme = () => {
theme.global.name.value = theme.global.current.value.dark
? "light"
: "dark";
};
mainmenuStore.loadlinks();
const navigations = ref([
{
name: "Новости",
@@ -283,7 +76,7 @@ export default {
submenu: [
{
name: "Справочник",
link: "http://10.252.44.33/accounting6/members.php",
path: "/employee_directory",
},
// {
@@ -304,11 +97,11 @@ export default {
// ],
// },
{
name: "Календарь",
ico: "mdi-calendar",
path: "/ical",
},
// {
// name: "Календарь",
// ico: "mdi-calendar",
// path: "/ical",
// },
{
name: "Голосование",
ico: "mdi-vote",
@@ -339,11 +132,6 @@ export default {
return new URL(`@/assets/FNS-logo-xs.png`, import.meta.url).href;
});
const closeinfo = () => {
LikeDialog.value = false;
// feedalert.value=true
};
const getSafetyChapter = () => {
axiosApiInstance.get("api/safety/gettypes/").then((response) => {
response.data.forEach((item) => {
@@ -367,71 +155,23 @@ export default {
// getSafetyChapter();
return {
theme,
mainmenuStore,
accountStore,
drawer,
drawer_right,
toggleTheme,
showUser,
navigations,
imageSrc,
LikeDialog,
scrimg,
rail,
showTooltip,
menuTruncated,
alert,
burl,
name,
closeinfo,
baseURL,
usersOnline,
message,
};
},
};
</script>
<style lang="scss">
.bgCard {
background: rgba(255, 255, 255, 0.3) !important;
background-color: rgba(255, 255, 255, 0.3) !important;
}
.v-card.bgCard {
background: rgba(255, 255, 255, 0.3) !important;
background-color: rgba(255, 255, 255, 0.3) !important;
}
.bgText {
background: rgba(255, 255, 255, 0.5) !important;
background-color: rgba(255, 255, 255, 0.5) !important;
}
.textcolor {
color: #2f535e !important;
}
.mystat {
position: fixed;
right: 10px;
bottom: 10px;
z-index: 1005;
}
.btnNav .v-navigation-drawer__content {
display: flex;
align-items: center;
}
.railmenu .v-list-group__items .v-list-item {
padding-inline-start: 11px !important;
}
.textcolor {
color: #2f535e;
}
#tr-popup {
display: none;
}
</style>
</style>
-11
View File
@@ -1,10 +1,3 @@
/**
* main.js
*
* Bootstraps Vuetify and other plugins then mounts the App`
*/
// Components
import App from './App.vue'
// Composables
@@ -27,10 +20,6 @@ components.forEach((component) => {
app.component('vue3-autocounter', Vue3Autocounter)
// Vue.use(VueScrollTo)
registerPlugins(app)
app.mount('#app')
+27
View File
@@ -0,0 +1,27 @@
<template>
<v-app>
<v-app-bar density="compact" color="teal-darken-4" elevation="1">
<template v-slot:image>
<v-img gradient="to top right, rgba(19,84,122,.8), rgba(128,208,199,.8)" />
</template>
<v-col class="d-flex justify-end">
<AuthForm @challengealert="alarm = true" />
</v-col>
</v-app-bar>
<v-card class="h-100 mt-11 pa-5 d-flex align-center text-center" variant="tonal" image="/src/assets/squirrel.jpg">
<v-card class="w-100 h-100 d-flex align-center bg-grey-lighten-1 opacity-70">
<!-- style="background-color: rgba(255, 255, 255, .5);" -->
<v-container class="opacity-100 mx-2 bg-grey-lighten-5" fluid>
<!-- style="background-color: #ffffff38;" -->
<v-col class=" font-weight-black text-text_card_auth text-h3">Добро пожаловать на портал МИ ФНС России по ЦОД № 2</v-col>
<v-col class="text-subtitle-1">Авторизуйтесь для получения доступа к контенту портала</v-col>
</v-container>
</v-card>
</v-card>
</v-app>
</template>
<script setup>
import AuthForm from "@/components/UI/Auth-form.vue"
</script>
+10 -27
View File
@@ -5,32 +5,15 @@
*/
// Plugins
import { loadFonts } from './webfontloader';
import vuetify from './vuetify';
import pinia from '../store';
import router from '../router';
import { loadFonts } from './webfontloader'
import vuetify from './vuetify'
import pinia from '../store'
import router from '../router'
// FullCalendar
import FullCalendar from '@fullcalendar/vue3';
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';
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,
};
export function registerPlugins (app) {
loadFonts()
app
.use(vuetify)
.use(pinia)
.use(router)
}
+9 -7
View File
@@ -7,16 +7,19 @@ import { ru } from 'vuetify/locale'
export default createVuetify({
locale: {
messages: { ru, },
},
components: {
VCalendar,
},
theme: {
defaultTheme: 'light',
options: {
customProperties: true
},
themes: {
light: {
colors: {
@@ -43,12 +46,13 @@ export default createVuetify({
insert_table: '#FAFAFA',
btn_text: '#00897B', // фигма, текст кнопки с иконкой
select_list: '#E0EAE8',
btn_gray: '#E0E0E0'
btn_gray: '#E0E0E0',
text_card_auth: '#2f535e',
},
},
dark: {
colors: {
lampa: '#121212',
lampa: '#FFB300',
primary: '#1E88E5',
secondary: '#64B5F6',
main_theme: "#121212",
@@ -74,14 +78,12 @@ export default createVuetify({
btn_gray: '#2C2C2C',
surface: '#1E1E1E',
background: '#121212',
text_card_auth: '#2f535e',
'on-background': '#FFFFFF',
'on-surface': '#FFFFFF',
'card-background': '#1E1E1E'
},
},
options: {
customProperties: true
},
},
},
})
+16 -18
View File
@@ -1,15 +1,18 @@
// Composables
import { createRouter, createWebHistory } from "vue-router";
import { useAccountStore } from "@/store/AccountStore";
const routes = [
{
path: "/auth",
component: () => import('@/pages/AuthorizePage.vue'),
name: "Auth",
},
{
path: "/",
component: () => import("@/layouts/default/DefaultPortal.vue"),
meta: {
title: "Вход",
requiresAuth: true,
},
children: [
{
path: "/",
@@ -192,7 +195,13 @@ const routes = [
name: 'Secret Page',
component: () =>
import("@/views/secret/SecretPage.vue")
}
},
{
path: '/employee_directory',
name: 'EmployeeDirectory',
component: () =>
import("@/views/employee_directory/EmployeeDirectoryMain.vue")
},
],
},
];
@@ -202,23 +211,12 @@ const router = createRouter({
routes,
});
function isSuperuser() {
const accountStore = useAccountStore();
if (accountStore.user.is_superuser === false) {
return true;
} else {
return false;
}
}
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && isSuperuser()) {
const accountStore = useAccountStore();
if (to.meta.requiresAuth && !accountStore.cod2user) {
document.title = to.meta.title;
next("/");
next("/auth");
} else {
document.title = to.meta.title;
next();
}
});
+60 -44
View File
@@ -1,19 +1,25 @@
// Utilities
import { defineStore } from 'pinia';
import { ref, watch, computed } from 'vue';
import { clearAxios, spravURL } from '@/utils/axios-api';
import VueJwtDecode from 'vue-jwt-decode';
import { checkremote } from '@/utils/universal_functions';
import { useAppStore } from '@/store/app.js';
import { defineStore } from "pinia";
import { ref, watch, computed } from "vue";
import { clearAxios, spravURL } from "@/utils/axios-api";
import VueJwtDecode from "vue-jwt-decode";
import { checkremote } from "@/utils/universal_functions";
import { useAppStore } from "@/store/app.js";
import { useRouter } from "vue-router";
export const useAccountStore = defineStore('AccountStore', () => {
export const useAccountStore = defineStore("AccountStore", () => {
const AppStore = useAppStore();
const user = ref(getuserFromStorage());
const router = useRouter();
const settingsStorage = computed({
get() {
if (Object.keys(user.value).length == 0) {
getuserFromStorage();
if (Object.keys(user.value).length==0){
getuserFromStorage()
}
return JSON.parse(localStorage.getItem(user.value.is_idEmployee));
},
@@ -24,11 +30,12 @@ export const useAccountStore = defineStore('AccountStore', () => {
};
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 calendar = ref(get_setting('calendar'));
const calendar = ref(get_setting("calendar")
);
const setUser = (value) => {
value.photo = checkremote(`${spravURL}${value.login}.jpg`);
user.value = value;
@@ -37,57 +44,66 @@ export const useAccountStore = defineStore('AccountStore', () => {
//
// геттер бывший
// const getUser=computed(()=> uyser.value)
function getuserFromStorage() {
try {
let u = VueJwtDecode.decode(localStorage.getItem('refresh'));
u.user.photo = checkremote(`${spravURL}${u.user.login}.jpg`);
return u.user;
} catch {
return {};
}
function getuserFromStorage(){
try{
let u = VueJwtDecode.decode(localStorage.getItem("refresh"));
u.user.photo = checkremote(`${spravURL}${u.user.login}.jpg`);
return u.user;
}catch{
return {}}
}
const logging = async (anon) => {
AppStore.loading = true;
const result = await clearAxios.post('api/accounts/token/', anon);
localStorage.setItem('access', result.data.access);
localStorage.setItem('refresh', result.data.refresh);
user.value = getuserFromStorage();
const result = await clearAxios.post("api/accounts/token/", anon);
localStorage.setItem("access", result.data.access);
localStorage.setItem("refresh", result.data.refresh);
user.value=getuserFromStorage()
if (settingsStorage.value === null) {
settingsUp(defaultSettings);
settingsUp(defaultSettings)
}
console.log(user.value);
AppStore.loading = false;
};
const logout = () => {
user.value = {};
localStorage.removeItem('access');
localStorage.removeItem('refresh');
localStorage.removeItem("access");
localStorage.removeItem("refresh");
router.push('/auth')
};
watch(
user,
(newValue, oldValue) => {
cod2user.value = 'login' in newValue && newValue.login.startsWith('9966-') ? true : false;
cod2user.value =
"login" in newValue && newValue.login.startsWith("9966-")
? true
: false;
},
{ deep: true },
{ deep: true }
);
function settingsUp(newSet) {
localStorage.setItem(user.value.is_idEmployee, JSON.stringify(newSet));
function settingsUp(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 },
);
return { user, setUser, cod2user, logging, logout, calendar, getuserFromStorage };
watch(() => calendar.value, (newValue) => {
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 };
});
+1 -1
View File
@@ -1,5 +1,5 @@
import { defineStore } from 'pinia'
import {ref, watch} from 'vue'
import { ref } from 'vue'
import { clearAxios } from '@/utils/axios-api'
export const useMainmenuStore = defineStore('MainmenuStore', () => {
-274
View File
@@ -1,274 +0,0 @@
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)) {
where.push(what);
}
}
}
export function getfromserver(path, reactive) {
try {
@@ -63,7 +63,7 @@ export function checkremote(filecheck) {
export default str;
export function splitname(name) {
return name.familyname + " " + name.name[0] + "." + name.parentname[0] + ".";
}
@@ -71,7 +71,7 @@ export function pagecounter() {
// Функция записи посещения страницы сотрудникам.
// В случае, если в роуте присутствует ключ мета и в нем ико - тогда производится запись
const router = useRouter();
if('meta' in router.currentRoute.value && 'ico' in router.currentRoute.value.meta){
const accountStore = useAccountStore();
const appStore = useAppStore();
@@ -95,7 +95,7 @@ export function pagecounter() {
export function useICalReader(url) {
///
const events = ref([]);
const loadICalFile = async () => {
try {
const response = await fetch(url);
@@ -120,13 +120,13 @@ export function useICalReader(url) {
location: event.location,
}
})
return {
type: "calendar",
title: name,
calendar: calendarEvents,
}
// const vevents = comp.getAllSubcomponents('vevent')
// const eventsData = vevents.map(vevent => ({
// vevent: vevent,
@@ -173,4 +173,4 @@ export function useICalReader(url) {
export function declOfNum(value, titles) {
const cases = [2, 0, 1, 1, 1, 2];
return titles[(value % 100 > 4 && value % 100 < 20) ? 2 : cases[(value % 10 < 5) ? value % 10 : 5]];
}
}
+8 -24
View File
@@ -7,15 +7,11 @@
<Carousel-list />
</v-col>
</v-row>
<v-row class="flex-grow-0" style="min-height: 300px">
<v-col class="pa-1 d-flex align-stretch">
<HomeCalendarWidget />
<v-row style="height: 250px">
<v-col class="d-flex flex-column flex-grow-0 pa-1">
<!-- <event-calendar/> -->
</v-col>
</v-row>
<!-- <v-row style="height: 250px">
<HomeCalendarWidget />
</v-row> -->
</v-col>
<v-col class="d-flex flex-column" lg="5" md="12" cols="12">
<v-row>
@@ -51,12 +47,7 @@
<v-btn-toggle v-model="toggle" divided variant="outlined" color="teal-darken-4">
<v-tooltip :text="x.pages__page" location="top">
<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>
</v-tooltip>
</v-btn-toggle>
@@ -83,15 +74,14 @@ import NewsHome from '@/components/news-home.vue';
import DigitalLetna from '@/components/digital-letna.vue';
import { axiosApiInstance } from '@/utils/axios-api';
import HomeCalendarWidget from '@/components/calendar_of_events/UI_calendar/HomeCalendarWidget.vue';
import { useCalendarStore } from '@/store/calendarStore';
export default {
components: {
CarouselList,
DigitalLetna,
NewsHome,
HomeCalendarWidget,
},
setup() {
@@ -100,17 +90,11 @@ export default {
const toggle = ref(null);
const accountStore = useAccountStore();
const calendarStore = useCalendarStore();
pagecounter();
const fetchMyCalendars = () => {
calendarStore.loadCalendars();
};
onMounted(() => {
favoritLinks();
fetchMyCalendars();
});
const favoritLinks = () => {
@@ -124,14 +108,14 @@ export default {
appStore,
favoritLinks,
favorit,
fetchMyCalendars,
toggle,
};
},
};
</script>
<style lang="scss" scoped>
<style lang="scss">
.v-picker-title,
.v-picker__header,
.v-picker__actions {
+1 -8
View File
@@ -1,14 +1,7 @@
<template>
<v-row class="justify-center ma-0 ">
<v-row class="justify-center ma-0 h-100">
<v-col class="flex-column d-flex">
<news-crossroad />
</v-col>
</v-row>
</template>
File renamed without changes.
@@ -0,0 +1,42 @@
<template>
<v-container fluid>
<HeaderEmployeeDirectory :department="department" v-model:selectedDep="selectedDep" v-model:isWork="isWork" v-model:search="search"/>
<CardEmployeeDirection :selectedDep="selectedDep" :isWork="isWork" :search="search"/>
</v-container>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { axiosApiInstance } from '@/utils/axios-api'
import HeaderEmployeeDirectory from '../../components/EmployeeDirectory/HeaderEmployeeDirectory.vue';
import CardEmployeeDirection from '../../components/EmployeeDirectory/CardEmployeeDirection.vue';
const department = ref([])
const selectedDep = ref({
id: 0,
persons: []
})
const isWork = ref(0)
const search = ref('')
async function getDepartment() {
try {
const response = await axiosApiInstance.get('api/userauth/getdepartments')
response.data[0].persons= response.data.reduce((acc,elm)=>{
acc.push(...elm.persons)
return acc},[]
)
department.value = response.data
} catch (error) {
console.error('Ошибка запроса получения отделов:', error);
throw error;
}
}
onMounted(async () => {
await getDepartment();
selectedDep.value = department.value[0]
})
</script>