106 Commits

Author SHA1 Message Date
Fedor
e630d03e67 Support chat mobile UX: fix keyboard overlap and improve composer.
Hide bottom navigation while typing and in support chat mode, adapt chat layout to visual viewport/keyboard insets, and enlarge the message composer so input remains visible and comfortable in TG/MAX mobile webviews.
2026-03-02 08:22:26 +03:00
Fedor
66a0065df8 Consultations, CRM dashboard, Back button in support and consultations
- Consultations: list from DraftsContext, ticket-detail webhook, response card
- Back button in bar on consultations and in support chat (miniapp:goBack)
- BottomBar: back enabled on /support; Support: goBack subscription
- n8n: CRM normalize (n8n_CODE_CRM_NORMALIZE), flatten data (n8n_CODE_FLATTEN_DATA)
- Dashboard: filter by category for CRM items, draft card width
- Backend: consultations.py, ticket-detail, n8n_ticket_form_podrobnee_webhook
- CHANGELOG_MINIAPP.md: section 2026-02-25
2026-03-01 10:49:38 +03:00
Fedor
c39b12630e Профиль: валидация, календарь, ИНН 12 цифр, email, DaData адреса, банки из BANK_IP, подсказка ИНН (ФНС)
- Backend: N8N_AUTH_WEBHOOK из env (fallback), банки из BANK_IP, эндпоинт
  /api/v1/profile/dadata/address для подсказок адресов (FORMA_DADATA_*).
- Config: bank_ip, bank_api_url, forma_dadata_api_key, forma_dadata_secret.
- Frontend Profile: DatePicker для даты рождения, ИНН 12 цифр + ссылка на ФНС,
  валидация email, чекбокс «Совпадает с адресом регистрации», AutoComplete
  адресов через DaData, Select банков из /api/v1/banks/nspk (bankId/bankName).

Подробности в CHANGELOG_PROFILE_VALIDATION.md.
2026-02-27 18:32:06 +03:00
Fedor
b5c31b43dd Banner: system banners zone carousel mobile layout remove Home from Profile 2026-02-27 15:56:40 +03:00
Fedor
06b89d20e7 Support: маршрут /support на страницу чата поддержки
- App.tsx: добавлен импорт страницы Support и роутинг pathname === '/support' на компонент Support.
- При клике на иконку «Поддержка» в нижнем баре теперь открывается список обращений и чат, а не форма «Мои обращения».
2026-02-27 10:13:19 +03:00
Fedor
9c65b6a4ea Profile: редактируемый профиль при verification="0", сохранение через N8N_PROFILE_UPDATE_WEBHOOK
- Backend: config.py — добавлена настройка n8n_profile_update_webhook (читает N8N_PROFILE_UPDATE_WEBHOOK из .env).
- Backend: profile.py — общий хелпер _resolve_profile_identity(), обновлён _fetch_contact(), новый эндпоинт POST /api/v1/profile/contact/update, который отправляет данные профиля в N8N_PROFILE_UPDATE_WEBHOOK.
- Frontend: Profile.tsx — если verification === "0", показывается форма редактирования (все поля, кроме телефона, обязательны к заполнению, телефон только для чтения) и сохранение вызывает /api/v1/profile/contact/update; иначе профиль остаётся только для просмотра.
2026-02-27 08:34:27 +03:00
Fedor
62fc57f108 Auth: multibot TG MAX logging fix 500 2026-02-27 07:48:16 +03:00
Fedor
b3a7396d32 Support: chat, tickets list, SSE Postgres NOTIFY, read/unread 2026-02-25 23:18:45 +03:00
Fedor
d8fe0b605b Unified auth and sessions: POST /api/v1/auth, session by channel:id and token, need_contact fix, n8n parsing, TTL 24h 2026-02-24 16:17:59 +03:00
Fedor
6350f9015b Mini-app updates: UI TG MAX session nav logs 2026-02-23 11:31:52 +03:00
Fedor
4536210284 Draft detail and Back button 2026-02-21 22:08:30 +03:00
root
8c3e993eb7 feat: add soft ui auth page 2026-02-20 09:31:13 +03:00
AI Assistant
2e45786e46 feat: Telegram Mini App integration and UX improvements
- Добавлена полная интеграция с Telegram Mini App (динамическая загрузка SDK)
- Отдельный компактный дизайн для Telegram Mini App
- Добавлен loader при инициализации (предотвращает мелькание SMS-авторизации)
- Улучшена навигация: кнопки "Назад" и "К списку заявок" теперь сохраняют авторизацию
- Telegram Mini App: кнопка "Выход" просто закрывает приложение
- Telegram Mini App: заявки "В работе" скрыты из списка
- Веб-версия: для заявок "В работе" добавлена кнопка "Просмотреть в Telegram" (ссылка на @klientprav_bot)
- Telegram Mini App: кнопки действий в черновиках расположены вертикально
- Веб-версия: убрано отображение номера телефона в приветствии
- Исправлена проблема с возвратом к списку черновиков (не требует повторной SMS-авторизации)
- Заблокировано удаление и редактирование заявок со статусом "В работе"
- Добавлена документация по Telegram Mini App интеграции
2026-01-29 16:12:48 +03:00
Fedor
73524465fd feat: Обновления после последнего коммита
Изменения в backend:
- Обновления в n8n_proxy.py
- Изменения в SMS API
- Обновления конфигурации
- Улучшения SMS сервиса

Изменения в frontend:
- Обновления Step1Phone компонента
- Изменения в Step3Payment
- Улучшения generateConfirmationFormHTML
- Обновления ClaimForm страницы
- Изменения в vite.config.ts

Статистика: +242 строки, -81 строка
2026-01-02 17:37:37 +03:00
Fedor
f7d27388a0 feat: Add SMS debug code modal for dev environment 2025-12-29 10:59:21 +03:00
AI Assistant
30774db18c Production fixes: n8n workflow auto-restart, user-friendly messages, fixed navigation buttons 2025-12-29 01:19:19 +03:00
AI Assistant
080e7ec105 feat: Получение cf_2624 из MySQL и блокировка полей при подтверждении данных
- Добавлен сервис CrmMySQLService для прямого подключения к MySQL CRM
- Обновлён метод get_draft() для получения cf_2624 напрямую из БД
- Реализована блокировка полей (readonly) при contact_data_confirmed = true
- Добавлен выбор банка для СБП выплат с динамической загрузкой из API
- Обновлена документация по работе с cf_2624 и MySQL
- Добавлен network_mode: host в docker-compose для доступа к MySQL
- Обновлены компоненты формы для поддержки блокировки полей
2025-12-04 12:22:23 +03:00
AI Assistant
64385c430d fix: Исправление логики загрузки документов и расчёта прогресса
- Исправлена ошибка порядка объявления allDocsProcessed (Cannot access before initialization)
- Исправлена логика поиска незагруженного документа: поиск с начала, если сохранённый индекс уже обработан
- Исправлен расчёт прогресса: теперь используется количество обработанных документов (uploadedDocs + skippedDocs), а не currentDocIndex
- Убрана синхронизация currentDocIndex из formData, которая перезаписывала правильный индекс
- Добавлена логика автоматического пропуска уже загруженных документов при открытии формы
- Добавлено подробное логирование для отладки состояния документов
- Исправлена логика определения завершённости: проверяется каждый документ из documentsRequired

Результат:
- Форма корректно показывает следующий незагруженный документ
- Прогресс правильно отображает процент обработанных документов (75% при 3 из 4)
- Система не требует повторной загрузки уже загруженных документов
2025-11-27 14:36:42 +03:00
AI Assistant
02689e65db fix: Исправление загрузки документов и SQL запросов
- Исправлена потеря документов при обновлении черновика (SQL объединяет вместо перезаписи)
- Исправлено определение типа документа (приоритет field_label над field_name)
- Исправлены дубликаты в documents_meta и documents_uploaded
- Добавлена передача group_index с фронтенда для правильного field_name
- Исправлены все документы в таблице clpr_claim_documents с правильными field_name
- Обновлены SQL запросы: claimsave и claimsave_final для нового флоу
- Добавлена поддержка multi-file upload для одного документа
- Исправлены дубликаты в списке загруженных документов на фронтенде

Файлы:
- SQL: SQL_CLAIMSAVE_FIXED_NEW_FLOW.sql, SQL_CLAIMSAVE_FINAL_FIXED_NEW_FLOW_WITH_UPLOADED.sql
- n8n: N8N_CODE_PROCESS_UPLOADED_FILES_FIXED.js (поддержка group_index)
- Backend: documents.py (передача group_index в n8n)
- Frontend: StepWizardPlan.tsx (передача group_index, исправление дубликатов)
- Скрипты: fix_claim_documents_field_names.py, fix_documents_meta_duplicates.py

Результат: документы больше не теряются, имеют правильные типы и field_name
2025-11-26 19:54:51 +03:00
AI Assistant
9c159eda21 fix: Add protection to prevent saveFormData without SMS code
Added validation to ensure saveFormData is only called after SMS verification:
- Check if SMS code is provided
- Show error message if called without SMS code
- Prevent data from being sent to Redis without verification

This prevents accidental form submission without SMS approval.

Files:
- frontend/src/components/form/StepClaimConfirmation.tsx
2025-11-25 14:34:44 +03:00
AI Assistant
b71f079699 debug: Add logging for SMS code in saveFormData
Added console logs to track SMS code:
- Log SMS code when saveFormData is called
- Log payload with masked SMS code before sending to Redis
- This will help debug why SMS code might not appear in Redis channel

Files:
- frontend/src/components/form/StepClaimConfirmation.tsx
2025-11-25 14:26:58 +03:00
AI Assistant
116ea17b4a feat: Add SMS code to Redis channel data
Added SMS code to form approval data:
- Frontend: Pass SMS code to saveFormData function
- Frontend: Include sms_code in payload sent to backend
- Backend: Include sms_code in Redis event data

This allows n8n workflow to access the verified SMS code for logging/audit purposes.

Files:
- frontend/src/components/form/StepClaimConfirmation.tsx
- backend/app/api/claims.py
2025-11-25 13:43:13 +03:00
AI Assistant
f439ba76f3 fix: Remove premature smsForm.resetFields() call to fix React warning
Fixed warning: 'Instance created by useForm is not connected to any Form element'
- Removed resetFields() call before form is rendered
- Form is only rendered when smsCodeSent === true
- Added preserve={false} to Form to ensure clean state
- Updated handleCancelSMS to only reset if form was rendered

Files:
- frontend/src/components/form/StepClaimConfirmation.tsx
2025-11-25 13:34:23 +03:00
AI Assistant
23a236a036 fix: Move React hooks before conditional render in StepClaimConfirmation
Fixed React Hooks order violation:
- Moved handleSendCode, handleVerifyCode, handleCancelSMS useCallback hooks BEFORE conditional render
- Changed handleCancelSMS to useCallback for consistency
- Moved phone/displayPhone calculations before conditional render
- All hooks now called in the same order on every render

This fixes the error: 'Rendered more hooks than during the previous render'

Files:
- frontend/src/components/form/StepClaimConfirmation.tsx
2025-11-25 12:37:46 +03:00
AI Assistant
13070a2100 fix: Change Redis channel to fixed name clientright:webform:approve
Changed from dynamic channel form_approve:{claim_id} to fixed channel:
- Channel: clientright:webform:approve
- Simpler n8n subscription (no need for dynamic channel name)
- All form approvals go to the same channel

Files:
- backend/app/api/claims.py
- frontend/src/components/form/StepClaimConfirmation.tsx
- docs/REDIS_FORM_APPROVE.md
2025-11-25 12:32:51 +03:00
AI Assistant
de092755af feat: Switch form approval to Redis channel instead of webhook
Changed from webhook to Redis Pub/Sub channel:
- Created endpoint POST /api/v1/claims/approve
- Publishes to Redis channel: form_approve:{claim_id}
- Added idempotency_key for future RabbitMQ integration
- Fire-and-forget approach (no waiting for response)

Benefits:
- Higher performance (Redis Pub/Sub is faster)
- Better scalability
- Ready for RabbitMQ queue integration
- Idempotency key included for duplicate protection

Files:
- backend/app/api/claims.py (new /approve endpoint)
- frontend/src/components/form/StepClaimConfirmation.tsx (updated saveFormData)
- docs/REDIS_FORM_APPROVE.md (documentation)
2025-11-25 12:29:36 +03:00
AI Assistant
82f4bf818b feat: Send form approval data to webhook without waiting for response
Simplified approach:
- Removed backend endpoint /approve (will use direct webhook)
- Updated saveFormData to send data directly to n8n webhook
- Fire-and-forget approach: no waiting for response
- Show success message 'Ваше заявление отправлено!' after SMS verification
- Uses webhook URL: https://n8n.clientright.pro/webhook/eebe58d4-0bcd-4d09-9d62-39868b110960

Flow:
1. User confirms form → SMS modal appears
2. SMS code sent automatically
3. User enters code → verified
4. Data sent to webhook (fire-and-forget)
5. Success message shown
6. Navigate to next step

Files:
- frontend/src/components/form/StepClaimConfirmation.tsx
- backend/app/api/claims.py (removed /approve endpoint)
2025-11-25 11:58:29 +03:00
AI Assistant
c9a2b95983 feat: Add SMS approval before form submission
Implemented SMS verification modal before saving confirmed form data:
- Added SMS modal component in StepClaimConfirmation.tsx
- Intercept claim_confirmed event and show SMS modal
- Send SMS code automatically when form is confirmed
- Verify SMS code before proceeding to save data
- Phone number extracted from claimPlanData (applicant.phone, user.mobile, or phone)
- Added saveFormData placeholder for future implementation

Features:
- Modal with SMS code input field
- Auto-send SMS code on form confirmation
- Code validation (6 digits, numbers only)
- Resend code functionality
- Cancel option
- Proper error handling

TODO: Implement saveFormData function to save form data to backend/n8n

Files:
- frontend/src/components/form/StepClaimConfirmation.tsx
2025-11-25 11:40:32 +03:00
AI Assistant
de56bc13cd fix: Replace deprecated bodyStyle with styles.body in StepClaimConfirmation
Ant Design warning:
- bodyStyle prop is deprecated
- Use styles.body instead

Changed:
- StepClaimConfirmation.tsx: Replaced bodyStyle with styles={{ body: {...} }}

Files:
- frontend/src/components/form/StepClaimConfirmation.tsx
2025-11-24 18:01:46 +03:00
AI Assistant
8c85eda7ac fix: Use attachments array instead of attachments_names in old format normalizeData 2025-11-24 17:58:17 +03:00
AI Assistant
6bf5cfad26 feat: Add green border for filled fields and use field_label for documents
Changes:
1. Added green border styling for filled form fields (.filled class)
   - Green border (#10b981) and light green background (#f0fdf4)
   - Applied automatically when field has value
   - Works for inputs, textareas, and checkboxes

2. Updated document display to use field_label instead of filename
   - Changed ClaimForm.tsx to include field_label in attachments
   - Updated normalizeData to use full attachments array with field_label
   - Display shows field_label if available, falls back to filename

3. Added updateFieldStyle function
   - Updates field styling on input, blur, and change events
   - Automatically applies filled class when field has value

Files:
- frontend/src/pages/ClaimForm.tsx: Added field_label to attachments
- frontend/src/components/form/generateConfirmationFormHTML.ts:
  - Added .filled CSS class with green border
  - Added updateFieldStyle function
  - Updated document display to use field_label
  - Updated normalizeData to use attachments array
2025-11-24 17:57:47 +03:00
AI Assistant
f82df1ebd7 fix: Add propertyName to caseJson for iframe form data
Problem:
- Form was empty because propertyName was not passed to iframe
- JavaScript code checked for injected.propertyName but it was undefined
- Only case (normalized) was passed, not the original propertyName

Solution:
- Added propertyName to caseJson object that gets embedded in HTML
- Now JavaScript code can access both case and propertyName
- This allows the form to properly display data from send_to_form_approve.draft

Files:
- frontend/src/components/form/generateConfirmationFormHTML.ts: Added propertyName to caseJson
2025-11-24 17:44:30 +03:00
AI Assistant
29a9fe7532 fix: Use payload.send_to_form_approve.draft data directly instead of converting
Problem:
- Data already exists in DB in propertyName format at payload.send_to_form_approve.draft
- We were trying to convert from wizard_answers instead of using existing data
- Form was empty because we ignored the correct data structure

Solution:
1. Added priority check for payload.send_to_form_approve.draft:
   - If exists, use it directly (PRIORITY 1)
   - If not, fall back to conversion from wizard_answers (PRIORITY 2)

2. Direct usage of send_to_form_approve.draft:
   - Extract propertyName structure directly from draft
   - Preserve all fields: applicant, case, contract_or_service, offenders, claim, meta, attachments
   - Use unified_id from draft.meta or fallback to claim/formData

3. Enhanced logging:
   - Logs if send_to_form_approve.draft found
   - Logs draft data structure
   - Logs result structure

Files:
- frontend/src/pages/ClaimForm.tsx: Use send_to_form_approve.draft directly
2025-11-24 16:42:16 +03:00
AI Assistant
717295eb02 feat: Complete wizard_answers to propertyName conversion from DB data
Problem:
- Data comes from DB in wizard_answers format (answers to wizard questions)
- Form confirmation expects propertyName format (structured data)
- transformDraftToClaimPlanFormat tried to extract propertyName from DB, but it doesn't exist
- Form shows empty because propertyName structure is empty

Solution:
1. Added complete field mapping from wizard_answers to propertyName:
   - answersParsed.item → contract_or_service.subject
   - answersParsed.price → contract_or_service.amount_paid (normalized)
   - answersParsed.place_date → contract_or_service.agreement_date
   - answersParsed.cancel_date → contract_or_service.period_start
   - answersParsed.steps_taken → claim.description
   - answersParsed.expectation → claim.reason
   - payload.problem_description → claim.description and contract.subject

2. Added applicant data extraction:
   - phone from claim.phone, payload.phone, body.phone, or formData.phone
   - email from claim.email, payload.email, body.email, or formData.email
   - Other applicant fields (FIO, birth_date, INN) will be filled in confirmation form

3. Added default values:
   - case.category = 'consumer'
   - case.direction = 'web_form'

4. Enhanced logging:
   - Logs what data exists in DB
   - Logs wizard_answers keys
   - Logs conversion process

Files:
- frontend/src/pages/ClaimForm.tsx: Complete wizard_answers conversion
2025-11-24 16:35:27 +03:00
AI Assistant
4516fe8bfe feat: Add wizard_answers to propertyName conversion mapping
Problem:
- Data comes from DB in wizard_answers format (answers to wizard questions)
- Form confirmation expects propertyName format (structured data: applicant, case, contract_or_service)
- transformDraftToClaimPlanFormat tried to extract propertyName data from DB, but it doesn't exist there
- Form shows empty because propertyName structure is empty

Solution:
1. Added wizard_answers parsing from multiple sources:
   - body.answers, payload.answers
   - body.wizard_answers, payload.wizard_answers

2. Added basic field mapping from wizard_answers to propertyName:
   - answersParsed.item → contract_or_service.subject
   - answersParsed.price → contract_or_service.amount_paid
   - answersParsed.place_date → contract_or_service.agreement_date
   - answersParsed.steps_taken → claim.description

3. Added logging to debug data flow:
   - Logs what data exists in DB
   - Logs wizard_answers parsing
   - Logs conversion process

Note: This is a basic mapping. Full conversion requires complete field mapping from wizard_answers to propertyName structure.

Files:
- frontend/src/pages/ClaimForm.tsx: Added wizard_answers conversion
2025-11-24 16:33:16 +03:00
AI Assistant
d9414b32ad fix: Remove incorrect formData.case.meta access causing crash
Problem:
- Line 77 tried to access formData.case.meta
- formData structure changed to propertyName format
- formData.case doesn't exist, causing runtime error
- Form shows blank screen due to crash

Solution:
- Removed incorrect formData.case.meta access
- Added proper logging for formData and propertyName structure
- Form should now render correctly

Files:
- frontend/src/components/form/StepClaimConfirmation.tsx: Fixed formData access
2025-11-24 16:25:50 +03:00
AI Assistant
d34712f666 fix: Correct data extraction logic in JavaScript for propertyName format
Problem:
- When data comes as { propertyName: {...}, ... }, dataCandidate was set to propertyName object
- normalizeData expects { propertyName: {...} } format, not just propertyName
- Data normalization failed because structure didn't match

Solution:
- Changed logic to use entire injected object when propertyName exists
- This ensures normalizeData receives correct structure
- Data should now normalize correctly and populate form fields

Files:
- frontend/src/components/form/generateConfirmationFormHTML.ts: Fixed data extraction logic
2025-11-24 16:17:29 +03:00
AI Assistant
fc3ecdb63f fix: Pass data in propertyName format to match n8n structure
Problem:
- Data was being passed in normalized 'case' format
- generateConfirmationFormHTML expects propertyName format for normalization
- Form fields were empty because normalization didn't work correctly

Solution:
- Changed StepClaimConfirmation to pass data in propertyName format
- This matches the structure expected by normalizeData function
- Function can now properly normalize data from propertyName to case format
- All fields should now populate correctly

Files:
- frontend/src/components/form/StepClaimConfirmation.tsx: Changed data format to propertyName
2025-11-24 16:16:45 +03:00
AI Assistant
5e59a15bae feat: Increase iframe size and add auto-resize functionality
Problem:
- Form iframe was too small (800px fixed height)
- Only spinner visible, form content not fully visible

Solution:
1. Increased iframe container:
   - Changed Card bodyStyle to use calc(100vh - 200px)
   - Set minHeight to 800px
   - Made iframe flex: 1 to fill available space

2. Added auto-resize functionality:
   - Form sends iframe_resize messages with height
   - Parent component listens and adjusts iframe height
   - ResizeObserver watches for content changes
   - Window resize handler updates iframe size

3. Improved iframe styling:
   - Added sandbox attributes for security
   - Made height responsive (100% of container)
   - Minimum height ensures form is always visible

Files:
- frontend/src/components/form/StepClaimConfirmation.tsx: Increased iframe size, added resize handler
- frontend/src/components/form/generateConfirmationFormHTML.ts: Added auto-resize messaging
2025-11-24 16:03:25 +03:00
AI Assistant
08d59b9522 fix: Remove duplicate caseObj declaration
Problem:
- caseObj was declared twice: once at line 6 and again at line 270
- Caused esbuild compilation error

Solution:
- Removed first declaration at line 6
- Updated smsInputData extraction to handle multiple data formats
- caseObj is now only declared after normalization at line 270

Files:
- frontend/src/components/form/generateConfirmationFormHTML.ts: Fixed duplicate declaration
2025-11-24 15:59:40 +03:00
AI Assistant
67e0ff400e feat: Add normalizeData function matching n8n implementation
Problem:
- Form didn't handle data in propertyName format from n8n
- Missing normalization logic from n8n Code node

Solution:
1. Added normalizeData function in TypeScript:
   - Handles propertyName format (new format from n8n)
   - Handles old format (applicant, case, contract_or_service)
   - Handles case format (current structure)
   - Converts field names (first_name -> firstname, etc.)
   - Normalizes money values
   - Extracts attachments_names

2. Added normalizeData function in JavaScript:
   - Same logic as TypeScript version
   - Handles data extraction from multiple sources:
     * propertyName (object or string)
     * value
     * data
     * output
     * case
   - Supports array format (takes first element)

3. Enhanced data extraction logic:
   - Checks multiple data sources
   - Handles both array and object formats
   - Merges SMS meta data from injected
   - Ensures base structures exist

Files:
- frontend/src/components/form/generateConfirmationFormHTML.ts: Added normalization logic
2025-11-24 15:58:17 +03:00
AI Assistant
206e62ce76 feat: Add full confirmation form functionality matching n8n structure
Problem:
- Form was simplified and didn't match n8n implementation
- Missing validation, button state updates, checkbox handling
- Missing full statement text with consent checkbox

Solution:
1. Added complete renderStatement function:
   - Возмещение section with SBP phone display
   - Full ЗАЯВЛЕНИЕ text with all fields inline
   - Period fields (startdate/finishdate)
   - Full offender fields (email, phone, website)
   - Consent checkbox for privacy policy
   - Attachments list display

2. Added validation functions:
   - validateAllFields - checks all required fields
   - updateSubmitButton - updates button state based on consent and validation
   - Field validation helpers (isValidPhone, isValidEmail, isValidINN, etc.)

3. Enhanced attachBindings:
   - Date field conversion (YYYY-MM-DD <-> DD.MM.YYYY)
   - Money field comma to dot replacement
   - INN field filtering (numeric only, length limits)
   - Checkbox handling for privacy consent
   - Phone display update in SBP section

4. Added checkbox styles and createCheckbox function:
   - Custom checkbox styling matching n8n
   - Required checkbox error states
   - Proper label and link styling

5. Improved initialization:
   - Better error handling
   - Field validation on load
   - Delegated INN filtering
   - Proper state initialization

Files:
- frontend/src/components/form/generateConfirmationFormHTML.ts: Complete form implementation
2025-11-24 15:47:16 +03:00
AI Assistant
7fa3561038 fix: Remove duplicate smsInputData declaration
- Removed second declaration of smsInputData that used undefined 'raw' variable
- First declaration already correctly uses data.sms_meta
2025-11-24 15:41:33 +03:00
AI Assistant
ad7ff3786a fix: Add money normalization for confirmation form
- Normalize agrprice if it comes as string with 'рублей' etc
- Ensures consistent number format for money fields
2025-11-24 15:39:14 +03:00
AI Assistant
c410eb77c9 fix: Simplify data normalization in confirmation form HTML generator
Problem:
- Function was trying to normalize already normalized data
- Used undefined 'raw' variable after refactoring
- Data structure mismatch causing form not to render

Solution:
1. Removed redundant normalization logic:
   - Data is already normalized in StepClaimConfirmation component
   - Use caseObj directly from data.case
   - Only ensure base structures exist (user, project, offenders, meta, attachments)

2. Fixed undefined variable:
   - Changed raw.token to data.token
   - Removed unused normalization code

3. Simplified data flow:
   - Input: data.case (already normalized)
   - Output: caseJson with same structure
   - JavaScript in HTML uses injected.case directly

Files:
- frontend/src/components/form/generateConfirmationFormHTML.ts: Simplified normalization
2025-11-24 15:38:24 +03:00
AI Assistant
827a1e46ad refactor: Use provided structure for confirmation form HTML generation
Problem:
- User wants to use the provided n8n Code node structure for generating confirmation form HTML
- Current implementation doesn't match the expected structure

Solution:
1. Created separate file generateConfirmationFormHTML.ts:
   - Implements data normalization from propertyName format
   - Uses provided HTML template structure
   - Includes field creation functions (createField, createDateField, etc.)
   - Implements form rendering with editable inline fields
   - Handles form data binding and submission via postMessage

2. Updated StepClaimConfirmation component:
   - Imports generateConfirmationFormHTML from separate file
   - Removed old inline HTML generation function
   - Uses new structure-based generation

3. Data normalization:
   - Transforms propertyName structure to form structure
   - Maps applicant fields: first_name -> firstname
   - Maps contract_or_service fields to project
   - Maps claim fields to project (description, reason)
   - Handles attachments and offenders arrays

4. Form features:
   - Inline editable fields in statement text
   - Date fields with calendar picker
   - Money fields with рублей suffix
   - Readonly fields for phone and category
   - Form data collection and submission

Files:
- frontend/src/components/form/generateConfirmationFormHTML.ts: New file with form generation logic
- frontend/src/components/form/StepClaimConfirmation.tsx: Updated to use new generator
2025-11-24 15:32:08 +03:00
AI Assistant
98802b0540 feat: Implement full confirmation form with editable fields
Problem:
- Only placeholder with Claim ID and Unified ID was shown
- No actual form for editing claim data
- User asked when the actual form will appear

Solution:
1. Created full HTML form with editable fields:
   - Applicant data (name, birthday, birthplace, INN, address, phone, email)
   - Case data (category, subject, date, amount, reason, description)
   - Offender data (organization name, address, INN, OGRN, contacts)
   - Attachments list (read-only display)

2. Fixed data mapping:
   - Transform propertyName structure to form structure
   - Map applicant fields: first_name -> firstname, etc.
   - Map contract_or_service fields to project
   - Map claim fields to project (description, reason)

3. Form features:
   - All fields are editable except phone (read-only)
   - Category is read-only (set by system)
   - Form collects edited values on confirmation
   - Sends form data back via postMessage

4. Removed n8n webhook call:
   - HTML form is generated locally in React component
   - No external dependencies for form generation

Files:
- frontend/src/components/form/StepClaimConfirmation.tsx: Full form implementation
2025-11-24 15:24:49 +03:00
AI Assistant
aed2a86ba8 fix: Fix claim_id and unified_id display in confirmation form
Problem:
- Claim ID and Unified ID showing as 'не указан' in confirmation form
- transformDraftToClaimPlanFormat was returning array instead of object
- StepClaimConfirmation was not correctly extracting IDs from claimPlanData

Solution:
1. Changed transformDraftToClaimPlanFormat return type:
   - Changed from array [{ propertyName, ... }] to object { propertyName, ... }
   - This matches what StepClaimConfirmation expects

2. Enhanced ID extraction in StepClaimConfirmation:
   - Added explicit claimId and unifiedId variables
   - Better fallback chain: claimPlanData.claim_id -> propertyName.meta.claim_id
   - Same for unified_id

3. Added comprehensive logging:
   - Log claimPlanData structure on component mount
   - Log extracted IDs before form generation
   - Log transformDraftToClaimPlanFormat input/output
   - Log claim.unified_id from API response

4. Improved data flow:
   - claim.unified_id from API -> transformDraftToClaimPlanFormat -> StepClaimConfirmation
   - Fallback to currentFormData.unified_id if claim.unified_id missing

Files:
- frontend/src/pages/ClaimForm.tsx: Changed return type, added logging
- frontend/src/components/form/StepClaimConfirmation.tsx: Enhanced ID extraction, added logging
2025-11-24 15:16:46 +03:00
AI Assistant
1789dafce2 fix: Improve problem_description detection for draft completeness check
Problem:
- problem_description not found in payload, but exists in draft list
- Completeness check fails because hasDescription = false
- Draft not recognized as ready for confirmation

Solution:
1. Enhanced problem_description extraction:
   - Checks multiple locations: body.problem_description, payload.problem_description
   - Also checks payload.body.problem_description for nested structures
   - Added fallback to body.description and payload.description

2. Improved completeness logic:
   - If problem_description not found but wizard_plan and answers exist,
     infer that description was entered (plan is generated from description)
   - This handles cases where description exists but not in expected payload location

3. Better logging:
   - Shows if problem_description was found directly or inferred
   - Logs all payload keys for debugging

Logic:
- hasDescription = !!problemDescription || (!!wizardPlan && !!answers)
- If plan and answers exist → description was entered earlier
- This allows drafts with plan+answers+documents to proceed to confirmation

Files:
- frontend/src/pages/ClaimForm.tsx: Enhanced problem_description detection
2025-11-24 15:12:29 +03:00
AI Assistant
577611c65d refactor: Load claim confirmation data from DB instead of SSE for drafts
Problem:
- When draft is fully filled, we subscribed to Redis SSE channel claim:plan
- But all data already exists in PostgreSQL database
- No need to wait for n8n to publish data - we can load it directly

Solution:
1. Removed subscribeToClaimPlanForDraft() function
   - No longer subscribes to SSE channel for drafts
   - Removed EventSource cleanup code

2. Added transformDraftToClaimPlanFormat() function
   - Transforms draft data from DB format to propertyName format
   - Extracts data from payload/body (telegram/web_form formats)
   - Maps documents_meta to attachments array
   - Formats applicant, case, contract_or_service, offenders, claim, meta
   - Returns data in array format expected by confirmation form

3. Updated loadDraft() logic:
   - When draft is ready for confirmation (all steps filled + draft status)
   - Calls transformDraftToClaimPlanFormat() instead of subscribing to SSE
   - Immediately shows confirmation form with data from DB

Flow:
1. User selects fully filled draft
2. System checks completeness (description, plan, answers, documents)
3. If ready → transforms DB data to propertyName format
4. Shows confirmation form immediately (no SSE wait)

Benefits:
-  Faster: no waiting for n8n to publish data
-  More reliable: data always available from DB
-  Simpler: no SSE connection management for drafts
-  Works offline: doesn't depend on Redis pub/sub

Files:
- frontend/src/pages/ClaimForm.tsx: Added transform function, removed SSE subscription
2025-11-24 15:08:00 +03:00