# PBPS MIS V2 — Frontend Build Prompt

> **How to use this document.** Paste Part 0–4 first (foundation: stack, theme, shell, shared components, mock layer). Then paste the page sections of Part 5 one module at a time (each section is self-contained). Ask the generator to build every page against the **mock API layer** described in Part 4 so the real backend can be plugged in later by replacing the mock handlers — **do not hard-code data inside components.**
>
> **Privacy note for whoever pastes this into an external tool:** all names, providers and numbers in this prompt are fictional sample data. Do not paste real trainee data into the generator.

---

## PART 0 — PRODUCT BRIEF

Build **PBPS MIS** — a web application for monitoring and verifying a results-based skills-training programme. Training providers (TPs) train young people (18–29) in digital skills; the programme pays TPs based on results (attendance, completion, certification, employment), which an independent team verifies by phone-surveying a statistical sample of trainees.

**Users and what they do**

| Role | What they do in the app |
|---|---|
| System admin | Users, roles, settings, master data, mail, audit |
| M&E lead / M&E officer | Monitor all providers, approve schedules/breakdowns/corrections/resubmissions, review activity evidence, set per-provider targets, manage indicators, run reports |
| Verification supervisor / enumerator / data-quality officer | Plan and draw samples, call sampled trainees, record answers, review and finalise verification runs |
| Funder viewer (World Bank, EDI) | Read-only dashboards, indicators, reports, aggregate verification results |
| TP admin / site lead / attendance clerk / outcomes officer / TP viewer | Set up classes, register trainees (form or Excel import), record daily attendance, submit outcome reports (dropout, completion, certification, employment), upload activity evidence, answer grievances — **only for their own provider and assigned sites/classes** |
| Public (no login) | Submit a grievance/feedback, look up its status, rate the response |

**Core objects:** Project → Training Provider → Training (a course) → Site (the course in one city: Addis Ababa, Hossana, Dessie) → Class (a group with its own start/end dates, weekdays and shift) → Trainees. Plus: Attendance sessions, Outcome reports, Indicators & targets, Activity obligations, Verification runs, Grievance cases, Notifications.

**The three promises of V2's UI**
1. **Fast and honest** — every page shows immediately (skeletons), states clearly what is loading, empty, failed or out of date, and never freezes.
2. **Guided** — users always see "what do I need to do next" (to-do lists, due dates, checklists, wizards).
3. **Safe** — destructive or irreversible actions always confirm; forms validate per field with the same rules as the server; nothing is silently dropped.

---

## PART 1 — TECH STACK AND CONVENTIONS

- **React 18 + TypeScript (strict) + Vite.**
- **Routing:** React Router 6 (data routers), lazy-loaded route modules per area.
- **Server state:** TanStack Query v5 for *every* API call (no `useEffect` fetching). Query keys: `['projects', pid, 'trainees', filters]`. Default `staleTime` 30 s; KPI/dashboard queries 60 s.
- **Tables:** TanStack Table v8, **server-side** pagination, sorting and filtering (all list endpoints return `{ items, page, pageSize, total }`).
- **Forms:** react-hook-form + Zod; schemas live in `src/features/<module>/schemas.ts`; field-level errors under inputs; summary error box on submit failure.
- **UI kit:** shadcn/ui (Radix) + Tailwind CSS; icons `lucide-react`; charts Recharts; dates `date-fns` (+ `date-fns-tz` for `Africa/Addis_Ababa`); animations `framer-motion` (subtle).
- **Fonts:** self-hosted via `@fontsource` (Plus Jakarta Sans, Inter, JetBrains Mono) — the app may run on a government intranet without Google Fonts.
- **API layer:** `src/api/client.ts` (fetch wrapper with `credentials: 'include'`, CSRF header, JSON, `application/problem+json` error parsing → `ApiError { status, code, message, fieldErrors[] }`), one module per area (`src/api/trainees.ts`…). Types in `src/api/types.ts` (will be replaced by a generated OpenAPI client later — keep names matching Part 4.3).
- **Mocking:** **MSW (Mock Service Worker)** handlers in `src/mocks/` returning realistic fictional data with artificial latency (300–900 ms) so loading states are visible; toggle with `VITE_USE_MOCKS=true`.
- **Folder structure:**
  ```
  src/
    app/            (router, providers, layout shell, error boundary)
    api/            (client + typed endpoint functions)
    mocks/          (MSW handlers + fixtures)
    components/     (shared UI: data-table, kpi-card, status-badge, calendar, file-dropzone, …)
    features/
      auth/ dashboard/ providers/ delivery/ registration/ attendance/ outcomes/
      indicators/ activities/ verification/ grievance/ notifications/ reports/
      datahealth/ admin/ public/
    lib/            (formatters, permissions, dates, phone, ethiopian-calendar)
    styles/         (tokens.css, globals.css)
  ```
- **Permissions in the UI:** `useAccess()` returns `{ role, permissions: Set<string>, providerId?, scopes[] }` from `GET /projects/:p/access/me`. Components use `<Can perm="outcome.submit">…</Can>`; routes use `RequirePermission`. The UI hides what you cannot do, but **always handles 403** gracefully (the server is the authority).
- **Accessibility:** WCAG 2.1 AA — keyboard navigation everywhere (attendance grid included), visible focus rings, `aria-live` for toasts and job progress, colour is never the only signal (icons + text on status badges), minimum contrast 4.5:1.
- **Responsiveness:** desktop-first (1280–1920), fully usable at 1024 (laptop) and tablet landscape; the attendance sheet, obligations list, grievance reply and enumerator call screen must also work on a phone (≥ 360 px).
- **Language:** English UI; all strings through a tiny `t()` helper (i18n-ready for Amharic later). Numbers with thousands separators; percentages with 1 decimal; dates displayed `12 May 2026`; inputs ISO under the hood.

---

## PART 2 — DESIGN SYSTEM: "HIGHLAND" THEME

A calm, institutional, high-legibility theme inspired by the Ethiopian highlands: deep teal (lakes, trust), warm amber (Meskel daisy, attention), sage (growth), on warm paper-white. It must look clearly different from the old V1 (deep blue "Institutional Architect").

### 2.1 Colour tokens (HSL, defined as CSS variables in `tokens.css`, mapped in `tailwind.config.ts`)

**Light (default)**

| Token | HSL | Hex | Use |
|---|---|---|---|
| `--background` | 45 20% 96% | #F7F6F2 | App background (warm paper) |
| `--surface` | 0 0% 100% | #FFFFFF | Cards, tables, dialogs |
| `--surface-2` | 45 16% 92% | #EFEDE6 | Sub-panels, table header, sidebar |
| `--surface-3` | 45 14% 87% | #E3E0D6 | Hover rows, selected chips |
| `--border` | 44 14% 84% | #DDD9CE | Hairlines |
| `--ink` | 198 26% 15% | #1C2A30 | Primary text |
| `--ink-muted` | 196 10% 40% | #5B6B70 | Secondary text, labels |
| `--ink-subtle` | 196 8% 58% | #8E999C | Placeholders, disabled |
| `--primary` | 192 78% 25% | #0E5E6F | Primary actions, active nav, links |
| `--primary-hover` | 192 78% 21% | #0B4F5D | |
| `--primary-soft` | 190 45% 92% | #E2F1F3 | Primary tinted backgrounds |
| `--primary-foreground` | 0 0% 100% | #FFFFFF | |
| `--accent` | 37 80% 57% | #E9A23B | Highlights, "due soon", focus accents, KPI target line |
| `--accent-soft` | 40 90% 93% | #FDF1DC | |
| `--sage` | 128 15% 49% | #6B8F71 | Secondary brand, growth charts |
| `--success` | 145 46% 33% | #2E7D4F | Met / approved / present |
| `--success-soft` | 140 40% 92% | #E3F3E8 | |
| `--warning` | 36 90% 41% | #C77D0A | At risk / due soon / pending review |
| `--warning-soft` | 40 90% 92% | #FDF0D8 | |
| `--danger` | 6 63% 46% | #C0392B | Not met / overdue / errors / absent |
| `--danger-soft` | 6 70% 94% | #FBE7E4 | |
| `--info` | 211 58% 44% | #2F6FB0 | Info notices, links in alerts |
| `--info-soft` | 211 60% 94% | #E5EEF8 | |
| `--focus` | 37 80% 57% | #E9A23B | 2 px focus ring (amber) with 2 px offset |

**Dark**

| Token | Hex | | Token | Hex |
|---|---|---|---|---|
| `--background` | #0F1A1D | | `--primary` | #3FB1C4 |
| `--surface` | #152328 | | `--primary-hover` | #5CC1D2 |
| `--surface-2` | #1C2E34 | | `--primary-soft` | #17363D |
| `--surface-3` | #24393F | | `--accent` | #F2B65C |
| `--border` | #2C4248 | | `--success` | #4FB97A |
| `--ink` | #E7EEF0 | | `--warning` | #E8A33A |
| `--ink-muted` | #A3B3B7 | | `--danger` | #E8695B |
| `--ink-subtle` | #6F8287 | | `--info` | #6FA7E0 |

Theme switch in the user menu (Light / Dark / System); persisted per user.

**Data-visualisation palette (categorical, colour-blind safe, in this order):** `#0E7C86` teal · `#E9A23B` amber · `#4C5BD4` indigo · `#C2547A` rose · `#7E8B2E` olive · `#3A9BDC` sky · `#8E5EA2` plum · `#5B6B70` slate. **Sequential (rates 0→100 %):** `#F2F7F7 → #0E5E6F`. **Diverging (vs target):** `#C0392B ← #F4F1EA → #2E7D4F`. Female/Male always: female `#C2547A`, male `#0E7C86`.

### 2.2 Typography

| Style | Font | Size / line | Weight | Use |
|---|---|---|---|---|
| Display | Plus Jakarta Sans | 32/40 | 700 | Dashboard greeting, KPI hero numbers |
| H1 | Plus Jakarta Sans | 24/32 | 700 | Page titles |
| H2 | Plus Jakarta Sans | 18/26 | 650 | Card / section titles |
| H3 | Plus Jakarta Sans | 15/22 | 650 | Sub-sections |
| Body | Inter | 14/22 | 400 | Default |
| Body-strong | Inter | 14/22 | 600 | Labels, table emphasis |
| Small | Inter | 12.5/18 | 500 | Meta, helper text, badges |
| Mono | JetBrains Mono | 12.5/18 | 500 | IDs (`PBPS-ABA-000123`), codes, file hashes |
| KPI number | Plus Jakarta Sans | 28/32 tabular-nums | 700 | Numbers on KPI cards |

Use `font-variant-numeric: tabular-nums` in tables and KPIs.

### 2.3 Shape, spacing, elevation

- Spacing scale 4 px (4, 8, 12, 16, 20, 24, 32, 40, 48, 64). Page padding 24 px (16 px on mobile). Card padding 20 px.
- Radius: cards & dialogs 12 px, inputs & buttons 8 px, badges/chips full pill, tables 10 px container.
- Elevation: `shadow-sm` = `0 1px 2px rgba(28,42,48,.06)`; `shadow-md` = `0 4px 14px rgba(28,42,48,.08)` (dropdowns, popovers); dialogs `0 12px 32px rgba(28,42,48,.18)`. Cards rely on a 1 px border + `shadow-sm`, not heavy shadows.
- A subtle **"terrace" motif**: page headers have a 3-step thin line accent (three stacked 2 px lines in primary / sage / accent, 24 px wide) left of the page title — the only decorative element.
- Density toggle on data tables: Comfortable (row 48 px) / Compact (row 36 px), remembered per user.

### 2.4 Components styling (shadcn overrides)

- **Buttons:** primary (teal fill), secondary (surface with border), ghost, destructive (danger fill), link. Sizes sm 32 / md 36 / lg 44. Loading state: spinner replaces icon, label stays, button disabled, width fixed (no layout jump).
- **Inputs:** 36 px, border `--border`, focus ring amber; error state border danger + message below in danger small text with an `AlertCircle` icon; helper text muted.
- **Status badges** (pill, icon + text, soft background):
  - `met` / `approved` / `present` / `accepted` / `verified complete` → success
  - `at risk` / `due soon` / `pending review` / `returned` / `inconclusive` → warning
  - `not met` / `overdue` / `rejected` / `absent` / `failed` / `clear fail` → danger
  - `draft` / `pending` / `upcoming` / `no data` → neutral slate
  - `info` / `in field` / `submitted` → info
  - `clear pass` → success with `ShieldCheck` icon
- **KPI card:** title (small, muted), big number, unit, delta vs previous snapshot (▲/▼ coloured by direction-is-good), a thin **target bar** (filled to value, amber tick at target), status badge, "as of 12 May, 07:30" footnote with a refresh-pending dot if a recompute is queued.
- **Tables:** sticky header in `surface-2`, zebra off, row hover `surface-3`, selected row primary-soft, numeric columns right-aligned, column visibility menu, CSV/XLSX export button (server job), empty state inside the table frame.
- **Tabs:** underline style, primary indicator 2 px.
- **Toasts (sonner):** bottom-right; success 4 s, error persistent until dismissed with "Details" expander (shows `code` and request id).
- **Dialogs:** title, body, footer actions right-aligned; destructive confirm requires typing the object name for irreversible actions (e.g. "delete draft training").

### 2.5 Loading, empty, error and long-running states (mandatory on every page)

| State | Pattern |
|---|---|
| **Initial load** | Skeletons that match the final layout: KPI cards (grey blocks with shimmer), table skeleton (10 rows, column widths approximated), detail skeleton (header + tabs + 2 cards). Never a blank page or a centred spinner for page loads. |
| **Background refetch** | Keep showing data; a 2 px indeterminate progress bar at the top of the card/table; "Updating…" chip in the card header. |
| **Pagination/filter change** | Table body dims to 60 % opacity with an inline spinner in the header; previous rows stay visible (TanStack `placeholderData: keepPreviousData`). |
| **Empty** | Illustration (simple line icon in a soft circle), one-sentence explanation, primary action if the user can create (e.g. "No classes yet — Add the first class"), secondary link to help. Differentiate *"nothing yet"* from *"no results for these filters"* (the latter offers "Clear filters"). |
| **Error** | Inline error card: icon, human message from the API, `code`, "Try again" button, request id (copyable). For 403: "You don't have access to this" + who to contact. For 404: back link. Page-level crash → error boundary with reload. |
| **Stale data** | KPI cards and dashboards show "as of …" and a small amber dot "recalculating" when the server reports a pending recompute. |
| **Long-running jobs** (imports, exports, KPI recompute, sample draw) | A **Job progress** component: title, determinate progress bar (`progress_pct`), current step text, elapsed time, "You can leave this page — we'll notify you" message; on completion a success panel with the result link; failures show the error and "Retry". Polls `GET /jobs/:id` every 1.5 s. |
| **Saving** | Button spinner; optimistic UI for toggles (attendance cells, notification read) with rollback on error. |
| **Unsaved changes** | Prompt on navigation away from forms/grids with unsaved changes. |
| **Offline** | Top banner "You are offline — changes will not be saved" (attendance sheet keeps local draft in `localStorage` and offers "Restore unsaved draft"). |

Motion: 150–200 ms ease-out for hovers and expanding panels; 120 ms fade for route transitions; KPI numbers count up over 400 ms on first render; skeleton shimmer 1.4 s; all disabled when `prefers-reduced-motion`.

### 2.6 Brand

Wordmark "PBPS MIS" in Plus Jakarta Sans 700 with the three-line terrace motif as a logo mark (teal / sage / amber). Sub-label "Monitoring & Verification". No external logos are required; leave a slot in Settings for an uploaded programme logo used in PDF reports.

---

## PART 3 — APP SHELL AND SHARED PATTERNS

### 3.1 Layout

- **Left sidebar** (240 px, collapsible to 64 px icons; on mobile a drawer): logo; project switcher (if the user has more than one project); navigation groups (below); bottom: Help, collapse toggle.
- **Top bar** (56 px): breadcrumb trail; **global search** (⌘K / Ctrl+K command palette: trainees by name/ID/phone, providers, classes, grievance refs, indicators; results grouped, keyboard navigable, recent searches); **notification bell** with unread count (opens a popover with the latest 10 + "View all"); **"What's due" button** for TP roles (count of overdue + due-this-week items); user menu (profile, theme, sign out).
- **Content area:** max width 1440 px for reading pages; full width for grids (attendance sheet, KPI matrix).
- **Page header pattern:** terrace motif + H1 title + one-line description; right side: primary action(s); below: optional tabs; then filter bar.
- **Filter bar pattern:** horizontally arranged selects (Provider → Training → Site → Class cascade, each searchable), status multi-select, date range, search input; "Clear all"; filters reflected in the URL query string (shareable links); a "Saved views" menu (store per user in localStorage).

### 3.2 Navigation (shown according to permissions)

**M&E / admin / funder view**
- *Overview:* Programme dashboard · Notifications
- *Delivery:* Training providers · Trainings & classes · Trainees · Attendance · Outcomes · Activities
- *Results:* Indicators · KPI report · Verification · Grievances
- *Quality:* Duplicates · Roster changes · Data health
- *Reports:* Report centre
- *Admin:* Users & access · Project settings · Master data · Mail & reminders · Audit log

**TP view**
- *Home:* My dashboard (to-do) · Notifications
- *My programme:* Classes · Trainees · Attendance · Outcome reports · Activities & evidence · Grievances
- *Results:* My indicators & targets · Verification results (finalised only)
- *Organisation:* Staff (tp_admin only) · Provider profile

**Verification team view**
- My work (enumerator) · Review queue (supervisor) · Runs · Plans · Results

### 3.3 Shared components to build first

| Component | Purpose / behaviour |
|---|---|
| `DataTable` | Server-side table (props: `queryKey`, `fetcher`, columns, filters, row actions, bulk actions, export) with skeleton/empty/error states built in |
| `FilterBar` + `ScopePicker` | Cascading Provider → Training → Site → Class picker respecting the user's scope |
| `KpiCard`, `KpiGrid` | As in §2.4, with target bar and status |
| `StatusBadge` | Maps status keys to colours/icons (§2.4) |
| `TargetBar` | Horizontal bar with value fill and target tick; shows "92.1 % vs target 90 %" |
| `ProgressRing` | Circular % (coverage, completion of verification) |
| `TrendSparkline` | 30-day mini line chart for KPI cards |
| `CalendarMonth` | Month calendar with day kinds (session = teal dot, holiday = amber, breakdown = striped grey, exempt = light hatch, non-session = blank); used in class schedule & attendance |
| `AttendanceGrid` | Trainees × session dates grid; cells P/A/E; keyboard (arrows, P/A/E keys, Space toggles), "mark all present" per date, sticky first column, dirty-cell highlight |
| `FileDropzone` | Drag & drop with type/size validation, upload progress, cancel |
| `ImportPreviewTable` | Rows with per-cell error highlighting, filter by issue, inline cell editing with instant re-validation, duplicate match panel |
| `JobProgress` | §2.5 |
| `Timeline` | Vertical event list (trainee history, case history, report versions) |
| `EmptyState`, `ErrorState`, `SkeletonX` | §2.5 |
| `ConfirmDialog` | With optional "type to confirm" |
| `PersonName` | Renders "First Father Grandfather" + ID in mono + copy button |
| `PhoneText` | Shows `0911 22 33 44` format, click-to-copy (never `tel:` links on desktop) |
| `DateText` | `12 May 2026`; tooltip with ISO; optional Ethiopian date display |
| `Can`, `RequirePermission` | Permission gates |
| `WhatsDuePanel` | TP to-do aggregator (attendance days missing, reports due, obligations due, grievances to answer, roster freeze upcoming) |
| `ChecklistCard` | Onboarding/setup checklist with done/pending items and deep links |
| `DiffView` | Before/after values (roster change requests, audit) |

### 3.4 Validation rules shared by forms (must match the server)

- **Phone (Ethiopian mobile):** accept `0911223344`, `911223344`, `+251911223344`, `251911223344`, also `07…`/`7…` (Safaricom); spaces/dashes allowed; reject scientific notation (`9.11E+08`) with message *"This looks like an Excel number format. Format the column as Text and re-enter the number."*; display normalised `0911 22 33 44`.
- **Dates:** date pickers output ISO; typed dates in forms use **DD/MM/YYYY** with live parsing feedback ("= 15 May 2026"). Never guess day vs month: if ambiguous typed text like `05/04/2026` is entered, show both readings and ask.
- **Ethiopian date of birth:** three selects (Day 1–30, Month 1–13 with Amharic month names shown in brackets, Year) — month 13 (Pagume) allows days 1–5 (6 in leap years); show the Gregorian equivalent and computed age underneath; warn if it differs from the typed age by more than 1 year.
- **Names:** letters (Latin or Ge'ez), spaces, apostrophe, hyphen; 1–60 characters; trimmed.
- **Email:** standard; lower-cased.
- **Enums:** always selects/radio groups (never free text) using the official form options (Part 5.5.3).
- **Booleans:** Yes/No radio (never a checkbox that can mean "not answered").

---

## PART 4 — DATA CONTRACT AND MOCK LAYER

### 4.1 API conventions (mock exactly this)

- Base `/api/v2`; project-scoped resources under `/api/v2/projects/:projectId/...`.
- IDs are **strings**. Dates `YYYY-MM-DD`; timestamps ISO UTC.
- Lists: `GET …?page=1&pageSize=25&sort=name:asc&<filters>` → `{ items: T[], page, pageSize, total }`.
- Errors: HTTP status + body `{ type, title, status, code, detail, fieldErrors?: [{ path, code, message }], requestId }`.
- Long jobs: `POST` returns `202 { jobId }`; `GET /projects/:p/jobs/:jobId` → `{ id, status: 'queued'|'running'|'done'|'failed', progressPct, progressNote, result?, error? }`.
- Auth: cookie session; `GET /auth/me` → `{ user, memberships: [{ projectId, projectCode, projectTitle, roleCode, roleLabel, providerId?, providerName? }] }`; `GET /projects/:p/access/me` → `{ roleCode, permissions: string[], providerId?, scopes: [{ type: 'site'|'class', id, label }] }`.

### 4.2 Fictional fixtures (MSW)

- Project `PBPS` — "Performance Based Payment Scheme", contract window 2026-04-01 → 2027-03-31.
- Locations: Addis Ababa (AA), Hossana (HO), Dessie (DE).
- Providers (fictional): **Abay Digital Academy (ABA)** target 1,000, Intermediate, 3 sites; **Lalibela Tech Institute (LTI)** target 800, Advanced, Addis only; **Entoto Skills Hub (ESH)** target 500, Basic, 3 sites; **Simien Coding School (SCS)** target 400, Advanced; **Tana Youth Works (TYW)** target 250, Intermediate.
- Trainings per provider 2–5 (e.g. "Full-Stack Web Development", "Graphics & Multimedia Design", "Cybersecurity Essentials", "Digital Marketing", "Cloud & Network Infrastructure").
- Classes: 4–20 per training with codes like `AA-MWF-1`, `HO-TTS-2`, shifts morning/afternoon, weekdays sets (Mon/Wed/Fri, Tue/Thu/Sat, Mon–Fri, Mon–Sat).
- ~3,000 trainees with fictional Ethiopian names (e.g. Hana Tesfaye Alemu, Dawit Bekele Gebre, Meron Asfaw Kebede, Yonas Haile Tadesse, Selam Girma Wolde), ages 18–29, 62 % male, phones `09xxxxxxxx`.
- Attendance rates 70–98 %, ~8 % at-risk; dropouts ~8 %; completions ~85 % of non-dropouts for ended classes.
- 19 indicators (Part 5.9), targets per provider varying ±5 points around defaults.
- 3 verification runs (one in field, one under review, one finalised with Wilson CI).
- 120 grievance cases across categories/statuses; notifications per role.

### 4.3 Core types (keep these names)

```ts
type Id = string; type DateOnly = string; type Iso = string;
type RosterStatus = 'active'|'reserve'|'withdrawn'|'transferred';
type Tri = 'pending'|'no'|'yes'|'not_applicable';
interface Provider { id: Id; code: string; name: string; status: 'onboarding'|'active'|'suspended'|'closed';
  contractTarget: number; registered: number; activeCount: number; reserveCount: number; maxRegistration: number;
  notificationEmail?: string; replyToEmail?: string; registrationWindow?: { from?: DateOnly; until?: DateOnly; closedAt?: Iso } }
interface Training { id: Id; providerId: Id; title: string; programmeName?: string; level: 'basic'|'intermediate'|'advanced';
  durationMonths: 3|4|6; plannedStart: DateOnly; plannedEnd: DateOnly; sitesCount: number; classesCount: number; traineesCount: number }
interface Site { id: Id; trainingId: Id; location: { id: Id; code: string; name: string }; displayName: string; classesCount: number }
interface TrainingClass { id: Id; siteId: Id; trainingId: Id; providerId: Id; code: string; name: string;
  shift?: 'morning'|'afternoon'|'evening'|'full_day'|'weekend'|'other'; venue?: string; weekdays: number[];
  plannedStart: DateOnly; plannedEnd: DateOnly; actualStart?: DateOnly; effectiveStart: DateOnly; effectiveEnd: DateOnly;
  status: 'planned'|'ongoing'|'ended'|'cancelled'; trackedTrainees: number; sessionsTotal: number; sessionsToDate: number;
  sessionsMissing: number; rosterFrozenAt?: Iso }
interface TraineeListItem { id: Id; code: string; fullName: string; sex: 'male'|'female'; age: number; phone: string;
  providerCode: string; className: string; siteName: string; rosterStatus: RosterStatus;
  eligibility: 'eligible'|'not_eligible'|'unknown'; attendanceRate?: number; dropout: 'pending'|'no'|'yes'; completion: Tri }
interface TraineeStatus { attendance: { present: number; excused: number; absent: number; sessionsToDate: number; sessionsTotal: number;
  rateToDate?: number; rateFinal?: number; maxReachable?: number }; systemDropoutRisk: boolean; systemDropoutFinal: boolean;
  dropout: { status: 'pending'|'no'|'yes'; date?: DateOnly; reason?: string; source?: string }; completion: { status: Tri; date?: DateOnly; source?: string };
  certification: { status: Tri; date?: DateOnly }; jobLinkage: Tri; decentJobM1: Tri; decentJobM2: Tri; locality: Tri; retention3m: Tri }
interface KpiValue { indicatorCode: string; providerId?: Id; layer: 'monitoring'|'verified'; value?: number; numerator?: number;
  denominator?: number; target?: number; targetSource: 'provider'|'project_default'|'definition'|'none';
  status: 'met'|'not_met'|'no_data'|'not_applicable'; asOf: DateOnly; computedAt: Iso; detail?: Record<string, unknown> }
interface Obligation { id: Id; providerId: Id; activity: { code: string; name: string; scope: 'provider'|'training'|'site'|'class' };
  scopeLabel: string; openDate: DateOnly; dueDate: DateOnly; closeDate: DateOnly;
  status: 'upcoming'|'open'|'submitted'|'approved'|'returned'|'overdue'|'waived'; latestSubmissionId?: Id }
interface OutcomeReport { id: Id; classId: Id; reportType: 'dropout'|'completion'|'certification'|'job_linkage'|'decent_job'|'locality_compliant'|'job_retention_3m';
  stageKey?: string; version: number; status: 'draft'|'ready'|'accepted'|'returned'|'superseded'|'discarded';
  rowsTotal: number; yesCount: number; noCount: number; naCount: number; submittedAt?: Iso; submittedBy?: string; reviewNote?: string }
interface VerificationRun { id: Id; indicatorCode: string; providerId: Id; providerName: string; period: string; stageKey?: string; tier: 1|2;
  status: 'planned'|'drawn'|'in_field'|'under_review'|'finalised'|'cancelled'; populationCount: number; sampleSize: number;
  counts: { primary: number; reserve: number; completed: number; definite: number; success: number; unreachable: number; refused: number; inconclusive: number };
  result?: { rate: number; ciLow: number; ciHigh: number; target: number; pathway: 'clear_pass'|'clear_fail'|'inconclusive' } }
interface GrievanceCase { id: Id; ref: string; providerName: string; category: 'complaint'|'suggestion'|'question'|'appreciation';
  subject: string; status: 'new'|'acknowledged'|'in_progress'|'responded'|'resolved'|'closed'|'escalated'|'reopened';
  submittedAt: Iso; dueAt: Iso; firstResponseAt?: Iso; overdue: boolean; satisfaction?: number }
interface AppNotification { id: Id; type: string; severity: 'info'|'warning'|'critical'; title: string; body?: string; link?: string; createdAt: Iso; readAt?: Iso }
```

---

## PART 5 — PAGES

> Format for every page: **Route · Who · Purpose · Layout · Data (API) · Actions · States · Rules**. "States" lists only what is page-specific — the universal states of §2.5 always apply.

### 5.1 Public pages (no login)

#### 5.1.1 Landing — `/`
- **Who:** anyone.
- **Purpose:** explain the programme and route visitors to Sign in or Submit feedback.
- **Layout:** full-width hero on `--background` with the terrace motif drawn large and faint on the right; headline "Skills for jobs — monitored, verified, transparent"; two CTAs: **Sign in** (primary) and **Submit feedback or a complaint** (secondary). Below: 4 public figures cards (Providers, Trainees registered, Female share, Trainings) from `GET /public/stats` with count-up animation; a short "How it works" 4-step strip (Register → Train & attend → Report outcomes → Independent verification); footer with programme name, data-protection notice and contact email shown as text.
- **States:** stats skeleton; if stats fail, hide the stats row (never block the page).

#### 5.1.2 Sign in — `/login`
- **Purpose:** email + password login.
- **Layout:** split screen: left panel (teal gradient `#0E5E6F → #0B4F5D` with the terrace motif and a quote "Every trainee counted, every result verified"), right panel card with form.
- **Fields:** Email, Password (show/hide), "Remember this device" (extends refresh session), **Sign in** button, links "Forgot password?" and "Submit feedback (no account needed)".
- **Data:** `POST /auth/login` → `{status:'ok'}` → go to `/projects` (or straight to the only project) / `{status:'2fa_required', challengeId}` → `/verify`.
- **Errors:** wrong credentials (generic message, no hint which field); `ACCOUNT_LOCKED` → show countdown "Try again in 12:40"; `ACCOUNT_DISABLED` → contact admin; rate-limited → "Too many attempts".
- **States:** button loading; Caps-Lock warning on the password field.

#### 5.1.3 Two-step verification — `/verify`
- Six single-digit inputs (auto-advance, paste fills all), "Use authenticator app / email code" toggle depending on the method, **Verify**, "Resend code" (disabled with 60 s countdown), "Back to sign in". Errors: invalid / expired code.

#### 5.1.4 Forgot / Reset password — `/forgot-password`, `/reset-password?token=`
- Forgot: email field → always shows "If an account exists, we sent a link" (no account enumeration).
- Reset: new password + confirm with a strength meter (≥ 10 chars, not common, not equal to email) and live checklist; success → sign in.

#### 5.1.5 Accept invitation — `/invite?token=`
- Shows "You have been invited to PBPS MIS as *TP site lead* for *Abay Digital Academy*"; fields: full name (pre-filled), new password + confirm; optional TOTP setup prompt for roles that require 2FA. Expired token → message with "Ask your administrator to resend".

#### 5.1.6 Forced password change — `/change-password`
- Shown after first login with a temporary state; same fields as reset plus current password if applicable; cannot navigate away.

#### 5.1.7 Public feedback / grievance form — `/feedback/new`
- **Purpose:** trainees and the public submit complaints, suggestions, questions or appreciation about a training provider.
- **Layout:** single centred card (max 720 px), 3 short steps with a step indicator: **1. About** (Training provider select (searchable), Category as 4 large selectable tiles with icons: Complaint ⚠, Suggestion 💡-style icon via lucide `Lightbulb`, Question `HelpCircle`, Appreciation `Heart`), **2. Details** (Subject 3–200 chars with counter, Description 3–4,000 chars with counter, optional Region select), **3. Contact** (Name, Email (required — replies are sent there), Phone (optional)). Review summary → **Submit**.
- **Data:** `GET /public/projects/:p/providers`, `POST /public/projects/:p/grievances` → `{ ref }`.
- **Success screen:** large reference number `GRM-2026-000123` with copy button, expected response date ("by 19 May 2026"), "Check status later" link, and a note that an acknowledgement email was sent.
- **Rules:** client-side markup rejection mirrors the server (no `<tags>`), rate-limit message friendly; works perfectly on mobile.

#### 5.1.8 Grievance status lookup — `/feedback/status`
- Fields: Reference number + email → shows status timeline (Submitted → Acknowledged → Responded → Resolved), due date, and the public replies (internal notes never shown). If resolved: "Rate the response" link.

#### 5.1.9 Satisfaction survey — `/feedback/rate?ref=&token=`
- 1–5 stars (large tap targets), optional comment, submit → thank-you. Token single-use.

#### 5.1.10 Error pages — `/403`, `/404`, `/maintenance`
- Friendly illustration, explanation, primary button (Go to dashboard / Sign in), request id where relevant. Maintenance page shows planned end time.

### 5.2 Project selection

#### 5.2.1 Project picker — `/projects`
- **Who:** users with more than one project (auto-skip when only one).
- Cards per project: code, title, my role label, provider name (TP users), quick stats (trainees, providers), "Open". Admins see **New project**.

#### 5.2.2 Create / edit project — `/projects/new`, `/p/:pid/settings/project` (admin)
- Sections: Identity (code, title, donor, sector, description, start/end dates), Policies (over-enrolment %, attendance threshold %, exempt days from class start, late attendance days, grievance SLA days, roster freeze offset days, roster policy: *tracked equally* / *replacement window* with window days), Security (roles requiring 2FA). Each policy has a help tooltip explaining its effect. On create: indicators (19) and default reminder rules are seeded automatically; show a confirmation summary.

### 5.3 Dashboards

#### 5.3.1 Programme dashboard — `/p/:pid/dashboard` (M&E, admin, funder, verification)
- **Purpose:** the state of the programme in one screen, with drill-down.
- **Layout (top → bottom):**
  1. Greeting row: "Good morning, Selamawit" + date + "Data as of 07:30 today" + **Recompute** (M&E only, shows JobProgress inline).
  2. **Headline KPI grid** (4 per row): Registered vs contract target (with over-enrolment headroom), Attendance rate, Dropout rate (lower is better), Completion rate, Certification rate, Job linkage, Decent job (60 days), Retention 3 months, Eligibility, Timely grievance resolution. Each card: monitoring value, verified value (if any, with ShieldCheck), project target, status, sparkline (30 days).
  3. **Providers vs targets matrix** (heat-table): rows = providers, columns = key indicators; cells coloured on the diverging palette by distance to *that provider's* target; click a cell → indicator detail filtered to provider.
  4. Two charts side by side: *Attendance trend* (line, 12 weeks, one line per provider + project dashed) and *Trainee funnel* (registered → active at mid-course → completed → certified → linked → employed) as a horizontal funnel bar.
  5. Three panels: **Obligations compliance** (stacked bar per provider: approved/submitted/open/overdue), **Grievances** (open by age bucket, SLA % donut, link to list), **Verification progress** (runs in field/under review/finalised; per-run progress rings).
  6. **Data health** strip: score per provider (0–100) with top 3 issue types.
- **Filters:** provider multi-select, training level, location, sex (applies to charts that support disaggregation).
- **Data:** `GET /projects/:p/dashboard/programme?filters` (single call returning all widget data from snapshots).
- **States:** each widget has its own skeleton/error so one failure doesn't blank the page; funder view hides personal-data links.

#### 5.3.2 Provider dashboard (TP home) — `/p/:pid/home` (TP roles; also reachable by M&E via provider page "View as provider dashboard")
- **Purpose:** "what do I need to do today" + my results vs my targets.
- **Layout:**
  1. Header: provider name + logo slot, contract target, registered / max registration progress bar, registration window status chip ("Open until 30 May" / "Closed").
  2. **To-do panel (`WhatsDuePanel`)** — prioritised list with counts and deep links:
     - Attendance: "3 classes have missing days (7 sessions)" → attendance to-do;
     - Outcome reports due: "Dropout report due for HO-TTS-2 (class ended 4 days ago)";
     - Activity obligations: overdue (red), due in 7 days (amber), open;
     - Grievances: new / due soon / overdue;
     - Roster: "Roster of AA-MWF-1 freezes in 2 days — confirm your trainee list";
     - Returned items: activity submissions or outcome reports returned for correction;
     - Setup checklist (until complete): classes scheduled, staff invited, trainees imported.
  3. **My KPIs vs my targets** — KPI cards (monitoring; verified results appear only after finalisation).
  4. **Class progress table:** class, site, dates, status, trainees, attendance rate, at-risk count, sessions missing, next report due — row click → class detail.
  5. **At-risk trainees** (top 10 by lowest max-reachable attendance) with link to dropout monitoring.
- **Data:** `GET /projects/:p/dashboard/provider/:providerId`.
- **Rules:** scoped staff see only their sites/classes; attendance clerks see only the attendance to-do and class table.

### 5.4 Training providers

#### 5.4.1 Providers list — `/p/:pid/providers` (M&E, admin, funder, verification)
- Table columns: Code (mono), Name, Status badge, Levels, Sites (chips AA/HO/DE), Contract target, Registered (active + reserve, with mini bar vs max registration), Classes (ongoing/ended), Attendance %, Completion % vs target, Open obligations (overdue in red), Open grievances, Onboarding checklist % (for onboarding providers).
- Filters: status, level, location, "has overdue items". Actions: **New provider** (opens onboarding wizard), export.
- Row click → provider detail.

#### 5.4.2 Onboarding wizard — `/p/:pid/providers/new` (M&E/admin)
- 7-step wizard with left step rail, progress saved after every step (provider created in `onboarding` status at step 1):
  1. **Profile** — code (2–10 uppercase letters, unique), name, legal name, contact person, contact phone, **notification email** (where system emails go), **reply-to email** (shown to complainants), "requires external beneficiary ID" toggle + label (e.g. "Qiyas ID").
  2. **Contract** — contract number, signed date, start/end dates, **target trainees**, levels, sites (locations), upload signed contract (PDF). Shows computed *max registration = target × (1 + over-enrolment %)*.
  3. **Targets** — table of all 19 indicators with the project default pre-filled and an editable provider target per indicator (comparator shown: ≥ or ≤), effective-from date, note; "Reset to defaults".
  4. **Organisation admin** — invite by email (name, email) → sends an invitation link.
  5. **Trainings** — add one or more trainings (title, programme, level, duration auto from level, planned start/end, sites) — optional here (TP may do it).
  6. **Registration window** — open from / until dates.
  7. **Review & activate** — checklist of everything above (✓ / missing with "Fix" links); **Activate** generates the provider's activity obligations (show a preview list of obligations that will be created with their due dates before confirming).

#### 5.4.3 Provider detail — `/p/:pid/providers/:id`
- Header: name, code, status badge, levels, sites, contract target, registered/max, registration window chip, actions (Edit, Suspend/Activate, Open/close registration, Grant late registration window (date + reason)).
- **Tabs:**
  - **Overview** — KPI cards vs this provider's targets (monitoring + verified), class progress summary, recent activity feed.
  - **Contract** — current contract card + version history (amendments) with documents; "Amend contract" (creates a new version, requires reason).
  - **Targets** — per-indicator target table with history (effective periods); edit creates a new effective-dated target (never overwrites); shows which value applied on any given date.
  - **Staff** — members with role, scopes (sites/classes chips), status, last login; Invite staff (email, role, scopes picker), change role/scopes, deactivate. Visible to tp_admin for own provider.
  - **Trainings & classes** — tree: Training → Sites → Classes with dates, weekdays, trainees, status.
  - **Trainees** — embedded trainees table filtered to this provider.
  - **Obligations** — this provider's obligations timeline (Gantt-like strip by month) + list.
  - **Grievances** — cases for this provider + SLA stats.
  - **Data health** — findings for this provider.
  - **Settings** — notification email, reply-to email, external ID settings.

#### 5.4.4 TP: Provider profile — `/p/:pid/my-provider` (tp_admin; read-only for other TP roles)
- Same as detail but limited: profile (editable contact/notification fields), contract (read-only), targets (read-only), staff (tp_admin manages).

### 5.5 Delivery: trainings, sites, classes

#### 5.5.1 Trainings list — `/p/:pid/trainings`
- Cards or table toggle. Card: title, provider, level badge (Basic = sage, Intermediate = teal, Advanced = indigo), duration, planned window, sites chips, classes count (ongoing/ended), trainees count, attendance %, completion %.
- Filters: provider, level, status, location. Actions: **New training** (M&E/TP admin).

#### 5.5.2 Training create / edit — `/p/:pid/trainings/new`, `/p/:pid/trainings/:id/edit`
- Fields: provider (fixed for TP), title, programme name (optional), level, duration (auto by level, editable 3/4/6), planned start & end (end suggested = start + duration), default weekdays (7 toggle chips Mon…Sun), allowed sites (location multi-select), description.
- Inline validation: end ≥ start; duration mismatch warning.

#### 5.5.3 Training detail — `/p/:pid/trainings/:id`
- Header with key facts and actions (Edit, Add site).
- **Sites section:** one card per site (location name, display name, classes count, trainees, attendance %, next report due). Inside each card: classes table (code, name, shift, weekdays chips, start → end, status, trainees, attendance %, sessions missing, roster frozen ✓). Actions per site: **Add class**.
- Right rail: training timeline (planned window, earliest/latest class dates), breakdown requests for this training.

#### 5.5.4 Class create / edit — modal or page `/p/:pid/sites/:siteId/classes/new`
- Fields: code (unique within site; suggestion `AA-MWF-1`), name, shift (segmented: Morning / Afternoon / Evening / Full day / Weekend / Other), venue/campus, weekdays (toggle chips), planned start, planned end (suggested from duration), capacity (optional).
- **Live calendar preview** (`CalendarMonth`, 2–3 months visible, scrollable): session days teal, holidays amber with label tooltip, exempt start period hatched ("first 14 days not counted"), breakdowns striped; summary under it: "78 sessions · first counted session 11 May · ends 27 Aug". Changes to weekdays/dates update the preview instantly (`POST /classes/preview-calendar`).
- Edit of a class with attendance: past dates locked; a warning lists what will change.

#### 5.5.5 Class detail — `/p/:pid/classes/:id`
- Header: "Digital Marketing · Hossana · HS-DW-M (Morning)", status badge, dates (planned/actual), weekdays chips, trainees (active/reserve), roster status ("Frozen on 25 Apr" or "Freezes in 3 days").
- Actions: Edit, Set actual start (date picker with explanation: end date shifts by the same number of days), Request breakdown (TP), Freeze roster now (M&E).
- **Tabs:**
  - **Overview** — attendance rate, coverage ring (marks recorded vs expected), at-risk count, outcome board for this class (one chip per report type with status and due date), obligations for this class.
  - **Schedule** — full calendar (session / holiday / breakdown / exempt / non-session) with legend; list of breakdowns.
  - **Roster** — trainees table (code, name, sex, age, phone, roster status, eligibility, attendance %, dropout/completion status); roster snapshot history with "Compare with current" (`DiffView`: added/withdrawn since freeze).
  - **Attendance** — embedded `AttendanceGrid` read-only for the selected month, with link "Open attendance sheet".
  - **Outcomes** — report types with versions and statuses; open report editor.
  - **Activity** — obligations scoped to this class.

#### 5.5.6 Breakdown requests — `/p/:pid/breakdowns`
- List: training/site/class scope, dates, days affected, reason, status, requested by/at, decided by/at.
- TP: **Request breakdown** dialog (scope picker, start/end dates, reason ≥ 20 chars; preview of affected sessions and the new class end date).
- M&E: Approve / Reject with note; approval shows the effect ("Class end moves from 27 Aug to 10 Sep; 9 sessions excluded; obligations due dates shift").

### 5.6 Registration (trainees)

#### 5.6.1 Trainees list — `/p/:pid/trainees`
- **Summary strip** (from counters, instant): Registered (active / reserve), Withdrawn, Female %, Eligible %, Headroom to max registration per provider (TP sees own).
- **Table** (server-side, 25/50/100 per page): Trainee ID (mono), Full name, Sex, Age, Phone (masked unless permission), Provider (M&E), Training · Site · Class, Roster status, Eligibility badge, Attendance %, Dropout, Completion.
- **Filters:** search (name / ID / phone — any format), provider, training, site, class, roster status, eligibility, sex, age range, attendance band (< 70, 70–80, ≥ 80), dropout status, completion status.
- **Actions:** **Add trainee**, **Import trainees**, Export (job), bulk "Request withdrawal" (after freeze → creates change requests).
- **States:** "No trainees yet — import your first list" with template download link.

#### 5.6.2 Trainee detail — `/p/:pid/trainees/:id`
- Header card: full name (large), trainee ID (mono + copy), external ID (if any), status chips (Active/Reserve, Eligible / Not eligible with reasons tooltip, At risk / System dropout), provider · training · site · class (links), phone (masked by permission), age & sex.
- **Tabs:**
  - **Profile** — sections exactly as the registration form (Programme, Personal & contact, Education & background, Employment, Inclusion, Consents) in read view; **Edit** button (identity/eligibility fields locked after roster freeze with explanation "Changes need M&E approval — Request change").
  - **Attendance** — rate to date, max reachable, sessions present/excused/absent, mini calendar heatmap (session days coloured P/E/A), list of corrections.
  - **Outcomes** — status cards per outcome (Dropout, Completion, Certification, Job linkage, Decent job 30/60 days, Locality, Retention 3 months) with value, date, source, report link; history of report lines (all versions).
  - **Verification** (only roles with `verification.view_subjects`) — runs in which this trainee was sampled, status code, attempts.
  - **History** — `Timeline` of audit events (registered, edited (with diff), transferred, roster changes, outcome changes).

#### 5.6.3 Trainee form (add / edit) — `/p/:pid/trainees/new`, `/p/:pid/trainees/:id/edit`
- **Layout:** sectioned form with a sticky section index on the left and a sticky footer (Cancel / **Save**). Sections and fields (official registration form):
  1. **Programme** (TP fills): Training provider (fixed for TP), Training (select), Site (select, filtered), Class (select, filtered; shows weekdays & dates), External beneficiary ID (if provider requires; label from provider), Date of form completion (date picker; DD/MM/YYYY typing), Roster status (Active / Reserve, with headroom note "You can register 37 more trainees").
  2. **Personal & contact:** First name*, Father's name*, Grandfather's name*, Sex* (Male/Female segmented), Age (years)*, Date of birth (Ethiopian calendar)* (3 selects + Gregorian/age preview + consistency warning), Phone (primary)*, Alternative phone, Email, Kebele, Woreda*, Sub-city (required when region is a city administration), Region* (select), Emergency contact name*, Emergency contact phone*.
  3. **Education & background:** Highest education* (No formal education · Primary (Grades 1–8) · Secondary (Grades 9–12) · High school dropout · TVET Certificate Level I–IV · Diploma · Bachelor's Degree · Above Bachelor's · Short-term Training), Previously participated in skills training?* (Yes/No) → if Yes: Type/field*, Completed?* → if Yes: Year completed*.
  4. **Employment (last month):** Status* (Not currently working · Working occasionally · Working fewer hours than desired · Working full-time for an employer · Self-employed / own business) → if not "Not currently working": Income sufficient?*, Skill usage* (Fully / Partially / Not at all); Post-training plan* (Wage employment / Self-employment / Other → specify*).
  5. **Inclusion:** multi-select chips (Person with disability · IDP · Returnee · Low-income household · None of the above · Prefer not to say — the last two are exclusive) → if PWD: Disability type* (Hearing · Visual · Paralysis · Prefer not to say · Other → specify*).
  6. **Consent:** four Yes/No questions (accuracy*, follow-up surveys*, employment verification contact*, image use*) with the full wording from the form.
- **Live helpers:** eligibility badge updates as you type ("Eligible" / "Not eligible: age 31 is outside 18–29"); **duplicate hint** after names + phone are filled (`POST /duplicates/check`): an amber card "Possible duplicate: Hana Tesfaye Alemu — PBPS-ABA-000211 (Abay Digital Academy, AA-MWF-1) — 96 % match: same father & grandfather name, same date of birth" with actions *View* / *This is a different person*.
- **Errors:** field-level; server `fieldErrors` mapped to fields; registration window closed → page-level banner and disabled Save.

#### 5.6.4 Import trainees wizard — `/p/:pid/trainees/import`
- **Step 1 — Target:** provider (fixed for TP), training, site; class either "per row (class code column)" or "all rows go to class …". Mode: **Import** / **Check only (no import — duplicate & quality report)**. Download template: **XLSX (recommended — with drop-downs and instructions sheet)** or CSV; template columns pre-filtered to the target.
- **Step 2 — Upload:** `FileDropzone` (CSV/XLSX, ≤ 5,000 rows, ≤ 10 MB) → upload progress → server validation job (`JobProgress`: "Reading file… Validating 1,240 rows… Checking duplicates…").
- **Step 3 — Review:** summary cards (Total rows, Valid ✓, Errors ✗, Warnings ⚠, Possible duplicates ⧉); tabs to filter rows by issue; `ImportPreviewTable` with:
  - cells in error outlined red with tooltip message (e.g. "Phone looks like Excel scientific notation (9.11E+08)…", "Region 'Adiss ababa' recognised as Addis Ababa" (warning, auto-fixed), "Date 05/04/2026 is ambiguous — choose 5 April or 4 May");
  - **inline editing** of any cell (re-validated immediately; row turns green when fixed);
  - duplicate rows show a side panel with the matching existing trainee(s), score and reasons, and the decision buttons *Skip this row* / *Different person (reason)*;
  - header problems (missing required column, unknown columns) shown above the table;
  - capacity check: "This import would bring you to 1,162 of 1,150 allowed — remove 12 rows or mark them as reserve within the limit" (blocking).
- **Step 4 — Confirm:** "Import 1,198 trainees (42 skipped)". **Import** is enabled only when errors = 0 and all duplicates are decided.
- **Step 5 — Result:** created count, link to the new trainees list filtered by this import, downloadable result file (row → new trainee ID), and a reminder of the roster freeze date.
- **Import history** (tab on the trainees page): date, user, file name, rows, created, status, download original/result.

#### 5.6.5 Roster changes — `/p/:pid/roster-changes`
- **TP view:** "Request a change" (types: add trainee after freeze, withdraw, transfer to another class, correct identity/eligibility data) → form with reason and evidence upload; list of my requests with status.
- **M&E view:** queue (oldest first) with `DiffView` of the requested change, roster impact (e.g. "Class AA-MWF-1 tracked trainees 39 → 38"), Approve / Reject with note; bulk approve for identical simple requests.

#### 5.6.6 Duplicate review — `/p/:pid/duplicates` (M&E, data-quality)
- Queue of candidate pairs sorted by score: side-by-side comparison cards (name parts with similarity %, sex, age, DOB, phones, provider, class, registration date, attendance rate) with highlighted matching fields; decision: **Confirmed duplicate** (choose record to keep → creates a withdrawal of the other, reason "duplicate"), **Not a duplicate** (note required), **Skip**. Filters: risk (high/medium), provider, cross-provider only, status. Button **Run full scan** (job).

### 5.7 Attendance

#### 5.7.1 Attendance home (to-do) — `/p/:pid/attendance`
- **Who:** TP roles (own scope), M&E (all).
- **Layout:** KPI strip (attendance rate to date, capture coverage %, sessions missing, at-risk trainees); **"Days to record"** list grouped by class: class name, missing session dates as chips (oldest first, red when older than the late-entry limit of 7 days), **Record** button per date; then a classes table (class, site, sessions to date, submitted, missing, rate).
- **Data:** `GET /projects/:p/attendance/todo`, `GET …/attendance/summary`.
- **Empty:** "All attendance is up to date 🎉" (use lucide `PartyPopper`).

#### 5.7.2 Class attendance sheet — `/p/:pid/classes/:id/attendance?date=YYYY-MM-DD`
- **Layout:** header with class name, date picker restricted to session days (non-session days disabled with tooltip reason: holiday "Eid al-Adha", breakdown, exempt start period, not a class day, future); left/right arrows to move between session days.
- **Single-date mode (default):** list of trainees (ID, name, roster badge) with a 3-state segmented control per row: **Present / Absent / Excused** (excused requires a reason select: illness, official leave, family emergency, other); "Mark all present" button; counters at top (P / A / E / not marked); **Submit attendance for 12 May** (disabled until every trainee is marked).
- **Grid mode:** `AttendanceGrid` trainees × session dates of the month; submitted dates read-only (lock icon); unsubmitted dates editable; keyboard shortcuts shown in a help popover.
- **After submit:** the date shows "Submitted by Meron, 12 May 09:14"; marks are read-only; each cell has "Request correction" (from → to, reason) which goes to M&E.
- **Rules/messages:** late entry after 7 days → "This date is older than 7 days. Submit with a justification" (opens correction-style justification); already submitted → shows the submitted sheet; offline draft saved locally.
- **Mobile:** single-date mode with large touch targets.

#### 5.7.3 Attendance import — `/p/:pid/classes/:id/attendance/import`
- Download template for a date range (rows = trainees, columns = valid session dates); upload → preview with cell errors (unknown trainee, invalid value, non-session date, already submitted) → commit as sessions. Same wizard pattern as trainee import.

#### 5.7.4 Corrections queue — `/p/:pid/attendance/corrections` (M&E)
- Table: class, date, trainee, from → to, reason, requested by/at, age; Approve / Reject (note). TP sees own requests with status.

#### 5.7.5 Attendance insights — `/p/:pid/attendance/insights`
- Charts: rate by provider (bar vs 80 % line), weekly trend, rate by site and by sex, coverage by class (table with progress rings); filters scope cascade + date range. Export.

#### 5.7.6 Dropout monitoring — `/p/:pid/attendance/dropout-monitoring`
- **Summary cards:** At risk (ongoing classes), System-final dropouts (class ended, < 80 %), TP-reported dropouts, Missing from TP dropout report, Effective dropout rate vs target (with "buffer absorbs N dropouts" note per provider).
- **Table:** trainee, class, attendance to date, max reachable %, final %, flags (at risk / system final / TP reported), reason, last attended date. Filters: provider, training, class, flag.
- **Reason breakdown** chart (voluntary withdrawal, health, economic, migration, found a job, low attendance, dismissal, other).
- Row click → trainee attendance tab.

### 5.8 Outcomes

#### 5.8.1 Outcomes board — `/p/:pid/outcomes`
- **Purpose:** for every class, which outcome reports are due, submitted, accepted or returned.
- **Layout:** matrix — rows = classes (grouped by training/site, filterable), columns = report types in order (Dropout → Completion → Certification → Job linkage → Decent job 30 d → Decent job 60 d → Locality → Retention 3 m). Each cell is a status chip: *Not yet due* (grey, shows due date on hover), *Due* (amber, days since due), *Overdue* (red), *Accepted* (green, Y/N counts), *Returned* (warning), *Blocked* (lock icon with reason: "attendance incomplete (3 sessions)", "dropout report not accepted", "class not ended"). Clicking a cell opens the report editor or the accepted report.
- Top summary: reports due this week, overdue, returned, awaiting M&E review.
- **Data:** `GET /projects/:p/outcome-reports?…` + class outcome summaries — must load fast (no KPI engine calls).

#### 5.8.2 Report editor — `/p/:pid/classes/:id/outcomes/:type/new` (TP)
- **Header:** report type, class, stage (for decent job), gates checklist (✓ class ended · ✓ attendance complete · ✓ dropout report accepted).
- **Two ways to fill (tabs):**
  - **On screen** — roster table of all applicable trainees (dropout: everyone tracked; completion: everyone except dropouts; certification/job linkage/decent job: completers; locality/retention: decent-job yes). Per row: **Yes / No** toggle (required), and the type-specific fields appearing for Yes or No (dropout: date + reason select + note; completion: completion date or non-completion reason; certification: date + certificate number; job linkage: date, type, employer; decent job: employment type, employer, job title, start date, monthly income, criteria checkboxes; locality: workplace location, distance band; retention: still employed, same employer, gap days). System-final dropouts are pre-set to **Yes** and locked with tooltip "Attendance below 80 % at class end — correct attendance instead if this is wrong". Bulk actions: "Set all remaining to Yes/No", fill a date for selected rows.
  - **Upload file** — download pre-filled template (XLSX/CSV), upload, preview with errors (same preview table pattern), fix inline.
- **Footer:** counts (Yes / No / not filled), **Validate**, **Submit report**. For a resubmission: "Reason for change" required and a notice if M&E approval is needed.
- **Result:** accepted instantly (statuses updated) or validation errors listed; never partially saved.

#### 5.8.3 Report detail & history — `/p/:pid/outcome-reports/:id`
- Version selector (v1 superseded, v2 accepted…), summary (Yes/No/NA), lines table with filters, diff between versions (changed lines highlighted), source file download, review notes; M&E actions: **Return for correction** (reason), **Approve resubmission**.

#### 5.8.4 Resubmission approvals — `/p/:pid/outcomes/approvals` (M&E)
- Queue of pending resubmissions with reason, diff summary ("12 lines changed: 9 No→Yes"), verification impact warning ("A verification run has sampled this class"), Approve / Reject.

#### 5.8.5 Outcome status explorer — `/p/:pid/outcomes/status`
- Trainee-level table of current statuses (one row per trainee, one column per outcome) with filters per outcome value; export. Used by M&E to answer "who are the non-completers in HO classes".

### 5.9 Indicators and targets

#### 5.9.1 Indicator registry — `/p/:pid/indicators`
- Cards or table of the **19 protocol indicators**: protocol no., name, level (trainee / provider), purpose (monitoring / verification / both), unit, direction, default target, verification method, current project value vs target (status badge). Filter by purpose/level.
  1 TPs that signed a contract · 2 TPs with approved inception report · 3 Registered/enrolled trainees · 4 % enrolled meeting eligibility · 5 TPs with LMDA-based curriculum · 6 TPs that held orientation sessions · 7 TPs with pre-training evaluation report · 8 TPs that delivered full duration · 9 Attendance rate · 10 Dropout rate · 11 Completion rate · 12 Certification rate · 13 TPs with post-training assessment report · 14 Job linkage support within 60 days · 15 Decent job within 2 months · 16 Retention ≥ 3 months · 17 TPs with structured post-placement support · 18 Locality-compliant placements · 19 Timely grievance resolution.

#### 5.9.2 Indicator detail — `/p/:pid/indicators/:code`
- **Protocol card** (read view, print-friendly): operational definition, data sources & methods, frequency, method of computation (numerator, denominator, formula rendered nicely), disaggregations, target/threshold, purpose, verification method, payment linkage, version & effective date.
- **Results:** table providers × (monitoring value, verified value, target, status, numerator/denominator, notes like "buffer absorbs 12 dropouts", "capped at contract target"); project total row. Trend chart (daily snapshots). Disaggregation tabs (sex, location, level, age group).
- **Targets:** per-provider target list with history; **Edit targets** (M&E).
- **Versions:** list of definition versions with change notes; **Propose new version** (M&E) → draft → approve.

#### 5.9.3 Indicator editor — `/p/:pid/indicators/:code/versions/new` (M&E)
- Form with all protocol fields (rich text for definitions), numerator & denominator metric selects (from `GET /metrics`, each with description), direction, comparator, default target, disaggregations multi-select, verification method; live **preview** of the computed values per provider using the draft definition.

#### 5.9.4 Target management — `/p/:pid/targets` (M&E)
- Spreadsheet-like grid: rows = providers, columns = indicators, cells = current target (blank = uses default, shown in grey). Editing a cell asks for effective-from date and note. Toolbar: copy defaults, import/export XLSX, view history.

#### 5.9.5 KPI report — `/p/:pid/kpi-report`
- Big matrix providers × indicators; toggle Monitoring / Verified / Both (both shows two values per cell); cell colour vs **that provider's target**; footer project totals; export PDF/XLSX/DOCX (job); "as of" date picker (historical snapshots).

### 5.10 Activities (evidence)

#### 5.10.1 Obligations (TP) — `/p/:pid/obligations`
- Views: **List** (grouped Overdue / Due this week / Open / Upcoming / Submitted / Approved) and **Calendar** (month view with obligation pills). Each item: activity name, scope (provider / class label), open → due → close dates, status badge, days left.
- Row → obligation detail.

#### 5.10.2 Obligation detail / submit — `/p/:pid/obligations/:id`
- Requirements panel (what evidence is needed, allowed file types, checklist items — e.g. inception report components (a)–(e)), due/close dates with countdown, submission versions history, reviewer feedback per checklist item (for returned submissions).
- Submit form: file dropzone (multiple), checklist ticks with optional comments, note → **Submit**. Late submissions allowed until close date (flagged); after close: "Request extension" (reason).

#### 5.10.3 Review queue (M&E) — `/p/:pid/activities/review`
- Oldest first; filters by activity/provider; each submission opens a split view: file viewer (PDF/image inline preview, others download) on the left, checklist with per-item ✓/✗ + comment on the right; decision **Approve** / **Return** (new due date) ; keyboard shortcuts for next/previous.

#### 5.10.4 Activity definitions & schedules — `/p/:pid/activities/setup` (M&E)
- Definitions table (code, name, scope, linked indicator, evidence rules, recurrence, active). Schedule editor per definition: rows of rules (applies to: all / level / duration / provider), anchor select (contract signed date, provider first class start, training planned start, site first class start, class start, class end), open offset, due offset, grace days, repeat (every N days × count), "breakdowns extend dates" toggle.
- **Preview** panel: choose a provider → list of obligations that would be generated with concrete dates (and which existing ones would change).

#### 5.10.5 Compliance matrix — `/p/:pid/activities/compliance`
- Providers × activities heat-table (approved / submitted / open / overdue / not applicable) with counts for class-scoped activities ("14/20 classes approved"); export.

### 5.11 Verification

#### 5.11.1 Verification home — `/p/:pid/verification` (verification team, M&E; funders see Results only)
- Tabs: **Runs** (table from stored counters: indicator, provider, period, stage, tier, status, sample size, progress ring (completed/sample), rate & CI when available, pathway badge), **Plans**, **Results**.
- Actions: **New run**.

#### 5.11.2 Plan editor — `/p/:pid/verification/plans/:id`
- Fields: indicator, population metric (Registered trainees / Eligible trainees / Claimed completers …), strata (location, sex), sample size method & parameters (Z, p, e, non-response factor, reserve %, min per stratum), tiering (**Single tier** / **Two-tier**), estimator (Wilson one-sided / two-sided / Clopper-Pearson / simple rate), CI z, decision rule (CI vs target / point vs target), max call attempts, questionnaire version. Live example: "For N = 1,040 → n₀ = 385, n = 281, +10 % non-response = 313, reserves 47". Versioned with effective date.

#### 5.11.3 New run wizard — `/p/:pid/verification/runs/new`
1. Indicator, provider, period, stage → **preview** population by stratum (table location × sex) and planned sample/reserves; warnings (missing locations, unknown sex, reports not yet submitted → offer "pre-report draw" with explanation).
2. Seed (auto, editable) and confirmation → draw (`JobProgress`) → run created with frozen frame.

#### 5.11.4 Run workspace — `/p/:pid/verification/runs/:id`
- Header: indicator, provider, period, tier, status stepper (Drawn → In field → Under review → Finalised), target used (provider-specific), parameters popover.
- **Tabs:**
  - **Overview** — progress rings (contacted, completed, definite), status code breakdown (V-COMP, V-NCOMP, V-UNR, V-REF, V-INC), live rate with CI bar against target line, pathway preview.
  - **Strata** — population / primary / reserve per stratum, completion per stratum.
  - **Subjects** — table (subject key, name, phone (masked unless permitted), stratum, role, enumerator, attempts, status, supervisor status); filters; bulk **Assign to enumerator**; actions: promote reserve for replaceable statuses (system suggests the next reserve in the same stratum), view responses.
  - **Fieldwork files** — Kobo export (CSV/XLSX), Kobo import (upload → preview mapping by subject key → apply).
  - **Results** — final computation, CI chart, pathway, **Tier 2** button (only for two-tier plans when inconclusive), **Finalise** (blocked with a list until all primaries are definite or replaced), report download (PDF/DOCX).

#### 5.11.5 Enumerator: My work & call screen — `/p/:pid/verification/my-work`
- Queue of assigned subjects (sorted: call-backs due, not yet called, attempt 2, attempt 3). Call screen (phone-friendly): trainee details to confirm (name, provider, training type, city, sex, phones with click-to-copy), **attempt logger** (outcome buttons: Reached / No answer / Busy / Switched off / Wrong number / Call back later + note), and when reached the **questionnaire** (protocol Q1–Q17: consent; identity confirmations with "Correct / Not correct → record actual"; attendance; completion; assessment; certificate; reasons) with skip logic; derived status shown before submit ("V-COMP — Verified completion confirmed"). After max attempts → auto V-UNR suggestion.

#### 5.11.6 Supervisor review — `/p/:pid/verification/review`
- Completed records pending approval: answers summary, derived status, attempts log; Approve / Reject (back to enumerator with note); back-check sampling flag for the data-quality officer.

#### 5.11.7 Results — `/p/:pid/verification/results`
- Finalised results per indicator × provider: verified rate, CI, target, pathway, run link, date. **TP view shows only its own finalised aggregates** (no subject lists).

### 5.12 Grievances (GRM)

#### 5.12.1 Cases list — `/p/:pid/grievances`
- KPI strip: open, due in 2 days, overdue, escalated, SLA compliance % (indicator 19), average satisfaction.
- Table: reference (mono), category icon, subject, provider, status badge, submitted, due (countdown; red when overdue), first response time, assigned to, satisfaction stars. Filters: status, category, provider, overdue only, date range, search. Saved views ("My overdue", "New today").
- **TP sees a "New" badge count in the sidebar** and new cases highlighted.

#### 5.12.2 Case detail — `/p/:pid/grievances/:id`
- Left: conversation thread (public messages and **internal notes** in a different style with a lock icon), reply composer with "Send to submitter" vs "Internal note" toggle, preview of the email ("From: Abay Digital Academy via PBPS MIS · Reply-To: feedback@aba.example"). Right panel: details (category, provider, submitter contact, region, channel), status control (Acknowledge, In progress, Responded, Resolved, Close, Reopen), SLA clock, assignment, tags, **Corrective actions** (add action with owner and due date; track done), escalation info, satisfaction result, audit timeline.

#### 5.12.3 Insights — `/p/:pid/grievances/insights`
- Charts: cases by category over time, by provider, response-time distribution, SLA compliance trend, satisfaction distribution, top recurring topics (keyword chips with counts), open corrective actions. Export.

### 5.13 Notifications

#### 5.13.1 Notification centre — `/p/:pid/notifications`
- List grouped Today / This week / Earlier; filters (type, severity, unread); mark read/unread, mark all read; each item with icon by type, title, body, time ago, deep link.

#### 5.13.2 Preferences — `/me/notifications`
- Table of notification types × channels (In-app on/off; Email: Immediate / Daily digest / Off); mandatory types shown locked; quiet hours info.

### 5.14 Reports — `/p/:pid/reports`
- **Report centre:** catalogue cards (Claimed vs verified, Provider profile, Trainee profile, Indicator summary, Grievance summary/register, Verification run/summary, Activities compliance, Attendance register, Roster export, Executive pack) each with parameters (provider, period, format PDF/DOCX/XLSX/CSV) and **Generate** → job → appears in "My recent reports" with status and download (kept 7 days).

### 5.15 Data health — `/p/:pid/data-health`
- Score per provider (0–100 gauge), findings table (check, severity, provider, entity link, message, first/last seen), filters, "Fix" deep links (e.g. to trainee edit, attendance sheet, class schedule). TP sees own findings with guidance text.

### 5.16 Administration

#### 5.16.1 Users & access — `/p/:pid/admin/users`
- Users table (name, email, role(s), provider, scopes, status, 2FA, last login); **Invite user** (email, role, provider (for TP roles), scopes); user detail: memberships, sessions (revoke), resend invite, disable/enable, reset 2FA.
- **Roles & permissions** — matrix view (roles × permissions, grouped by category) with toggles for custom roles; system roles read-only with "duplicate as custom role"; export matrix.

#### 5.16.2 Project settings — `/p/:pid/admin/settings` — policies of §5.2.2, registration master switch, roster policy.

#### 5.16.3 Master data — `/p/:pid/admin/master-data`
- Tabs: Locations (code, name, region, active), Regions & aliases (add alias → canonical), Training levels & durations, **Holidays** (year calendar view + list; adding a past holiday shows impact "3 classes, 41 marks will be excluded").

#### 5.16.4 Mail & reminders — `/p/:pid/admin/mail`
- **Mail server** (system only — host, port, security, user, password (write-only), from name/email, **Send test**); **Outbox** (queued/sent/failed with retry and error details); **Reminder rules** (rule, offsets in days as chips e.g. −2, 0, +1, repeat, severity, email on/off, enable toggle) with "what will be sent this week" preview.
- **There is no TP SMTP page** — providers only set notification and reply-to emails on their profile.

#### 5.16.5 Audit log — `/p/:pid/admin/audit`
- Filters (module, action, actor, entity, date range); rows expand to show before/after `DiffView`; **Verify integrity** (range → result "Chain intact: 12,430 events" or the first broken link); **Export bundle** (job). Legacy V1 events shown with a "V1" tag.

#### 5.16.6 Profile — `/me`
- Name, email (read-only), password change, two-step verification (set up authenticator with QR code / switch to email codes), active sessions (device, IP, last used, revoke), theme, density, notification preferences link.

---

## PART 6 — PAGES THAT MUST NOT BE BUILT (removed from V1)

| V1 page | Why it is gone | Replacement |
|---|---|---|
| TP SMTP settings | TPs could not configure SMTP | System mail + provider notification/reply-to emails |
| Phone correction | Phones validated at entry | Validators + Data health |
| Registration integrity | Unauthorised removals impossible | Roster freeze, snapshots, change requests |
| Roster duplicate check (separate tool) | Part of import | Import "Check only" mode |
| Holiday attendance audit | Holidays excluded automatically | Data health notice |
| Roster simulation | Policy documented in settings | Project settings → roster policy |
| TP mapping diagnostics | Single membership model | — |
| Date integrity check/normalise | Typed dates | Data health |

---

## PART 7 — ACCEPTANCE CHECKLIST FOR THE GENERATED UI

1. Every route above exists, is lazy-loaded and guarded by permission.
2. Every page shows skeletons on first load, keeps data during refetch, and has designed empty and error states.
3. All lists are server-paginated via the mock API with filters in the URL.
4. Forms use the shared validators (phone, DD/MM dates, Ethiopian DOB, enums, booleans) and map server `fieldErrors`.
5. Long operations use `JobProgress` (imports, exports, recompute, draws).
6. Light and dark Highland themes, WCAG AA contrast, keyboard-operable attendance grid.
7. TP users never see other providers' data, verification subjects or open runs (test with the mock TP user).
8. No component fetches data directly; all go through `src/api/*` and TanStack Query.
9. Mock users for every role (switchable in a dev-only role switcher) to review each view.
10. The UI builds without TypeScript errors (`tsc --noEmit`) and lint passes.

---

## PART 8 — END-TO-END USER JOURNEYS (build and demo these with mock data)

### J1 — M&E onboards a new provider
1. Providers → **New provider** → wizard step 1 Profile (code `TYW`, name "Tana Youth Works", notification email).
2. Step 2 Contract: target 250, signed date, upload PDF → "Max registration 287 (15 %)".
3. Step 3 Targets: change completion target 90 → 92; note "Agreed in contract annex".
4. Step 4 Invite organisation admin (email) → toast "Invitation sent".
5. Step 5 Add training "Digital Marketing" (Intermediate, 4 months, Addis Ababa + Hossana).
6. Step 6 Registration window 1–31 May.
7. Step 7 Review: checklist all green → preview of 9 obligations → **Activate** → provider status Active; redirected to provider detail.

### J2 — TP admin sets up classes and staff
1. Accepts invite → sets password → lands on TP home with the "Get started" checklist.
2. Training detail → site Hossana → **Add class** `HO-TTS-1`, Afternoon, Tue/Thu/Sat, 5 May → 5 Sep → calendar preview shows holidays and the 14-day exempt period → Save.
3. Staff → invite attendance clerk scoped to `HO-TTS-1`.

### J3 — TP imports trainees with errors and fixes them
1. Trainees → **Import** → target Digital Marketing · Hossana; class per row.
2. Upload XLSX with 120 rows → job progress → review: 112 valid, 5 errors, 6 warnings, 2 possible duplicates.
3. Fix inline: phone `9.11E+08` → retype; date `05/04/2026` → choose 5 April; region "Hosana" warning accepted (mapped to Central Ethiopia).
4. Duplicates: one "Skip row", one "Different person – twins, different DOB".
5. Commit → 119 created; result file downloaded.

### J4 — Attendance clerk records a week
1. Logs in on a phone → Attendance to-do shows 3 missing days for `HO-TTS-1`.
2. Opens oldest date → "Mark all present" → switches 2 to Absent, 1 to Excused (illness) → Submit.
3. Tries to edit a submitted day → "Request correction" → reason → M&E approves later; notification received.

### J5 — Class ends: dropout then completion reports
1. Outcomes board shows "Dropout — Due" for `HO-TTS-1`.
2. Report editor (on-screen): 2 system-final dropouts pre-set Yes (locked); TP marks 1 more Yes (reason: found a job, date); others No → Submit → Accepted.
3. Completion cell becomes "Due"; editor lists 36 trainees (dropouts excluded); 34 Yes with completion date, 2 No with reason "failed assessment" → Submit → Accepted.
4. KPI cards update within a minute ("recalculating" dot, then new values).

### J6 — Activity evidence submitted and returned
1. TP home: "Inception report due in 3 days" → obligation detail → upload PDF, tick 4 of 5 components → Submit.
2. M&E review queue → returns with comment on component (d) "trainers list missing", new due date +5 days.
3. TP gets notification → resubmits v2 → approved → indicator #2 turns Met for this provider.

### J7 — Grievance lifecycle
1. Public user submits a complaint on mobile → reference shown.
2. TP sees sidebar badge "1 new" + email → acknowledges → internal note → reply sent (email preview shows Reply-To).
3. Due date passes without resolution → reminders → escalation to M&E (status Escalated).
4. TP resolves with a corrective action → submitter rates 4 ★.

### J8 — Verification of completion
1. Supervisor: New run → completion, Abay Digital Academy, 2026-09 → preview strata → draw (seed shown).
2. Assigns subjects to 3 enumerators.
3. Enumerator: My work → calls → attempt 1 no answer → attempt 2 reached → questionnaire → derived V-COMP → submit.
4. Unreachable after 3 attempts → supervisor promotes next reserve of same stratum.
5. Supervisor approves records → Results: 91.4 % (CI 88.9–93.6) vs provider target 92 % → Inconclusive → plan is two-tier → **Tier 2** draw → final Clear pass → Finalise → report PDF; TP now sees the aggregate result.

### J9 — Funder reviews progress
1. World Bank viewer logs in → Programme dashboard → KPI report "Both" toggle → exports PDF.
2. Cannot open trainee personal data (PII hidden) and sees no edit buttons anywhere.

---

## PART 9 — MICROCOPY AND MESSAGE CATALOGUE

Use these texts (and their tone: short, specific, tell the user what to do next).

### 9.1 Validation messages

| Code | Message |
|---|---|
| `REQUIRED` | "{Field} is required." |
| `PHONE_INVALID` | "Enter an Ethiopian mobile number, e.g. 0911 22 33 44 or 0711 22 33 44." |
| `PHONE_SCIENTIFIC_NOTATION` | "This looks like an Excel number (9.11E+08). Format the column as Text and type the full number." |
| `PHONE_DUPLICATE` | "This phone number is already registered for {name} ({traineeId})." |
| `DATE_INVALID` | "Enter a valid date as DD/MM/YYYY." |
| `DATE_AMBIGUOUS` | "{value} could be {readingA} or {readingB}. Choose the correct date." |
| `DATE_FUTURE` | "This date cannot be in the future." |
| `ET_DATE_INVALID` | "This is not a valid Ethiopian calendar date (Pagume has 5 days, 6 in a leap year)." |
| `AGE_DOB_MISMATCH` | "Age {age} does not match the date of birth (≈ {computed}). Please check both." (warning) |
| `AGE_NOT_ELIGIBLE` | "Age {age} is outside the eligible range 18–29. The trainee can be registered but will count as not eligible." (warning) |
| `ENUM_UNKNOWN` | "'{value}' is not an allowed value. Choose one of: {options}." |
| `ENUM_ALIAS_MAPPED` | "'{value}' was recognised as '{canonical}'." (warning) |
| `BOOLEAN_INVALID` | "Answer Yes or No." |
| `NAME_INVALID` | "Use letters only (Latin or Ge'ez), spaces, hyphen or apostrophe." |
| `EMAIL_INVALID` | "Enter a valid email address." |
| `EXTERNAL_ID_REQUIRED` | "{label} is required for this provider." |
| `EXTERNAL_ID_DUPLICATE` | "{label} {value} is already used by {traineeId}." |
| `CLASS_NOT_IN_SITE` | "Class {code} does not belong to the selected site." |
| `CAPACITY_EXCEEDED` | "This would register {n} trainees; the maximum is {max} (target {target} + {pct} %). Remove {excess} rows." |
| `CONSENT_REQUIRED` | "The trainee must agree to {consent} to be registered." |

### 9.2 Workflow messages

| Code | Message |
|---|---|
| `REGISTRATION_CLOSED` | "Registration for {provider} closed on {date}. Ask M&E for a late registration window if needed." |
| `ROSTER_FROZEN` | "The roster of {class} was frozen on {date}. Submit a roster change request instead." |
| `NOT_A_SESSION_DAY` | "{date} is not a session day for {class} ({reason})." |
| `SESSION_ALREADY_SUBMITTED` | "Attendance for {date} was already submitted by {user}. Request a correction to change it." |
| `LATE_ATTENDANCE` | "This date is more than {n} days ago. Add a justification to submit it." |
| `ATTENDANCE_INCOMPLETE_GATE` | "Attendance is incomplete for {class} ({n} sessions missing). Complete it before submitting this report." |
| `DROPOUT_REPORT_REQUIRED` | "Submit and get the dropout report accepted before the completion report." |
| `CLASS_NOT_ENDED` | "{class} ends on {date}. Outcome reports open after the class ends." |
| `SYSTEM_DROPOUT_LOCKED` | "{name} attended {pct} % (below 80 %). This is recorded as a dropout; correct attendance if it is wrong." |
| `RESUBMISSION_NEEDS_APPROVAL` | "This report has already been used for verification. Your new version will apply after M&E approval." |
| `WINDOW_NOT_OPEN` | "This obligation opens on {date}." |
| `WINDOW_CLOSED` | "The submission window closed on {date}. Request an extension." |
| `RUN_FINALISE_BLOCKED` | "{n} sampled trainees still need a definite result or a replacement." |
| `NO_ACCESS` | "You don't have access to this. Contact your administrator if you need it." |

### 9.3 Empty states

| Page | Title | Text | Action |
|---|---|---|---|
| Trainees | "No trainees yet" | "Import your trainee list from Excel or add trainees one by one." | Import · Add trainee |
| Attendance to-do | "All caught up" | "Every scheduled session up to today has been recorded." | — |
| Outcomes board | "No classes have ended yet" | "Outcome reports become due after each class ends." | View classes |
| Obligations | "Nothing due" | "New obligations appear when classes are scheduled." | — |
| Grievances | "No cases" | "Cases submitted through the public form appear here." | Copy public form link |
| Notifications | "You're up to date" | "We'll let you know when something needs your attention." | — |
| Verification runs | "No verification runs yet" | "Create a run to draw a sample for an indicator." | New run |
| Filtered list | "No results" | "Nothing matches these filters." | Clear filters |

### 9.4 Success toasts

"Trainee registered — {traineeId}" · "119 trainees imported" · "Attendance for {date} submitted" · "Correction requested" · "Report accepted — {yes} Yes / {no} No" · "Evidence submitted" · "Reply sent to {submitter}" · "Targets saved (effective {date})" · "Sample drawn: {n} trainees + {r} reserves" · "Run finalised" · "Export ready — Download".

---

## PART 10 — PAGE STATES MATRIX (quick reference for the generator)

| Page | Skeleton | Empty | Job progress | Optimistic | Offline draft | Mobile-first |
|---|---|---|---|---|---|---|
| Programme dashboard | KPI grid + charts | — | Recompute | — | — | no |
| Provider home | KPI + to-do list | "All caught up" | — | — | — | yes |
| Providers list / detail | table / header+tabs | yes | — | — | — | no |
| Onboarding wizard | step form | — | Activate (obligations) | — | — | no |
| Trainings / class detail | cards / header+tabs | yes | — | — | — | partial |
| Class editor | form + calendar | — | — | — | — | no |
| Trainees list | table | yes | Export | — | — | partial |
| Trainee detail | header+tabs | — | — | — | — | yes |
| Trainee form | form | — | — | — | — | yes |
| Import wizard | — | — | Validate, Commit | inline cell fix | — | no |
| Attendance to-do | list | yes | — | — | — | yes |
| Attendance sheet | roster list | — | Import | mark toggles | yes | yes |
| Corrections / approvals queues | table | yes | — | — | — | partial |
| Dropout monitoring | cards + table | yes | — | — | — | no |
| Outcomes board | matrix | yes | — | — | — | no |
| Report editor | roster table | — | Validate (upload) | Yes/No toggles | yes | partial |
| Indicator registry / detail | cards / protocol card | — | — | — | — | no |
| Targets grid | grid | — | Import/Export | cell save | — | no |
| KPI report | matrix | — | Export | — | — | no |
| Obligations / detail | list / panel | yes | Upload | — | — | yes |
| Review queue | split view | yes | — | — | — | no |
| Verification runs / workspace | table / tabs | yes | Draw, Kobo import, Finalise | — | — | no |
| Enumerator call screen | card | "No assigned calls" | — | attempt log | yes | yes |
| Grievance list / case | table / thread | yes | Export | status change | — | yes |
| Notifications | list | yes | — | mark read | — | yes |
| Report centre | cards | — | Generate | — | — | no |
| Data health | gauges + table | "No issues" | — | — | — | no |
| Admin pages | forms/tables | yes | Audit verify/export | toggles | — | no |
| Public pages | minimal | — | — | — | — | yes |

---

*End of the frontend prompt. When the UI is generated, the backend (Master Plan Part G) will be implemented to the same contract and the MSW handlers replaced by the real API.*

---

## PART 11 — SHARED COMPONENT PROPS (implement exactly; pages compose these)

```ts
// DataTable — server-side table used by every list page
interface DataTableProps<T, F> {
  queryKey: unknown[];                       // e.g. ['p', pid, 'trainees', filters]
  fetcher: (args: { page: number; pageSize: number; sort?: string; filters: F }) => Promise<Page<T>>;
  columns: ColumnDef<T>[];
  filters: F;                                // controlled by FilterBar, mirrored in URL
  rowLink?: (row: T) => string;              // whole-row click target
  rowActions?: (row: T) => Action[];         // kebab menu, permission-aware
  bulkActions?: BulkAction<T>[];             // appear when rows are selected
  exportKey?: string;                        // shows Export button → starts a report job
  emptyState?: { title: string; text: string; action?: Action };
  density?: 'comfortable' | 'compact';
}

// KpiCard
interface KpiCardProps {
  title: string; value?: number; unit?: '%' | '#'; verifiedValue?: number;
  target?: number; comparator?: '>=' | '<='; status: 'met' | 'not_met' | 'no_data' | 'not_applicable';
  deltaVsPrevious?: number; direction?: 'higher_is_better' | 'lower_is_better';
  trend?: { date: string; value: number }[]; asOf?: string; recalculating?: boolean;
  footnote?: string;                         // e.g. "Capped at contract target 1,000"
  href?: string;
}

// StatusBadge
type StatusKey = 'met'|'not_met'|'at_risk'|'pending'|'no_data'|'approved'|'returned'|'overdue'|'due_soon'|'upcoming'
  |'submitted'|'accepted'|'superseded'|'draft'|'present'|'absent'|'excused'|'in_field'|'under_review'|'finalised'
  |'clear_pass'|'clear_fail'|'inconclusive'|'new'|'responded'|'resolved'|'escalated'|'active'|'reserve'|'withdrawn';
interface StatusBadgeProps { status: StatusKey; label?: string; size?: 'sm' | 'md'; }

// ScopePicker — cascading, scope-aware
interface ScopePickerProps {
  value: { providerId?: string; trainingId?: string; siteId?: string; classId?: string };
  onChange: (v: ScopePickerProps['value']) => void;
  levels?: ('provider' | 'training' | 'site' | 'class')[];   // which selects to show
  required?: ('provider' | 'training' | 'site' | 'class')[];
}

// CalendarMonth
interface CalendarDay { date: string; kind: 'session'|'holiday'|'breakdown'|'exempt'|'non_session'; label?: string;
  attendance?: 'present'|'absent'|'excused'|'missing'; }
interface CalendarMonthProps { months: string[]; days: CalendarDay[]; onSelect?: (date: string) => void;
  selectableKinds?: CalendarDay['kind'][]; legend?: boolean; }

// AttendanceGrid
interface AttendanceGridProps {
  trainees: { id: string; code: string; name: string; rosterStatus: 'active' | 'reserve' }[];
  dates: { date: string; submitted: boolean; submittedBy?: string }[];
  marks: Record<string /*traineeId*/, Record<string /*date*/, 'P' | 'A' | 'E' | undefined>>;
  editableDates: string[];
  onChange: (traineeId: string, date: string, value: 'P' | 'A' | 'E') => void;
  onSubmitDate: (date: string) => Promise<void>;
  onRequestCorrection: (traineeId: string, date: string) => void;
}

// ImportPreviewTable
interface ImportRow { rowNo: number; status: 'ok' | 'error' | 'warning' | 'duplicate'; values: Record<string, string>;
  issues: { field: string; code: string; message: string; severity: 'error' | 'warning' }[];
  duplicates?: { traineeId: string; code: string; name: string; provider: string; score: number; reasons: string[] }[];
  decision?: 'import' | 'skip'; }
interface ImportPreviewTableProps { batchId: string; columns: { key: string; label: string; required: boolean }[];
  filter: 'all' | 'error' | 'warning' | 'duplicate' | 'ok';
  onCellEdit: (rowNo: number, field: string, value: string) => Promise<ImportRow>;
  onDuplicateDecision: (rowNo: number, decision: 'skip' | 'not_duplicate', reason?: string) => Promise<void>; }

// JobProgress
interface JobProgressProps { jobId: string; title: string; onDone?: (result: unknown) => void;
  successAction?: { label: string; href: string }; }

// FileDropzone
interface FileDropzoneProps { accept: string[]; maxSizeMb: number; multiple?: boolean;
  onUpload: (files: File[], onProgress: (pct: number) => void) => Promise<void>; helpText?: string; }

// WhatsDuePanel
interface DueItem { kind: 'attendance'|'outcome_report'|'obligation'|'grievance'|'roster_freeze'|'returned'|'setup';
  title: string; detail?: string; dueDate?: string; severity: 'overdue'|'due_soon'|'open'|'info'; href: string; count?: number; }
interface WhatsDuePanelProps { items: DueItem[]; loading?: boolean; }

// TargetBar
interface TargetBarProps { value?: number; target?: number; comparator?: '>=' | '<='; max?: number; showLabels?: boolean; }

// ConfirmDialog
interface ConfirmDialogProps { title: string; description: string; confirmLabel: string; destructive?: boolean;
  typeToConfirm?: string; onConfirm: () => Promise<void>; }

// EthiopianDateInput
interface EthiopianDateInputProps { value?: { y: number; m: number; d: number }; onChange: (v?: { y: number; m: number; d: number }) => void;
  statedAge?: number; referenceDate?: string; /* form completion date for age check */ }

// PhoneInput
interface PhoneInputProps { value?: string; onChange: (raw: string) => void; onNormalized?: (e164?: string) => void; label: string; required?: boolean; }
```

**Hooks to provide:** `useAccess()`, `useCan(perm)`, `useProject()`, `useJob(jobId)`, `useUrlFilters<F>(defaults)`, `useUnsavedChangesPrompt(dirty)`, `useLocalDraft(key, value)`, `useNotificationsCount()` (polls every 60 s), `useDebounce`.

**Formatting helpers (`src/lib/format.ts`):** `fmtPct(v)` → "92.1 %", `fmtInt(v)` → "1,040", `fmtDate(iso)` → "12 May 2026", `fmtDateTime(iso)` (Africa/Addis_Ababa), `fmtPhone(e164)` → "0911 22 33 44", `fmtName(first, father, grandfather)`, `fmtEthiopianDate({y,m,d})` → "12 Meskerem 2016 E.C.", `relativeTime(iso)` → "3 h ago".

**Usage tip:** if the generator runs out of context, paste Part 2 (theme) and Part 3 (shell) again before each module of Part 5.
