103 Commits

Author SHA1 Message Date
c1a907cd60 feat(ui): restyle message composers 2025-11-28 11:56:47 +03:00
70d0260919 Fix: подключение ChatComposer.js и очистка шаблона 2025-11-28 10:09:23 +03:00
c97c2f329b Debug: добавлена подробная отладка отправки сообщений 2025-11-28 08:47:05 +03:00
f7f6308953 Fix: исправлены цвета файлов и двойная отправка сообщений 2025-11-28 08:34:36 +03:00
af23136a6d Fix: убраны рамки у файлов, исправлены цвета текста, откачены проблемные изменения видео 2025-11-28 08:26:06 +03:00
91bc8386a1 Fix: исправлена загрузка видео и стилизация вложений
Исправление видео:
- Видео элементы создаются с уникальными ID
- src устанавливается после добавления в DOM через requestAnimationFrame
- Используется preload='auto' вместо 'metadata' для немедленной загрузки
- video.load() вызывается после установки src

Стилизация вложений:
- Убран bg-light у ссылок на файлы
- Добавлены стили .message-attachments для прозрачного фона
- Для bubble-me используется rgba(255,255,255,0.15) фон
- Для обычных сообщений используется rgba(0,0,0,0.05) фон
- Добавлены hover эффекты
- Файлы теперь соответствуют цвету сообщения
2025-11-28 08:19:15 +03:00
eae685eacf Fix: улучшена загрузка видео и сделан текст необязательным
Исправления видео:
- Видео элементы теперь создаются программно через createElement
- Удалён setTimeout, добавлена прямая замена placeholder'ов
- video.load() вызывается сразу после создания элемента
- Исправлен доступ к правильному контейнеру вложения

Текст необязателен при файлах:
- Удалён атрибут required у textarea
- Добавлена валидация: должен быть либо текст, либо файлы
- При отправке файла без текста отправляется пустая строка
- Показывается alert если нет ни текста, ни файлов
2025-11-28 08:14:08 +03:00
116547621b Fix: исправлена загрузка видео в чате
- Добавлен атрибут preload='metadata' для video элементов
- Добавлен текст-заглушка 'Ваш браузер не поддерживает видео'
- Добавлена принудительная загрузка video.load() после добавления в DOM
- Исправлено как в шаблоне, так и в JavaScript для WebSocket сообщений

Теперь видео загружается сразу после отправки без перезагрузки страницы
2025-11-28 08:10:19 +03:00
3b7786c32f Feature: отправка сообщений с файлами через WebSocket
- Добавлена отправка сообщения через WebSocket после создания в API
- Используется channel_layer.group_send для рассылки всем участникам
- Сообщение с вложениями теперь появляется в чате мгновенно
- Не требуется перезагрузка страницы

Импорты:
- async_to_sync для синхронного вызова асинхронного кода
- get_channel_layer для доступа к WebSocket
- serialize_message для форматирования данных
2025-11-28 08:06:45 +03:00
446d59f0fa Fix: исправлена проверка доступа к чату при загрузке файлов
- Добавлена поддержка разных типов чатов (private, global, department, group)
- Для личных чатов проверяется участие через participants
- Для чатов отдела проверяется принадлежность к отделу
- Для глобального чата проверяется только is_active
- Для групповых/канальных чатов используется ChatMembership

Настройки CSRF:
- CSRF_COOKIE_HTTPONLY = False
- CSRF_COOKIE_SAMESITE = 'Lax'
- CSRF_USE_SESSIONS = False
2025-11-28 08:04:09 +03:00
6df487bd93 Fix: исправлена ошибка 403 при загрузке файлов в чат
- Добавлен декоратор @ensure_csrf_cookie в API view
- Изменён способ получения CSRF токена: теперь берётся из cookie через getCookie()
- Добавлена функция getCookie() в chat_detail.html

Причина ошибки: CSRF токен брался из формы вместо cookie при AJAX запросе
2025-11-28 07:52:11 +03:00
cc71038c5e Refactor: перенос API загрузки файлов в приложение api
- Создан api/v1/communications/views.py с функцией upload_message_with_attachments
- Добавлен endpoint /api/v1/communications/upload-message/
- Обновлён frontend для использования правильного API пути
- Удалён дублирующий код из communications/api_views.py
- Обновлён communications/urls.py (убран старый endpoint)

Теперь все API эндпоинты находятся в приложении api, как и должно быть
2025-11-28 07:48:47 +03:00
d7139f7f84 Feature: реализована отправка файлов в чате
Backend:
- Добавлен API endpoint /communications/api/upload-message/ для загрузки сообщений с файлами
- Обновлён consumers.py: добавлена сериализация вложений в serialize_message()
- Поддержка 4 типов файлов: image, video, audio, file
- Автоопределение типа по MIME

Frontend:
- Обновлён chat_detail.html: отправка файлов через fetch API вместо alert
- Добавлено отображение вложений в шаблоне (изображения, аудио, видео, документы)
- Обновлён chatMessageTemplates.js: рендеринг вложений для WebSocket сообщений
- Добавлена функция formatFileSize() для отображения размера файлов

Модель MessageAttachment уже существовала, миграции применены
2025-11-27 18:12:09 +03:00
b0f0fdb516 Fix: убрана полоска прокрутки у поля ввода чата и улучшена обработка вложений
- Убрана полоска скролла у textarea (overflow-y: hidden, scrollbar-width: none)
- Исправлена логика обработки вложений: теперь файлы хранятся в массиве
- Улучшено удаление отдельных файлов из превью
- Добавлена обработка отправки формы с файлами (подготовка к API)
- Пока отправка файлов показывает предупреждение о будущей реализации
2025-11-27 17:59:24 +03:00
edc1b578ee Redesign: современный интерфейс чата в стиле мессенджеров
Изменения в chat_detail.html:
- Убрана кнопка с фотографией из композера
- Кнопка вложений встроена в строку ввода с выпадающим меню
- Добавлено выпадающее меню с опциями: Документ, Фото/видео, Камера, Аудио
- Добавлены скрытые input для каждого типа файлов
- Реализовано превью прикрепленных файлов
- Добавлен JavaScript для обработки выбора и отображения файлов

Изменения в chat-detail.css:
- Обновлен стиль композера под современные мессенджеры
- Круглые кнопки вложений и отправки (40px)
- Поле ввода с закругленными углами (border-radius: 20px)
- Анимации hover для кнопок (scale 1.05)
- Стили для превью вложений
- Улучшенное выпадающее меню с иконками и transition эффектами
2025-11-27 17:55:02 +03:00
2f9d3a6ee7 Fix: убрана лишняя запятая в именах участников чата
- Исправлен шаблон chat_list.html для личных чатов
- Использован {% cycle %} для правильного разделения имен участников
- Теперь запятая не отображается перед первым именем
2025-11-27 17:36:58 +03:00
dc4e983a74 Fix: чаты и LDAP
- Добавлен CSRF токен в модальные окна (createDepartmentModal, createChatModal)
- Исправлена работа групповых чатов (group/channel/announcement):
  * Добавлена проверка доступа через ChatMembership в views и consumers
  * Групповые чаты теперь отображаются в списке
  * WebSocket подключается корректно без бесконечных перезагрузок
- API create_chat теперь читает JSON вместо POST данных
- Изменена отправка сообщений: Enter вместо Ctrl+Enter, Shift+Enter для переноса строки
- Добавлен сертификат LDAP (corp-ca.pem)
- Отключен LDAP в локальном .env для разработки (USE_SQLITE=True, LDAP_ENABLED=False)
2025-11-27 17:23:13 +03:00
4cf6828536 Fix CSRF token missing error in department creation modal 2025-11-27 15:08:00 +03:00
40b7e5d39d Fix email verification: check LdapSyncState instead of model attributes, handle LDAP errors gracefully 2025-11-21 16:31:33 +03:00
9cc26b70a6 Fix registration: update LDAP paths, fix email verification create_user call 2025-11-21 15:46:02 +03:00
8fe844780e Fix ApiResponse.content error and add API base URL logging
- Changed resp.content to resp.text in register_view (ApiResponse has no content attribute)
- Added logging for API base URL to debug 404 errors
- This should help identify why API returns 404 for registration endpoint
2025-11-21 13:39:06 +03:00
2637e9ed65 Add detailed logging for registration debugging
- Added logging in RegisterAPIView to track incoming data and validation errors
- Added logging in register_view to track form data and API communication
- Created test_register_api.py script for testing registration API
- Logs include: POST data, Content-Type, validation errors, API payload and responses
- All logs use [REGISTER] and [REGISTER_VIEW] prefixes for easy filtering
2025-11-21 13:35:38 +03:00
08c5c4a895 chore: Update requirements.txt with all dependencies organized by category
- Added missing dependencies (djangorestframework_simplejwt, social-auth, redis, etc.)
- Organized packages by categories (Core, Auth, Database, Telegram, etc.)
- Updated python-dotenv to v1.1.1
- Added cryptography, httpx, beautifulsoup4 for completeness
2025-11-21 12:57:01 +03:00
0f167fc8ff docs: Add comprehensive README.md with project description and setup instructions 2025-11-21 12:51:20 +03:00
b4ba030c7f chore: Remove temporary documentation files from backend directory 2025-11-21 12:47:36 +03:00
35f365a1b0 feat: Add department-based document distribution with department picker in UI
- Added departments ManyToMany field to Document model
- Implemented department selection in document create/edit modals
- Added automatic notification creation for all department employees
- Fixed document filtering to include uploaded documents in 'My Documents'
- Fixed acknowledgements API to include department recipients
- Added bulk notification support with configurable threshold
- Removed acknowledge button, added visual highlighting for unread documents
- Implemented server-side acknowledgment flow with redirect to file
- Fixed mobile responsive layout for document actions
- Removed temporary test files and documentation
2025-11-21 12:46:43 +03:00
930087143e Merge branch 'merge/master-and-ldap-writeback': JWT auto-refresh и система уведомлений
- Автоматическое обновление JWT токенов (исправление 403 ошибок)
- Проактивное обновление токена за 5 минут до истечения
- JWTRefreshMiddleware для фонового обновления
- Полная система уведомлений (5 модулей интегрированы)
- Улучшения мессенджера (реакции, пересылка, редактирование)
2025-11-20 18:54:04 +03:00
ddf22c47da fix: автоматическое обновление JWT токенов
- ApiClient теперь обрабатывает 401 и 403 ошибки для обновления токена
- Добавлен JWTRefreshMiddleware для проактивного обновления токенов за 5 минут до истечения
- Добавлена настройка JWT_REFRESH_THRESHOLD_MINUTES (по умолчанию 5)
- Исправлена проблема с периодическими 403 ошибками после истечения access token
2025-11-20 18:52:29 +03:00
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