658 Commits

Author SHA1 Message Date
243fffc126 refactor: Restructure document card layout for better visual hierarchy
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.
2026-02-28 14:15:28 +03:00
11acea9ad0 feat: Extend DocumentUploadForm with full enterprise features
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
2026-02-28 14:04:27 +03:00
5b040f663c fix: Replace nested button with span in folder filter
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.
2026-02-28 14:00:03 +03:00
4025eb2b19 feat: Create modern DocumentDetailModal with tabs based on market analysis
Analyzed leading DMS solutions (Google Drive, Notion, Confluence, SharePoint, ClickUp)
and implemented enterprise-grade document modal with progressive disclosure.

NEW COMPONENT:
- DocumentDetailModal.tsx - modern tabbed interface for document details

STRUCTURE:
- Fixed header with title, metadata, quick actions, status badge
- Tab navigation: Overview | Activity | Acknowledgements | Versions
- Full-screen modal with optimized layout

TAB: OVERVIEW
- 2-column layout (66% main content, 33% sidebar)
- Document preview (images, PDF iframe, file icon fallback)
- Description section
- Workflow actions
- Sidebar with:
  • Author & dates (created, modified)
  • Folder location (breadcrumbs)
  • Tags (color badges)
  • Recipients (departments + individuals)

TAB: ACTIVITY
- Timeline placeholder for workflow events
- Ready for integration with django-reversion API
- Shows created/published events

TAB: ACKNOWLEDGEMENTS
- Reuses existing DocumentAcknowledgement component
- Progress visualization
- User list with status

TAB: VERSIONS
- Placeholder for version history
- Ready for integration with django-reversion API

IMPROVEMENTS:
- Progressive disclosure - info organized in tabs, not overwhelming
- Visual hierarchy - preview is focal point, actions always visible
- Quick actions - Open, Download, Share in header
- Rich metadata - type, size, dates, location, tags, recipients
- Scalable structure - easy to add new tabs (comments, related docs)

TYPES:
- Added document_type field (id, name, description) to Document interface
- Added tags field (id, name, color) to Document interface

DOCUMENTATION:
- docs/guides/MODERN_DOCUMENT_UI.md - comprehensive guide
- Market analysis of 5+ leading DMS solutions
- Architecture decisions and UX improvements
- Integration roadmap with django-reversion
- Future features: comments, related documents, @mentions

BENEFITS:
- Enterprise-level UX matching Confluence/SharePoint standards
- All document info accessible without context switching
- Transparent workflow and history (after backend integration)
- Modular and extensible architecture
2026-02-28 13:46:58 +03:00
8ab14d79a1 feat: Make thumbnail conditional on fullscreen mode
- 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
2026-02-28 13:41:21 +03:00
640584be30 feat: Add two-column layout to document details modal
- 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
2026-02-28 13:37:38 +03:00
cea3db4203 feat: Enhance document details modal with comprehensive metadata
- 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
2026-02-28 13:36:25 +03:00
23e122e2b5 fix: Remove duplicate max-h-[90vh] in Modal container
The max-h-[90vh] class was duplicated:
- Once in the hard-coded className
- Once in modalSizeClass variable

Now it only comes from modalSizeClass, avoiding CSS duplication
2026-02-28 13:32:50 +03:00
ba8cee22d3 refactor: Align Modal component with project-wide style
Changes to match existing modal patterns:
- Update z-index from z-50 to z-[100] for consistency
- Add backdrop-blur-sm to backdrop for modern glass effect
- Change shadow-2xl to shadow-xl (project standard)
- Move max-h-[90vh] to container level (not content div)
- Move overflow-y-auto to container for proper scrolling
- Update close button from rounded-lg to rounded-full
- Change button padding from p-2 to p-1 for tighter look
- Remove border-b from header, use mb-4 instead
- Change h2 to h3 for header title (semantic hierarchy)
- Add bottom padding div for proper spacing

Style now matches CalendarModal, EventModal, and ViewEventDetailsModal patterns
2026-02-28 13:29:08 +03:00
a92a7dcdcd feat: Improve modal functionality with advanced UX features
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
2026-02-28 13:22:42 +03:00
6def6d2d43 feat: Improve folders UI with breadcrumbs and document counts
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
2026-02-28 13:15:06 +03:00
f4b5b75c01 feat: Implement folder-document integration and acknowledgements UI
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
2026-02-28 13:06:41 +03:00
8e872b3593 feat(documents): Full integration - Folder Tree + All Phase 4 components
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
2026-02-28 09:51:37 +03:00
ec7d046d44 docs: Update Phase 4 status in master plan
- Mark Phase 4 as complete ✅
- Update comparison table (16/17 features complete)
- Add link to detailed Phase 4 report
- Update advantages list with Phase 4 achievements
- Postpone PDF Annotations to Phase 6
2026-02-28 09:44:45 +03:00
7a8d085867 docs: Add Phase 4 completion report
Phase 4: Advanced Features - Complete! ✅

Report includes:
- Detailed breakdown of all 5 deliverables
- Code statistics (2000+ lines)
- Git commit history
- Usage examples for all components
- Next steps (Phase 5 & 6)
2026-02-28 09:43:50 +03:00
d3abf1ad67 feat(documents): Add Batch Operations and Dashboard
Phase 4 Advanced Features complete!

- Created BulkActionsToolbar component with features:
  * Multi-select documents with checkboxes
  * Batch actions: move to folder, add tags, change status, delete
  * Real-time progress tracking for batch operations
  * Undo notification with 5-second timeout
  * useDocumentSelection hook for state management

- Created DocumentsDashboard component with features:
  * Statistics cards: total docs, my docs, approved, activity
  * Line chart: uploads over last 30 days (recharts)
  * Pie chart: document type distribution
  * Bar chart: document status distribution
  * Activity feed: recent uploads, edits, status changes
  * Quick access sections: Recent, Favorites, My Documents
  * Responsive grid layout

Total Phase 4 Deliverables:
  1. ✅ Client-side processing integration into upload form
  2. ✅ Enhanced PDF Viewer with zoom, rotate, page navigation
  3. ✅ Advanced Search with filters and saved searches
  4. ✅ Batch Operations with progress tracking
  5. ✅ Dashboard & Analytics with charts
2026-02-28 09:42:08 +03:00
9e1a1d4138 feat(documents): Add Enhanced PDF Viewer and Advanced Search
- Created EnhancedPDFViewer component with features:
  * Page navigation with keyboard shortcuts
  * Zoom in/out (0.5x - 3.0x)
  * Rotate pages clockwise
  * Fit to width / Fit to page modes
  * Thumbnail sidebar for quick navigation
  * Search functionality (Ctrl+F)
  * Print support (Ctrl+P)
  * Fullscreen modal overlay

- Created AdvancedSearch component with features:
  * Full-text search with fuzzy matching (fuse.js)
  * Multiple filters: document type, status, tags, date range, author
  * Sort options: relevance, date, title, author
  * Saved searches (localStorage)
  * Results with highlighted matches
  * Active filter badges
  * Mobile-responsive grid layout
2026-02-28 09:38:57 +03:00
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
047e1c1763 feat(frontend): Phase 2 & 3 - Client-side document processing utilities
Created comprehensive document processing library:

� src/lib/document-utils/
├── processor.ts - Главный процессор (интеллектуальная обработка)
├── ocr.ts - OCR через Tesseract.js (rus+eng)
├── pdf.ts - PDF операции (extract text, thumbnail, split, merge, rotate)
├── docx.ts - DOCX извлечение текста (mammoth.js)
├── image.ts - Image processing (compress, crop, rotate, thumbnail)
└── index.ts - Экспорты

Возможности:
✅ Автоматическое определение типа файла
✅ OCR для изображений (client-side, не нагружает сервер)
✅ Извлечение текста из PDF и DOCX
✅ Сжатие изображений перед загрузкой
✅ Генерация thumbnails
✅ Progress callbacks для UI
✅ Оценка времени обработки
✅ TypeScript типы для всех функций

Преимущества перед server-side:
- Моментальная обратная связь
- Не нагружает backend
- Приватность (файл не уходит на сервер до загрузки)
- Экономия трафика (сжатие до отправки)
- Можно показать preview extracted text ДО upload

Phase 2 & 3 Complete!
2026-02-28 09:29:47 +03:00
82762d3ce4 feat(frontend): Install DMS libraries for client-side processing
Added libraries:
- tesseract.js: Client-side OCR (rus+eng)
- pdf-lib: PDF operations (split, merge, rotate)
- mammoth: DOCX text extraction
- fuse.js: Client-side fuzzy search
- reactflow: Workflow visualization
- recharts: Dashboard charts
- react-signature-canvas: Digital signatures
- @dnd-kit: Advanced drag & drop

Phase 2: Frontend Foundation started
2026-02-28 09:27:38 +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
856e08db4a fix(documents): Исправлена кнопка открытия файла и удален document_type
- Добавлена закрывающая скобка } в onClick handler
- Добавлено содержимое кнопки с иконкой Eye
- Удален блок отображения document_type (поле не существует в модели)
2026-02-28 08:48:39 +03:00
15e1367042 fix(documents): Исправлена синтаксическая ошибка в page.tsx
- Добавлен пропущенный символ < в открывающем теге div
- Удалена проверка на несуществующее поле doc.tags
2026-02-28 08:47:48 +03:00
1a86e61341 fix(documents): Упрощение формы загрузки - удалены document_type и tags
- Убраны поля document_type и tags из DocumentUploadForm
- Обновлен API клиент: createDocument и updateDocument без этих полей
- Обновлены TypeScript типы в api.ts
- Убраны document_type и tags из отображения в documents/page.tsx
- Форма теперь принимает только: title, description, file
2026-02-28 08:45:47 +03:00
0b88d05094 fix(documents): Исправление polymorphic_ctype_id для filer.File
- Создана management команда fix_filer_polymorphic
- Использует прямой SQL для обновления polymorphic_ctype_id
- Исправляет ошибку PolymorphicTypeUndefined при GET /api/v1/documents/
- Обработано 22 файла в базе данных
2026-02-28 08:34:50 +03:00
12f3b7b81b feat(frontend): Полная интеграция документов с django-filer и django-fsm
- Установлены библиотеки: react-dropzone, react-pdf, pdfjs-dist, react-file-icon, @tanstack/react-table
- Обновлены TypeScript типы для Document + FSM статусы
- Обновлен API клиент: CRUD операции, FSM переходы, подтверждение прочтения
- Создан DocumentUploadForm: drag&drop загрузка файлов
- Создан DocumentStatusBadge: цветные статусы (draft/in_review/approved/published/archived/rejected)
- Создан DocumentWorkflowButtons: динамические кнопки FSM переходов
- Создан DocumentPreview: встроенный просмотр PDF с навигацией
- Создан DocumentAcknowledgement: подтверждение прочтения с комментариями
- Обновлена страница documents: фильтры, модальные окна, workflow UI
- Добавлена документация в DOCUMENTS_IMPLEMENTATION.md
2026-02-28 08:30:11 +03:00
33ce8d646e docs: добавлена документация по django-fsm workflow
- Диаграмма переходов между состояниями
- Примеры использования в коде и API
- Интеграция с уведомлениями
- Тестирование и расширение функционала
2026-02-28 01:34:24 +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
14e4d0e0ce docs: добавлен отчет о завершении рефакторинга documents
- Описание процесса рефакторинга
- Статистика изменений (12 файлов, -636 строк)
- Результаты миграции (23/23 документов)
- Покрытие тестами (16/16 тестов проходит)
- Рекомендации по дальнейшим шагам
2026-02-28 01:11:31 +03:00
3e99bfc4b2 fix(documents): Remove unsupported send_immediately parameter
- Fixed TypeError in create_notification_async() call
- Removed send_immediately parameter (only supported by create_notification)
- All 16 tests now pass
2026-02-28 01:10:21 +03:00
499fcb1e78 refactor(documents): Consolidate filer-based models as primary
- Replaced models.py with filer version (FilerFileField)
- Replaced admin.py with full filer admin (thumbnails, previews, file info)
- Replaced rules.py with updated django-rules predicates
- Replaced tests.py with comprehensive test suite (298 lines, 16 tests)
- Deleted duplicate V2 files: models_v2.py, admin_v2.py, rules_v2.py, tests_v2.py
- Deleted management/commands/migrate_to_filer.py (no longer needed)
- Created migration 0005_migrate_to_filer.py with data migration:
  * Migrated 23 existing documents from FileField to FilerFileField
  * Dropped DocumentV2 and DocumentAcknowledgementV2 models

Breaking changes: None (V2 models removed, primary models enhanced)
Migration applied: All 23 documents successfully migrated to django-filer
2026-02-28 01:05:20 +03:00
b5a1f99ef8 docs: добавлен отчет по интеграции django-filer
Подробный отчет о выполненной работе по интеграции django-filer:
- Установленные пакеты и зависимости
- Изменения в конфигурации
- Описание созданных файлов
- Статистика кода и сокращение
- План миграции (6 фаз)
- Преимущества решения
- Проверка работоспособности

Файл: docs/in-progress/DJANGO_FILER_INTEGRATION.md (550+ строк)
2026-02-28 00:38:01 +03:00
49eff37671 feat(documents): Интеграция django-filer для управления файлами
Добавлена поддержка django-filer для профессионального управления файлами в приложении documents.

Что добавлено:
- models_v2.py: Новые модели DocumentV2 и DocumentAcknowledgementV2 с FilerFileField
- admin_v2.py: Django admin с drag & drop загрузкой и превью thumbnails
- rules_v2.py: Правила доступа django-rules для новых моделей
- tests_v2.py: Юнит-тесты для моделей и правил доступа
- management/commands/migrate_to_filer.py: Команда для миграции данных из старых моделей

Настройки:
- settings.py: Добавлены filer, easy_thumbnails, mptt, reversion в INSTALLED_APPS
- settings.py: Настроены THUMBNAIL_PROCESSORS и THUMBNAIL_ALIASES
- requirements.txt: Добавлены django-filer==3.4.4, easy-thumbnails==2.10.1, django-mptt==0.18.0, django-reversion==6.1.0

Документация:
- docs/reports/DOCUMENTS_REPLACEMENT_ANALYSIS.md: Анализ вариантов замены приложения documents

Преимущества:
- Поддержка папок и вложенной структуры файлов
- Автоматическая генерация thumbnails для изображений и PDF
- Полнотекстовый поиск по содержимому файлов
- Информация о размере, MIME-типе, метаданные
- История версий через django-reversion
- Сокращение кода с 1180 → ~580 строк (50%)

Миграция:
- Старые модели Document и DocumentAcknowledgement оставлены для совместимости
- Миграция данных: python manage.py migrate_to_filer
- После проверки старые модели можно удалить

Связанные issues: #N/A
Тип изменений: Feature
Область: documents, file management
2026-02-28 00:36:17 +03:00
01f0cce2c6 Merge branch 'feature/django-rules' into develop 2026-02-28 00:16:35 +03:00
7e4c693211 feat: добавлены правила для 5 приложений (requests, communications, calendar, procurement, feed)
- requests_app/rules.py: 8 предикатов + 10 правил
  * Предикаты: is_request_author, is_request_assignee, can_manage_requests и др.
  * Правила: view/change/delete/assign/approve requests, комментирование, статистика

- communications/rules.py: 9 предикатов + 15 правил
  * Предикаты: is_chat_member, is_chat_owner, is_chat_admin, is_message_author и др.
  * Правила: view/send/change/delete чаты и сообщения, управление участниками, закрепление
  * Включены примеры для WebSocket consumers

- calendar_app/rules.py: 9 предикатов + 12 правил
  * Предикаты: is_calendar_owner, is_personal_calendar, has_calendar_access и др.
  * Правила: view/change/delete календари и события, подписки, экспорт iCal, приглашения

- procurement/rules.py: 8 предикатов + 13 правил
  * Предикаты: is_procurement_manager, is_purchase_request_author, can_approve_purchases и др.
  * Правила: view/change/delete заявки на закупку, управление поставщиками и договорами

- feed/rules.py: 8 предикатов + 11 правил
  * Предикаты: is_post_author, can_publish_posts, can_moderate_posts и др.
  * Правила: view/create/change/delete посты, публикация, закрепление, комментирование, реакции

Во всех apps.py добавлен импорт rules для автозагрузки правил при старте Django
2026-02-28 00:13:46 +03:00
967819a58f feat: интеграция django-rules для object-level permissions
- Установлен пакет rules==3.5
- Добавлен ObjectPermissionBackend в AUTHENTICATION_BACKENDS
- Созданы базовые правила для employees:
  * Предикаты: is_hr_staff, is_department_head, is_own_profile и др.
  * Правила: view/change/delete employee, view reports и контакты
- Созданы базовые правила для documents:
  * Предикаты: is_document_owner, has_document_access, can_approve и др.
  * Правила: view/change/delete/approve/publish/share documents
- Правила регистрируются в apps.py (ready() метод)
- Создана подробная документация с примерами использования
  * В views, templates, DRF permissions, Django Admin
  * Сценарии: многоуровневое согласование, временные ограничения
  * Сравнение с django-guardian, отладка, тестирование

Документация: docs/guides/DJANGO_RULES_INTEGRATION.md
2026-02-28 00:07:53 +03:00
f1135dfe8a docs: анализ замены кастомных модулей на библиотеки
- Добавлен django-service-objects==0.7.1 в requirements.txt
- Создан отчёт LIBRARY_REPLACEMENT_ANALYSIS.md с рекомендациями:
  * django-cacheops → замена common/cache_decorators.py
  * django-post-office → замена common/emails.py
  * easy-thumbnails → замена common/image_utils.py
  * django-rules → улучшение permissions
  * requests-cache → кэширование внешних API

План внедрения по фазам с метриками и приоритетами.
Impact: снижение кастомного кода с ~360 до ~50 строк.

Refs: #tech-debt #modernization
2026-02-27 23:51:02 +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
04cbd5d58a Merge feature/django-push-notifications into develop
Интеграция системы уведомлений:
- Backend: django-push-notifications 3.1.0
- Frontend: NotificationCenter + Web Push + Sonner
- Миграция данных: 9 подписок перенесено
- Производительность: ожидается 10-50x ускорение

Полная документация:
- backend/docs/reports/DJANGO_PUSH_NOTIFICATIONS_INTEGRATION.md
- frontend/NOTIFICATIONS_IMPLEMENTATION.md
2026-02-27 20:08:02 +03:00
38a027379d style: обновлены стили NotificationCenter под дизайн AppShell
Изменения:
- Кнопка: rounded-full как в AppShell, размер h-10 w-10
- Иконка Bell: size={18}, text-gray-600
- Badge: компактный дизайн -top-0.5 -right-0.5, размер 16px
- Dropdown: rounded-xl, shadow-lg ring-1 ring-slate-100
- Цвета: sky вместо blue (sky-600, sky-50, sky-700)
- Фон: slate-50/slate-100 вместо gray-50/gray-100
- Границы: border-slate-100
- Размеры текста: уменьшены для компактности (text-xs, text-[10px])
- Padding: уменьшен для более плотного размещения (p-3 вместо p-4)
- Точка непрочитанных: w-1.5 h-1.5 вместо w-2 h-2

Адаптивность:
- Добавлен variant prop ('default' | 'mobile')
- Мобильная версия: border + bg-gray-50 (как другие кнопки)
- Адаптивная ширина: w-80 sm:w-96
- AppShell: передан variant='mobile' для мобильной версии
2026-02-27 19:57:19 +03:00
acc511f4b8 fix: исправлена ошибка notifications.slice is not a function
- Добавлена проверка Array.isArray() в NotificationCenter
- Добавлена защита от non-array в useNotifications хук
- Исправлен импорт date-fns/locale для версии 4+
- В случае ошибки API устанавливается пустой массив []
2026-02-27 19:41:20 +03:00
98a5095b0e feat: реализована система уведомлений на фронтенде
Frontend:
- Установлен Sonner для toast уведомлений
- Создан Service Worker (public/sw.js) для Web Push
- Реализован хук useWebPush для управления подписками
- Добавлены утилиты Web Push (lib/push.ts)
- Создан компонент NotificationCenter с UI
- Интегрирован в AppShell (header desktop + mobile)
- Добавлен Toaster в Providers

API методы:
- getVapidPublicKey() - получение VAPID ключа
- subscribePush() - создание подписки
- unsubscribePush() - удаление подписки
- getPushSubscriptions() - список подписок

Возможности:
- � Web Push (работают даже когда вкладка закрыта)
- � NotificationCenter с badge и историей
- � Toast уведомления (Sonner)
- ⚙️ Настройки push подписок
- � Респонсивный дизайн

Документация: frontend/NOTIFICATIONS_IMPLEMENTATION.md
2026-02-27 19:39:13 +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
5806811d88 Merge feature/replace-search-with-django-watson into develop
Расширение поиска: добавлены модели procurement, documents, notifications, schedule.
Всего 12 моделей доступны для полнотекстового поиска через django-watson.
2026-02-27 19:02:45 +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
8eed7bd654 feat: Replace custom search with django-watson
- Installed django-watson 1.6.3
- Added watson to INSTALLED_APPS
- Created search_indexes.py with model registrations:
  * Post (title, body)
  * Employee (name, email, phone)
  * Department (name, description)
  * Request (title, comment)
  * Chat (name, description)
  * Message (content)
  * CalendarEvent (title, description)
- Replaced search/views.py (484 lines → 158 lines)
- Applied watson migrations and built search indexes (1015 entries)
- Tested search functionality

Benefits:
- 67% code reduction (326 lines removed)
- Better search relevance with full-text indexing
- Automatic ranking and highlighting
- Less maintenance burden
2026-02-27 18:12:21 +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