# PEOPLEFLOW — System Architecture

## 1. Architectural Style: Modular Monolith

PEOPLEFLOW is engineered as a **layered Modular Monolith** built on Next.js 15+ (App Router), TypeScript, Prisma, and PostgreSQL.

**Why a Modular Monolith instead of Microservices?**
- All lifecycle processes (Onboarding, Offboarding, Movements, Tasks, Assets, Approvals, Audit Logs) require **strong ACID transactions** (e.g., completing an offboarding clearance atomically updates request status, employee assignment status, and writes an immutable audit event).
- Operational simplicity for internal SMC Cement Group IT hosting (single deployable web/API runtime + background worker + PostgreSQL).
- Clean internal module boundaries (`services/`, `integrations/`, `lib/auth/`) allow extracting high-throughput workers later without rewriting business logic.

```mermaid
flowchart TB
    subgraph Client["Browser Client (Desktop / Tablet / Mobile)"]
        UI["Next.js App Router UI\n(Tailwind + shadcn/ui + Framer Motion)"]
    end

    subgraph AppServer["PEOPLEFLOW Application Server (Next.js 15+ Node.js Runtime)"]
        AuthLayer["Auth & Session Layer\n(Entra ID SSO / Dev Auth)"]
        RBACGuard["Authorization & Company-Scope Policy Guard\n(assertPermission + assertCompanyAccess)"]
        API["Route Handlers (/api/v1/*) & Server Actions\n(Zod Input Validation + Rate Limiting)"]

        subgraph Services["Domain Service Layer (Pure Business Logic)"]
            EmpSvc["Employee & Org Service"]
            OnbSvc["Onboarding Service"]
            OffSvc["Offboarding Service"]
            MovSvc["Movement Service"]
            WfEngine["Workflow Engine Service"]
            TaskSvc["Task & Approval Service"]
            AssetDocSvc["Asset & Document Service"]
            ReportSvc["Reporting & Export Service"]
            AuditSvc["Immutable Audit & Logger Service"]
        end

        subgraph Adapters["Integration Adapter Layer"]
            GraphAdp["Microsoft Graph Adapter\n(Mock / Live)"]
            FreshAdp["Freshservice Adapter\n(Mock / Live)"]
            RamcoAdp["Ramco ERP Adapter\n(Manual / Mock / Future API)"]
            NotifyAdp["Notification Adapter\n(In-App + Email/Graph)"]
        end
    end

    subgraph Async["Background Job Processor"]
        Worker["Scheduled & Async Worker\n(Scheduled Deactivations, Reminders,\nEscalations, Integration Retries)"]
    end

    subgraph Data["Data & Storage Layer"]
        PG[("PostgreSQL\n(Prisma ORM)")]
        DocStore[("Private Document Storage\n(Encrypted Local / Azure Blob / S3)")]
    end

    subgraph External["External Enterprise Systems"]
        Entra["Microsoft Entra ID / M365"]
        Fresh["Freshservice ITSM"]
        Ramco["Ramco ERP"]
    end

    UI -->|HTTPS + Session Cookie| AuthLayer
    AuthLayer --> API
    API --> RBACGuard
    RBACGuard --> Services
    Services --> PG
    AssetDocSvc --> DocStore
    Services --> Adapters
    Services -->|Enqueue Job| PG
    Worker -->|Poll / Lock Jobs| PG
    Worker --> Services
    Worker --> Adapters
    GraphAdp -.-> Entra
    FreshAdp -.-> Fresh
    RamcoAdp -.-> Ramco
    NotifyAdp -.-> Entra
```

---

## 2. Multi-Company Data Isolation Strategy (ECC | NCC | SCII)

PEOPLEFLOW uses a **Shared Database, Row-Level Company Scoping** model enforced centrally in the authorization and service layers.

1. **Company Scope Binding**:
   - Every user has explicit `UserCompanyAccess` grants (`ECC`, `NCC`, `SCII`) OR a `hasGroupWideAccess` flag (restricted to System Administrators and authorized Group Executives).
   - The Top Bar **Company Selector** lets multi-company users filter the UI to `ECC`, `NCC`, `SCII`, or `All Authorized Companies`.
2. **Server-Side Enforcement (Zero Trust of Client Filter)**:
   - Every service method receives a verified `AuthContext` (`userId`, `roles`, `permissions`, `allowedCompanyIds`, `activeCompanyFilter`).
   - All Prisma queries automatically inject `where: { companyId: { in: ctx.effectiveCompanyIds } }` via a centralized `buildCompanyScopeFilter(ctx, requestedCompanyId)` helper.
   - Attempting to read, mutate, or pass a `companyId` outside `ctx.allowedCompanyIds` immediately throws `ForbiddenError` (`403`) and logs a `SECURITY_CROSS_COMPANY_DENIED` audit event.
3. **Cross-Company Transfers (Special Case)**:
   - A `MovementRequest` of type `COMPANY_TRANSFER` stores both `sourceCompanyId` and `targetCompanyId`.
   - Authorization permits authorized HR/Managers in **source** company to see source context and **target** company to see target context, while restricting confidential historical records from unrelated companies.

---

## 3. API & Server Action Architecture

### Conventions
- **Reads in Server Components**: Call `services/*` directly with `getServerAuthContext()` to avoid unnecessary HTTP hops while preserving identical RBAC checks.
- **Mutations & External/Export Endpoints**: Exposed via RESTful Route Handlers under `/api/v1/...` (cleanly testable with Vitest/Playwright, consistent HTTP status codes, supports file streaming/exports and webhook callbacks).
- **Validation**: Every request body and query parameter is validated with Zod before reaching services.
- **Idempotency**: Lifecycle request submissions (`POST /api/v1/onboarding`, `POST /api/v1/offboarding`, `POST /api/v1/movements`) support an `Idempotency-Key` header and active-request uniqueness guards to prevent accidental duplicate submissions.
- **Standard Response Envelope**:
  - Success: `{ data: T, meta?: { page, pageSize, total } }`
  - Error: `{ error: { code: string, message: string, details?: Record<string, string[]> }, requestId: string }` (never leaks stack traces, SQL errors, or secrets).

### Core API Resource Map
- `/api/v1/auth/*` — Session, Entra ID SSO callback, dev login (non-prod only), logout
- `/api/v1/dashboard` — Live KPI aggregations, trends, SLA metrics (company-scoped)
- `/api/v1/companies`, `/api/v1/departments`, `/api/v1/positions` — Org master data
- `/api/v1/users`, `/api/v1/roles` — User, role, permission, and company-access administration
- `/api/v1/employees` — Directory CRUD, profile, employment/movement/asset/lifecycle history
- `/api/v1/onboarding` — Onboarding requests, approvals, task generation, completion summary
- `/api/v1/offboarding` — Offboarding requests, manager review, scheduled & emergency revocation, clearance
- `/api/v1/movements` — Transfers, promotions, inter-company movements, access delta reviews
- `/api/v1/workflows` — Workflow definitions, stages, templates, draft/publish versioning
- `/api/v1/tasks` — Task inbox, status updates, reassignment, comments, evidence upload
- `/api/v1/assets` — Inventory CRUD, assign, return, transfer, condition logs
- `/api/v1/documents` — Authenticated upload, metadata, version history, authorized download streaming
- `/api/v1/integrations` — Config, health tests, manual sync/retry, execution logs
- `/api/v1/reports` — 12 management reports + `?format=json|csv|xlsx|pdf`
- `/api/v1/audit-logs` — Searchable immutable compliance log

---

## 4. Background Job & Scheduling Architecture

Lifecycle automation requires reliable asynchronous execution:
1. **Scheduled Account Deactivations** (e.g., execute Entra ID disable at exact `scheduledDeactivationAt` on Last Working Date).
2. **Overdue Task Reminders & Escalations** (daily/hourly scan for tasks nearing or past SLA).
3. **Integration Calls & Retries** (exponential backoff for transient Graph API / Freshservice timeouts, dead-letter alert to IT Admin on permanent failure).
4. **Workflow Delay Nodes** (e.g., unlock tasks `N` days before/after start date).

**Design**: A PostgreSQL-backed `BackgroundJob` table using `SELECT ... FOR UPDATE SKIP LOCKED` semantics executed by a dedicated Node worker script (or scheduled trigger). This avoids requiring Redis on day one while guaranteeing transactional enqueueing (job creation commits in the same DB transaction as the lifecycle state change).

---

## 5. UI/UX Design System (Aligned to Reference Screenshot)

Inspired by the uploaded **Crewly** reference and modern SaaS platforms (Linear, Asana, Monday.com):

### Visual Tokens
| Token | Value | Usage |
| :--- | :--- | :--- |
| Canvas Background | `#F8FAFC` | Main app workspace background |
| Surface | `#FFFFFF` | Cards, tables, sidebar, modals |
| Primary Text | `#111827` | Headings, primary table values |
| Secondary Text | `#64748B` | Captions, metadata labels, helper text |
| Border | `#E5E7EB` | `1px` crisp structural dividers |
| Primary Accent | `#2563EB` | Primary actions, active links, focus rings |
| Accent Soft Surface | `#EFF6FF` | Active sidebar pill, selected items |
| Success | `#16A34A` / `#DCFCE7` | Completed, Published, Active badges |
| Warning | `#F59E0B` / `#FEF3C7` | Pending Approval, In Progress, Due Soon |
| Danger | `#DC2626` / `#FEE2E2` | Overdue, Emergency Offboarding, Failed Integration |
| Info | `#0EA5E9` / `#E0F2FE` | Pre-boarding, Scheduled, Info notices |

### Typography & Layout Principles
- **Font**: `Inter` (primary UI) + `JetBrains Mono` (Employee IDs, Asset Tags, Ticket IDs, Audit hashes).
- **Persistent Collapsible Left Sidebar** (`248px` expanded / `68px` collapsed):
  - Brand mark (**PEOPLEFLOW**) at top.
  - Permission-filtered nav items: Home, Onboarding, Offboarding, Employee Movement, People, Workflows, Tasks, Assets, Documents, Integrations, Reports, Audit Logs, Settings.
  - Compact user profile footer with avatar initials, name, active role badge, and account menu.
- **Sticky Top Bar** (`60px` height):
  - **Company Selector** (`All Companies (SMC)` / `ECC` / `NCC` / `SCII`, restricted to authorized companies).
  - **Global Search** (`Ctrl+K` command palette searching employees, requests, tasks, assets).
  - **Notifications Bell** (live unread count + popover), **Help**, and **Profile Menu**.
- **Workflow Builder Pattern** (directly matching the reference screenshot):
  - Top breadcrumb + status badge (`Draft` / `Published`) + `Preview` + `Publish` actions.
  - 4-column metadata summary bar (`Template`, `Date Reference`, `Company Scope`, `Total Tasks`).
  - Stacked stage containers with softly tinted stage headers (`Pre-Start`, `Day 1`, `Week 1`, etc.), inline task rows with Department pill + Assignee avatar picker + relative due date (`-3d`, `D1`, `+5d`).
  - Right-hand `Add Component` palette (`Basic Tasks` & `Advanced Components`) supporting drag-and-drop and click-to-add.

---

## 6. Security, Privacy & Observability

- **Philippine Data Privacy Act (RA 10173)**:
  - Sensitive Personal Information (DOB, personal email/phone, separation reason, disciplinary notes) is access-controlled at field level and redacted from logs.
  - Documents are stored **outside** `public/` and streamed only after server-side permission & company-scope verification, with every download recorded in `AuditLog`.
- **Irreversible Action Safety**:
  - Emergency offboarding and live external account revocation require explicit confirmation dialogs, re-verified permissions, and dual tracking (requested by, approved by, executed by, external system response, verification timestamp).
- **Structured Logging**:
  - JSON logs with `requestId`, `userId`, `companyId`, `action`, `durationMs`, and automatic scrubbing of tokens, secrets, passwords, and PII fields.
- **Credential Security**:
  - Integration credentials stored via environment variables or AES-256-GCM encrypted columns in `Integration.encryptedConfig` keyed by a server-only `INTEGRATION_ENCRYPTION_KEY`.
