540 Commits

Author SHA1 Message Date
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
3bb3db1e99 feat: update frontend to use django-scheduler API
- Updated API endpoints to /api/v1/schedule/
- Updated Calendar and CalendarEvent types for django-scheduler
- Added methods: getCalendars(), createCalendar(), createEvent()
- Changed field names: start_time -> start, end_time -> end
2026-02-24 18:00:55 +03:00
9378054349 Merge branch 'frontend/Igor' into feature/django-scheduler-integration 2026-02-24 17:59:17 +03:00
f42e6ec7d0 docs: add frontend migration completion report 2026-02-24 17:55:32 +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
f67e625c14 feat: add django-scheduler alongside calendar_app
- Install django-scheduler 0.12.0 (parallel to existing calendar_app)
- Add 'schedule' to INSTALLED_APPS
- Create integration plan documentation
- Old calendar_app remains untouched (works as before)
- New django-scheduler for gradual migration
- API v2 will be created next for testing

Related: Strangler Fig Pattern for clean code migration
2026-02-24 17:29:15 +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
b324e61285 Бета версия (80% функционала) 2026-02-24 14:13:26 +03:00
3651554d9e Альфа версия 2026-02-24 13:11:32 +03:00
e44bfd4755 fix: добавлено поле calendar_title в CalendarEventSerializer 2026-02-23 13:11:54 +03:00
10a1c210a3 fix: исправлено отображение календаря vs контекста в деталях события 2026-02-23 13:07:59 +03:00
abc7f96902 fix: добавлено отображение создателя и календаря в деталях события + исправлен calendarId string→number 2026-02-23 13:02:38 +03:00
705fa39052 - 2026-02-23 12:56:23 +03:00
8c3c4119af - 2026-02-23 12:56:11 +03:00
d31e8cd064 fix: can_user_edit теперь проверяет default_can_edit даже если есть подписка с can_edit=False 2026-02-23 12:47:17 +03:00
8825434b7a fix: can_user_edit теперь учитывает default_can_edit
Проблема: даже после включения default_can_edit=True обычные
пользователи не могли создавать события в календаре.

Причина: метод Calendar.can_user_edit() проверял только:
- is_superuser/is_staff
- is_owner()
- subscription.can_edit
НО НЕ проверял default_can_edit для случая когда подписки нет.

Решение: добавлена проверка default_can_edit после проверки подписки.
Теперь если подписки нет, но default_can_edit=True, пользователь
может редактировать.

Это позволяет создавать публичные календари, где ВСЕ пользователи
могут создавать события без явных подписок.
2026-02-23 12:38:14 +03:00
2c70730a17 fix: добавлено поле default_can_edit в CalendarWriteSerializer
Проблема: настройка 'Подписчики могут редактировать по умолчанию'
не сохранялась при создании/редактировании календаря.

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

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

Теперь можно включить эту настройку для глобального календаря,
и обычные пользователи смогут создавать события.
2026-02-23 12:33:27 +03:00
7a055c79cb fix: исправлены JS ошибки в календаре и emoji-picker
- Создана заглушка для calendarEventDragDrop.js с экспортом initCalendarEventDragDrop
- Закомментирован импорт несуществующего database.js в emoji-picker/index.js
- Исправлена ошибка 'does not provide an export named initCalendarEventDragDrop'
- Исправлена ошибка 404 для emoji-picker/database.js
2026-02-23 12:26:03 +03:00
ffd3e469a1 фикс календаря 2026-02-23 12:20:18 +03:00
d3ecb3d126 merge: resolve AppShell conflict with frontend/main 2026-02-20 13:23:43 +03:00
2d16c526f5 feat: update messaging UI and online status indicators 2026-02-20 13:22:40 +03:00
c5470e0131 Clean up corp.front directory and update frontend layout/AppShell 2026-02-20 11:08:19 +03:00
e9d20d48eb feat: integrate Next.js frontend with Django backend
- Add complete Next.js 16 frontend with TypeScript and Tailwind CSS
- Implement API proxy route for CORS-free backend communication
- Create UserContext for global authentication state management
- Add authentication flow with JWT tokens
- Implement real data integration for posts and employees pages
- Add dynamic user avatars (with fallback to initials)
- Update API types to match backend Employee serializer
- Remove all hardcoded mock data
- Add route protection with automatic redirect to /login
- Configure Docker orchestration for full-stack setup
2026-02-19 15:57:42 +03:00
ce78f7481f feat: Улучшенный UI с компонентом AppShell
- Добавлен компонент AppShell с Header, Sidebar, Calendar
- Установлен lucide-react для современных иконок
- Обновлены все страницы: главная, login, employees, documents, etc
- Единый дизайн с PageHeader и переиспользуемыми элементами
- Улучшенная навигация с активными ссылками
- Responsive design с sticky элементами
- Градиентный фон и современные shadow/ring эффекты
2026-02-19 14:17:20 +03:00
d19bb560ea feat: Полная интеграция Next.js frontend с Docker orchestration
- Создан Next.js 16 frontend приложение с TypeScript и Tailwind
- Настроена Docker инфраструктура (docker-compose с 7 сервисами)
- Добавлен nginx reverse proxy для маршрутизации frontend/backend
- Реализован полный API client с JWT авторизацией
- Интегрированы страницы: login, register, feed, employees
- Переименована папка corp.front → frontend
- Исправлены проблемы с trailing slash в Django APPEND_SLASH
- Добавлена документация: DOCKER_ORCHESTRATION.md, INTEGRATION_GUIDE.md

Архитектура:
- nginx:80 → frontend:3000 (Next.js) + web:8000 (Django API)
- PostgreSQL 16 + Redis 7 для backend
- Celery worker + beat для фоновых задач
- JWT authentication через SimpleJWT
2026-02-19 13:51:19 +03:00
66ab7fb672 chore: удаление временных тестовых файлов оптимизации
- backend/test_message_optimization.py
- backend/test_refactored_notifications.py
2026-02-17 18:34:25 +03:00
dfe98244e8 feat(tools): добавление инструмента анализа DB запросов и package-lock
- backend/scripts/analyze_queries.py - автоматизированный анализ запросов
  * count_queries context manager для подсчета запросов
  * Тестирование ViewSet'ов с разными методами (list, retrieve, create)
  * Детальный вывод с количеством запросов на эндпоинт
  * Утилита для выявления N+1 проблем

- backend/package-lock.json - зафиксированы версии npm пакетов
  * sass@1.93.3 для компиляции CSS
  * Гарантирует идентичные сборки на разных машинах
2026-02-17 18:34:16 +03:00
e97dc26514 docs: добавление документации по тестированию и оптимизации
API Testing:
- docs/guides/API_TESTING_GUIDE.md - полное руководство по API тестированию
  * Использование Postman коллекции
  * Newman CLI интеграция
  * REST Client примеры
  * Pytest примеры с fixtures
- docs/reports/API_EMPLOYEES_COVERAGE.md - анализ покрытия эндпоинтов
  * Покрытие расширено с 23% до ~70%
  * Список протестированных и непокрытых эндпоинтов

Database Optimization:
- backend/docs/reports/DB_QUERIES_ANALYSIS.md - детальный анализ запросов к БД
  * 8 ViewSet'ов проанализированы
  * Найдены критические N+1 проблемы:
    - SkillViewSet.merge() делает 2N запросов в цикле
    - GroupViewSet.retrieve не использует prefetch_related
    - RegisterAPIView дважды проверяет email
  * Предложены оптимизации с raw SQL
  * Рейтинг текущего состояния: 4/5 звезд
2026-02-17 18:33:56 +03:00
9c23e59e56 feat(testing): добавление комплексной инфраструктуры API тестирования
Postman коллекция (52 теста):
- Аутентификация (3): login, refresh, verify
- Сотрудники (11): CRUD, search, bulk operations, skills
- Отделы (3): list, create, retrieve
- Документы (3): list, create, retrieve
- Лента (5): posts CRUD с пагинацией
- Коммуникации (5): чаты и сообщения
- Календарь (3): события и подписки
- Заявки (3): requests CRUD
- Уведомления (3): list, mark_read, mark_all_read
- Действия сотрудников (3): actions CRUD
- Роли отделов (3): department_roles CRUD
- Продвинутые функции: группы (5), навыки (2)

Newman CLI интеграция:
- newman_test_results.txt - последний запуск (32 requests, 0 failures)
- newman-report.json - детальный JSON отчет

REST Client:
- api_tests.http - альтернатива Postman для VSCode REST Client

Документация:
- API_QUICKSTART.md - быстрый старт с примерами
- docs/guides/API_TESTING_GUIDE.md - полное руководство (см. след. коммит)
2026-02-17 18:33:36 +03:00
0c2ad449ef feat(docker): добавление вспомогательных файлов для Docker
- .dockerignore - исключение ненужных файлов при сборке образа
- .env.example - пример переменных окружения
- backend/eusrr_backend/urls.py - добавлена раздача статических файлов в DEBUG режиме
2026-02-17 18:33:20 +03:00
025f82147c feat(logging): внедрение современной системы логирования с ротацией
Добавлена полнофункциональная система логирования:

Структура логов (backend/logs/):
- all.log - все сообщения (DEBUG+)
- error.log - ошибки и критические события (ERROR+)
- debug.log - отладочная информация (DEBUG+)
- security.log - события безопасности (аутентификация, авторизация)
- requests.log - HTTP запросы с деталями производительности

Возможности:
- Ротация файлов (10MB макс. размер, 5 бэкапов)
- 3 форматтера (verbose, simple, json_style)
- Фильтр RequireDebugFalse для production
- Раздельное логирование Django, DRF, Channels, Celery

Документация:
- LOGGING_GUIDE.md - полное руководство (400+ строк)
- logging_examples.py - примеры использования для всех компонентов
2026-02-17 18:32:30 +03:00
98104fcded refactor(settings): упрощение конфигурации и удаление дубликатов
- Упрощена инициализация DATABASES (удален пустой словарь, использован .update())
- Удалена закомментированная секция AUTH_PASSWORD_VALIDATORS
- Консолидированы дублирующиеся настройки LDAP:
  * LDAP_UPN_SUFFIX (было 2 определения)
  * LDAP_USERS_BASE / LDAP_USER_BASE (было дублирование)
- Изменены дефолтные значения с robotail.local на eusrr.local
- Расширена конфигурация логирования (см. следующий коммит)
2026-02-17 18:31:20 +03:00
8aa6d6ec87 chore: удаление устаревших тестовых и временных файлов
- Удалены старые тестовые файлы (test_*.html, test_*.py)
- Удалены временные конфиги и скрипты (.env.test, test_reply.sh)
- Удалены устаревшие документы (CELERY_NEXT_STEPS.md, FIX_INTEGRATION.md)
- Очищена папка localcerts_backup
- Удалены выводы pytest (pytest_output.txt)
- Удалены конфигурационные остатки (.gitignore.ldap, corp-ca.pem)
2026-02-17 18:29:24 +03:00
fcf4bff3a9 fix: add ensure_ldap_disabled to 71 tests to prevent LDAP sync issues 2026-02-16 21:44:53 +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
6a88f76ff1 docs: add test fixes session report 2026-02-16 17:39:30 +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
8b7d816390 docs: add LDAP testing infrastructure summary 2026-02-16 17:34:26 +03:00
ad8208789f feat: add LDAP testing infrastructure
- Add LDAP docker container structure (01-base-structure.ldif)
- Add .env.test with LDAP configuration for tests
- Create tests/ldap_fixtures.py with LDAP-specific fixtures
- Create tests/api/v1/employees/test_helpers.py with centralized helpers
- Add LDAP markers to pytest.ini (ldap_required, ldap_optional)
- Add comprehensive LDAP testing documentation
- Fix test_department_head_rights.py to use centralized helpers

New fixtures:
- ldap_available: checks if LDAP server is accessible
- ldap_config: returns LDAP configuration
- ensure_ldap_enabled/disabled: force LDAP state for test
- ldap_cleanup: auto-cleanup LDAP entries after test

New helpers:
- make_user(): centralized user creation
- grant_permission(): permission assignment
- make_department/position/role(): entity creation
- extract_results(): paginated response helper

Infrastructure:
- OU=Users, OU=Departments, OU=Groups, OU=Positions, OU=Dismissed
- Test groups: Developers, Managers
- Test departments: IT, HR
2026-02-16 17:31:48 +03:00
3977c99c0c test: fix tests after views split
- Remove @pytest.fixture from make_user (it's a helper function, not a fixture)
- Update _is_ldap_enabled patch paths to api.v1.employees.views._helpers
- Fixes AttributeError and fixture calling errors
2026-02-16 17:25:25 +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
423f14831d test: fix import errors after views.py split
- Fix IndentationError in test_poll_complete.py (remove duplicate lines)
- Fix ImportError in test_ldap_optional_helpers.py (update import path to _helpers module)

Tests now collect 515 items without collection errors.
11 pre-existing test failures remain (auth registration issues unrelated to refactoring).
2026-02-16 16:47:17 +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