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
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.
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
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
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.
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.
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.
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.
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.
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.
- 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
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.
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
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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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)
- RegistrationIPRestrictionMiddleware added
- Removed view decorators
- All logic now in middleware
- Updated docs and settings
- IP utils in common/ip_restrictions.py
- Добавлен отдельный контейнер для данных заявлений
- JS работает только с #reqListContent, шапка всегда видна
- Исправлен порядок заявлений (order_by)
- comments_count через annotate
- Исправлен обработчик формы комментария (preventDefault)
- Удаление начального спиннера после загрузки
- Добавлена функция getCsrfToken() для получения токена из cookie
- Добавлен скрытый input с csrfmiddlewaretoken в каждую форму
- Исправлена отправка комментариев в AJAX-режиме
- Обновлен requestListHandler.js: рендеринг в табличном формате
- Сохранена структура таблицы req-table-header + req-row
- Шаблон: удален SSR-цикл, сохранена шапка таблицы
- Добавлены данные пользователя в dataset (userId, canProcess)
- Включен useAjaxList режим в initRequestListPage
- Удалены старые CSS для req-item (не используются)
- Структура совместима с существующими стилями request-list.css
- Шаблоны используют obj.attachment_url напрямую из API
- Удален templatetag absolute_url (больше не нужен)
- Упрощена проверка наличия вложения
- Создан requestListHandler.js для AJAX загрузки с infinite scroll
- Обновлен requestList.js для поддержки AJAX режима
- Подход аналогичен приложению документов
- Добавлен templatetag absolute_url для преобразования относительных путей
- Обновлены все шаблоны заявлений: request_list_full, request_detail, request_process
- Теперь все ссылки на вложения используют {% absolute_url %} для полных URL
- Добавлен use_url=True для attachment_url в сериализаторе API
- Исправлена проблема с локальными URL вместо доменных
- Изменено attachment_url на serializers.FileField (как в DocumentReadSerializer)
- Удален ручной метод get_attachment_url
- DRF автоматически преобразует FileField в абсолютный URL при наличии request в контексте
- Изменено поле attachment_url на SerializerMethodField
- Добавлен метод get_attachment_url с использованием request.build_absolute_uri()
- Теперь возвращается полный абсолютный URL вместо относительного пути
- Добавлен attachment_url для полного URL к прикрепленному файлу
- Исправлен шаблон my_requests.html (удалены лишние теги)
- Теперь API заявлений работает аналогично API документов
- Создан компонент requestListHandler.js для AJAX загрузки
- Упрощен view my_requests - данные загружаются через API
- Обновлен шаблон my_requests.html на AJAX загрузку
- Добавлен поиск по типу заявления и комментарию
- Intersection Observer для автоматической подгрузки
- Фильтрация по статусу заявления
- Удалена серверная пагинация
- Добавлены спиннеры загрузки
- Убран параметр no_search из шапки страницы
- Добавлено поле поиска с placeholder
- Реализована фильтрация по названию и описанию документа
- Поиск работает на клиенте с debounce 300ms
- Фильтрация применяется ко всем загруженным документам
- Настройка обработчика поиска после первой загрузки
- Добавлен импорт initDocumentListHandler в documentList.js
- Инициализация documentListHandler с правильными параметрами
- Считывание scope и ack_status из URL параметров
- Добавление scope в API запрос
- Передача userId и canManage через data-атрибуты
- Автоматическое применение scope при инициализации
- Упрощен DocumentView - не загружает документы с сервера
- Шаблон использует спиннер вместо серверного рендеринга
- Удалена старая пагинация из шаблона
- Все документы загружаются через documentListHandler.js
- Предотвращена двойная загрузка (сервер + клиент)
- Заменена пагинация на Intersection Observer
- Документы подгружаются автоматически при прокрутке вниз
- Добавлено отслеживание nextUrl и hasMore из API
- При append рендерятся только новые документы, без дублирования
- Убраны кнопки Назад/Вперёд
- Добавлено логирование для отладки
- Сохранена фильтрация по scope и ack_status
- loadEmployees() теперь возвращает только новые записи
- render() принимает массив записей для рендеринга, а не использует this.employees
- При append=true рендерятся только новые записи, а не весь массив
- Добавлено логирование в render() для отладки
- Добавлена проверка nextUrl при append=true
- Если nextUrl пуст при подгрузке - останавливаем загрузку
- Добавлено логирование для отладки процесса загрузки
- Предотвращает повторную загрузку с начала списка
- Added intersection observer for automatic loading
- Track nextUrl and hasMore from API response
- Append new employees instead of replacing
- Removed old pagination controls from template
- Show loading spinner while fetching more data
- Упрощен employee_list view - НЕ загружает данные сотрудников
- Сервер отдает только справочники для фильтров
- Убран серверный рендеринг карточек из шаблона
- Добавлен spinner во время загрузки
- Данные загружаются один раз через JavaScript
- Производительность улучшена - нет двойного запроса