174 Commits

Author SHA1 Message Date
a315ce4f33 feat(documents): Integrate client-side processing into upload form
- Updated DocumentUploadForm to use processDocument utility
- Added real-time progress tracking with visual feedback
- Display extracted text in editable textarea
- Support compressed file upload
- Added extracted_text field to API client and backend serializer
- Auto-process PDFs, DOCX, and images on file selection
2026-02-28 09:36:17 +03:00
ab07a6ff9a feat(documents): Phase 1 - Backend Foundation Complete
- Добавлены расширенные модели для Mayan-level DMS:
  * DocumentType - типы документов с JSON schema
  * DocumentTag - теги для категоризации
  * Cabinet - виртуальные коллекции
  * DocumentMetadata - динамические key-value метаданные
  * DocumentAuditLog - полный аудит действий

- Расширена модель Document:
  * extracted_text - для полнотекстового поиска
  * document_type - FK к типу
  * modified_by, modified_at - audit trail

- Интегрирован django-watson для full-text search:
  * Регистрация с extracted_text
  * Кастомный adapter с URL
  * Обновлен индекс (22 документа)

- API Serializers:
  * DocumentTypeSerializer
  * DocumentTagSerializer
  * CabinetSerializer
  * FolderSerializer расширен
  * DocumentReadSerializer обновлен с новыми полями

Следующий этап: Phase 2 Frontend Foundation
2026-02-28 09:26:23 +03:00
abed82ed6c feat(documents): Добавлен django-fsm для workflow управления
Установлен и настроен django-fsm==3.0.1 для управления жизненным циклом документов.

Изменения в модели (documents/models.py):
- Добавлено FSM поле 'status' с 6 состояниями:
  * draft (черновик) - по умолчанию
  * in_review (на рассмотрении)
  * approved (одобрен)
  * published (опубликован)
  * archived (архивирован)
  * rejected (отклонен)

- Созданы transitions (переходы между состояниями):
  * submit_for_review(): draft → in_review
  * approve(): in_review → approved
  * reject(): in_review → rejected
  * publish(): approved → published (с отправкой уведомлений)
  * return_to_draft(): draft/in_review → draft
  * archive(): published → archived
  * unarchive(): archived → published

Изменения в админке (documents/admin.py):
- Добавлен status_badge() с цветовыми индикаторами статусов
- Добавлен available_transitions() - список доступных переходов
- Поле status добавлено в list_display и fieldsets
- Фильтрация по статусам в list_filter

Изменения в API (api/v1/documents/):
- Добавлены поля status и status_code в DocumentReadSerializer
- Созданы actions для всех FSM transitions:
  * POST /api/v1/documents/{id}/submit-for-review/
  * POST /api/v1/documents/{id}/approve/
  * POST /api/v1/documents/{id}/reject/
  * POST /api/v1/documents/{id}/publish/
  * POST /api/v1/documents/{id}/return-to-draft/
  * POST /api/v1/documents/{id}/archive/
  * POST /api/v1/documents/{id}/unarchive/

Миграция:
- Создана 0006_add_fsm_status.py
- Применена успешно
- Все 16 юнит-тестов проходят

Зависимости:
- Добавлен django-fsm==3.0.1 в requirements.txt
2026-02-28 01:33:23 +03:00
f138358862 feat(api): Адаптация API documents для django-filer
- Создан FilerFileField для сериализации filer.File объектов
- При чтении: возвращает URL файла через filer.url
- При записи: создает filer.File из UploadedFile с валидацией размера
- Обновлены serializers для работы с FilerFileField
- Обновлены тесты API: _filer_file() helper, mak_document() использует filer
- Удален устаревший mock documents.notification
- Удален validate_file() (валидация перенесена в FilerFileField)

WIP: Некоторые тесты не проходят, требуется отладка permissions
2026-02-28 01:26:23 +03:00
8ca806712a feat(employees): переход на Service Layer и перенос birthday логики из calendar_app
- Интегрирован django-service-objects 0.7.1 для Service Layer Pattern
- Перенесена вся логика дней рождения из calendar_app → employees:
  * UpsertBirthdayEventService - создание/обновление событий ДР
  * DeleteBirthdayEventService - удаление событий ДР
  * BulkSyncBirthdaysService - массовая синхронизация
  * signals_birthday.py - автосинхронизация через post_save/post_delete
  * management command sync_birthdays - CLI команда синхронизации
  * тесты (11 tests, 6 passing)

- Обновлена миграция 0013_migrate_to_django_scheduler:
  * Добавлен ШАГ 5: автоматическая синхронизация дней рождения (131 событие)
  * Исключены старые события ДР из миграции (source.endswith(':birthday'))
  * Исправлены имена сотрудников (f'{last_name} {first_name}' вместо get_full_name())
  * Добавлен цвет #FFC107 для событий дней рождения

- Очищен calendar_app от birthday сервисов:
  * Удалены calendar_app/services/birthday_events.py
  * Удалены calendar_app/signals_scheduler.py
  * Удалены calendar_app/management/commands/sync_birthdays.py
  * Удалены calendar_app/tests/test_services.py
  * Обновлен apps.py - удалены ссылки на signals_scheduler

- API улучшения:
  * Добавлен api/v1/schedule/permissions.py (IsCalendarOwnerOrAdmin)
  * Обновлен views.py с правильными permissions

- Документация:
  * DJANGO_SERVICE_OBJECTS_INTEGRATION.md - руководство по Service Layer
  * CALENDAR_MIGRATION_ANALYSIS.md - анализ миграции
  * MODERNIZATION_ANALYSIS.md - анализ модернизации кодовой базы

Цель: подготовка к будущему удалению calendar_app, централизация
логики сотрудников в employees приложении.

Refs: #birthday-refactoring
2026-02-27 23:49:09 +03:00
a30856ccc7 feat: интегрирован django-push-notifications для Web Push
- Добавлен django-push-notifications==3.1.0 в requirements.txt
- Настроен PUSH_NOTIFICATIONS_SETTINGS в settings.py
- Создана миграция данных 0008_migrate_webpush_to_library.py (9 подписок)
- Обновлен send_web_push_notification() в services.py (150→25 строк)
- Обновлены API endpoints: subscribe_push, unsubscribe_push, get_push_subscriptions
- Ожидается 10-50x ускорение при отправке push уведомлений
- Обратная совместимость: API не изменилось, старая модель сохранена
- Полный отчет: backend/docs/reports/DJANGO_PUSH_NOTIFICATIONS_INTEGRATION.md
2026-02-27 19:30:51 +03:00
6a76b231a6 feat: расширен поиск - добавлены модели procurement, documents, notifications, schedule
- Добавлены 5 новых моделей в watson search:
  * ProcurementRequest (заявки на закупку)
  * Equipment (оборудование)
  * Document (документы)
  * Notification (уведомления)
  * Event из django-scheduler (расписание)

- Backend API: форматтеры для новых типов моделей
- Frontend: добавлены иконки и названия для новых типов
- Тесты: исправлены фикстуры, все 13 тестов проходят
- Индексы: 3895 записей проиндексировано

Итого: 12 моделей доступны для полнотекстового поиска
2026-02-27 19:02:15 +03:00
8fd44448f4 feat: Add frontend integration for watson search API
Backend:
- Created REST API endpoint /api/v1/search/
- Added SearchResultSerializer and SearchResponseSerializer
- Implemented search_api_view with model formatters (employee, department, post, request, chat, message, event)
- Registered search endpoint in api/v1/urls.py
- Added permission check for requests (HR can see all, users only their own)

Frontend:
- Added SearchResponse, SearchResult, SearchModelType types
- Added apiClient.search() method in lib/api.ts
- Completely rewrote search/page.tsx:
  * Single API call instead of 6 parallel requests
  * Cleaner UI with icons for each result type
  * Real-time search with loading states
  * Meta information display (email, phone, status, etc.)
  * Better performance and UX

Benefits:
- Frontend: 220 lines → 178 lines (19% reduction)
- 1 API request instead of 6 (83% less network calls)
- Server-side full-text search via watson (better relevance)
- Unified search results with metadata

Testing:
- API endpoint verified at /api/v1/search/?q=test
- Returns JSON with query, results, counts, total
- Requires authentication (IsAuthenticated decorator)
2026-02-27 18:27:36 +03:00
4c23a0ec4d feat: Add procurement refactoring plan and merge migrations 2026-02-27 17:55:42 +03:00
5cf586ac1d merge: frontend/Igor2 into feature/procurement-module with Igor2 priority 2026-02-27 16:36:16 +03:00
66e82fc18a Fix WebSocket URL handling and simplify .env.local setup 2026-02-26 20:18:37 +03:00
8a083f6f67 fix: Исправлена система автоотметки прочитанных сообщений
- Удалено поле last_read_at из ChatReadState, используется только last_read_message FK
- Исправлена логика автоотметки: отмечается последнее ЗАГРУЖЕННОЕ сообщение, а не последнее в чате
- Убран вызов chat.mark_read() при WebSocket open_chat (отмечал последнее в чате вместо загруженного)
- Добавлен signal для мониторинга изменений ChatReadState
- Исправлена логика скролла: убран автоскролл при дозагрузке вниз
- Добавлена проверка разрывов при WebSocket сообщениях (предотвращает пропуск сообщений)
- Реализована автоотметка WebSocket сообщений (только если пользователь внизу)
- Асимметричная загрузка: 24 контекста + 6 новых сообщений
- Добавлен ScrollableMessageList компонент для корректной работы скролла
- Миграции: 0028 (удаление last_read_at), 0029 (индекс на last_read_message)
2026-02-25 20:29:00 +03:00
d6a3135bae Удалён режим 'до даты' для повторяемых событий, исправлен патч django-scheduler, фронт теперь только 'count' и 'forever' 2026-02-25 11:13:20 +03:00
4988f1eee7 feat: детальное отображение параметров повторяющихся событий
Backend:
- Добавлено поле rule_data в EventSerializer
- get_rule_data() возвращает частоту, параметры и описание правила
- Использует rule.get_params() для получения распарсенных параметров

Frontend:
- Добавлены константы FREQUENCY_LABELS и WEEKDAY_LABELS для русификации
- Новый блок с детальной информацией о повторении в синем фоне
- Отображается частота (WEEKLY, MONTHLY и т.д.)
- Дни недели для еженедельных событий (ПН, ВТ, СР...)
- Количество повторений (count)
- Дата окончания повторения (end_recurring_period)
- Подсказка о невозможности редактирования параметров

Проблема: пользователь не видел детали повторяющихся событий.
Решение: красивый информационный блок с полной информацией о правиле.
2026-02-25 02:20:24 +03:00
544b7f3e89 fix: исправлена работа повторяющихся событий с django-scheduler
- Исправлен RuleSerializer для корректной конвертации params между форматами:
  * Frontend отправляет dict/JSON: {"byweekday": [0, 4], "interval": 1}
  * Backend сохраняет в формате django-scheduler: "byweekday:0,4;interval:1"
  * Добавлен универсальный парсер _parse_params_input() для всех форматов

- Добавлен UX в стиле Apple Calendar для еженедельных событий:
  * Авто-выбор дня начала при включении WEEKLY
  * Информационный баннер с датой первого события если начальный день не выбран
  * Защита от перезаписи выбора пользователя через useRef

- Рефакторинг и очистка кода:
  * Удалены все отладочные console.log() и print()
  * Улучшены docstrings с примерами
  * Добавлена константа VALID_FREQUENCIES

- Исправлена загрузка событий в режиме "Все события":
  * Убрана блокировка для selectedCalendarId === null
  * События и occurrences загружаются корректно для всех календарей

Closes: повторяющиеся события теперь генерируются только в выбранные дни недели
2026-02-25 01:55:51 +03:00
9908c11c62 feat(calendar): доступ к событиям для участников + UX улучшения
Backend:
- Расширен get_queryset в ScheduleEventViewSet: теперь пользователь видит события где он участник (EventRelation), даже если не имеет доступа к календарю
- Добавлен action my-events для получения только событий участника
- Исправлена архитектурная проблема: участники событий теперь могут видеть свои события

Frontend:
- Добавлен метод apiClient.getMyEvents() для получения событий пользователя
- Добавлена подсказка в EventModal о логике начала/конца для повторяющихся событий
- Улучшен UX: пользователи понимают что начало/конец применяются ко всем повторениям
2026-02-25 00:47:45 +03:00
45870fba86 fix(calendar): timezone handling для datetime-local inputs
- Добавлена функция toLocalDateTimeString для корректной конвертации UTC в локальное время
- Исправлено отображение времени в модальном окне событий (было 21:00 UTC вместо 00:00 MSK)
- Упрощена логика datetime-local inputs (удалена сложная условная логика)
- Добавлен allDayAccessor в react-big-calendar для корректного отображения событий
- Унифицирован EventModal для обоих календарей (~718 строк удалено)
2026-02-25 00:38:54 +03:00
0dd3ac7cc1 Реализация системы schedule (django-scheduler) с тестовыми данными
- Добавлен CustomToolbar для BigCalendar со стрелками навигации
- Выпадающий список для выбора вида календаря
- Management command для создания тестовых пользователей и календарей
- Создано 3 тестовых пользователя (anna_ivanova, petr_petrov, maria_sidorova)
- Создано 5 календарей с 11 событиями
- Убраны подписки (они для старой системы calendar_app)
- Исправлены стили тулбара BigCalendar
- Модалы календаря рендерятся на корневом уровне AppShell
2026-02-24 20:24:39 +03:00
74a29fde28 feat: replace old calendar with django-scheduler in frontend
- Removed legacy calendar with department_id/employee_id filters
- New CalendarCard loads calendars from django-scheduler API
- Events filtered by calendar ID instead of legacy params
- Removed unused SidebarCalendarOption type
2026-02-24 18:12:28 +03:00
ecc166e08b fix: correct imports after frontend/Igor merge
- Fixed PHONE_FIELD import from _helpers module
- Fixed _normalize_phone import from employees.utils
2026-02-24 18:04:05 +03:00
9378054349 Merge branch 'frontend/Igor' into feature/django-scheduler-integration 2026-02-24 17:59:17 +03:00
63b6fff1ef feat: migrate frontend to django-scheduler API
- Updated API endpoints from /api/v1/calendar/ to /api/v1/schedule/
- Removed subscriptions concept (django-scheduler uses simpler approach)
- Adapted CalendarSerializer to accept 'title' field for EUSRR compatibility
- All calendar visibility now stored in localStorage
- Removed deprecated subscribe/unsubscribe functions
2026-02-24 17:54:46 +03:00
d94e82d313 feat: add django-scheduler API v1 endpoints
New clean API alongside old calendar_app:

API endpoints:
- /api/v1/schedule/calendars/ - Calendar CRUD
- /api/v1/schedule/events/ - Event CRUD (with timezone)
- /api/v1/schedule/rules/ - rrule RFC 5545 rules
- /api/v1/schedule/occurrences/ - materialized recurrences
- /api/v1/schedule/relations/ - meeting attendees

Features:
- Timezone support (pytz)
- RFC 5545 rrule for recurring events
- EventRelation for meeting participants
- Clean, tested code (django-scheduler)
- Parallel work with old /api/v1/calendar/

Old API untouched, works as before.
Gradual migration approach (Strangler Fig Pattern).
2026-02-24 17:35:30 +03:00
8b2d3b378e feat(frontend): добавлен API клиент и восстановлен backend из master
- Создан frontend/src/lib/api.ts с 43 методами для всех API endpoint'ов
- Создан frontend/src/lib/permissions.ts для проверки прав доступа
- Исправлен URL в getChatMessagesAround: /messages/around/ → /messages-around/
- Исправлен параметр: message_id → around_id
- Восстановлен backend из ветки master для стабильности
- Удалены конфликтующие файлы Pages Router (src/pages, App.tsx, providers)
- Оставлена только чистая структура Next.js App Router
- Добавлена документация по миграции API v2
2026-02-24 15:40:50 +03:00
3651554d9e Альфа версия 2026-02-24 13:11:32 +03:00
e44bfd4755 fix: добавлено поле calendar_title в CalendarEventSerializer 2026-02-23 13:11:54 +03:00
2c70730a17 fix: добавлено поле default_can_edit в CalendarWriteSerializer
Проблема: настройка 'Подписчики могут редактировать по умолчанию'
не сохранялась при создании/редактировании календаря.

Причина: поле default_can_edit отсутствовало в fields
CalendarWriteSerializer.

Решение: добавлено поле default_can_edit в список полей сериализатора.

Теперь можно включить эту настройку для глобального календаря,
и обычные пользователи смогут создавать события.
2026-02-23 12:33:27 +03:00
ffd3e469a1 фикс календаря 2026-02-23 12:20:18 +03:00
a335594932 fix: remove mocks from LDAP tests, use real LDAP integration, set gender default=0 2026-02-16 21:12:25 +03:00
4629a52834 fix: resolve test failures - add logger, LDAP_POSITIONS_BASE, make avatar/gender optional, add ensure_ldap_disabled fixtures 2026-02-16 17:38:00 +03:00
f85b5dfa08 refactor: remove DB access from LDAP layer update method
- Move department_id to department_dn resolution to ViewSet layer
- update_user_in_ldap_only now receives ready department_dn parameter
- LDAP service no longer queries Department.objects directly
- All three *_in_ldap_only methods are now pure LDAP (no DB access)
2026-02-16 17:22:38 +03:00
4b56711636 refactor(employees): minimize ViewSet overrides - let mixin do the work
Removed unnecessary method overrides:

Deleted:
- create(): removed entirely - миксин работает через perform_create
- partial_update(): removed entirely - миксин работает автоматически
- perform_update() avatar handling: moved to perform_update

Simplified:
- perform_create(): only unusable password + skills (30 lines)
- perform_update(): only email verification (15 lines)

Benefits:
- Миксин работает "из коробки" без явных переопределений
- Меньше кода для поддержки
- create/update/destroy используют стандартный механизм DRF
- Только необходимая кастомная логика в perform_*

Теперь ViewSet минимален:
- Конфигурация миксина (get_external_sync_method, prepare_external_data)
- Только критичная логика (unusable password, email verification)
- Все остальное - автоматически через миксин

manage.py check: no issues
2026-02-16 17:16:19 +03:00
518fb6e790 refactor(employees): remove _perform_user_update, simplify me() PATCH
Removed 180+ lines of complex update logic:

Deleted:
- _perform_user_update(): 180 lines of manual LDAP/DB coordination
- Complex validation and error handling
- Manual transaction management
- Direct DirectoryService.update_user() calls

Simplified me() PATCH:
- Now uses standard perform_update() mechanism
- 4 lines instead of 15
- Consistent with partial_update()
- Миксин управляет всем автоматически

Total code reduction in employees.py: ~400 lines removed
(create: -150, partial_update: -200, _perform_user_update: -180)

File now: ~800 lines (was 1200+)

Benefits:
- Single source of truth for update logic
- No code duplication
- Automatic transaction management
- Cleaner, easier to maintain

manage.py check: no issues
2026-02-16 17:10:03 +03:00
7a3402f1b6 refactor(employees): simplify partial_update using ExternalSystemSyncMixin
Replaced _perform_user_update (180+ lines) with clean mixin approach:

Before:
- _perform_user_update(): 180 lines of manual LDAP/DB coordination
- Manual transaction management
- Direct DirectoryService.update_user() calls with transaction.atomic inside
- Complex error handling
- Duplicate email verification logic

After:
- partial_update(): delegates to super() + email verification (30 lines)
- perform_update(): only avatar handling (20 lines)
- prepare_external_data(): builds LDAP changes dict with avatar_bytes
- Миксин автоматически управляет транзакциями

Changes:
1. partial_update(): simplified to super() + email verification
2. perform_update(): handles avatar file -> ContentFile
3. prepare_external_data(): extracts LDAP fields (first_name, last_name, email, etc),
   converts avatar to bytes, passes move_to_department_dn and group_cns
4. update_user_in_ldap_only(): updated signature to accept move_to_department_dn, group_cns

Code reduction: 200 lines -> 80 lines
Benefits: cleaner, automatic rollback, consistent with create()

Next: можно удалить _perform_user_update() если не используется

manage.py check: no issues
2026-02-16 17:08:45 +03:00
59b8f56c5a refactor(employees): simplify create() using ExternalSystemSyncMixin
Replaced 150+ lines of manual transaction management with mixin:

Before:
- Manual transaction.atomic()
- Manual LDAP sync calls
- Duplicate code for LDAP/non-LDAP modes
- Manual error handling and rollback
- ~150 lines of boilerplate

After:
- create() delegates to super() - миксин управляет всем
- perform_create() - только БД логика (30 lines)
- handle_external_sync_result() - обработка LDAP результата
- Миксин автоматически управляет транзакциями и откатами

Changes:
1. create(): simplified to validation + super().create()
2. perform_create(): creates Employee in DB, sets password/avatar/skills
3. prepare_external_data(): builds DTO with avatar_bytes, group_cns
4. handle_external_sync_result(): saves DN/GUID to LdapSyncState,
   sets employeeNumber, assigns position

5. ExternalSystemSyncMixin: added handle_external_sync_result() hook
   for custom post-sync actions

Code reduction: 150 lines -> 80 lines
Benefits: cleaner, DRYer, automatic error handling

manage.py check: no issues
2026-02-16 17:07:15 +03:00
df82e4f66d feat: add ExternalSystemSyncMixin for universal LDAP/DB sync
Created universal solution for ViewSet + external system synchronization:

1. ExternalSystemSyncMixin (common/external_sync_mixin.py):
   - Automatically wraps CRUD operations in transactions
   - Coordinates DB + LDAP in single atomic transaction
   - Rolls back DB if LDAP fails
   - Configurable error handling
   - Works with any external system (LDAP, APIs, etc)

2. Applied to EmployeeViewSet:
   - Added mixin to base classes
   - Configured LDAP sync mapping (create/update/destroy)
   - prepare_external_data() for DTO creation
   - handle_external_sync_error() for LDAP errors
   - No need to override create/update/destroy methods

3. Created pure LDAP methods in DirectoryService/UserService:
   - create_user_in_ldap_only() - LDAP create, returns dn/guid
   - update_user_in_ldap_only() - LDAP update, no DB access
   - delete_user_in_ldap_only() - LDAP delete, no DB access
   - All methods removed transaction.atomic (managed by ViewSet)

4. Documentation:
   - Complete guide in docs/guides/EXTERNAL_SYNC_MIXIN_GUIDE.md
   - Usage examples for all patterns
   - Migration guide from old architecture
   - Comparison with alternatives (Signals, Celery, Saga)

Benefits:
- Minimal code (3 methods vs overriding entire ViewSet)
- Clear separation: View owns DB, LDAP service owns LDAP
- Reusable for all ViewSets (departments, positions, etc)
- Easy to test (external_sync_enabled = False)
- Universal (works with any external system)

manage.py check: System check identified no issues
2026-02-16 17:04:08 +03:00
1f0858b085 refactor(ldap): fix architectural issues in views
DirectoryService:
- Added public methods: assign_role, revoke_role, create_role, update_role, delete_role
- Added public method: move_user_to_base (replaces private _user_service._move_user_to_base)
- Fixed method signatures to match DepartmentService API

roles.py:
- Replaced direct DepartmentService usage with DirectoryService facade (5 methods)
- Removed manual GroupService/UserService instantiation
- All CRUD operations now go through facade layer

actions.py:
- Replaced private API svc._user_service._move_user_to_base() with public svc.move_user_to_base()
- Simplified LDAP connection handling (2 occurrences)
- Removed manual _ldap() and ensure_container_exists calls

manage.py check: System check identified no issues
2026-02-16 16:38:01 +03:00
19464a38cf refactor(employees): DRY duplicate logic in employees and departments
employees.py:
- Extracted _perform_user_update() method (180 lines)
- Simplified me PATCH: removed ~150 lines of duplicate code
- Simplified partial_update: removed ~155 lines of duplicate code
- Total reduction: ~255 lines (930 → 675)

departments.py:
- Extracted _perform_set_head() method (70 lines)
- Simplified set_head action: removed ~50 lines of duplicate code
- Simplified partial_update head branch: removed ~70 lines of duplicate code
- Total reduction: ~140 lines (752 → 612)

manage.py check: System check identified no issues
2026-02-16 16:32:12 +03:00
09dfb7598e refactor(employees): DRY duplicate logic in employees and departments
employees.py:
- Extracted _perform_user_update() method (180 lines)
- Simplified me PATCH: removed ~150 lines of duplicate code
- Simplified partial_update: removed ~155 lines of duplicate code
- Total reduction: ~255 lines (930 → 675)

departments.py:
- Extracted _perform_set_head() method (70 lines)
- Simplified set_head action: removed ~50 lines of duplicate code
- Simplified partial_update head branch: removed ~70 lines of duplicate code
- Total reduction: ~140 lines (752 → 612)

manage.py check: System check identified no issues
2026-02-16 16:27:08 +03:00
eaedea1403 refactor(employees): remove permissions.py shim, fix relative imports
- Replaced ..permissions with ...permissions in all 7 view modules
- Deleted backend/api/v1/employees/permissions.py (duplicate re-export)
- Views now import directly from api.v1.permissions (3 dots up)

manage.py check: System check identified no issues
2026-02-16 16:21:45 +03:00
8efcabf530 refactor(employees): split monolithic views.py (4593 lines) into views/ package
- Split into 9 modules by ViewSet: departments, employees, positions,
  roles, skills, actions, groups, auth, _helpers
- Created views/__init__.py with re-exports for backward compatibility
- Created employees/permissions.py re-export shim (views/ is now a
  sub-package, so ..permissions resolves to employees.permissions)
- Fixed api/auth/serializers.py import: PHONE_FIELD from _helpers,
  _normalize_phone from employees.utils
- Removed ~250+ debug print()/logger.info() statements from
  departments.py and employees.py
- Removed dead _with_ldap_service() decorator from helpers
- Removed unreachable code at end of GroupViewSet.replace_members

manage.py check: System check identified no issues (0 silenced)
2026-02-16 16:18:03 +03:00
28e2f1615f feat: реализован drag & drop для перемещения событий между календарями
- Создан модуль calendarEventDragDrop.js с классами DragDropState и CalendarUtils
- Реализовано перетаскивание событий между календарями через модальное окно
- Добавлена кнопка 'Переместить все' для массового перемещения
- Модальное окно отображает источник и цель перемещения
- Поддержка legacy-календарей (company/department/personal)
- Добавлены стили для подсветки drop-target (папки и календари)
- Backend: исправлена обработка null значений в serializer
- Backend: добавлен endpoint list_raw для получения немодерируемых событий
- Использованы стандартные Bootstrap стили для модалов
- Исправлено всплытие событий dragover/drop (stopPropagation)
- Эмодзи иконки для типов календарей (����)
- Toast уведомления об успехе/ошибках перемещения
2026-02-12 15:59:53 +03:00
281f0b2bbc feat: современное отображение событий календаря с множественным выбором
Реализовано:

1. Множественный выбор календарей через чекбоксы
   - Заменил <select> на чекбоксы для выбора нескольких календарей
   - События создаются одновременно во всех выбранных календарях
   - При редактировании - обновляется только первый выбранный
   - Цветовые индикаторы для каждого календаря

2. Современный дизайн событий
   - Двухцветная схема: левая граница = цвет календаря, фон = цвет события
   - Полупрозрачный фон события (80%) для лучшей видимости
   - Тени и hover эффекты для объёма
   - Закругленные углы (4px)
   - Плавные анимации (transform + transition)

3. Улучшенное отображение накладывающихся событий
   - dayMaxEvents: автоматически показывать '+N еще'
   - dayMaxEventRows: 4 - максимум 4 строки на день
   - moreLinkClick: 'popover' - красивый popover для остальных
   - eventMaxStack: 3 - до 3 событий в стеке
   - eventOrder: сортировка по началу, длительности, алфавиту

4. Новый CSS файл calendar-improvements.css
   - Современные стили для FullCalendar
   - Улучшенный popover с градиентом
   - Стили для выходных дней (розоватый фон)
   - Hover эффекты на события
   - Анимация fadeInEvent при загрузке
   - Улучшенная читаемость текущего дня
   - Адаптивность для мобильных устройств
   - Кастомные scrollbar для списков

5. Передача цвета календаря в события
   - calendar_color добавляется в extendedProps
   - Используется __calendar из интеграции
   - Отдельная обработка eventColor и calendarColor

6. Визуальные улучшения
   - Текст события: font-weight 500, line-height 1.3
   - Отступы: paddingLeft 6px (с цветом календаря)
   - Тень текста для читаемости на любом фоне
   - Паттерн для ежегодных событий (диагональные полосы)
   - Индикатор текущего дня: синий круг с белым текстом

Результат:
✅ События визуально различимы по календарям (левая граница)
✅ Сохранён индивидуальный цвет события (основной фон)
✅ Множество событий в день отображается компактно (+N еще)
✅ Современный Material Design стиль
✅ Плавные анимации и hover эффекты
✅ Улучшенная читаемость и UX
2026-02-11 12:52:25 +03:00
db69efb329 fix: удален дубликат кода в CalendarSubscriptionSerializer
- Удалены повторяющиеся строки в методе validate()
- Fixes: IndentationError: unexpected indent на строке 487
2026-02-11 12:33:06 +03:00
b03ef1308e fix: удален дубликат urlpatterns в api/v1/urls.py
- Удалены повторяющиеся строки с notifications и router.urls
- Исправлена длинная строка с MessageViewSet
- Fixes: IndentationError: unexpected indent
2026-02-11 12:30:49 +03:00
f7d3cd8c91 feat(calendar): add comprehensive test suite for new Calendar API
- Added make_event fixture for creating test events
- Added CalendarSubscription.color_override null=True migration
- Added computed fields (is_personal, is_global, is_department) to CalendarSerializer
- Fixed CalendarViewSet.create() to use CalendarSerializer for response
- Created test_new_calendar_api.py with 29 comprehensive tests:
  * 11 CRUD tests (list, create, retrieve, update, delete)
  * 6 subscription tests (subscribe, unsubscribe, my-subscriptions)
  * 3 event filtering tests (calendar_id filtering, legacy separation)
  * 3 visibility tests (public, private, department)
  * 6 permission tests (is_owner, can_user_view, can_user_edit)

Test results:
- ✅ 34 legacy tests passing (backward compatibility maintained)
- ✅ 29 new tests passing (new functionality validated)
- ✅ Total: 63 tests passing
2026-02-11 08:35:24 +03:00
526ebe6b76 fix(calendar): add calendar_id to serializer fields and fix related_name for departments
- Added calendar_id to CalendarEventWriteSerializer Meta.fields
- Fixed related_name from employee_departments to departments_links
- Updated make_event fixture to support calendar parameter
- Added comprehensive test suite for new Calendar and CalendarSubscription API
- Added fixtures: make_calendar, make_subscription, auth_client, user fixtures
- All legacy tests passing (34 passed)
2026-02-11 08:27:00 +03:00
870a08ee66 feat(calendar): add API layer for optional calendars
Phase 2: API implementation
- Updated CalendarEventWriteSerializer to support calendar_id parameter
- Added CalendarSerializer and CalendarWriteSerializer for Calendar CRUD
- Added CalendarSubscriptionSerializer for subscription management
- Created CalendarViewSet with subscribe/unsubscribe actions
- Created CalendarSubscriptionViewSet for managing subscriptions
- Updated CalendarEventsViewSet to support calendar_id filtering
- Added CalendarManager with get_available_for_user() method
- Added permission methods to Calendar model (is_owner, can_user_view, can_user_edit, can_user_manage)
- Registered new ViewSets in URL routing

API endpoints:
- GET /api/v1/calendar/calendars/ - list available calendars
- POST /api/v1/calendar/calendars/ - create new calendar
- GET /api/v1/calendar/calendars/{id}/ - retrieve calendar details
- PATCH /api/v1/calendar/calendars/{id}/ - update calendar
- DELETE /api/v1/calendar/calendars/{id}/ - delete calendar
- POST /api/v1/calendar/calendars/{id}/subscribe/ - subscribe to calendar
- POST /api/v1/calendar/calendars/{id}/unsubscribe/ - unsubscribe from calendar
- GET /api/v1/calendar/calendars/my-calendars/ - list user's calendars
- GET /api/v1/calendar/subscriptions/ - list user's subscriptions
- POST /api/v1/calendar/subscriptions/ - create subscription
- GET /api/v1/calendar/events/?calendar_id={id} - filter events by calendar

Backward compatibility: all legacy endpoints continue to work
2026-02-11 08:18:47 +03:00
3e4137daa4 feat(ldap): добавлено кэширование LDAP логина с возможностью обновления
- Добавлено поле Employee.username для кэширования LDAP логина
- API endpoint обновлен: поддержка кэша и force_refresh параметра
- Новый дизайн: убран blur, добавлена иконка обновления
- Автоматическая загрузка при инициализации (из кэша или LDAP)
- Визуальная индикация источника данных (cached/fresh)
- Доступно всем пользователям без ограничений
2026-02-06 15:33:48 +03:00
10f7287ae5 fix(employees): добавлено LDAP соединение для LdapRepository
- LdapRepository требует активное соединение в конструкторе
- Добавлен вызов _conn() для получения LDAP соединения
- Исправлена ошибка: TypeError: LdapRepository.__init__() missing 1 required positional argument: 'conn'
- Теперь используется: LdapRepository(_conn())
2026-02-06 14:57:37 +03:00