- Remove hard-coded Russian translations from backend API
- Backend now returns raw verb values (language-agnostic)
- Implement frontend translation functions for notification titles and categories
- Add category badge system with filters on notifications page
- Create translation utilities in frontend (verbTranslations.ts)
- Add notification settings page structure
- Update API endpoints to return simplified notification data
- Refactor notification signals across all apps
- Remove deprecated code and tests
- Add comprehensive documentation for v2 migration
Backend changes:
- notifications/api/views.py: Remove translation logic, simplify responses
- All notification_signals.py: Update to use consistent patterns
- Remove deprecated Telegram bot command
- Update Celery tasks for new notification structure
Frontend changes:
- app/notifications/page.tsx: Add translation functions and category badges
- hooks/useNotificationWebSocket.ts: New WebSocket hook for real-time updates
- lib/verbTranslations.ts: Centralized translation mappings
- components/NotificationCenter.tsx: Update to use new API format
This makes the notifications module fully reusable and project-independent.
- Создан requirements.txt с основными зависимостями (Django, DRF, Celery, Channels)
- Обновлена секция установки с подробными инструкциями
- Добавлена структура модуля и описание компонентов
- Обновлены TODO (убраны выполненные задачи)
- Добавлена информация о production-safe миграциях
- Добавлены секции: настройка конфигурации, запуск Celery worker
- Модуль полностью самостоятельный и готов к переносу в другие проекты
Исправлено:
- channels.py: удалены осиротевшие строки после рефакторинга
- api/v1/notifications/urls.py: исправлен file для реэкспорта
- notifications/urls.py: создан для обратной совместимости
Миграции:
- 0010_userchannelpreferences_and_more.py: переход на v2 модели
* Notification с GenericForeignKey (actor/action_object/target)
* UserChannelPreferences вместо UserNotificationSettings
* Удалены старые модели (NotificationCategory, NotificationType и тд.)
* Переименована таблица в notifications_notification_v2
КРИТИЧНЫЕ УЛУЧШЕНИЯ:
✅ Убран хардкод 'EUSRR' → универсальное 'My Site'
✅ Созданы email шаблоны внутри модуля (4 файла)
✅ Централизованная конфигурация в config.py
✅ API перемещен в notifications/api/
Новые файлы:
- config.py - централизованные настройки с fallback значениями
- templates/notifications/email/*.html/*.txt - HTML и текстовые шаблоны
- api/__init__.py, api/views.py, api/urls.py - REST API внутри модуля
Изменения в существующих файлах:
- senders/email.py: использует config.site_name() и config.from_email()
- tasks/email.py: rate_limit, max_retries, retry_delay из config
- tasks/push.py: rate_limit, max_retries, retry_delay из config
- tasks/websocket.py: max_retries, retry_delay из config
- api/v1/notifications/urls.py: реэкспорт из notifications.api (обратная совместимость)
Структура шаблонов:
📁 notifications/templates/notifications/email/
├── notification.html - красивый HTML для обычных уведомлений
├── notification.txt - текстовая версия
├── digest.html - HTML дайджест (daily/weekly)
└── digest.txt - текстовая версия дайджеста
Конфигурация (config.py):
- DEFAULT_CONFIG с fallback значениями для всех параметров
- get_config() - объединяет с settings.NOTIFICATIONS_CONFIG
- Удобные функции: email_rate_limit(), push_max_retries(), site_name()
- Полностью настраиваемо через settings проекта
API внутри модуля:
- notifications/api/views.py - все endpoint'ы
- notifications/api/urls.py - URL patterns
- Относительные импорты (from ..models)
- Обратная совместимость через api/v1/notifications/urls.py
УНИВЕРСАЛЬНОСТЬ:
✅ Нет хардкода проекта
✅ Все шаблоны внутри модуля
✅ API внутри модуля
✅ Конфигурация через settings
✅ Можно скопировать в любой проект Django 5.2+
Критичные задачи:
- Создать email шаблоны (notification.html/txt, digest.html/txt)
- Написать unit и integration тесты (coverage >80%)
- Убрать хардкод 'EUSRR' из email sender
Важные улучшения:
- Вынести настройки rate_limit, max_retries в settings
- Переместить API endpoints в notifications/api/
- Централизовать конфигурацию в notifications/settings.py
Желательные доработки:
- setup.py для публикации в PyPI
- Sphinx документация
- CI/CD pipeline
- Pre-commit hooks
Затронуты файлы:
- models.py - TODO для тестов моделей
- signals.py - TODO для тестов сигналов
- channels.py - TODO для integration тестов
- senders/email.py - TODO для шаблонов и хардкода
- tasks/email.py - TODO для конфигурации
- tasks/push.py - TODO для конфигурации
- README.md - секция TODO с чеклистом
- Файл task_base.py (500 строк) использовал удаленный NotificationService API
- Нигде не импортировался и не использовался
- Создавал путаницу с новым tasks/base.py
- Экономия: -500 строк кода
BREAKING CHANGES:
- API полностью переписан под новую модель (verb вместо category/type)
- NotificationService заменен на stub с NotImplementedError
- Удалена обратная совместимость
API endpoints (обновлены):
- GET /api/v1/notifications/ - новый формат ответа
- GET /api/v1/notifications/verb-types/ - вместо categories
- GET/PUT /api/v1/notifications/preferences/ - вместо settings
- POST /api/v1/notifications/<id>/unread/ - новый endpoint
- DELETE /api/v1/notifications/delete-all-read/ - новый endpoint
Удалены endpoints:
- /api/v1/notifications/categories/ (нет категорий в v2)
- /api/v1/notifications/settings/* (заменено на preferences)
- /api/v1/notifications/telegram/* (Telegram отключен)
- /api/v1/notifications/push/vapid-key/ (не нужен)
- /api/v1/notifications/push/subscriptions/ (не нужен)
services.py:
- Заменен на stub с NotImplementedError
- Все методы выбрасывают исключения с подсказками миграции
- Документация как мигрировать со старого API
Новая структура ответа API:
- verb вместо category/type
- actor (GenericForeignKey) вместо sender
- description вместо message/title
- timesince() вместо created_at
- unread вместо is_read
Старые файлы:
- Удалены все *.old файлы
BREAKING CHANGES:
- Удалена старая система (6 моделей → 2 модели)
- models_new.py → models.py (Notification, UserChannelPreferences)
- signals_new.py → signals.py (notify.send API)
- admin_new.py → admin.py
Новая архитектура:
- Все отправки через Celery (полностью асинхронно)
- Модульная структура tasks/ (base, email, push, websocket)
- Каждый канал - отдельный класс задачи наследующий BaseNotificationTask
- Rate limiting, retry, приоритеты из коробки
Обратная совместимость:
- Создан services.py facade для старого API
- NotificationService.create_notification() работает через notify.send()
- Старый код продолжает работать без изменений
Удалено:
- Старые models.py, signals.py, admin.py, tasks.py (→ .old)
- telegram_bot.py, telegram_models.py (Telegram отключен)
- test_views.py, views.py, urls.py (устаревшие)
Создано:
- tasks/ модуль с классовой архитектурой (как senders/)
- tasks/base.py - BaseNotificationTask
- tasks/email.py - EmailNotificationTask + DigestEmailTask
- tasks/push.py - PushNotificationTask
- tasks/websocket.py - WebSocketNotificationTask
Обновлено:
- apps.py - загружает signals, channels, tasks
- channels.py - все отправки через Celery задачи
- Все импорты models_new → models
Очистка от дублирующегося кода:
Удалены старые файлы:
❌ email_sender.py → заменен на senders/email.py
❌ telegram_sender.py → функционал Telegram удален
❌ signals_telegram.py → Telegram сигналы удалены
Обновлены:
✅ apps.py - убран импорт signals_telegram
✅ services.py - обновлены импорты, Telegram помечен deprecated
NotificationService (старый) продолжает работать для обратной
совместимости, но использует новые senders где возможно.
Telegram функционал отключен в старой системе с пометкой
'use new notification system'.
Результат:
- Меньше дублирования кода
- Чище структура проекта
- Все отправители теперь наследуются от BaseNotificationSender
- Готовы к полной миграции на новую архитектуру
Создана объектно-ориентированная архитектура для отправителей:
Новая структура:
- BaseNotificationSender - абстрактный базовый класс
- EmailNotificationSender(BaseNotificationSender)
- WebSocketNotificationSender(BaseNotificationSender)
- PushNotificationSender(BaseNotificationSender)
Преимущества:
✅ Единый интерфейс send() для всех каналов
✅ can_send() - проверка возможности отправки
✅ Унифицированное логирование (log_success, log_error, log_skip)
✅ Легко расширять новыми каналами
✅ Переиспользуемость кода
Изменения:
- notifications/senders/base.py - базовый класс
- notifications/senders/email.py - email отправитель (упрощен)
- notifications/senders/websocket.py - WebSocket отправитель
- notifications/senders/push.py - Web Push отправитель
- notifications/channels.py - обновлен для использования классов
Старые функции send_* сохранены для обратной совместимости (deprecated)
- Убрана поддержка Telegram из каналов доставки
- Удалено telegram_enabled из UserChannelPreferences
- Обновлена документация
- Сфокусировались на WebSocket, Email и Web Push
Фокус: веб-уведомления, email дайджесты и web push
- Упрощена архитектура: 2 модели вместо 6
- GenericForeignKey для универсальности
- Стандартный API notify.send() как в django-notifications-hq
- Совместимость с Django 5.2+
- Сохранен multi-channel функционал (WebSocket, Email, Telegram, Push)
- Создана полная документация
Файлы:
- models_new.py - Notification + UserChannelPreferences
- signals_new.py - notify.send() API
- channels.py - роутинг по каналам доставки
- admin_new.py - Django Admin интерфейс
- README.md - краткое описание для переиспользования
- docs/guides/NOTIFICATIONS_V2_USAGE.md - полное руководство
- docs/reports/NOTIFICATIONS_REFACTORING_REPORT.md - отчет о рефакторинге
Требуется тестирование перед внедрением.
- Фронтенд: добавлена обработка поля 'notifications' (бэкенд возвращает { notifications: [...] })
- Фронтенд: исправлены URL endpoints для отметки прочитанным (/read/ вместо /mark_read/)
- Бэкенд: добавлено поле 'short_message' в ответ API для корректного отображения превью
- Убран фильтр по календарю при поиске существующих событий
- События автоматически переносятся из personal-XX в общий календарь birthdays
- Удаляются дубликаты событий ДР для одного сотрудника
- Закомментирован RunPython для избежания pending trigger events
- Добавлена команда kill_db_connections для завершения соединений БД
- Data migration нужно выполнить отдельно после применения схемы
- Изменено событие на длительность до конца дня вместо 2 дней
- Все ДР теперь добавляются в общий календарь '🎂 Дни рождения'
- Убрана логика личных календарей для каждого сотрудника
- Добавлена миграция 0011 для удаления FSM полей и добавления is_published
- Добавлена миграция 0012 для удаления is_published (не нужно)
- Добавлена миграция 0013 для удаления document_type
- Добавлена команда migrate_documents_storage для миграции файлов в django-filer
- Добавлена конфигурация django-filer в settings.py
- Настроены URL для filer admin
- Обновлен admin.py для работы с FilerFileField
- Обновлен индекс поиска для новой структуры
- Удалены поля document_type, status, published_at из модели Document
- Упрощены разрешения и правила доступа
- Удалены endpoint'ы для работы со статусами
- Удалены тесты FSM workflow
- Обновлены serializers для новой структуры модели
Added:
- is_not_document_uploader predicate
- Specific FSM action permissions (approve_document, publish_document, etc.)
- Tests for author cannot approve/publish own documents
Note: This is work in progress and will be reviewed/simplified after comparing with develop branch
- Added TestAuthorCanSubmitOwnDocument class with 3 tests
- test_author_can_submit_own_document_without_model_permission: verifies authors can submit their own documents via is_document_uploader predicate
- test_regular_user_cannot_submit_others_document: ensures users cannot submit others' documents
- test_author_can_edit_own_draft_document: confirms authors can edit their drafts
Benefits:
- Validates django-rules integration (is_document_uploader predicate)
- Ensures proper separation: authors manage own documents, not others'
- No model permissions required for basic author operations
All 91 tests passing ✅
- Modified DocumentReadOrModelPerms to allow 'create' action for all authenticated users
- Documents are created in DRAFT status by default (FSM workflow ensures control)
- Updated test_regular_user_access_according_to_policy to expect 201 instead of 403
- Added new test test_regular_user_can_create_document_in_draft
- Updated policy documentation in test file
Benefits:
- Encourages employee engagement in document management
- FSM workflow (draft → review → approve → publish) maintains quality control
- Approval/publish still requires change_document permission
- Regular users only see PUBLISHED documents (except their own)
All 88 tests passing ✅
- Added check for :memory: and test in DB name
- Prevents calendar_app → django-scheduler migration from running during tests
- Test DB name: file:memorydb_default?mode=memory&cache=shared
- Saves ~10 seconds per test run and eliminates migration output spam
Previously showed ~80 lines of migration logs on every test run.
- Changed return type from bool to Optional[Notification]
- In EAGER mode (tests), query and return created Notification
- In fallback mode, return created Notification object
- Fixes integration tests where code expected Notification object
Previously returned True/False which broke code expecting notification.id
attribute. Now properly returns the created Notification instance or None.
- Created test suite for all new ViewSets:
* DocumentTagViewSet (3 tests)
* DocumentTypeViewSet (2 tests)
* CabinetViewSet (4 tests)
* DocumentCommentViewSet (5 tests)
- Tests for related documents management (4 tests)
- Tests for django-reversion endpoints (2 tests)
- Integration test for complex document with all features
- Total: 21 test cases covering all new functionality
Tests use pytest fixtures for clean test data setup.
Tests cover CRUD operations, permissions, and edge cases.
- Added related_documents ManyToMany field to Document model
- Created DocumentComment model with threading support (parent/replies)
- Created DocumentCommentViewSet with CRUD and permission checks
- Added endpoints for related documents:
* GET /documents/{id}/related/ - list related documents
* POST /documents/{id}/add_related/ - add related document
* POST /documents/{id}/remove_related/ - remove related document
- DocumentComment features:
* Threading support via parent field
* Edit tracking (is_edited flag)
* Author-only deletion (or staff)
* Depth calculation for nested comments
- Created migration 0010 for new fields and model
- Registered DocumentCommentViewSet in router
All medium-priority features complete!
- Created DocumentTagViewSet with CRUD and document listing
- Created DocumentTypeViewSet with CRUD and filtering (active/inactive)
- Created CabinetViewSet for virtual document collections with hierarchy
- Added thumbnail endpoint to DocumentViewSet (GET /documents/{id}/thumbnail/?size=medium)
- Registered all new ViewSets in router:
* /api/v1/document-tags/
* /api/v1/document-types/
* /api/v1/cabinets/
- Thumbnail sizes: admin_thumbnail, small, medium, large
- All ViewSets support search and filtering
- Cabinet ViewSet has add_document/remove_document actions
This completes high-priority missing API endpoints for frontend.
- Added RevisionMiddleware to settings for automatic user tracking
- Created VersionSerializer and ActivityItemSerializer for version history
- Implemented GET /documents/{id}/versions/ endpoint
- Implemented GET /documents/{id}/activity/ endpoint (versions + audit + acknowledgements)
- Implemented POST /documents/{id}/revert/ endpoint for version rollback
- Activity timeline combines data from reversion, audit log, and acknowledgements
- All endpoints properly serialize user data with avatar support
This unblocks the Activity and Versions tabs in DocumentDetailModal.
PROBLEM:
- Upload form was minimal, not using full backend capabilities
- Missing: recipients, departments, acknowledgement requirement
- No folder indication when uploading to specific folder
SOLUTION - BACKEND:
- Added 'acknowledgement_required' field to DocumentWriteSerializer
- Now accepts: sent_to_all, department_ids, recipient_ids, acknowledgement_required
SOLUTION - FRONTEND:
Extended DocumentUploadForm with enterprise-grade features:
NEW FIELDS:
1. Sent to All Toggle
- Checkbox to send document to all employees
- When checked, hides recipients/departments selection
2. Recipients Section (when sent_to_all = false)
- Multi-select for departments (with Building2 icon)
- Multi-select for specific employees (with Users icon)
- Live loading from API
- Validation: requires at least one department OR recipient
- Helper text for Ctrl/Cmd multi-select
3. Acknowledgement Required
- Checkbox to require recipients to acknowledge reading
- Clear explanation of what it means
UX IMPROVEMENTS:
- Folder indicator: shows when uploading to specific folder
- Visual sections with dividers and headers
- Icons for each field type
- Warning when no recipients selected (amber alert)
- Better validation messages
- Reset all new fields on successful upload
API CLIENT:
- Updated createDocument signature to include acknowledgement_required
- Properly serializes checkbox values as strings
DATA LOADING:
- useEffect loads departments and employees on mount
- Loading states during fetch
- Handles empty lists gracefully
VALIDATION:
- Requires file and title (unchanged)
- NEW: When sent_to_all=false, requires departments OR recipients
- Shows user-friendly error messages
BENEFITS:
- Full feature parity with backend capabilities
- Professional document management workflow
- Granular control over document distribution
- Acknowledgement tracking from upload stage
- Better UX with progressive disclosure
Backend improvements:
- Add document_count annotation to FolderViewSet queryset
- Add document_count field to FolderSerializer
Frontend improvements:
- Add folder_path display in document cards with folder icon
- Add document count badges in folder tree
- Add breadcrumbs navigation showing current folder path
- Improve folder selector button to show selected folder name
- Add clear filter button (X) to folder selector
- Add highlighted style for selected folder in selector
- Update Document interface to include folder and folder_path fields
UI enhancements:
- Folder path shown in sky-blue color with FolderOpen icon in cards
- Document count displayed in gray badge next to folder names
- Breadcrumbs allow quick navigation back to root
- Selected folder highlighted with sky-blue background
- Visual feedback for folder selection state
Backend changes:
- Add acknowledgement_required field to Document model (migration 0009)
- Add FolderViewSet with CRUD endpoints for folder management
- Add folder_id filtering support in DocumentViewSet.get_queryset()
- Register folders endpoint in API router
Frontend changes:
- Add DocumentAcknowledgementsReport component for viewing acknowledgement status
- Add folder_id parameter to getDocuments API method
- Add currentFolderId prop to DocumentUploadForm
- Update document creation to save to selected folder
- Add folder filtering in documents list view
- Fix PDF worker loading (use local worker instead of CDN)
- Lock pdfjs-dist version to 5.4.296 to prevent conflicts
- Add postinstall script to copy PDF worker to public/
Features:
- Hierarchical folder structure with parent-child relationships
- Filter documents by selected folder
- Upload documents to specific folders
- View acknowledgement statistics with search and export
- Local PDF worker for reliable document preview