Commit Graph

157 Commits

Author SHA1 Message Date
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
f2e144e9ca Session: дублировать сессии во внешний Redis для доступа из n8n
- backend/app/api/session.py: при записи сессии в локальный Redis (6383) теперь также дублируем те же ключи
  в внешний Redis (REDIS_HOST/REDIS_PORT) через redis_service.client.
- Дублируются оба вида ключей:
  - session:{channel}:{channel_user_id}
  - session:{session_token}
- Ошибки внешнего Redis не ломают авторизацию: при недоступности — warning в логах.
2026-02-27 10:33:07 +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
1887336aba docs: describe auth2 hello flow 2026-02-20 09:57:11 +03:00
root
8c3e993eb7 feat: add soft ui auth page 2026-02-20 09:31:13 +03:00
AI Assistant
a4cc4f9de6 docs: актуальное описание проекта AiForm 2026-02-19 10:36:41 +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
Fedor
56516fdd7d Add docker-compose.dev.yml for dev environment (ports 5177, 8201) 2025-12-29 10:55:48 +03:00
AI Assistant
1a653f2154 docs: Move session log to root 2025-12-29 01:28:24 +03:00
AI Assistant
df8c93f46b Add session log 2025-12-29 2025-12-29 01:23:01 +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
1d6c9d1f52 feat: Add detailed logging for description endpoint and n8n workflow docs
Added:
- Detailed logging for /api/v1/claims/description endpoint
- Full event data logging for debugging
- Documentation for n8n workflow setup (N8N_DESCRIPTION_WORKFLOW.md)

The issue: Form hangs on recommendations step because n8n doesn't process description events.

Flow:
1. Frontend sends description to /api/v1/claims/description
2. Backend publishes to Redis channel ticket_form:description
3. Frontend subscribes to SSE /api/v1/events/{session_id} (listens to ocr_events:{session_id})
4. n8n must:
   - Subscribe to ticket_form:description channel
   - Process description and generate wizard_plan
   - Publish wizard_plan back to ocr_events:{session_id} channel

Files:
- backend/app/api/claims.py (enhanced logging)
- docs/N8N_DESCRIPTION_WORKFLOW.md (new documentation)
2025-11-25 17:42:31 +03:00
AI Assistant
521831be5e docs: Add n8n workflow documentation for form approval
Added documentation for n8n workflow setup:
- Redis channel subscription (clientright:webform:approve)
- Data structure description
- SQL script usage for marking forms as approved
- Verification steps

Files:
- docs/N8N_FORM_APPROVAL_WORKFLOW.md
2025-11-25 16:42:28 +03:00
AI Assistant
2fb0921e4c feat: Exclude approved forms from drafts list
Added filtering to exclude approved/confirmed forms from drafts list:
- Updated /drafts/list endpoint to filter out forms with status_code='approved' or is_confirmed=true
- Created SQL script for n8n to mark forms as approved after processing Redis channel data
- Forms marked as approved will no longer appear in drafts list

SQL script: SQL_MARK_FORM_APPROVED.sql
- Updates status_code to 'approved'
- Sets is_confirmed = true
- Uses claim_lookup CTE to find claim by id or payload->>'claim_id'

Files:
- backend/app/api/claims.py (updated drafts list queries)
- docs/SQL_MARK_FORM_APPROVED.sql (new SQL script for n8n)
2025-11-25 16:42:09 +03:00
AI Assistant
3d3f5995af fix: SMS code now properly included in Redis channel
SMS code is now successfully included in the Redis event data:
- Frontend sends SMS code in payload to backend
- Backend extracts SMS code from request body
- Backend includes SMS code in event_data before publishing to Redis
- Added comprehensive logging for debugging

The issue was that backend Docker image needed to be rebuilt after code changes.

Files:
- backend/app/api/claims.py (added detailed logging)
- frontend/src/components/form/StepClaimConfirmation.tsx (SMS code validation)
2025-11-25 15:55:06 +03:00
AI Assistant
6f31ad0dda debug: Add detailed logging for SMS code in backend
Added comprehensive logging to track SMS code:
- Log all keys in request body
- Log SMS code presence and value
- Log extracted SMS code before adding to event_data
- This will help identify why SMS code might not appear in Redis

Files:
- backend/app/api/claims.py
2025-11-25 15:38:07 +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
cd02c21c34 fix: Move /approve route before /{claim_id} to fix 405 error
Fixed route conflict:
- Moved POST /approve route BEFORE GET /{claim_id}
- FastAPI processes routes in order, so specific routes must come before parameterized ones
- This fixes 405 Method Not Allowed error

Files:
- backend/app/api/claims.py
2025-11-25 13:09:42 +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
f26e0ba48e fix: Add claim_lookup CTE to send_to_form_approve SQL query
Problem:
- Query only searched by ID: WHERE id = claim_id::uuid
- If record exists with different ID but same claim_id in payload,
  it wasn't found and send_to_form_approve wasn't saved

Solution:
- Added claim_lookup CTE that searches both by ID and payload->>'claim_id':
  WHERE c.id = claim_id::uuid OR c.payload->>'claim_id' = claim_id::text
- base now uses claim_lookup instead of direct query
- UPDATE uses claim_lookup.id instead of direct claim_id::uuid
- This ensures correct record is always used

Changes:
- Added claim_lookup CTE for record lookup
- base reads from claim_lookup instead of direct query
- UPDATE uses claim_lookup.id instead of claim_id::uuid

Files:
- docs/SQL_SEND_TO_FORM_APPROVE_FIXED.sql: Fixed version with claim_lookup
2025-11-24 17:07:52 +03:00
AI Assistant
d08e0da1ad fix: Add FROM partial to claim_lookup CTE to fix PostgreSQL error
Error:
- missing FROM-clause entry for table "partial"
- claim_lookup CTE used partial.claim_id_str but didn't have FROM partial

Root Cause:
- In CTE claim_lookup, we referenced partial.claim_id_str in WHERE clause
- But didn't include FROM partial, so PostgreSQL couldn't find the table

Solution:
- Added FROM partial to claim_lookup CTE:
  FROM clpr_claims c, partial
- Now partial is available in claim_lookup CTE
- Also prefixed columns with table aliases (c.id, c.payload) for clarity

Files:
- docs/SQL_CLAIMSAVE_FINAL_FIXED.sql: Added FROM partial to claim_lookup
2025-11-24 17:05:59 +03:00
AI Assistant
a8de3f0fc9 fix: Add claim_lookup CTE to search by both ID and payload claim_id
Problem:
- Original query only searched by ID: WHERE c.id = partial.cid
- If record exists with different ID but same claim_id in payload,
  it wasn't found and documents weren't updated

Solution:
- Added claim_lookup CTE that searches both by ID and payload->>'claim_id':
  WHERE id::text = claim_id_str OR payload->>'claim_id' = claim_id_str
- Uses found ID from claim_lookup instead of partial.cid
- This ensures correct record is always used

Changes:
- partial now accepts $2::text (instead of $2::uuid)
- Added claim_lookup CTE for record lookup
- upd_claim uses claim_lookup.id instead of partial.cid
- docs uses claim_lookup.id instead of partial.cid

Files:
- docs/SQL_CLAIMSAVE_FINAL_FIXED.sql: Fixed version with claim_lookup
2025-11-24 17:02:29 +03:00
AI Assistant
33de3955ac fix: Add created_at to existing_claim CTE to fix PostgreSQL error
Error:
- column "created_at" does not exist
- There is a column named "created_at" in table "clpr_claims", but it cannot be referenced from this part of the query

Root Cause:
- existing_claim CTE only selected id and payload
- But INSERT query tried to use: (SELECT created_at FROM existing_claim)
- PostgreSQL couldn't find created_at in existing_claim CTE

Solution:
- Added created_at to existing_claim CTE SELECT clause
- Now created_at is available for use in INSERT query

Files:
- docs/SQL_CLAIMSAVE_UPSERT_SIMPLE.sql: Added created_at to existing_claim CTE
2025-11-24 16:59:33 +03:00
AI Assistant
81963d18c3 fix: Prevent duplicate claims by searching both by ID and payload claim_id
Problem:
- Multiple records created with same claim_id but different IDs
- Example: ID=0eb051ec... (correct) vs ID=b532b1b3... (duplicate)
- Different SQL queries used different approaches:
  * Some used claim_id as UUID for ID (partial.claim_id_str::uuid)
  * Others searched by payload->>'claim_id' and created new UUID if not found

Root Cause:
- SQL_CLAIMSAVE_UPSERT_SIMPLE.sql only searched by ID:
  WHERE id = claim_id_str::uuid
- If record existed with different ID but same claim_id in payload,
  it wasn't found and new record was created

Solution:
1. existing_claim now searches both by ID and payload->>'claim_id':
   WHERE id = claim_id_str::uuid OR payload->>'claim_id' = claim_id_str
   ORDER BY priority (ID match first), then updated_at DESC
2. INSERT uses ID from existing_claim if found:
   COALESCE((SELECT id FROM existing_claim), partial.claim_id_str::uuid)
3. This ensures same record is always used, preventing duplicates

Files:
- docs/SQL_CLAIMSAVE_UPSERT_SIMPLE.sql: Fixed search logic and INSERT ID
2025-11-24 16:52:58 +03:00
AI Assistant
894463742f fix: Order by updated_at DESC to get latest claim record with send_to_form_approve
Problem:
- Multiple records exist with same claim_id in DB
- One record (ID: 0eb051ec...) has send_to_form_approve.draft (updated: 2025-11-24)
- Another record (ID: b532b1b3...) doesn't have send_to_form_approve (updated: 2025-11-21)
- API query used LIMIT 1 without ORDER BY, could return wrong record
- Form was empty because wrong record (without send_to_form_approve) was returned

Solution:
- Added ORDER BY updated_at DESC to get latest record first
- This ensures we always get the record with send_to_form_approve.draft
- Latest record has correct data structure for confirmation form

Files:
- backend/app/api/claims.py: Added ORDER BY updated_at DESC
2025-11-24 16:46:56 +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