Files
aiform_dev/docs/N8N_RESPONSE_FORMAT.md
AI Assistant d6b17baa7d feat: Add PostgreSQL fields and workflow for form without files
Database changes:
- Add unified_id, contact_id, phone columns to clpr_claims table
- Create indexes for fast lookup by these fields
- Migrate existing data from payload to new columns
- SQL migration: docs/SQL_ALTER_CLPR_CLAIMS_ADD_FIELDS.sql

SQL improvements:
- Simplify claimsave query: remove complex claim_lookup logic
- Use UPSERT (INSERT ON CONFLICT) with known claim_id
- Always return claim (fix NULL issue)
- Store unified_id, contact_id, phone directly in table columns
- SQL: docs/SQL_CLAIMSAVE_UPSERT_SIMPLE.sql

Workflow enhancements:
- Add branch for form submissions WITHOUT files
- Create 6 new nodes: extract, prepare, save, redis, respond
- Separate flow for has_files=false in IF node
- Instructions: docs/N8N_FORM_GET_NO_FILES_INSTRUCTIONS.md
- Node config: docs/N8N_FORM_GET_NO_FILES_BRANCH.json

Migration stats:
- Total claims: 81
- With unified_id: 77
- Migrated from payload: 2

Next steps:
1. Add 6 nodes to n8n workflow form_get (ID: 8ZVMTsuH7Cmw7snw)
2. Connect TRUE branch of IF node to extract_webhook_data_no_files
3. Test form submission without files
4. Verify PostgreSQL save and Redis event
2025-11-21 15:57:18 +03:00

96 lines
3.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Формат ответа 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`