271 Commits

Author SHA1 Message Date
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
9e0e5fa01a fix: использование абсолютных URL для вложений в заявлениях
- Добавлен templatetag absolute_url для преобразования относительных путей
- Обновлены все шаблоны заявлений: request_list_full, request_detail, request_process
- Теперь все ссылки на вложения используют {% absolute_url %} для полных URL
- Добавлен use_url=True для attachment_url в сериализаторе API
- Исправлена проблема с локальными URL вместо доменных
2025-12-05 14:25:55 +03:00
1b329936bb fix: использовать FileField вместо SerializerMethodField для attachment_url
- Изменено attachment_url на serializers.FileField (как в DocumentReadSerializer)
- Удален ручной метод get_attachment_url
- DRF автоматически преобразует FileField в абсолютный URL при наличии request в контексте
2025-12-05 14:13:09 +03:00
65dd5894f7 fix: исправлена генерация attachment_url для полного URL
- Изменено поле attachment_url на SerializerMethodField
- Добавлен метод get_attachment_url с использованием request.build_absolute_uri()
- Теперь возвращается полный абсолютный URL вместо относительного пути
2025-12-05 14:08:03 +03:00
3b3e0e3697 fix: добавлено поле attachment_url в RequestReadSerializer
- Добавлен attachment_url для полного URL к прикрепленному файлу
- Исправлен шаблон my_requests.html (удалены лишние теги)
- Теперь API заявлений работает аналогично API документов
2025-12-05 13:42:59 +03:00
37e2b67c2f feat: добавлена бесконечная прокрутка для заявлений
- Создан компонент requestListHandler.js для AJAX загрузки
- Упрощен view my_requests - данные загружаются через API
- Обновлен шаблон my_requests.html на AJAX загрузку
- Добавлен поиск по типу заявления и комментарию
- Intersection Observer для автоматической подгрузки
- Фильтрация по статусу заявления
- Удалена серверная пагинация
- Добавлены спиннеры загрузки
2025-12-05 13:31:55 +03:00
a473808b10 feat: добавлен поиск документов по названию и описанию
- Убран параметр no_search из шапки страницы
- Добавлено поле поиска с placeholder
- Реализована фильтрация по названию и описанию документа
- Поиск работает на клиенте с debounce 300ms
- Фильтрация применяется ко всем загруженным документам
- Настройка обработчика поиска после первой загрузки
2025-12-05 13:19:04 +03:00
7fd191d8ef fix: добавлена инициализация AJAX загрузки документов
- Добавлен импорт initDocumentListHandler в documentList.js
- Инициализация documentListHandler с правильными параметрами
- Считывание scope и ack_status из URL параметров
- Добавление scope в API запрос
- Передача userId и canManage через data-атрибуты
- Автоматическое применение scope при инициализации
2025-12-05 13:13:43 +03:00
944e14737b refactor: переход на AJAX загрузку документов
- Упрощен DocumentView - не загружает документы с сервера
- Шаблон использует спиннер вместо серверного рендеринга
- Удалена старая пагинация из шаблона
- Все документы загружаются через documentListHandler.js
- Предотвращена двойная загрузка (сервер + клиент)
2025-12-05 13:07:57 +03:00
066bda1af5 feat: добавлена бесконечная прокрутка для списка документов
- Заменена пагинация на Intersection Observer
- Документы подгружаются автоматически при прокрутке вниз
- Добавлено отслеживание nextUrl и hasMore из API
- При append рендерятся только новые документы, без дублирования
- Убраны кнопки Назад/Вперёд
- Добавлено логирование для отладки
- Сохранена фильтрация по scope и ack_status
2025-12-05 13:03:57 +03:00
b036e2412c fix: исправлено дублирование записей при подгрузке
- loadEmployees() теперь возвращает только новые записи
- render() принимает массив записей для рендеринга, а не использует this.employees
- При append=true рендерятся только новые записи, а не весь массив
- Добавлено логирование в render() для отладки
2025-12-05 12:59:31 +03:00
4ccc85f9f8 fix: исправлена ссылка на чат с сотрудником
- Изменен URL с /communications/chats/private/ на /communications/chats/start/
- Теперь соответствует правильному роуту start_private_chat
2025-12-05 12:56:14 +03:00
1b967a34c9 fix: предотвращение дублирования при бесконечной прокрутке
- Добавлена проверка nextUrl при append=true
- Если nextUrl пуст при подгрузке - останавливаем загрузку
- Добавлено логирование для отладки процесса загрузки
- Предотвращает повторную загрузку с начала списка
2025-12-05 12:54:34 +03:00
c4d2662fcf fix: правки после внедрения бесконечной прокрутки сотрудников 2025-12-05 12:51:00 +03:00
881743bc1f feat: add infinite scroll to employees list
- 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
2025-12-05 12:39:35 +03:00
e31972b7aa fix: убрана двойная загрузка данных на странице списка сотрудников
- Упрощен employee_list view - НЕ загружает данные сотрудников
- Сервер отдает только справочники для фильтров
- Убран серверный рендеринг карточек из шаблона
- Добавлен spinner во время загрузки
- Данные загружаются один раз через JavaScript
- Производительность улучшена - нет двойного запроса
2025-12-05 12:35:10 +03:00
785a82f54b feat: переделана страница списка сотрудников на AJAX загрузку
- Создан новый JS модуль employeesList.js
- Список сотрудников загружается через API /api/v1/employees/
- Аватары получают правильные глобальные URL
- Сохранена поддержка фильтрации и поиска
- Передается ID текущего пользователя для скрытия кнопок
- Добавлена обработка ошибок загрузки
- Исправлена проблема с localhost URL в аватарах
2025-12-05 12:28:59 +03:00
d22b297651 feat: переделана страница профиля на AJAX загрузку
- Создан новый JS модуль employeeProfile.js
- Аватар сотрудника загружается через API с глобальными URL
- Посты сотрудника загружаются через FeedList с правильными URL медиа
- Добавлены ID контейнеров для динамической загрузки (#employeeAvatar, #employeeName, #employeePosts)
- Подключены скрипты для лайков, комментариев и модала деталей
- Добавлен emoji-picker для форм комментариев
- Добавлен модал для просмотра публикаций
- Исправлена проблема с localhost URL в аватарах и медиа постов
2025-12-05 12:21:30 +03:00
5550f7e45a fix: прыжок автоскроллера теперь происходит в середине контента
- Вычисляется loopPoint как blockScrollWidth * floor(totalCopies/2)
- Прыжок происходит реже (в середине вместо начала)
- Переход стал менее заметным для пользователя
- Добавлено логирование loopPoint для отладки
2025-12-05 11:11:09 +03:00
fcc52317cd fix: добавлен cache-busting для динамического импорта autoScrollerHandler
- Добавлен timestamp параметр в URL импорта
- Браузер будет загружать свежую версию вместо кешированной
- Исправлена проблема с устаревшими скриптами
2025-12-05 11:10:02 +03:00