# Task P.7.1 - Notification Foundation

## Objective
Build a generic Notification Foundation for ALLA OS that supports event-driven notifications across multiple delivery channels.

The first implementation target is `Email`, but the architecture must support future channels such as:
- Email
- Microsoft Teams
- LINE OA
- Slack
- Mobile Push
- SMS
- Web Notification

The Notification Foundation must not be coupled to CRM quotation only.

## Background
Completed phases:
- P.4 PDF Runtime
- P.5 Template Management
- P.5.1 Production Hardening
- P.6 Document Library
- P.6.1 Document Sequence Refactor
- P.7 Document Assembly Framework

Current capability:

```text
Quotation -> Approved PDF -> Document Assembly -> Final Customer PDF
```

Next capability:

```text
Business Event -> Notification Event -> Notification Engine -> Email / Teams / LINE / Slack
```

## Discovery Requirement
Before implementation, inspect the existing project and review at minimum:
- AGENTS.md
- authentication layer / RBAC
- audit logging
- storage abstraction
- document assembly
- document library
- CRM approval flow
- existing email utilities, if any
- existing queue / background job infrastructure
- existing scheduler / automation support

Do not assume notification infrastructure already exists. Produce a discovery summary before implementation.

## Design Principles
The notification engine must be:
- event-driven
- channel-agnostic
- template-driven
- retryable
- auditable
- extensible

Do not hardcode quotation logic inside the notification engine.

## Core Architecture
Design around:

```text
Business Event
  -> Notification Event
  -> Notification Dispatcher
     -> Email
     -> Teams
     -> LINE OA
     -> Slack
     -> Future Providers
```

Business modules only publish events. They must not directly call SMTP or a provider SDK.

## Notification Events
Support generic events. Initial CRM events:
- `quotation.created`
- `quotation.submitted`
- `quotation.approved`
- `quotation.rejected`
- `quotation.sent`
- `quotation.cancelled`
- `lead.assigned`
- `opportunity.assigned`

Future events:
- `po.received`
- `service.completed`
- `maintenance.due`
- `inventory.low`
- `asset.expired`

Events should carry payload only.

## Notification Template
Support reusable notification templates with fields:
- `code`
- `name`
- `channel`
- `subject`
- `body`
- `language`
- `variables`
- `active`
- `version`

Support placeholder replacement.

Example:

```text
Dear {{customerName}}
Your quotation {{quotationCode}} has been approved.

Attached:
- Quotation
- SLA

Thank you.
```

## Notification Channels
Create a provider abstraction:

```ts
NotificationProvider
```

Methods:
- `send()`
- `validate()`
- `healthCheck()`

Implement `EmailProvider` only in this phase. Other providers remain placeholders.

## Email Foundation
Support:
- SMTP
- provider abstraction
- HTML body
- plain text fallback
- multiple recipients
- CC
- BCC
- Reply-To
- attachments

No provider lock-in.

## Attachment Support
Notification must support attachments such as:
- approved PDF
- final assembled PDF
- SLA
- warranty

Attachments must come from the storage abstraction. Do not regenerate PDFs during sending.

## Notification Queue
Create a notification queue abstraction. Even if processed synchronously now, the architecture must allow future background processing.

States:
- `pending`
- `sending`
- `sent`
- `failed`
- `retry`

## Notification Log
Create notification history that tracks:
- event
- recipient
- channel
- template
- subject
- attachment list
- status
- error
- retry count
- createdAt
- sentAt

This becomes permanent delivery audit history.

## Document Package Integration
Integrate P.7 output.

```text
Quotation -> Approved PDF -> Assembly -> Document Package -> Notification
```

Notification must never rebuild PDFs. It must use stored artifacts only.

## API Requirements
Create APIs for:
- send notification
- resend notification
- preview notification
- list notifications
- notification history
- notification detail

Notification sending should support:
- recipient override
- template override
- attachment selection
- dry-run preview

## CRM Integration
Do not automatically send emails yet. Instead provide service methods that CRM modules can call.

Example:

```text
Quotation Approved -> Notification Service -> Email Provider
```

Future phases decide when automatic sending occurs.

## RBAC
Add permissions:
- `notificationRead`
- `notificationSend`
- `notificationResend`
- `notificationManageTemplate`
- `notificationViewHistory`

## Audit Logging
Record:
- notification requested
- provider selected
- send started
- send succeeded
- send failed
- resend
- template changed

## Validation
Validate:
- recipient exists
- valid email
- template exists
- attachment exists
- storage object exists
- provider available

Return business-readable errors only.

## Testing Requirements
Add tests for:
- template rendering
- placeholder replacement
- attachment resolution
- provider abstraction
- notification queue
- failed send
- retry
- audit logging

Run:

```bash
npm run typecheck
npm run build
npm run audit:pdf
```

## Acceptance Criteria
- Generic Notification Engine exists.
- Business modules publish notification events instead of calling providers directly.
- Email provider abstraction is implemented.
- Notification templates support placeholders.
- Attachments resolve from stored artifacts.
- Notification history is persisted.
- Retry architecture exists.
- Queue abstraction exists.
- Notification service is reusable across ALLA OS.
- No CRM module is tightly coupled to SMTP or a provider SDK.

## Out of Scope

### P.7.2
- SMTP provider configuration UI
- provider secrets management
- SendGrid / Microsoft Graph / Resend implementation
- email branding
- DKIM / SPF guidance

### P.7.3
- automatic approval notifications
- automatic quotation emails
- customer email workflow
- manager notifications

### P.8
- user notification preferences
- subscription management
- channel selection UI
- notification scheduling

## Final Success Condition
Task P.7.1 is complete when ALLA OS has a reusable, event-driven Notification Foundation capable of rendering templates, resolving stored document artifacts, dispatching notifications through a provider abstraction (initially Email), persisting delivery history, and serving as the foundation for future notification channels without coupling business modules to specific delivery mechanisms.

---

## Implementation Status - 2026-06-30

Current round completed:
- reviewed existing notification, approval automation, storage, document artifact, and document assembly foundations before implementation
- extended notification schema/contracts for generic dispatch history, richer templates, provider abstraction, and retry state
- added SMTP-based `EmailNotificationProvider`
- added reusable preview/send/resend/history/detail APIs under `/api/notifications/**`
- added attachment resolution from stored artifacts and document-library files only
- added tests for template rendering and retry queue execution
- verified `npm run typecheck`, targeted notification tests, `npm run build`, and `npm run audit:pdf`

Implementation notes:
- [docs/implementation/task-p.7.1-implementation.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/implementation/task-p.7.1-implementation.md)
- [docs/implementation/task-p.7.1-verification-report.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/implementation/task-p.7.1-verification-report.md)

Open follow-ups:
- add dedicated seeded email templates for all initial CRM events instead of relying on fallback behavior
- add template management UI and provider configuration UX
- move dispatch processing to a background worker when scheduler / worker runtime is introduced
