290 Commits

Author SHA1 Message Date
2b3bbdf3a5 fix(api): convert PhoneNumber to string in Excel export
Проблема: ValueError при экспорте - PhoneNumber объект нельзя напрямую записать в Excel ячейку.
Ошибка: Cannot convert PhoneNumber(country_code=7, national_number=...) to Excel

Решение:
- Добавлено форматирование PhoneNumber в международный формат (+7 928 826-66-50)
- Использован phonenumbers.format_number() с INTERNATIONAL форматом
- Добавлен fallback на str() в случае ошибки форматирования

Теперь телефоны корректно экспортируются в читаемом виде.
2025-12-18 15:36:50 +03:00
07a6eded9a feat(api): add Excel export endpoint for employees
Добавлен GET эндпоинт для экспорта списка сотрудников в Excel формат.

Endpoint: GET /api/v1/employees/export-excel/

Функционал:
- Экспорт всех сотрудников в формат .xlsx
- Применяются все фильтры из queryset (department, position, active и т.д.)
- Поддержка поиска и сортировки из основного API

Колонки в Excel:
- ID, Фамилия, Имя, Отчество
- Email, Телефон
- Должность, Отделы (с ролями)
- Дата рождения, Дата регистрации
- Статус: Активен, Email подтвержден
- Навыки
- Мессенджеры: Telegram, WhatsApp, WeChat

Особенности:
- Стилизованные заголовки (синий фон, белый текст)
- Автоподбор ширины колонок (максимум 50 символов)
- Закрепленная первая строка (заголовки)
- Перенос текста в ячейках
- Имя файла: employees_YYYYMMDD_HHMMSS.xlsx

Зависимости:
- openpyxl==3.1.5 (добавлена в requirements.txt)

Использование:
GET /api/v1/employees/export-excel/
GET /api/v1/employees/export-excel/?department=5
GET /api/v1/employees/export-excel/?active=true&search=Иванов
2025-12-18 15:29:40 +03:00
e973cc6075 fix(ldap): handle dismissal of employees without departments
Проблема: При увольнении сотрудника, не состоящего ни в одном отделе,
он оставался в текущей OU (например, OU=Users) вместо перемещения в OU=Dismissed.

Причина: Цикл по active_departments был пустым, remove_member() не вызывался,
перемещение в OU=Dismissed не происходило.

Решение:
- Добавлена проверка departments_processed
- Если сотрудник не состоял ни в одном отделе, выполняется явное перемещение
- Используется get_base_dn_for_employee() для определения целевой OU
- Прямой вызов _move_user_to_base() для перемещения в OU=Dismissed

Тест: test_dismissal_without_department_moves_to_dismissed
- Проверяет увольнение сотрудника без отделов
- Убеждается, что LDAP соединение создано для перемещения
- Подтверждает деактивацию в LDAP (userAccountControl=514)

Edge case покрыт: Теперь все уволенные попадают в OU=Dismissed независимо
от наличия отделов.
2025-12-18 12:32:09 +03:00
c7f43d0c5b feat(ldap): separate dismissed employees to OU=Dismissed
Implemented automatic movement of dismissed employees to dedicated OU.

Core Changes:
- Configuration: Added LDAP_DISMISSED_BASE setting for dismissed employees OU
- Utility: Created get_base_dn_for_employee() to determine target OU by is_active status
- Service Layer: Modified DepartmentService.remove_member() to use status-based OU selection
- View Logic: Updated EmployeeActionViewSet._apply_effects() to:
  * Deactivate employee BEFORE removing from departments (critical for correct OU routing)
  * Loop through all departments and call remove_member() for each
  * Handle restoration: move from OU=Dismissed back to OU=Users on activation

Infrastructure:
- Management Command: ensure_dismissed_ou.py to create OU=Dismissed in AD
  * Checks OU existence before creation
  * Supports --force flag for recreation
  * Configurable description

Testing:
- test_dismissal_moves_to_dismissed_ou: Verifies dismissal → OU=Dismissed movement
- test_restoration_moves_from_dismissed_to_users: Verifies activation → OU=Users movement

Edge Cases Handled:
- Repeat dismissal: Idempotent (already inactive employees stay in OU=Dismissed)
- Restoration: Automatic move from OU=Dismissed to OU=Users on any activating action
- Missing OU: ensure_container_exists() creates OU=Dismissed if missing (fallback to OU=Users on error)
- LDAP errors: Graceful logging without blocking database operations

Technical Details:
- OU=Dismissed: OU=Dismissed,OU=company,DC=robotail,DC=local
- Dismissal flow: is_active=False → deactivate EmployeeDepartment → update LDAP UAC → remove from all departments
- Restoration flow: is_active=True → update LDAP UAC → check current OU → move if in OU=Dismissed
- Backward compatible: Works with existing dismissals (they will move to OU=Dismissed on next department change)

Files Changed:
- backend/.env: Added LDAP_DISMISSED_BASE configuration
- backend/eusrr_backend/settings.py: Registered LDAP_DISMISSED_BASE setting
- backend/employees/ldap/utils/ldap_utils.py: New get_base_dn_for_employee() utility
- backend/employees/ldap/services/department_service.py: Modified remove_member() logic
- backend/api/v1/employees/views.py: Enhanced dismissal and restoration logic
- backend/employees/management/commands/ensure_dismissed_ou.py: New management command
- backend/tests/api/v1/employees/test_employee_actions.py: Added tests for new behavior
2025-12-18 11:56:51 +03:00
8f2f22fab5 Merge branch 'feature/avatar-validation' into master
Added avatar cropper with FaceID requirements and human silhouette overlay guide.

Features:
- Avatar cropper using Cropper.js library
- Portrait format 3:4 (600x800px output)
- Human silhouette overlay for proper positioning
- FaceID requirements validation
- Real-time crop synchronization
- Integrated in registration and profile editor

Components:
- avatarCropperHandler.js (542 lines)
- Updated templates (register.html, employee forms)
- Bootstrap modal UI with instructions

Technical:
- CDN: Cropper.js v1.6.1
- Output: JPEG 92% quality
- Validation: size, format, dimensions
- SVG overlay with guide lines

Commits:
- d6e9747: Initial avatar cropper implementation
- 9474860: Added human silhouette overlay
- e9b530d: Changed to 3:4 portrait ratio
- 3231651: Centered and enlarged face
2025-12-18 10:25:05 +03:00
3231651efe feat(avatar): center and enlarge face in overlay guide
Improved human silhouette overlay to better center the face and make it larger for optimal FaceID recognition.

Changes:

Face positioning:
- Moved face center from cy=120 to cy=150 (centered vertically)
- Face now occupies middle of frame instead of upper third
- Eyes align with horizontal center line at y=150
- Better balance between head and body in frame

Face size increase:
- Increased head ellipse from rx=75,ry=95 to rx=90,ry=115
- ~20% larger face area for better recognition
- More prominent facial features in final crop
- Improved face-to-frame ratio (70-80% coverage)

Body proportions updated:
- Neck: y=250 to y=285 (moved down)
- Shoulders: y=230 to y=285 (centered below face)
- Torso extends to bottom of frame
- More natural body proportions

Guide lines adjusted:
- Eye-level line: y=120 → y=150 (center of frame)
- Shoulder line: y=230 → y=285 (below center)
- Vertical center line unchanged (x=150)

UI text updates:
- Instructions emphasize face centering
- 'Расположите глаза на центральной линии'
- 'Голова занимает верхнюю половину фото'
- Changed bottom label from 'Пояс' to 'Низ кадра'

Benefits:
✓ Face more prominent in photo (better for FaceID)
✓ Centered composition (professional appearance)
✓ Balanced head-to-body ratio
✓ Easier for users to align correctly
✓ Improved recognition accuracy
2025-12-18 10:19:47 +03:00
e9b530d356 feat(avatar): change crop ratio to 3:4 portrait and improve overlay sync
Changed avatar cropper aspect ratio from 1:1 to 3:4 (portrait) for better FaceID recognition.
Improved human silhouette overlay synchronization with crop box during all interactions.

Key changes:

Aspect ratio:
- Changed from 1:1 (square) to 3:4 (portrait)
- Output size: 600x800px (instead of 800x800px)
- Better suited for full body positioning (head, shoulders, torso)

SVG overlay improvements:
- Updated viewBox from 400x400 to 300x400 (3:4 proportions)
- Redesigned human silhouette for portrait format
- Added torso outline up to waist level
- Additional guide line for shoulders
- Better proportions for face/head/shoulders alignment

Synchronization enhancements:
- Added cropstart, cropmove, cropend event handlers
- Overlay now follows crop box during all interactions:
  ✓ Moving the crop box
  ✓ Resizing the crop box
  ✓ Zooming the image
  ✓ Initial positioning
- Real-time position updates using getCropBoxData()

UI/UX updates:
- Updated instructions: 'Совместите тело с зелёным контуром'
- Face should occupy upper third of frame
- Portrait format 3:4 mentioned in requirements
- Changed label from 'Плечи' to 'Пояс' (waist)
- Templates updated with new size requirements (600x800px)

Technical details:
- minCropBoxHeight: 266px (200 * 4/3 for aspect ratio)
- preserveAspectRatio: none (for proper stretching)
- Event handlers ensure overlay follows crop box smoothly
- No performance impact from additional event listeners

Benefits:
✓ Better for FaceID (full body context)
✓ Standard portrait photo format
✓ More professional appearance
✓ Consistent with ID photo standards
✓ Improved overlay visibility and accuracy
2025-12-18 10:15:00 +03:00
94748609e5 feat(avatar): add human silhouette overlay to avatar cropper
Added visual guide with human body contour overlay to help users properly position their face for FaceID.

Features:
- SVG overlay with human silhouette (head, neck, shoulders)
- Green dashed outline (70-80% face coverage guidance)
- Guide lines (vertical center, horizontal eye level)
- Text labels ('Верх головы', 'Плечи')
- Toggle checkbox to show/hide overlay
- Real-time overlay positioning synchronized with crop box

Technical implementation:
- SVG viewBox 400x400 with preserveAspectRatio
- Dynamic positioning using getCropBoxData()
- Event handlers: ready, crop, zoom
- Overlay updates on cropper interactions
- Pointer-events: none for non-intrusive UI

UI/UX improvements:
- Clear visual guidance for face positioning
- Non-intrusive overlay (can be toggled off)
- Color: #00ff00 (green) for high visibility
- Opacity: 0.8 for overlay, 0.4 for guide lines
- Auto-shown by default, user can disable

Benefits:
✓ Reduces user errors in face positioning
✓ Ensures consistent photo quality for FaceID
✓ Visual feedback for proper head/shoulders alignment
✓ Improves user experience and reduces support requests
2025-12-18 10:03:34 +03:00
d6e974746e feat(avatar): implement avatar cropper with FaceID requirements
Implemented avatar cropping component for FaceID system integration.

Features:
- Image cropper using Cropper.js library
- FaceID requirements validation (70-80% face coverage, 600x600px min)
- Square crop area (1:1 aspect ratio)
- Output: 800x800px JPEG at 92% quality
- Real-time size indicator
- Integrated in 2 places: registration + profile editor

Components:
- avatarCropperHandler.js: Main cropper module with AvatarCropper class
- Modal UI with Bootstrap 5
- FaceID instructions and guidelines
- File validation (size, format, dimensions)

Integration:
- auth/register.html: Registration form with cropper
- employees/employee_form_personal.html: Profile editor with cropper
- employees/employee_form_scripts.html: Scripts updated

Technical details:
- CDN: Cropper.js v1.6.1
- Min input size: 600x600px
- Max file size: 10 MB
- Formats: JPG, PNG, GIF
- Output format: JPEG (optimized for face recognition)

Validation:
✓ File format validation
✓ File size validation (10 MB max)
✓ Image dimensions validation (600x600px min)
✓ Real-time crop size indicator
✓ Error handling with user-friendly messages

UI/UX:
- Modal window with instructions
- Live preview of cropped image
- Size indicator (green/red based on requirements)
- Clear FaceID guidelines for users
- Responsive layout
2025-12-18 09:56:50 +03:00
3ab23973b5 feat: add employee dismissal UI and filter inactive employees
- Added dismissal form on employee profile page with permissions
- Shows warning when dismissing (LDAP deactivation notice)
- Inactive employees filtered by default in employee list (active=true)
- Team wheel now shows only active employees
- Auto-submit filter form on status change
- Added redirect to set active=true by default on first visit
2025-12-17 09:14:34 +03:00
a280f6e7f7 feat: sync employee dismissal/activation with LDAP
- Added LDAP synchronization in EmployeeActionViewSet._apply_effects()
- Dismissal sets userAccountControl=514 (disabled) in LDAP
- Other actions set userAccountControl=512 (enabled)
- Graceful error handling: DB succeeds even if LDAP fails
- Works correctly when LDAP is disabled
- Added 5 comprehensive tests for LDAP sync behavior
2025-12-17 08:15:35 +03:00
b5fbeca09f feat: maximize LDAP avatar quality (384px, progressive JPEG, 4:4:4)
- Увеличено разрешение: 120px -> 384px (+900% пикселей)
- Повышено качество JPEG: 50-95 -> 75-98
- Добавлен progressive JPEG для лучшего сжатия
- Включён subsampling 4:4:4 (без потери цветности)
- Добавлена обработка EXIF ориентации
- Добавлено сохранение пропорций (thumbnail вместо resize)
- Обработка прозрачности PNG

Улучшения в:
- employees/ldap/utils/image_utils.py
- employees/ldap/services/user_service.py
- employees/ldap/sync_service.py

Добавлены тестовые скрипты:
- test_ldap_simple.py (быстрый тест)
- test_avatar_simple.py (тест системного сжатия)
- TEST_IMAGE_SCRIPTS.md (документация)
2025-12-16 14:55:58 +03:00
b4221386ff fix: preserve EXIF orientation when compressing images 2025-12-16 13:37:35 +03:00
9dfe006d26 docs: add comprehensive implementation plan for Procurement module
Created detailed documentation covering:
- 8 data models with relationships and fields
- Complete API endpoints specification (30+ endpoints)
- Permission matrix and access control
- Approval workflow state machine
- UI/UX mockups for all pages
- 8-stage implementation roadmap (1-2 months)
- Technology stack decisions
- Risk assessment and mitigation strategies
- Complete checklist for tracking progress

Key Features:
- Procurement request creation and approval workflow
- Multi-level approval based on cost thresholds
- Budget control per department/quarter
- Equipment/inventory management with QR codes
- Maintenance tracking and history
- Supplier management
- Real-time notifications and WebSocket updates
- Export to PDF/Excel reports

Ready to start Stage 1: Basic Structure
2025-12-16 13:37:34 +03:00
18468fad64 fix: add permission checks for create buttons in employee module templates
Changes:
1. employees_list.html - 'Create Profile' button now only visible to staff/superuser
   API requires staff/superuser for POST /employees/ (explicit check in create method)

2. department_list.html - Simplified permission check for 'Create Department' button
   Changed from: can_create_departments OR perms.employees.add_department OR is_staff
   To: is_staff OR is_superuser OR perms.employees.add_department
   API uses AdminOrActionOrModelPerms which checks employees.add_department

3. skill_list.html - 'Add Skill' button now requires authentication
   API allows any authenticated user to create skills (IsAuthenticated only)

Before:
- Department creation check was redundant with can_create_departments variable
- Skill creation had no check

After:
- All create buttons properly check permissions matching API requirements
- Consistent with feed and documents modules permission patterns
2025-12-08 14:24:40 +03:00
0dc51abe77 docs: document final solution for position permissions issue
Root cause identified:
- Template checked non-existent permissions (publish_company_post, publish_department_post)
- Django only creates 4 default permissions: add, change, delete, view
- User actually HAD feed.add_post permission from Position→Group chain

Solution:
- Changed template check to use feed.add_post (real permission)
- Confirmed PositionRoleBackend works correctly (13/13 tests passed)
- User can now see 'Create Post' button

Production diagnostic confirmed user has permissions through position:
Position 'СММ специалист' → Group 'Дизайн СММ Реклама' → Permissions include feed.add_post
2025-12-08 14:17:06 +03:00
6162d9f16e fix: correct permission check in feed_list.html template
Changed from non-existent permissions:
  - perms.feed.publish_company_post
  - perms.feed.publish_department_post

To actual Django model permission:
  - perms.feed.add_post

User diagnosis confirmed:
- User has Position 'СММ специалист'
- Position linked to Group 'Дизайн СММ Реклама'
- Group has permissions: add_post, change_post, delete_post, view_post
- PositionRoleBackend correctly grants these permissions

The 'Create Post' button will now appear for users with feed.add_post permission through their position groups.
2025-12-08 14:14:58 +03:00
4a6b92f5f8 docs: add production debugging guide for position permissions
Added comprehensive troubleshooting section:
- Django shell diagnostic script
- SQL queries to check database state
- Permission cache clearing instructions
- Template debugging
- Common issues and solutions
- Complete test results table (13/13 PASSED)

All tests confirmed PositionRoleBackend logic is correct.
If buttons still don't appear, issue is likely:
1. Permission caching (needs re-login)
2. LDAP group sync not working
3. Database missing Position→Groups→Permissions links
2025-12-08 14:06:01 +03:00
66406d94ad fix: add is_active check to PositionRoleBackend and fix tests
Changes:
1. auth_backends.py - Added is_active check in get_all_permissions()
   Inactive users should not receive any permissions from their position

2. test_position_permissions.py - Multiple test fixes:
   - Moved fixtures to module level (accessible to all test classes)
   - Changed Permission creation to filter().first() pattern (no IntegrityError)
   - Fixed permission cache issues (use fresh User.objects.get() after changes)
   - Changed test_staff_user_keeps_all_permissions → test_superuser_has_all_permissions
     (is_staff does NOT grant all perms, only is_superuser does)

Test Results:
✅ 13/13 tests PASSED
✅ All permission inheritance scenarios verified
✅ PositionRoleBackend implementation confirmed working

Key Findings:
- Position → Groups → Permissions inheritance works correctly
- Permission caching requires fresh instance after position changes
- is_active check was missing (now fixed)
- is_staff does NOT grant all permissions (only is_superuser)

Next Steps:
- Check production environment for permission caching issues
- Verify LDAP group sync is working
- Test UI button visibility with real user accounts
2025-12-08 14:02:09 +03:00
769f2ed633 test: add comprehensive position permissions tests
Created pytest test suite to verify permission inheritance through positions:

Test Coverage:
1. User without position has no permissions (PASS)
2. User with position gets all group permissions (needs fix)
3. Position change updates permissions dynamically
4. Remove position removes all permissions
5. Multiple users with same position get same permissions
6. Staff users keep all permissions regardless
7. Multiple groups' permissions are additive
8. get_all_permissions() includes position perms
9. Position without groups grants no permissions (PASS)
10. Inactive users have no permissions
11. Direct user permissions + position permissions combine
12. Feed/Documents integration tests

Current Results:
- 3 tests PASSED (basic cases)
- 10 tests need fixing (fixture scope issues)

Purpose:
These tests will validate that PositionRoleBackend correctly
grants permissions from Position.groups to users, which is
needed for features like:
- Show 'Create Post' button for users with publishing rights
- Show 'Create Document' button for users with document rights
- Consistent permission checks across frontend and backend

Next Steps:
1. Fix IntegrityError in permission creation (use filter first)
2. Make fixtures work across test classes
3. Run tests to verify PositionRoleBackend implementation
4. If tests fail, fix the backend implementation
2025-12-08 13:54:28 +03:00
194157e1ef fix: prevent double form submission in employee edit form
Problem:
- When editing employee profile, got duplicate PATCH requests
- One request returned 502, another 200 OK
- Error appeared in console but operation succeeded
- Classic double-submit race condition

Root Cause:
initEmployeeForm() added new addEventListener('submit') on every call.
If function was called twice (e.g., on tab navigation or re-render),
two event handlers would fire simultaneously, sending parallel requests.

Solution:
1. Check if form already initialized via data-attribute
2. Set form.dataset.employeeFormInitialized = 'true' flag
3. Skip re-initialization if already initialized
4. Return API object for already initialized forms

This ensures only ONE submit handler per form, preventing:
- Duplicate PATCH requests
- 502 errors from race conditions
- Confusing UX with errors that don't break functionality

Now form submits cleanly with single request.
2025-12-08 13:37:20 +03:00
f51789b5fe fix: use PositionService instead of DirectoryService for position groups
Problem:
- When assigning/changing position, got 502 error
- Error: 'DirectoryService' object has no attribute '_ensure_position_group'
- Method was called on wrong service class

Root Cause:
DirectoryService doesn't have _ensure_position_group method.
This method exists in PositionService (line 190 of position_service.py).

Solution:
- Import and use PositionService for position-specific operations
- Keep DirectoryService for general group operations (add/remove members)
- Use pos_svc._ensure_position_group() to create/get position group DN
- Use dir_svc for add_group_members/remove_group_members

Now position assignment/changes work correctly through LDAP sync.
2025-12-08 13:29:53 +03:00
7e8cb9abd8 fix: handle empty position_id and unwillingToPerform LDAP error
Problem:
- When clearing employee position (position_id: ''), LDAP sync failed
- Error: LDAP modify failed: 'unwillingToPerform' (code 53)
- System tried to remove user from position group but LDAP refused

Root Causes:
1. Empty string '' not explicitly converted to None
2. unwillingToPerform error not handled (user may not be in group)

Solution:
1. Convert position_id: '' to None (no position) at parsing stage
2. Wrap remove_group_members in try/except
3. Ignore unwillingToPerform errors with warning log
4. Add detailed logging for position group operations

This allows users to clear positions without LDAP sync failures.
2025-12-08 13:14:40 +03:00
48391600fe feat: show create document button only for authorized users
Previously: 'Create Document' button visible to everyone
Now: Button visible only for:
- Staff users (is_staff), OR
- Users with documents.add_document permission

This prevents regular users from seeing a button they can't use,
improving UX by showing only available actions.
2025-12-08 13:09:55 +03:00
94e61ca9ed feat: show create post button for users with publish permissions
Previously: Only staff users could see 'Create Post' button
Now: Button visible for:
- Staff users (is_staff), OR
- Users with feed.publish_company_post permission, OR
- Users with feed.publish_department_post permission

This allows department managers and content creators to publish
posts without needing full staff status.
2025-12-08 13:05:12 +03:00
d1b58d4c2d fix: prevent QueryDict conversion breaking form data for non-admin users
Problem: Regular users couldn't create requests while admins could
Root cause: to_internal_value() used dict(QueryDict) which converts
all values to lists, breaking validation

Solution:
- For QueryDict: use _mutable flag to modify in-place
- For regular dict: use dict() conversion as before
- Avoids ['value'] instead of 'value' conversion

This fixes 400 errors for non-admin users when creating requests
with multipart/form-data.
2025-12-08 12:41:56 +03:00
54e3fc6dbc debug: add more detailed logging for request creation
- Log Content-Type header
- Log POST, FILES, and data keys separately
- Log actual values and types of key fields (type, title, dates, comment)
- This will help identify multipart parsing issues
2025-12-08 12:35:02 +03:00
da62d93c57 feat: add detailed logging for request creation errors
Backend (API):
- Added logging of user ID and request data keys before validation
- Log validation errors with full details before raising exception
- Helps diagnose 400 Bad Request errors from users

Frontend (JS):
- Added console logging of all FormData entries before submit
- Improved error message display with field-specific validation errors
- Shows structured error messages instead of generic 'HTTP 400'

This will help identify why some users get 400 errors when creating requests.
2025-12-08 12:29:44 +03:00
ff9b094dd7 fix: improve recipient picker - load all users with avatars
RecipientPicker (заявления):
- Added pagination support to load ALL users (not just first page)
- Added avatar images from media URLs instead of base64
- Falls back to initials when no avatar available
- Loads users in batches of 100 per page

RecipientPickerHandler (чаты):
- Added pagination support for full user list
- Keeps existing avatar display logic
- Loads 100 users per page when not searching
- Limits to 20 results when searching

CSS improvements:
- Added styles for avatar images (.user-avatar-img)
- Added placeholder styles for initials
- Proper object-fit and border-radius for avatars
2025-12-08 12:09:32 +03:00
62e03ad538 Фикс скролла 2025-12-08 11:21:31 +03:00
aec6cb42f1 feat: improve employee scroller UX - pause only at edges
Changed auto-scroller behavior for new employees:
- Removed pause on card hover - cards now only scale on hover (CSS)
- Added edge detection (20% zones on left/right sides)
- Scroller pauses ONLY when mouse is near container edges
- When paused at edge, centers nearest card for better visibility
- Mouse in center zone keeps auto-scroll running
- Smoother interaction - no interruption when browsing cards
2025-12-08 11:17:59 +03:00
8b0c853f29 feat: add avatar zoom modal on click
- Added Bootstrap modal for enlarged avatar view
- Made avatar image clickable with cursor pointer
- Added modal trigger to both static and dynamically loaded avatars
- Modal displays full-size avatar centered with dark backdrop
- Close button positioned in top-right corner
2025-12-08 11:07:45 +03:00
21265dd683 feat: increase file upload limits to 10MB
- Set DATA_UPLOAD_MAX_MEMORY_SIZE to 10MB (from default 2.5MB)
- Set FILE_UPLOAD_MAX_MEMORY_SIZE to 10MB
- Fixes RequestDataTooBig error when uploading larger avatars
2025-12-08 10:48:59 +03:00
17fada541a fix: avatar upload with Base64ImageField and ForeignKey handling
- Changed EmployeeSerializer.avatar from ImageField to Base64ImageField
  to properly handle base64-encoded images from employee_edit_me view
- Added conversion of empty strings to None for ForeignKey fields (_id)
  to prevent 'Field expected a number but got empty string' errors
- Improved logging for debugging multipart form processing
2025-12-08 10:32:31 +03:00
8cf9f1334f fix: handle empty avatar field in profile update (complete fix)
- Skip empty avatar field in views_front.py before sending to API
- Add validate_avatar() in serializer to convert empty strings to None
- Prevent avatar update when value is None in serializer.update()
- Fix ValidationError when updating profile without changing avatar
2025-12-08 10:15:10 +03:00
b32e2b9865 fix: handle empty avatar field in employee profile update
- Add validate_avatar() to ignore empty strings from FormData
- Prevent avatar field update when value is None (no file selected)
- Fix ValidationError 'Загруженный файл не является корректным файлом'
- User can now update profile without changing avatar
2025-12-08 09:58:06 +03:00
5e8ca6c25d refactor: remove total messages counter from chat list
- Removed badge showing total message count (chat.messages.count)
- Keep only unread messages counter for cleaner UI
- Users can still see unread count which is more important
2025-12-08 08:36:56 +03:00
4328490170 новое уведомление 2025-12-08 07:56:53 +03:00
c81cb71fb5 feat: add paste and drag-and-drop support for chat files
- Added paste event handler to detect and handle files from clipboard
- Support for pasting images and files with Ctrl+V / Cmd+V
- Added drag-and-drop file upload functionality
- Visual feedback with green highlight during drag-over
- Supports multiple file paste/drop at once
- Prevents text insertion when files are pasted
- Uses clipboard items API for better file detection
- Fallback to clipboard files for broader compatibility
- Console logging for debugging paste/drop operations
2025-12-08 07:55:53 +03:00
5699f6db50 fix: prevent calendar context menu from going off-screen
- Added smart positioning logic to keep menu within viewport bounds
- Menu now adjusts horizontal position if it would overflow right edge
- Menu moves above cursor if it would overflow bottom edge
- Changed position from absolute to fixed for consistent behavior
- Added 10px safety margins from all edges
- Menu is temporarily hidden during position calculation for smooth appearance
2025-12-05 17:01:33 +03:00
25004e538a feat: move calendar button from FAB to navbar
- Removed floating action button (FAB) for calendar
- Added calendar icon in navbar next to notification bell
- Calendar button only visible on mobile devices (d-lg-none)
- Fixed issue where FAB could overlap message send button
- Commented out calendar-fab CSS in all relevant files
2025-12-05 16:59:23 +03:00
bb8b14c4f7 Fix reg 2025-12-05 16:39:42 +03:00
29db86d4f1 fix: add corporate network 172.11.0.0/16 to allowed IPs
- Allow registration from 172.11.0.0/16 network
- Add explicit list of allowed networks instead of default
- Include test script for corporate IP validation
- All tests passed (8/8)
2025-12-05 16:25:17 +03:00
f438aa6433 test: add my_requests.html and IP restriction test scripts 2025-12-05 16:18:45 +03:00
65c6d47eaa feat: centralized IP restriction for registration via middleware
- RegistrationIPRestrictionMiddleware added
- Removed view decorators
- All logic now in middleware
- Updated docs and settings
- IP utils in common/ip_restrictions.py
2025-12-05 16:18:11 +03:00
56d1e3ae5e fix(requests): сохраняем шапку таблицы при ajax загрузке, исправлен порядок, счетчик комментариев, preventDefault для Enter
- Добавлен отдельный контейнер для данных заявлений
- JS работает только с #reqListContent, шапка всегда видна
- Исправлен порядок заявлений (order_by)
- comments_count через annotate
- Исправлен обработчик формы комментария (preventDefault)
- Удаление начального спиннера после загрузки
2025-12-05 15:59:21 +03:00
bb2dc4ca31 fix: добавлен CSRF токен в форму комментариев AJAX
- Добавлена функция getCsrfToken() для получения токена из cookie
- Добавлен скрытый input с csrfmiddlewaretoken в каждую форму
- Исправлена отправка комментариев в AJAX-режиме
2025-12-05 15:02:51 +03:00
ab05b916dd feat: полная AJAX-загрузка списка заявлений с infinite scroll
- Обновлен requestListHandler.js: рендеринг в табличном формате
- Сохранена структура таблицы req-table-header + req-row
- Шаблон: удален SSR-цикл, сохранена шапка таблицы
- Добавлены данные пользователя в dataset (userId, canProcess)
- Включен useAjaxList режим в initRequestListPage
- Удалены старые CSS для req-item (не используются)
- Структура совместима с существующими стилями request-list.css
2025-12-05 15:00:36 +03:00
589b6fabcf refactor: использование attachment_url из API + AJAX компонент для заявлений
- Шаблоны используют obj.attachment_url напрямую из API
- Удален templatetag absolute_url (больше не нужен)
- Упрощена проверка наличия вложения
- Создан requestListHandler.js для AJAX загрузки с infinite scroll
- Обновлен requestList.js для поддержки AJAX режима
- Подход аналогичен приложению документов
2025-12-05 14:53:52 +03:00
ff41eb62b0 refactor: удалены неиспользуемые файлы заявлений
- Удалены шаблоны: my_requests.html, all_requests.html (старые)
- Удален JS компонент: requestListHandler.js (неиспользуемый)
- Обновлены views: my_requests() и all_requests() теперь редиректят на requests:request_list
- Обновлены все редиректы с requests_app:my_requests на requests:request_list
- Основная страница заявлений: /requests/ (request_list_full.html)
2025-12-05 14:33:15 +03:00