# Architecture

## Stack

Laravel 13 (PHP 8.5) · Filament 5 (Livewire) · MySQL 8.4 · Redis (cache + queue) · Pest 4 ·
spatie/laravel-permission · spatie/laravel-backup · mPDF (Arabic PDF) · OpenSpout (Excel/CSV) ·
Tesseract + Poppler (OCR) · Anthropic / OpenAI SDKs (optional AI extraction).

## Layout

```
app/
  Domain/<Module>/   business logic: Models, Enums, Actions, Services, Policies, Jobs, Listeners
  Filament/          UI only: resources, pages and widgets call domain actions, no business rules
  Http/              download controllers (signed + policy), middleware (security headers, active account)
  Console/Commands/  expiry check, reminders, report pruning, permissions sync/matrix
  Support/           shared helpers (translated enum labels, validation rules, phone formats)
```

| Module | Responsibility |
|---|---|
| Authorization | `PermissionRegistry` (source of truth), `DefaultRoleMatrix`, privilege-escalation guard |
| Users | Users, departments, login history, suspension |
| Contracts | Contract record, status state machine, numbering, **ContractAccess** (row-level visibility), history and timeline |
| Organizations | Parties and contacts |
| Documents | Private storage, versions, checklist, duplicate hash, scanner hook |
| AI | Text and OCR stage, provider abstraction (Anthropic / OpenAI / heuristic), review and apply |
| Finance | Financials (exact-decimal `Money`), optional VAT, payment schedules and statuses |
| Notifications | Rule engine, idempotent dispatch, channel drivers (in-app / e-mail / WhatsApp / Telegram), inbox |
| Approvals | Configurable workflows, `ApprovalGuard` (locks a contract while it is pending approval) |
| Renewals, Tasks, Notes | Renewal decisions, tasks with reminders, notes with visibility and @mentions |
| Reports, Imports | Report builder (PDF/Excel/CSV, e-mail, saved templates), Excel/CSV contract import |
| Dashboard | KPIs, priority list, calendar events, analytics |
| Audit | Append-only audit log with secret masking |
| Backups, Health | Encrypted backups and their logs; system health checks and heartbeats |
| Settings | Encrypted runtime settings, `SettingsOverrides` (applied to config), master data, feature flags |

## Key rules (enforced in code)

- **Visibility:** `Contract::visibleTo($user)` is the single source of row access, used by lists,
  reports, exports, the dashboard, the calendar, the audit log and downloads.
- **Super Admin** passes every check through `Gate::before`. Critical rules (permanent deletion, backups,
  AI keys) are checked explicitly so they hold even if a permission is granted to another role.
- **Zero data loss:** contracts are soft-deleted, organizations are never permanently deleted,
  migrations are reversible and additive, and permission sync never revokes grants.
- **Idempotent automation:** expiry runs and reminder dispatches use unique dispatch keys, so re-running
  a day never sends duplicates. Missed days are caught up.
- **Strict models outside production:** lazy loading, missing attributes and silently discarded
  attributes throw errors.
- **Time and money:** Asia/Dubai timezone, AED currency; amounts are decimal strings, never floats.

## Request and background flow

```
Browser ─► Nginx ─► PHP-FPM (Laravel + Filament/Livewire) ─► MySQL / Redis
                         │ dispatch
                         ▼
          Redis queue ─► worker (Supervisor): extraction, notifications, reports, backups
cron ─► schedule:run ─► expiry check · reminders · backups · pruning · heartbeats
```

## Further reading

- [SECURITY.md](SECURITY.md)
- [ROLES_AND_PERMISSIONS.md](ROLES_AND_PERMISSIONS.md)
- [DEPLOYMENT.md](DEPLOYMENT.md)
- [OPERATIONS.md](OPERATIONS.md)
- [BACKUP_RESTORE.md](BACKUP_RESTORE.md)
