# Notification Engine

## Overview
A custom **pipeline-based notification system** built alongside Laravel's native notification system. It provides centralized control over notification delivery with configurable stages for filtering, routing, rendering, and dispatch.

## Architecture

### Core Components

```
NotificationEvent (event string + payload)
    │
    ▼
NotificationDispatcher (implements NotificationEngine interface)
    │
    ▼
NotificationPipeline (ordered stages)
    │
    ├── 1. GlobalSettingsStage      ─ Master on/off switch
    ├── 2. SettingResolutionStage   ─ Resolve event settings
    ├── 3. ProgramOverrideStage     ─ Per-program overrides
    ├── 4. RecipientResolutionStage ─ Resolve recipients
    ├── 5. UserPreferenceStage      ─ User channel preferences
    ├── 6. ChannelResolutionStage   ─ Determine channels
    ├── 7. QuietHoursStage          ─ Quiet hours enforcement
    ├── 8. ThrottleStage            ─ Rate limiting
    ├── 9. DedupStage               ─ Deduplication
    ├── 10. TemplateRenderStage     ─ Render notification content
    ├── 11. QueueDecisionStage      ─ Queue vs synchronous decision
    ├── 12. DispatchStage           ─ Send via channels
    ├── 13. HistoryStage            ─ Record history
    ├── 14. RetryStage              ─ Retry on failure
    └── 15. AuditStage              ─ Audit logging
```

### Key Files
- `NotificationDispatcher` — Entry point, dispatches events through pipeline
- `NotificationEvent` — Event data object (event name, payload, context)
- `NotificationPipeline` — Manages stage ordering and execution

## Pipeline Stages

| Stage | Purpose |
|-------|---------|
| **GlobalSettingsStage** | Checks `NOTIFICATION_ENGINE_ENABLED` config — master switch |
| **SettingResolutionStage** | Resolves notification settings for the event |
| **ProgramOverrideStage** | Applies per-program notification overrides from `ProgramNotificationOverride` model |
| **RecipientResolutionStage** | Resolves recipients using `RecipientResolverRegistry` |
| **UserPreferenceStage** | Checks user's saved notification preferences |
| **ChannelResolutionStage** | Determines which channels to use (database, mail, whatsapp) |
| **QuietHoursStage** | Defers notifications during quiet hours |
| **ThrottleStage** | Rate limits dispatches per minute |
| **DedupStage** | Prevents duplicate notifications |
| **TemplateRenderStage** | Renders notification content via `TemplateRenderer` |
| **QueueDecisionStage** | Decides to queue or send synchronously (threshold: 10 recipients) |
| **DispatchStage** | Actually sends the notification via resolved channels |
| **HistoryStage** | Records notification in `NotificationHistory` model |
| **RetryStage** | Handles retry logic for failed dispatches |
| **AuditStage** | Logs audit trail via `AuditLogger` |

## Notification Events
Events are referenced by string keys (e.g., `user.account.created`, `assessment.created`). Each event maps to a notification class via `NotificationClassResolver`.

### Event Categories
- **User:** `user.account.created`, `user.account.deleted`, `user.email.verified`, `user.phone.verified`, `user.account.approved`, `user.account.suspended`, `user.password.changed`, `user.profile.updated`, `user.teacher.assigned`, `user.program.assigned`, `user.login.detected`
- **Program:** `program.created`, `program.deleted`, `program.approved`, `program.suspended`, `program.enabled`, `program.disabled`
- **Course:** `course.created`, `course.updated`, `course.deleted`
- **Lesson:** `lesson.created`, `lesson.updated`, `lesson.deleted`
- **Assessment:** `assessment.created`, `assessment.updated`
- **Marathon:** `marathon.created`
- **Team:** `team.created`, `team.updated`, `team.deleted`
- **Announcement:** `announcement.created`, `announcement.updated`, `announcement.deleted`
- **Video:** `video.uploaded`, `file.uploaded`
- **Participation:** `participation.*`, `enrollment.*`, `payment.*`, `seat.*` (defined in participation config)

## Models

| Model | Purpose |
|-------|---------|
| `NotificationHistory` | Records all dispatched notifications |
| `NotificationPreference` | User notification preferences |
| `FailedNotification` | Failed notification records for retry |
| `ProgramNotificationOverride` | Per-program notification overrides |

## Resolvers

### Channel Resolver
Determines notification channels based on event, user preferences, and program settings.

### Recipient Resolver Registry
A centralized registry of recipient resolvers organized by key:

**Static Resolvers** (resolve by role):
- `super-admin`, `super-manager`, `super-admins`
- `portal-admin`, `portal-manager`, `portal-admins`
- `portal-teacher`, `portal-teacher-assistant`, `portal-teachers`
- `portal-student`
- `role` (generic role resolver)
- `custom` (custom user IDs)

**Dynamic Resolvers** (resolve from event context):
- `creator`, `teacher`, `student`, `subscriber`, `acting-user`
- `assessment-owner`, `marathon-owner`, `course-owner`, `lesson-owner`
- `program-admins`, `program-teachers`, `program-students`
- `team-teacher`, `team-members`
- `participants`, `participant`
- `join-request-owner`, `approver`
- `student-teacher`
- `marathon-authorities`, `competition-authorities`
- `enroller`

### Global Settings Resolver
Reads global notification settings from config.

### Program Override Resolver
Checks program-level notification overrides.

### User Preference Resolver
Reads each user's notification channel preferences.

## Renderers
- `TemplateRenderer` — Renders notification templates with translation support

## Services
- `AuditLogger` — Logs all notification dispatching
- `RetryManager` — Manages retry attempts for failed notifications
- `NotificationClassResolver` — Maps event keys to notification classes

## Jobs
- `DispatchNotificationJob` — Queued notification dispatch

## Console Commands
- `RetryFailedNotificationsCommand` — Retries failed notifications from queue

## Configuration (`config/notification-engine.php`)
- `enabled` — Master switch (env: `NOTIFICATION_ENGINE_ENABLED`)
- `default_channels` — Default channels: `['database']`
- `queue_enabled` / `queue_connection` — Queue configuration
- `queue_threshold` — Recipient count threshold for queuing (default: 10)
- `rate_limit_per_minute` — Global rate limit (default: 100)
- `max_retries` — Max retry attempts (default: 3)
- `audit_enabled` — Audit logging toggle
- `log_level` — Minimum log level
- `pipeline` — Ordered array of stage classes

## Notification Classes (Laravel Notifications)
The system also uses standard Laravel notification classes in `app/Notifications/`:
- `BaseNotification` — Abstract base class with common logic
- `SystemNotification` — System-level mail notification example
- `Admin/CustomNotification` — Ad-hoc admin notifications
- Channel-specific: `Channels/WhatsAppChannel`
- 40+ notification classes organized by module (User, Course, Assessment, etc.)
