Frontend изменения:
- Оптимизирована загрузка уведомлений: только 50 unread для badges
- Упрощены проверки is_read в AppShell и NotificationCenter
- Разделены useNotifications (для badges) и notifications page (для списка)
- Добавлены визуальные индикаторы в список чатов (badges, pin, notifications)
- Улучшена сортировка: закрепленные чаты показываются первыми
Связано с backend оптимизацией denormalized unread_count
- 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.
- Добавлен маппинг категорий на эмодзи-иконки
- Исправлено отображение текста вместо иконок (bi-chat-dots -> 💬)
- Увеличен размер иконок (text-xl)
- Добавлены эмодзи для всех основных категорий
- Полный список всех уведомлений с прокруткой
- Поиск по заголовку и содержимому
- Фильтрация по статусу (все/непрочитанные/прочитанные)
- Фильтрация по категориям
- Кнопка "Прочитать все" для непрочитанных
- Красивые карточки с иконками категорий
- Клик на уведомление переходит по action_url
- Responsive дизайн
- Удалена кнопка 'Загрузить ещё'
- Реализована автоматическая подгрузка через Intersection Observer API
- Данные начинают загружаться за 100px до конца списка
- Учитываются все фильтры и поиск
- Добавлен индикатор загрузки при подгрузке данных
Доработан DocumentDetailModal:
- Добавлен встроенный предпросмотр PDF и изображений
- Добавлен полноэкранный режим для предпросмотра (desktop)
- Добавлены вкладки: Предпросмотр, Информация, Активность, Ознакомления, Комментарии, Связанные
- Добавлены пропсы: onEditMetadata, onViewReport, onNavigateToRelated
- Интегрированы DocumentComments и DocumentRelated
- Улучшена шапка с полной информацией о документе на мобильных
Desktop layout:
- Split-view: предпросмотр слева (60%), вкладки справа
- Кнопка полноэкранного режима
Mobile layout:
- Вкладочная навигация
- Все метаданные видны в шапке (имя файла, размер, дата, автор)
Оптимизация page.tsx:
- Заменен встроенный модал (270 строк) на компонент DocumentDetailModal
- Удалены ненужные импорты DocumentAcknowledgement, DocumentComments, DocumentRelated
- Уменьшен размер с 1199 до 952 строк (-247 строк, -21%)
PROBLEM:
- Document cards had unstructured layout with all elements mixed together
- No clear visual separation between sections
- Poor readability and cluttered appearance
- Actions scattered without logical grouping
SOLUTION:
Completely restructured document cards into 3 distinct sections:
1. HEADER (with light background and border-bottom)
- Checkbox + Title (h3 with semibold)
- Status badges (primary + acknowledgement)
- Quick action buttons (Preview/PDF + Details) on the right
- Improved: Buttons now have solid backgrounds (bg-sky-100, bg-gray-100) for better visibility
2. BODY (main content area)
- Description (only if exists, with better line-height)
- Metadata grid (3 columns on large screens):
• Folder location (sky background with FolderOpen icon)
• Author (gray background with User icon)
• Created date (gray background with Calendar icon)
- Workflow actions (only for draft/review/approved/rejected states)
- Better spacing and visual hierarchy
3. FOOTER (conditional, only when needed)
- Shows only if document has acknowledgement requirement OR is published/archived
- Acknowledgement actions (Ознакомиться + Ведомость buttons)
- Workflow for published/archived states (aligned right)
- Light background matching header
IMPROVEMENTS:
- Clear visual sections with borders and backgrounds
- Metadata in colored pill-shaped cards instead of plain text
- Icons for all metadata fields (folder, user, calendar)
- Removed redundant 'Updated' field (not essential)
- Removed empty description text ('Описание не заполнено')
- Better button hierarchy: primary actions in header, secondary in footer
- Larger, more clickable buttons (px-3 py-1.5 instead of px-2.5 py-1)
- Consistent rounded-lg instead of mix of rounded-full/rounded-lg
- Better hover states (bg-sky-200 instead of bg-sky-100)
- Conditional rendering: footer only appears when necessary
VISUAL DESIGN:
- Header: bg-gray-50/50 with border-bottom
- Body: white background, clean content area
- Footer: bg-gray-50/50 with border-top
- Metadata cards: colored backgrounds (sky-50 for folder, gray-50 for others)
- Better border colors: border-gray-200 instead of border-gray-100
This matches the structure of modern DMS systems like Notion, Confluence, and Google Drive where cards have clear header/body/footer separation.
Fixed React hydration error caused by button nested inside button.
ISSUE:
- Console error: 'In HTML, <button> cannot be a descendant of <button>'
- Folder dropdown button contained a reset filter button inside it
- This is invalid HTML and causes hydration mismatch
SOLUTION:
- Changed inner button to span element
- Added cursor-pointer for visual feedback
- Added role="button" for accessibility
- Added tabIndex={0} for keyboard navigation
- Added onKeyDown handler for Enter/Space key support
- Maintains full functionality and accessibility
LOCATION:
- frontend/src/app/documents/page.tsx:255-267
- Folder filter reset button
The fix ensures proper HTML structure while preserving all interactive functionality and accessibility features.
- Changed Modal component to support render prop pattern (children as function)
- Modal children can now receive isFullscreen state as parameter
- Changed modal size from 'xl' to 'lg' for compact default view
- Thumbnail now only shows when modal is in fullscreen mode
- In normal mode: single column with metadata and 'Open file' button
- In fullscreen mode: two columns with metadata (left) and thumbnail (right)
- Provides progressive disclosure: compact view first, expanded view on demand
- Left column: metadata and information (2/3 width)
- Right column: document thumbnail preview (1/3 width)
- Thumbnail supports: images (direct display), PDFs (iframe), other files (icon placeholder)
- Added 'Open in full size' button in thumbnail section
- Removed separate file open button from main content
- Sticky positioning for thumbnail on scroll
- Responsive: single column on mobile, two columns on large screens
- Changed modal size from 'lg' to 'xl' for better layout
- Added metadata grid with author, creation date, file info, and file size
- Added folder location section with FolderOpen icon
- Enhanced recipients section with departments and individual recipients
- Added visual indicators with colored icon badges
- Improved layout with better spacing and visual hierarchy
- File open button now full-width for better visibility
- Shows up to 10 individual recipients with overflow indicator
New features:
- Create reusable Modal component with animations
- Add useModal hook for common modal behaviors
- Add useClickOutside hook for backdrop clicks
- Implement ESC key handling for all modals
- Add focus trap to prevent focus escaping modals
- Add body scroll locking when modals are open
- Add fullscreen toggle option for modals
- Add fade-in/scale animations for smooth transitions
Modal improvements:
- Upload modal: converted to use new Modal component
- Document details modal: converted to use new Modal component
- Create folder modal: converted to use new Modal component
- Acknowledgements report: enhanced with modal hooks
Technical details:
- Modal sizes: sm, md, lg, xl, full
- Configurable close behavior (ESC, click outside, close button)
- Automatic scrollbar width compensation
- Focus restoration after modal close
- Accessible with ARIA attributes and keyboard navigation
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
MAJOR UPDATE: Complete documents page overhaul with all advanced features!
Frontend Integration:
- Created FolderTree component (hierarchical folder navigation)
- Added sidebar with folders and quick navigation
- Integrated Dashboard view (toggle between Documents/Dashboard)
- Added Advanced Search toggle (simple/advanced modes)
- Integrated BulkActionsToolbar with multi-select checkboxes
- Added EnhancedPDFViewer for PDF files
- Select All checkbox for bulk operations
- Folder filtering support
New Components:
- FolderTree: Expandable tree with CRUD actions
- Sidebar: Folders + Quick navigation menu
- View Modes: Documents | Dashboard tabs
Updated documents/page.tsx:
- 2-column layout: Sidebar + Main content
- Bulk selection with useDocumentSelection hook
- Enhanced PDF preview for .pdf files
- Regular preview for other files
- Folder-based filtering
- Toggle sidebar visibility
- All Phase 4 components integrated
Features Now Available:
✅ Hierarchical folder navigation
✅ Bulk operations (select all, multi-select)
✅ Enhanced PDF viewer with zoom/rotate/search
✅ Advanced search with filters
✅ Dashboard with analytics
✅ Document acknowledgements (already present)
✅ Workflow buttons
✅ Status filtering
What Users Can Now See:
1. Folder tree in sidebar
2. Documents with checkboxes
3. Bulk actions toolbar when items selected
4. Advanced search option
5. Dashboard tab
6. Enhanced PDF viewer for PDFs
7. Select all functionality
Branch: feature/django-filer-documents
- Добавлена закрывающая скобка } в onClick handler
- Добавлено содержимое кнопки с иконкой Eye
- Удален блок отображения document_type (поле не существует в модели)
- Убраны поля document_type и tags из DocumentUploadForm
- Обновлен API клиент: createDocument и updateDocument без этих полей
- Обновлены TypeScript типы в api.ts
- Убраны document_type и tags из отображения в documents/page.tsx
- Форма теперь принимает только: title, description, file
- Добавлены 5 новых моделей в watson search:
* ProcurementRequest (заявки на закупку)
* Equipment (оборудование)
* Document (документы)
* Notification (уведомления)
* Event из django-scheduler (расписание)
- Backend API: форматтеры для новых типов моделей
- Frontend: добавлены иконки и названия для новых типов
- Тесты: исправлены фикстуры, все 13 тестов проходят
- Индексы: 3895 записей проиндексировано
Итого: 12 моделей доступны для полнотекстового поиска
- Добавлены 5 новых моделей в watson search:
* ProcurementRequest (заявки на закупку)
* Equipment (оборудование)
* Document (документы)
* Notification (уведомления)
* Event из django-scheduler (расписание)
- Backend API: форматтеры для новых типов моделей
- Frontend: добавлены иконки и названия для новых типов
- Тесты: исправлены фикстуры, все 13 тестов проходят
- Индексы: 3895 записей проиндексировано
Итого: 12 моделей доступны для полнотекстового поиска
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)
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)
- Удалено поле 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)
- Удалено поле 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)
- Добавлены API методы в api.ts:
* getChats, getChat, createChat
* getChatMessages, sendMessage, sendMessageWithFiles
* updateMessage, deleteMessage
* markChatAsRead, togglePinChat, toggleChatNotifications
- Создан компонент NewChatModal:
* Поиск и выбор сотрудников
* Поддержка приватных и групповых чатов
* Автоматическое название для групп
- Интегрирована кнопка 'Новый чат' в Chatscope UI
- При создании чата автоматически открывается диалог
- Добавлены API методы в api.ts:
* getChats, getChat, createChat
* getChatMessages, sendMessage, sendMessageWithFiles
* updateMessage, deleteMessage
* markChatAsRead, togglePinChat, toggleChatNotifications
- Создан компонент NewChatModal:
* Поиск и выбор сотрудников
* Поддержка приватных и групповых чатов
* Автоматическое название для групп
- Интегрирована кнопка 'Новый чат' в Chatscope UI
- При создании чата автоматически открывается диалог
- Установлены пакеты @chatscope/chat-ui-kit-react и @chatscope/chat-ui-kit-styles
- Создана новая страница /messages-chatscope с полнофункциональным мессенджером
- Добавлен пункт 'Мессенджер (NEW)' в навигационное меню
- Реализована интеграция с существующим Django API
- Добавлена поддержка WebSocket для real-time сообщений
- Список чатов с поиском и аватарами
- Отображение сообщений с датами и вложениями
- Индикатор 'печатает...' через WebSocket
- Установлены пакеты @chatscope/chat-ui-kit-react и @chatscope/chat-ui-kit-styles
- Создана новая страница /messages-chatscope с полнофункциональным мессенджером
- Добавлен пункт 'Мессенджер (NEW)' в навигационное меню
- Реализована интеграция с существующим Django API
- Добавлена поддержка WebSocket для real-time сообщений
- Список чатов с поиском и аватарами
- Отображение сообщений с датами и вложениями
- Индикатор 'печатает...' через WebSocket
- Добавлен CustomToolbar для BigCalendar со стрелками навигации
- Выпадающий список для выбора вида календаря
- Management command для создания тестовых пользователей и календарей
- Создано 3 тестовых пользователя (anna_ivanova, petr_petrov, maria_sidorova)
- Создано 5 календарей с 11 событиями
- Убраны подписки (они для старой системы calendar_app)
- Исправлены стили тулбара BigCalendar
- Модалы календаря рендерятся на корневом уровне AppShell
- Добавлен CustomToolbar для BigCalendar со стрелками навигации
- Выпадающий список для выбора вида календаря
- Management command для создания тестовых пользователей и календарей
- Создано 3 тестовых пользователя (anna_ivanova, petr_petrov, maria_sidorova)
- Создано 5 календарей с 11 событиями
- Убраны подписки (они для старой системы calendar_app)
- Исправлены стили тулбара BigCalendar
- Модалы календаря рендерятся на корневом уровне AppShell
- 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
- 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
- Добавлен компонент AppShell с Header, Sidebar, Calendar
- Установлен lucide-react для современных иконок
- Обновлены все страницы: главная, login, employees, documents, etc
- Единый дизайн с PageHeader и переиспользуемыми элементами
- Улучшенная навигация с активными ссылками
- Responsive design с sticky элементами
- Градиентный фон и современные shadow/ring эффекты