# Alert Lifecycle – Backend
# Functional Requirements

1. Receive alert payload from the agent.
2. Send an email to the user's registered email address.
3. Store every alert in the database.

# Non-Functional Requirements

1. No credentials hardcoded — all from environment variables.
2. Email delivery and DB write should work reliably under normal load.
3. Simple, maintainable code with clear error handling.
# Overall Acceptance Criteria

This module is a simple backend service. It receives alert events, sends email notifications to users, and stores alerts in the database. No frontend, UI, or extra complexity is included. Acceptance is based on:

- Alerts are received and stored in the database.
- Emails are sent to the intended recipients.
- No UI or user-facing actions are required.

If these criteria are met, the module is considered complete and ready for QA approval.

> **Jira:** [DEB-353](https://divami.atlassian.net/browse/DEB-353)
> **Updated:** 2026-03-17

---

## 1. Overview

A backend module that receives alert events from the Decision Intelligence Agent and sends email notifications to the relevant user.

Current scope:
- Send email via SMTP
- Store alert in database

WhatsApp and Browser Push are deferred to Phase 2.

---

---

## 4. Alert States

| State       | Description                          |
| ----------- | ------------------------------------ |
| `created`   | Saved in DB, not yet sent            |
| `sent`      | Email dispatched to provider         |
| `delivered` | Provider confirmed delivery          |
| `failed`    | All retries exhausted                |

---

## 5. Database Schema

### `alerts`

| Column       | Type                                                      | Notes                    |
| ------------ | --------------------------------------------------------- | ------------------------ |
| `alert_id`   | `UUID` PK                                                 |                          |
| `user_id`    | `UUID` FK                                                 | Recipient                |
| `title`      | `VARCHAR(255)`                                            |                          |
| `message`    | `TEXT`                                                    |                          |
| `severity`   | `ENUM(low, medium, high, critical)`                       |                          |
| `source`     | `VARCHAR(100)`                                            | Which agent sent this    |
| `status`     | `ENUM(created, sent, delivered, read, resolved, failed)`  |                          |
| `error`      | `TEXT`                                                    | Populated if failed      |
| `metadata`   | `JSONB`                                                   | Any extra context        |
| `created_at` | `TIMESTAMP WITH TIME ZONE`                                |                          |
| `updated_at` | `TIMESTAMP WITH TIME ZONE`                                |                          |

---

## 6. APIs

// No APIs or UI routes in scope. Backend only.

## 7. Email Payload (SMTP)

```python
send_email(
    to="user@company.com",
    subject="[HIGH] Revenue Drop Detected",
    html_body="<p>Revenue dropped by 20%.</p><a href='...'>View Dashboard</a>",
    text_body="Revenue dropped by 20%. View: https://..."
)
```

Provider is set via `EMAIL_PROVIDER` env variable (`smtp` | `sendgrid` | `ses`).

---

## 8. Subtask Plan

### DEB-355 — Send Email Function

- File: `backend/app/alerts/email.py`
- Function: `send_email(to, subject, html_body, text_body)`
- Reads `EMAIL_PROVIDER` from env, picks the right client
- Raises `EmailDeliveryError` on failure

**Env vars:**
```
EMAIL_PROVIDER=smtp
SMTP_HOST=...
SMTP_PORT=587
SMTP_USER=...
SMTP_PASS=...
```

---

### DEB-356 — WhatsApp — Phase 2

Deferred. Will be implemented after email is stable.

---

### DEB-357 — Store in Database

- Insert `alerts` row with `status=created` before sending
- Update `alerts.status` after each attempt (`sent`, `delivered`, `failed`)
- Store error message in `alerts.error` if delivery fails
- SQLAlchemy model + Alembic migration for the `alerts` table
- All writes are async

---



## 9. Testing & Acceptance Criteria

QA team should use these as acceptance criteria. All tests are simple and directly map to backend functionality:

### Acceptance Criteria

0. This module is a simple backend functionality: it receives alerts, sends emails, and stores them in the database. No frontend, UI, or extra complexity is included.
1. When an alert is sent, an email is delivered to the user's registered email address.
2. Every alert is saved in the database before sending the email.
3. No frontend or UI actions are required.

### Minimal Test Cases (for QA)

1. Send alert → Email is received by user.
2. Send alert → Alert row exists in database.
3. If email delivery fails, alert status is updated to 'failed' and error is stored.
4. No retry logic, delivery logs, or provider switching are required for acceptance.
