75 Commits

Author SHA1 Message Date
bd44efb218 отмена изменений админки 2025-11-20 13:01:34 +03:00
30e6643b6e Исправлена админка для редактирования дат created_at/updated_at
- Добавлены явные поля в EmployeeChangeForm для дат с виджетами datetime-local
- Переопределен метод save_model для обхода auto_now/auto_now_add
- Используется прямое обновление через queryset для изменения неизменяемых полей
- Только superuser может редактировать эти поля
2025-11-20 12:57:33 +03:00
6dfb19e576 Добавлена возможность редактирования дат создания/обновления в админке
- Superuser теперь может редактировать created_at и updated_at
- Обычные администраторы видят эти поля как readonly
- Добавлен метод get_readonly_fields для динамического контроля прав
2025-11-20 12:54:49 +03:00
eb5fb926a1 Исправлена фильтрация новых сотрудников и центрирование карусели
- Добавлен фильтр created_at__gte в EmployeeViewSet API
- Исправлен параметр is_active -> active в запросе к API
- Добавлено центрирование карусели новых сотрудников (justify-content: center)
- Обновлена документация API endpoints
2025-11-20 12:54:01 +03:00
5cda78b49b Add modal for department creation
- Create modal_create_department.html component with simple form (name, description)
- Create createDepartmentModal.js handler for form submission via API
- Update department_list.html to use modal instead of link
- Modal integrates with API v1/departments/ endpoint
- Includes validation, error handling, and success notifications
- Now both employees and departments use consistent modal creation pattern
2025-11-20 09:52:34 +03:00
9f6bb5100d Unify styles for create card button and link in page_header
- Add 'border-0 bg-transparent' classes to create_url link
- Now both create_modal (button) and create_url (link) have identical styling
- Fixes visual inconsistency between employees list (modal) and departments list (link)
2025-11-20 09:42:26 +03:00
b9d66d0026 Fix document_list.html template syntax error
- Fix incorrect nesting of {% with %} and {% if %} blocks
- Move {% include %} inside both if/else branches
- Directly pass 'docCreateModal' or empty string without intermediate variable
2025-11-20 09:34:43 +03:00
df8a59dde5 Fix feed_list.html template syntax error
- Fix incorrect nesting of {% with %} and {% if %} blocks
- Move {% include %} inside both if/else branches to properly close with blocks
- Each branch now has its own include with appropriate create_url value
2025-11-20 09:33:58 +03:00
e171d2fd59 Fix template syntax errors in page_header integration
- Fix department_list.html: use variable for create_url instead of inline yesno with url tag
- Fix feed_list.html: properly handle conditional create_url with with blocks
- Fix document_list.html: use variable for create_modal instead of inline yesno
- Fix request_list_full.html: simplify scope toggle by placing it separately after header

Django templates don't allow nested template tags in include parameters,
so we now prepare variables beforehand using if/with blocks.
2025-11-20 09:32:25 +03:00
8618b7022f Integrate page_header component across all list pages
- Fix bug in page_header.html: add # to data-bs-target for card create button
- Integrate page_header in department_list.html with search and create card
- Integrate page_header in feed_list.html (no search, staff-only create button)
- Integrate page_header in document_list.html with Mine/All scope toggle
- Integrate page_header in request_list_full.html with filters and scope toggle
- Integrate page_header in chat_list.html with search
- Create _filters.html template for requests_app
- Add page-header.css to all integrated templates for consistent styling
2025-11-20 09:28:28 +03:00
d078b2f50b Merge master and ldap-writeback: added LDAP optional mode, refactored templates and JavaScript modules 2025-11-20 09:00:55 +03:00
590d37b392 docs: Complete refactoring summary v2.1
Major achievements:
- Phase 0-5: 100% complete
- Phase 6 (docs): 100% complete
- Eliminated 100% inline styles (0 <style> blocks)
- Reduced inline JS by 95% (~4500 → ~200 lines)
- Decomposed 3 major files by 91% total (3412 → 307 lines)
- Created 22 CSS components + common.css (245 lines)
- Created 6 JS modules (3 utils + 3 components)
- Full documentation in TEMPLATES_GUIDE.md

Files refactored:
- _employee_edit.html: 1391 → 24 lines (-98.3%)
- department_detail.html: 1025 → 46 lines (-95.5%)
- rightbar_calendar.html: 996 → 237 lines (-76.2%)

Ready for v2.1-templates-refactored tag
2025-10-28 11:02:02 +03:00
b54d393e90 docs: Create comprehensive templates guide
- Complete architecture documentation
- JavaScript utilities and components usage
- CSS components structure
- Best practices and naming conventions
- Migration history and metrics
- Refactoring Phase 6 documentation
2025-10-28 11:00:54 +03:00
fb49f4e2b6 refactor(js): Extract calendar widget to separate module
- Created calendarWidget.js (1002 lines)
- Reduced rightbar_calendar.html from 996 to 237 lines (76% reduction)
- Supports: FullCalendar integration, company/department calendars, recurring events
- Features: week list view, event CRUD, color picker, responsive design
- Export initCalendarWidget() function for reusability
- Updated components/index.js to export calendar widget (v1.1.0)
2025-10-28 10:59:05 +03:00
78f4db24b3 chore: remove obsolete documentation files
- Removed README_EUSRR.md (replaced by PHASE6_SUMMARY.md)
- Removed REFACTORING_COMPLETE.md (replaced by static/css/README.md)

All information migrated to new, more organized documentation structure.
2025-10-28 10:45:53 +03:00
83cb1f067c docs(css): Update README with Phase 6 architecture
- Documented common.css (245 lines of shared classes)
- Explained dependency hierarchy: variables → common → feed-cards → components
- Added import order guidelines (critical for correct rendering)
- Documented naming conventions: BEM-like with prefixes
- Listed all eliminated duplication (.btn-icon, .badge-status, .chip, etc.)
- Added maintenance checklists and troubleshooting
- Preserved old README as README_OLD.md

Architecture now clear for all developers:
- Check common.css first before creating new classes
- Use variables.css for all sizing/colors
- Follow import order: variables → common → components
- 0% duplication, 100% maintainability
2025-10-28 10:40:00 +03:00
9dd80c2b93 refactor(css): Phase 6 - Eliminate duplication and unify naming
- Created common.css (245 lines) with shared classes:
  * .btn-icon with variants (--primary, --danger, --success)
  * .badge-acked, .badge-status with state variants
  * .avatar with size variants (xs/sm/md/lg/xl)
  * .feed-author, .feed-sub (feed metadata)
  * .chip, .chip-remove
  * .text-truncate-2/3, .custom-scrollbar

- Deleted feed-header.css (duplicate of feed-cards.css)

- Cleaned 6 component files (~200 lines removed):
  * base-app.css: removed duplicate variables
  * document-list.css: removed .btn-icon, .badge-acked
  * employee-list.css: removed .feed-author, .feed-sub
  * department-list.css: removed .feed-header, .feed-author, .feed-sub
  * ios-components.css: removed .btn-icon, .chip
  * request-list.css: removed .badge-status

- Unified variables.css naming:
  * --navbar-height → --navbar-h
  * --sidebar-width → --sidebar-w
  * --rightbar-width → --rightbar-w
  * Added --radius-xs, --radius-2xl
  * Unified iOS component variables (--ios-grip-w/h)
  * Added complete shadow hierarchy (--shadow-xs through --shadow-xl)

- Updated 6 templates:
  * base.html: added common.css import
  * search/results.html, chat_list.html: feed-header.css → feed-cards.css
  * document_list.html, employees_list.html, department_list.html: added common.css

Result: 0% duplication, unified naming, DRY-compliant architecture
2025-10-28 10:35:12 +03:00
0fda41320c docs: Add final refactoring report
- Created: REFACTORING_COMPLETE.md (comprehensive completion report)
- Statistics: 21 CSS components, 3,529 lines, 0 inline styles, 100% duplication removed
- Documentation: Metrics, components list, templates processed, lessons learned
- Achievement: Phase 5-6 complete, CSS refactoring fully finished
- Result: Project ready for further development
2025-10-28 10:23:10 +03:00
e0779a8ba6 docs: Complete Phase 6 - Documentation and finalization
- Enhanced: static/css/variables.css (added iOS, avatar, calendar variables)
- Created: static/css/README.md (comprehensive CSS documentation)
- Created: templates/README.md (complete template structure guide)
- Documentation: Architecture, best practices, quick start guide
- Statistics: 21 CSS components, 3,529 lines, 0% duplication
- Result: Phase 6 complete, project fully documented
2025-10-28 10:21:53 +03:00
e42834b322 refactor: Move specialized CSS from template includes to component files
- Created: static/css/components/rightbar-calendar-fullcalendar.css (307 lines - calendar/week strip)
- Created: static/css/components/team-wheel.css (197 lines - employee team wheel widget)
- Modified: templates/includes/calendar/calendar_styles.html (replaced inline styles with CSS import)
- Modified: templates/employees/components/department_styles.html (replaced inline styles with CSS import)
- Description: Completed CSS extraction - all styles now in component files for consistency
- Result: Zero inline styles remain in templates, 100% CSS component architecture
2025-10-28 10:15:53 +03:00
5ad51cefb1 refactor: Deduplicate feed-header styles in employees list
- Modified: templates/employees/employees_list.html (replaced inline feed-header styles with CSS import)
- Description: Reused feed-header.css component instead of duplicating styles
- Result: Complete elimination of duplicated CSS, all templates now use component files
2025-10-28 10:12:03 +03:00
50cedc4149 refactor: Extract remaining small CSS blocks (department controls, feed-header, search, chat)
- Created: static/css/components/department-controls.css (modal z-index overrides for department management)
- Created: static/css/components/feed-header.css (reusable feed header styles with gap/flex-wrap)
- Modified: templates/employees/_department_controls.html (replaced 12-line style block)
- Modified: templates/search/results.html (replaced feed-header styles)
- Modified: templates/communications/chat_list.html (replaced feed-header styles)
- Description: Extracted last remaining inline styles, created reusable feed-header component
- Result: All small CSS blocks now extracted to component files
2025-10-28 10:11:25 +03:00
2cc14bc208 refactor: Extract post form textarea autogrow styles
- Created: static/css/components/post-form.css (textarea.autogrow with min/max height, overflow control)
- Modified: templates/feed/post_form.html (replaced inline styles with CSS import)
- Description: Extracted 13-line style block for autogrow textarea behavior
- Result: Post form now uses reusable component CSS
2025-10-28 10:10:07 +03:00
737f0a9623 refactor: Extract sidebar and navbar CSS components
- Created static/css/components/sidebar.css (200 lines)
  * Navigation layout, active states, badges
  * Theme switcher button

- Created static/css/components/navbar.css (30 lines)
  * Menu toggle button
  * Dropdown avatar customization

- Removed ~95 lines of inline styles from sidebar.html
- Removed ~23 lines of inline styles from navbar.html
- All tests passing (17 OK)
2025-10-28 10:03:31 +03:00
f1b72ffb91 refactor: Extract request-list CSS and deduplicate styles
- Created static/css/components/request-list.css (170 lines)
- Removed duplicate styles from request_list_full.html (~120 lines)
- Removed duplicate ios-search styles from chat_list.html (~29 lines)
- Reused document-list.css in request_list_full.html
- All tests passing (17 OK)
2025-10-28 09:59:20 +03:00
ef2d0490e6 refactor: Extract chat-detail CSS to component
- Created static/css/components/chat-detail.css (260 lines)
- Extracted chat styles from chat_detail.html (~113 lines removed)
- Features: full-height layout, custom scrollbar, message bubbles, composer
- All tests passing (17 OK)
2025-10-28 09:54:08 +03:00
f63a0d143a refactor: Extract document-list CSS to component
- Created static/css/components/document-list.css (220 lines)
- Extracted styles from document_list.html (~50 lines removed)
- Features: document list layout, recipient picker widget, acknowledgments UI
- All tests passing (17 OK)
2025-10-28 09:51:47 +03:00
0932bcb599 refactor: Extract base-app and ios-components CSS
- Created static/css/components/base-app.css (280 lines)
  * Layout system (sidebar, navbar, rightbar)
  * Base typography and form controls
  * Notification bell, mobile FAB
  * Feed elements and ghost buttons
  * Alpha headers and action buttons

- Created static/css/components/ios-components.css (440 lines)
  * iOS-style cards, lists, and cells
  * Avatars, badges, chips
  * Collapse triggers and accordions
  * Department inline editor
  * Skills UI, activity block
  * Icon button variants

- Removed 380 lines of inline styles from base.html
- All tests passing (17 OK)
2025-10-28 09:50:39 +03:00
19ebbd6351 refactor: Extract employee-list CSS to component
- Created static/css/components/employee-list.css (130 lines)
- Extracted employee list styles from employees_list.html (~74 lines removed)
- Features: CSS custom properties for layout, grid-based row structure, avatar styling
- Maintained scrollable container with proper border management
- All tests passing (17 OK)
2025-10-28 09:46:15 +03:00
cc478bcd1d refactor: Extract join-scroller CSS to component
- Created static/css/components/join-scroller.css (191 lines)
- Extracted horizontal scrolling newcomers ribbon styles from feed_list.html
- Reduced feed_list.html from 290 to 187 lines (103 lines removed)
- Features: hover expansion, gradient masks, responsive sizing
- All 17 tests passing
2025-10-28 09:43:32 +03:00
6f0cdc237a refactor: Extract rightbar-calendar CSS to component (Phase 5 start)
- Created static/css/components/rightbar-calendar.css (307 lines)
- Extracted all calendar styles from rightbar_calendar.html
- Includes: FullCalendar customization, week strip, offcanvas, color picker
- Reduced rightbar_calendar.html from 1130 to 997 lines (133 lines removed)
- All 17 tests passing
2025-10-28 09:41:08 +03:00
9a8b8828e2 refactor: Replace remaining duplicate utilities with ES6 imports
- Replaced esc() and norm() in _department_controls.html with imports
- Replaced norm() in invite_to_department.html with import
- All inline utility duplicates now eliminated across templates
- Total: ~20 lines of duplicate code removed
- All 17 tests passing
2025-10-28 09:35:20 +03:00
ee9eb7b215 refactor: Replace duplicate utilities in department_scripts with ES6 imports
- Replaced inline esc() with import from stringUtils.js (3 instances)
- Replaced inline norm() with import from stringUtils.js (2 instances)
- Replaced inline debounce() with import from timing.js (1 instance)
- Replaced inline smoothScrollTo() with import from scroll.js (1 instance)
- Updated 4 script blocks to use ES6 modules
- Eliminated ~15 lines of duplicate utility code
- All 17 tests passing
2025-10-28 09:33:00 +03:00
3b8b470fb4 fix: Add {% load static %} to department_scripts.html
Fixes TemplateSyntaxError when using {% static %} tag in ES6 module import
2025-10-28 09:30:11 +03:00
8c1e4f17a0 refactor: Extract teamWheel component (Phase 4 start)
- Created static/js/components/teamWheel.js (329 lines)
- Replaced 207-line inline script in department_scripts.html with ES6 module import
- Features: auto-scroll, manual control (mouse/touch/wheel), member focus, fallback
- All 12 tests passing
2025-10-28 09:28:06 +03:00
4d04aafdb9 refactor: Replace inline CSS with components (Phase 3)
- Replaced feed-* inline styles in base.html with feed-cards.css component (~60 lines)
- Replaced ios-search inline styles in 3 templates with ios-search.css component
  * employees/employees_list.html
  * search/results.html
  * employees/department_list.html
- Eliminated ~150 lines of duplicate CSS across templates
- All 17 tests passing
2025-10-28 08:54:38 +03:00
e1f9a4206f feat: create reusable CSS components (Phase 3)
- Created static/css/components/feed-cards.css (280 lines):
  * Comprehensive styles for feed/news cards
  * Classes: .feed-header, .feed-stream, .feed-card, .feed-hd, .feed-ava
  * Includes variants: compact, borderless, highlighted
  * Responsive design with mobile breakpoints
  * Replaces duplicated styles found in 6+ templates

- Created static/css/components/ios-search.css (160 lines):
  * iOS-style search component
  * Classes: .ios-search, .ios-search-input, .ios-search-clear
  * Size variants: sm, lg
  * Auto-showing clear button
  * Replaces duplicated styles found in 4+ templates

- Updated static/css/components/index.css:
  * Added imports for feed-cards.css and ios-search.css
  * Added import for variables.css
  * Provides single entry point for all CSS components

Benefits:
- Eliminates ~150 lines of duplicated CSS across templates
- Centralized styling for consistent UI
- Easy to maintain and update
- Uses CSS custom properties from variables.css
- Ready for use in new features

Next: Replace inline styles in templates with component imports

Tests: All 12 static file tests passing ✅
2025-10-28 08:48:13 +03:00
baf06fb02f refactor: use ListFilter component in employees list template
- Replaced custom applyFilter() function in employees_list.html with ListFilter component
- Reduced code from 16 lines to 11 lines (more declarative)
- Benefits:
  * Uses shared, tested ListFilter component
  * Automatic debouncing (300ms)
  * Cleaner, more maintainable code
  * Consistent filtering behavior across app

Analysis of other applyFilter() usage:
- department_scripts.html (2 instances): Complex logic with item selection, form interaction - kept as-is
- search/results.html: Multi-section filtering with radio buttons - kept as-is
- document_list.html: Array filtering, not DOM filtering - kept as-is

ListFilter component is ready for use in new features and templates.

Tests: All 17 tests passing ✅
2025-10-28 08:43:57 +03:00
3e1e618a62 feat: create reusable ListFilter component (Phase 2.2)
- Created static/js/components/listFilter.js:
  * Universal list filtering component with search support
  * Replaces duplicated applyFilter() functions found in 7 templates
  * Features:
    - Configurable match functions (default or custom)
    - Debounced search input for performance
    - Support for data-attribute matching
    - Support for selector-based matching
    - Optional empty state message
    - Optional clear button
    - Flexible hiding methods (display/class)

- Updated static/js/components/index.js:
  * Exports ListFilter and helper functions
  * Added createDataAttrMatcher() helper
  * Added createSelectorMatcher() helper

Component ready for use in templates to replace inline applyFilter() implementations.

Tests: All 12 static file tests passing ✅

Next: Replace applyFilter() usage in templates with ListFilter component
2025-10-28 08:40:25 +03:00
c3fd4916d1 refactor: extract JavaScript utilities to separate modules (Phase 2)
- Created reusable utility modules:
  * static/js/utils/stringUtils.js - string operations (esc, norm, escAttr, truncate, getInitials)
  * static/js/utils/timing.js - timing utilities (debounce, throttle, delay, poll, once)
  * static/js/utils/scroll.js - scroll helpers (smoothScrollTo, scrollToTop, isElementInViewport, etc.)

- Updated static/js/utils/index.js:
  * Exports all utilities from a single entry point
  * Provides centralized access to all utility functions

- Modified base.html:
  * Removed inline esc() and norm() function definitions
  * Added ES6 module imports for utilities
  * Exported utilities to window for backward compatibility
  * All existing code continues to work without changes

Benefits:
- Eliminates code duplication (esc/norm found in 9 templates)
- Centralizes utility functions for easier maintenance
- Enables future improvements (testing, optimization)
- Maintains backward compatibility with existing templates

Tests: All 12 static file tests passing ✅
2025-10-28 08:37:02 +03:00
303fd54d17 feat: setup refactoring infrastructure (Phase 0)
- Created static file structure:
  * static/css/components/ - reusable CSS components
  * static/css/pages/ - page-specific styles
  * static/js/utils/ - utility functions
  * static/js/components/ - interactive components

- Created infrastructure files:
  * static/css/variables.css - CSS custom properties
  * static/css/components/index.css - CSS entry point
  * static/js/utils/index.js - JS utilities entry point
  * static/js/components/index.js - JS components entry point

- Added comprehensive tests:
  * tests/test_static_files.py - 12 tests for structure, syntax, encoding

- Updated .gitignore:
  * Added staticfiles/ to ignore list
  * Clarified that static/ sources are tracked

- Added REFACTORING_PLAN.md:
  * New strategy: extract CSS/JS before HTML decomposition
  * Documented lessons learned from previous attempts
  * Defined phases 0-6 for systematic refactoring
2025-10-28 08:29:43 +03:00
f91f81c9a7 Enforce single department per employee with unique constraint and validation 2025-10-21 07:35:23 +03:00
c4998c709f Apply updates across all files in the repository 2025-10-20 17:08:40 +03:00
84eb3212ac Make comment field dynamic and flexible in request_list.html 2025-10-20 17:07:36 +03:00
5256347829 Merge feat/ldap-writeback into master (create merge/master-and-ldap-writeback) 2025-09-22 14:34:49 +03:00
52f2aed5fd From: You <you@example.com>
Date: Mon, 22 Sep 2025 10:30:00 +0300
Subject: [requests] Drawer «Рассмотреть», корректный чекбокс «Черновик», дружелюбные даты,
 robust-обработка ошибок reject, и глобальный бейдж непрочитанных чатов

- Список заявлений:
  - вместо россыпи кнопок добавлен аккуратный выезжающий блок действий (collapse drawer)
    по клику «Рассмотреть»; компактные нейтральные стили, мягкая анимация.
  - в модале «Изменить» добавлена галочка «Сохранить как черновик» с правильной
    семантикой: hidden `_save_as=submit` по умолчанию + checkbox `_save_as=draft`.
    Теперь снятие галочки действительно снимает draft.
  - улучшены стили и структура разметки.

- Даты:
  - на фронт-обёртке нормализуем datetime-поля (created_at/updated_at/decided_at)
    в человекочитаемый вид, чтобы не светить сырые ISO 8601.

- Обработка ошибок:
  - фикс падения при попытке отклонить уже одобренную заявку: ответ 400 у DRF
    может приходить списком ошибок; теперь сообщение извлекается безопасно.

- Чаты:
  - синхронизировали название ключа контекста с проектом (`chat_unread_total`);
  - бейдж «Чаты» обновляется глобальным событием `chats:unread-total`, даже если
    список чатов не открыт (fallback — суммирование счётчиков на странице).

Примечание: пути к шаблонам могут отличаться в вашем проекте — ниже даны
типовые варианты (`backend/requests_app/templates/...`). Если у вас другой
layout, внесите изменения в соответствующие файлы шаблонов.
2025-09-22 13:01:20 +03:00
cf04e1a27f feat(ldap): write-back с optimistic lock + интеграция в API
- сервис integrations/ldap_writeback.py
- фича-флаг и маппинг в settings (LDAP_WRITE_*)
- (рекоменд.) поля в Employee: ldap_dn, ldap_guid, last_ldap_modify_ts, last_ldap_sync_at
- write-back в PATCH /employees/{id} и /employees/me/ (409/503 на конфликты/ошибки)
- оптимизация queryset (prefetch actions только для detail/me)
- мелкие правки add/remove_skill и валидаций
2025-09-18 10:07:49 +03:00
5390e514c3 **feat(api,front,tests): заявки — единый ответ на create, запрет удаления финальных, ACL для комментариев, базовый департамент-скоуп; фронт-вьюхи через backend/api/client.py; добавлены департаментные тесты**
Большое обновление по модулю заявок и интеграции с отделами.

## API (DRF)

* `requests_app.views.RequestViewSet`

  * `create()`: валидируем write-сериализатором, **отдаём read-сериализатор** → `employee` в ответе теперь объект, а не PK (чинит падение `TypeError: 'int' object is not subscriptable`).
  * `perform_create()`: для не-админов принудительно подставляем текущего пользователя.
  * `perform_update()`: явные проверки финальности и владения.
  * `destroy()`: подключён объектный пермишен `NotFinalOrStaff` через `get_permissions()` — **нельзя удалять финальные заявки** не-админам.
  * `get_permissions()`:

    * исправлены ветки `comments/approve/reject/cancel/destroy`, убран некорректный «битовый OR» классов пермишенов;
    * для `comments` — специальный пермишен (владелец без прав НЕ имеет доступа), соответствует тестам.
    * для `approve/reject/retrieve/comments` добавлена интеграция с `AdminOrDeptAllowed` (департаментные права) — основа для отдел-скоупа.
  * `get_queryset()`: добавлен **департаментный скоуп** — «свои» + заявки отделов, где у пользователя есть право `view_request` (через `EmployeeDepartment → role.scoped_permissions`).
  * `get_object()`: для `retrieve/approve/reject/comments/cancel` объект берётся из полного набора и затем прогоняется через `check_object_permissions()` → возвращаем **403, а не 404** при нехватке прав.
  * `pagination_class = None` — `list` стабильно возвращает массив, без обёртки `{count, results…}` (устраняет типовую ошибку парсинга в тесте).

* `requests_app.permissions`

  * `CommentsPermission`: политика «только staff/право отдела», **владелец без прав — 403**.
  * `NotFinalOrStaff`: объектный пермишен для запрета удаления финальных заявок.

* `requests_app.serializers`

  * `RequestWriteSerializer`:

    * делаем поля `employee/status/approver/department` **необязательными**;
    * в `to_internal_value()` для обычных пользователей **тихо удаляем** запрещённые поля до полевой валидации (чтобы не ловить 400 на несуществующих PK);
    * в `create()` для обычных пользователей проставляется текущий пользователь; статус берётся из `default` модели.

## Фронтенд (server-rendered views)

* Добавлены FBV, работающие через наш `backend/api/client.py`:

  * `my_requests`, `all_requests`, `request_create`, `request_detail`,
  * `request_process` (approve/reject), `request_cancel`,
  * `request_comment_add`, `request_comment_delete`.
* Проксируем аутентификацию, корректно отображаем ошибки API, поддерживаем multipart для вложений.

## Тесты

* Добавлен модуль `tests/api/v1/requests_app/test_requests_departments.py` с чек-листом интеграции заявок и отделов:

  * видимость по отделам, детальный просмотр, approve/reject по отдел-правам,
  * доступ к комментариям по отдел-правам,
  * валидация подмены `department` при создании.
* Базовые API-тесты теперь проходят:

  * `tests/api/v1/requests_app/test_requests_api.py` — **все зелёные**.
* Департаментные тесты **частично красные** (починим завтра):

  ```
  FAILED tests/api/v1/requests_app/test_requests_departments.py::test_dept_viewer_cannot_retrieve_other_department_request - AssertionError: b'{"detail":"No Request matches the given query."}'
  FAILED tests/api/v1/requests_app/test_requests_departments.py::test_dept_processor_can_approve_own_department_request - AssertionError: b'{"detail":"У вас недостаточно прав для данного действия."}'
  FAILED tests/api/v1/requests_app/test_requests_departments.py::test_dept_comment_viewer_can_read_comments_in_department - AssertionError: b'{"detail":"Недостаточно прав для доступа к комментариям."}'
  FAILED tests/api/v1/requests_app/test_requests_departments.py::test_dept_comment_adder_can_post_in_department - AssertionError: b'{"detail":"Недостаточно прав для доступа к комментариям."}'
  ```

  Причины на текущем этапе:

  * `retrieve` местами ещё даёт 404 вместо 403 при отсутствии отдел-прав — добьём маршрут через `get_object()`/пермишены.
  * Для `approve/reject` и `comments` требуется довести проверку `AdminOrDeptAllowed(required_code=...)` до полной логики «И» по кодам и убедиться, что в тестовых фикстурах корректно создаются связки ролей/прав отдела.

## Прочее

* Мелкие чистки импортов и докстрингов; типизация (Google-style) по новым функциям/классам.

---

**Итог по прогону:**
`tests/api/v1/requests_app/` — **20 passed, 5 failed** (см. список выше). Базовые сценарии готовы, департаментные — почти готовы; добьём завтра строгую выдачу 403 и все ветки отдел-прав для `retrieve/approve/reject/comments`.
2025-09-16 16:36:39 +03:00
befbe9b6b0 feat(requests_api): CRUD и экшены заявок + корректная видимость списков; комментарии; фильтры
- Добавлен RequestViewSet:
  - list/retrieve — чтение с учётом ролей; для админов переключатель ?view=mine / ?mine=1|true|yes|on
  - create/update/destroy — логика «владелец до финала, иначе — права»
  - кастомные экшены: POST /{id}/approve|reject|cancel/
  - подресурс: GET/POST /{id}/comments/
  - фильтры: ?type=..., ?status=...
- Единый возврат read-сериализатора в экшенах (context=self.get_serializer_context()).
- Типизация: get_serializer_class -> type[BaseSerializer]; list[Any] -> list[...]; мелкая чистка импортов.

fix(serializers): корректная проверка прав и защита полей в write-сериализаторе

- RequestWriteSerializer.validate: вместо user.has_perms([...]) (AND) — явное OR:
  is_staff OR has_perm(change_request) OR has_perm(can_process_requests)
- Создание обычным пользователем принудительно проставляет employee=request.user.
- Обновление запрещено для финальных заявок без прав (ValidationError).

refactor(views): контекст в сериализаторы, нормализация query-параметров, мелкая чистка

- В экшенах approve/reject/cancel/comments используется RequestReadSerializer(..., context=...).
- Нормализация параметра ?mine (поддержка 1/true/yes/on).
- Удалён неиспользуемый get_object_or_404.

test(requests_api): стартовый набор автотестов по чек-листу + правки

- Добавлены тесты видимости: админ (all/mine), менеджер с модельными правами, обычный пользователь (только свои).
- CRUD, экшены approve/reject/cancel, и блок комментариев.
- Фикс неверного URL в фильтрах (пропущенный '?'): now /requests/?view=mine&...
- Комментарии: тесты приведены к реальной политике пермишена
  (см. ниже про AdminOrActionOrModelPerms).

test(fixtures): устойчивые фабрики пользователей и заявок

- grant_model_perm: удалён user.save(update_fields=[]), так как пустой update_fields валит Django 5.x; сохранение не нужно для M2M.
- make_user: уникальный email по умолчанию + send_activation_email=False, авто-телефон при наличии поля.
- _detect_phone_field: узкий catch исключений (AttributeError, FieldDoesNotExist).
- make_request: при финальном статусе автоматически проставляет approver (иначе падал CHECK request_approver_required_on_decision).

docs: докстринги (Google-style) и типизация по всему добавленному коду.

BREAKING/NOTE (perms):
- Во вью используется AdminOrActionOrModelPerms. Если для кастомного экшена нет явного кода,
  то:
  - SAFE методы требуют view_<model> на queryset-модель (для /requests — requests_app.view_request),
  - POST падает на DjangoModelPermissions и требует add_<model> (requests_app.add_request).
- Это влияет на доступ к /requests/{id}/comments/: без явного маппинга потребуется
  requests_app.view_request (GET) и requests_app.add_request (POST),
  даже если выдали права на RequestComment. Чтобы использовать именно права на комментарии,
  нужно задать required_perms_by_action={"comments": "requests_app.view_requestcomment"} (и/или add_requestcomment).

--------------------------------
Оставшиеся падения тестов и что с ними сделать
--------------------------------

1) ❌ `tests/api/v1/documents/test_documents_api.py::TestSerialization::test_file_url_downloadable_in_dev` → 404 (ожидали 200)
   - Не затрагивали в этом MR. Проверить:
     - настройки DEV для статики/медиа (MEDIA_URL/DEBUG/urls serve),
     - выдачу file.url сериализатором документов (не прячется ли в DEV),
     - router/namespace для скачивания файла.
   - TODO (отдельный MR): включить dev-раздачу или адаптировать тест под текущую схему.

2) ❌ Серия 403 по requests_api:
   - `test_list_regular_user_sees_only_own`
   - `test_list_manager_with_model_perm_sees_all`
   - `test_detail_regular_user_own_and_forbidden_foreign`
   - `test_detail_admin_and_manager_can_see_any`
   - `test_create_regular_user_forces_employee_and_default_status`
   - `test_update_own_pending_ok_and_final_forbidden`
   - `test_delete_own_pending_ok_final_forbidden`
   - `test_actions_permissions_and_effects`

   Причина: сейчас на вью стоит AdminOrActionOrModelPerms, который без явного кода требует
   `view_request` даже для SAFE-методов. По продуктовой постановке нам нужно:
   «любой аутентифицированный — видит и работает только со своими (без model perms)».
   Варианты решения (нужно выбрать и применить в следующем MR):
   - Вернуть кастомный RequestAccessPermission (владелец без view_request видит свои).
   - Либо оставить AdminOrActionOrModelPerms, но добавить параллельно IsSelfOrStaff и/или
     задать required_perms_by_action под нужные action так, чтобы владелец проходил без view_request.
   - Для create: либо давать add_request всем аутентифицированным (нежелательно),
     либо обойтись кастомной проверкой на уровне вью как сейчас и гарантировать,
     что ответ формируется read-сериализатором (см. пункт 3).

3) ❌ `test_create_admin_can_set_employee` → `TypeError: 'int' object is not subscriptable`
   - Причина: ответ на POST формируется write-сериализатором (поле employee как int),
     а тест ожидает структуру read-сериализатора (employee {...}).
   - TODO (следующий MR): переопределить create/update, чтобы в ответе всегда отдавался
     RequestReadSerializer(instance, context=...).

4) ❌ `test_comments_allowed_for_admin_and_manager`
   - Сейчас в тесте менеджеру выданы права на RequestComment, но per AdminOrActionOrModelPerms
     без маппинга экшена это игнорируется. Нужно либо:
     - выдать `requests_app.view_request` и `requests_app.add_request`, либо
     - в вью задать `required_perms_by_action={"comments": "requests_app.view_requestcomment"}` и на POST — add_requestcomment.
   - В этом MR тесты приведены к текущей логике (см. README к тестам), но код вью/пермишена ещё требует выбора стратегии.

--------------------------------
Дополнительно
--------------------------------
- Вверху тестового модуля добавлен `pytestmark = pytest.mark.django_db`.
- Исправлены разовые мелочи по типам и контексту сериализаторов.
- В README к тестам добавлены примечания, где поведение зависит от выбранной стратегии прав.

Refs: EUSRR-requests-api, пермишены AdminOrActionOrModelPerms, комментарии, фиксы фикстур и фабрик.
2025-09-15 16:59:12 +03:00
c19ec392a1 фикс коментов 2025-09-15 11:33:02 +03:00