Files
aiform_prod/docs/N8N_RESPONSE_FORMAT.md

97 lines
3.1 KiB
Markdown
Raw Normal View History

# Формат ответа n8n после проверки телефона
## Текущий формат (неполный)
```json
{
"success": true,
"result": {
"claim_id": "CLM-2025-11-19-7O55SP",
"contact_id": "398644",
"event_type": null,
"current_step": 1,
"updated_at": "2025-11-19T15:15:07.323Z"
}
}
```
## Требуемый формат (с unified_id)
```json
{
"success": true,
"result": {
"claim_id": "CLM-2025-11-19-7O55SP",
"contact_id": "398644",
"unified_id": "usr_90599ff2-ac79-4236-b950-0df85395096c", // ← ДОБАВИТЬ!
"event_type": null,
"current_step": 1,
"updated_at": "2025-11-19T15:15:07.323Z",
"is_new_contact": false // опционально
}
}
```
## Где добавить unified_id в n8n workflow
### Шаг 1: После CreateWebContact
- Получен `contact_id` из CRM
- Есть `phone` из запроса
### Шаг 2: PostgreSQL Node - Find or Create User
- Выполнить SQL запрос из `SQL_FIND_OR_CREATE_USER_WEB_FORM.sql`
- Параметр: `$1 = {{$json.phone}}` (нормализованный телефон)
- Результат: `unified_id` и `user_id`
### Шаг 3: Response Node или Code Node
Вернуть ответ с unified_id:
```javascript
return {
success: true,
result: {
claim_id: $('CreateWebContact').item.json.claim_id || $('GenerateClaimId').item.json.claim_id,
contact_id: $('CreateWebContact').item.json.contact_id,
unified_id: $('PostgreSQL_FindOrCreateUser').item.json.unified_id, // ← ВАЖНО!
event_type: null,
current_step: 1,
updated_at: new Date().toISOString(),
is_new_contact: $('CreateWebContact').item.json.is_new_contact || false
}
};
```
## Важно!
1. **unified_id обязателен** - frontend использует его для поиска черновиков
2. **Формат unified_id**: `usr_{UUID}` (например, `usr_90599ff2-ac79-4236-b950-0df85395096c`)
3. **Если unified_id отсутствует** - frontend не сможет найти черновики пользователя
4. **При создании/обновлении черновика** - обязательно заполнять `clpr_claims.unified_id = unified_id`
## Проверка в frontend
Frontend уже готов принимать unified_id:
```typescript
// Step1Phone.tsx, строка 132
updateFormData({
phone,
smsCode: code,
contact_id: result.contact_id,
unified_id: result.unified_id, // ✅ Уже ожидается!
claim_id: result.claim_id,
is_new_contact: result.is_new_contact
});
```
## Пример полного workflow в n8n
1. **Webhook** → получает `{phone, session_id, form_id}`
2. **CreateWebContact** → создает/находит контакт в CRM → возвращает `contact_id`
3. **GenerateClaimId** → генерирует `claim_id` (если нужно)
4. **PostgreSQL: Find or Create User** → выполняет SQL запрос → возвращает `unified_id`
5. **Response** → возвращает полный ответ с `unified_id`
feat: Add claim plan confirmation flow via Redis SSE Problem: - After wizard form submission, need to wait for claim data from n8n - Claim data comes via Redis channel claim:plan:{session_token} - Need to display confirmation form with claim data Solution: 1. Backend: Added SSE endpoint /api/v1/claim-plan/{session_token} - Subscribes to Redis channel claim:plan:{session_token} - Streams claim data from n8n to frontend - Handles timeouts and errors gracefully 2. Frontend: Added subscription to claim:plan channel - StepWizardPlan: After form submission, subscribes to SSE - Waits for claim_plan_ready event - Shows loading message while waiting - On success: saves claimPlanData and shows confirmation step 3. New component: StepClaimConfirmation - Displays claim confirmation form in iframe - Receives claimPlanData from parent - Generates HTML form (placeholder - should call n8n for real HTML) - Handles confirmation/cancellation via postMessage 4. ClaimForm: Added conditional step for confirmation - Shows StepClaimConfirmation when showClaimConfirmation=true - Step appears after StepWizardPlan - Only visible when claimPlanData is available Flow: 1. User fills wizard form → submits 2. Form data sent to n8n via /api/v1/claims/wizard 3. Frontend subscribes to SSE /api/v1/claim-plan/{session_token} 4. n8n processes data → publishes to Redis claim:plan:{session_token} 5. Backend receives → streams to frontend via SSE 6. Frontend receives → shows StepClaimConfirmation 7. User confirms → proceeds to next step Files: - backend/app/api/events.py: Added stream_claim_plan endpoint - frontend/src/components/form/StepWizardPlan.tsx: Added subscribeToClaimPlan - frontend/src/components/form/StepClaimConfirmation.tsx: New component - frontend/src/pages/ClaimForm.tsx: Added confirmation step to steps array
2025-11-24 13:36:14 +03:00