# PBPS MIS — Version 2 Master Plan

**Project:** Performance Based Payment Scheme (PBPS) — Monitoring & Verification MIS, Skills-for-Jobs component of the EASE / Qiyas project (World Bank financed; EDI / MoLS; M&E & verification by ICOS).
**Document purpose:** a complete, implementable plan to rebuild the MIS as Version 2 — same functionality, reorganised and corrected, able to serve **120,000 trainees** reliably — **without losing any existing data**.
**Companion documents:** `02_DATABASE_REDESIGN_AND_MIGRATION.md` (schema + migration SQL), `03_FRONTEND_PROMPT.md` (UI build prompt).
**Basis of this plan:** a full read of the V1 code base (backend ≈ 32,000 lines / 104 files; frontend ≈ 35,000 lines), the live database `pbps_mis` (MariaDB 10.4.32 under XAMPP), the official indicator protocol (19 indicators), the official trainee registration form, the completion-verification sampling protocol, and the repository documentation. Where documentation and code disagree, **the code and the live data were treated as the truth** (several documents are out of date — see §2.12).

---

## Table of contents

- **Part A — Where we are today**
  - 1. Executive summary
  - 2. Current-state analysis (V1), module by module
  - 3. Why pages take more than a minute — root-cause analysis with evidence
  - 4. Requirement traceability — every request in the brief and where it is answered
- **Part B — V2 target architecture**
  - 5. Guiding principles
  - 6. Technology stack and why
  - 7. Backend structure (modular monolith) — folders, layers, rules
  - 8. Cross-cutting concerns (request context, errors, validation, dates & calendars, IDs, jobs, cache, files, logging)
- **Part C — Domain model and naming**
  - 9. The new delivery hierarchy (Training → Site → Class) and glossary
  - 10. Active and reserve trainees — role, rules, V2 policy
- **Part D — Module specifications (functional + technical)**
  - 11. Identity & sessions
  - 12. Access control (roles, permissions, scopes) — full matrix
  - 13. Projects & settings
  - 14. Training-provider onboarding, contracts and targets
  - 15. Delivery structure: trainings, sites, classes, calendars, holidays, breakdowns
  - 16. Registration: trainee field schema, form, CSV/XLSX import, validation helpers
  - 17. Duplicate prevention and detection
  - 18. Roster lifecycle: freeze, change requests, withdrawals (replaces "registration integrity")
  - 19. Attendance
  - 20. Outcomes (dropout, completion, certification, employment) — new status model
  - 21. Indicators: registry (protocol definitions), metrics, per-TP targets, KPI engine & snapshots
  - 22. Activities: definitions, schedules, obligations, submissions, review
  - 23. Verification (sampling, tiers, fieldwork, decision) — configurable
  - 24. Grievance / feedback (GRM)
  - 25. Notifications, email and reminders (TP SMTP removed)
  - 26. Dashboards & reporting (PDF / DOCX / CSV)
  - 27. Audit trail and integrity
  - 28. Data health (replaces phone-correction / holiday-audit / duplicate tools)
- **Part E — Performance & scale engineering**
  - 29. Capacity model for 120,000 trainees
  - 30. Read models, snapshots, indexes, pagination, caching
  - 31. Performance budgets and load testing
- **Part F — Quality, security, operations**
  - 32. Testing strategy
  - 33. Security hardening
  - 34. Deployment, backup and disaster recovery
  - 35. Observability
- **Part G — API contract (endpoint inventory)**
- **Part H — Migration & cutover (summary; details in document 02)**
- **Part I — Delivery roadmap, work breakdown, risks**
- **Part R — Decisions that need M&E / client sign-off**
- **Appendices** — A: V1→V2 feature map; B: V1 defects found; C: glossary; D: business-rule catalogue

---

# PART A — WHERE WE ARE TODAY

## 1. Executive summary

### 1.1 The situation

The V1 MIS was built during the pilot while requirements were still being discovered. It works and it holds real data: **3,234 trainees** (2,993 active, 241 reserve) across **5 training providers** (IBT, AAU, Selam Children's Village, DAB DRT, Mohas Consult), **18 trainings**, **24 "cohorts"**, **111 "batches"**, **≈180,000 daily attendance rows**, **4,387 outcome rows**, **3 verification runs** (875 sampled subjects), **123 grievance cases**, and **7,285 audit events**.

The pilot changed the requirements many times (one start date per TP → many classes per site with their own start dates and weekdays; replacement of withdrawn trainees → reserves tracked equally; global registration gate → per-provider gates; tentative verification). Each change was absorbed into the existing code. The result is functional but:

1. **Slow.** Core pages (Outcomes, Verification, Dashboard, Indicator report) take tens of seconds to more than a minute **with only 3,234 trainees**. The cause is not the size of the data (the whole database is < 100 MB) but *how* it is computed: every page load re-computes every KPI for every provider from raw rows, in JavaScript, several times over (§3). At 120,000 trainees (≈ 12 million attendance rows) the V1 approach would not finish at all.
2. **Hard to change.** Two route files (`routes/domain.ts` 4,171 lines and `routes/performance.ts` 4,252 lines) hold most of the business logic, mixed with HTTP handling, validation, scope checks and database access. The same rule is implemented in several places (e.g. the eligibility rule exists in **three different versions**).
3. **Inconsistent at data entry.** Many registration fields are free text with no rules (region, date of birth, disability type…), booleans sent as "yes/no" are silently dropped, the form-completion date is parsed as **M/D/YYYY although the official form specifies DD/MM/YYYY**, and phones beginning with 7 (Safaricom) are rejected. Several "repair" pages (phone correction, duplicate roster check, holiday attendance audit, registration integrity) exist only because entry was not validated.
4. **Under-modelled.** Outcomes are stored as generic rows (`trainee_outcomes`: one row per trainee per report type, completion stores only the "yes" rows); indicators have no protocol definition in the system; per-provider targets do not exist; activity deadlines are configured as "day 1 to day 200" for every activity (effectively no deadline); feedback reminders are coded but **never called**; resubmission requests are stored inside the audit log; each TP was expected to configure its own SMTP server (none did — all five rows use the same ICOS mailbox).

### 1.2 The V2 answer in one page

| Problem | V2 solution | Where |
|---|---|---|
| Pages take > 1 minute | KPIs are **pre-computed into snapshot tables** by background jobs; attendance is summarised **per trainee** at write time; pages read small, indexed tables; every list is server-paginated. Target: p95 < 500 ms for lists, < 1 s for dashboards **at 120k trainees**. | §3, §21, Part E |
| God files | **Modular monolith**: 17 modules (registration, attendance, outcomes, verification, …), each with routes / schemas / service / repository / policy. Registration never imports verification, etc. | §7 |
| Outcome rows ×5 per trainee, non-completers implicit | **One status row per trainee** (`trainee_status`) holding dropout / completion / certification / employment statuses as typed columns (`yes`/`no`/`pending`), plus an append-only history of every reported line (both Yes and No). | §20, Doc 02 §5 |
| Cohort/batch names meaningless | **Training → Site → Class** hierarchy; a Class owns its start/end dates, weekdays, shift and venue. | §9 |
| No indicator definitions; one threshold for all TPs | **Indicator registry** with all protocol fields (operational definition, data source, frequency, computation, disaggregation, purpose) + **per-TP targets** with effective dates. | §21 |
| Unreliable activity deadlines | Activities produce **obligations** (one per TP / class with concrete open, due, close dates) generated from schedule rules; reminders are driven by obligations. | §22 |
| TP SMTP nobody could configure | **Removed.** One system mail service; TP-originated mail is sent "From: <TP name> via PBPS MIS" with **Reply-To: the TP's notification address**. | §25 |
| No reminders; TPs not told about new feedback | Unified **notification centre** (in-app + email outbox with retries) and a **reminder engine** (feedback SLA, activity due/overdue, attendance missing, outcome report due, verification tasks). | §24, §25 |
| Weak/unclear permissions | One membership model (user × project × role × provider × scope), permissions as code constants, policies per module, a published **permission matrix**, verifier roles added. | §12 |
| Free-text registration | **Field schema registry** (one definition drives the form, the CSV/XLSX template, server validation and the import preview), strict enums from the official form, Ethiopian-calendar date validation, phone normalisation to E.164, staging + preview + fix-in-place import. | §16 |
| Repair pages | Replaced by **validators at entry** and a scheduled **Data health** report. Registration integrity replaced by **roster freeze + change requests**. | §17, §18, §28 |
| Tentative verification, slow run list | **Verification plans** per indicator (parameters, single-tier or two-tier, CI method) with frozen sampling frames, call-attempt log, supervisor approval, Kobo export/import; the run list reads stored counters. Samples hidden from TPs until finalised. | §23 |
| No loading feedback | Every page has skeletons, progress for long jobs, optimistic updates, empty and error states (see document 03). | Doc 03 |
| Data must survive | New schema `pbps_v2` on the same server; **IDs preserved**; idempotent `INSERT … SELECT` scripts; raw values kept beside cleaned values; legacy tables archived verbatim; reconciliation queries + KPI parity report before cutover. | Part H, Doc 02 |

### 1.3 What does **not** change

- The business: TPs register trainees, record attendance, report outcomes, submit activity evidence; M&E monitors; ICOS verifies a statistical sample; EDI / World Bank oversee.
- The KPI meanings, unless explicitly listed in Part R for sign-off.
- Trainee IDs (`PBPS-<TP>-000001`), provider codes, existing record IDs, uploaded evidence files, the audit history.

---

## 2. Current-state analysis (V1), module by module

> Each subsection lists *what exists*, *how it really works (code truth)*, and *problems found*. Line references are to the V1 repository at the time of analysis.

### 2.1 Platform and structure

- **Backend:** Node.js + Express 4 + TypeScript (ESM), Prisma 6 over MySQL/MariaDB, Zod, Multer (uploads to local disk), Nodemailer, PDFKit, docx. Entry `src/index.ts` mounts 26 routers, most at `/api`.
- **Frontend:** React 18 + Vite + TypeScript, Tailwind + shadcn/ui (49 primitives), react-router 6, TanStack Query installed but most pages use hand-written `useEffect` + `useState` fetching; 59 page components; navigation grouped *Operate / Monitor / Govern*.
- **Database:** 52 tables (50 domain + `_prisma_migrations` + settings), 47 Prisma migrations. Engine in use: MariaDB 10.4.32 (XAMPP) — **end-of-life since June 2024**.
- **Size by file (backend):** `routes/performance.ts` 4,252 lines; `routes/domain.ts` 4,171; `routes/attendance.ts` 1,883; `routes/verification.ts` 1,666; `routes/projects.ts` 1,183; `services/smtp.ts` 867. These six files hold ≈ 45 % of the backend.
- **Background work:** an in-process `setInterval` alert scheduler (`services/alertScheduler.ts`) — runs inside every API process, also on boot.
- **Caching:** an in-process Map with TTL (`services/simpleCache.ts`), used only by the dashboard (45 s, keyed per *user*, so it rarely hits).

### 2.2 Authentication and sessions

- Email + password (bcrypt cost 12), JWT HS256 in **`localStorage`** (1-day lifetime), optional email-OTP 2FA (global switch; currently **off**), login rate-limit (20 / 15 min), lockout after 5 failures for 15 min, forced password change on first login.
- Welcome / staff-invite emails contain a **plaintext temporary password**.
- `requireAuth` runs up to **4 queries per request** (`canUserAuthenticate`) to decide whether the user may still sign in.

### 2.3 Authorisation (roles, permissions, scope)

- Roles: `admin`, `me` (M&E Lead), `tp`, `world_bank`, `edi` (+ custom roles). 44 permissions stored in `permissions` / `role_permissions`. Extra permissions are appended at boot (`permissionCatalog.ts`).
- TP users are linked to their provider in **three different ways**: `training_providers.user_id` (owner), `project_users.project_role = 'tp'`, and `tp_staff_memberships` (+ `tp_staff_delivery_scopes` at provider / cohort / batch level). A diagnostics + repair screen exists just to fix inconsistencies between them (`/tp-mapping-diagnostics`).
- TP staff roles (`tp_org_admin`, `tp_site_lead`, `tp_attendance_clerk`, `tp_outcomes_officer`, `tp_readonly`) are **hard-coded permission templates** intersected with the `tp` role at runtime.
- `requirePermission(key)` **without** a project parameter accepts the permission from **any** project the user belongs to.
- Per request: `requirePermission` (1 membership query + `resolveEffectiveAbilities` ≈ 4–6 queries) and then most handlers call `hasProjectAccess` and `resolveScope` again → **≈ 10–15 queries before any business logic**.
- Questionable grants in live data: `submit:outcomes` is granted to `world_bank`; `manage:tps` to `world_bank`; TPs hold `view:verification` and can therefore see **which of their trainees were sampled** before verification is finished (risk of coaching respondents).

### 2.4 Projects and settings

- One project in data (`PBPS`, over-enrolment allowance 15 %). Project-level and provider-level registration gates (`registration_closed_at` + note).
- App settings (key/value): `security.email_2fa_enabled`, `alerts.scheduler_enabled`, `alerts.evaluation_interval_minutes`, `attendance.exempt_days_from_scope_start` (default 14), `trainee.replacement_window_days`.
- Master data: 3 locations (Addis Ababa AA, Hossana HO, Dessie DE), 3 durations (3 / 4 / 6 months).

### 2.5 Delivery structure (trainings, cohorts, batches)

- `trainings` (18): one per TP course, with type (Basic/Intermediate/Advanced), duration, planned start/end, `delivery_location_ids` (JSON array of strings), `session_weekdays` (JSON), status, optional `timeline_anchor_date` (actual start). `training_programs` (19) exists but is only half used (several trainings have no program; a "Test Training" program exists).
- `training_cohorts` (24): intended to mean **a delivery location** of the training, but in data some are named after the course ("Cloud Computing", "4 Kilo Campus Cohorts", "6K Campus Chort"). Status is always `planned` (never maintained).
- `training_batches` (111): intended to mean **a class / section**, each with its own start/end and weekdays (e.g. `[1,3,5]` vs `[2,4,6]`). Names are inconsistent: code "Selam class 3" with name "Cohort 1"; "MG-GH-M / Megenagna – Growth Hackers (Morning)"; "6K – Batches MWF". `campus_label` and `sections_count` are unused. A single-site training silently gets an auto-created `MAIN` cohort and batch.
- Every trainee carries `training_id`, `cohort_id`, `batch_id`, `location_id`, `training_duration_id` (denormalised, all populated).
- "Actual start" can be set per training / cohort / batch; it moves the end date by the same delta. In data, all anchors are NULL.
- `trainee_enrollments` duplicates the trainee's scope; **85 reserve trainees have no enrollment row**.

### 2.6 Registration (trainees)

- Manual form and CSV import (CSV parsed **in the browser**, posted as JSON rows).
- Server checks: provider, first name, sex (any non-empty text), age numeric (**no 18–29 range check**), primary phone must be an Ethiopian mobile beginning with **9** (so **07 Safaricom numbers are rejected**), duplicate phone in file and in project, form-completion date (Excel serial, M/D/YYYY or ISO), roster role, external beneficiary ID (required for AAU; unique per provider), training scope (training type, duration, location text must match cohort), cohort/batch resolution, registration gate open, contract cap (target × 1.15).
- **Not validated:** region, woreda, sub-city, kebele, email format, education and employment (keyword-normalised; unknown values pass), disability type, booleans (any non-boolean value becomes NULL — **silent data loss**), prior-training fields, consents, age vs date of birth consistency, sex enum.
- **Date of birth** ("Ethiopian calendar") is stored as **free text**; live data mixes `7/24/92`, `27/01/1993`, `2/5/2000`.
- **Form-completion date** is parsed month-first although the official form says DD/MM/YYYY; 702 of 3,234 stored dates have a day ≤ 12, and after a plausibility rule (the swapped reading must not fall after the registration date) **363 remain genuinely ambiguous** (Doc 02 §9.5.3, §14 Q1).
- Regions in data: `Addis Ababa` 2,627, `Amhara` 253, `Central Ethiopia` 107, `Oromia` 92, `Central Ethiopia Regional State` 59, `Oromiya` 27, `Central Ethiopian region` 16, `Addis Abeba` 6, `A.A` 5, `Adiss ababa` 3, `Addisabeba` 2, `Ethiopia` 3, `Sheger City` 2 …
- Disability type: NULL 1,672, `not a person with disability` 1,464, `None` 6, `No` 4, `nothing` 2, `Prefer not to say` 34, real types ≈ 34.
- Import performance: per row, separate queries for provider, external ID, training, cohorts, location (N+1); unique ID generated per row by reading the max ID (retry up to 8× on collision).
- Trainee ID format: `<PROJECT>-<TP>-<6 digits>` (e.g. `PBPS-AAU-000001`).
- Trainee edit requires the registration gate to be open.

### 2.7 Duplicate handling

- Hard rule at import: a primary phone may exist only once per project.
- Scan (`traineeDuplicateDetection.ts`, algorithm `v3-fuzzy-name-parts`): first and father name (and grandfather when both present) must each be "close" (Jaro-Winkler ≥ 0.85, or Levenshtein ≤ 2 for names ≤ 6 letters); score = average similarity × 100, +5 for the same phone; candidates ≥ 85 kept; blocking by 3-letter name prefixes; the entire project is loaded into memory (limit 20,000). **Date of birth, age and sex are ignored.** 46 scans run, 19 candidates (17 pending).
- Separate tools: "Roster duplicate check" (messy external rosters, IBT spec), "Phone correction" (fix scientific-notation phones from Excel), "Holiday attendance audit" (remove attendance on holidays), "Registration integrity" (compare initial TP lists with the system after unauthorised removals).

### 2.8 Attendance

- One row per trainee per session date per batch (`trainee_attendance_days`), status present / absent (`excused` exists in the schema but cannot be submitted), source manual / csv_daily / manual_backfill.
- Rules: date must be a scheduled session of the batch (batch weekdays, batch dates, not a holiday, not inside an approved breakdown, not in the first 14 "exempt" days, not in the future); one submission per batch per date (second attempt → 409); "backfill missing" adds rows for trainees added later; CSV import with strict headers.
- KPI: (present + excused) ÷ eligible scheduled sessions to date, active + reserve, per trainee from batch start (the stored `attendance_eligible_from` is **ignored**).
- Problems: no correction workflow once a day is submitted; row-by-row upserts without a transaction; 37 rows exist on dates later declared holidays; each row repeats six foreign keys (project, provider, training, cohort, batch, trainee) — the index footprint (47 MB) is more than twice the data (20 MB).
- Dates are mixed between local-time keys (`getFullYear()`) and UTC keys (`toISOString().slice(0,10)`); stored as `DATETIME 12:00:00` to dodge time-zone shifts.

### 2.9 Outcomes

- Report types and order: **dropout → completion → certification / job_linkage / decent_job (stages m1 = 30 days, m2 = 60 days) / locality_compliant → job_retention_3m** (needs decent_job).
- Upload = CSV per (TP, training, optional cohort). Gates: all delivery batches in the file must have ended; attendance must be fully captured (for dropout and completion); completion needs a processed dropout report per delivery batch; per-trainee prerequisites (certification needs completion = yes, …); dropout cannot follow completion; **every "system-final" low-attendance dropout must be reported as Y** (no dispute path any more); `dropout_reason` required for Y; once a scope has a processed report, a **resubmission request** (request → approve/reject → consumed) is required — and these requests are **stored as rows in the audit table** (`submission_events`).
- Storage: one `outcome_report_batches` row per delivery batch per upload; one `trainee_outcomes` row per trainee line, written **row by row, outside a transaction** (a crash leaves a half-written report). Dates of completion/certification are kept as **strings inside JSON** (`{"completion_date":"8/27/2026"}`); `status_date` is NULL for 228 completion and 733 dropout rows. No unique constraint on (trainee, outcome type, stage).
- Completion templates only list eligible candidates and the stored data contains **only completers** (1,706 rows, all `reported_value = 1`) — non-completers are implicit. Dropout templates list everyone, so dropout has both Y (261) and N (1,706) rows; the N rows of one provider carry a legacy `{"dropout_dispute":"system_final_disputed"}` marker.
- After an upload, open "pre-report" verification runs are back-filled automatically.

### 2.10 Indicators and KPIs

- 11 indicators configured (`project_indicators`), each pointing to numerator/denominator **variables** (`indicator_variables`, 15) whose meaning is a JSON `query_spec` interpreted by a long `if` chain in `services/indicatorKpis.ts`.
- Rules actually applied (code truth):
  - **Registered**: active + reserve.
  - **Eligible %**: age 18–29 AND education keyword AND employment keyword ÷ **contract target**; threshold 100.
  - **Attendance %**: see §2.8; threshold 80.
  - **Dropout %**: TP-reported Y **or** system-final (class ended and attendance < 80 %, transfers excluded); dropouts inside the **over-enrolment buffer** (registered − contract target) do not count; ÷ contract target; no threshold.
  - **Completion %**: completers, **set to 0 for the whole provider** if the provider's *average* attendance is below the attendance threshold **or** if any expected attendance slot is missing; capped at contract target; ÷ contract target; threshold 90.
  - **Certification / job linkage / decent job / locality / retention**: positive outcome counts ÷ completion (retention ÷ decent job); thresholds 100 / 80 / 80 / 80 / 90.
  - **Timely grievance resolution**: responded within the due date ÷ (responded + overdue unanswered).
- "Verified" values for sampling indicators = latest finalised run per TP (pooled tiers).
- **Thresholds are per indicator only; there are no per-provider targets.**
- The official protocol defines **19 indicators**; 8 provider-level ones (contract signed, inception report, LMDA, orientation, pre-training evaluation, full duration, post-training assessment, post-placement support) exist only as *activities*, with no indicator row. None of the protocol fields (operational definition, data source, frequency, disaggregation, purpose) are stored.

### 2.11 Activities (evidence submission)

- 8 activities: `contract_signed`, `inception_report`, `lmda_alignment` (provider scope), `orientation_sessions`, `pretraining_report`, `full_training_duration`, `posttraining_report`, `postplacement_support_program` (delivery scope). TPs may also create activities.
- Windows: rule per activity × **training duration**, anchor (training / cohort / batch start or anchor), open offset, end offset, grace days; extended by approved breakdowns; frozen during a breakdown. **Provider-scope activities never have a window.**
- In data **every rule is "open day +1, close day +200, grace 0, anchor cohort_anchor"** — i.e. deadlines are effectively absent, which is why the "due soon" alerts are noise (176 open). 28 submissions, **none reviewed**.

### 2.12 Verification

- Sampling indicators: eligibility, completion, certification, job linkage, decent job, locality, retention.
- Draw per (indicator, TP, period `YYYY-MM`, stage): population = **all registered (active + reserve) trainees of the TP**; Cochran n₀ = Z²p(1−p)/e² (Z 1.96, p 0.5, e 0.05 → 385), finite-population correction, ÷ 0.9 non-response, reserves 15 % per stratum; strata = delivery location × sex; largest-remainder allocation with minimum 1 per stratum; deterministic seeded shuffle (seed stored).
- Fieldwork statuses: V-COMP, V-NCOMP (definite), V-UNR, V-REF, V-INC (replaceable by next reserve of the same stratum).
- Rate = V-COMP ÷ definite; **Wilson interval, one-sided, z = 1.645**; pathway: clear pass (lower > threshold), clear fail (upper < threshold), inconclusive → **Tier 2** draw pooled with Tier 1 (the "twice verification").
- "Pre-report" draws allowed (sample before the TP reports); dropouts auto-marked V-NCOMP at draw.
- The protocol document's call-attempt rule is internally inconsistent (table: 3 attempts; note: "maximum of two").
- 3 runs exist (all completion, period 2026-09, all open); 79 subjects have a verdict (all auto V-NCOMP dropouts).
- Fieldwork itself happens in KoboToolbox outside the MIS; there is no import of Kobo results and no call-attempt log.

### 2.13 Grievance / feedback (GRM)

- Public form (rate-limited, XSS-hardened, with tests) → thread with reference `GRM-<year>-<last 6 digits of epoch ms>` (collision possible), due in 7 days; TP replies (sent through the TP SMTP, falling back to system SMTP), resolve, summary metrics, exports.
- New-case email goes only to **active TP staff memberships** (not to the provider's owner account or contact email); **no in-app notification**; `sendFeedbackDueDateReminderToProvider` is **implemented but never called** — so no reminders exist.
- Public routes are registered **twice** (in `feedback.ts` and `publicFeedback.ts`).
- 123 cases (complaint 32, appreciation 63, suggestion 22, question 6); 69 TP replies.

### 2.14 Email, alerts, reminders

- System SMTP from `smtp_configurations` (password stored in clear) or env; TP SMTP from `tp_smtp_configurations` — 5 rows, **all identical** (`feedback@icosconsult.com`), proving TPs could not set their own.
- Alert types: `activity_due_soon`, `activity_overdue`, `attendance_coverage_low`, `dropout_risk_summary`; in-app recipient states + email; admin daily digest sent with **all admins in one To: header**. Nothing for: new/overdue feedback, outcome reports due, verification tasks, registration windows, contract or target setup.

### 2.15 Audit trail

- `submission_events` with a SHA-256 hash chain and an integrity check/export bundle.
- Defects: the chain head is read then written without a lock (concurrent writes fork the chain); `stableJson` passes an **array replacer** to `JSON.stringify`, which also filters nested keys — so the contents of `meta` are not actually covered by the hash; the table doubles as a workflow store (resubmission requests).

### 2.16 Reports and dashboards

- PDF/DOCX: dashboard claimed-vs-verified, provider profile, trainee profile, indicator summary, feedback summary/detail, verification run & summary, activities compliance; executive pack; CSV exports.
- Dashboard bundle = full KPI engine + another full attendance roll-up + daily series + roster insights.

### 2.17 Frontend

- Pages fetch with `useEffect`, rarely with TanStack Query; **skeletons used on 2 pages**, elsewhere plain "Loading…" text — consistent with the brief's "no loading state". The handover document claims skeleton loading everywhere; that is not the case.
- Prototype stores (`src/data/governance.ts`, `mock.ts`) are still imported by real screens (trainee verification tab, Settings, Project create).
- Client-side duplicates of server rules (`lib/eligibility.ts`, `lib/phoneNormalize.ts`, `lib/rosterReconciliation.ts`).

### 2.18 Documentation drift (do not rely on these without checking)

| Document | Drift found |
|---|---|
| `HANDOVER_TECHNICAL_BRIEF.md` | Claims skeleton loading states across the UI; claims "every sensitive route" is project-scoped (global routes are not). |
| `ACTIVITY_DEADLINES_EASY_GUIDE.md` | Describes windows that data configuration does not use (all 1–200). |
| `DROPOUT_COMPOSITE_ROLLOUT.md` | Describes a TP dispute path that `dropoutPolicy.ts` now blocks. |
| `RESERVE_ROSTER_QA.md` | Mentions "verification sample draws from `enrolled_trainees`"; code draws from `registered_trainees`. |
| Feedback SMTP guides | Assume per-TP SMTP is the normal path. |
| Verification protocol | 3 vs 2 call attempts; Z values differ between sections (1.96 for size, 1.645 for CI). |

---

## 3. Why pages take more than a minute — root-cause analysis with evidence

### 3.1 The data is small; the computation is not

Live sizes: `trainee_attendance_days` 180k rows / 20 MB data / 47 MB indexes; `trainees` 3,234 rows; `trainee_outcomes` 4,387 rows. Any well-indexed query over these returns in milliseconds. The slowness is **algorithmic**.

### 3.2 The KPI engine is executed on page load

`GET /projects/:id/indicator-kpis` → `buildIndicatorKpiPayload()` is called by:

| Page | Why it calls the full engine |
|---|---|
| Outcomes hub | only to show one banner: "Completion is blocked because attendance uploads are incomplete" |
| Verification list | to show claimed values next to runs |
| Verification insights | claimed vs verified |
| Indicator report | its main content |
| Dashboard | via the dashboard bundle (plus an extra attendance roll-up) |

### 3.3 What one engine call does (sequential, uncached)

1. For each of ≈ 15 variable codes: one `findUnique` on `indicator_variables` (N+1), then `resolveVariableCounts()`.
2. `attendance_present_entries` → `computeAttendancePresentPossible()` — **full attendance roll-up #1**.
3. `attendance_possible_entries` → the same function again — **roll-up #2**.
4. `completion_trainees_protocol` → present **#3**, possible **#4**, then `attendanceSubmissionCoverageByTp()` → `computeAttendanceCapturePossible()` **#5** + a group-by over all attendance rows.
5. `effective_dropout_trainees_protocol` → `computeDropoutProjections()` **#1**.
6. Later, `attendanceSubmissionCoverageByTp()` again → roll-up **#6**.
7. Per indicator: two more `indicator_variables` lookups; for the dropout indicator `computeDropoutProjections()` **#2**; for each sampling indicator, finalised runs and pooled subjects.

### 3.4 What one attendance roll-up does

`computeAttendancePresentPossibleInternal()`:
- loads every training **with all its trainees nested**;
- for each training, queries its batches; **for each batch** (111) runs a `trainee_attendance_days.findMany` that returns **every present/excused row** of that batch (≈ 160,000 rows in total) to Node.js;
- for each trainee, builds the session calendar in JavaScript (iterating every calendar day of the batch, filtering weekdays/holidays/breakdowns/exempt days) and intersects it with the rows.

≈ **115 queries and 160,000 rows transferred per roll-up**, executed **≈ 6 times per KPI request**, plus **2 dropout projections**, each of which also loads all present rows and rebuilds calendars per trainee. A single Outcomes page load therefore moves roughly **one million rows** through the ORM and the JavaScript heap. Prisma's per-row materialisation cost (BigInt conversion, Date objects) dominates — hence tens of seconds, and over a minute when several users load pages at once (the connection pool is 10).

### 3.5 Secondary contributors

- 10–15 authorisation queries per request (§2.3).
- Verification run list includes **all subjects of up to 200 runs** to compute two counters.
- Dashboard cache keyed per user (no sharing across users).
- Trainee import validation runs per-row queries (N+1) and generates IDs one by one.
- Duplicate scan loads the whole project into memory.

### 3.6 Projection to 120,000 trainees

Attendance volume: ≈ 120,000 trainees × ≈ 75–100 sessions ≈ **9–12 million rows**. The V1 roll-up would transfer ~10 M rows × 6 per page view — it will not complete within any HTTP timeout. **Indexing alone cannot fix this**; the design must change:

1. **Compute at write time, read summaries.** When a class's attendance for a day is saved, update that class's trainees' counters (≈ 40 rows). When the calendar changes (holiday, breakdown, actual start), recompute that class's schedule (a few hundred date rows).
2. **Snapshot KPIs.** A background job recomputes `kpi_snapshots` (per indicator × provider × as-of date) after relevant writes (debounced) and nightly. Pages read snapshots.
3. **Use SQL aggregation** over narrow, indexed tables for anything ad hoc (`SUM(completion_status='yes') GROUP BY provider_id` over 120k rows ≈ 20 ms).
4. **Paginate every list on the server.**

Details in Part E.

---

## 4. Requirement traceability — every request in the brief and where it is answered

| # | Request (from the brief) | Answer in V2 | Section |
|---|---|---|---|
| R1 | Analyse the whole system, every part of the code | Current-state analysis, defect list | §2, §3, App. B |
| R2 | Pilot now ≈ 3,000 trainees; must serve 120,000 efficiently | Capacity model, read models, snapshots, budgets, load tests | Part E |
| R3 | Outcome report page and core pages take > 1 minute | Root cause + fix | §3, §20, §21, Part E |
| R4 | DB organisation suspected (outcome rows ×5) — consider status columns per trainee (completion yes/no, dropout…) | `trainee_status` 1:1 table with typed status columns + append-only report lines | §20, Doc 02 §5 |
| R5 | Convert the DB to a suitable design **without losing accuracy of stored data** | New schema, ID-preserving idempotent migration, raw columns, archive, reconciliation | Part H, Doc 02 |
| R6 | Remove TP SMTP settings; use system SMTP; TP notifications use the TP's email | Mail service + Reply-To/display name; TP notification address; TP SMTP archived | §25 |
| R7 | Reminders need a correct implementation | Reminder engine (rules, idempotent schedule, digest) | §25.5 |
| R8 | Registration format: enforce rules for every column (dates not enforced) | Field schema registry, per-column validators, ET-calendar dates | §16 |
| R9 | CSV import must check each column with its own method | Import pipeline with staging, per-cell errors, preview/fix | §16.6 |
| R10 | Completion report should record non-completers as "no" | Completion submissions are full rosters (Y/N for every trainee); migration infers "no" only where provable | §20.4, Doc 02 §9.6 |
| R11 | System has no loading state or animation | Loading/empty/error/progress standards in every page | Doc 03 §3 |
| R12 | Activity submission per TP timeline (3 vs 6 months, different starts) — doubt reliability | Schedules → concrete obligations per TP/class; previews; reminders | §22 |
| R13 | Feedback: notify TPs of new feedback; check improvement areas | Notification centre + SLA reminders + escalation + GRM analytics + satisfaction + corrective actions | §24 |
| R14 | Permissions/authorisation not well defined | Membership model, permission constants, policies, full matrix | §12 |
| R15 | Attendance is fine but check it | Findings §2.8 + V2 design (corrections, excused, calendars, summaries) | §19 |
| R16 | Backend organisation: `domain.ts` / `performance.ts` do everything — want clear structure, each folder its own responsibility | Modular monolith with enforced boundaries | §7 |
| R17 | Verification not finalised, slow run list; maybe remove "twice verification" for some indicators; formula may change | Verification plans (configurable params, single/two-tier per indicator, pluggable estimator), stored counters | §23 |
| R18 | TP onboarding should be well configured | Onboarding wizard + checklist | §14 |
| R19 | Cohorts and batches badly designed / named; must not lose data | Training → Site → Class; mapping keeps all IDs | §9, Doc 02 §9.3 |
| R20 | Different classes per site with own start dates and weekdays | Class owns start/end/weekdays/shift/venue; calendar per class | §15 |
| R21 | Duplicate scanning mechanism should be improved | Prevention at entry + indexed, multi-signal matching; incremental scans | §17 |
| R22 | Indicator protocol/definition missing — study indicator functionality | Indicator registry with all protocol fields; 19 indicators seeded | §21 |
| R23 | Each TP will have its own target (not only per-indicator threshold) | `indicator_targets` per provider with effective dates, default fallback | §21.4 |
| R24 | Study active and reserve trainees | Role analysis + V2 policy | §10 |
| R25 | Markdown files may not reflect code | Drift table; code treated as truth | §2.18 |
| R26 | Very organised files/folders; registration not mixed with verification; future changes easy | Module boundaries, dependency rules, events, extension points | §7.3–7.6 |
| R27 | Give SQL to change the DB, or build a new DB and migrate (idempotency, indexes …) | New DB + migration SQL (both), indexes, constraints | Doc 02 |
| R28 | Frontend prompt: every page, what it does, new theme, ≥ 1,000 lines | Document 03 | Doc 03 |
| R29 | Phone correction and duplicate scan were needed because registration was weak → make them utilities/helpers | Validators in `shared/validation`, used at entry; Data health report | §16.4, §28 |
| R30 | Registration integrity page not needed (unauthorised removals) — do it properly | Roster freeze + change requests + soft delete | §18 |
| R31 | This is polishing, but a redesign from scratch; keep the same functionality | Feature map V1→V2 | App. A |
| R32 | Never lose data | Principle, archive, reconciliation, sign-off gates | §5, Part H |

---

# PART B — V2 TARGET ARCHITECTURE

## 5. Guiding principles

1. **Data is never lost.** Migration preserves IDs, keeps raw values beside cleaned values, archives anything not mapped, and is verified by reconciliation before cutover. Deletion in V2 is *soft* for business records (trainees, reports, submissions); hard deletes are limited to drafts and are audited.
2. **Validate at the door.** Bad data is rejected (or held for correction) at entry with a clear, per-field message. No V2 feature exists only to repair data that should never have been accepted.
3. **Compute once, read many.** Expensive results (attendance rates, dropout status, KPI values, verification statistics) are computed when inputs change and stored. Page loads never recompute project-wide aggregates from raw rows.
4. **One rule, one place.** Every business rule (eligibility, dropout, completion gate, window calculation, sample size…) lives in exactly one pure function inside its module, with unit tests, and is reused by API, jobs, exports and reports.
5. **Modules own their data.** A module's tables are written only by that module. Other modules read through the module's service API or subscribe to its events.
6. **Explicit state machines.** Every workflow object (import, report, submission, obligation, run, subject, case, request) has a documented status set and allowed transitions enforced in one place.
7. **Configuration over code for programme rules that change** (targets, thresholds, windows, sampling parameters, reminder offsets, tiering) — but **code over configuration for logic** (metric definitions are code, selected by key; no JSON mini-language interpreted at runtime).
8. **Least privilege, scoped by default.** Every query is filtered by the caller's access context (project → provider → site/class); tests prove TP A cannot see TP B.
9. **Dates are dates.** Calendar dates are stored as `DATE` and handled as `YYYY-MM-DD` strings in a single explicit time zone (`Africa/Addis_Ababa`); timestamps are UTC `DATETIME(3)`.
10. **Every screen tells the user what is happening.** Loading, empty, error, partial and long-running states are designed, not left to chance.
11. **Documentation is a deliverable** and lives next to the code (`/docs` in each module), generated where possible (OpenAPI, permission matrix, indicator registry).

## 6. Technology stack and why

| Layer | Choice | Reason |
|---|---|---|
| Runtime | **Node.js 22 LTS + TypeScript 5 (strict)** | Same language as V1 and the team; reuse of proven pure functions (sampling, Jaro-Winkler, calendar). |
| HTTP framework | **Fastify 5** (with `fastify-type-provider-zod`) | Higher throughput than Express, schema-based validation and serialisation, plugin encapsulation that fits modules, built-in structured logging (pino). |
| Validation / DTOs | **Zod** schemas per endpoint, also used to generate **OpenAPI 3.1** | One definition for runtime validation, types, docs and the generated frontend client. |
| Database | **MySQL 8.4 LTS** in production (MariaDB 10.11 LTS acceptable) | Team and client familiarity; migration runs as cross-schema `INSERT … SELECT` on the same server; CHECK constraints, CTEs, window functions, generated columns, `SKIP LOCKED` (job queue). MariaDB 10.4 (XAMPP) is end-of-life — development only. |
| ORM / SQL | **Prisma 6** (multi-file schema, one file per module) for transactional CRUD; **Prisma TypedSQL** (`.sql` files with typed results) for aggregates and reports | Keeps V1 familiarity; analytic queries are written in SQL and reviewed with `EXPLAIN`, never assembled in an ORM loop. |
| Background jobs | **DB-backed job queue** (`jobs` table, `SELECT … FOR UPDATE SKIP LOCKED`) in a separate **worker process** | No extra infrastructure; jobs survive restarts; one scheduler instance via a DB lease. Redis + BullMQ is the documented upgrade path. |
| Cache | In-process LRU (access contexts, reference data) with **version-stamp invalidation**; KPI results live in DB snapshot tables | Correct with several API instances because invalidation keys come from DB version counters. |
| Files | Storage adapter: **local disk** (default) or **S3-compatible** (MinIO / cloud); SHA-256 checksum per file | Evidence files are audit material; checksums prove integrity. |
| Email | Nodemailer behind a **mail service** with an **outbox table**, retries and templates (HTML + text) | Reliable, auditable, no per-TP SMTP. |
| Documents | PDFKit + `docx` (V1 builders reused), **streamed CSV**, **XLSX** via `exceljs` (import and export) | TPs work in Excel; streaming avoids memory spikes at 120k rows. |
| Auth | **Session cookies** (httpOnly, Secure, SameSite=Lax): short-lived access + rotating refresh tokens stored hashed in DB; optional **TOTP** 2FA (email OTP as fallback) | Removes the JWT-in-localStorage risk; sessions can be revoked. |
| Testing | **Vitest** (unit + integration on a real MySQL), **Playwright** E2E, **k6** load tests (V1 already has k6 scripts) | |
| Frontend | React 18 + Vite + TypeScript, **TanStack Query**, **TanStack Table** (server-side), react-hook-form + Zod, shadcn/ui + Tailwind, Recharts, generated API client from OpenAPI | Document 03. |
| Operations | Ubuntu LTS VM, **Nginx** (TLS, compression, static files, rate limits), **systemd** units (`pbps-api`, `pbps-worker`), MySQL 8.4, nightly encrypted backups + off-site copy | §34. |

## 7. Backend structure (modular monolith)

### 7.1 Repository layout

```
V2/backend/
├── package.json
├── tsconfig.json
├── .env.example
├── prisma/
│   ├── schema/                  # one Prisma file per module (prismaSchemaFolder)
│   │   ├── _base.prisma         # generator + datasource
│   │   ├── identity.prisma      access.prisma      projects.prisma
│   │   ├── providers.prisma     delivery.prisma    registration.prisma
│   │   ├── duplicates.prisma    attendance.prisma  outcomes.prisma
│   │   ├── indicators.prisma    activities.prisma  verification.prisma
│   │   ├── grievance.prisma     notifications.prisma files.prisma
│   │   ├── audit.prisma         platform.prisma    # jobs, settings, sequences
│   ├── migrations/              # Prisma migrations for V2 schema evolution (after go-live)
│   └── sql/                     # TypedSQL query files (read models, reports)
├── migration/                   # one-off V1 → V2 data migration
│   ├── sql/                     # 00_prepare.sql … 90_reconcile.sql (see document 02)
│   ├── run-migration.ts         # runs scripts in order, logs to migration_runs
│   └── reports/                 # generated reconciliation reports (markdown + CSV)
├── src/
│   ├── main.ts                  # API process (HTTP)
│   ├── worker.ts                # worker process (jobs + scheduler)
│   ├── app/
│   │   ├── buildApp.ts          # Fastify instance, plugins, module mounting
│   │   ├── plugins/             # session, access-context, error-handler, rate-limit, cors, openapi, request-id, idempotency
│   │   └── moduleRegistry.ts    # ordered list of modules
│   ├── config/env.ts            # Zod-validated environment
│   ├── core/                    # infrastructure only — no business rules
│   │   ├── db/                  # prisma client, transaction helper, TypedSQL runner, chunked bulk insert
│   │   ├── jobs/                # enqueue, schedule, lease, registry types
│   │   ├── events/              # domain event bus + transactional outbox
│   │   ├── cache/               # LRU + version stamps
│   │   ├── mail/                # transport, outbox writer, template renderer
│   │   ├── files/               # storage adapters, checksum, MIME sniffing
│   │   ├── http/                # pagination, sorting, filters, problem+json
│   │   ├── audit/               # append-only chained audit writer
│   │   ├── time/                # clock, Africa/Addis_Ababa, DateOnly type
│   │   └── logger/
│   ├── shared/                  # pure helpers, also compiled for the browser
│   │   ├── validation/          # phone, email, names, ethiopianCalendar, strict dates, enums, booleans
│   │   ├── text/                # normalisation, transliteration keys, Jaro-Winkler, Levenshtein
│   │   ├── stats/               # Cochran, FPC, Wilson, Clopper-Pearson, allocation, seeded RNG
│   │   └── calendar/            # session-calendar builder
│   └── modules/
│       ├── identity/            # login, sessions, 2FA, password reset, invites
│       ├── access/              # roles, permissions, memberships, scopes, policies
│       ├── projects/            # project profile, settings, master data (locations, durations, regions)
│       ├── providers/           # providers, contracts, notification addresses, staff, onboarding checklist
│       ├── delivery/            # trainings, sites, classes, holidays, breakdowns, class calendars
│       ├── registration/        # field schema, trainees, imports, roster freeze, change requests
│       ├── duplicates/          # matching keys, candidate generation, review
│       ├── attendance/          # sessions, marks, corrections, summaries, coverage
│       ├── outcomes/            # report types, templates, submissions, trainee statuses
│       ├── indicators/          # registry, targets, metrics, KPI engine, snapshots
│       ├── activities/          # definitions, schedules, obligations, submissions, reviews
│       ├── verification/        # plans, frames, draws, subjects, attempts, results, Kobo I/O
│       ├── grievance/           # public intake, cases, replies, SLA, satisfaction, actions
│       ├── notifications/       # in-app notifications, preferences, reminders, digests
│       ├── reporting/           # dashboards (read models), PDF/DOCX/CSV/XLSX exports
│       ├── audit/               # audit browsing, integrity verification, export bundle
│       └── datahealth/          # scheduled data-quality checks
└── test/
    ├── fixtures/                # factories producing realistic data
    ├── integration/             # API tests per module (real DB)
    └── load/                    # k6 scenarios
```

### 7.2 Inside a module (example: `modules/attendance/`)

```
modules/attendance/
├── index.ts                  # manifest: routes, jobs, event handlers, public API (attendanceApi)
├── attendance.routes.ts      # HTTP only: parse → service → map. No SQL, no rules.
├── attendance.schemas.ts     # Zod DTOs (→ OpenAPI)
├── attendance.service.ts     # use-cases: submitSession, requestCorrection, approveCorrection, getClassSheet…
├── attendance.repository.ts  # all DB access for this module's tables
├── attendance.policy.ts      # authorisation on resources
├── attendance.rules.ts       # pure rules (date eligibility, rate formulae) — unit tested
├── attendance.events.ts      # events emitted / handled
├── attendance.jobs.ts        # recomputeClassSummaries, nightlyRollover, coverageCheck
├── attendance.errors.ts      # typed domain errors with stable codes
└── __tests__/
```

**Layer rules** (enforced in CI by `dependency-cruiser`):

| Layer | May import | May not import |
|---|---|---|
| routes | own schemas, own service, `core/http` | repository, Prisma, other modules |
| service | own repository/rules/policy, `core/*`, `shared/*`, **other modules' public `index.ts` only** | other modules' repositories or tables |
| repository | `core/db`, Prisma client | services, other modules |
| rules | `shared/*` | anything doing I/O |
| shared | nothing outside `shared` | everything else |

Size guard: CI fails when a routes file exceeds **400 lines** or a service file **700 lines** — this forces split services (e.g. `outcomes/submission.service.ts`, `outcomes/status.service.ts`, `outcomes/template.service.ts`) and prevents a new "domain.ts".

### 7.3 Module dependency graph

```
identity → access → projects → providers → delivery → registration → attendance → outcomes
                                                         │                 │
                                                     duplicates            │
indicators   reads public read-APIs of: registration, attendance, outcomes, activities, grievance, verification
verification reads: registration (frame snapshot), outcomes (claims), indicators (definitions, targets)
activities   reads: delivery (dates), providers (contract dates)
grievance    reads: providers
notifications  driven by events from every module (nobody calls its internals)
reporting    reads read-models; writes only export jobs/files
audit        written through core/audit by all; browsed by the audit module
datahealth   read-only SQL over everyone; writes only its findings
```

No cycles. **Registration knows nothing about verification**; verification receives a frozen *frame* (list of trainee IDs + strata attributes) from a registration/outcomes read API and never queries their tables directly.

### 7.4 Communication between modules

1. **Synchronous reads** through public APIs (e.g. `deliveryApi.getClassCalendar(classId)`).
2. **Domain events** for side effects, written to an **outbox** in the same transaction as the change and dispatched by the worker:
   - `trainee.registered`, `trainee.updated`, `trainee.withdrawn`, `roster.frozen`
   - `class.scheduleChanged`, `holiday.changed`, `breakdown.approved`
   - `attendance.sessionSubmitted`, `attendance.correctionApproved`, `attendance.summaryUpdated`
   - `outcome.reportAccepted`, `outcome.reportSuperseded`
   - `activity.submissionReviewed`, `activity.obligationOverdue`
   - `verification.runFinalized`
   - `grievance.caseCreated`, `grievance.caseReplied`, `grievance.caseResolved`
   - `target.changed`, `indicator.definitionChanged`
3. Typical chain: `attendance.sessionSubmitted` → attendance updates class counters → `attendance.summaryUpdated` → outcomes refreshes system-dropout flags of that class → indicators marks the provider's KPI snapshot **stale** → debounced `kpi.recompute` job (≤ 60 s) replaces snapshot rows atomically → notifications raises alerts if thresholds are crossed.

### 7.5 Extension points

| Future change | Where it plugs in |
|---|---|
| New outcome type | `outcomes/reportTypes.ts` entry (columns, prerequisites, status mapping) + status column + metric. |
| New indicator | Metric function in `indicators/metrics/` (if needed) + definition row; targets via UI. |
| New verification method | New verification plan; estimators are strategies selected by key (`wilson_one_sided`, `clopper_pearson`, `wald`). |
| New registration field | Field schema registry entry → form, template, validation, preview update automatically. |
| New reminder | Reminder rule row (event, audience, offsets, template). |
| New role | Role + permissions in UI; policies use permission keys only. |
| Second project | Everything is project-scoped from day one. |
| Kobo / ODK API | `verification/kobo/` adapter behind the interface already used by CSV import. |
| SSO (OIDC / LDAP) | `identity/strategies/`; sessions unchanged. |
| SMS channel | `notifications/channels/sms.ts`. |

### 7.6 Coding conventions

- IDs: `BIGINT UNSIGNED` in DB, **strings in JSON**, `bigint` in services.
- Percentages: `DECIMAL(7,4)` (0–100); displayed with one decimal.
- Lists: `?page=&pageSize=` (max 200) or cursor (`?cursor=&limit=`) for very large tables; `?sort=field:asc`; filters as explicit, validated query params.
- Errors: RFC 7807 `application/problem+json` with a stable `code` (e.g. `REGISTRATION_CLOSED`, `PHONE_INVALID`, `WINDOW_CLOSED`) and `fieldErrors[]` for validation.
- Multi-row writes in a transaction; bulk inserts in chunks of 500.
- `Idempotency-Key` header on create/submit endpoints (stored 24 h): a double click never creates two reports.
- Optimistic concurrency: editable records carry `version`; updates send `If-Match`; conflicts → 409 with the current record.

## 8. Cross-cutting concerns

### 8.1 Request context

```ts
type RequestContext = {
  requestId: string;
  user: { id: bigint; email: string; name: string } | null;
  project: { id: bigint; code: string } | null;   // from :projectId
  access: AccessContext | null;                    // §12 — cached and versioned
  clock: Clock;                                    // injectable; today() in Africa/Addis_Ababa
};
```

`AccessContext` is loaded with **one** joined query (membership + role permissions + scopes) and cached in an LRU keyed `userId:projectId:accessVersion`; `accessVersion` is a counter on the user row bumped whenever memberships or roles change. Typical cost: 0 queries (hit) or 1 query (miss) — versus 10–15 in V1.

### 8.2 Errors

- Domain errors: `DomainError { code, httpStatus, message, details? }`.
- Zod errors → `fieldErrors: [{ path: "rows[12].phonePrimary", code: "PHONE_INVALID", message: "…" }]`.
- Unknown errors → 500 with `requestId`; stack traces only in logs.

### 8.3 Validation helpers (`shared/validation`) — the utilities that replace the repair pages

| Helper | Behaviour |
|---|---|
| `parsePhoneET(raw)` | Removes spaces, dashes, dots, Excel `.0`, leading `+`; **rejects scientific notation** (`9.11E+08`, code `PHONE_SCIENTIFIC_NOTATION`); accepts `09xxxxxxxx`, `07xxxxxxxx`, `9xxxxxxxx`, `7xxxxxxxx`, `2519…`, `2517…`, `+251…`; returns `{ e164: "+2519XXXXXXXX", national: "09XXXXXXXX", operator: "ethio_telecom" \| "safaricom" }`. |
| `parseEmail(raw)` | Trim, lower-case, structural check, ≤ 254 chars. |
| `parseName(raw)` | Trim, collapse spaces, Unicode NFC; Latin and Ge'ez letters, space, apostrophe, hyphen, dot; 1–60 chars; returns `{ display, normalized }`. |
| `parseDateStrict(raw, format)` | `DD/MM/YYYY` (official form) or `YYYY-MM-DD`; Excel serial converted only for numeric cells; **never guesses day vs month**; rejects impossible dates. |
| `parseEthiopianDate(raw)` | Ethiopian `DD/MM/YYYY`: month 1–13, day 1–30 (month 13: 1–5, or 1–6 in a leap year); returns `{ etc, gregorian }` via Julian-day-number conversion. |
| `checkAgeConsistency(age, dobGregorian, formDate)` | Flags when stated age differs from computed age by more than 1 year. |
| `parseEnum(raw, enumDef)` | Case/space/punctuation-insensitive match on canonical values **and aliases** (e.g. "A.A", "Addis Abeba", "Addisabeba" → `addis_ababa`); unknown → error listing allowed values. |
| `parseBoolean(raw)` | Yes/No, Y/N, True/False, 1/0, ☑/☐, Amharic አዎ/አይ; anything else → error (**never silently NULL**). |
| `parseIntRange(raw, min, max)` | Integers (Excel `23.0` accepted). |
| `normalizeFreeText(raw, opts)` | V1 helper reused, with markup rejection. |

The package is also compiled for the browser so the import preview shows the same messages before upload.

### 8.4 Dates, time zone and calendars

- Calendar dates → MySQL `DATE`, TypeScript `DateOnly` (branded `"YYYY-MM-DD"` string). No `Date` objects in calendar logic (removes V1's local-vs-UTC key mixing).
- Timestamps → `DATETIME(3)` in UTC.
- "Today" = `clock.today('Africa/Addis_Ababa')`.
- One builder: `buildSessionCalendar({ start, end, weekdays, holidays[], breakdowns[], exemptDays })` → `[{ date, kind: 'session' | 'holiday' | 'breakdown' | 'exempt' | 'non_session' }]`, used by attendance, dropout, activities and reports.

### 8.5 Identifiers

- Internal IDs: `BIGINT UNSIGNED AUTO_INCREMENT`; **V1 IDs preserved** for migrated rows (new rows continue above the V1 maximum).
- Trainee public ID `PBPS-<TP>-<6 digits>` (unchanged) from a **sequence table** `id_sequences(scope, next_value)` locked with `SELECT … FOR UPDATE`; bulk import reserves N numbers in one statement (no read-max-and-retry).
- GRM reference `GRM-<YYYY>-<6-digit yearly sequence>` (no collisions).
- Verification subject key for Kobo: `VS-<runId>-<seq>`.

### 8.6 Jobs and scheduling

- `jobs(id, queue, type, payload JSON, run_at, attempts, max_attempts, status queued|running|done|failed|dead, locked_by, locked_until, last_error, dedupe_key UNIQUE NULL, created_at, finished_at)`.
- Worker: `SELECT … WHERE status='queued' AND run_at <= NOW(3) ORDER BY run_at LIMIT 10 FOR UPDATE SKIP LOCKED`; 5-minute lease; exponential back-off; dead-letter after `max_attempts`.
- Scheduler in the worker holds a DB lease (`scheduler_leases`) so only one instance schedules.
- Debounce: `enqueue({ type: 'kpi.recompute', dedupeKey: 'kpi:p1:tp3', runAt: now + 60 s })`.
- Standard jobs: `attendance.recomputeClass`, `attendance.nightlyRollover`, `outcomes.refreshSystemDropouts`, `kpi.recompute`, `kpi.nightly`, `activities.materializeObligations`, `reminders.tick` (every 15 min), `notifications.sendEmailOutbox` (every minute), `duplicates.scanIncremental` (nightly), `datahealth.run` (nightly), `exports.generate`, `imports.validate`, `imports.commit`.
- Long jobs report progress (`progress_pct`, `progress_note`) that the UI polls.

### 8.7 Files

- `files(id, storage_key, original_name, mime_type, size_bytes, sha256, purpose, uploaded_by, uploaded_at, legacy_path)`; `purpose` ∈ activity_evidence, verification_evidence, import_source, export, report.
- Per-purpose rules (size, MIME sniffed from content).
- Downloads stream through the API after an access check; time-limited signed links for direct downloads.
- V1 `uploads/` is copied and checksummed during migration (document 02 §9.12).

### 8.8 Logging and metrics

- Structured JSON logs with `requestId`, `userId`, `projectId`, route, duration, status.
- SQL slower than 300 ms is logged (parameters redacted).
- `/health/live`, `/health/ready` (DB reachable, job lag < 5 min), `/metrics` (request durations, queue depth, outbox depth, KPI snapshot age).

---

# PART C — DOMAIN MODEL AND NAMING

## 9. The new delivery hierarchy (Training → Site → Class)

### 9.1 What the pilot taught us

| First assumption | Reality discovered | V1 workaround | V2 model |
|---|---|---|---|
| A TP starts all its training on one date | Each class starts on its own date | `training_batches` with own dates | **Class** owns start/end dates |
| One class format per TP; Mon–Fri for everyone | Classes meet on different weekdays (MWF, TTS, Mon–Sat, weekends) and shifts (morning/afternoon) | `session_weekdays` on batch | **Class** owns weekdays + shift |
| All three sites (Addis Ababa, Hossana, Dessie) start the same day | Sites have many classes, all different | "cohort" = location, with its own dates | **Site** = the training delivered in one city; dates are summaries of its classes |
| A trainee list is one class | A list contains many classes | batch resolved by `delivery_batch_code` | Every tracked trainee belongs to exactly one **Class** |

### 9.2 V2 hierarchy

```
Project (PBPS)
└── Training Provider (TP)                      e.g. Selam Children's Village (SCV)
    ├── Contract (target trainees, dates)       e.g. 1,040 trainees
    ├── Indicator targets (per indicator)       e.g. completion ≥ 92 %, attendance ≥ 85 %
    └── Training  (= course offered by the TP)  e.g. "IT Infrastructure and System Support" — Intermediate, 4 months
        └── Site  (= the training in one city)  e.g. "IT Infrastructure — Hossana"  (location HO)
            └── Class (= one group taught together)  e.g. "Hossana Class 2" — morning, Mon/Tue/Thu, 27 Apr → 27 Aug
                └── Trainees (active / reserve)
```

| V2 entity | V1 table | Meaning | Owns |
|---|---|---|---|
| **Training** | `trainings` (+ `training_programs` merged) | A course a TP delivers under the contract. | title, programme name, level (basic/intermediate/advanced), duration (3/4/6 months), planned window, default weekdays, allowed sites |
| **Site** | `training_cohorts` | The training delivered in one city/location. | location, optional site coordinator, derived first start / last end |
| **Class** | `training_batches` | A group of trainees taught together on one schedule. | code, display name, venue/campus, shift, start date, end date, weekdays, capacity, status, actual start |

Display names are generated so they are always descriptive: `"{Training title} · {Location} · {Class name}"`, e.g. *"Digital Marketing · Hossana · HS-DW-M (Digital Warriors, Morning)"*. The class name stays free text (TPs like their names) but **code is unique per site** and **shift**, **venue**, **weekdays** are structured fields, so lists never depend on naming discipline.

### 9.3 Rules

- A Training has ≥ 1 Site; a Site has ≥ 1 Class; a tracked trainee has exactly one Class (and therefore one Site and one Training).
- Class dates must lie inside the training's contracted window ± configurable tolerance (default 30 days); end − start must match the training duration ± 10 % (warning, not error, because breakdowns extend it).
- Weekdays: at least 1 day; stored as a 7-bit mask (`TINYINT`, Mon=1 … Sun=64) plus a readable array in the API.
- "Actual start" is recorded on the **Class** (V1 allowed training/cohort/batch levels); setting it shifts the class end date by the same number of days (V1 behaviour kept) and regenerates the class calendar, obligations and summaries.
- Class status is **derived** (not hand-maintained): `planned` (today < start), `ongoing`, `ended` (today > end), `cancelled` (explicit).
- The auto-generated `MAIN` cohort/batch of single-site V1 trainings migrates as a normal Site/Class named after the location (e.g. "Addis Ababa") and class "Main class".

### 9.4 Glossary used everywhere (UI, API, docs)

| Term | Definition |
|---|---|
| **Registered trainees** | Active + reserve trainees of a TP (withdrawn excluded). |
| **Contract target** | Number of trainees the TP is contracted to train (KPI denominator for completion, dropout, eligibility). |
| **Over-enrolment allowance** | Extra registrations allowed above target (project setting, 15 %). |
| **Session** | A scheduled class day (weekday of the class, inside its dates, not a holiday/breakdown/exempt day). |
| **Exempt start period** | First N calendar days of a class (default 14) not counted for attendance. |
| **System-final dropout** | Class ended and trainee attendance < 80 % (attendance threshold). |
| **At-risk** | Class ongoing and the trainee can no longer reach 80 %, or has already missed ≥ 15 % of sessions. |
| **Report** | A TP submission of one outcome type for one class (completion report for class X). |
| **Obligation** | A dated duty of a TP (submit inception report by 12 May; submit orientation evidence for class X by …). |
| **Run** | One verification sample draw for one indicator × TP × period (× stage). |

## 10. Active and reserve trainees — role, rules and V2 policy

### 10.1 What V1 actually does (code and data)

- Roles: `active`, `reserve`, `replaced_withdrawn`, `reserve_withdrawn`; the legacy value `backup` maps to `reserve`.
- **Both active and reserve are "tracked"**: both count as registered, both receive attendance capture, both count in the attendance rate, dropout projection, outcomes and the verification population.
- The **replacement workflow is switched off**: `POST /trainees/replacement` now returns *"Reserve replacement workflow is no longer available. Active and reserve trainees are tracked equally; update roster_role for reporting only."* No withdrawn rows exist in the data (2,993 active, 241 reserve).
- Registration cap: registered ≤ ⌊contract target × (1 + 15 %)⌋. Reserves are therefore the **over-enrolment buffer** that protects the TP against early dropouts.
- Dropout KPI buffer: dropouts up to (registered − target) do not count against the TP; beyond that they count, capped at target. V1 then assigns "counts toward KPI" to individual trainees by **sorting on trainee ID** — arbitrary, and meaningless for anyone reading a trainee list.
- Completion is capped at the contract target (a TP cannot exceed 100 % by over-enrolling).
- `attendance_eligible_from` (intended as the promotion date of a reserve) is stored but ignored.
- 85 reserve trainees lack a `trainee_enrollments` row (an artefact of the old replacement design).

### 10.2 Why this is reasonable — and what was unclear

The protocol's denominator is the contract target; TPs may register up to 15 % extra to absorb early attrition. Treating all registered trainees equally avoids an administrative replacement step and matches what happened in the field. What was unclear: the meaning of "reserve" for the TP (a label with no effect), and the per-trainee "counts toward KPI" flag.

### 10.3 V2 policy (default — matches current behaviour, clarified)

1. **Roster status** of a trainee (separate from outcomes): `active`, `reserve`, `withdrawn` (with `withdrawal_reason`: `never_started`, `replaced`, `transferred_out`, `registration_error`, `duplicate`, `other`), `transferred` (to another class of the same TP — keeps history).
2. **Tracked = active + reserve.** All monitoring treats them identically. The "reserve" label is kept because TPs and EDI use it for planning and it appears in historic reports.
3. **Cap** at registration: `registered ≤ floor(target × (1 + allowance))`; the import preview shows the remaining headroom.
4. **Dropout buffer is applied to counts, not to people:** `effective_dropouts = min(target, max(0, dropouts − max(0, registered − target)))`. The UI shows "buffer absorbs N dropouts" at provider level; individual trainees are never labelled "counts toward KPI".
5. **Completion cap:** `effective_completers = min(completers, target)` (unchanged).
6. **Policy switch for the future** (`projects.roster_policy`): `tracked_equally` (default, V1 behaviour) or `replacement_window` (re-enables formal replacement: within N days of class start a withdrawn active may be replaced by a reserve, the reserve becomes active and `attendance_eligible_from` is applied). The switch exists because the brief notes requirements may change again; both behaviours are implemented in one rule module (`registration/rosterPolicy.rules.ts`).
7. **Withdrawal before the roster freeze** (§18) is a simple status change with a reason; **after the freeze** it requires an approved change request.

### 10.4 Migration of roster data

- `roster_role` copied verbatim to `trainees.roster_status` (`active`/`reserve`; any `*_withdrawn` → `withdrawn` + reason `replaced`), original value kept in `roster_role_legacy`.
- `replaces_trainee_id` and `attendance_eligible_from` preserved.
- Missing enrollment rows are not needed in V2 (class membership lives on the trainee/enrollment row created for everyone).

---

# PART D — MODULE SPECIFICATIONS

> Format for each module: **Purpose · Entities · Rules · Workflows/state machines · API · Jobs/events · UI pages · Changes vs V1**.

## 11. Identity & sessions (`modules/identity`)

**Purpose.** Prove who the user is; manage sessions, passwords, 2FA, invitations.

**Entities.** `users` (id, name, email unique, password_hash, status `active|disabled|invited`, must_change_password, password_changed_at, failed_login_count, locked_until, totp_secret_enc, two_factor_method `none|email|totp`, access_version, last_login_at), `user_sessions` (id, user_id, refresh_token_hash, created_at, last_used_at, expires_at, revoked_at, ip, user_agent), `user_invites` (token_hash, user_id, expires_at, used_at), `password_resets` (token_hash, user_id, expires_at, used_at), `email_otp_challenges`.

**Rules.**
- Password ≥ 10 chars, not in a 10k common-password list, not equal to email; bcrypt cost 12 (V1 hashes migrate unchanged).
- Lockout: 5 failures in 15 min → locked 15 min (V1 rule kept); audit event on lockout.
- Access cookie 15 min; refresh cookie 7 days sliding, rotated on each use; reuse of an old refresh token revokes the whole session family (theft detection).
- 2FA: project setting "require 2FA for roles" (default: admin, me); TOTP preferred, email OTP fallback.
- **Invitations instead of temporary passwords:** new users (including TP staff) receive a one-time link (48 h) to set their own password. No password ever travels by email.
- A user with no active membership cannot sign in (replaces V1's 4-query `canUserAuthenticate`).

**API.** `POST /auth/login`, `POST /auth/2fa/verify`, `POST /auth/2fa/resend`, `POST /auth/refresh`, `POST /auth/logout`, `GET /auth/me`, `POST /auth/password/change`, `POST /auth/password/forgot`, `POST /auth/password/reset`, `POST /auth/invites/accept`, `GET /auth/sessions`, `DELETE /auth/sessions/:id`, `POST /auth/2fa/totp/setup`, `POST /auth/2fa/totp/confirm`.

**Changes vs V1.** Cookies instead of localStorage JWT; invite links; TOTP; session list and revoke; one-query login check.

## 12. Access control (`modules/access`)

### 12.1 Model

```
users ─┬─< memberships >── projects
       │      │ role_id → roles ─< role_permissions >─ permission keys (code constants)
       │      │ provider_id (NULL for project-wide roles; required for TP roles)
       │      └─< membership_scopes (site_id | class_id)   — optional narrowing inside a provider
```

- **One table** replaces V1's three TP linkages (`training_providers.user_id`, `project_users.tp`, `tp_staff_memberships`).
- A membership with `provider_id` is **provider-bound**: every query is filtered to that provider; scopes narrow further to sites/classes.
- Roles are data (editable in UI) but **system roles cannot be deleted**; permission keys are **code constants** (the catalogue is generated from code and synced at boot; unknown keys cannot be granted).

### 12.2 System roles

| Role | Bound to provider? | Purpose |
|---|---|---|
| `system_admin` | no | Platform administration (users, settings, master data, purge drafts). |
| `me_lead` | no | M&E management: structure review, approvals, indicators, targets, reports. |
| `me_officer` | no | Day-to-day monitoring, reviews of activities and outcomes, no configuration. |
| `verification_supervisor` | no | ICOS: plan and draw samples, approve verification records, finalise runs. |
| `verification_enumerator` | no | ICOS: record call attempts and responses for assigned subjects only. |
| `data_quality_officer` | no | ICOS: back-checks, audit of verification records. |
| `funder_viewer` | no | World Bank / EDI read-only (dashboards, indicators, reports, aggregate verification). |
| `tp_admin` | **yes** | TP organisation admin: everything for own provider, manages TP staff. |
| `tp_site_lead` | yes (+ scopes) | Registration, attendance, outcomes, activities, feedback for scoped sites/classes. |
| `tp_attendance_clerk` | yes (+ scopes) | Attendance capture only for scoped classes. |
| `tp_outcomes_officer` | yes (+ scopes) | Outcome reports for scoped classes. |
| `tp_viewer` | yes (+ scopes) | Read-only for own provider. |

V1 mapping: `admin` → `system_admin` (+ `me_lead` permissions), `me` → `me_lead`, `world_bank`/`edi` → `funder_viewer` (role label kept: "World Bank", "EDI" as two roles with the same permission set), `tp` owner / `tp_org_admin` → `tp_admin`, `tp_site_lead`/`tp_attendance_clerk`/`tp_outcomes_officer`/`tp_readonly` → same-named V2 roles (`tp_readonly` → `tp_viewer`). Questionable V1 grants (e.g. `submit:outcomes` for World Bank) are **not** carried over — listed in Part R for confirmation.

### 12.3 Permission catalogue (keys)

```
project.view            project.manage          settings.manage         masterdata.manage
user.view               user.manage             role.manage             audit.view
audit.export            audit.verify
provider.view           provider.manage         provider.contract.manage provider.staff.manage
target.view             target.manage
training.view           training.manage         class.schedule.manage   breakdown.request
breakdown.approve       holiday.manage
trainee.view            trainee.view_pii        trainee.create          trainee.import
trainee.update          trainee.withdraw        trainee.delete_draft
roster.freeze           roster.change.request   roster.change.approve
duplicate.review
attendance.view         attendance.submit       attendance.correct.request attendance.correct.approve
outcome.view            outcome.submit          outcome.review          outcome.resubmit.approve
indicator.view          indicator.manage        kpi.recompute
activity.view           activity.submit         activity.review         activity.configure
verification.view_aggregate  verification.view_subjects  verification.plan  verification.draw
verification.record     verification.approve    verification.finalize
grievance.view          grievance.respond       grievance.resolve       grievance.manage
notification.manage     report.view             report.export           datahealth.view
```

### 12.4 Permission matrix (default grants)

Legend: ● full · ◐ own provider / scoped · ○ read-only · – none

| Permission | sys_admin | me_lead | me_officer | ver_sup | ver_enum | dq_officer | funder | tp_admin | tp_site_lead | tp_att_clerk | tp_out_officer | tp_viewer |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| project.view | ● | ● | ● | ● | ● | ● | ● | ◐ | ◐ | ◐ | ◐ | ◐ |
| project.manage / settings.manage | ● | – | – | – | – | – | – | – | – | – | – | – |
| masterdata.manage (locations, durations, regions) | ● | ● | – | – | – | – | – | – | – | – | – | – |
| user.manage / role.manage | ● | – | – | – | – | – | – | – | – | – | – | – |
| provider.view | ● | ● | ● | ● | – | ● | ● | ◐ | ◐ | ◐ | ◐ | ◐ |
| provider.manage / contract.manage | ● | ● | – | – | – | – | – | – | – | – | – | – |
| provider.staff.manage | ● | ● | – | – | – | – | – | ◐ | – | – | – | – |
| target.view | ● | ● | ● | ● | – | ● | ● | ◐ | ◐ | – | ◐ | ◐ |
| target.manage | ● | ● | – | – | – | – | – | – | – | – | – | – |
| training.view | ● | ● | ● | ● | – | ● | ● | ◐ | ◐ | ◐ | ◐ | ◐ |
| training.manage / class.schedule.manage | ● | ● | – | – | – | – | – | ◐ | ◐ | – | – | – |
| breakdown.request | ● | – | – | – | – | – | – | ◐ | ◐ | – | – | – |
| breakdown.approve / holiday.manage | ● | ● | – | – | – | – | – | – | – | – | – | – |
| trainee.view | ● | ● | ● | ● | ○ (assigned) | ● | ○ (aggregate only) | ◐ | ◐ | ◐ | ◐ | ◐ |
| trainee.view_pii (phone, address) | ● | ● | ● | ● | ○ (assigned) | ● | – | ◐ | ◐ | ◐ | ◐ | – |
| trainee.create / import / update | ● | – | – | – | – | – | – | ◐ | ◐ | – | – | – |
| trainee.withdraw (before freeze) | ● | ● | – | – | – | – | – | ◐ | ◐ | – | – | – |
| roster.freeze | ● | ● | – | – | – | – | – | – | – | – | – | – |
| roster.change.request | ● | – | – | – | – | – | – | ◐ | ◐ | – | – | – |
| roster.change.approve | ● | ● | – | – | – | – | – | – | – | – | – | – |
| duplicate.review | ● | ● | ● | – | – | ● | – | ○ (own, explain) | – | – | – | – |
| attendance.view | ● | ● | ● | ● | – | ● | ○ | ◐ | ◐ | ◐ | ◐ | ◐ |
| attendance.submit | ● | – | – | – | – | – | – | ◐ | ◐ | ◐ | – | – |
| attendance.correct.request | ● | – | – | – | – | – | – | ◐ | ◐ | ◐ | – | – |
| attendance.correct.approve | ● | ● | ● | – | – | – | – | – | – | – | – | – |
| outcome.view | ● | ● | ● | ● | – | ● | ○ | ◐ | ◐ | – | ◐ | ◐ |
| outcome.submit | ● | – | – | – | – | – | – | ◐ | ◐ | – | ◐ | – |
| outcome.review / resubmit.approve | ● | ● | ● | – | – | – | – | – | – | – | – | – |
| indicator.view | ● | ● | ● | ● | – | ● | ● | ◐ | ◐ | – | ◐ | ◐ |
| indicator.manage | ● | ● | – | – | – | – | – | – | – | – | – | – |
| kpi.recompute | ● | ● | ● | – | – | – | – | – | – | – | – | – |
| activity.view | ● | ● | ● | ● | – | ● | ● | ◐ | ◐ | – | – | ◐ |
| activity.submit | ● | – | – | – | – | – | – | ◐ | ◐ | – | – | – |
| activity.review | ● | ● | ● | – | – | – | – | – | – | – | – | – |
| activity.configure | ● | ● | – | – | – | – | – | – | – | – | – | – |
| verification.view_aggregate | ● | ● | ● | ● | – | ● | ● | ◐ (finalised only) | ◐ (finalised) | – | – | ◐ (finalised) |
| verification.view_subjects | ● | ● | – | ● | ○ (assigned) | ● | – | – | – | – | – | – |
| verification.plan / draw / approve / finalize | ● | ○ | – | ● | – | – | – | – | – | – | – | – |
| verification.record | ● | – | – | ● | ● (assigned) | ● (back-check) | – | – | – | – | – | – |
| grievance.view | ● | ● | ● | – | – | – | ● | ◐ | ◐ | – | – | ◐ |
| grievance.respond / resolve | ● | – | – | – | – | – | – | ◐ | ◐ | – | – | – |
| grievance.manage (reassign, escalate, close) | ● | ● | ● | – | – | – | – | – | – | – | – | – |
| report.view / export | ● | ● | ● | ● | – | ● | ● | ◐ | ◐ | – | ◐ | ◐ |
| audit.view | ● | ● | – | – | – | ● | ○ | – | – | – | – | – |
| audit.verify / export | ● | – | – | – | – | – | ○ verify | – | – | – | – | – |
| datahealth.view | ● | ● | ● | – | – | ● | – | ◐ (own findings) | ◐ | – | – | – |

**Key changes:** TPs never see sampled subjects or open runs (only finalised aggregate results for their own provider); enumerators only see subjects assigned to them; funders see aggregates without personal data; World Bank cannot submit outcomes.

### 12.5 Enforcement

1. **Route guard:** `requirePermission('outcome.submit')` — checks the cached access context for the route's project (every project route is `/projects/:projectId/...`; global routes require a global role).
2. **Resource policy:** `outcomesPolicy.canSubmit(ctx, report)` — checks provider binding and scopes against the resource's provider/site/class.
3. **Query scoping:** repositories receive a `ScopeFilter` built from the context (`{ providerId?: bigint; siteIds?: bigint[]; classIds?: bigint[] }`) and must apply it — enforced by a lint rule requiring the parameter on list methods, and by integration tests ("TP A cannot list TP B's trainees", for every list endpoint).
4. **Field-level masking:** serializers omit PII fields when the context lacks `trainee.view_pii`.

### 12.6 API

`GET /projects/:p/access/me` (permissions, provider, scopes — used by the UI), `GET/POST/PUT/DELETE /projects/:p/memberships`, `GET /roles`, `POST /roles`, `PUT /roles/:id/permissions`, `GET /permissions` (catalogue with descriptions), `GET /projects/:p/access/matrix` (exportable matrix).

## 13. Projects & settings (`modules/projects`)

**Entities.** `projects` (code, title, donor, sector, description, start/end dates, over_enrolment_pct, roster_policy, timezone, attendance_threshold_pct default 80, exempt_days_from_class_start default 14, replacement_window_days, grievance_sla_days default 7, settings_version), `project_settings` (typed key/value for the rest), master data: `locations` (code, name, region_code, active), `regions` (canonical list + aliases), `training_levels` (basic, intermediate, advanced → default duration), `durations` (3, 4, 6 months), `holidays` (project_id, date, label, type national/religious/local, applies_to_location NULL = all).

**Rules.** Holidays may be added in the past only by `holiday.manage` with a reason; adding one triggers recomputation of affected class calendars and summaries (and flags any attendance already captured on that date — the V1 "holiday audit" becomes an automatic notice, the marks are kept but excluded).

**Pages.** Project settings (general, registration, attendance policy, grievance SLA, security), Master data (locations, regions & aliases, levels & durations, holidays calendar).

## 14. Training-provider onboarding, contracts and targets (`modules/providers`)

### 14.1 Entities

- `providers` (code unique per project, name, legal_name, status `onboarding|active|suspended|closed`, contact_person, contact_phone, **notification_email** (where system emails for this TP go), **reply_to_email** (shown to grievance submitters), requires_external_beneficiary_id, external_id_label (e.g. "Qiyas ID"), registration_open_from, registration_open_until, registration_closed_at/by/note, onboarding_completed_at).
- `provider_contracts` (provider_id, contract_number, signed_date, start_date, end_date, target_trainees, levels JSON, sites JSON, notes, document_file_id, status `draft|active|amended|closed`) — **versioned** (amendments create a new row; the active one is used for KPIs with effective dating).
- `indicator_targets` — see §21.4 (lives in the indicators module, edited from the provider page).

### 14.2 Onboarding wizard (new) — M&E/admin side

1. **Provider profile** (code, names, contacts, notification and reply-to emails, external ID requirement).
2. **Contract** (number, dates, target, levels, sites, upload signed contract → this also satisfies the "contract signed" activity obligation).
3. **Targets** (per indicator; defaults copied from the project defaults, editable).
4. **Organisation admin** (invite by email → `tp_admin` membership).
5. **Trainings** (titles, level, duration, planned window, sites) — may also be done by the TP admin.
6. **Registration window** (open from / until).
7. **Review & activate** — a checklist shows anything missing (no target, no contract file, no trainings, no admin, no sites…). Activation generates provider-level activity obligations (§22).

### 14.3 TP side first-login checklist

Dashboard card "Get started": set up classes for each site (dates, weekdays, shift, venue) → invite staff (scoped) → download registration template → import trainees → confirm roster before the freeze date. Each item shows done/pending with deep links.

### 14.4 API

`/projects/:p/providers` (list/create), `/providers/:id` (get/update/status), `/providers/:id/contracts` (list/create/amend), `/providers/:id/onboarding` (checklist state), `/providers/:id/staff` (invite/update/scopes/deactivate), `/providers/:id/registration-window` (open/close/extend with note).

### 14.5 Changes vs V1

Contract becomes versioned and document-backed; notification/reply-to emails replace TP SMTP; onboarding checklist; one membership table for staff; registration window has explicit dates (V1 had only "closed at").

## 15. Delivery structure (`modules/delivery`)

### 15.1 Entities

- `trainings` (id, project_id, provider_id, title, programme_name, level, duration_months, planned_start, planned_end, default_weekdays_mask, description, status `draft|active|closed`, legacy_training_program_id).
- `training_sites` (id, training_id, provider_id, location_id, display_name, coordinator_name, status, legacy_cohort_code, legacy_cohort_name).
- `training_classes` (id, site_id, training_id, provider_id, code, name, shift `morning|afternoon|evening|full_day|weekend|other`, venue, weekdays_mask, planned_start, planned_end, actual_start, effective_start (generated = COALESCE(actual_start, planned_start)), effective_end, capacity, status_override `cancelled` NULL, sort_order, calendar_version).
- `class_calendar_days` (class_id, date, kind `session|holiday|breakdown|exempt|non_session`, session_no (1..n for sessions), PRIMARY KEY (class_id, date)) — **materialised schedule**, rebuilt by `delivery.rebuildClassCalendar(classId)` whenever dates, weekdays, holidays or breakdowns change. ≈ 180 rows per class; 3,000 classes → ~540k small rows.
- `class_counters` (class_id PK, sessions_total, sessions_to_date, last_session_date, next_session_date, as_of_date) — refreshed nightly and on calendar rebuild.
- `training_breakdowns` (id, training_id, site_id NULL, class_id NULL, start_date, end_date, reason, status `requested|approved|rejected|cancelled`, requested_by/at, decided_by/at, decision_note).

### 15.2 Rules

- Weekdays mask must be non-empty; class `planned_end ≥ planned_start`.
- Changing dates/weekdays of a class that already has attendance is allowed only for future dates; past session days with marks cannot disappear (the rebuild keeps them as `session` and raises a data-health notice if the new schedule would exclude them).
- Breakdown approval extends the class end by the number of breakdown session days (V1 extended activity windows; V2 applies the same effect consistently to attendance, obligations and outcome due dates).
- Structure changes are blocked for a provider whose registration window is closed **unless** the user has `class.schedule.manage` with M&E approval (V1 blocked them entirely, forcing admins to reopen registration).

### 15.3 Pages

Trainings list (by provider, level, status; counts), Training detail (sites, classes, trainees, progress), **Class detail** (schedule calendar, roster, attendance status, outcome reports, obligations), Class create/edit (with calendar preview showing every session day, holidays and exempt days before saving), Breakdown requests (TP request, M&E approve).

## 16. Registration (`modules/registration`)

### 16.1 Field schema registry — single source of truth

`registration/fieldSchema.ts` defines every field once:

```ts
type FieldDef = {
  key: string;                    // API/CSV key, e.g. "phonePrimary" / "phone_primary"
  label: string;                  // "Phone number (primary)"
  section: 'program' | 'personal' | 'education' | 'employment' | 'inclusion' | 'consent';
  type: 'text' | 'name' | 'enum' | 'multi_enum' | 'boolean' | 'int' | 'date_dmy' | 'date_et' | 'phone' | 'email';
  required: boolean | ((row) => boolean);   // conditional requirements
  enum?: EnumDef;                 // canonical values + aliases
  min?: number; max?: number;
  maxLength?: number;
  dependsOn?: { field: string; equals: unknown };
  csvAliases: string[];           // accepted header spellings
  help: string;                   // shown in template notes and form
  pii: boolean;                   // masks for roles without trainee.view_pii
  storage: { column: string; rawColumn?: string };
};
```

This drives: the **web form**, the **CSV/XLSX template** (headers, an instructions sheet, Excel data-validation drop-downs in XLSX), **server validation**, the **import preview** and the **trainee profile view**.

### 16.2 Field list and rules (aligned with the official "Trainee Registration Form")

| # | Field | Type / allowed values | Required | Validation & normalisation |
|---|---|---|---|---|
| 1 | Trainee unique ID | system generated `PBPS-<TP>-000000` | auto | never supplied by TP (ignored if present) |
| 2 | Training provider | from session (TP users) / chosen (admin) | ✓ | must exist and be active |
| 3 | Training | from import target selection | ✓ | belongs to provider |
| 4 | Training type | Basic · Intermediate · Advanced | ✓ (derived) | must equal the training's level (taken from training; CSV column optional, must match if present) |
| 5 | Training duration | 3 · 4 · 6 months | ✓ (derived) | must equal training duration |
| 6 | Training location | Addis Ababa · Dessie · Hossana (project locations) | ✓ (derived) | must equal the class's site location |
| 7 | Class | class code within the selected site | ✓ | must exist under the site; if the site has one class it is implied |
| 8 | External beneficiary ID | text ≤ 64 | if provider requires | unique per provider |
| 9 | Date of form completion | DD/MM/YYYY (Gregorian, as on the form) or ISO | ✓ | not in the future; not before contract start − 90 days |
| 10 | First name | name | ✓ | `parseName` |
| 11 | Father's name | name | ✓ | `parseName` |
| 12 | Grandfather's name | name | ✓ | `parseName` (V1: optional — make required; existing NULLs allowed via migration flag) |
| 13 | Sex | Male · Female | ✓ | enum (M/F/ወንድ/ሴት aliases) |
| 14 | Age (years) | integer 15–64 | ✓ | eligibility separately checks 18–29 (an out-of-range age is accepted with an eligibility warning, not rejected — TPs sometimes enrol ineligible people and the eligibility KPI must show it) |
| 15 | Date of birth (Ethiopian calendar) | DD/MM/YYYY ET | ✓ | `parseEthiopianDate`; converted Gregorian stored; `checkAgeConsistency` warning if off by > 1 year |
| 16 | Phone (primary) | Ethiopian mobile | ✓ | `parsePhoneET`; stored E.164; unique per project (hard) |
| 17 | Phone (alternative) | Ethiopian mobile | – | `parsePhoneET`; must differ from primary |
| 18 | Email | email | – | `parseEmail` |
| 19 | Kebele | text ≤ 50 | – | trimmed |
| 20 | Woreda | text ≤ 80 | ✓ | trimmed (free text; a woreda list can be added later) |
| 21 | Sub-city | text ≤ 80 | when region is a city administration | trimmed |
| 22 | Region | enum of regions/city administrations (Addis Ababa, Afar, Amhara, Benishangul-Gumuz, Central Ethiopia, Dire Dawa, Gambella, Harari, Oromia, Sidama, Somali, South Ethiopia, South West Ethiopia Peoples, Tigray) + aliases | ✓ | `parseEnum` with alias table (A.A, Addis Abeba, Oromiya, Central Ethiopia Regional State …) |
| 23 | Emergency contact name | name | ✓ | |
| 24 | Emergency contact phone | Ethiopian mobile | ✓ | must differ from trainee primary phone (warning) |
| 25 | Highest education | No formal education · Primary (Grades 1–8) · Secondary (Grades 9–12) · TVET Certificate Level I–IV · Diploma · Bachelor's Degree · Above Bachelor's · Short-term Training | ✓ | enum with aliases; **"High school dropout"** kept as an additional canonical value because V1 data contains it (14 rows) and the protocol names it |
| 26 | Previously participated in skills training | Yes/No | ✓ | boolean |
| 27 | Prior training type | text ≤ 120 | if 26 = Yes | |
| 28 | Prior training completed | Yes/No | if 26 = Yes | |
| 29 | Year completed | integer 1990–current year (Gregorian) | if 28 = Yes | |
| 30 | Employment status (last month) | Not currently working · Working occasionally · Working fewer hours than desired · Working full-time for an employer · Self-employed / own business | ✓ | enum |
| 31 | Income sufficient | Yes/No | if 30 ≠ Not currently working | |
| 32 | Skill usage in current job | Fully · Partially · Not at all | if 30 ≠ Not currently working | |
| 33 | Post-training employment plan | Wage employment · Self-employment · Other | ✓ | |
| 34 | Plan — other (specify) | text ≤ 200 | if 33 = Other | |
| 35 | Inclusion categories | multi: Person with disability · IDP · Returnee · Low-income household · None of the above · Prefer not to say | ✓ (≥ 1) | "None"/"Prefer not to say" exclusive with others |
| 36 | Disability type | Hearing · Visual · Paralysis · Not a person with disability · Prefer not to say · Other | if 35 includes PWD | aliases: None/No/nothing → "Not a person with disability" |
| 37 | Disability — other | text ≤ 120 | if 36 = Other | |
| 38–41 | Consents: accuracy, follow-up surveys, employment verification contact, image use | Yes/No each | ✓ | accuracy and employment-verification consent must be **Yes** to register (they are preconditions for M&E and verification) — confirm in Part R |
| 42 | Roster status | Active · Reserve | ✓ | cap check |

Derived and stored: `age_at_registration`, `dob_gregorian`, `eligibility_status` (`eligible` / `not_eligible` + reasons array), name keys for duplicate matching (§17).

### 16.3 Eligibility rule (one implementation)

`registration/eligibility.rules.ts`:
- age 18–29 at form date (uses DOB when valid, else stated age);
- education ∈ {Secondary (9–12) *completed*, High school dropout, TVET I–IV, Diploma, Bachelor's, Above Bachelor's} — see Part R item on "Secondary 9–12 vs Grade 12 completed";
- employment ∈ {Not currently working, Working occasionally, Working fewer hours than desired}.

Returns `{ eligible, reasons: ['AGE_OUT_OF_RANGE' | 'EDUCATION_NOT_ELIGIBLE' | 'EMPLOYMENT_NOT_ELIGIBLE'] }`, stored on the trainee and recomputed when fields change. V1's three diverging implementations are replaced by this one.

### 16.4 Single-trainee form

- Sections exactly as the official form; conditional fields appear/disappear; inline validation using the same shared validators; live duplicate hint ("A trainee with a very similar name exists: PBPS-SCV-000312 — Selam class 3") before save.
- Save as draft is not offered (keeps data simple) — the form is short enough.

### 16.5 Bulk import — pipeline

```
[Download template (CSV or XLSX with drop-downs)]
        ↓
Upload file (CSV / XLSX, ≤ 5,000 rows) + choose target (provider → training → site; class per row or fixed)
        ↓  server
import_batches (status=uploaded) ← file stored (files table, sha256)
        ↓  job imports.validate (progress %)
import_rows: one row per line {raw JSON, parsed JSON, errors[], warnings[], duplicate_matches[]}
        ↓
Preview UI: summary (valid / invalid / warnings / duplicates), filter by issue, **fix cells inline** (re-validated instantly), mark duplicates "not a duplicate (reason)" or "skip row"
        ↓
Commit (only when 0 errors and all duplicate matches resolved) → job imports.commit:
   reserve N trainee IDs from id_sequences in one statement → bulk INSERT trainees in chunks of 500 → INSERT trainee_status rows → emit trainee.registered (bulk) → audit event with file checksum
        ↓
Result: created N, report downloadable (row → new trainee ID)
```

Properties: the whole commit is **one transaction** (all-or-nothing, as in V1); no per-row queries (provider, trainings, classes, existing phones and name keys are pre-loaded into maps); 2,000 rows validate in ≈ 2–5 s and commit in ≈ 3 s.

**Header handling:** exact canonical headers or listed aliases (case/space-insensitive); unknown columns are reported as warnings and kept in `raw` (never silently dropped); missing required columns stop validation with a precise message.

**Excel pitfalls handled:** scientific-notation phones rejected with guidance ("format the column as Text"); leading-zero loss recovered (`911223344` → `0911223344`); Excel date serials converted only in date columns; `="0911…"` formula-style text unwrapped; BOM and `;` delimiters detected.

### 16.6 Registration windows and gates

- A provider can register when `now` is within its registration window and the window is not closed (project-level master switch also exists). Late registration = M&E opens a **time-boxed late window** for one provider with a reason (V1's "open registration for a third TP" use case) — other providers are unaffected.
- Trainee edits of non-identity fields (phone, address, emergency contact) are always allowed to the TP; identity/eligibility fields (names, sex, age, DOB, education, employment) after the roster freeze need a change request (§18).

### 16.7 API

`GET /projects/:p/registration/schema` (field defs for UI), `GET …/registration/template?format=csv|xlsx&trainingId=`, `POST …/imports` (multipart), `GET …/imports/:id` (status, summary, progress), `GET …/imports/:id/rows?issue=error|warning|duplicate&page=`, `PATCH …/imports/:id/rows/:rowId` (fix cells), `POST …/imports/:id/rows/:rowId/duplicate-decision`, `POST …/imports/:id/commit`, `DELETE …/imports/:id` (discard), `GET/POST …/trainees`, `GET/PATCH …/trainees/:id`, `POST …/trainees/:id/withdraw`, `POST …/trainees/:id/transfer`, `GET …/trainees/export?format=csv|xlsx`.

### 16.8 Trainee list performance

Server pagination with indexed filters (provider, training, site, class, roster status, eligibility, sex, search). Search uses `name_search_key` (normalised "first father grandfather"), `phone_e164`, `trainee_code`, `external_beneficiary_id` — prefix/equality lookups on indexes, not `%LIKE%` scans. Summary counts come from `trainee_status`/counters, not from loading rows.

## 17. Duplicate prevention and detection (`modules/duplicates`)

### 17.1 V1 assessment

Good: Jaro-Winkler + Levenshtein name-part matching tuned on real Ethiopian names (Ribka/Rebka, Alene/Alana); dedupe keys; review statuses. Weak: name-only (DOB, age, sex ignored), whole project loaded in memory (limit 20k), scans run manually and after the fact, phone duplicates hard-blocked only on primary phone, separate "roster duplicate check" tool for external lists, no cross-check at form entry.

### 17.2 V2 design — prevent first, detect second

**Stored matching keys** (computed on insert/update, indexed):

| Column | Example | Use |
|---|---|---|
| `phone_e164` (UNIQUE per project) | `+251911223344` | hard block |
| `phone_alt_e164` | | soft signal |
| `name_norm_first`, `name_norm_father`, `name_norm_grandfather` | `ribka`, `alemu`, `tesfaye` | similarity |
| `name_key_fn_fa` | `ribka|alemu` | exact block |
| `name_phon_fn`, `name_phon_fa` | phonetic code tuned for Ethiopian transliteration (collapse vowels e/a/i variants, `ph→f`, `kh→k`, `ts/tz→s`, double consonants, trailing vowels) | blocking key |
| `dob_gregorian`, `birth_year` | | signal |
| `external_beneficiary_id` | | exact (per provider) |

**Candidate generation (indexed, no full scan):** for a new or changed trainee, select existing trainees (all providers in the project) where any of: same `phone_e164`/alt phone; same `name_key_fn_fa`; same (`name_phon_fn`, `name_phon_fa`); same `external_beneficiary_id`. Typically < 20 candidates even at 120k trainees.

**Scoring (0–100):**

```
names   = weighted mean of JW similarity (first 0.4, father 0.4, grandfather 0.2; grandfather only when both present)
signals = +10 same primary phone (any field) · +6 same DOB · +3 |age diff| ≤ 1 · −15 different sex · +5 same emergency phone · −10 DOB differ by > 3 years
score   = clamp(round(names × 100) + signals, 0, 100)
risk    = high ≥ 92 · medium 85–91 · low (not stored) < 85
```

(V1 threshold 85 kept; weights to be tuned on the 19 reviewed V1 candidates + a labelled sample — Part R.)

**When it runs:**
1. **Form entry** — live check on blur of the name/phone fields (API `POST /duplicates/check`).
2. **Import preview** — every row checked against existing trainees and against other rows in the file; high-risk rows must be resolved (skip / "different person" with reason) before commit.
3. **Nightly incremental scan** — only trainees created/updated since the last scan, against everyone (indexed) → new candidates to the review queue.
4. **On demand** — full re-scan job for M&E (progress bar), uses the same blocking so it scales.

**Review workflow:** `pending → confirmed_duplicate | not_duplicate | merged`. Confirming a duplicate opens a **withdrawal** of the later record (reason `duplicate`, linked to the kept record) — never a hard delete. The TP of each record is notified and may comment.

**External roster check** (V1 "roster duplicate check" tool) becomes a mode of the import preview: "Check only — do not import", producing the same report (internal clusters + matches across all providers), downloadable as XLSX.

## 18. Roster lifecycle: freeze, change requests, withdrawals (replaces "Registration integrity")

### 18.1 Why

In the pilot, opening registration late for one provider allowed already-registered providers to silently delete trainees; the "Registration integrity" page later compared initial lists with current data to force re-registration. V2 makes unauthorised removal impossible by design.

### 18.2 Rules

- **No hard delete** of trainees by TPs, ever. Before the roster freeze a TP may **withdraw** a trainee (reason required; record stays, excluded from tracked counts). Admin may hard-delete only records created by mistake **before any attendance/outcome exists**, with a reason, audited.
- **Roster freeze** per class: automatically at class start + exempt period (default 14 days — matching the protocol's "eligibility measured after 2 weeks of training start"), or manually by M&E. At freeze, a **roster snapshot** (`roster_snapshots` + `roster_snapshot_members`) is stored: the list of tracked trainees with a hash.
- After freeze, the following need an approved **change request** (`roster_change_requests`): add trainee, withdraw, transfer between classes, change of identity or eligibility fields. M&E approves/rejects with a note; approved requests apply automatically.
- Every snapshot can be compared to the current roster (`GET /classes/:id/roster/diff?snapshot=`) — the integrity report is now a by-product, not a forensic tool.

### 18.3 State machine (change request)

`draft → submitted → approved → applied` · `submitted → rejected` · `submitted → withdrawn_by_requester`.

## 19. Attendance (`modules/attendance`)

### 19.1 Storage

- `attendance_sessions` (id, class_id, session_date, status `submitted|corrected|locked`, source `manual|csv|mobile|backfill|migration`, submitted_by, submitted_at, marks_count, present_count, absent_count, excused_count, legacy flag) — UNIQUE (class_id, session_date).
- `attendance_marks` (session_id, trainee_id, status TINYINT 1=present 2=absent 3=excused, reason_code NULL, PRIMARY KEY (session_id, trainee_id), INDEX (trainee_id, session_id)) — **≈ 16 bytes per row** instead of ≈ 100 bytes + 6 indexes in V1.
- `attendance_corrections` (id, session_id, trainee_id, from_status, to_status, reason, requested_by/at, status `requested|approved|rejected`, decided_by/at, note).
- Per-trainee counters in `trainee_status` (§20): `att_present`, `att_excused`, `att_absent`, `att_sessions_to_date`, `att_sessions_total`, `att_rate_to_date`, `att_rate_final_projected`, `att_max_reachable_rate`, `att_last_marked_date`, `att_missing_sessions`.

### 19.2 Rules (V1 kept, clarified)

- A session can be submitted only for a `session` day of the class calendar (not holiday, breakdown, exempt or non-session; not in the future).
- One submission per class per date (V1: 409). A second submission becomes a **correction request** for the changed marks.
- Every tracked trainee of the class must be marked (V1 allowed partial lists; V2 requires a status per trainee; absent is the default in the UI).
- **Excused** becomes selectable (with a reason: illness with note, official leave…) — counts as attended for the KPI exactly as V1's computation already did. Who may mark excused is a project setting (default: TP, with reason; M&E can audit).
- Late submission: allowed up to N days after the session (project setting, default 7); after that a correction request with justification is required. Missing sessions appear in the TP's "attendance to do" list and in reminders.
- Corrections: TP requests → M&E approves → mark changed, counters recomputed, audit.

### 19.3 Rates (protocol §9)

- `att_rate_to_date = (present + excused) / sessions_to_date_eligible × 100`, where eligible sessions are class `session` days ≤ today, after `attendance_eligible_from` if the replacement policy is on, else from class start (V1 default).
- `att_max_reachable_rate = (present + excused + remaining_sessions) / sessions_total × 100`.
- Provider rate = Σ attended ÷ Σ eligible over tracked trainees (pooled, as V1).
- **Capture coverage** = marks recorded ÷ marks expected (sessions to date × tracked trainees), per class and provider.

### 19.4 Computation (fast)

- On session submit: one transaction inserts the session + marks, then updates `trainee_status` counters for the ≈ 40 trainees of the class with a single `UPDATE … JOIN (SELECT trainee_id, SUM(...) …) ` statement; class counters updated; event emitted.
- Nightly (00:30 Addis Ababa): `attendance.nightlyRollover` advances `sessions_to_date` for classes that had a session yesterday and recomputes rates in one set-based statement per provider (≈ 120k rows, seconds).
- Calendar change (holiday/breakdown/actual start): rebuild that class's calendar and recompute its trainees.

### 19.5 CSV / XLSX import of attendance

Template per class: rows = trainees (ID, name), columns = session dates (only valid session dates of the selected period), cells P/A/E. Validated like registration imports (staging + preview); committed as sessions (one per date). Replaces V1's strict-header daily CSV; the daily CSV format is still accepted for compatibility.

### 19.6 UI

**Attendance home** (TP): "To do" list of missing sessions per class (oldest first) with one-click open; **Class sheet** (grid: trainees × dates, keyboard navigation, mark all present, colour-coded, unsaved-changes guard, submit per date); **History** with corrections; **Insights** (rates per class/site/provider, coverage, at-risk list); **Dropout monitoring** (§20.6).

### 19.7 Findings fixed

Excused unavailable → available; no corrections → workflow; partial lists → full roster required; holiday rows → excluded automatically with notice; timezone key mixing → `DateOnly`; row-by-row writes → one transaction.

## 20. Outcomes (`modules/outcomes`)

### 20.1 Concept

Two layers, clearly separated:

1. **Submissions (history)** — what the TP reported, when, in which file, line by line, **including every "No"**. Append-only. Superseded by later versions, never edited.
2. **Trainee status (current state)** — one row per trainee with typed columns that the rest of the system reads (KPIs, verification frames, dashboards, templates). Updated only by the outcomes module when a report is accepted (or by the system dropout rule).

This answers the brief: the "column per outcome" convenience the user proposed, *plus* a full history and auditability.

### 20.2 Report types (configuration in `outcomes/reportTypes.ts`)

| Report type | Scope | Roster in template | Allowed values | Required extra fields | Prerequisite (per trainee) | Gate (per class) | Status columns updated |
|---|---|---|---|---|---|---|---|
| `dropout` | class | all tracked | Yes / No | if Yes: dropout_date, dropout_reason (enum: voluntary withdrawal, dismissal, health, economic/financial, migration/relocation, found a job, low attendance, other + text) | – | class ended; attendance capture complete | `dropout_status`, `dropout_date`, `dropout_reason`, `dropout_source` |
| `completion` | class | all tracked **except** dropout = Yes | Yes / No | if Yes: completion_date; if No: non_completion_reason (enum: failed assessment, incomplete assignments, insufficient attendance, other) | dropout ≠ Yes | dropout report accepted for the class | `completion_status`, `completion_date`, `noncompletion_reason` |
| `certification` | class | completion = Yes | Yes / No | if Yes: certificate_date, certificate_number (optional) | completion = Yes | completion accepted | `certification_status`, `certification_date`, `certificate_number` |
| `job_linkage` | class | completion = Yes | Yes / No | if Yes: linkage_date, linkage_type (job fair, referral, internship, CV support, employer introduction, other), employer_name (opt.) | completion = Yes | completion accepted; within 60 days of class end (warning after) | `job_linkage_status`, `job_linkage_date`, `job_linkage_type` |
| `decent_job` (stage m1 = 30 d, m2 = 60 d) | class × stage | completion = Yes | Yes / No | if Yes: employment_type (wage / self), employer_name, job_title, start_date, monthly_income, contract_duration, criteria met (multi: contract ≥ X months or open-ended, skills relevance, income ≥ market, …) | completion = Yes | stage date reached (class end + offset) | `decent_job_m1_status`, `decent_job_m2_status`, `job_start_date`, `employment_type` |
| `locality_compliant` | class | decent_job (final stage) = Yes | Yes / No | workplace location, distance band | decent_job = Yes | decent job accepted | `locality_status` |
| `job_retention_3m` | class | decent_job (final stage) = Yes | Yes / No | still employed date, same employer Y/N, gap days | decent_job = Yes | job start + 90 days | `retention_3m_status`, `retention_check_date` |

Every report type: one row per listed trainee, value **must** be Yes or No (blank = validation error). A trainee not listed because of a prerequisite gets status `not_applicable` (dropouts for completion, non-completers for certification…). This is how **non-completers are recorded as "No"**.

### 20.3 Status columns (in `trainee_status`, 1 row per trainee)

`dropout_status` ENUM(`pending`,`no`,`yes`), `dropout_source` ENUM(`tp_reported`,`system_low_attendance`,`migration`), `dropout_date`, `dropout_reason`, `dropout_report_id`;
`system_dropout_final` BOOL, `system_dropout_risk` BOOL (from attendance);
`completion_status` ENUM(`pending`,`no`,`yes`,`not_applicable`), `completion_date`, `noncompletion_reason`, `completion_report_id`, `completion_source` (`tp_reported`,`migration_reported`,`migration_inferred`);
`certification_status`, `certification_date`, `certificate_number`, `certification_report_id`;
`job_linkage_status`, `job_linkage_date`, `job_linkage_type`;
`decent_job_m1_status`, `decent_job_m2_status`, `job_start_date`, `employment_type`;
`locality_status`; `retention_3m_status`, `retention_check_date`;
`eligibility_status`, `eligibility_reasons`;
attendance counters (§19.1);
`status_version`, `updated_at`.

Indexes: `(project_id, provider_id, completion_status)`, `(project_id, provider_id, dropout_status)`, `(class_id)`, and one per status used in KPI filters. KPI queries become single `GROUP BY provider_id` statements over ≤ 120k rows.

### 20.4 Submission workflow

`outcome_reports` (id, project, provider, training, site, class, report_type, stage_key, version, status, file_id, rows_total, yes_count, no_count, na_count, submitted_by/at, reviewed_by/at, review_note, supersedes_report_id, idempotency_key) and `outcome_report_lines` (report_id, trainee_id, value ENUM yes/no, date, reason, details JSON (type-specific fields), raw JSON).

State machine:

```
draft ──validate──▶ ready ──submit──▶ accepted ──(new version submitted & approved)──▶ superseded
  │                   │                  │
  └──discard          └──errors          └──M&E "return for correction" ──▶ returned ──▶ (TP resubmits new version)
```

- **Accepted immediately** when all gates pass (V1 behaviour: processed). M&E can **return** an accepted report (with reason) → the TP must resubmit; until then statuses stay as accepted (not lost).
- **Resubmission** (V1 request/approve/consume via audit rows) becomes: TP creates version n+1 with a "reason for change"; it requires M&E approval when (a) a verification run has already drawn from that scope, or (b) more than N days have passed since acceptance (setting). On approval, statuses are recomputed from the new version; the previous version becomes `superseded` (kept forever).
- Validation is the V1 rule set (kept and consolidated): ordering, per-trainee prerequisites, system-final dropouts must be Yes (attendance is the TP's own data — corrections go through attendance), dropout cannot follow completion, class ended, attendance coverage complete.
- **Atomic:** a report and all its lines are written in one transaction; statuses are updated in the same transaction; then events.
- Template download pre-fills the roster with current suggested values (system-final dropouts = Yes, locked; trainees ineligible for the report omitted with explanation sheet).
- Entry modes: **XLSX/CSV upload** (as V1) or **on-screen grid** (for small classes: toggle Yes/No per trainee, fill dates) — both produce the same report object.

### 20.5 System dropout rule (protocol §10, V1 code truth)

- `system_dropout_final` = class ended ∧ `att_sessions_total` > 0 ∧ final rate < attendance threshold (80) ∧ not transferred.
- `system_dropout_risk` = ¬final ∧ sessions_to_date > 0 ∧ (missed ≥ 15 % ∨ max reachable < 80 %).
- Effective dropout (KPI) = `dropout_status = yes` ∨ `system_dropout_final` (V1: TP-reported OR system-final).
- Recomputed for a class whenever its attendance summary changes (event-driven), and nightly.

### 20.6 Dropout monitoring page (kept, faster)

Lists per class/provider: at-risk, system-final, TP-reported, missing in TP report; reasons breakdown; buffer effect at provider level (§10.3). Reads `trainee_status` (indexed) — instant at 120k.

### 20.7 Changes vs V1

| V1 | V2 |
|---|---|
| `trainee_outcomes` rows (only Yes for completion) | lines with Yes and No + typed status columns |
| Dates as strings in JSON | typed `DATE` columns |
| One `outcome_report_batches` row per delivery batch per upload | one report per class per type per version |
| Writes not transactional | one transaction |
| Resubmission requests in audit log | versioned reports + approval |
| Stage key inside JSON `meta` | `stage_key` column, indexed |
| Completion gate per provider (all-or-nothing) | per trainee — see §21.5 and Part R |

## 21. Indicators (`modules/indicators`)

### 21.1 Indicator registry (protocol definitions inside the system)

`indicator_definitions` — one row per indicator per version, containing every protocol column:

| Column | Example (Indicator 11) |
|---|---|
| `code` | `completion_rate` |
| `protocol_no` | 11 |
| `name` | Percentage of registered trainees per TP who completed the training |
| `unit` | `%` |
| `level` | `trainee` (vs `provider` for TP-level indicators) |
| `purpose` | `monitoring_and_verification` |
| `operational_definition` | A trainee has completed if they (i) attended ≥ 80 % of sessions and (ii) fulfilled all training requirements … |
| `data_sources` | MIS attendance records; TP completion report; verification phone survey (sample) |
| `collection_method` | TP submits trainee-level completion report (Yes/No for all trainees) … |
| `frequency` | At training end, per class |
| `computation_text` | Numerator = trainees with completion = Yes AND attendance ≥ 80 %; Denominator = contract target; × 100 |
| `numerator_metric` | `trainees.completed_with_attendance_gate` |
| `denominator_metric` | `provider.contract_target` |
| `direction` | `higher_is_better` (dropout: `lower_is_better`) |
| `default_target` | 90 |
| `comparator` | `>=` |
| `disaggregations` | `["provider","level","location","sex","age_group","education","inclusion"]` |
| `verification_method` | `sampling` (plan reference) / `full_review` / `document_review` / `system` / `none` |
| `payment_linkage` | Tranche 3 — verified rate ≥ target |
| `version`, `effective_from`, `status` (`draft`/`active`/`retired`), `approved_by`, `approved_at`, `change_note` |

All **19 protocol indicators** are seeded (V1 has 11). Provider-level indicators (1, 2, 5, 6, 7, 8, 13, 17) use metrics over approved activity obligations, e.g. `provider.activity_approved:inception_report`.

Versioning: editing an active definition creates a new version (draft → approve). KPI snapshots record the definition version used. V1's `project_indicator_versions` (empty) is superseded.

### 21.2 Metric catalogue (code, not JSON specs)

`indicators/metrics/*.ts` — each metric is a function returning counts **per provider** (and per disaggregation key when asked), implemented as **one SQL statement** over read models:

| Metric key | Definition (SQL over) |
|---|---|
| `trainees.registered` | `trainees` tracked (active+reserve) |
| `trainees.eligible` | tracked ∧ `eligibility_status='eligible'` |
| `attendance.attended_sessions` / `attendance.eligible_sessions` | Σ counters in `trainee_status` |
| `trainees.dropout_effective` | tracked ∧ (dropout = yes ∨ system_final) |
| `trainees.dropout_effective_buffered` | above, with the over-enrolment buffer applied (count rule §10.3) |
| `trainees.completed` | completion = yes |
| `trainees.completed_with_attendance_gate` | completion = yes ∧ `att_rate_final ≥ threshold` (see Part R) |
| `trainees.completed_capped` | min(completed…, contract target) |
| `trainees.certified` | certification = yes |
| `trainees.job_linked` | job_linkage = yes |
| `trainees.decent_job_final` | decent job final stage = yes |
| `trainees.locality_compliant` | locality = yes |
| `trainees.retained_3m` | retention = yes |
| `provider.contract_target` | active contract target |
| `provider.activity_approved:<code>` | 1 if the provider's obligation(s) for the activity are approved, else 0 |
| `grievance.resolved_within_sla` / `grievance.total_due` | from case table (V1 definitions kept) |

A metric declares its **inputs** (tables/events) so the engine knows which snapshots become stale after which event.

### 21.3 KPI engine and snapshots

- `kpi_snapshots` (project_id, indicator_code, definition_version, provider_id NULL = project, dimension_key NULL / e.g. `sex=female`, as_of_date, numerator, denominator, value, target, target_source (`provider`/`default`), status (`met`/`not_met`/`no_data`/`not_applicable`), computed_at, inputs_hash) — PRIMARY KEY (project_id, indicator_code, provider_id, dimension_key, as_of_date).
- `kpi_snapshot_latest` view (or table) = latest per key.
- **Recompute triggers:** debounced 60 s after any input event for that provider; nightly full recompute (keeps one row per day → trend charts for free); manual "Recompute now" (M&E).
- **Verified values:** for sampling indicators, a parallel snapshot `layer='verified'` written when a verification run is finalised (§23).
- Pages (dashboard, indicator report, outcomes banner, verification list) read snapshots: **one indexed query, < 50 ms**.
- Each snapshot shows "computed at …" in the UI, with a refresh indicator if a recompute is pending.

### 21.4 Per-provider targets (new requirement)

`indicator_targets` (id, project_id, indicator_code, provider_id NULL (= project default), target_value DECIMAL, comparator, effective_from DATE, effective_to DATE NULL, set_by, set_at, note, approved_by NULL).

- Resolution: provider-specific row valid on the snapshot date → else project default row → else definition default.
- Editing never overwrites: a new row with a new `effective_from` closes the previous one (history kept; reports show which target applied).
- Provider page has a **Targets** tab; Indicator page shows a table "target per provider".
- V1 `threshold_value` values migrate as project defaults (completion 90, attendance 80, eligibility 100, certification 100, job linkage 80, decent job 80, locality 80, retention 90).

### 21.5 Formula decisions to confirm (see Part R)

1. **Completion attendance gate per trainee** (protocol: "attended ≥ 80 % AND fulfilled requirements") instead of V1's provider-level all-or-nothing gate (provider average attendance < 80 % → completion 0; any missing attendance slot → completion 0).
2. **Coverage gate**: V1 sets completion to 0 if any attendance slot is missing; V2 proposal: block **submission** of the completion report until the class's attendance is complete (already a gate), but do not zero an accepted KPI.
3. **Denominators**: contract target for completion, dropout, eligibility (V1, protocol-consistent "registered trainees per TP" interpreted as contracted); others: completion count (as V1).
4. **Eligibility education list** (Secondary 9–12 vs "Grade 12 completed").

### 21.6 Pages

Indicator registry (list with protocol no., level, purpose, target default, verification method), Indicator detail (full protocol card, formula, targets per provider, monitoring vs verified by provider, trend, disaggregation), Indicator report (matrix providers × indicators with colour vs target), Target management.

## 22. Activities (`modules/activities`)

### 22.1 Why V1 is unreliable

Windows are computed on the fly per request from a rule keyed only by training duration; provider-scope activities have no window at all; the configured rules are all "+1 … +200 days"; there is no list of "what is due when" per TP; reminders (`activity_due_soon`) fire against meaningless windows; 28 submissions were never reviewed.

### 22.2 V2 model: definitions → schedules → obligations → submissions

```
activity_definitions   (what)      e.g. "Inception report" — scope=provider, linked indicator #2, evidence: PDF, checklist of 5 components
activity_schedules     (when rule) e.g. anchor=first class start of the provider, due +14 days, open −30 days, grace 3 days
activity_obligations   (concrete)  e.g. SCV — inception report — opens 2026-03-28, due 2026-05-11, closes 2026-05-14 — status=submitted
activity_submissions   (evidence)  files + checklist answers + note, version n
activity_reviews       (decision)  approved / returned (with reasons per checklist item)
```

**`activity_definitions`**: code, name, description, `scope` (`provider` | `training` | `site` | `class`), `linked_indicator_code`, `evidence_requirements` JSON (allowed file types, min files, required checklist items — e.g. inception report's 5 components (a)–(e); LMDA's 3 criteria), `recurrence` (`once` | `per_scope_once` | `monthly` for post-placement support), `active`, `created_by_provider_id` (TP-defined optional activities, as V1).

**`activity_schedules`**: definition_id, applies_to (`all` | level | duration | provider_id) — most specific wins (provider override > duration > level > all); `anchor` ∈ {`contract_signed_date`, `provider_first_class_start`, `training_planned_start`, `site_first_class_start`, `class_start`, `class_end`, `project_date:<key>`}; `open_offset_days`, `due_offset_days`, `grace_days`; `breakdown_extends` (bool); `repeat_every_days` + `repeat_count` (for monthly support logs).

**`activity_obligations`** (materialised): provider_id, definition_id, scope ids (training/site/class), sequence_no (for recurring), `open_date`, `due_date`, `close_date` (= due + grace), status `upcoming | open | submitted | approved | returned | overdue | waived`, latest_submission_id, computed_from_schedule_id, schedule_version.

- Generated by `activities.materializeObligations` on: provider activation, training/site/class creation, class date change, breakdown approval, schedule change. Idempotent (UNIQUE on provider, definition, scope ids, sequence_no) — recalculation updates dates of not-yet-approved obligations and records the change in an obligation history table.
- Status transitions by date are applied nightly (`upcoming → open → overdue`) and by actions.
- A TP can **always see its full obligation calendar** ("You have 3 obligations due this week").

### 22.3 Example schedules (proposed defaults — Part R to confirm)

| Activity (indicator) | Scope | Anchor | Open | Due | Grace |
|---|---|---|---|---|---|
| Signed contract (1) | provider | contract signed date | 0 | +7 | 0 |
| Inception report (2) | provider | provider first class start | −30 | +14 | 3 |
| LMDA alignment (5) | provider | provider first class start | −60 | 0 | 7 |
| Orientation sessions (6) | class | class start | −14 | 0 | 3 |
| Pre-training evaluation (7) | class | class start | 0 | +14 | 3 |
| Full duration delivered (8) | class | class end | 0 | +14 | 7 |
| Post-training assessment (13) | class | class end | 0 | +30 | 7 |
| Post-placement support (17) | class | class end | +30 | +30 monthly ×3 | 7 |

Because anchors are class dates, a 3-month Basic class starting in April and a 6-month Advanced class starting in July automatically get different, correct due dates.

### 22.4 Submission & review

- TP uploads evidence + ticks checklist items; may submit a new version until approved.
- Reviewer (M&E) approves, or returns with per-item reasons; returned obligations reopen with a new due date (+N days).
- Late submissions are accepted until `close_date` and flagged; after close the TP needs an extension (M&E grants a new close date with a note) — V1 had grace only.
- Approval feeds provider-level indicators (`provider.activity_approved:<code>`).

### 22.5 Pages

TP: Obligations calendar/list (filter by status, scope), Obligation detail (requirements, upload, history). M&E: Review queue (oldest first, SLA), Activity definitions & schedules (with a **preview** "for provider X these obligations would be generated"), Compliance matrix (providers × activities, colour by status).

## 23. Verification (`modules/verification`)

### 23.1 Principles

- Verification is **independent**: TPs never see sampled trainees, open runs, or individual verdicts; they see finalised aggregate results for their provider.
- Every parameter is recorded with the run; every draw is reproducible (seed + frozen frame).
- The method is **configurable per indicator** because the protocol is still evolving (brief: "verification is at its stage, the formula may change").

### 23.2 Entities

- `verification_plans` (per indicator, versioned): population_metric (e.g. `trainees.registered` — V1 behaviour — or `trainees.claimed_completers`), stratify_by (`["location","sex"]`), sample-size method (`cochran_fpc`), Z, p, e, non_response_factor, reserve_pct, min_per_stratum, **tiering** (`single` | `two_tier`), tier2 rule (sample augmentation size), **estimator** (`wilson_one_sided` | `wilson_two_sided` | `clopper_pearson` | `simple_rate`), confidence (0.95), decision rule (`ci_vs_target` | `point_vs_target`), definite statuses (`["V-COMP","V-NCOMP"]`), questionnaire version, max call attempts, status-code mapping from questionnaire answers, effective_from.
- `verification_runs` (plan_version, indicator_code, provider_id, period, stage_key, tier, parent_run_id, seed, frame_id, parameters JSON (frozen copy), n0, n_fpc, n_target, reserves, status `planned → frame_frozen → drawn → in_field → under_review → finalised` (+ `cancelled`), counters (primary, reserve, completed, definite, successes, unreachable, refused, inconclusive), results (rate, ci_low, ci_high, pathway), finalised_by/at, report_file_id).
- `verification_frames` + `verification_frame_members` (trainee_id, stratum_key, claim_value, attributes snapshot: name, phones, training, location, sex) — **frozen** at draw; later data changes never alter the frame.
- `verification_subjects` (run_id, trainee_id, role `primary|reserve|replacement`, stratum_key, reserve_order, replaces_subject_id, assigned_enumerator_id, status code, verified_value, supervisor_status `pending|approved|rejected`, notes).
- `verification_call_attempts` (subject_id, attempt_no, called_at, phone_used, outcome `reached|no_answer|busy|switched_off|wrong_number|call_back_requested`, note, enumerator_id).
- `verification_responses` (subject_id, questionnaire_version, answers JSON, derived_status_code, source `mis_form|kobo_import`, kobo_submission_uuid, submitted_at).
- `verification_evidence` (files per subject, as V1).
- `verification_strata` (per run: population, primary_drawn, reserve_drawn — V1 table kept).

### 23.3 Workflow

1. **Plan** (supervisor): choose indicator, provider(s), period, stage → system shows population per stratum and the planned sample (V1 `sample-plan` endpoint, kept).
2. **Freeze frame & draw**: frame stored; seeded stratified draw (V1 algorithm kept: largest remainder, min 1 per stratum, reserves per stratum).
3. **Assign** subjects to enumerators (bulk, by stratum or round-robin).
4. **Fieldwork**: either (a) the built-in phone-survey form (questionnaire Q1–Q17 from the protocol; status auto-derived) with call-attempt logging, or (b) **Kobo export** (CSV/XLSX of assigned subjects in Kobo's pre-load format) and **Kobo import** (results file mapped by `subject_key`; status codes derived by the same rule).
5. **Replacement**: when a subject reaches V-UNR (after max attempts), V-REF or V-INC, the supervisor promotes the next reserve of the same stratum (V1 rule) — or the system proposes it automatically.
6. **Supervisor review**: approve/reject each completed record; data-quality officer back-checks a configurable % (flag discrepancies).
7. **Compute & decide**: rate = successes ÷ definite; CI by the plan's estimator; pathway: `clear_pass` (CI low ≥ target), `clear_fail` (CI high < target), `inconclusive`. **Target = the provider's target for that indicator** (§21.4) — no longer one threshold for all.
8. **Tier 2** (only if the plan is `two_tier` and the result is inconclusive): augmentation draw from the remaining frame members; pooled computation (V1 behaviour). For indicators configured `single`, the inconclusive result is reported as such (or decided on the point estimate if the plan's decision rule says so) — this is the switch requested in the brief ("remove the twice verification for some indicators").
9. **Finalise**: locks the run, writes the verified KPI snapshot, generates the report (PDF/DOCX), notifies M&E, and makes the aggregate visible to the TP.

### 23.4 Performance fixes

Run list reads `verification_runs` counters (no subject join); run detail paginates subjects (filters by status/stratum/enumerator); enumerator work list is a narrow indexed query (`assigned_enumerator_id, status`).

### 23.5 V1 data

All 3 runs, 875 subjects, 18 strata, 79 dropout auto-marks and the seeds are migrated unchanged; their plan is recorded as a migrated "V1 ICOS plan" (Z 1.96, p 0.5, e 0.05, non-response 0.9, reserve 15 %, Wilson one-sided z 1.645, two-tier) so their numbers reproduce exactly.

## 24. Grievance / feedback — GRM (`modules/grievance`)

### 24.1 Entities

`grievance_cases` (ref `GRM-YYYY-000123`, provider_id, category `complaint|suggestion|question|appreciation`, subject, description, submitter name/email/phone, region, channel `web|phone|in_person|email`, priority `normal|high`, status `new → acknowledged → in_progress → responded → resolved → closed` (+ `escalated`, `reopened`), due_at (submitted + SLA days), first_response_at, resolved_at, satisfaction_score 1–5, satisfaction_comment, assigned_to, tags), `grievance_messages` (author type public/tp/me/system, body, visibility `public|internal`, email delivery status), `grievance_actions` (corrective action: description, owner, due date, status) — **improvement tracking**.

### 24.2 What changes

- **TP notification on new case**: in-app notification (bell + Feedback badge count) to TP admins and site leads of that provider **and** email to the provider's `notification_email` and those users; daily digest of open cases.
- **SLA reminders** (fixes the never-called V1 reminder): T−2 days, due day, overdue (then every 2 days) to the TP; at overdue + 2 days **escalation** to M&E with status `escalated`.
- **Submitter experience**: acknowledgement email with reference and due date; reply emails sent from the system address with **Reply-To = provider reply_to_email**; a public **status lookup** page (reference + email) and a **satisfaction survey link** after resolution (1–5 + comment) — measures whether responses actually solved problems.
- **Internal notes** (not sent to the submitter) for TP/M&E collaboration.
- **Improvement insights** (the "win point"): categories and tags over time per provider, recurring topics (simple keyword clustering of subjects/descriptions), response-time distribution, SLA compliance (= indicator 19), satisfaction average, open corrective actions; exported in the GRM report.
- Public form: V1 sanitisation and rate limits kept; single route registration (V1 registered the routes twice); optional CAPTCHA (hCaptcha/Turnstile) if abuse appears.

### 24.3 Indicator 19

Timely resolution = cases resolved within SLA ÷ (resolved + overdue unresolved) — V1 definition kept ("responded" in V1 is treated as resolution if the case was closed; Part R asks M&E to confirm response vs resolution).

## 25. Notifications, email and reminders (`modules/notifications`) — TP SMTP removed

### 25.1 Mail architecture

- **One mail transport** configured by the system admin (SMTP host/port/user/password **encrypted at rest** with an app key, or env-only in production). Test-send button kept.
- Every email is written to `email_outbox` (to, cc, reply_to, from_name, subject, html, text, template_key, related entity, status `queued|sending|sent|failed|dead`, attempts, last_error, sent_at, provider_message_id) in the business transaction and sent by the worker with retries (1 min, 5 min, 30 min, 2 h, 12 h).
- **TP-originated mail** (grievance replies, notices to trainees in the future): `From: "<TP name> via PBPS MIS" <noreply@<system-domain>>`, `Reply-To: <provider.reply_to_email>` — replies reach the TP mailbox while SPF/DKIM stay valid for the system domain. No TP needs SMTP credentials.
- **Mail to TPs** goes to the provider's `notification_email` plus users with the relevant role (each user can mute categories in preferences, except mandatory ones).
- V1 `tp_smtp_configurations` (5 identical rows) and `smtp_configurations` are archived; the active system SMTP row is migrated into settings (password re-encrypted).

### 25.2 In-app notifications

`notifications` (user_id, project_id, type, title, body, link, severity `info|warning|critical`, entity_type/id, created_at, read_at, dedupe_key UNIQUE) + `notification_preferences` (user, type, in_app bool, email `immediate|daily_digest|off`).

UI: bell with unread count (poll 60 s or SSE), notification centre page (filters, mark all read), deep links.

### 25.3 Event catalogue

| Type | Audience | Channel default |
|---|---|---|
| grievance.new_case | TP admin, site leads of provider | in-app + email |
| grievance.due_soon / overdue / escalated | TP; M&E on escalation | in-app + email |
| activity.obligation_open / due_in_7d / due_in_1d / overdue / returned / approved | TP admin (+ scoped leads) | in-app + email (digest for open) |
| attendance.missing_sessions (≥ 2 missing days in a class) | class's scoped staff + TP admin | in-app + daily digest |
| attendance.correction_requested / decided | M&E / requester | in-app |
| outcome.report_due (class ended N days ago, report not accepted) | TP | in-app + email |
| outcome.report_returned / resubmission_decided | TP | in-app + email |
| roster.freeze_upcoming (3 days before) / frozen | TP | in-app + email |
| roster.change_requested / decided | M&E / TP | in-app |
| registration.window_closing (7 d, 1 d) | TP | email |
| duplicate.found (high risk) | M&E; TP of both records | in-app |
| verification.assigned (enumerator) / ready_for_review (supervisor) / finalised (M&E, TP aggregate) | per role | in-app + email |
| kpi.below_target (provider snapshot moves from met → not_met) | M&E, TP admin | in-app + weekly digest |
| system.import_finished / export_ready | requester | in-app |

### 25.4 Digests

Daily (07:00 Addis Ababa) per user: everything set to "daily digest"; weekly M&E summary (KPIs vs targets, overdue obligations, open grievances, verification progress). Each recipient gets an individual email (V1 put all admins in one To: header).

### 25.5 Reminder engine

`reminder_rules` (key, event source, audience resolver, offsets in days relative to a date field (e.g. obligation.due_date −7, −1, 0, +1, +3…), repeat policy, template, enabled). The `reminders.tick` job (every 15 min) finds due reminders with indexed date queries and inserts notifications/emails with `dedupe_key = rule:entity:offset` (UNIQUE) — **idempotent**: a reminder can never be sent twice even if the job overlaps or restarts. Quiet hours (no email 20:00–07:00) configurable.

## 26. Dashboards & reporting (`modules/reporting`)

### 26.1 Dashboards (read models only)

- **Programme dashboard (M&E / funder):** headline KPIs vs targets (monitoring and verified), trainees by provider/level/location/sex, attendance trend (from daily snapshots), dropout & completion funnel, obligations compliance, open grievances & SLA, verification progress, data-health score.
- **Provider dashboard (TP):** own KPIs vs own targets, to-do list (attendance days missing, reports due, obligations due, grievances to answer), class progress table, at-risk trainees.
- **Class view:** roster, attendance grid summary, outcome status per trainee.
- All widgets read `kpi_snapshots`, `trainee_status`, `class_counters`, `activity_obligations`, `grievance_cases` — target < 1 s total.

### 26.2 Reports (kept from V1, re-implemented on read models)

| Report | Formats | Audience |
|---|---|---|
| Claimed vs verified (programme) | PDF, DOCX, XLSX | M&E, funders |
| Provider profile | PDF, DOCX | M&E, TP |
| Trainee profile | PDF | M&E, TP |
| Indicator summary (with targets per provider) | PDF, DOCX, XLSX | all |
| Grievance summary / detailed register | PDF, DOCX, CSV, XLSX | M&E, funders |
| Verification run report / summary | PDF, DOCX | M&E, funders |
| Activities compliance | PDF, DOCX, XLSX | M&E |
| Attendance register (class) | XLSX, PDF | TP, M&E |
| Roster export (full trainee data) | CSV, XLSX | M&E, TP (own) |
| Executive pack | PDF | leadership |

Large exports run as jobs (`exports.generate`) and stream to a file; the user is notified when ready (no HTTP timeouts at 120k rows).

## 27. Audit trail (`modules/audit` + `core/audit`)

- `audit_events` (id, project_id, occurred_at, actor_user_id, actor_role, ip, module, action, entity_type, entity_id, provider_id, summary, before JSON, after JSON, payload_sha256, prev_hash, hash, request_id).
- Hash = SHA-256 over a **canonical JSON** (keys sorted recursively — fixes V1's array-replacer bug) of the event + `prev_hash`.
- Chain head per project kept in `audit_chain_heads (project_id, last_event_id, last_hash)` updated with `SELECT … FOR UPDATE` in the same transaction (fixes V1's race).
- Workflow state never lives in the audit table (V1 resubmission requests move to `outcome_reports`).
- Integrity check (full or range), signed export bundle (V1 feature kept), retention policy (7 years), monthly partitioning by `occurred_at` when > 10 M rows.
- **V1 events migrate verbatim** into `audit_events_legacy` (all columns, including V1 hashes), and the V1 chain can still be verified with the V1 algorithm; the V2 chain starts with a genesis event that records the hash of the last V1 event.

## 28. Data health (`modules/datahealth`) — replaces the repair pages

Nightly checks with results in `datahealth_findings` (check_key, severity, entity, provider, message, first_seen, last_seen, resolved_at):

| Check | Replaces |
|---|---|
| Phones failing `parsePhoneET` (legacy rows) | Phone correction page |
| High-risk duplicate pairs pending review | Possible duplicates / roster duplicate check |
| Attendance marks on non-session days (holiday added later) | Holiday attendance audit |
| Roster differs from freeze snapshot without approved change | Registration integrity |
| Trainees with ambiguous legacy dates (form date day ≤ 12, DOB unparsable) | — (new) |
| Classes with no schedule / ended without outcome reports | — (new) |
| Providers without targets / contract / notification email | — (new) |
| Obligations overdue > 14 days | — (new) |
| Missing attendance > 3 sessions in an ongoing class | — (new) |
| KPI snapshot older than 26 h | — (new) |

Page "Data health": score per provider, list with filters, deep links to fix screens, export. TPs see findings for their provider.

---

# PART E — PERFORMANCE & SCALE ENGINEERING

## 29. Capacity model for 120,000 trainees

| Quantity | Pilot (now) | Target | Basis |
|---|---|---|---|
| Providers | 5 | 50–150 | assumption: ~1,000 trainees per TP |
| Trainings | 18 | ~600 | |
| Sites | 24 | ~1,000 | |
| Classes | 111 | ~4,000 | ~30–40 trainees per class |
| Trainees | 3,234 | 120,000 | brief |
| Session days per class | 60–150 | 60–150 | 3–6 months, 3–6 days/week |
| Attendance marks | 180k | **≈ 10–12 M** | 120k × ~90 |
| Calendar days rows | ~20k | ~700k | 4,000 classes × ~180 days |
| Outcome report lines | 4.4k | ~600k | 120k × ~5 report types |
| Trainee status rows | – | 120k | 1 per trainee |
| KPI snapshot rows / day | – | ~3,000 | 19 indicators × 150 TPs (+ dimensions) |
| Audit events / year | 7k | ~2–3 M | |
| Concurrent users (peak) | ~20 | 300–500 | TP clerks capturing attendance in the morning |

Storage estimate (InnoDB, with indexes): attendance marks ≈ 12 M × ~45 B ≈ 0.6 GB; everything else < 1 GB; files (evidence) dominate — plan 50–200 GB.

## 30. Read models, snapshots, indexes, pagination, caching

### 30.1 Read-model tables (always up to date via events / jobs)

| Read model | Written by | Read by |
|---|---|---|
| `trainee_status` (1 row / trainee) | attendance, outcomes, registration | KPIs, lists, verification frames, dashboards, templates |
| `class_counters` | delivery, attendance | attendance to-do, dashboards |
| `class_calendar_days` | delivery | attendance validation, rates, obligations |
| `provider_counters` (registered, active, reserve, withdrawn, eligible, by sex/location…) | registration | dashboards, caps |
| `kpi_snapshots` | indicators | dashboards, reports, indicator pages |
| `activity_obligations` | activities | to-do, compliance, reminders |
| `verification_runs` counters | verification | run lists |

### 30.2 Index plan (principal)

- `trainees`: UNIQUE (`trainee_code`); UNIQUE (`project_id`, `phone_e164`); UNIQUE (`provider_id`, `external_beneficiary_id`); (`project_id`, `provider_id`, `roster_status`); (`class_id`, `roster_status`); (`project_id`, `name_key_fn_fa`); (`project_id`, `name_phon_fn`, `name_phon_fa`); (`provider_id`, `created_at`).
- `trainee_status`: PK `trainee_id`; (`provider_id`, `completion_status`); (`provider_id`, `dropout_status`); (`provider_id`, `system_dropout_final`); (`class_id`); (`provider_id`, `eligibility_status`).
- `attendance_sessions`: UNIQUE (`class_id`, `session_date`); (`provider_id`, `session_date`).
- `attendance_marks`: PK (`session_id`, `trainee_id`); (`trainee_id`, `session_id`).
- `outcome_reports`: (`class_id`, `report_type`, `stage_key`, `status`); (`provider_id`, `report_type`, `status`).
- `outcome_report_lines`: PK (`report_id`, `trainee_id`); (`trainee_id`, `report_id`).
- `kpi_snapshots`: PK (`project_id`, `indicator_code`, `provider_key`, `dimension_key`, `as_of_date`); (`project_id`, `as_of_date`).
- `activity_obligations`: UNIQUE (`provider_id`, `definition_id`, `scope_key`, `sequence_no`); (`status`, `due_date`); (`provider_id`, `status`).
- `notifications`: (`user_id`, `read_at`, `created_at`); UNIQUE `dedupe_key`.
- `grievance_cases`: UNIQUE `ref`; (`provider_id`, `status`, `due_at`).
- `audit_events`: (`project_id`, `occurred_at`); (`entity_type`, `entity_id`); (`actor_user_id`, `occurred_at`).

All index decisions are verified with `EXPLAIN ANALYZE` on a seeded 120k dataset (§31).

### 30.3 Query rules

- No endpoint loads unbounded rows into memory; exports stream.
- No ORM loops issuing a query per item (lint rule + query-count assertions in integration tests: list endpoints must use ≤ 5 queries).
- Aggregates are SQL `GROUP BY` statements over read models.
- `COUNT(*)` for paginated lists uses the same filters; for very large lists the UI shows "1–50 of 120,000" from counters when no filter is applied.

### 30.4 Caching

- Access contexts (LRU, version-stamped).
- Reference data (locations, enums, indicator definitions, role catalogue): LRU 10 min + version bump on change.
- HTTP: `ETag` on snapshot-backed endpoints (`kpi` responses carry `computed_at` → `ETag`), so the browser revalidates cheaply.
- No per-user dashboard cache (V1); the data is already pre-computed and shared.

## 31. Performance budgets and load testing

| Operation | Budget (p95) at 120k trainees, 300 concurrent users |
|---|---|
| Login | < 300 ms |
| Any list page (trainees, classes, cases…) | < 500 ms |
| Dashboard (all widgets) | < 1 s |
| Indicator report (all providers) | < 500 ms |
| Attendance class sheet load | < 400 ms |
| Attendance submit (40 trainees) | < 600 ms (counters included) |
| Outcome report submit (40 lines, all validations) | < 1.5 s |
| Registration import validate 2,000 rows | < 10 s (job, with progress) |
| Registration import commit 2,000 rows | < 10 s (job) |
| KPI recompute one provider | < 3 s (background) |
| KPI nightly full recompute | < 2 min (background) |
| Verification draw (frame 5,000) | < 5 s |
| Export full roster 120k (XLSX) | < 2 min (job) |

**Load testing:** a generator script creates a synthetic project with 150 providers / 4,000 classes / 120,000 trainees / 12 M marks (realistic names from a dictionary, realistic distributions taken from the pilot). k6 scenarios (V1 has `loadtest/k6`): morning attendance peak, dashboard browsing, imports, report submissions, mixed. Gate: budgets met before UAT; regression run on every release candidate.

---

# PART F — QUALITY, SECURITY, OPERATIONS

## 32. Testing strategy

| Level | Scope | Tools | Gate |
|---|---|---|---|
| Unit | every `*.rules.ts`, `shared/*` (phone, ET calendar, dates, enums, names, Jaro-Winkler, sampling, Wilson, allocation, calendar builder, eligibility, dropout, completion gate, buffer, window calc) | Vitest | 95 % line coverage of rules & shared |
| Golden tests | V1 behaviour parity: run V1 pure functions and V2 functions on the same fixtures (sampling plan, allocation, Wilson, windows) | Vitest | identical outputs (or documented intentional differences) |
| Integration | each module's API against a real MySQL: happy paths, validation errors, **authorisation (cross-provider leakage tests for every list/detail)**, query-count assertions | Vitest + Testcontainers MySQL 8.4 | all pass |
| Migration | run full V1→V2 migration on a copy of production; reconciliation must be 100 %; KPI parity report reviewed | migration runner | sign-off |
| E2E | critical journeys: onboarding, class setup, registration import with errors fixed, attendance week, dropout & completion reports, obligation submit & review, grievance lifecycle, verification draw → fieldwork → finalise | Playwright | all pass |
| Load | §31 | k6 | budgets met |
| Security | dependency audit, SAST, authz tests, OWASP ZAP baseline, pen-test before go-live | npm audit, Semgrep, ZAP | no high/critical open |

CI (GitHub Actions or the client's GitLab): lint, typecheck, boundaries check, file-size guard, unit, integration, build, OpenAPI diff check (breaking changes flagged).

## 33. Security hardening

- Session cookies (httpOnly, Secure, SameSite=Lax), CSRF token for state-changing requests, refresh rotation with reuse detection.
- 2FA mandatory for `system_admin`, `me_lead`, `verification_supervisor` (configurable).
- Password policy + breached-list check; lockout (V1 rule).
- Strict CSP (no inline scripts), HSTS, X-Content-Type-Options, frame-ancestors none, Referrer-Policy.
- Rate limits: login, public grievance form (V1 limits kept), import/export endpoints, global per-IP at Nginx.
- Upload safety: size limits per purpose, MIME sniffing, extension allow-list, optional ClamAV scan hook, files stored outside the web root, downloads via authorised stream.
- Secrets only in env / secret store; SMTP password encrypted with an app key if stored in DB.
- PII minimisation: field-level masking by permission; exports containing PII are logged in the audit trail; funders receive aggregates.
- Backups encrypted; access to production DB limited to named administrators.
- Dependency updates monthly; pen test before go-live (V1 handover risk list).

## 34. Deployment, backup and disaster recovery

- **Environments:** dev (XAMPP acceptable for UI work, but MySQL 8.4 container recommended), staging (copy of production, migration rehearsals), production.
- **Production topology:** Nginx (TLS, static frontend, `/api` reverse proxy) → `pbps-api` (2 Node processes) + `pbps-worker` (1 process) → MySQL 8.4; files on a separate volume (or MinIO); systemd units with automatic restart; log rotation.
- **Backups:** nightly `mysqldump --single-transaction` (or Percona XtraBackup) + binary logs for point-in-time recovery (RPO ≤ 15 min), files rsync nightly; encrypted off-site copy; **monthly restore drill**; retention 30 daily / 12 monthly.
- **Releases:** versioned builds, Prisma migrations applied with a pre-deploy backup, zero-downtime restart of API processes, worker drained before restart.
- **DR:** documented restore runbook (RTO ≤ 4 h), standby VM optional.

## 35. Observability

- Dashboards (Grafana or the client's tool): request rate/latency/errors by route, slow SQL, job queue depth and lag, email outbox (queued/failed), KPI snapshot age, disk usage, backup status.
- Alerts to the operations email: API down, error rate > 2 %, job lag > 10 min, outbox failures > 20, backup missing.

---

# PART G — API CONTRACT (ENDPOINT INVENTORY)

Conventions: base path `/api/v2`; all project resources under `/projects/:projectId`; JSON; IDs as strings; pagination `page/pageSize` (default 25, max 200) or `cursor/limit`; errors `application/problem+json`; write endpoints accept `Idempotency-Key`; editable resources use `version` + `If-Match`. The OpenAPI document generated from the Zod schemas is the authoritative contract; this inventory is the plan.

### G.1 Identity
```
POST   /auth/login                          {email,password} → {status:'ok'|'2fa_required', challengeId?}
POST   /auth/2fa/verify                     {challengeId, code}
POST   /auth/2fa/resend                     {challengeId}
POST   /auth/refresh
POST   /auth/logout
GET    /auth/me                             → user, memberships (projects), must_change_password
POST   /auth/password/change                {current,new}
POST   /auth/password/forgot                {email}
POST   /auth/password/reset                 {token,new}
POST   /auth/invites/accept                 {token,password,name}
GET    /auth/sessions | DELETE /auth/sessions/:id
POST   /auth/2fa/totp/setup | POST /auth/2fa/totp/confirm | DELETE /auth/2fa
```
### G.2 Access
```
GET    /projects/:p/access/me               → role, permissions[], provider?, scopes[]
GET    /projects/:p/memberships             ?role=&providerId=&q=
POST   /projects/:p/memberships             {userEmail|userId, roleCode, providerId?, scopes?}  (invites if new)
PATCH  /projects/:p/memberships/:id         {roleCode?, scopes?, status?}
DELETE /projects/:p/memberships/:id
GET    /roles | POST /roles | PUT /roles/:id/permissions | GET /permissions
GET    /projects/:p/access/matrix           ?format=json|xlsx
GET    /users (admin) | GET/PATCH /users/:id | POST /users/:id/disable | POST /users/:id/resend-invite
```
### G.3 Projects & master data
```
GET    /projects | POST /projects | GET/PATCH /projects/:p
GET/PATCH /projects/:p/settings
GET/POST/PATCH /locations | /regions (with aliases) | /training-levels | /durations
GET/POST/DELETE /projects/:p/holidays       (POST triggers calendar rebuild job)
```
### G.4 Providers
```
GET    /projects/:p/providers               ?status=&q=
POST   /projects/:p/providers
GET/PATCH /projects/:p/providers/:id
POST   /projects/:p/providers/:id/activate | /suspend | /close
GET    /projects/:p/providers/:id/onboarding
GET/POST /projects/:p/providers/:id/contracts ; POST …/contracts/:cid/amend
GET/PUT  /projects/:p/providers/:id/registration-window   {openFrom, openUntil, note}
POST   /projects/:p/providers/:id/registration-window/late {until, reason}
GET/POST /projects/:p/providers/:id/staff ; PATCH/DELETE …/staff/:membershipId
```
### G.5 Delivery
```
GET/POST   /projects/:p/trainings                       ?providerId=&level=&status=
GET/PATCH  /projects/:p/trainings/:id
GET/POST   /projects/:p/trainings/:id/sites
GET/PATCH  /projects/:p/sites/:id
GET/POST   /projects/:p/sites/:id/classes
GET/PATCH  /projects/:p/classes/:id                     (dates/weekdays/shift/venue…)
POST       /projects/:p/classes/:id/actual-start        {date | null}
GET        /projects/:p/classes/:id/calendar            ?from=&to=
POST       /projects/:p/classes/preview-calendar        {start,end,weekdays} → days (no save)
GET/POST   /projects/:p/breakdowns ; POST …/breakdowns/:id/decision {approve|reject, note}
```
### G.6 Registration & duplicates
```
GET    /projects/:p/registration/schema
GET    /projects/:p/registration/template           ?format=csv|xlsx&trainingId=&siteId=
POST   /projects/:p/imports                         multipart {file, providerId, trainingId, siteId, classId?, mode: import|check_only}
GET    /projects/:p/imports/:id                     → status, progress, summary
GET    /projects/:p/imports/:id/rows                ?issue=error|warning|duplicate|ok&page=
PATCH  /projects/:p/imports/:id/rows/:rowId         {field: value…} → re-validated row
POST   /projects/:p/imports/:id/rows/:rowId/duplicate-decision {decision: skip|not_duplicate, reason}
POST   /projects/:p/imports/:id/commit
DELETE /projects/:p/imports/:id
GET    /projects/:p/trainees                        ?providerId=&trainingId=&siteId=&classId=&roster=&eligibility=&sex=&q=&page=
POST   /projects/:p/trainees
GET/PATCH /projects/:p/trainees/:id
GET    /projects/:p/trainees/:id/timeline           (registration, attendance summary, outcome history, verification (if allowed), changes)
POST   /projects/:p/trainees/:id/withdraw | /transfer
GET    /projects/:p/trainees/export                 ?format=csv|xlsx (job)
POST   /projects/:p/duplicates/check                {fields…} → candidates
GET    /projects/:p/duplicates                      ?status=&risk=&providerId=
POST   /projects/:p/duplicates/:id/decision         {confirmed_duplicate|not_duplicate, note, keepTraineeId?}
POST   /projects/:p/duplicates/scan                 (job)
GET    /projects/:p/classes/:id/roster/snapshots ; GET …/roster/diff?snapshotId=
POST   /projects/:p/classes/:id/roster/freeze
GET/POST /projects/:p/roster-changes ; POST …/roster-changes/:id/decision
```
### G.7 Attendance
```
GET    /projects/:p/attendance/todo                 ?providerId=&classId=   (missing sessions)
GET    /projects/:p/classes/:id/attendance          ?from=&to=   (grid: trainees × sessions)
GET    /projects/:p/classes/:id/attendance/:date    (one session sheet)
POST   /projects/:p/classes/:id/attendance/:date    {marks:[{traineeId,status,reason?}]}
POST   /projects/:p/classes/:id/attendance/import   multipart (staging like registration)
GET/POST /projects/:p/attendance/corrections ; POST …/corrections/:id/decision
GET    /projects/:p/attendance/summary              ?providerId=&trainingId=&siteId=&classId=  (rates, coverage)
GET    /projects/:p/attendance/at-risk              ?providerId=&classId=&page=
GET    /projects/:p/attendance/daily-series         ?providerId=&days=
GET    /projects/:p/classes/:id/attendance/export   ?format=xlsx|pdf
```
### G.8 Outcomes
```
GET    /projects/:p/outcomes/report-types
GET    /projects/:p/classes/:id/outcomes            → per report type: status, due date, latest version, counts
GET    /projects/:p/classes/:id/outcomes/:type/template   ?stage=&format=xlsx|csv
POST   /projects/:p/classes/:id/outcomes/:type/drafts     multipart file | JSON lines  → draft with validation result
GET    /projects/:p/outcome-reports/:id             (+ lines paginated, issues)
PATCH  /projects/:p/outcome-reports/:id/lines/:traineeId  (draft only)
POST   /projects/:p/outcome-reports/:id/submit      {reasonForChange?}
POST   /projects/:p/outcome-reports/:id/return      {reason}            (M&E)
POST   /projects/:p/outcome-reports/:id/approve-resubmission {note}     (M&E)
GET    /projects/:p/outcome-reports                 ?providerId=&type=&status=&classId=&page=
GET    /projects/:p/outcomes/status                 ?providerId=&classId=&type=&value=&page=  (trainee status list)
GET    /projects/:p/outcomes/dropout-monitoring     ?providerId=&trainingId=&classId=
```
### G.9 Indicators & KPIs
```
GET    /projects/:p/indicators                      (registry)
GET    /projects/:p/indicators/:code                (definition, versions)
POST   /projects/:p/indicators ; POST …/indicators/:code/versions ; POST …/versions/:v/approve
GET    /projects/:p/metrics                         (catalogue)
GET    /projects/:p/targets                         ?indicator=&providerId=&asOf=
POST   /projects/:p/targets                         {indicatorCode, providerId|null, value, comparator, effectiveFrom, note}
GET    /projects/:p/kpis                            ?asOf=&layer=monitoring|verified&providerId=&indicator=&dimension=
GET    /projects/:p/kpis/trend                      ?indicator=&providerId=&from=&to=
POST   /projects/:p/kpis/recompute                  {providerId?} (job)
GET    /projects/:p/kpis/status                     → last computed, pending jobs
```
### G.10 Activities
```
GET/POST/PATCH /projects/:p/activity-definitions
GET/POST/PATCH /projects/:p/activity-schedules ; POST …/activity-schedules/preview {providerId} → obligations
GET    /projects/:p/obligations                     ?providerId=&status=&dueFrom=&dueTo=&definition=
GET    /projects/:p/obligations/:id
POST   /projects/:p/obligations/:id/submissions     multipart (files + checklist + note)
POST   /projects/:p/obligations/:id/review          {decision: approve|return, items:[{key,ok,comment}], note, newDueDate?}
POST   /projects/:p/obligations/:id/extend          {closeDate, note}
POST   /projects/:p/obligations/:id/waive           {reason}
GET    /projects/:p/activities/compliance           ?format=json|xlsx|pdf
GET    /projects/:p/files/:id/download
```
### G.11 Verification
```
GET/POST /projects/:p/verification/plans ; POST …/plans/:id/versions
GET    /projects/:p/verification/sample-preview     ?indicator=&providerId=&stage=
POST   /projects/:p/verification/runs               {indicator, providerId, period, stage?, seed?}  → frame frozen + drawn
GET    /projects/:p/verification/runs               ?status=&indicator=&providerId=  (counters only)
GET    /projects/:p/verification/runs/:id           (summary, strata, results)
GET    /projects/:p/verification/runs/:id/subjects  ?status=&stratum=&enumerator=&page=
POST   /projects/:p/verification/runs/:id/assign    {subjectIds|strata, enumeratorId}
GET    /projects/:p/verification/my-work            (enumerator queue)
POST   /projects/:p/verification/subjects/:id/attempts   {outcome, note, phoneUsed}
PUT    /projects/:p/verification/subjects/:id/response   {answers}  → derived status
POST   /projects/:p/verification/subjects/:id/replace    {reserveSubjectId?}
POST   /projects/:p/verification/subjects/:id/review     {approve|reject, note}
POST   /projects/:p/verification/subjects/:id/evidence   multipart
GET    /projects/:p/verification/runs/:id/kobo-export    ?format=csv|xlsx
POST   /projects/:p/verification/runs/:id/kobo-import    multipart → staging & preview
POST   /projects/:p/verification/runs/:id/tier2
POST   /projects/:p/verification/runs/:id/finalize
GET    /projects/:p/verification/runs/:id/report        ?format=pdf|docx
GET    /projects/:p/verification/results                (aggregate, TP-visible when finalised)
```
### G.12 Grievance
```
GET    /public/projects                              (active projects for the public form)
GET    /public/projects/:p/providers
POST   /public/projects/:p/grievances                (rate-limited)
GET    /public/grievances/status                     ?ref=&email=
POST   /public/grievances/:ref/satisfaction          {token, score, comment}
GET    /projects/:p/grievances                       ?status=&category=&providerId=&overdue=&q=&page=
GET    /projects/:p/grievances/:id
POST   /projects/:p/grievances/:id/messages          {body, visibility: public|internal}
POST   /projects/:p/grievances/:id/status            {status, note}
POST   /projects/:p/grievances/:id/assign | /escalate
GET/POST/PATCH /projects/:p/grievances/:id/actions   (corrective actions)
GET    /projects/:p/grievances/insights              ?providerId=&from=&to=
GET    /projects/:p/grievances/export                ?format=csv|xlsx|pdf
```
### G.13 Notifications
```
GET    /projects/:p/notifications                    ?unread=&type=&page=
GET    /projects/:p/notifications/unread-count
POST   /projects/:p/notifications/:id/read | POST /projects/:p/notifications/read-all
GET/PUT /me/notification-preferences
GET/PUT /settings/mail ; POST /settings/mail/test
GET    /settings/mail/outbox                         ?status=&page= ; POST …/outbox/:id/retry
GET/PUT /projects/:p/reminder-rules
```
### G.14 Reporting, audit, data health, jobs
```
GET    /projects/:p/dashboard/programme | /projects/:p/dashboard/provider/:providerId
GET    /projects/:p/reports/catalogue
POST   /projects/:p/reports/:key                     {params, format} → job
GET    /projects/:p/jobs/:id                         → status, progress, fileId
GET    /projects/:p/audit/events                     ?module=&action=&actor=&entity=&from=&to=&page=
POST   /projects/:p/audit/verify                     {from?,to?} → result
POST   /projects/:p/audit/export-bundle              → job
GET    /projects/:p/datahealth/findings              ?check=&severity=&providerId=&status=
GET    /projects/:p/datahealth/summary
```

---

# PART H — MIGRATION & CUTOVER (SUMMARY)

Full design, DDL and SQL are in **document 02**. Summary:

1. **Strategy:** build the new schema `pbps_v2` on the same MySQL server; copy and transform with `INSERT … SELECT` from `pbps_mis` (read-only); **preserve all primary keys**; keep raw values in `*_raw` columns; copy every V1 table verbatim into a `pbps_legacy` schema (or keep `pbps_mis` frozen) so the original is always available.
2. **Idempotency:** every script can run any number of times with the same result (`INSERT IGNORE` keyed on preserved IDs, `ON DUPLICATE KEY UPDATE`, `NOT EXISTS` guards, deterministic derivations). The runner logs each script in `migration_runs` with row counts and checksums.
3. **Order:** reference data → identity & access → projects/providers/contracts → delivery (trainings/sites/classes) → trainees → trainee_status → attendance sessions/marks → outcomes (reports, lines, statuses) → indicators/targets → activities (definitions, schedules, obligations, submissions, files) → verification → grievance → notifications/alerts → audit (legacy) → post-processing (calendars, counters, KPI snapshots) → reconciliation.
4. **No-loss guarantees:** row-count equality per entity; per-provider sums (trainees by role/sex, attendance present/absent by class, outcome Yes/No by type) equal between V1 and V2; every V1 row ID present in V2 or in the archive (anti-join checks return zero rows); file checksums verified.
5. **Data cleaning is additive:** cleaned/normalised columns are filled beside raw columns (e.g. `region_code` + `region_raw`); anything that cannot be parsed is kept raw and listed in Data health — never discarded.
6. **Inferred completion "No"** is created only where it is provable (a processed completion report exists for the trainee's class, the trainee was tracked, not a dropout, and not listed as completer) and is marked `completion_source = 'migration_inferred'`. Measured on the live data: **0 rows** need inference — every tracked non-dropout trainee in a reported class is listed as a completer; from V2 onward every completion report lists Yes **and** No explicitly.
7. **KPI parity report:** V1 `/indicator-kpis` output saved before cutover is compared with V2 snapshots; every difference is explained (bug fix or rule change approved in Part R).
8. **Cutover:** 3 rehearsals on staging (timed); final run during a declared freeze window (V1 read-only); smoke tests; go/no-go; V1 kept read-only for 6 months.

---

# PART I — DELIVERY ROADMAP, WORK BREAKDOWN, RISKS

## I.1 Phases

| Phase | Weeks | Content | Exit criteria |
|---|---|---|---|
| 0. Sign-off | 1–2 | Review this plan; decide Part R items; freeze V1 feature work (bug fixes only) | Signed decision log |
| 1. Foundations | 3–5 | Repo skeleton, CI, core (db, jobs, events, mail outbox, files, audit, time), shared validators, identity, access, projects; V2 schema v1; migration runner + reference/identity scripts | Login works on migrated users; boundaries check in CI |
| 2. Frontend shell | 3–6 (parallel) | Build of the UI from document 03 against mock API (MSW) | All pages navigable with mock data |
| 3. Providers & delivery | 6–8 | Providers, contracts, onboarding, trainings/sites/classes, calendars, holidays, breakdowns; migration scripts for these | Structure migrated 100 %; calendars generated |
| 4. Registration | 8–11 | Field schema, form, imports (staging/preview/commit), duplicates, roster freeze/changes; trainee migration + cleaning | 3,234 trainees migrated; import of 2,000 synthetic rows within budget |
| 5. Attendance | 11–13 | Sessions/marks, corrections, summaries, to-do, import; migration of 180k rows | Rates equal V1 per trainee (± documented) |
| 6. Outcomes | 13–16 | Report types, templates, drafts/submit/return/resubmit, statuses, system dropout, monitoring; migration | Outcome counts reconcile; parity report |
| 7. Indicators & KPIs | 15–17 | Registry (19), metrics, targets, snapshots, jobs, dashboards | Dashboard < 1 s on 120k synthetic |
| 8. Activities | 17–19 | Definitions, schedules, obligations, submissions, review, compliance | Obligations generated for all migrated classes |
| 9. Verification | 18–22 | Plans, frames, draws, assignment, attempts, responses, review, Kobo I/O, tiering, finalise, reports; migration of 3 runs | V1 runs reproduce exactly |
| 10. Grievance & notifications | 20–23 | GRM cases, SLA, satisfaction, actions, insights; notification centre, reminders, digests, outbox | Reminder idempotency tests pass |
| 11. Reporting, audit, data health | 22–24 | Report jobs, exports, audit chain, integrity, data health checks | All V1 reports available |
| 12. Hardening | 24–26 | Load tests, security review, pen test fixes, accessibility pass, documentation | Budgets met; no high findings |
| 13. UAT & cutover | 26–28 | UAT with M&E, ICOS, 2 TPs; 3 migration rehearsals; training; go-live | Go/no-go signed |

(Durations assume 2–3 backend developers, 1–2 frontend, 1 QA; adjust to team size.)

## I.2 Work breakdown (backend, by module — indicative effort in developer-days)

| Module | Effort | Notes |
|---|---|---|
| core + shared | 15 | jobs, events, outbox, audit chain, validators, calendar, stats |
| identity + access | 12 | sessions, TOTP, invites, matrix, policies, scope tests |
| projects + master data | 5 | |
| providers + onboarding | 8 | |
| delivery | 12 | calendars, breakdowns, actual start |
| registration + duplicates | 22 | field schema, XLSX templates, staging, preview, commit, keys, scoring |
| attendance | 14 | |
| outcomes | 20 | 7 report types, versions, gates |
| indicators | 15 | 19 definitions, metrics, snapshots |
| activities | 12 | |
| verification | 25 | plans, frames, fieldwork, Kobo, tiering |
| grievance | 8 | |
| notifications | 10 | |
| reporting | 12 | reuse V1 PDF/DOCX builders |
| audit + datahealth | 7 | |
| migration (SQL + runner + reconciliation + rehearsals) | 20 | |
| load/security/hardening | 12 | |
| **Total** | **≈ 230** | |

## I.3 Risks

| Risk | Mitigation |
|---|---|
| Requirements keep changing during the rebuild | Freeze V1 features; Part R decisions signed; extension points (§7.5); change requests with impact estimate |
| Formula changes alter historic KPI values | Snapshots record definition version; parity report; approvals in Part R |
| Ambiguous legacy dates | Keep raw; flag in Data health; TP confirmation workflow (Doc 02 §9.4) |
| Migration surprises in production data | 3 rehearsals on fresh copies; reconciliation must be 100 % |
| Generated UI diverges from API | Contract-first: OpenAPI + mock server; typed client generated |
| Single server | Backups + restore drills; optional standby |
| Email deliverability | SPF/DKIM/DMARC for the system domain; Reply-To for TPs |
| Key-person dependency | Module docs, ADRs, pairing, recorded walkthroughs |

---

# PART R — DECISIONS THAT NEED M&E / CLIENT SIGN-OFF

| # | Topic | Current V1 behaviour | V2 proposal | Impact |
|---|---|---|---|---|
| R-1 | Completion attendance gate | Provider-level: if provider's average attendance < 80 % → completion = 0 for the whole provider | **Per trainee**: completer counts only if own final attendance ≥ 80 % (protocol wording) | Fairer; KPI may differ from V1 |
| R-2 | Completion & missing attendance | Any missing attendance slot → completion = 0 | Missing attendance blocks **submission** of the completion report (gate), not the KPI after acceptance | Avoids silent zeroes |
| R-3 | Completion report content | Only completers listed (Yes) | Full roster Yes/No (+ non-completion reason) | Non-completers explicit |
| R-4 | Dropout KPI buffer | Count rule + arbitrary per-trainee "counts toward KPI" (sorted by ID) | Count rule only; no per-trainee flag | Clearer, same totals |
| R-5 | Eligibility education | Includes "Secondary (Grades 9–12)" (any grade) | Confirm: Grade 12 completed only? or keep 9–12 | Eligibility % may change |
| R-6 | Consents | Not enforced | Accuracy + employment-verification consent mandatory to register | Some registrations may be blocked |
| R-7 | Age outside 18–29 | Accepted silently | Accepted with "not eligible" status (visible) — or reject? | |
| R-8 | Grandfather name | Optional | Required for new registrations | |
| R-9 | Verification population | All registered (active + reserve) | Keep; or eligible enrolled only (protocol §4 says "eligible trainees") | Sample size, rate |
| R-10 | Tiering per indicator | Two-tier for all | Choose per indicator (`single` / `two_tier`) | Fieldwork volume |
| R-11 | CI parameters | Size Z 1.96, CI one-sided z 1.645 | Keep, documented in plan; or align | Pass/fail boundary |
| R-12 | Call attempts | Protocol inconsistent (3 vs 2) | Configurable; default 3 | |
| R-13 | Target used in verification decision | One threshold per indicator | Provider-specific target (§21.4) | Decision per TP |
| R-14 | TP visibility of verification | TP sees runs and subjects | TP sees finalised aggregates only | Integrity |
| R-15 | World Bank grants | `submit:outcomes`, `manage:tps` granted | Read-only funder role | |
| R-16 | Activity schedules | All "+1…+200" | Defaults in §22.3 | Real deadlines & reminders |
| R-17 | Grievance indicator | "responded within due date" | Confirm: response vs resolution within 7 days | Indicator 19 value |
| R-18 | Roster freeze date | none | Class start + 14 days | Changes after need approval |
| R-19 | Excused attendance | Not available in UI | Allowed with reason (TP) | Attendance % |
| R-20 | Late attendance entry | Unlimited | ≤ 7 days, then correction request | Discipline |
| R-21 | Duplicate weights | Name-only | Multi-signal weights (§17.2) | Fewer false positives |
| R-22 | Legacy ambiguous form dates | Parsed M/D | Keep stored value, flag the 363 genuinely ambiguous rows for TP confirmation | Data accuracy |

---

# APPENDICES

## Appendix A — V1 → V2 feature map (nothing is dropped silently)

| V1 page / feature | V1 route | V2 equivalent |
|---|---|---|
| Landing / login / 2FA / reset / force password | `/`, `/login`, `/verify`, `/reset-password`, `/force-password` | Same pages, cookie sessions, invite acceptance, TOTP |
| Public feedback form | `/feedback/new` | Public GRM form + status lookup + satisfaction |
| Project picker / create / edit | `/projects`, `/projects/new`, `/p/:id/edit` | Same |
| Dashboard | `/p/:id/dashboard` | Programme dashboard (M&E/funder) and Provider dashboard (TP) |
| Training providers list / create / detail (contract panel, staff panel, location breakdown, registration gate) | `/providers…` | Providers list, onboarding wizard, provider detail tabs (profile, contract, targets, staff, trainings, trainees, obligations, KPIs, grievances) |
| Trainings list / create / edit / detail / scopes (cohorts, batches, breakdowns) | `/trainings…` | Trainings, Training detail (sites & classes), Class detail, Class editor with calendar preview, Breakdowns |
| Attendance hub / manage / insights / dropout monitoring | `/attendance…` | Attendance to-do, Class sheet, Corrections, Insights, Dropout monitoring |
| Trainees list / new / import / edit / detail | `/trainees…` | Same with server pagination, field schema form, import wizard with preview & fix |
| Roster simulation (reserve promotion) | `/trainees/roster-simulation` | Removed as a page; the policy is documented and the switch lives in Project settings (§10.3) |
| Outcomes hub / templates | `/outcomes…` | Outcomes by class (status board), report editor (upload or grid), report history, resubmissions, dropout monitoring |
| Activities list / create / edit / windows / review / detail | `/activities…` | Activity definitions, schedules with preview, obligations (TP), review queue (M&E), compliance matrix |
| Indicators list / builder / detail / report | `/indicators…`, `/indicators-report` | Indicator registry (protocol cards), definition editor with versioning, targets, KPI report |
| Verification list / runs / run detail / insights | `/verification…` | Plans, Runs (counters), Run workspace (strata, subjects, assignment, fieldwork, review, results), My work (enumerator), Results |
| Feedback list / detail / TP SMTP | `/feedback…` | GRM cases, case detail, insights; **TP SMTP removed** (provider notification/reply-to emails on provider profile) |
| Alerts | `/alerts` | Notification centre |
| Possible duplicates | `/monitor/possible-duplicates` | Duplicate review queue |
| Registration integrity | `/monitor/registration-integrity` | Roster snapshots & diff (by-product of freeze) + Data health check |
| Phone correction | `/monitor/phone-correction` | Validator at entry + Data health check for legacy rows |
| Roster duplicate check | `/monitor/roster-duplicate-check` | Import "check only" mode |
| Holiday attendance audit | `/monitor/holiday-attendance-audit` | Automatic exclusion + Data health notice |
| Settings (security, SMTP, holidays, registration gates & limits, roster policy, training durations, alerts, role permissions) | `/settings` | Project settings, Mail settings, Master data, Holidays, Roles & permissions, Reminder rules |
| Users / user detail | `/users…` | User management (invite, memberships, scopes, sessions) |
| Audit trail | `/audit` | Audit log + integrity + export bundle |
| Profile | `/profile` | Profile, password, 2FA, sessions, notification preferences |
| Reports (PDF/DOCX/CSV endpoints) | `/reports/...` | Report centre (catalogue → job → download) |
| Ops: data quality, repair scope fields, repair orphan attendance, risk monitor, executive pack | `/ops/...` | Data health; executive pack in Report centre; repairs unnecessary by design |
| TP mapping diagnostics / repair | `/projects/tp-mapping-diagnostics` | Not needed (single membership model) |
| Training purge | `/trainings/:id/purge` | Admin "delete draft training" (only without attendance/outcomes); otherwise close/archive |
| Date integrity check/normalize | `/trainings/date-integrity/...` | Not needed (DATE columns, validated input) + Data health |
| Seed performance catalogue | `/performance/seed-catalog` | Seeded indicator registry (19) at project creation |
| Monitor registration activity | `/monitor/registration-activity` | Audit log filter + registration analytics on provider page |

## Appendix B — V1 defects and risks found during analysis

| # | Area | Defect | Severity | V2 fix |
|---|---|---|---|---|
| B1 | KPIs | Full KPI engine executed on page loads; ~6 attendance roll-ups + 2 dropout projections per request | Critical (performance) | Snapshots, read models |
| B2 | Attendance | Roll-up loads all present rows into Node per batch | Critical | Counters at write time |
| B3 | Auth | 10–15 authorisation queries per request | High | Cached access context |
| B4 | Auth | `requirePermission` without project param accepts any project's grant | High | Project-scoped routes |
| B5 | Auth | JWT in localStorage; temp passwords emailed | High | Cookies; invite links |
| B6 | Verification | TPs can see sampled subjects | High (integrity) | Hidden until finalised |
| B7 | Registration | Booleans not true/false silently stored as NULL | High (data loss) | `parseBoolean` errors |
| B8 | Registration | Form date parsed M/D vs form's DD/MM; 702 ambiguous rows | High (accuracy) | Strict DD/MM; flag legacy |
| B9 | Registration | DOB free text (mixed formats) | Medium | ET-calendar parser |
| B10 | Registration | Safaricom (07) numbers rejected | Medium | `parsePhoneET` |
| B11 | Registration | Region/disability free text | Medium | Enums + aliases |
| B12 | Registration | N+1 queries in import; ID generation by max+retry | Medium | Pre-loaded maps; sequences |
| B13 | Outcomes | Report writes not transactional | High | One transaction |
| B14 | Outcomes | Dates as strings in JSON; 961 NULL status dates | Medium | Typed columns |
| B15 | Outcomes | Resubmission workflow stored in audit table | Medium | Versioned reports |
| B16 | Outcomes | No unique constraint (trainee, type, stage) | Medium | Status table PK + line PK |
| B17 | KPIs | Completion zeroed for whole provider on average attendance or any missing slot | High (fairness) | Part R-1/R-2 |
| B18 | KPIs | Eligibility rule in 3 different implementations | Medium | One rule |
| B19 | Activities | All windows "+1…+200"; provider-scope never windowed | High (reliability) | Obligations |
| B20 | Grievance | Reminder function never called; no in-app notice; refCode collision possible; routes registered twice | High | Notification centre, sequences |
| B21 | Email | TP SMTP required per TP; SMTP passwords in clear | Medium | Removed; encryption |
| B22 | Email | Digest with all admins in one To: header | Low (privacy) | Individual emails |
| B23 | Audit | Chain race; nested meta not hashed | Medium | Locked head; canonical JSON |
| B24 | Scheduler | setInterval in every API process | Medium | Worker + lease |
| B25 | Attendance | Excused not selectable; no corrections; partial rosters allowed | Medium | §19 |
| B26 | Dates | Local vs UTC key mixing | Medium | `DateOnly` |
| B27 | Structure | Cohort/batch naming; MAIN auto rows; stale statuses | Medium | Training/Site/Class; derived status |
| B28 | Data | 85 reserves without enrollment rows | Low | Not needed in V2 model |
| B29 | Frontend | Mock stores in production screens; minimal loading states | Medium | Document 03 |
| B30 | Duplicates | Name-only matching; in-memory full scan | Medium | §17 |
| B31 | Dashboard | Cache keyed per user (no sharing) | Low | Snapshots |
| B32 | Verification | Run list loads all subjects of 200 runs | Medium | Counters |

## Appendix C — Glossary

See §9.4. Additional: **EDI** — Entrepreneurship Development Institute (contracting authority); **MoLS** — Ministry of Labour and Skills; **ICOS** — ICOS Consulting PLC (independent M&E and verification); **EASE / Qiyas** — the World Bank-financed project and its national branding; **GRM** — Grievance Redress Mechanism; **LMDA** — Labour Market Demand Assessment; **FPC** — finite population correction; **CI** — confidence interval; **PII** — personally identifiable information.

## Appendix D — Business-rule catalogue (single implementation location in V2)

| Rule | V2 location | Source |
|---|---|---|
| Registration cap = ⌊target × (1 + allowance %)⌋ | `registration/roster.rules.ts` | V1 `providerContract.ts` |
| Roster policy (tracked equally / replacement window) | `registration/rosterPolicy.rules.ts` | V1 `traineeRoster.ts` + §10 |
| Eligibility (age, education, employment) | `registration/eligibility.rules.ts` | Protocol #4; V1 ×3 |
| Phone / date / ET calendar / enum / boolean parsing | `shared/validation/*` | V1 `phoneNormalize.ts`, `traineeImportDates.ts` + new |
| Duplicate keys & scoring | `duplicates/matching.rules.ts` | V1 `traineeDuplicateDetection.ts` + §17 |
| Session calendar | `shared/calendar/buildSessionCalendar.ts` | V1 `attendanceCalendar.ts`, `attendanceExemptPeriod.ts`, `attendanceEligibility.ts` |
| Attendance rate, max reachable, coverage | `attendance/attendance.rules.ts` | V1 `attendanceRollup.ts`, `dropoutProtocol.ts` |
| System dropout final / risk | `outcomes/dropout.rules.ts` | V1 `dropoutProtocol.ts` |
| Dropout report must include system-final as Yes | `outcomes/dropout.rules.ts` | V1 `dropoutPolicy.ts` |
| Report ordering & prerequisites | `outcomes/reportTypes.ts` | V1 `performance.ts` import route |
| Dropout buffer (count rule) | `indicators/metrics/dropout.ts` | V1 `providerContract.ts` |
| Completion cap & attendance gate | `indicators/metrics/completion.ts` | V1 `completionProtocol.ts` + R-1 |
| Target resolution | `indicators/targets.rules.ts` | new |
| Obligation dates (anchor, offsets, grace, breakdown extension, freeze) | `activities/schedule.rules.ts` | V1 `enforceActivitySubmissionWindow` |
| Sample size (Cochran + FPC + non-response), allocation, reserves, seeded draw | `shared/stats/*`, `verification/draw.rules.ts` | V1 `verificationSamplingService.ts` |
| Wilson CI & pathway; finalise blockers; pooled tiers | `shared/stats/wilson.ts`, `verification/decision.rules.ts` | V1 `verificationStatisticsService.ts`, `verificationRunService.ts` |
| Questionnaire → status code derivation | `verification/questionnaire.rules.ts` | Protocol §6.4–6.8 |
| Grievance SLA, timely-resolution indicator | `grievance/sla.rules.ts` | V1 `feedbackMetrics.ts` |
| Reminder offsets & dedupe | `notifications/reminders.rules.ts` | new (V1 reminder unused) |

---

*End of the master plan. Next: `02_DATABASE_REDESIGN_AND_MIGRATION.md`.*
