# n8n Integration

n8n is the **automation layer** for Anwal Growth Platform. The CRM remains the system of record in MongoDB.

## Design principles

1. **Configurable URLs** — every webhook target is an environment variable (`N8N_WEBHOOK_*`).
2. **Fire-and-forget with logging** — failed n8n calls must not roll back CRM transactions; log and alert.
3. **Idempotent payloads** — include stable `eventId` for n8n deduplication.
4. **No CRM logic in n8n** — n8n orchestrates Slack, sheets, calendar, etc.; not primary data store.

## Outbound webhooks (app → n8n)

Triggered by domain services after successful DB writes.

| Event | Env variable | When fired |
|-------|--------------|------------|
| Email reply processed | `N8N_WEBHOOK_EMAIL_REPLY` | Inbound message linked/classified |
| Lead created | `N8N_WEBHOOK_LEAD_CREATED` | New lead persisted |
| Campaign created | `N8N_WEBHOOK_CAMPAIGN_CREATED` | Campaign saved (draft or scheduled) |
| Follow-up due | `N8N_WEBHOOK_FOLLOW_UP` | Scheduler detects due follow-up |

### Payload envelope (standard)

```json
{
  "eventId": "uuid",
  "eventType": "lead.created",
  "timestamp": "2026-06-02T12:00:00.000Z",
  "data": { }
}
```

`data` shape per event — documented in Task 019.

### HTTP client behavior

- Method: `POST`
- Headers: `Content-Type: application/json`, optional `X-Anwal-Signature` (HMAC secret TBD in Task 019)
- Timeout: 10s
- Retry: 2 retries with exponential backoff on 5xx/network errors

## Inbound webhooks (n8n → app)

| Endpoint | Purpose |
|----------|---------|
| `POST /api/webhooks/n8n` | Receive commands: create lead, add note, trigger sync |

Authentication: shared secret header `X-Webhook-Secret` (env `N8N_INBOUND_SECRET` — add in Task 019).

## Example n8n workflows (reference)

- Lead created → notify BD channel in Teams/Slack
- Campaign created → create checklist task for marketing lead
- Email reply `interested` → assign owner and schedule follow-up task
- Follow-up due → send internal reminder email

## Disabled integrations

If webhook URL env var is empty, skip call and log at debug level — allows local dev without n8n.

## Related

- [10-environment-variables.md](./10-environment-variables.md)
- [13-decisions-log.md](./13-decisions-log.md)
- task-019
