# Notifications & Automation Rules

**Task 015 — internal only (no n8n, no external webhooks)**

## Overview

The platform creates **in-app notifications** when important CRM events occur. Rules live in `automation-rules.service.ts` and run **non-blocking** via `triggerAutomation()` so API latency is unaffected.

## Notification model

Collection: `notifications` — `src/server/models/notification.model.ts`

| Field | Notes |
|-------|-------|
| userId | Optional — targeted user; `null`/missing = broadcast to all users |
| type | See `NOTIFICATION_TYPES` in `src/lib/enums.ts` |
| title, message | Arabic/English copy |
| entityType, entityId | Link to email, lead, opportunity, etc. |
| priority | `low`, `medium`, `high`, `critical` |
| status | `unread`, `read` |
| actionUrl | In-app route (e.g. `/inbox/[id]`) |
| metadata | Extra JSON |
| readAt | Set when marked read |

## Automation rules

| Handler | Trigger |
|---------|---------|
| `onEmailReplyCreated` | New inbox reply imported |
| `onAiClassified` | Email reply classified (+ hot lead-worthy alert) |
| `onLeadCreated` | Lead created |
| `onHotLeadCreated` | Lead with `temperature: hot` |
| `onLeadAssigned` | Lead assigned to user |
| `onOpportunityStageChanged` | Pipeline stage move |
| `onTaskCreated` | Task created |
| `onTaskDueToday` / `onTaskOverdue` | Scanned on dashboard load (`processTaskDueNotifications`) |
| `onCampaignCompleted` | Campaign batch fully sent (no failures) |
| `onEmailFailed` | Campaign recipient send failed |
| `onHighPriorityDataIssue` | Data quality issue severity `high` on import |

## Services

- `src/server/services/notification.service.ts` — CRUD, unread count, list
- `src/server/services/automation-rules.service.ts` — event handlers

## API

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/notifications` | List (`status`, `priority`, `page`, `limit`) |
| GET | `/api/notifications/unread-count` | Unread badge count |
| PATCH | `/api/notifications/[id]/read` | Mark one read |
| POST | `/api/notifications/read-all` | Mark all read |
| DELETE | `/api/notifications/[id]` | Delete |

All require authentication. Visibility: notifications for current user **or** broadcast (`userId` unset).

## UI

| Location | Component |
|----------|-----------|
| Topbar | `NotificationBell` + dropdown |
| `/notifications` | Full list with filters |
| `/dashboard` | Recent notifications widget |

## Deferred

- Email/SMS push outside the app
- Per-user notification preferences
- n8n / external automation (explicitly out of scope)

## Related

- [01-architecture.md](./01-architecture.md)
- [03-api-specification.md](./03-api-specification.md)
