# PBPS MIS V2 — Database Redesign and Zero-Loss Migration

**Scope:** the new V2 database (`pbps_v2`), how every table of the current database (`pbps_mis`) maps into it, the complete DDL, the ordered idempotent migration scripts, reconciliation, rollback, and cutover runbook.
**Source analysed:** live `pbps_mis` on MariaDB 10.4.32 (XAMPP), 52 tables, profiled on the day of analysis (3,234 trainees; 182,215 max attendance id; 4,387 outcome rows; 7,285 audit events).
**Companion:** `01_V2_MASTER_PLAN.md` (functional design). Section numbers like "MP §20" refer to the master plan.

---

## Contents

1. Principles of this migration
2. Assessment of the current database
3. Target engine, server and conventions
4. Table-by-table mapping (every V1 table)
5. The outcome redesign — from rows to status columns (with worked example)
6. New schema — DDL (all tables)
7. Index and constraint rationale
8. Migration architecture (schemas, bookkeeping, runner)
9. Migration scripts — ordered, idempotent SQL
10. Reconciliation — proving nothing was lost
11. Re-run, rollback and incremental re-sync
12. Cutover runbook
13. Optional interim SQL for V1 (while V2 is built)
14. Data-quality findings to resolve with TPs

---

## 1. Principles of this migration

| # | Principle | How it is guaranteed |
|---|---|---|
| P1 | **Nothing is lost** | Every V1 row is either mapped (with its original primary key) or copied verbatim into the archive schema `pbps_legacy`; anti-join checks in §10 must return zero rows. |
| P2 | **The source is never modified** | `pbps_mis` is restored into the new server and the migration user has **SELECT only** on it. |
| P3 | **IDs are preserved** | V2 rows created from V1 rows keep the same `id` (trainees, trainings, classes, reports, outcome lines, runs, subjects, cases, users…). Links in old emails, exports and audit events stay valid. |
| P4 | **Idempotent** | Each script can be executed any number of times with the same final state: `INSERT IGNORE` / `ON DUPLICATE KEY UPDATE` keyed on preserved IDs or natural unique keys; derived values are recomputed deterministically; no script depends on wall-clock time except recorded `migrated_at`. |
| P5 | **Cleaning is additive** | For every free-text field that V2 normalises, the original text is stored in a `*_raw` column. Values that cannot be parsed stay NULL in the clean column and are listed in `migration_issues` and Data health — never discarded. |
| P6 | **Inference is labelled** | Any value V2 derives that V1 did not store explicitly (e.g. completion = "no") carries a `*_source = 'migration_inferred'` label and is reported. |
| P7 | **Verifiable** | Reconciliation queries (counts, sums per provider/class, KPI parity) are part of the migration, produce a report, and gate cutover. |
| P8 | **Repeatable rehearsal** | The full migration runs in minutes at pilot scale, so every rehearsal and the final cutover start from a fresh restore. |

---

## 2. Assessment of the current database

### 2.1 What is good and is kept

- InnoDB, utf8mb4 everywhere (Ge'ez/Amharic text safe; the `?` seen in a terminal is a display artefact — the bytes are correct, e.g. `E2 80 99` for the apostrophe in "Selam Children's Village").
- Surrogate `BIGINT UNSIGNED` keys, foreign keys with sensible `ON DELETE` behaviour, `created_at`/`updated_at` on most tables.
- Unique constraints on business keys (`trainee_unique_id`, provider code per project, external beneficiary ID per provider, attendance (trainee, batch, date), dedupe keys).
- Verification tables (runs, subjects, strata, dropouts) — well structured, kept almost 1:1.

### 2.2 Structural problems (and the V2 response)

| Problem | Evidence | V2 response |
|---|---|---|
| Outcomes as generic rows; completion only stores "yes" | `trainee_outcomes`: completion 1,706 rows all `reported_value=1`; dropout 1,967 rows (261 Y, 1,706 N) | `outcome_reports` + `outcome_report_lines` (Y and N) + `trainee_status` typed columns (§5) |
| Typed data inside JSON | `meta.completion_date = "8/27/2026"`, `meta.stageKey`, `delivery_location_ids` as JSON strings, `session_weekdays` as JSON | Real columns (`DATE`, `stage_key`, weekday bitmask, join tables) |
| Wide attendance rows | 6 FKs + status + source + 2 timestamps per mark; index 47 MB vs data 20 MB for 180k rows | `attendance_sessions` header + `attendance_marks(session_id, trainee_id, status)` |
| Scope duplicated on every row | `project_id, training_provider_id, training_id, cohort_id, batch_id` on trainees, enrollments, attendance, outcomes, batches, runs, events, alerts | Child rows reference the narrowest parent (class / session / report); provider kept only where it drives row-level security and indexes |
| Three ways to link a TP user | `training_providers.user_id`, `project_users.project_role='tp'`, `tp_staff_memberships` | One `memberships` table (+ `membership_scopes`) |
| Workflow state in the audit log | resubmission requests as `submission_events` rows | `outcome_reports` versions with approval |
| Configuration as JSON mini-language | `indicator_variables.query_spec` | Metric catalogue in code + `indicator_definitions` |
| Stale status columns | cohort/batch `status='planned'` for running classes | Derived status |
| Dates as `DATETIME 12:00:00` | trainings/cohorts/batches/outcome dates | `DATE` |
| Free-text enums | region, disability type, education/employment variants | Enum codes + alias tables + `*_raw` |
| No uniqueness on outcome facts | (trainee, type, stage) not unique | PKs on lines and status |
| Duplicate tables | `trainee_enrollments` mirrors trainee scope (85 reserves missing) | Class membership on the trainee row (+ history table) |

### 2.3 Live data facts that shape the migration

| Fact | Value | Consequence |
|---|---|---|
| Trainees | 3,234 (active 2,993, reserve 241); max id 6,453 (deleted rows left gaps) | Preserve ids; `AUTO_INCREMENT` continues above 6,453 |
| Trainees without enrollment row | 85 (all reserve) | Ignore enrollment table for class membership (trainee row is authoritative) |
| Trainees with no dropout row | 1,267 (AAU and IBT classes not yet ended) | `dropout_status = 'pending'` |
| Outcome rows | certification 714 (Y), completion 1,706 (Y), dropout 261 Y + 1,706 N | Lines Y/N; statuses derived |
| Outcome report batches | 183 (all processed), exactly one per (class, type, stage) | One V2 report per batch, same id, version 1 |
| `status_date` NULL | completion 228, dropout 733 | Dates taken from `meta.*_date` strings when parseable; else NULL + issue |
| Attendance | 179,956 rows; 4,954 distinct (batch, date) sessions; 117 sessions mixed manual/backfill | Session header + marks; backfill flag per mark |
| Attendance on holidays | 37 rows | Kept; class calendar marks the date `holiday`; Data health notice |
| Form-completion dates with day ≤ 12 | 702, of which **363** remain ambiguous after the plausibility rule | Ambiguity classification (§9.5.3) |
| Date of birth text | mixed `M/D/YY`, `D/M/YYYY`, `M/D/YYYY` | Parsed by the TypeScript enrichment step; raw kept |
| Region variants | ≥ 15 spellings for 6 regions | `region_aliases` mapping |
| Phones | 3,233 valid 9-digit (stored without leading 0); 1 invalid (`9.`) | E.164 conversion; invalid kept raw + issue |
| Users | 24 (ids to 27); 16 TP users, each with exactly one staff membership; 5 provider owners | Clean mapping to memberships |
| TP SMTP | 5 identical rows | Archived; provider `notification_email` seeded from `contact_email` |
| Activity rules | 16, all `cohort_anchor +1/+200/grace 0` | Migrated as legacy schedules (inactive) + new default schedules (MP §22.3) |
| Activity submissions | 28 (all `submitted`), 28 files | Obligations created and linked; files copied with checksums |
| Verification | 3 runs, 875 subjects, 18 strata, 79 run-dropouts | 1:1 |
| Audit events | 7,285 with V1 hash chain | Verbatim to `audit_events_legacy` |

---

## 3. Target engine, server and conventions

### 3.1 Engine

- **Production:** MySQL **8.4 LTS** (InnoDB). **Acceptable:** MariaDB **10.11 LTS** or 11.4 LTS.
- **Why not stay on MariaDB 10.4 (XAMPP):** end-of-life; lacks `JSON_TABLE` (needed to explode V1 JSON arrays), `SKIP LOCKED` (job queue), and several optimiser improvements.
- **Step 0 of the migration** therefore restores a dump of `pbps_mis` into the new server; all scripts run there (cross-schema SQL on one server).

### 3.2 Schemas on the new server

| Schema | Content | Access |
|---|---|---|
| `pbps_mis` | V1 database restored from dump — **source of truth, never modified** | migration user: SELECT |
| `pbps_legacy` | Verbatim copies of V1 tables that V2 archives (e.g. `tp_smtp_configurations`, `indicator_variables`, `trainee_enrollments`, `trainee_outcomes` as-was, `submission_events`) | read-only after migration |
| `pbps_v2` | New application schema | app user: DML; migration user: DDL+DML |

### 3.3 Conventions

- Charset/collation: `utf8mb4` / `utf8mb4_unicode_ci` (identical to V1 → no "illegal mix of collations" in cross-schema joins; works on MySQL and MariaDB).
- Names: `snake_case`, plural table names, `id` PK, `<entity>_id` FKs, booleans `is_*`/`has_*`, dates `*_date`, timestamps `*_at` (`DATETIME(3)`, UTC).
- Every table: `created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3)`; mutable tables also `updated_at … ON UPDATE CURRENT_TIMESTAMP(3)`, `version INT UNSIGNED NOT NULL DEFAULT 1` (optimistic locking).
- Migrated rows: `legacy_source VARCHAR(40) NULL` where the origin is not obvious from the preserved id (e.g. `trainee_outcomes`), and `migrated_at` where useful.
- Status columns use `ENUM` (readable, 1 byte, validated) for closed sets; open sets use `VARCHAR` + reference table.
- Weekdays: `TINYINT UNSIGNED` bitmask (Mon = 1, Tue = 2, Wed = 4, Thu = 8, Fri = 16, Sat = 32, Sun = 64).

---

## 4. Table-by-table mapping (every V1 table)

Legend: **M** = migrated (transformed into V2 tables) · **A** = archived verbatim in `pbps_legacy` (also) · **R** = replaced by a new mechanism · **D** = derived in V2 from other data.

| # | V1 table | Rows | Fate | V2 destination | Notes |
|---|---|---|---|---|---|
| 1 | `users` | 24 | M | `users` | same ids; password hashes copied; `two_factor_enabled` → `two_factor_method` |
| 2 | `email_two_factor_tokens` | 0 | R | `email_otp_challenges` | transient; not migrated |
| 3 | `app_settings` | 3 | M | `app_settings` / `project_settings` | keys renamed (§9.2) |
| 4 | `projects` | 1 | M | `projects` | `meta` JSON exploded into columns; `max_overenrollment_percent` → `over_enrolment_pct` |
| 5 | `project_users` | 24 | M | `memberships` | roles mapped (MP §12.2) |
| 6 | `roles` | 5 | M | `roles` | codes mapped; V1 codes kept in `legacy_code` |
| 7 | `permissions` | 44 | M + A | `permissions` (new keys) | mapping table `permission_key_map`; V1 rows archived |
| 8 | `role_permissions` | 113 | M + A | `role_permissions` | translated through the key map; V1 archived (grant differences reported) |
| 9 | `smtp_configurations` | 1 | M + A | `mail_settings` | password re-encrypted by the TS step |
| 10 | `tp_smtp_configurations` | 5 | A + R | — | TP SMTP removed; `providers.notification_email` seeded |
| 11 | `locations` | 3 | M | `locations` | same ids |
| 12 | `training_durations` | 3 | M | `durations` | same ids |
| 13 | `training_providers` | 5 | M | `providers` | same ids; owner `user_id` → `memberships(tp_admin)` |
| 14 | `training_provider_contracts` | 5 | M | `provider_contracts` | same ids; status `active` |
| 15 | `tp_staff_memberships` | 16 | M | `memberships` | `staff_role` → V2 role; `is_active` → status |
| 16 | `tp_staff_delivery_scopes` | 49 | M | `membership_scopes` | provider-level rows dropped (implicit); cohort → site; batch → class |
| 17 | `trainings` | 18 | M | `trainings` | same ids; JSON arrays exploded; program merged |
| 18 | `training_programs` | 19 | M + A | `trainings.programme_name` | archived for reference |
| 19 | `training_cohorts` | 24 | M | `training_sites` | same ids; code/name kept in `legacy_*` |
| 20 | `training_batches` | 111 | M | `training_classes` | same ids; weekdays → mask |
| 21 | `project_holidays` | 6 | M | `holidays` | same ids |
| 22 | `training_breakdowns` | 3 | M | `training_breakdowns` | same ids; cohort → site, batch → class |
| 23 | `trainees` | 3,234 | M | `trainees` (+ `trainee_status`) | same ids; cleaned + raw columns |
| 24 | `trainee_enrollments` | 3,173 | A + D | `trainee_class_history` (seed) | membership lives on `trainees.class_id` |
| 25 | `trainee_attendance_days` | 179,956 | M + A | `attendance_sessions` + `attendance_marks` | natural key (trainee, batch, date) preserved |
| 26 | `outcome_report_batches` | 183 | M | `outcome_reports` | same ids |
| 27 | `trainee_outcomes` | 4,387 | M + A | `outcome_report_lines` (+ `trainee_status`) | same ids (`outcome_report_lines.id`) |
| 28 | `indicator_variables` | 15 | A + R | metric catalogue (code) | mapping variable → metric key recorded |
| 29 | `project_indicators` | 11 | M | `indicator_definitions` (+ 8 new from protocol) | ids preserved for the 11 |
| 30 | `project_indicator_stages` | 2 | M | `indicator_stages` | same ids |
| 31 | `project_indicator_versions` | 0 | R | `indicator_definitions` versioning | empty |
| 32 | `project_activities` | 8 | M | `activity_definitions` | same ids |
| 33 | `project_activity_assignments` | 40 | M | `activity_assignments` | same ids |
| 34 | `project_activity_rules` | 16 | M + A | `activity_schedules` (inactive legacy) | new defaults added separately |
| 35 | `tp_activity_submissions` | 28 | M | `activity_submissions` (+ `activity_obligations` D) | same ids |
| 36 | `tp_activity_submission_files` | 28 | M | `files` + `activity_submission_files` | checksums computed |
| 37 | `feedback_threads` | 123 | M | `grievance_cases` | same ids; `ref_code` kept |
| 38 | `feedback_messages` | 199 | M | `grievance_messages` | same ids |
| 39 | `verification_sample_runs` | 3 | M | `verification_runs` (+ `verification_plans` D) | same ids |
| 40 | `verification_sample_subjects` | 875 | M | `verification_subjects` | same ids |
| 41 | `verification_subject_evidence` | 0 | M | `verification_evidence` | empty |
| 42 | `verification_sample_strata` | 18 | M | `verification_strata` | same ids |
| 43 | `verification_sample_run_dropouts` | 79 | M | `verification_run_dropouts` | same ids |
| 44 | `submission_events` | 7,285 | A + M | `audit_events_legacy` (verbatim) | V2 chain genesis references last V1 hash |
| 45 | `alert_rules` | 4 | M | `reminder_rules` (mapped) | new rules added |
| 46 | `alert_events` | 202 | A | — | open alerts regenerated by V2 engine |
| 47 | `alert_recipient_states` | 1,818 | A | — | read states not needed |
| 48 | `alert_digest_runs` | 173 | A | — | |
| 49 | `trainee_duplicate_scan_runs` | 46 | M | `duplicate_scan_runs` | same ids |
| 50 | `trainee_duplicate_candidates` | 19 | M | `duplicate_candidates` | same ids; statuses mapped |
| 51 | `_prisma_migrations` | 47 | A | — | history only |
| 52 | (files on disk) `uploads/` | 28+ | M | storage + `files` | sha256 recorded |

Every V1 table is also dumped in full as part of the pre-migration backup (§12, step 1).

---

## 5. The outcome redesign — from rows to status columns

### 5.1 V1 (what is stored today) for one trainee

```
trainee_outcomes
id    trainee_id  report_batch_id  outcome_type   reported_value  status_date  meta
9001  1203        41               dropout        0               NULL         {"dropout_dispute":"system_final_disputed"}
9850  1203        58               completion     1               2026-09-23   {"completion_date":"8/27/2026"}
10422 1203        77               certification  1               2026-09-05   {"certification_date":"9/5/2026"}
```

To answer "how many completers does SCV have?", V1 scans outcome rows, joins trainees for roster role, and — for the KPI — runs attendance roll-ups. To answer "who did **not** complete?", V1 cannot answer directly (non-completers are not stored).

### 5.2 V2

```
outcome_reports           (one per class × type × stage × version)
id  class_id  report_type    stage_key  version  status    yes_count  no_count
41  76        dropout        NULL       1        accepted  2          38
58  76        completion     NULL       1        accepted  36         2     ← new submissions list everyone
77  76        certification  NULL       1        accepted  36         0

outcome_report_lines      (one per trainee per report — Y and N)
id     report_id  trainee_id  value  event_date   reason  details
9001   41         1203        no     NULL         NULL    {"legacy_meta":{"dropout_dispute":"system_final_disputed"}}
9850   58         1203        yes    2026-08-27   NULL    {}
10422  77         1203        yes    2026-09-05   NULL    {}

trainee_status            (one row per trainee — current state, typed)
trainee_id  provider_id  class_id  dropout_status  completion_status  completion_date  certification_status  att_rate_final  …
1203        3            76        no              yes                2026-08-27       yes                   91.2500
```

KPI query (completion, all providers, at 120k trainees) becomes:

```sql
SELECT s.provider_id,
       SUM(s.completion_status = 'yes' AND s.att_rate_final >= 80) AS completers_gated,
       SUM(s.completion_status = 'yes')                           AS completers
FROM trainee_status s
WHERE s.project_id = ? AND s.roster_status IN ('active','reserve')
GROUP BY s.provider_id;
```

— one index range scan, milliseconds.

### 5.3 Status derivation rules used by the migration (and by V2 at runtime)

| Status | Derivation from lines (latest accepted report of each type for the trainee's class) |
|---|---|
| `dropout_status` | `yes` if any accepted dropout line = yes; else `no` if an accepted dropout line = no; else `pending` |
| `dropout_source` | `tp_reported` for TP lines; V1 meta `source_type='tp_reported'` → `tp_reported`; system-final without TP yes → set by the dropout rule (`system_low_attendance`) |
| `completion_status` | `yes` if accepted completion line = yes; `no` if line = no (V2 submissions); **V1 only:** `no` + `completion_source='migration_inferred'` when (a) an accepted completion report exists for the trainee's class, (b) the trainee is tracked, (c) `dropout_status <> 'yes'`, (d) no completion line for the trainee; `not_applicable` if `dropout_status='yes'`; else `pending` |
| `certification_status` | analogous; V1 inference of `no` only when a certification report exists for the class and the trainee has completion = yes |
| employment statuses | from their report types (none in V1 data) → `pending` / `not_applicable` |

---

## 6. New schema — DDL (all tables)

> Run as the migration user on MySQL 8.4 (or MariaDB 10.11+). File `migration/sql/01_schema.sql`. All statements are `CREATE TABLE IF NOT EXISTS` so the file is idempotent. Foreign keys reference preserved IDs. In the application this DDL is owned by Prisma (`prisma/schema/*.prisma`); the SQL below is the reviewed reference that the Prisma schema must produce.

```sql
CREATE DATABASE IF NOT EXISTS pbps_v2     CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE DATABASE IF NOT EXISTS pbps_legacy CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE pbps_v2;
SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;
```

### 6.1 Platform

```sql
-- Migration bookkeeping ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS migration_runs (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  run_label     VARCHAR(64)  NOT NULL,              -- e.g. 'rehearsal-1', 'cutover'
  script        VARCHAR(120) NOT NULL,              -- e.g. '20_trainees.sql'
  started_at    DATETIME(3)  NOT NULL,
  finished_at   DATETIME(3)  NULL,
  status        ENUM('running','ok','failed') NOT NULL DEFAULT 'running',
  rows_affected BIGINT NULL,
  checksum      CHAR(64) NULL,                      -- sha256 of script text
  notes         TEXT NULL,
  KEY ix_mr_label (run_label, script)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS migration_issues (
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  entity       VARCHAR(60)  NOT NULL,              -- 'trainee', 'outcome_line', …
  entity_id    BIGINT UNSIGNED NOT NULL,
  field        VARCHAR(80)  NOT NULL,
  issue_code   VARCHAR(60)  NOT NULL,              -- 'DOB_UNPARSABLE', 'REGION_UNKNOWN', 'FORM_DATE_AMBIGUOUS', …
  raw_value    TEXT NULL,
  detail       TEXT NULL,
  severity     ENUM('info','warning','error') NOT NULL DEFAULT 'warning',
  created_at   DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  resolved_at  DATETIME(3) NULL,
  UNIQUE KEY uq_mi (entity, entity_id, field, issue_code)          -- idempotent re-insert
) ENGINE=InnoDB;

-- Settings, sequences, jobs, events ------------------------------------------------
CREATE TABLE IF NOT EXISTS app_settings (
  setting_key   VARCHAR(120) PRIMARY KEY,
  value_json    JSON NOT NULL,
  updated_by    BIGINT UNSIGNED NULL,
  updated_at    DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS id_sequences (
  scope         VARCHAR(80) PRIMARY KEY,           -- 'trainee:PBPS:SCV', 'grm:2026'
  next_value    BIGINT UNSIGNED NOT NULL,
  updated_at    DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS jobs (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  queue         VARCHAR(40)  NOT NULL DEFAULT 'default',
  type          VARCHAR(80)  NOT NULL,
  payload       JSON NOT NULL,
  dedupe_key    VARCHAR(191) NULL,
  status        ENUM('queued','running','done','failed','dead') NOT NULL DEFAULT 'queued',
  run_at        DATETIME(3) NOT NULL,
  attempts      SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  max_attempts  SMALLINT UNSIGNED NOT NULL DEFAULT 5,
  locked_by     VARCHAR(80) NULL,
  locked_until  DATETIME(3) NULL,
  progress_pct  TINYINT UNSIGNED NULL,
  progress_note VARCHAR(255) NULL,
  result_json   JSON NULL,
  last_error    TEXT NULL,
  requested_by  BIGINT UNSIGNED NULL,
  project_id    BIGINT UNSIGNED NULL,
  created_at    DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  finished_at   DATETIME(3) NULL,
  UNIQUE KEY uq_jobs_dedupe (dedupe_key),
  KEY ix_jobs_pick (status, queue, run_at)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS scheduler_leases (
  name          VARCHAR(60) PRIMARY KEY,
  holder        VARCHAR(80) NOT NULL,
  expires_at    DATETIME(3) NOT NULL
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS outbox_events (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  project_id    BIGINT UNSIGNED NULL,
  event_type    VARCHAR(80) NOT NULL,
  payload       JSON NOT NULL,
  created_at    DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  dispatched_at DATETIME(3) NULL,
  attempts      SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  KEY ix_outbox_pending (dispatched_at, id)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS idempotency_keys (
  idem_key      VARCHAR(100) NOT NULL,
  user_id       BIGINT UNSIGNED NOT NULL,
  route         VARCHAR(160) NOT NULL,
  response_code SMALLINT NOT NULL,
  response_body JSON NULL,
  created_at    DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  PRIMARY KEY (user_id, idem_key)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS files (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  project_id    BIGINT UNSIGNED NULL,
  purpose       ENUM('activity_evidence','verification_evidence','import_source','export','report','contract','other') NOT NULL,
  storage_key   VARCHAR(500) NOT NULL,
  original_name VARCHAR(255) NOT NULL,
  mime_type     VARCHAR(128) NULL,
  size_bytes    BIGINT UNSIGNED NULL,
  sha256        CHAR(64) NULL,
  uploaded_by   BIGINT UNSIGNED NULL,
  uploaded_at   DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  legacy_path   VARCHAR(500) NULL,
  deleted_at    DATETIME(3) NULL,
  UNIQUE KEY uq_files_storage (storage_key),
  KEY ix_files_project_purpose (project_id, purpose)
) ENGINE=InnoDB;
```

### 6.2 Identity

```sql
CREATE TABLE IF NOT EXISTS users (
  id                   BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,   -- V1 id preserved
  name                 VARCHAR(255) NOT NULL,
  email                VARCHAR(255) NOT NULL,
  password_hash        VARCHAR(255) NULL,                            -- NULL until invite accepted
  status               ENUM('invited','active','disabled') NOT NULL DEFAULT 'active',
  must_change_password BOOLEAN NOT NULL DEFAULT FALSE,
  password_changed_at  DATETIME(3) NULL,
  failed_login_count   SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  first_failed_at      DATETIME(3) NULL,
  locked_until         DATETIME(3) NULL,
  two_factor_method    ENUM('none','email','totp') NOT NULL DEFAULT 'none',
  totp_secret_enc      VARBINARY(255) NULL,
  access_version       INT UNSIGNED NOT NULL DEFAULT 1,             -- bump to invalidate cached access context
  last_login_at        DATETIME(3) NULL,
  email_verified_at    DATETIME(3) NULL,
  created_at           DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  updated_at           DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_users_email (email)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS user_sessions (
  id                 BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id            BIGINT UNSIGNED NOT NULL,
  family_id          CHAR(36) NOT NULL,                 -- rotation family for reuse detection
  refresh_token_hash CHAR(64) NOT NULL,
  ip                 VARCHAR(64) NULL,
  user_agent         VARCHAR(255) NULL,
  created_at         DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  last_used_at       DATETIME(3) NULL,
  expires_at         DATETIME(3) NOT NULL,
  revoked_at         DATETIME(3) NULL,
  UNIQUE KEY uq_sessions_token (refresh_token_hash),
  KEY ix_sessions_user (user_id, revoked_at),
  CONSTRAINT fk_sessions_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS user_tokens (                 -- invites, password resets, email OTP
  id          BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id     BIGINT UNSIGNED NOT NULL,
  purpose     ENUM('invite','password_reset','email_otp') NOT NULL,
  token_hash  CHAR(64) NOT NULL,
  expires_at  DATETIME(3) NOT NULL,
  used_at     DATETIME(3) NULL,
  ip          VARCHAR(64) NULL,
  created_at  DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_tokens_hash (token_hash),
  KEY ix_tokens_user (user_id, purpose, expires_at),
  CONSTRAINT fk_tokens_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB;
```

### 6.3 Projects and master data

```sql
CREATE TABLE IF NOT EXISTS projects (
  id                          BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,   -- V1 id preserved
  code                        VARCHAR(40)  NOT NULL,
  title                       VARCHAR(255) NOT NULL,
  donor                       VARCHAR(255) NULL,
  sector                      VARCHAR(255) NULL,
  location_text               VARCHAR(255) NULL,
  description                 TEXT NULL,
  start_date                  DATE NULL,
  end_date                    DATE NULL,
  timezone                    VARCHAR(40) NOT NULL DEFAULT 'Africa/Addis_Ababa',
  over_enrolment_pct          DECIMAL(5,2) NOT NULL DEFAULT 15.00,
  roster_policy               ENUM('tracked_equally','replacement_window') NOT NULL DEFAULT 'tracked_equally',
  replacement_window_days     SMALLINT UNSIGNED NOT NULL DEFAULT 14,
  attendance_threshold_pct    DECIMAL(5,2) NOT NULL DEFAULT 80.00,
  exempt_days_from_class_start SMALLINT UNSIGNED NOT NULL DEFAULT 14,
  late_attendance_days        SMALLINT UNSIGNED NOT NULL DEFAULT 7,
  grievance_sla_days          SMALLINT UNSIGNED NOT NULL DEFAULT 7,
  roster_freeze_offset_days   SMALLINT UNSIGNED NOT NULL DEFAULT 14,
  registration_closed_at      DATETIME(3) NULL,                -- master switch (V1)
  registration_closed_by      BIGINT UNSIGNED NULL,
  registration_close_note     VARCHAR(500) NULL,
  settings_version            INT UNSIGNED NOT NULL DEFAULT 1,
  legacy_meta                 JSON NULL,
  created_at                  DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  updated_at                  DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_projects_code (code),
  CONSTRAINT ck_projects_pct CHECK (over_enrolment_pct BETWEEN 0 AND 100 AND attendance_threshold_pct BETWEEN 0 AND 100)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS project_settings (
  project_id   BIGINT UNSIGNED NOT NULL,
  setting_key  VARCHAR(120) NOT NULL,
  value_json   JSON NOT NULL,
  updated_by   BIGINT UNSIGNED NULL,
  updated_at   DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  PRIMARY KEY (project_id, setting_key),
  CONSTRAINT fk_ps_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS regions (
  code        VARCHAR(40) PRIMARY KEY,                 -- 'addis_ababa', 'amhara', …
  name        VARCHAR(120) NOT NULL,
  kind        ENUM('region','city_administration') NOT NULL,
  sort_order  SMALLINT NOT NULL DEFAULT 0,
  is_active   BOOLEAN NOT NULL DEFAULT TRUE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS enum_aliases (                -- generic alias table for all enums
  domain      VARCHAR(40)  NOT NULL,                   -- 'region','education','employment','disability','sex','dropout_reason',…
  alias_norm  VARCHAR(191) NOT NULL,                   -- lower-case, trimmed, single-spaced, punctuation stripped
  canonical   VARCHAR(60)  NOT NULL,
  PRIMARY KEY (domain, alias_norm)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS locations (
  id          BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,   -- V1 id preserved
  code        VARCHAR(20)  NOT NULL,
  name        VARCHAR(191) NOT NULL,
  region_code VARCHAR(40)  NULL,
  is_active   BOOLEAN NOT NULL DEFAULT TRUE,
  created_at  DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_locations_code (code),
  UNIQUE KEY uq_locations_name (name),
  CONSTRAINT fk_locations_region FOREIGN KEY (region_code) REFERENCES regions(code)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS durations (
  id          BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,   -- V1 id preserved
  months      TINYINT UNSIGNED NOT NULL,
  label       VARCHAR(60) NOT NULL,
  sort_order  SMALLINT NOT NULL DEFAULT 0,
  is_active   BOOLEAN NOT NULL DEFAULT TRUE,
  UNIQUE KEY uq_durations_months (months)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS holidays (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,  -- V1 id preserved
  project_id    BIGINT UNSIGNED NOT NULL,
  holiday_date  DATE NOT NULL,
  label         VARCHAR(255) NULL,
  kind          ENUM('national','religious','local','programme') NOT NULL DEFAULT 'national',
  location_id   BIGINT UNSIGNED NULL,                        -- NULL = all locations
  location_key  BIGINT UNSIGNED AS (COALESCE(location_id, 0)) STORED,
  created_by    BIGINT UNSIGNED NULL,
  created_at    DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_holidays (project_id, holiday_date, location_key),
  CONSTRAINT fk_holidays_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
  CONSTRAINT fk_holidays_location FOREIGN KEY (location_id) REFERENCES locations(id)
) ENGINE=InnoDB;
```

### 6.4 Providers

```sql
CREATE TABLE IF NOT EXISTS providers (
  id                         BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,   -- V1 id preserved
  project_id                 BIGINT UNSIGNED NOT NULL,
  code                       VARCHAR(20)  NOT NULL,
  name                       VARCHAR(255) NOT NULL,
  legal_name                 VARCHAR(255) NULL,
  status                     ENUM('onboarding','active','suspended','closed') NOT NULL DEFAULT 'active',
  contact_name               VARCHAR(255) NULL,
  contact_phone_e164         VARCHAR(20)  NULL,
  contact_phone_raw          VARCHAR(100) NULL,
  contact_email              VARCHAR(255) NULL,
  notification_email         VARCHAR(255) NULL,       -- system emails for this TP go here (replaces TP SMTP)
  reply_to_email             VARCHAR(255) NULL,       -- Reply-To on TP-originated mail (grievance replies)
  requires_external_id       BOOLEAN NOT NULL DEFAULT FALSE,
  external_id_label          VARCHAR(60) NULL,        -- e.g. 'Qiyas ID'
  registration_open_from     DATE NULL,
  registration_open_until    DATE NULL,
  registration_closed_at     DATETIME(3) NULL,
  registration_closed_by     BIGINT UNSIGNED NULL,
  registration_close_note    VARCHAR(500) NULL,
  onboarding_completed_at    DATETIME(3) NULL,
  version                    INT UNSIGNED NOT NULL DEFAULT 1,
  created_at                 DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  updated_at                 DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_providers_code (project_id, code),
  KEY ix_providers_status (project_id, status),
  CONSTRAINT fk_providers_project FOREIGN KEY (project_id) REFERENCES projects(id)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS provider_contracts (
  id                 BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,   -- V1 id preserved
  project_id         BIGINT UNSIGNED NOT NULL,
  provider_id        BIGINT UNSIGNED NOT NULL,
  contract_number    VARCHAR(80) NULL,
  signed_date        DATE NULL,
  start_date         DATE NULL,
  end_date           DATE NULL,
  target_trainees    INT UNSIGNED NOT NULL,
  effective_from     DATE NULL,
  levels_json        JSON NULL,
  notes              TEXT NULL,
  document_file_id   BIGINT UNSIGNED NULL,
  status             ENUM('draft','active','amended','closed') NOT NULL DEFAULT 'active',
  supersedes_id      BIGINT UNSIGNED NULL,
  set_by             BIGINT UNSIGNED NULL,
  created_at         DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  updated_at         DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  KEY ix_contracts_provider (provider_id, status),
  CONSTRAINT fk_contracts_provider FOREIGN KEY (provider_id) REFERENCES providers(id),
  CONSTRAINT fk_contracts_file FOREIGN KEY (document_file_id) REFERENCES files(id),
  CONSTRAINT ck_contracts_target CHECK (target_trainees > 0)
) ENGINE=InnoDB;
```

### 6.5 Access

```sql
CREATE TABLE IF NOT EXISTS roles (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  code          VARCHAR(60) NOT NULL,
  label         VARCHAR(120) NOT NULL,
  description   TEXT NULL,
  is_system     BOOLEAN NOT NULL DEFAULT FALSE,
  provider_bound BOOLEAN NOT NULL DEFAULT FALSE,        -- TP roles require provider_id on membership
  legacy_code   VARCHAR(100) NULL,
  created_at    DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_roles_code (code)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS permissions (                -- synced from code at boot
  perm_key     VARCHAR(80) PRIMARY KEY,
  category     VARCHAR(40) NOT NULL,
  label        VARCHAR(160) NOT NULL,
  description  TEXT NULL
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS role_permissions (
  role_id   BIGINT UNSIGNED NOT NULL,
  perm_key  VARCHAR(80) NOT NULL,
  PRIMARY KEY (role_id, perm_key),
  CONSTRAINT fk_rp_role FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE,
  CONSTRAINT fk_rp_perm FOREIGN KEY (perm_key) REFERENCES permissions(perm_key) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS memberships (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  project_id    BIGINT UNSIGNED NOT NULL,
  user_id       BIGINT UNSIGNED NOT NULL,
  role_id       BIGINT UNSIGNED NOT NULL,
  provider_id   BIGINT UNSIGNED NULL,
  provider_key  BIGINT UNSIGNED AS (COALESCE(provider_id, 0)) STORED,   -- NULL-safe uniqueness
  status        ENUM('active','inactive') NOT NULL DEFAULT 'active',
  invited_by    BIGINT UNSIGNED NULL,
  legacy_source VARCHAR(60) NULL,                       -- 'project_users:12' | 'tp_staff_memberships:7' | 'training_providers.user_id:3'
  created_at    DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  updated_at    DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_memberships (project_id, user_id, role_id, provider_key),
  KEY ix_memberships_user (user_id, status),
  KEY ix_memberships_provider (provider_id, status),
  CONSTRAINT fk_m_project  FOREIGN KEY (project_id)  REFERENCES projects(id) ON DELETE CASCADE,
  CONSTRAINT fk_m_user     FOREIGN KEY (user_id)     REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_m_role     FOREIGN KEY (role_id)     REFERENCES roles(id),
  CONSTRAINT fk_m_provider FOREIGN KEY (provider_id) REFERENCES providers(id)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS membership_scopes (
  id             BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  membership_id  BIGINT UNSIGNED NOT NULL,
  scope_type     ENUM('training','site','class') NOT NULL,
  scope_id       BIGINT UNSIGNED NOT NULL,
  legacy_scope_id BIGINT UNSIGNED NULL,               -- tp_staff_delivery_scopes.id
  UNIQUE KEY uq_ms (membership_id, scope_type, scope_id),
  KEY ix_ms_scope (scope_type, scope_id),
  CONSTRAINT fk_ms_membership FOREIGN KEY (membership_id) REFERENCES memberships(id) ON DELETE CASCADE
) ENGINE=InnoDB;
```

### 6.6 Delivery

```sql
CREATE TABLE IF NOT EXISTS trainings (
  id                        BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,   -- V1 id preserved
  project_id                BIGINT UNSIGNED NOT NULL,
  provider_id               BIGINT UNSIGNED NOT NULL,
  title                     VARCHAR(255) NOT NULL,
  programme_name            VARCHAR(255) NULL,               -- from V1 training_programs.name
  level                     ENUM('basic','intermediate','advanced') NOT NULL,
  duration_id               BIGINT UNSIGNED NULL,
  duration_months           TINYINT UNSIGNED NULL,
  planned_start             DATE NOT NULL,
  planned_end               DATE NOT NULL,
  default_weekdays_mask     TINYINT UNSIGNED NOT NULL DEFAULT 31,  -- Mon–Fri
  description               TEXT NULL,
  status                    ENUM('draft','active','closed') NOT NULL DEFAULT 'active',
  legacy_training_program_id BIGINT UNSIGNED NULL,
  legacy_status             VARCHAR(30) NULL,
  legacy_timeline_anchor    DATE NULL,
  legacy_location_id        BIGINT UNSIGNED NULL,
  legacy_intake_target      INT UNSIGNED NULL,
  legacy_notes              TEXT NULL,
  version                   INT UNSIGNED NOT NULL DEFAULT 1,
  created_at                DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  updated_at                DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  KEY ix_trainings_provider (project_id, provider_id, status),
  CONSTRAINT fk_tr_project  FOREIGN KEY (project_id)  REFERENCES projects(id),
  CONSTRAINT fk_tr_provider FOREIGN KEY (provider_id) REFERENCES providers(id),
  CONSTRAINT fk_tr_duration FOREIGN KEY (duration_id) REFERENCES durations(id),
  CONSTRAINT ck_tr_dates CHECK (planned_end >= planned_start),
  CONSTRAINT ck_tr_weekdays CHECK (default_weekdays_mask BETWEEN 1 AND 127)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS training_allowed_locations (     -- V1 trainings.delivery_location_ids (JSON)
  training_id  BIGINT UNSIGNED NOT NULL,
  location_id  BIGINT UNSIGNED NOT NULL,
  PRIMARY KEY (training_id, location_id),
  CONSTRAINT fk_tal_training FOREIGN KEY (training_id) REFERENCES trainings(id) ON DELETE CASCADE,
  CONSTRAINT fk_tal_location FOREIGN KEY (location_id) REFERENCES locations(id)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS training_sites (
  id                  BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,   -- V1 training_cohorts.id preserved
  project_id          BIGINT UNSIGNED NOT NULL,
  provider_id         BIGINT UNSIGNED NOT NULL,
  training_id         BIGINT UNSIGNED NOT NULL,
  location_id         BIGINT UNSIGNED NULL,
  display_name        VARCHAR(255) NOT NULL,                 -- generated "Training · Location"
  coordinator_name    VARCHAR(191) NULL,
  status              ENUM('active','closed') NOT NULL DEFAULT 'active',
  legacy_code         VARCHAR(64) NULL,
  legacy_name         VARCHAR(191) NULL,
  legacy_start_date   DATE NULL,
  legacy_end_date     DATE NULL,
  legacy_weekdays_json JSON NULL,
  legacy_timeline_anchor DATE NULL,
  version             INT UNSIGNED NOT NULL DEFAULT 1,
  created_at          DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  updated_at          DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_sites_training_legacycode (training_id, legacy_code),
  KEY ix_sites_provider (project_id, provider_id),
  KEY ix_sites_location (location_id),
  CONSTRAINT fk_site_training FOREIGN KEY (training_id) REFERENCES trainings(id),
  CONSTRAINT fk_site_provider FOREIGN KEY (provider_id) REFERENCES providers(id),
  CONSTRAINT fk_site_location FOREIGN KEY (location_id) REFERENCES locations(id)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS training_classes (
  id                  BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,   -- V1 training_batches.id preserved
  project_id          BIGINT UNSIGNED NOT NULL,
  provider_id         BIGINT UNSIGNED NOT NULL,
  training_id         BIGINT UNSIGNED NOT NULL,
  site_id             BIGINT UNSIGNED NOT NULL,
  code                VARCHAR(64)  NOT NULL,
  name                VARCHAR(191) NOT NULL,
  shift               ENUM('morning','afternoon','evening','full_day','weekend','other') NULL,
  venue               VARCHAR(191) NULL,
  weekdays_mask       TINYINT UNSIGNED NOT NULL,
  planned_start       DATE NOT NULL,
  planned_end         DATE NOT NULL,
  actual_start        DATE NULL,
  effective_start     DATE AS (COALESCE(actual_start, planned_start)) STORED,
  effective_end       DATE NOT NULL,                   -- planned_end shifted by actual-start delta and approved breakdowns
  capacity            SMALLINT UNSIGNED NULL,
  is_cancelled        BOOLEAN NOT NULL DEFAULT FALSE,
  sort_order          INT UNSIGNED NOT NULL DEFAULT 0,
  calendar_version    INT UNSIGNED NOT NULL DEFAULT 0,
  roster_frozen_at    DATETIME(3) NULL,
  legacy_campus_label VARCHAR(191) NULL,
  legacy_sections_count INT UNSIGNED NULL,
  legacy_status       VARCHAR(30) NULL,
  version             INT UNSIGNED NOT NULL DEFAULT 1,
  created_at          DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  updated_at          DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_classes_site_code (site_id, code),
  KEY ix_classes_provider (project_id, provider_id),
  KEY ix_classes_training (training_id),
  KEY ix_classes_dates (effective_start, effective_end),
  CONSTRAINT fk_class_site     FOREIGN KEY (site_id)     REFERENCES training_sites(id),
  CONSTRAINT fk_class_training FOREIGN KEY (training_id) REFERENCES trainings(id),
  CONSTRAINT fk_class_provider FOREIGN KEY (provider_id) REFERENCES providers(id),
  CONSTRAINT ck_class_dates    CHECK (planned_end >= planned_start),
  CONSTRAINT ck_class_weekdays CHECK (weekdays_mask BETWEEN 1 AND 127)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS class_calendar_days (
  class_id    BIGINT UNSIGNED NOT NULL,
  cal_date    DATE NOT NULL,
  kind        ENUM('session','holiday','breakdown','exempt','non_session') NOT NULL,
  session_no  SMALLINT UNSIGNED NULL,                    -- 1..n for kind='session'
  PRIMARY KEY (class_id, cal_date),
  KEY ix_ccd_kind (class_id, kind, cal_date),
  CONSTRAINT fk_ccd_class FOREIGN KEY (class_id) REFERENCES training_classes(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS class_counters (
  class_id            BIGINT UNSIGNED PRIMARY KEY,
  sessions_total      SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  sessions_to_date    SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  sessions_submitted  SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  sessions_missing    SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  last_session_date   DATE NULL,
  next_session_date   DATE NULL,
  tracked_trainees    SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  as_of_date          DATE NOT NULL,
  updated_at          DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  CONSTRAINT fk_cc_class FOREIGN KEY (class_id) REFERENCES training_classes(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS training_breakdowns (
  id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,   -- V1 id preserved
  project_id      BIGINT UNSIGNED NOT NULL,
  provider_id     BIGINT UNSIGNED NOT NULL,
  training_id     BIGINT UNSIGNED NOT NULL,
  site_id         BIGINT UNSIGNED NULL,
  class_id        BIGINT UNSIGNED NULL,
  start_date      DATE NOT NULL,
  end_date        DATE NOT NULL,
  reason          TEXT NOT NULL,
  status          ENUM('requested','approved','rejected','cancelled') NOT NULL DEFAULT 'requested',
  requested_by    BIGINT UNSIGNED NULL,
  requested_at    DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  decided_by      BIGINT UNSIGNED NULL,
  decided_at      DATETIME(3) NULL,
  decision_note   TEXT NULL,
  KEY ix_bd_scope (project_id, provider_id, status),
  KEY ix_bd_training (training_id, status),
  CONSTRAINT fk_bd_training FOREIGN KEY (training_id) REFERENCES trainings(id),
  CONSTRAINT fk_bd_site     FOREIGN KEY (site_id)     REFERENCES training_sites(id),
  CONSTRAINT fk_bd_class    FOREIGN KEY (class_id)    REFERENCES training_classes(id),
  CONSTRAINT ck_bd_dates CHECK (end_date >= start_date)
) ENGINE=InnoDB;
```

### 6.7 Registration

```sql
CREATE TABLE IF NOT EXISTS trainees (
  id                       BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,   -- V1 id preserved
  project_id               BIGINT UNSIGNED NOT NULL,
  provider_id              BIGINT UNSIGNED NOT NULL,
  training_id              BIGINT UNSIGNED NOT NULL,
  site_id                  BIGINT UNSIGNED NOT NULL,
  class_id                 BIGINT UNSIGNED NOT NULL,
  trainee_code             VARCHAR(40)  NOT NULL,               -- PBPS-SCV-000123 (V1 trainee_unique_id)
  external_beneficiary_id  VARCHAR(100) NULL,
  roster_status            ENUM('active','reserve','withdrawn','transferred') NOT NULL,
  withdrawal_reason        ENUM('never_started','replaced','transferred_out','registration_error','duplicate','other') NULL,
  withdrawn_at             DATETIME(3) NULL,
  replaces_trainee_id      BIGINT UNSIGNED NULL,
  attendance_eligible_from DATE NULL,
  -- personal
  first_name               VARCHAR(100) NOT NULL,
  father_name              VARCHAR(100) NULL,
  grandfather_name         VARCHAR(100) NULL,
  sex                      ENUM('male','female') NULL,
  sex_raw                  VARCHAR(20)  NULL,
  age_years                TINYINT UNSIGNED NULL,
  dob_et_raw               VARCHAR(50)  NULL,                    -- V1 date_of_birth_et_calendar verbatim
  dob_et_year              SMALLINT UNSIGNED NULL,
  dob_et_month             TINYINT UNSIGNED NULL,
  dob_et_day               TINYINT UNSIGNED NULL,
  dob_gregorian            DATE NULL,
  dob_parse_status         ENUM('ok','ambiguous','unparsable','missing') NOT NULL DEFAULT 'missing',
  form_completion_date     DATE NULL,
  form_date_confidence     ENUM('certain','ambiguous','missing') NOT NULL DEFAULT 'missing',
  -- contact
  phone_e164               VARCHAR(20)  NULL,
  phone_raw                VARCHAR(100) NULL,
  phone_alt_e164           VARCHAR(20)  NULL,
  phone_alt_raw            VARCHAR(100) NULL,
  email                    VARCHAR(254) NULL,
  kebele                   VARCHAR(80)  NULL,
  woreda                   VARCHAR(120) NULL,
  sub_city                 VARCHAR(120) NULL,
  region_code              VARCHAR(40)  NULL,
  region_raw               VARCHAR(191) NULL,
  emergency_contact_name   VARCHAR(191) NULL,
  emergency_phone_e164     VARCHAR(20)  NULL,
  emergency_phone_raw      VARCHAR(100) NULL,
  -- education & employment
  education_code           VARCHAR(40)  NULL,     -- no_formal | primary | secondary | high_school_dropout | tvet_1_4 | diploma | bachelor | above_bachelor | short_term
  education_raw            VARCHAR(100) NULL,
  previously_participated  BOOLEAN NULL,
  prior_training_type      VARCHAR(191) NULL,
  prior_completed          BOOLEAN NULL,
  prior_year_completed     SMALLINT UNSIGNED NULL,
  employment_code          VARCHAR(40)  NULL,     -- not_working | occasional | underemployed | full_time | self_employed
  employment_raw           VARCHAR(100) NULL,
  income_sufficient        BOOLEAN NULL,
  skill_usage_code         VARCHAR(20)  NULL,     -- fully | partially | not_at_all
  skill_usage_raw          VARCHAR(191) NULL,
  plan_code                VARCHAR(20)  NULL,     -- wage | self | other
  plan_raw                 VARCHAR(191) NULL,
  plan_other_text          TEXT NULL,
  -- inclusion
  is_pwd                   BOOLEAN NULL,
  disability_code          VARCHAR(30)  NULL,     -- hearing | visual | paralysis | not_pwd | prefer_not_say | other
  disability_raw           VARCHAR(191) NULL,
  disability_other_text    TEXT NULL,
  is_idp                   BOOLEAN NULL,
  is_returnee              BOOLEAN NULL,
  is_low_income            BOOLEAN NULL,
  inclusion_none           BOOLEAN NULL,
  inclusion_prefer_not_say BOOLEAN NULL,
  -- consents
  consent_accuracy         BOOLEAN NULL,
  consent_followup         BOOLEAN NULL,
  consent_contact_verify   BOOLEAN NULL,
  consent_image_use        BOOLEAN NULL,
  -- derived
  eligibility_status       ENUM('eligible','not_eligible','unknown') NOT NULL DEFAULT 'unknown',
  eligibility_reasons      JSON NULL,
  name_norm_first          VARCHAR(100) NULL,
  name_norm_father         VARCHAR(100) NULL,
  name_norm_grandfather    VARCHAR(100) NULL,
  name_key_fn_fa           VARCHAR(201) NULL,
  name_phon_fn             VARCHAR(40)  NULL,
  name_phon_fa             VARCHAR(40)  NULL,
  search_text              VARCHAR(400) NULL,      -- normalised "code first father grandfather"
  -- provenance
  raw_payload              JSON NULL,              -- V1 raw_payload verbatim
  legacy_training_type     VARCHAR(50)  NULL,
  legacy_training_location VARCHAR(191) NULL,
  legacy_location_id       BIGINT UNSIGNED NULL,
  legacy_duration_id       BIGINT UNSIGNED NULL,
  legacy_roster_role       VARCHAR(32)  NULL,
  import_batch_id          BIGINT UNSIGNED NULL,
  created_by               BIGINT UNSIGNED NULL,
  version                  INT UNSIGNED NOT NULL DEFAULT 1,
  created_at               DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  updated_at               DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_trainee_code (trainee_code),
  UNIQUE KEY uq_trainee_phone (project_id, phone_e164),
  UNIQUE KEY uq_trainee_extid (provider_id, external_beneficiary_id),
  KEY ix_tr_provider_roster (project_id, provider_id, roster_status),
  KEY ix_tr_class (class_id, roster_status),
  KEY ix_tr_training (training_id),
  KEY ix_tr_site (site_id),
  KEY ix_tr_namekey (project_id, name_key_fn_fa),
  KEY ix_tr_phon (project_id, name_phon_fn, name_phon_fa),
  KEY ix_tr_phone_alt (project_id, phone_alt_e164),
  KEY ix_tr_eligibility (project_id, provider_id, eligibility_status),
  KEY ix_tr_search (project_id, search_text(100)),
  CONSTRAINT fk_tn_provider FOREIGN KEY (provider_id) REFERENCES providers(id),
  CONSTRAINT fk_tn_training FOREIGN KEY (training_id) REFERENCES trainings(id),
  CONSTRAINT fk_tn_site     FOREIGN KEY (site_id)     REFERENCES training_sites(id),
  CONSTRAINT fk_tn_class    FOREIGN KEY (class_id)    REFERENCES training_classes(id),
  CONSTRAINT fk_tn_region   FOREIGN KEY (region_code) REFERENCES regions(code),
  CONSTRAINT fk_tn_replaces FOREIGN KEY (replaces_trainee_id) REFERENCES trainees(id),
  CONSTRAINT ck_tn_age CHECK (age_years IS NULL OR age_years BETWEEN 10 AND 80)
) ENGINE=InnoDB;

-- Current state per trainee (read model). Column groups are written only by their owning module:
--   registration → roster/eligibility copies; attendance → att_*; outcomes → *_status, dates, reasons.
CREATE TABLE IF NOT EXISTS trainee_status (
  trainee_id              BIGINT UNSIGNED PRIMARY KEY,
  project_id              BIGINT UNSIGNED NOT NULL,
  provider_id             BIGINT UNSIGNED NOT NULL,
  class_id                BIGINT UNSIGNED NOT NULL,
  roster_status           ENUM('active','reserve','withdrawn','transferred') NOT NULL,
  eligibility_status      ENUM('eligible','not_eligible','unknown') NOT NULL DEFAULT 'unknown',
  sex                     ENUM('male','female') NULL,
  location_id             BIGINT UNSIGNED NULL,
  -- attendance (owner: attendance)
  att_present             SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  att_excused             SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  att_absent              SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  att_sessions_to_date    SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  att_sessions_total      SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  att_missing_marks       SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  att_rate_to_date        DECIMAL(7,4) NULL,
  att_rate_final          DECIMAL(7,4) NULL,        -- set when class ended
  att_max_reachable       DECIMAL(7,4) NULL,
  att_last_marked_date    DATE NULL,
  att_computed_at         DATETIME(3) NULL,
  -- dropout (owner: outcomes)
  system_dropout_risk     BOOLEAN NOT NULL DEFAULT FALSE,
  system_dropout_final    BOOLEAN NOT NULL DEFAULT FALSE,
  dropout_status          ENUM('pending','no','yes') NOT NULL DEFAULT 'pending',
  dropout_source          ENUM('tp_reported','system_low_attendance','migration') NULL,
  dropout_date            DATE NULL,
  dropout_reason          VARCHAR(40) NULL,
  dropout_report_id       BIGINT UNSIGNED NULL,
  -- completion & certification
  completion_status       ENUM('pending','no','yes','not_applicable') NOT NULL DEFAULT 'pending',
  completion_source       ENUM('tp_reported','migration_reported','migration_inferred') NULL,
  completion_date         DATE NULL,
  noncompletion_reason    VARCHAR(40) NULL,
  completion_report_id    BIGINT UNSIGNED NULL,
  certification_status    ENUM('pending','no','yes','not_applicable') NOT NULL DEFAULT 'pending',
  certification_source    ENUM('tp_reported','migration_reported','migration_inferred') NULL,
  certification_date      DATE NULL,
  certificate_number      VARCHAR(80) NULL,
  certification_report_id BIGINT UNSIGNED NULL,
  -- employment pathway
  job_linkage_status      ENUM('pending','no','yes','not_applicable') NOT NULL DEFAULT 'pending',
  job_linkage_date        DATE NULL,
  decent_job_m1_status    ENUM('pending','no','yes','not_applicable') NOT NULL DEFAULT 'pending',
  decent_job_m2_status    ENUM('pending','no','yes','not_applicable') NOT NULL DEFAULT 'pending',
  job_start_date          DATE NULL,
  employment_type         ENUM('wage','self') NULL,
  locality_status         ENUM('pending','no','yes','not_applicable') NOT NULL DEFAULT 'pending',
  retention_3m_status     ENUM('pending','no','yes','not_applicable') NOT NULL DEFAULT 'pending',
  retention_check_date    DATE NULL,
  status_version          INT UNSIGNED NOT NULL DEFAULT 1,
  updated_at              DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  KEY ix_ts_provider_roster (project_id, provider_id, roster_status),
  KEY ix_ts_completion (project_id, provider_id, completion_status),
  KEY ix_ts_dropout (project_id, provider_id, dropout_status, system_dropout_final),
  KEY ix_ts_risk (project_id, provider_id, system_dropout_risk),
  KEY ix_ts_cert (project_id, provider_id, certification_status),
  KEY ix_ts_class (class_id),
  CONSTRAINT fk_ts_trainee FOREIGN KEY (trainee_id) REFERENCES trainees(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS trainee_class_history (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  trainee_id    BIGINT UNSIGNED NOT NULL,
  class_id      BIGINT UNSIGNED NOT NULL,
  from_date     DATE NULL,
  to_date       DATE NULL,
  change_reason VARCHAR(60) NOT NULL,           -- 'registered','transfer','migration_enrollment'
  legacy_enrollment_id BIGINT UNSIGNED NULL,
  created_at    DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_tch_legacy (legacy_enrollment_id),
  KEY ix_tch_trainee (trainee_id),
  CONSTRAINT fk_tch_trainee FOREIGN KEY (trainee_id) REFERENCES trainees(id) ON DELETE CASCADE,
  CONSTRAINT fk_tch_class   FOREIGN KEY (class_id) REFERENCES training_classes(id)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS import_batches (
  id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  project_id      BIGINT UNSIGNED NOT NULL,
  provider_id     BIGINT UNSIGNED NOT NULL,
  kind            ENUM('trainees','attendance','outcomes','kobo_results','roster_check') NOT NULL,
  target_json     JSON NOT NULL,                       -- training/site/class/report type…
  file_id         BIGINT UNSIGNED NOT NULL,
  status          ENUM('uploaded','validating','ready','has_errors','committing','committed','discarded','failed') NOT NULL,
  rows_total      INT UNSIGNED NOT NULL DEFAULT 0,
  rows_valid      INT UNSIGNED NOT NULL DEFAULT 0,
  rows_error      INT UNSIGNED NOT NULL DEFAULT 0,
  rows_warning    INT UNSIGNED NOT NULL DEFAULT 0,
  rows_duplicate  INT UNSIGNED NOT NULL DEFAULT 0,
  created_by      BIGINT UNSIGNED NOT NULL,
  created_at      DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  committed_at    DATETIME(3) NULL,
  KEY ix_ib_provider (project_id, provider_id, created_at),
  CONSTRAINT fk_ib_file FOREIGN KEY (file_id) REFERENCES files(id)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS import_rows (
  batch_id        BIGINT UNSIGNED NOT NULL,
  row_no          INT UNSIGNED NOT NULL,
  raw_json        JSON NOT NULL,
  parsed_json     JSON NULL,
  errors_json     JSON NULL,
  warnings_json   JSON NULL,
  duplicates_json JSON NULL,
  decision        ENUM('import','skip') NOT NULL DEFAULT 'import',
  decision_note   VARCHAR(500) NULL,
  status          ENUM('ok','error','warning','duplicate') NOT NULL,
  created_entity_id BIGINT UNSIGNED NULL,
  PRIMARY KEY (batch_id, row_no),
  KEY ix_ir_status (batch_id, status),
  CONSTRAINT fk_ir_batch FOREIGN KEY (batch_id) REFERENCES import_batches(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS roster_snapshots (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  class_id      BIGINT UNSIGNED NOT NULL,
  kind          ENUM('freeze','manual','migration_baseline') NOT NULL,
  members_count INT UNSIGNED NOT NULL,
  members_hash  CHAR(64) NOT NULL,
  taken_by      BIGINT UNSIGNED NULL,
  taken_at      DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  KEY ix_rs_class (class_id, taken_at),
  CONSTRAINT fk_rs_class FOREIGN KEY (class_id) REFERENCES training_classes(id)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS roster_snapshot_members (
  snapshot_id   BIGINT UNSIGNED NOT NULL,
  trainee_id    BIGINT UNSIGNED NOT NULL,
  roster_status ENUM('active','reserve') NOT NULL,
  PRIMARY KEY (snapshot_id, trainee_id),
  CONSTRAINT fk_rsm_snapshot FOREIGN KEY (snapshot_id) REFERENCES roster_snapshots(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS roster_change_requests (
  id             BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  project_id     BIGINT UNSIGNED NOT NULL,
  provider_id    BIGINT UNSIGNED NOT NULL,
  class_id       BIGINT UNSIGNED NOT NULL,
  trainee_id     BIGINT UNSIGNED NULL,
  change_type    ENUM('add','withdraw','transfer','update_identity','update_eligibility') NOT NULL,
  payload_json   JSON NOT NULL,
  reason         TEXT NOT NULL,
  status         ENUM('draft','submitted','approved','applied','rejected','withdrawn') NOT NULL DEFAULT 'submitted',
  requested_by   BIGINT UNSIGNED NOT NULL,
  requested_at   DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  decided_by     BIGINT UNSIGNED NULL,
  decided_at     DATETIME(3) NULL,
  decision_note  TEXT NULL,
  KEY ix_rcr_status (project_id, status, requested_at),
  KEY ix_rcr_provider (provider_id, status)
) ENGINE=InnoDB;
```

### 6.8 Duplicates

```sql
CREATE TABLE IF NOT EXISTS duplicate_scan_runs (
  id                BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,    -- V1 id preserved
  project_id        BIGINT UNSIGNED NOT NULL,
  trigger_kind      VARCHAR(32) NOT NULL,                          -- manual | nightly | import | migration
  algorithm_version VARCHAR(32) NOT NULL,
  config_json       JSON NULL,
  status            ENUM('running','finished','failed') NOT NULL,
  scanned_count     INT UNSIGNED NOT NULL DEFAULT 0,
  candidate_count   INT UNSIGNED NOT NULL DEFAULT 0,
  started_at        DATETIME(3) NOT NULL,
  finished_at       DATETIME(3) NULL,
  created_by        BIGINT UNSIGNED NULL
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS duplicate_candidates (
  id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,      -- V1 id preserved
  project_id      BIGINT UNSIGNED NOT NULL,
  scan_run_id     BIGINT UNSIGNED NULL,
  trainee_a_id    BIGINT UNSIGNED NOT NULL,
  trainee_b_id    BIGINT UNSIGNED NOT NULL,
  pair_key        VARCHAR(64) NOT NULL,                            -- "<min>::<max>"
  score           TINYINT UNSIGNED NOT NULL,
  risk            ENUM('high','medium') NOT NULL,
  signals_json    JSON NOT NULL,
  status          ENUM('pending','confirmed_duplicate','not_duplicate','merged') NOT NULL DEFAULT 'pending',
  reviewer_note   TEXT NULL,
  reviewed_by     BIGINT UNSIGNED NULL,
  reviewed_at     DATETIME(3) NULL,
  first_seen_at   DATETIME(3) NOT NULL,
  last_seen_at    DATETIME(3) NOT NULL,
  UNIQUE KEY uq_dc_pair (project_id, pair_key),
  KEY ix_dc_status (project_id, status, score),
  CONSTRAINT fk_dc_a FOREIGN KEY (trainee_a_id) REFERENCES trainees(id),
  CONSTRAINT fk_dc_b FOREIGN KEY (trainee_b_id) REFERENCES trainees(id)
) ENGINE=InnoDB;
```

### 6.9 Attendance

```sql
CREATE TABLE IF NOT EXISTS attendance_sessions (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  project_id    BIGINT UNSIGNED NOT NULL,
  provider_id   BIGINT UNSIGNED NOT NULL,
  class_id      BIGINT UNSIGNED NOT NULL,
  session_date  DATE NOT NULL,
  status        ENUM('submitted','corrected','locked') NOT NULL DEFAULT 'submitted',
  source        ENUM('manual','csv','backfill','migration_manual','migration_csv','migration_mixed') NOT NULL,
  marks_count   SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  present_count SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  absent_count  SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  excused_count SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  submitted_by  BIGINT UNSIGNED NULL,
  submitted_at  DATETIME(3) NOT NULL,
  UNIQUE KEY uq_as_class_date (class_id, session_date),
  KEY ix_as_provider_date (project_id, provider_id, session_date),
  CONSTRAINT fk_as_class FOREIGN KEY (class_id) REFERENCES training_classes(id)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS attendance_marks (
  session_id   BIGINT UNSIGNED NOT NULL,
  trainee_id   BIGINT UNSIGNED NOT NULL,
  status       TINYINT UNSIGNED NOT NULL,              -- 1 present, 2 absent, 3 excused
  reason_code  VARCHAR(30) NULL,                       -- for excused
  is_backfill  BOOLEAN NOT NULL DEFAULT FALSE,
  marked_at    DATETIME(3) NOT NULL,
  PRIMARY KEY (session_id, trainee_id),
  KEY ix_am_trainee (trainee_id, session_id),
  CONSTRAINT fk_am_session FOREIGN KEY (session_id) REFERENCES attendance_sessions(id) ON DELETE CASCADE,
  CONSTRAINT fk_am_trainee FOREIGN KEY (trainee_id) REFERENCES trainees(id),
  CONSTRAINT ck_am_status CHECK (status IN (1,2,3))
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS attendance_corrections (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  session_id    BIGINT UNSIGNED NOT NULL,
  trainee_id    BIGINT UNSIGNED NOT NULL,
  from_status   TINYINT UNSIGNED NULL,
  to_status     TINYINT UNSIGNED NOT NULL,
  reason        TEXT NOT NULL,
  status        ENUM('requested','approved','rejected') NOT NULL DEFAULT 'requested',
  requested_by  BIGINT UNSIGNED NOT NULL,
  requested_at  DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  decided_by    BIGINT UNSIGNED NULL,
  decided_at    DATETIME(3) NULL,
  decision_note TEXT NULL,
  KEY ix_ac_status (status, requested_at),
  CONSTRAINT fk_ac_session FOREIGN KEY (session_id) REFERENCES attendance_sessions(id)
) ENGINE=InnoDB;
```

### 6.10 Outcomes

```sql
CREATE TABLE IF NOT EXISTS outcome_reports (
  id                   BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,   -- V1 outcome_report_batches.id preserved
  project_id           BIGINT UNSIGNED NOT NULL,
  provider_id          BIGINT UNSIGNED NOT NULL,
  training_id          BIGINT UNSIGNED NOT NULL,
  site_id              BIGINT UNSIGNED NULL,
  class_id             BIGINT UNSIGNED NOT NULL,
  report_type          ENUM('dropout','completion','certification','job_linkage','decent_job','locality_compliant','job_retention_3m') NOT NULL,
  stage_key            VARCHAR(20) NOT NULL DEFAULT '',                -- '' when not staged (keeps UNIQUE usable)
  version_no           SMALLINT UNSIGNED NOT NULL DEFAULT 1,
  status               ENUM('draft','ready','accepted','returned','superseded','discarded') NOT NULL,
  source_file_id       BIGINT UNSIGNED NULL,
  source_filename      VARCHAR(255) NULL,
  rows_total           INT UNSIGNED NOT NULL DEFAULT 0,
  yes_count            INT UNSIGNED NOT NULL DEFAULT 0,
  no_count             INT UNSIGNED NOT NULL DEFAULT 0,
  na_count             INT UNSIGNED NOT NULL DEFAULT 0,
  reason_for_change    TEXT NULL,
  supersedes_report_id BIGINT UNSIGNED NULL,
  submitted_by         BIGINT UNSIGNED NULL,
  submitted_at         DATETIME(3) NULL,
  reviewed_by          BIGINT UNSIGNED NULL,
  reviewed_at          DATETIME(3) NULL,
  review_note          TEXT NULL,
  is_legacy_partial_roster BOOLEAN NOT NULL DEFAULT FALSE,             -- V1 completion/certification reports list only "yes"
  legacy_meta          JSON NULL,
  created_at           DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  updated_at           DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_or_version (class_id, report_type, stage_key, version_no),
  KEY ix_or_status (class_id, report_type, stage_key, status),
  KEY ix_or_provider (project_id, provider_id, report_type, status),
  CONSTRAINT fk_or_class FOREIGN KEY (class_id) REFERENCES training_classes(id)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS outcome_report_lines (
  id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,      -- V1 trainee_outcomes.id preserved
  report_id       BIGINT UNSIGNED NOT NULL,
  trainee_id      BIGINT UNSIGNED NOT NULL,
  value           ENUM('yes','no') NOT NULL,
  event_date      DATE NULL,                                       -- completion/certification/dropout/job start date
  reason_code     VARCHAR(40) NULL,
  details_json    JSON NULL,                                       -- type-specific fields (employer, salary, …)
  raw_json        JSON NULL,                                       -- original CSV cells / V1 meta
  legacy_status_date DATE NULL,
  created_at      DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_orl (report_id, trainee_id),
  KEY ix_orl_trainee (trainee_id, report_id),
  CONSTRAINT fk_orl_report  FOREIGN KEY (report_id)  REFERENCES outcome_reports(id) ON DELETE CASCADE,
  CONSTRAINT fk_orl_trainee FOREIGN KEY (trainee_id) REFERENCES trainees(id)
) ENGINE=InnoDB;
```

### 6.11 Indicators

```sql
CREATE TABLE IF NOT EXISTS indicator_definitions (
  id                    BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,   -- V1 project_indicators.id preserved for the 11
  project_id            BIGINT UNSIGNED NOT NULL,
  code                  VARCHAR(80) NOT NULL,
  version_no            SMALLINT UNSIGNED NOT NULL DEFAULT 1,
  status                ENUM('draft','active','retired') NOT NULL DEFAULT 'active',
  protocol_no           TINYINT UNSIGNED NULL,
  name                  VARCHAR(255) NOT NULL,
  unit                  ENUM('count','percent') NOT NULL,
  level                 ENUM('trainee','provider') NOT NULL,
  purpose               ENUM('monitoring','verification','monitoring_and_verification') NOT NULL,
  operational_definition TEXT NULL,
  data_sources          TEXT NULL,
  collection_method     TEXT NULL,
  frequency             VARCHAR(255) NULL,
  computation_text      TEXT NULL,
  numerator_metric      VARCHAR(80) NOT NULL,
  denominator_metric    VARCHAR(80) NULL,
  direction             ENUM('higher_is_better','lower_is_better') NOT NULL DEFAULT 'higher_is_better',
  default_target        DECIMAL(9,4) NULL,
  comparator            ENUM('>=','<=','=') NOT NULL DEFAULT '>=',
  disaggregations_json  JSON NULL,
  verification_method   ENUM('sampling','full_review','document_review','system','none') NOT NULL DEFAULT 'none',
  payment_linkage       TEXT NULL,
  display_order         SMALLINT NOT NULL DEFAULT 0,
  effective_from        DATE NULL,
  approved_by           BIGINT UNSIGNED NULL,
  approved_at           DATETIME(3) NULL,
  change_note           TEXT NULL,
  legacy_json           JSON NULL,                                 -- V1 row (variables, claim_mode, cohort_filter…)
  created_at            DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_ind_version (project_id, code, version_no),
  KEY ix_ind_active (project_id, status, display_order)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS indicator_stages (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,         -- V1 id preserved
  project_id    BIGINT UNSIGNED NOT NULL,
  indicator_code VARCHAR(80) NOT NULL,
  stage_key     VARCHAR(20) NOT NULL,
  label         VARCHAR(120) NOT NULL,
  offset_days   SMALLINT NOT NULL,                                 -- from class end
  is_final      BOOLEAN NOT NULL DEFAULT FALSE,
  sort_order    SMALLINT NOT NULL DEFAULT 0,
  is_active     BOOLEAN NOT NULL DEFAULT TRUE,
  UNIQUE KEY uq_stage (project_id, indicator_code, stage_key)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS indicator_targets (
  id             BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  project_id     BIGINT UNSIGNED NOT NULL,
  indicator_code VARCHAR(80) NOT NULL,
  provider_id    BIGINT UNSIGNED NULL,                             -- NULL = project default
  provider_key   BIGINT UNSIGNED AS (COALESCE(provider_id, 0)) STORED,
  target_value   DECIMAL(9,4) NOT NULL,
  comparator     ENUM('>=','<=','=') NOT NULL DEFAULT '>=',
  effective_from DATE NOT NULL,
  effective_to   DATE NULL,
  note           TEXT NULL,
  set_by         BIGINT UNSIGNED NULL,
  set_at         DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_target (project_id, indicator_code, provider_key, effective_from),
  KEY ix_target_lookup (project_id, indicator_code, provider_key, effective_from, effective_to)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS kpi_snapshots (
  project_id      BIGINT UNSIGNED NOT NULL,
  indicator_code  VARCHAR(80) NOT NULL,
  layer           ENUM('monitoring','verified') NOT NULL,
  provider_key    BIGINT UNSIGNED NOT NULL,                        -- 0 = project total
  dimension_key   VARCHAR(80) NOT NULL DEFAULT '',                 -- '' | 'sex=female' | 'location=2' | …
  as_of_date      DATE NOT NULL,
  definition_version SMALLINT UNSIGNED NOT NULL,
  numerator       DECIMAL(14,4) NULL,
  denominator     DECIMAL(14,4) NULL,
  value           DECIMAL(9,4) NULL,
  target_value    DECIMAL(9,4) NULL,
  target_source   ENUM('provider','project_default','definition','none') NOT NULL DEFAULT 'none',
  status          ENUM('met','not_met','no_data','not_applicable') NOT NULL,
  detail_json     JSON NULL,                                       -- buffers, caps, CI bounds, run id…
  computed_at     DATETIME(3) NOT NULL,
  inputs_hash     CHAR(64) NULL,
  PRIMARY KEY (project_id, indicator_code, layer, provider_key, dimension_key, as_of_date),
  KEY ix_kpi_date (project_id, as_of_date, layer)
) ENGINE=InnoDB;
```

### 6.12 Activities

```sql
CREATE TABLE IF NOT EXISTS activity_definitions (
  id                    BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,   -- V1 project_activities.id preserved
  project_id            BIGINT UNSIGNED NOT NULL,
  code                  VARCHAR(64) NOT NULL,
  name                  VARCHAR(255) NOT NULL,
  description           TEXT NULL,
  scope                 ENUM('provider','training','site','class') NOT NULL,
  linked_indicator_code VARCHAR(80) NULL,
  evidence_rules_json   JSON NULL,                                 -- allowed types, min files, checklist items
  recurrence            ENUM('once','monthly') NOT NULL DEFAULT 'once',
  is_active             BOOLEAN NOT NULL DEFAULT TRUE,
  sort_order            INT NOT NULL DEFAULT 0,
  created_by_provider_id BIGINT UNSIGNED NULL,
  legacy_submission_scope VARCHAR(16) NULL,
  created_at            DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_ad_code (project_id, code)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS activity_assignments (               -- which providers an activity applies to (V1 kept)
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,       -- V1 id preserved
  definition_id BIGINT UNSIGNED NOT NULL,
  provider_id   BIGINT UNSIGNED NOT NULL,
  UNIQUE KEY uq_aa (definition_id, provider_id),
  CONSTRAINT fk_aa_def FOREIGN KEY (definition_id) REFERENCES activity_definitions(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS activity_schedules (
  id                BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,   -- V1 project_activity_rules.id preserved (as legacy, inactive)
  definition_id     BIGINT UNSIGNED NOT NULL,
  applies_level     ENUM('basic','intermediate','advanced') NULL,
  applies_duration_id BIGINT UNSIGNED NULL,
  applies_provider_id BIGINT UNSIGNED NULL,
  anchor            ENUM('contract_signed_date','provider_first_class_start','training_planned_start','site_first_class_start','class_start','class_end') NOT NULL,
  open_offset_days  SMALLINT NOT NULL DEFAULT 0,
  due_offset_days   SMALLINT NOT NULL,
  grace_days        SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  repeat_every_days SMALLINT UNSIGNED NULL,
  repeat_count      SMALLINT UNSIGNED NULL,
  breakdown_extends BOOLEAN NOT NULL DEFAULT TRUE,
  is_active         BOOLEAN NOT NULL DEFAULT TRUE,
  schedule_version  INT UNSIGNED NOT NULL DEFAULT 1,
  legacy_rule_json  JSON NULL,
  created_at        DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  KEY ix_as_def (definition_id, is_active),
  CONSTRAINT fk_as_def FOREIGN KEY (definition_id) REFERENCES activity_definitions(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS activity_obligations (
  id                  BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  project_id          BIGINT UNSIGNED NOT NULL,
  provider_id         BIGINT UNSIGNED NOT NULL,
  definition_id       BIGINT UNSIGNED NOT NULL,
  training_id         BIGINT UNSIGNED NULL,
  site_id             BIGINT UNSIGNED NULL,
  class_id            BIGINT UNSIGNED NULL,
  scope_key           VARCHAR(60) NOT NULL,                      -- 'provider' | 'class:76' …  (for UNIQUE)
  sequence_no         SMALLINT UNSIGNED NOT NULL DEFAULT 1,
  open_date           DATE NOT NULL,
  due_date            DATE NOT NULL,
  close_date          DATE NOT NULL,
  status              ENUM('upcoming','open','submitted','approved','returned','overdue','waived') NOT NULL,
  latest_submission_id BIGINT UNSIGNED NULL,
  schedule_id         BIGINT UNSIGNED NULL,
  schedule_version    INT UNSIGNED NULL,
  waived_reason       TEXT NULL,
  updated_at          DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_obl (provider_id, definition_id, scope_key, sequence_no),
  KEY ix_obl_due (project_id, status, due_date),
  KEY ix_obl_provider (provider_id, status, due_date),
  CONSTRAINT fk_obl_def FOREIGN KEY (definition_id) REFERENCES activity_definitions(id)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS activity_submissions (
  id             BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,       -- V1 tp_activity_submissions.id preserved
  obligation_id  BIGINT UNSIGNED NULL,
  project_id     BIGINT UNSIGNED NOT NULL,
  provider_id    BIGINT UNSIGNED NOT NULL,
  definition_id  BIGINT UNSIGNED NOT NULL,
  version_no     SMALLINT UNSIGNED NOT NULL DEFAULT 1,
  checklist_json JSON NULL,
  note           TEXT NULL,
  status         ENUM('submitted','approved','returned','superseded') NOT NULL DEFAULT 'submitted',
  is_late        BOOLEAN NOT NULL DEFAULT FALSE,
  submitted_by   BIGINT UNSIGNED NULL,
  submitted_at   DATETIME(3) NOT NULL,
  reviewed_by    BIGINT UNSIGNED NULL,
  reviewed_at    DATETIME(3) NULL,
  review_json    JSON NULL,                                        -- per-checklist-item decisions
  review_note    TEXT NULL,
  legacy_scope_json JSON NULL,                                     -- V1 training/cohort/batch ids + meta
  KEY ix_sub_obl (obligation_id),
  KEY ix_sub_provider (provider_id, status),
  CONSTRAINT fk_sub_obl FOREIGN KEY (obligation_id) REFERENCES activity_obligations(id)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS activity_submission_files (
  submission_id BIGINT UNSIGNED NOT NULL,
  file_id       BIGINT UNSIGNED NOT NULL,
  legacy_file_row_id BIGINT UNSIGNED NULL,
  PRIMARY KEY (submission_id, file_id),
  CONSTRAINT fk_asf_sub  FOREIGN KEY (submission_id) REFERENCES activity_submissions(id) ON DELETE CASCADE,
  CONSTRAINT fk_asf_file FOREIGN KEY (file_id) REFERENCES files(id)
) ENGINE=InnoDB;
```

### 6.13 Verification

```sql
CREATE TABLE IF NOT EXISTS verification_plans (
  id                  BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  project_id          BIGINT UNSIGNED NOT NULL,
  indicator_code      VARCHAR(80) NOT NULL,
  version_no          SMALLINT UNSIGNED NOT NULL DEFAULT 1,
  status              ENUM('draft','active','retired') NOT NULL DEFAULT 'active',
  population_metric   VARCHAR(80) NOT NULL,              -- 'trainees.registered' (V1) | 'trainees.eligible' | 'trainees.completed' …
  stratify_by_json    JSON NOT NULL,                     -- ["location","sex"]
  size_method         ENUM('cochran_fpc','fixed','proportion') NOT NULL DEFAULT 'cochran_fpc',
  z_value             DECIMAL(6,4) NOT NULL DEFAULT 1.9600,
  p_value             DECIMAL(6,4) NOT NULL DEFAULT 0.5000,
  margin_e            DECIMAL(6,4) NOT NULL DEFAULT 0.0500,
  non_response_factor DECIMAL(6,4) NOT NULL DEFAULT 0.9000,
  reserve_pct         DECIMAL(6,2) NOT NULL DEFAULT 15.00,
  min_per_stratum     TINYINT UNSIGNED NOT NULL DEFAULT 1,
  tiering             ENUM('single','two_tier') NOT NULL DEFAULT 'two_tier',
  tier2_rule_json     JSON NULL,
  estimator           ENUM('wilson_one_sided','wilson_two_sided','clopper_pearson','simple_rate') NOT NULL DEFAULT 'wilson_one_sided',
  ci_z_value          DECIMAL(6,4) NOT NULL DEFAULT 1.6450,
  decision_rule       ENUM('ci_vs_target','point_vs_target') NOT NULL DEFAULT 'ci_vs_target',
  definite_codes_json JSON NOT NULL,                     -- ["V-COMP","V-NCOMP"]
  max_call_attempts   TINYINT UNSIGNED NOT NULL DEFAULT 3,
  questionnaire_key   VARCHAR(60) NULL,
  effective_from      DATE NULL,
  notes               TEXT NULL,
  created_at          DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_vp (project_id, indicator_code, version_no)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS verification_runs (
  id                 BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,    -- V1 id preserved
  project_id         BIGINT UNSIGNED NOT NULL,
  provider_id        BIGINT UNSIGNED NOT NULL,
  plan_id            BIGINT UNSIGNED NOT NULL,
  indicator_code     VARCHAR(80) NOT NULL,
  report_type        VARCHAR(40) NULL,
  stage_key          VARCHAR(20) NOT NULL DEFAULT '',
  period_key         CHAR(7) NULL,                                  -- YYYY-MM
  round_no           SMALLINT UNSIGNED NOT NULL DEFAULT 1,
  tier               TINYINT UNSIGNED NOT NULL DEFAULT 1,
  parent_run_id      BIGINT UNSIGNED NULL,
  training_id        BIGINT UNSIGNED NULL,
  status             ENUM('planned','drawn','in_field','under_review','finalised','cancelled') NOT NULL,
  is_pre_report_draw BOOLEAN NOT NULL DEFAULT FALSE,
  seed               VARCHAR(64) NULL,
  sampling_strategy  VARCHAR(64) NULL,
  parameters_json    JSON NOT NULL,                                 -- frozen copy of plan parameters
  population_count   INT UNSIGNED NOT NULL,
  n0                 INT UNSIGNED NULL,
  n_fpc              INT UNSIGNED NULL,
  sample_size        INT UNSIGNED NOT NULL,
  reserve_total      INT UNSIGNED NULL,
  cnt_primary        INT UNSIGNED NOT NULL DEFAULT 0,
  cnt_reserve        INT UNSIGNED NOT NULL DEFAULT 0,
  cnt_completed      INT UNSIGNED NOT NULL DEFAULT 0,
  cnt_definite       INT UNSIGNED NOT NULL DEFAULT 0,
  cnt_success        INT UNSIGNED NOT NULL DEFAULT 0,
  cnt_unreachable    INT UNSIGNED NOT NULL DEFAULT 0,
  cnt_refused        INT UNSIGNED NOT NULL DEFAULT 0,
  cnt_inconclusive   INT UNSIGNED NOT NULL DEFAULT 0,
  verified_rate_pct  DECIMAL(8,3) NULL,
  ci_lower_pct       DECIMAL(8,3) NULL,
  ci_upper_pct       DECIMAL(8,3) NULL,
  target_used        DECIMAL(9,4) NULL,
  pathway            ENUM('clear_pass','clear_fail','inconclusive') NULL,
  drawn_at           DATETIME(3) NOT NULL,
  finalised_at       DATETIME(3) NULL,
  finalised_by       BIGINT UNSIGNED NULL,
  created_by         BIGINT UNSIGNED NULL,
  report_file_id     BIGINT UNSIGNED NULL,
  legacy_json        JSON NULL,
  created_at         DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  updated_at         DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  KEY ix_vr_scope (project_id, indicator_code, provider_id, status),
  KEY ix_vr_parent (parent_run_id),
  CONSTRAINT fk_vr_plan FOREIGN KEY (plan_id) REFERENCES verification_plans(id)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS verification_frame_members (       -- frozen population at draw
  run_id        BIGINT UNSIGNED NOT NULL,
  trainee_id    BIGINT UNSIGNED NOT NULL,
  stratum_key   VARCHAR(191) NOT NULL,
  claim_value   BOOLEAN NULL,
  attrs_json    JSON NOT NULL,                       -- name, phones, training, location, sex at draw time
  PRIMARY KEY (run_id, trainee_id),
  CONSTRAINT fk_vfm_run FOREIGN KEY (run_id) REFERENCES verification_runs(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS verification_strata (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,   -- V1 id preserved
  run_id        BIGINT UNSIGNED NOT NULL,
  stratum_key   VARCHAR(191) NOT NULL,
  location_id   BIGINT UNSIGNED NULL,
  location_name VARCHAR(255) NOT NULL,
  sex_key       VARCHAR(32) NOT NULL,
  population    INT UNSIGNED NOT NULL,
  primary_drawn INT UNSIGNED NOT NULL,
  reserve_drawn INT UNSIGNED NOT NULL,
  KEY ix_vs_run (run_id),
  CONSTRAINT fk_vs_run FOREIGN KEY (run_id) REFERENCES verification_runs(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS verification_subjects (
  id                    BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,   -- V1 id preserved
  run_id                BIGINT UNSIGNED NOT NULL,
  trainee_id            BIGINT UNSIGNED NOT NULL,
  subject_key           VARCHAR(40) NOT NULL,                         -- VS-<run>-<seq> for Kobo
  role                  ENUM('primary','reserve','replacement') NOT NULL,
  stratum_key           VARCHAR(191) NULL,
  reserve_order         INT UNSIGNED NULL,
  replaces_subject_id   BIGINT UNSIGNED NULL,
  replacement_reason    VARCHAR(64) NULL,
  assigned_enumerator_id BIGINT UNSIGNED NULL,
  status_code           ENUM('V-COMP','V-NCOMP','V-UNR','V-REF','V-INC') NULL,
  verified_value        BOOLEAN NULL,
  tp_claim_value        BOOLEAN NOT NULL DEFAULT TRUE,
  supervisor_status     ENUM('pending','approved','rejected') NOT NULL DEFAULT 'pending',
  reviewer_note         TEXT NULL,
  verified_at           DATETIME(3) NULL,
  verified_by           BIGINT UNSIGNED NULL,
  is_auto_dropout       BOOLEAN NOT NULL DEFAULT FALSE,
  created_at            DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  updated_at            DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_vsub_run_trainee (run_id, trainee_id),
  UNIQUE KEY uq_vsub_key (subject_key),
  KEY ix_vsub_status (run_id, role, status_code),
  KEY ix_vsub_enum (assigned_enumerator_id, status_code),
  CONSTRAINT fk_vsub_run FOREIGN KEY (run_id) REFERENCES verification_runs(id) ON DELETE CASCADE,
  CONSTRAINT fk_vsub_trainee FOREIGN KEY (trainee_id) REFERENCES trainees(id)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS verification_call_attempts (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  subject_id    BIGINT UNSIGNED NOT NULL,
  attempt_no    TINYINT UNSIGNED NOT NULL,
  called_at     DATETIME(3) NOT NULL,
  phone_used    VARCHAR(20) NULL,
  outcome       ENUM('reached','no_answer','busy','switched_off','wrong_number','call_back_requested') NOT NULL,
  note          TEXT NULL,
  enumerator_id BIGINT UNSIGNED NOT NULL,
  UNIQUE KEY uq_vca (subject_id, attempt_no),
  CONSTRAINT fk_vca_subject FOREIGN KEY (subject_id) REFERENCES verification_subjects(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS verification_responses (
  id                    BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  subject_id            BIGINT UNSIGNED NOT NULL,
  questionnaire_key     VARCHAR(60) NOT NULL,
  answers_json          JSON NOT NULL,
  derived_status_code   ENUM('V-COMP','V-NCOMP','V-UNR','V-REF','V-INC') NULL,
  source                ENUM('mis_form','kobo_import') NOT NULL,
  kobo_submission_uuid  VARCHAR(64) NULL,
  submitted_by          BIGINT UNSIGNED NULL,
  submitted_at          DATETIME(3) NOT NULL,
  UNIQUE KEY uq_vr_kobo (kobo_submission_uuid),
  KEY ix_vresp_subject (subject_id),
  CONSTRAINT fk_vresp_subject FOREIGN KEY (subject_id) REFERENCES verification_subjects(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS verification_evidence (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,   -- V1 id preserved
  subject_id    BIGINT UNSIGNED NOT NULL,
  evidence_type VARCHAR(64) NOT NULL,
  file_id       BIGINT UNSIGNED NOT NULL,
  uploaded_by   BIGINT UNSIGNED NULL,
  created_at    DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  CONSTRAINT fk_ve_subject FOREIGN KEY (subject_id) REFERENCES verification_subjects(id) ON DELETE CASCADE,
  CONSTRAINT fk_ve_file FOREIGN KEY (file_id) REFERENCES files(id)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS verification_run_dropouts (       -- V1 table kept (auto V-NCOMP at draw)
  id          BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,     -- V1 id preserved
  run_id      BIGINT UNSIGNED NOT NULL,
  trainee_id  BIGINT UNSIGNED NOT NULL,
  UNIQUE KEY uq_vrd (run_id, trainee_id),
  CONSTRAINT fk_vrd_run FOREIGN KEY (run_id) REFERENCES verification_runs(id) ON DELETE CASCADE
) ENGINE=InnoDB;
```

### 6.14 Grievance

```sql
CREATE TABLE IF NOT EXISTS grievance_cases (
  id                  BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,   -- V1 feedback_threads.id preserved
  project_id          BIGINT UNSIGNED NOT NULL,
  provider_id         BIGINT UNSIGNED NOT NULL,
  ref                 VARCHAR(40) NOT NULL,                         -- V1 ref_code kept
  category            ENUM('complaint','suggestion','question','appreciation') NOT NULL,
  channel             ENUM('web','phone','in_person','email') NOT NULL DEFAULT 'web',
  priority            ENUM('normal','high') NOT NULL DEFAULT 'normal',
  subject             VARCHAR(255) NOT NULL,
  description         TEXT NOT NULL,
  submitter_name      VARCHAR(255) NOT NULL,
  submitter_email     VARCHAR(254) NOT NULL,
  submitter_phone     VARCHAR(40) NULL,
  region              VARCHAR(191) NULL,
  status              ENUM('new','acknowledged','in_progress','responded','resolved','closed','escalated','reopened') NOT NULL,
  assigned_to         BIGINT UNSIGNED NULL,
  submitted_at        DATETIME(3) NOT NULL,
  due_at              DATETIME(3) NOT NULL,
  first_response_at   DATETIME(3) NULL,
  resolved_at         DATETIME(3) NULL,
  closed_at           DATETIME(3) NULL,
  escalated_at        DATETIME(3) NULL,
  satisfaction_score  TINYINT UNSIGNED NULL,
  satisfaction_comment TEXT NULL,
  satisfaction_token_hash CHAR(64) NULL,
  tags_json           JSON NULL,
  legacy_status       VARCHAR(32) NULL,
  created_at          DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  updated_at          DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  UNIQUE KEY uq_gc_ref (ref),
  KEY ix_gc_provider (project_id, provider_id, status, due_at),
  KEY ix_gc_due (project_id, status, due_at),
  CONSTRAINT ck_gc_sat CHECK (satisfaction_score IS NULL OR satisfaction_score BETWEEN 1 AND 5)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS grievance_messages (
  id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,     -- V1 feedback_messages.id preserved
  case_id         BIGINT UNSIGNED NOT NULL,
  author_type     ENUM('public','tp','me','admin','system') NOT NULL,
  author_user_id  BIGINT UNSIGNED NULL,
  author_name     VARCHAR(255) NOT NULL,
  body            TEXT NOT NULL,
  visibility      ENUM('public','internal') NOT NULL DEFAULT 'public',
  email_outbox_id BIGINT UNSIGNED NULL,
  legacy_email_sent_at DATETIME(3) NULL,
  legacy_email_error TEXT NULL,
  created_at      DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  KEY ix_gm_case (case_id, created_at),
  CONSTRAINT fk_gm_case FOREIGN KEY (case_id) REFERENCES grievance_cases(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS grievance_actions (
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  case_id      BIGINT UNSIGNED NOT NULL,
  description  TEXT NOT NULL,
  owner_name   VARCHAR(191) NULL,
  due_date     DATE NULL,
  status       ENUM('open','done','cancelled') NOT NULL DEFAULT 'open',
  created_by   BIGINT UNSIGNED NOT NULL,
  created_at   DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  completed_at DATETIME(3) NULL,
  KEY ix_ga_case (case_id),
  CONSTRAINT fk_ga_case FOREIGN KEY (case_id) REFERENCES grievance_cases(id) ON DELETE CASCADE
) ENGINE=InnoDB;
```

### 6.15 Notifications and mail

```sql
CREATE TABLE IF NOT EXISTS mail_settings (
  id              TINYINT UNSIGNED PRIMARY KEY DEFAULT 1,
  from_name       VARCHAR(255) NOT NULL,
  from_email      VARCHAR(255) NOT NULL,
  smtp_host       VARCHAR(255) NOT NULL,
  smtp_port       SMALLINT UNSIGNED NOT NULL,
  smtp_secure     ENUM('none','starttls','tls') NOT NULL DEFAULT 'starttls',
  smtp_user       VARCHAR(255) NULL,
  smtp_password_enc VARBINARY(512) NULL,
  is_enabled      BOOLEAN NOT NULL DEFAULT TRUE,
  updated_by      BIGINT UNSIGNED NULL,
  updated_at      DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  CONSTRAINT ck_ms_single CHECK (id = 1)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS email_outbox (
  id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  project_id      BIGINT UNSIGNED NULL,
  to_email        VARCHAR(254) NOT NULL,
  cc_json         JSON NULL,
  reply_to        VARCHAR(254) NULL,
  from_name       VARCHAR(255) NULL,
  subject         VARCHAR(255) NOT NULL,
  html_body       MEDIUMTEXT NOT NULL,
  text_body       MEDIUMTEXT NOT NULL,
  template_key    VARCHAR(80) NOT NULL,
  entity_type     VARCHAR(40) NULL,
  entity_id       BIGINT UNSIGNED NULL,
  dedupe_key      VARCHAR(191) NULL,
  status          ENUM('queued','sending','sent','failed','dead') NOT NULL DEFAULT 'queued',
  attempts        SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  next_attempt_at DATETIME(3) NOT NULL,
  last_error      TEXT NULL,
  provider_message_id VARCHAR(255) NULL,
  created_at      DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  sent_at         DATETIME(3) NULL,
  UNIQUE KEY uq_eo_dedupe (dedupe_key),
  KEY ix_eo_pick (status, next_attempt_at)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS notifications (
  id          BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  project_id  BIGINT UNSIGNED NULL,
  user_id     BIGINT UNSIGNED NOT NULL,
  type        VARCHAR(80) NOT NULL,
  severity    ENUM('info','warning','critical') NOT NULL DEFAULT 'info',
  title       VARCHAR(255) NOT NULL,
  body        TEXT NULL,
  link        VARCHAR(500) NULL,
  entity_type VARCHAR(40) NULL,
  entity_id   BIGINT UNSIGNED NULL,
  dedupe_key  VARCHAR(191) NULL,
  created_at  DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  read_at     DATETIME(3) NULL,
  UNIQUE KEY uq_notif_dedupe (dedupe_key),
  KEY ix_notif_user (user_id, read_at, created_at),
  CONSTRAINT fk_notif_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS notification_preferences (
  user_id   BIGINT UNSIGNED NOT NULL,
  type      VARCHAR(80) NOT NULL,
  in_app    BOOLEAN NOT NULL DEFAULT TRUE,
  email     ENUM('immediate','daily_digest','off') NOT NULL DEFAULT 'immediate',
  PRIMARY KEY (user_id, type),
  CONSTRAINT fk_np_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS reminder_rules (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  project_id    BIGINT UNSIGNED NOT NULL,
  rule_key      VARCHAR(80) NOT NULL,              -- 'grievance.sla', 'obligation.due', 'attendance.missing', …
  is_enabled    BOOLEAN NOT NULL DEFAULT TRUE,
  offsets_json  JSON NOT NULL,                     -- e.g. [-2,0,1,3,5] days relative to the rule's date field
  repeat_after_days SMALLINT UNSIGNED NULL,
  severity      ENUM('info','warning','critical') NOT NULL DEFAULT 'warning',
  email_enabled BOOLEAN NOT NULL DEFAULT TRUE,
  config_json   JSON NULL,
  legacy_alert_rule_id BIGINT UNSIGNED NULL,
  UNIQUE KEY uq_rr (project_id, rule_key)
) ENGINE=InnoDB;
```

### 6.16 Audit and data health

```sql
CREATE TABLE IF NOT EXISTS audit_events (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  project_id    BIGINT UNSIGNED NULL,
  occurred_at   DATETIME(3) NOT NULL,
  actor_user_id BIGINT UNSIGNED NULL,
  actor_role    VARCHAR(60) NULL,
  ip            VARCHAR(64) NULL,
  request_id    VARCHAR(40) NULL,
  module        VARCHAR(40) NOT NULL,
  action        VARCHAR(80) NOT NULL,
  entity_type   VARCHAR(40) NULL,
  entity_id     BIGINT UNSIGNED NULL,
  provider_id   BIGINT UNSIGNED NULL,
  summary       VARCHAR(500) NULL,
  before_json   JSON NULL,
  after_json    JSON NULL,
  payload_sha256 CHAR(64) NULL,
  prev_hash     CHAR(64) NULL,
  hash          CHAR(64) NOT NULL,
  KEY ix_ae_project_time (project_id, occurred_at),
  KEY ix_ae_entity (entity_type, entity_id),
  KEY ix_ae_actor (actor_user_id, occurred_at)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS audit_chain_heads (
  project_id     BIGINT UNSIGNED PRIMARY KEY,       -- 0 for global events
  last_event_id  BIGINT UNSIGNED NOT NULL,
  last_hash      CHAR(64) NOT NULL
) ENGINE=InnoDB;

-- verbatim copy of V1 submission_events (incl. V1 chain hashes) — never updated
CREATE TABLE IF NOT EXISTS audit_events_legacy LIKE pbps_mis.submission_events;

CREATE TABLE IF NOT EXISTS datahealth_findings (
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  project_id   BIGINT UNSIGNED NOT NULL,
  check_key    VARCHAR(80) NOT NULL,
  severity     ENUM('info','warning','error') NOT NULL,
  provider_id  BIGINT UNSIGNED NULL,
  entity_type  VARCHAR(40) NOT NULL DEFAULT '',            -- '' / 0 instead of NULL keeps the UNIQUE key effective
  entity_id    BIGINT UNSIGNED NOT NULL DEFAULT 0,
  message      VARCHAR(500) NOT NULL,
  detail_json  JSON NULL,
  first_seen_at DATETIME(3) NOT NULL,
  last_seen_at  DATETIME(3) NOT NULL,
  resolved_at   DATETIME(3) NULL,
  UNIQUE KEY uq_dh (project_id, check_key, entity_type, entity_id),
  KEY ix_dh_open (project_id, resolved_at, severity),
  KEY ix_dh_provider (provider_id, resolved_at)
) ENGINE=InnoDB;
```

> `CREATE TABLE … LIKE pbps_mis.submission_events` copies the V1 structure including its indexes; foreign keys are not copied (desired — the legacy audit must not depend on V2 rows).

---

## 7. Index and constraint rationale

| Query pattern (hot path) | Index used | Why |
|---|---|---|
| KPI: tracked trainees per provider by status | `trainee_status.ix_ts_completion` / `ix_ts_dropout` / `ix_ts_provider_roster` | Range on (project, provider) with status prefix → covering counts |
| Trainee list filters | `trainees.ix_tr_provider_roster`, `ix_tr_class`, `ix_tr_eligibility` | Leftmost prefix on the most selective filter; server-side pagination |
| Trainee search | `uq_trainee_code`, `uq_trainee_phone`, `ix_tr_search` (prefix) | Equality/prefix lookups, no `%…%` |
| Duplicate candidate generation | `ix_tr_namekey`, `ix_tr_phon`, `uq_trainee_phone`, `ix_tr_phone_alt` | Blocking keys → < 20 candidates per record |
| Attendance sheet (class × date) | `attendance_sessions.uq_as_class_date` + `attendance_marks` PK | Unique session lookup, contiguous marks |
| Trainee attendance history | `attendance_marks.ix_am_trainee` | Per-trainee range |
| Missing sessions (to-do) | `class_calendar_days.ix_ccd_kind` anti-joined with `uq_as_class_date` | Small per class |
| Outcome status board per class | `outcome_reports.ix_or_status` | Latest accepted report per type |
| Obligations due / overdue | `activity_obligations.ix_obl_due`, `ix_obl_provider` | Date-range scans by status |
| Reminders | `grievance_cases.ix_gc_due`, `ix_obl_due`, `notifications.uq_notif_dedupe` | Indexed date windows; dedupe makes reminders idempotent |
| Dashboard KPIs | `kpi_snapshots` PK / `ix_kpi_date` | Point lookups |
| Enumerator work list | `verification_subjects.ix_vsub_enum` | Per enumerator |
| Audit browsing | `audit_events.ix_ae_project_time`, `ix_ae_entity` | Time window / entity history |

Constraints enforce what V1 enforced in code only: unique phone per project, one line per trainee per report, one session per class per date, one attendance mark per trainee per session, valid weekday masks, date ordering, status enums, positive contract targets.

---

## 8. Migration architecture

### 8.1 Flow

```
         (1) mysqldump pbps_mis  ──►  (2) restore on MySQL 8.4 server as pbps_mis (read-only)
                                                   │
                                   (3) 01_schema.sql creates pbps_v2 + pbps_legacy
                                                   │
             (4) runner executes 02…60 SQL scripts + TS enrichment steps in order
                     │                 │                      │
               pbps_v2 tables     pbps_legacy copies     migration_issues
                                                   │
             (5) post-processing using V2 application services (calendars, counters, KPIs, obligations)
                                                   │
             (6) 90_reconcile.sql + KPI parity  ──►  reconciliation report (gate)
```

### 8.2 The runner (`migration/run-migration.ts`)

- Reads `migration/sql/*.sql` in name order; for each: records a `migration_runs` row (`running`), executes statements in a transaction where possible (DDL auto-commits — DDL lives only in `01_schema.sql`), records `rows_affected`, `ok`/`failed`, sha256 of the script.
- TS steps (`*.step.ts`) are interleaved by number (e.g. `21_enrich_trainees.step.ts`) and use the **same validators** as the V2 application (`shared/validation`).
- Options: `--label rehearsal-2`, `--from 20 --to 40` (partial), `--fresh` (drop and recreate `pbps_v2`, then run everything).
- Session settings: `SET SESSION sql_mode = 'STRICT_ALL_TABLES,NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO'; SET SESSION time_zone = '+00:00';` — strict mode makes unexpected values **fail loudly** instead of being truncated.

### 8.3 Idempotency patterns used

| Pattern | Used for | Why |
|---|---|---|
| `INSERT … SELECT … WHERE NOT EXISTS (SELECT 1 FROM target WHERE target.id = source.id)` | all entity copies with preserved IDs | Re-runs insert only missing rows; any *other* unique-key conflict raises an error (deliberately — no silent skipping) |
| `INSERT … ON DUPLICATE KEY UPDATE` | reference data with only a PK/natural key (regions, aliases, settings, sequences) | Re-runs refresh values |
| `UPDATE target JOIN source …` with deterministic expressions | derived columns (statuses, confidence flags, counts) | Same inputs → same outputs |
| `CREATE TABLE IF NOT EXISTS` / `DROP FUNCTION IF EXISTS` + `CREATE FUNCTION` | DDL, helper functions | |
| `--fresh` full rebuild | rehearsals and cutover | At pilot scale the whole migration takes minutes; a clean rebuild is the simplest proof of determinism |

`INSERT IGNORE` is **not** used for entities: it hides errors (truncation, FK failures, unexpected duplicates) and could silently drop a row — the opposite of P1.

---

## 9. Migration scripts — ordered, idempotent SQL

> All scripts assume `USE pbps_v2;` and read from `pbps_mis.*`. Project id 1 (`PBPS`) is the only project in V1; scripts are nevertheless written for any number of projects.

### 9.0 `00_preflight.sql` — assertions on the source (every query must return 0 rows / 0)

```sql
-- P0.1 every trainee has a class, site and training
SELECT COUNT(*) AS trainees_missing_scope FROM pbps_mis.trainees
 WHERE batch_id IS NULL OR cohort_id IS NULL OR training_id IS NULL;
-- P0.2 class belongs to the trainee's site and training
SELECT COUNT(*) AS trainee_scope_mismatch FROM pbps_mis.trainees t
  JOIN pbps_mis.training_batches b ON b.id = t.batch_id
 WHERE b.cohort_id <> t.cohort_id OR b.training_id <> t.training_id;
-- P0.3 outcome rows have a report batch, a value, and a known type
SELECT COUNT(*) AS bad_outcomes FROM pbps_mis.trainee_outcomes
 WHERE report_batch_id IS NULL OR reported_value IS NULL
    OR outcome_type NOT IN ('dropout','completion','certification','job_linkage','decent_job','locality_compliant','job_retention_3m');
-- P0.4 report batches have a class
SELECT COUNT(*) AS report_batches_without_class FROM pbps_mis.outcome_report_batches WHERE batch_id IS NULL;
-- P0.5 one report batch per (class, type, stage)
SELECT COUNT(*) AS duplicate_report_scopes FROM (
  SELECT batch_id, report_type, COALESCE(JSON_UNQUOTE(JSON_EXTRACT(meta,'$.stageKey')),'') sk
    FROM pbps_mis.outcome_report_batches GROUP BY 1,2,3 HAVING COUNT(*) > 1) x;
-- P0.6 no duplicate outcome line per report/trainee
SELECT COUNT(*) AS duplicate_lines FROM (
  SELECT report_batch_id, trainee_id FROM pbps_mis.trainee_outcomes GROUP BY 1,2 HAVING COUNT(*) > 1) x;
-- P0.7 attendance statuses known; attendance batch = trainee batch
SELECT COUNT(*) AS bad_attendance FROM pbps_mis.trainee_attendance_days a
  JOIN pbps_mis.trainees t ON t.id = a.trainee_id
 WHERE a.status NOT IN ('present','absent','excused') OR a.batch_id <> t.batch_id;
-- P0.8 normalised phone collisions (must be 0, else see §9.4.2)
SELECT COUNT(*) AS phone_collisions FROM (
  SELECT RIGHT(REGEXP_REPLACE(phone_primary,'[^0-9]',''),9) k FROM pbps_mis.trainees
   WHERE phone_primary IS NOT NULL AND phone_primary <> '' GROUP BY project_id, k HAVING COUNT(*) > 1) x;
-- P0.9 users: unique e-mail after lower/trim
SELECT COUNT(*) AS email_collisions FROM (
  SELECT LOWER(TRIM(email)) e FROM pbps_mis.users GROUP BY e HAVING COUNT(*) > 1) x;
```

(On the analysed data all of these return 0 — verified during the analysis.)

### 9.1 `01_schema.sql`

The DDL of §6, plus helper functions:

```sql
DROP FUNCTION IF EXISTS fn_norm;
DELIMITER $$
CREATE FUNCTION fn_norm(s VARCHAR(500)) RETURNS VARCHAR(500) DETERMINISTIC NO SQL
BEGIN
  IF s IS NULL THEN RETURN NULL; END IF;
  -- lower-case, typographic apostrophes/dashes to ASCII, non-alphanumerics to space, collapse spaces
  SET s = LOWER(s);
  SET s = REPLACE(REPLACE(REPLACE(s, '’', ''''), '–', '-'), '—', '-');
  SET s = REGEXP_REPLACE(s, '[^[:alnum:]]+', ' ');
  RETURN TRIM(s);
END$$
DELIMITER ;

DROP FUNCTION IF EXISTS fn_phone_e164;
DELIMITER $$
CREATE FUNCTION fn_phone_e164(raw VARCHAR(100)) RETURNS VARCHAR(20) DETERMINISTIC NO SQL
BEGIN
  DECLARE d VARCHAR(100);
  IF raw IS NULL OR TRIM(raw) = '' THEN RETURN NULL; END IF;
  IF raw REGEXP '[eE][+-]?[0-9]+$' THEN RETURN NULL; END IF;          -- scientific notation → invalid
  SET d = REGEXP_REPLACE(REGEXP_REPLACE(raw, '\\.0$', ''), '[^0-9]', '');
  IF d REGEXP '^251[79][0-9]{8}$' THEN RETURN CONCAT('+', d); END IF;
  IF d REGEXP '^0[79][0-9]{8}$'   THEN RETURN CONCAT('+251', SUBSTRING(d, 2)); END IF;
  IF d REGEXP '^[79][0-9]{8}$'    THEN RETURN CONCAT('+251', d); END IF;
  RETURN NULL;
END$$
DELIMITER ;

DROP FUNCTION IF EXISTS fn_parse_mdy;
DELIMITER $$
CREATE FUNCTION fn_parse_mdy(s VARCHAR(40)) RETURNS DATE DETERMINISTIC NO SQL
BEGIN
  -- V1 outcome meta dates are Excel M/D/YYYY strings ("8/27/2026"); also accept ISO
  IF s IS NULL THEN RETURN NULL; END IF;
  SET s = TRIM(s);
  IF s REGEXP '^[0-9]{4}-[0-9]{2}-[0-9]{2}' THEN RETURN STR_TO_DATE(LEFT(s,10), '%Y-%m-%d'); END IF;
  IF s REGEXP '^(1[0-2]|0?[1-9])/(3[01]|[12][0-9]|0?[1-9])/[0-9]{4}$' THEN RETURN STR_TO_DATE(s, '%m/%d/%Y'); END IF;
  RETURN NULL;
END$$
DELIMITER ;

DROP FUNCTION IF EXISTS fn_weekday_mask;
DELIMITER $$
CREATE FUNCTION fn_weekday_mask(j JSON) RETURNS TINYINT UNSIGNED DETERMINISTIC NO SQL
BEGIN
  -- V1 session_weekdays: JSON array of ISO weekdays (Mon=1 … Sun=7); NULL/empty → Mon–Fri (V1 default)
  DECLARE m INT DEFAULT 0;
  DECLARE i INT DEFAULT 0;
  DECLARE n INT;
  IF j IS NULL OR JSON_LENGTH(j) = 0 THEN RETURN 31; END IF;
  SET n = JSON_LENGTH(j);
  WHILE i < n DO
    SET m = m | (1 << (CAST(JSON_UNQUOTE(JSON_EXTRACT(j, CONCAT('$[', i, ']'))) AS UNSIGNED) - 1));
    SET i = i + 1;
  END WHILE;
  RETURN m;
END$$
DELIMITER ;
```

(`fn_weekday_mask` uses a loop instead of `JSON_TABLE` so it also runs on MariaDB 10.6+.)

### 9.2 `02_reference.sql` — regions, aliases, locations, durations, projects, settings

```sql
-- Regions / city administrations
INSERT INTO regions (code, name, kind, sort_order) VALUES
 ('addis_ababa','Addis Ababa','city_administration',1), ('dire_dawa','Dire Dawa','city_administration',2),
 ('afar','Afar','region',10), ('amhara','Amhara','region',11), ('benishangul_gumuz','Benishangul-Gumuz','region',12),
 ('central_ethiopia','Central Ethiopia','region',13), ('gambella','Gambella','region',14), ('harari','Harari','region',15),
 ('oromia','Oromia','region',16), ('sidama','Sidama','region',17), ('somali','Somali','region',18),
 ('south_ethiopia','South Ethiopia','region',19), ('south_west_ethiopia','South West Ethiopia Peoples','region',20),
 ('tigray','Tigray','region',21)
ON DUPLICATE KEY UPDATE name = VALUES(name), kind = VALUES(kind), sort_order = VALUES(sort_order);

-- Region aliases (alias_norm = fn_norm(alias)); extend after reviewing migration_issues REGION_UNKNOWN
INSERT INTO enum_aliases (domain, alias_norm, canonical) VALUES
 ('region','addis ababa','addis_ababa'), ('region','addis abeba','addis_ababa'), ('region','adiss ababa','addis_ababa'),
 ('region','addisabeba','addis_ababa'), ('region','addis','addis_ababa'), ('region','a a','addis_ababa'), ('region','aa','addis_ababa'),
 ('region','finfinne','addis_ababa'), ('region','sheger city','oromia'), ('region','sheger','oromia'),
 ('region','amhara','amhara'), ('region','amhara region','amhara'),
 ('region','central ethiopia','central_ethiopia'), ('region','central ethiopia regional state','central_ethiopia'),
 ('region','central ethiopian region','central_ethiopia'), ('region','central ethiopian','central_ethiopia'),
 ('region','oromia','oromia'), ('region','oromiya','oromia'), ('region','oromia region','oromia'),
 ('region','tigray','tigray'), ('region','south ethiopia','south_ethiopia'), ('region','sidama','sidama'),
 ('region','afar','afar'), ('region','somali','somali'), ('region','harari','harari'), ('region','dire dawa','dire_dawa'),
 ('region','gambella','gambella'), ('region','benishangul gumuz','benishangul_gumuz'),
 ('region','south west ethiopia','south_west_ethiopia'), ('region','south west ethiopia peoples','south_west_ethiopia'),
 -- further spellings found in the live data profile
 ('region','adis abeba','addis_ababa'), ('region','adissababa','addis_ababa'), ('region','addisababa','addis_ababa'),
 ('region','adiss abeba','addis_ababa'), ('region','addiss ababa','addis_ababa'), ('region','addis abba','addis_ababa'),
 ('region','gulele','addis_ababa'),            -- Gulele is a sub-city of Addis Ababa (the value also goes to sub_city review)
 ('region','amahara','amhara')
ON DUPLICATE KEY UPDATE canonical = VALUES(canonical);
-- Intentionally NOT aliased (→ region_code NULL + issue for TP confirmation):
--   'ethiopia' (3, REGION_TOO_GENERIC), 'snnpr' and 'south' (former SNNP region, now split into several regions — ambiguous),
--   'oriental orthodox', '0', '3', '' (data-entry errors).

-- Education (V1 stores normalised lower-case labels)
INSERT INTO enum_aliases (domain, alias_norm, canonical) VALUES
 ('education','no formal education','no_formal'), ('education','primary','primary'), ('education','primary grades 1 8','primary'),
 ('education','secondary grades 9 12','secondary'), ('education','secondary','secondary'), ('education','grade 12','secondary'),
 ('education','high school dropout','high_school_dropout'),
 ('education','tvet certificate level i iv','tvet_1_4'), ('education','tvet','tvet_1_4'),
 ('education','diploma','diploma'), ('education','bachelor s degree','bachelor'), ('education','bachelors degree','bachelor'),
 ('education','above bachelor s','above_bachelor'), ('education','above bachelors','above_bachelor'),
 ('education','short term training','short_term')
ON DUPLICATE KEY UPDATE canonical = VALUES(canonical);

-- Employment
INSERT INTO enum_aliases (domain, alias_norm, canonical) VALUES
 ('employment','not currently working','not_working'), ('employment','unemployed','not_working'),
 ('employment','working occasionally','occasional'),
 ('employment','working fewer hours than desired','underemployed'),
 ('employment','working fewer hours than desired but willing and available to work more hours','underemployed'),
 ('employment','working full time for an employer','full_time'), ('employment','self employed','self_employed'),
 ('employment','self employed running own business','self_employed')
ON DUPLICATE KEY UPDATE canonical = VALUES(canonical);

-- Disability
INSERT INTO enum_aliases (domain, alias_norm, canonical) VALUES
 ('disability','hearing impairment','hearing'), ('disability','visual impairment','visual'), ('disability','paralysis','paralysis'),
 ('disability','not a person with disability','not_pwd'), ('disability','none','not_pwd'), ('disability','no','not_pwd'),
 ('disability','nothing','not_pwd'), ('disability','prefer not to say','prefer_not_say'), ('disability','other','other')
ON DUPLICATE KEY UPDATE canonical = VALUES(canonical);

-- Skill usage, plan
INSERT INTO enum_aliases (domain, alias_norm, canonical) VALUES
 ('skill_usage','fully','fully'), ('skill_usage','partially','partially'), ('skill_usage','not at all','not_at_all'),
 ('plan','wage employment','wage'), ('plan','self employment','self'), ('plan','other','other')
ON DUPLICATE KEY UPDATE canonical = VALUES(canonical);

-- Locations (ids preserved) — Hossana is in Central Ethiopia Region, Dessie in Amhara
INSERT INTO locations (id, code, name, region_code, is_active, created_at)
SELECT l.id, l.code, l.name,
       CASE l.code WHEN 'AA' THEN 'addis_ababa' WHEN 'HO' THEN 'central_ethiopia' WHEN 'DE' THEN 'amhara' ELSE NULL END,
       l.is_active, l.created_at
  FROM pbps_mis.locations l
 WHERE NOT EXISTS (SELECT 1 FROM locations x WHERE x.id = l.id);

-- Durations (ids preserved)
INSERT INTO durations (id, months, label, sort_order, is_active)
SELECT d.id, d.months, d.label, d.sort_order, d.is_active FROM pbps_mis.training_durations d
 WHERE NOT EXISTS (SELECT 1 FROM durations x WHERE x.id = d.id);

-- Projects (ids preserved; meta exploded)
INSERT INTO projects (id, code, title, donor, sector, location_text, description, start_date, end_date,
                      over_enrolment_pct, registration_closed_at, registration_closed_by, registration_close_note,
                      legacy_meta, created_at, updated_at)
SELECT p.id, p.project_code, p.title, p.donor, p.sector, p.location,
       JSON_UNQUOTE(JSON_EXTRACT(p.meta,'$.description')),
       fn_parse_mdy(JSON_UNQUOTE(JSON_EXTRACT(p.meta,'$.startDate'))),
       fn_parse_mdy(JSON_UNQUOTE(JSON_EXTRACT(p.meta,'$.endDate'))),
       p.max_overenrollment_percent, p.registration_closed_at, p.registration_closed_by_user_id, p.registration_close_note,
       p.meta, p.created_at, p.updated_at
  FROM pbps_mis.projects p
 WHERE NOT EXISTS (SELECT 1 FROM projects x WHERE x.id = p.id);

-- Project-level policy values from V1 app_settings
UPDATE projects pr
   SET exempt_days_from_class_start = COALESCE((SELECT CAST(value AS UNSIGNED) FROM pbps_mis.app_settings WHERE `key`='attendance.exempt_days_from_scope_start'), 14),
       replacement_window_days     = COALESCE((SELECT CAST(value AS UNSIGNED) FROM pbps_mis.app_settings WHERE `key`='trainee.replacement_window_days'), 14);

-- Global settings
INSERT INTO app_settings (setting_key, value_json)
SELECT CONCAT('legacy.', s.`key`), JSON_QUOTE(COALESCE(s.value,'')) FROM pbps_mis.app_settings s
ON DUPLICATE KEY UPDATE value_json = VALUES(value_json);
INSERT INTO app_settings (setting_key, value_json) VALUES
 ('security.require_2fa_roles', JSON_ARRAY('system_admin','me_lead','verification_supervisor')),
 ('notifications.quiet_hours', JSON_OBJECT('from','20:00','to','07:00'))
ON DUPLICATE KEY UPDATE setting_key = setting_key;

-- Holidays (ids preserved)
INSERT INTO holidays (id, project_id, holiday_date, label, kind, created_at)
SELECT h.id, h.project_id, h.holiday_date, h.label, 'national', h.created_at FROM pbps_mis.project_holidays h
 WHERE NOT EXISTS (SELECT 1 FROM holidays x WHERE x.id = h.id);
```

### 9.3 `10_identity_access.sql`

```sql
-- Users (ids preserved; bcrypt hashes copied unchanged)
INSERT INTO users (id, name, email, password_hash, status, must_change_password, password_changed_at,
                   failed_login_count, first_failed_at, locked_until, two_factor_method, email_verified_at, created_at, updated_at)
SELECT u.id, u.name, LOWER(TRIM(u.email)), u.password, 'active', u.must_change_password, u.password_changed_at,
       u.failed_login_attempts, u.first_failed_login_at, u.locked_until,
       CASE WHEN (SELECT value FROM pbps_mis.app_settings WHERE `key`='security.email_2fa_enabled') IN ('1','true') AND u.two_factor_enabled
            THEN 'email' ELSE 'none' END,
       u.email_verified_at, u.created_at, u.updated_at
  FROM pbps_mis.users u
 WHERE NOT EXISTS (SELECT 1 FROM users x WHERE x.id = u.id);

-- System roles (permissions are synced from code by the application at first boot)
INSERT INTO roles (code, label, is_system, provider_bound, legacy_code) VALUES
 ('system_admin','System administrator',TRUE,FALSE,'admin'),
 ('me_lead','M&E lead',TRUE,FALSE,'me'),
 ('me_officer','M&E officer',TRUE,FALSE,NULL),
 ('verification_supervisor','Verification supervisor',TRUE,FALSE,NULL),
 ('verification_enumerator','Verification enumerator',TRUE,FALSE,NULL),
 ('data_quality_officer','Data quality officer',TRUE,FALSE,NULL),
 ('funder_viewer','Funder (read-only)',TRUE,FALSE,'world_bank,edi'),
 ('tp_admin','TP organisation admin',TRUE,TRUE,'tp/tp_org_admin'),
 ('tp_site_lead','TP site lead',TRUE,TRUE,'tp_site_lead'),
 ('tp_attendance_clerk','TP attendance clerk',TRUE,TRUE,'tp_attendance_clerk'),
 ('tp_outcomes_officer','TP outcomes officer',TRUE,TRUE,'tp_outcomes_officer'),
 ('tp_viewer','TP viewer',TRUE,TRUE,'tp_readonly')
ON DUPLICATE KEY UPDATE label = VALUES(label), provider_bound = VALUES(provider_bound), legacy_code = VALUES(legacy_code);

-- Custom (non-system) V1 roles are carried over with their code prefixed
INSERT INTO roles (code, label, description, is_system, legacy_code)
SELECT CONCAT('custom_', r.code), r.label, r.description, FALSE, r.code FROM pbps_mis.roles r
 WHERE r.code NOT IN ('admin','me','tp','world_bank','edi')
   AND NOT EXISTS (SELECT 1 FROM roles x WHERE x.legacy_code = r.code);

-- Memberships: non-TP project roles
INSERT INTO memberships (project_id, user_id, role_id, provider_id, status, legacy_source, created_at)
SELECT pu.project_id, pu.user_id, r.id, NULL, 'active', CONCAT('project_users:', pu.id), pu.created_at
  FROM pbps_mis.project_users pu
  JOIN roles r ON r.code = CASE pu.project_role WHEN 'admin' THEN 'system_admin' WHEN 'me' THEN 'me_lead'
                                                WHEN 'world_bank' THEN 'funder_viewer' WHEN 'edi' THEN 'funder_viewer'
                                                ELSE CONCAT('custom_', pu.project_role) END
 WHERE pu.project_role <> 'tp'
   AND NOT EXISTS (SELECT 1 FROM memberships m WHERE m.legacy_source = CONCAT('project_users:', pu.id));

-- Memberships: TP staff (each V1 TP user has exactly one staff membership)
INSERT INTO memberships (project_id, user_id, role_id, provider_id, status, invited_by, legacy_source, created_at)
SELECT s.project_id, s.user_id, r.id, s.training_provider_id, IF(s.is_active,'active','inactive'), s.invited_by_user_id,
       CONCAT('tp_staff_memberships:', s.id), s.created_at
  FROM pbps_mis.tp_staff_memberships s
  JOIN roles r ON r.code = CASE s.staff_role WHEN 'tp_org_admin' THEN 'tp_admin' WHEN 'tp_readonly' THEN 'tp_viewer' ELSE s.staff_role END
 WHERE NOT EXISTS (SELECT 1 FROM memberships m WHERE m.legacy_source = CONCAT('tp_staff_memberships:', s.id));

-- Memberships: provider owners without a staff membership (none in current data; kept for safety)
INSERT INTO memberships (project_id, user_id, role_id, provider_id, status, legacy_source)
SELECT tp.project_id, tp.user_id, (SELECT id FROM roles WHERE code='tp_admin'), tp.id, 'active', CONCAT('training_providers.user_id:', tp.id)
  FROM pbps_mis.training_providers tp
 WHERE tp.user_id IS NOT NULL
   AND NOT EXISTS (SELECT 1 FROM pbps_mis.tp_staff_memberships s WHERE s.user_id = tp.user_id AND s.training_provider_id = tp.id)
   AND NOT EXISTS (SELECT 1 FROM memberships m WHERE m.legacy_source = CONCAT('training_providers.user_id:', tp.id));

-- Scopes (provider-level rows are implicit in V2 and are not copied)
INSERT INTO membership_scopes (membership_id, scope_type, scope_id, legacy_scope_id)
SELECT m.id, IF(ds.scope_level = 'batch','class','site'), IF(ds.scope_level = 'batch', ds.batch_id, ds.cohort_id), ds.id
  FROM pbps_mis.tp_staff_delivery_scopes ds
  JOIN memberships m ON m.legacy_source = CONCAT('tp_staff_memberships:', ds.tp_staff_membership_id)
 WHERE ds.scope_level IN ('cohort','batch')
   AND NOT EXISTS (SELECT 1 FROM membership_scopes x WHERE x.legacy_scope_id = ds.id);
```

Role-permission grants are **not** copied 1:1 (new keys, corrected grants). The V1 `role_permissions` table is archived and a comparison report (`V1 grant → V2 grant`) is produced for sign-off (Part R-15).

### 9.4 `20_providers_delivery.sql`

```sql
-- Providers (ids preserved). notification/reply-to e-mails seeded from V1 contact_email (TPs confirm after go-live).
INSERT INTO providers (id, project_id, code, name, status, contact_name, contact_phone_e164, contact_phone_raw, contact_email,
                       notification_email, reply_to_email, requires_external_id, external_id_label,
                       registration_closed_at, registration_closed_by, registration_close_note, created_at, updated_at)
SELECT p.id, p.project_id, p.tp_code, p.name, 'active', p.contact_name, fn_phone_e164(p.contact_phone), p.contact_phone,
       LOWER(TRIM(p.contact_email)), LOWER(TRIM(p.contact_email)), LOWER(TRIM(p.contact_email)),
       p.require_external_beneficiary_id, IF(p.require_external_beneficiary_id, 'Provider beneficiary ID', NULL),
       p.registration_closed_at, p.registration_closed_by_user_id, p.registration_close_note, p.created_at, p.updated_at
  FROM pbps_mis.training_providers p
 WHERE NOT EXISTS (SELECT 1 FROM providers x WHERE x.id = p.id);

-- Contracts (ids preserved)
INSERT INTO provider_contracts (id, project_id, provider_id, target_trainees, effective_from, notes, status, set_by, created_at, updated_at)
SELECT c.id, c.project_id, c.training_provider_id, c.contract_target, c.effective_from, c.notes, 'active', c.set_by_user_id, c.created_at, c.updated_at
  FROM pbps_mis.training_provider_contracts c
 WHERE NOT EXISTS (SELECT 1 FROM provider_contracts x WHERE x.id = c.id);

-- Trainings (ids preserved; program merged; level/duration normalised)
INSERT INTO trainings (id, project_id, provider_id, title, programme_name, level, duration_id, duration_months,
                       planned_start, planned_end, default_weekdays_mask, status,
                       legacy_training_program_id, legacy_status, legacy_timeline_anchor, legacy_location_id, legacy_intake_target, legacy_notes,
                       created_at, updated_at)
SELECT t.id, t.project_id, t.training_provider_id, t.title, pg.name,
       LOWER(t.training_type), t.training_duration_id, d.months,
       DATE(t.start_date), DATE(t.end_date), fn_weekday_mask(t.session_weekdays), 'active',
       t.training_program_id, t.status, DATE(t.timeline_anchor_date), t.location_id, t.intake_target, t.notes,
       t.created_at, t.updated_at
  FROM pbps_mis.trainings t
  LEFT JOIN pbps_mis.training_programs pg ON pg.id = t.training_program_id
  LEFT JOIN pbps_mis.training_durations d ON d.id = t.training_duration_id
 WHERE NOT EXISTS (SELECT 1 FROM trainings x WHERE x.id = t.id);

-- Allowed delivery locations (V1 JSON array of id strings)
INSERT INTO training_allowed_locations (training_id, location_id)
SELECT t.id, CAST(JSON_UNQUOTE(JSON_EXTRACT(t.delivery_location_ids, CONCAT('$[', n.i, ']'))) AS UNSIGNED)
  FROM pbps_mis.trainings t
  JOIN (SELECT 0 i UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5) n
    ON n.i < JSON_LENGTH(t.delivery_location_ids)
 WHERE t.delivery_location_ids IS NOT NULL
   AND NOT EXISTS (SELECT 1 FROM training_allowed_locations x
                    WHERE x.training_id = t.id
                      AND x.location_id = CAST(JSON_UNQUOTE(JSON_EXTRACT(t.delivery_location_ids, CONCAT('$[', n.i, ']'))) AS UNSIGNED));

-- Sites from cohorts (ids preserved). Display name = training title · location name (falls back to V1 name).
INSERT INTO training_sites (id, project_id, provider_id, training_id, location_id, display_name, status,
                            legacy_code, legacy_name, legacy_start_date, legacy_end_date, legacy_weekdays_json, legacy_timeline_anchor,
                            created_at, updated_at)
SELECT c.id, c.project_id, c.training_provider_id, c.training_id, c.location_id,
       CONCAT(t.title, ' · ', COALESCE(l.name, c.name)), 'active',
       c.code, c.name, DATE(c.start_date), DATE(c.end_date), c.session_weekdays, DATE(c.timeline_anchor_date),
       c.created_at, c.updated_at
  FROM pbps_mis.training_cohorts c
  JOIN pbps_mis.trainings t ON t.id = c.training_id
  LEFT JOIN pbps_mis.locations l ON l.id = c.location_id
 WHERE NOT EXISTS (SELECT 1 FROM training_sites x WHERE x.id = c.id);

-- Classes from batches (ids preserved). Shift inferred from the name; actual start from timeline anchor.
INSERT INTO training_classes (id, project_id, provider_id, training_id, site_id, code, name, shift, weekdays_mask,
                              planned_start, planned_end, actual_start, effective_end, sort_order,
                              legacy_campus_label, legacy_sections_count, legacy_status, created_at, updated_at)
SELECT b.id, b.project_id, b.training_provider_id, b.training_id, b.cohort_id,
       b.code, b.name,
       CASE WHEN LOWER(b.name) LIKE '%morning%' OR b.code LIKE '%-M' THEN 'morning'
            WHEN LOWER(b.name) LIKE '%afternoon%' OR b.code LIKE '%-A' THEN 'afternoon'
            ELSE NULL END,
       fn_weekday_mask(COALESCE(b.session_weekdays, t.session_weekdays)),
       DATE(b.start_date), DATE(b.end_date), DATE(b.timeline_anchor_date),
       DATE(b.end_date) + INTERVAL COALESCE(DATEDIFF(DATE(b.timeline_anchor_date), DATE(b.start_date)), 0) DAY,  -- V1 shift rule
       b.sort_order, b.campus_label, b.sections_count, b.status, b.created_at, b.updated_at
  FROM pbps_mis.training_batches b
  JOIN pbps_mis.trainings t ON t.id = b.training_id
 WHERE NOT EXISTS (SELECT 1 FROM training_classes x WHERE x.id = b.id);

-- Breakdowns (ids preserved)
INSERT INTO training_breakdowns (id, project_id, provider_id, training_id, site_id, class_id, start_date, end_date, reason, status,
                                 requested_by, requested_at, decided_by, decided_at)
SELECT b.id, b.project_id, b.training_provider_id, b.training_id, b.cohort_id, b.batch_id, b.break_start_date, b.break_end_date,
       b.reason, b.status, b.requested_by_user_id, b.created_at, b.approved_by_user_id, b.approved_at
  FROM pbps_mis.training_breakdowns b
 WHERE NOT EXISTS (SELECT 1 FROM training_breakdowns x WHERE x.id = b.id);
```

> V1 cohort/batch `start_date`/`end_date` were `DATETIME 12:00:00`; `DATE()` keeps the calendar day exactly. Cohort-level dates are kept as `legacy_*` (in V2 a site's dates are derived from its classes).

#### 9.4.1 Class names (no data changed, display improved)

The V1 `name` is kept verbatim. Where V1 used the code as the meaningful part (e.g. code "Selam class 3", name "Cohort 1"), the UI shows `code — name`; M&E/TPs can rename after migration. A report `migration/reports/class_names.csv` lists every class with training, site, code, name, shift, weekdays so TPs can confirm or correct.

### 9.5 `30_trainees.sql`

```sql
-- 9.5.1 Insert trainees (ids preserved). Plain INSERT: any unexpected unique-key conflict stops the run.
INSERT INTO trainees (
  id, project_id, provider_id, training_id, site_id, class_id, trainee_code, external_beneficiary_id,
  roster_status, withdrawal_reason, replaces_trainee_id, attendance_eligible_from,
  first_name, father_name, grandfather_name, sex, sex_raw, age_years, dob_et_raw,
  form_completion_date, form_date_confidence,
  phone_e164, phone_raw, phone_alt_e164, phone_alt_raw, email, kebele, woreda, sub_city, region_code, region_raw,
  emergency_contact_name, emergency_phone_e164, emergency_phone_raw,
  education_code, education_raw, previously_participated, prior_training_type, prior_completed, prior_year_completed,
  employment_code, employment_raw, income_sufficient, skill_usage_code, skill_usage_raw, plan_code, plan_raw, plan_other_text,
  is_pwd, disability_code, disability_raw, disability_other_text, is_idp, is_returnee, is_low_income, inclusion_none, inclusion_prefer_not_say,
  consent_accuracy, consent_followup, consent_contact_verify, consent_image_use,
  raw_payload, legacy_training_type, legacy_training_location, legacy_location_id, legacy_duration_id, legacy_roster_role,
  created_at, updated_at)
SELECT
  t.id, t.project_id, t.training_provider_id, t.training_id, t.cohort_id, t.batch_id, t.trainee_unique_id,
  NULLIF(TRIM(t.external_beneficiary_id), ''),
  CASE t.roster_role WHEN 'active' THEN 'active' WHEN 'reserve' THEN 'reserve' ELSE 'withdrawn' END,
  CASE WHEN t.roster_role IN ('replaced_withdrawn','reserve_withdrawn') THEN 'replaced' END,
  t.replaces_trainee_id, t.attendance_eligible_from,
  TRIM(t.first_name), NULLIF(TRIM(t.father_name), ''), NULLIF(TRIM(t.grandfather_name), ''),
  CASE fn_norm(t.sex) WHEN 'male' THEN 'male' WHEN 'm' THEN 'male' WHEN 'female' THEN 'female' WHEN 'f' THEN 'female' END,
  t.sex, t.age_years, NULLIF(TRIM(t.date_of_birth_et_calendar), ''),
  DATE(t.date_of_form_completion), IF(t.date_of_form_completion IS NULL, 'missing', 'certain'),   -- refined in 9.5.3
  fn_phone_e164(t.phone_primary), t.phone_primary,
  fn_phone_e164(t.phone_alternative), t.phone_alternative,
  NULLIF(LOWER(TRIM(t.email)), ''), NULLIF(TRIM(t.kebele), ''), NULLIF(TRIM(t.woreda), ''), NULLIF(TRIM(t.sub_city), ''),
  ra.canonical, t.region,
  NULLIF(TRIM(t.emergency_contact_name), ''), fn_phone_e164(t.emergency_contact_phone), t.emergency_contact_phone,
  ea.canonical, t.highest_education, t.previously_participated, NULLIF(TRIM(t.prior_training_type), ''), t.prior_completed,
  NULLIF(t.prior_year_completed, 0),
  ma.canonical, t.employment_status, t.income_sufficient, sa.canonical, t.skill_usage, pa.canonical,
  t.post_training_employment_plan_type, NULLIF(TRIM(t.post_training_employment_plan_other_text), ''),
  t.disability_flag, da.canonical, t.disability_type, NULLIF(TRIM(t.disability_other_text), ''),
  t.idp_flag, t.returnee_flag, t.low_income_flag, t.inclusion_none_of_above, t.inclusion_prefer_not_to_say,
  t.consent_accuracy, t.consent_followup_surveys, t.consent_contact_verify, t.consent_image_use,
  t.raw_payload, t.training_type, t.training_location, t.location_id, t.training_duration_id, t.roster_role,
  t.created_at, t.updated_at
FROM pbps_mis.trainees t
LEFT JOIN enum_aliases ra ON ra.domain = 'region'      AND ra.alias_norm = fn_norm(t.region)
LEFT JOIN enum_aliases ea ON ea.domain = 'education'   AND ea.alias_norm = fn_norm(t.highest_education)
LEFT JOIN enum_aliases ma ON ma.domain = 'employment'  AND ma.alias_norm = fn_norm(t.employment_status)
LEFT JOIN enum_aliases sa ON sa.domain = 'skill_usage' AND sa.alias_norm = fn_norm(t.skill_usage)
LEFT JOIN enum_aliases pa ON pa.domain = 'plan'        AND pa.alias_norm = fn_norm(t.post_training_employment_plan_type)
LEFT JOIN enum_aliases da ON da.domain = 'disability'  AND da.alias_norm = fn_norm(t.disability_type)
WHERE NOT EXISTS (SELECT 1 FROM trainees x WHERE x.id = t.id)
ORDER BY t.id;   -- replaces_trainee_id FK resolves because referenced rows have lower ids (verified in preflight)

-- 9.5.2 Issues for anything that did not normalise (raw value is kept on the row)
INSERT INTO migration_issues (entity, entity_id, field, issue_code, raw_value, severity)
SELECT 'trainee', v.id, 'phone_primary', 'PHONE_UNPARSABLE', v.phone_raw, 'warning'
  FROM trainees v WHERE v.phone_raw IS NOT NULL AND v.phone_raw <> '' AND v.phone_e164 IS NULL
ON DUPLICATE KEY UPDATE raw_value = VALUES(raw_value);
INSERT INTO migration_issues (entity, entity_id, field, issue_code, raw_value, severity)
SELECT 'trainee', v.id, 'region', IF(fn_norm(v.region_raw) = 'ethiopia', 'REGION_TOO_GENERIC', 'REGION_UNKNOWN'), v.region_raw, 'info'
  FROM trainees v WHERE v.region_raw IS NOT NULL AND v.region_raw <> '' AND v.region_code IS NULL
ON DUPLICATE KEY UPDATE raw_value = VALUES(raw_value);
INSERT INTO migration_issues (entity, entity_id, field, issue_code, raw_value, severity)
SELECT 'trainee', v.id, 'highest_education', 'EDUCATION_UNKNOWN', v.education_raw, 'warning'
  FROM trainees v WHERE v.education_raw IS NOT NULL AND v.education_code IS NULL
ON DUPLICATE KEY UPDATE raw_value = VALUES(raw_value);
INSERT INTO migration_issues (entity, entity_id, field, issue_code, raw_value, severity)
SELECT 'trainee', v.id, 'employment_status', 'EMPLOYMENT_UNKNOWN', v.employment_raw, 'warning'
  FROM trainees v WHERE v.employment_raw IS NOT NULL AND v.employment_code IS NULL
ON DUPLICATE KEY UPDATE raw_value = VALUES(raw_value);
INSERT INTO migration_issues (entity, entity_id, field, issue_code, raw_value, severity)
SELECT 'trainee', v.id, 'disability_type', 'DISABILITY_UNKNOWN', v.disability_raw, 'info'
  FROM trainees v WHERE v.disability_raw IS NOT NULL AND v.disability_code IS NULL
ON DUPLICATE KEY UPDATE raw_value = VALUES(raw_value);

-- 9.5.3 Form-completion date confidence (V1 parsed slash dates month-first; the form says DD/MM/YYYY)
-- 'certain' when day > 12, day = month, or the swapped date would lie after the registration timestamp.
UPDATE trainees v
   SET v.form_date_confidence = CASE
         WHEN v.form_completion_date IS NULL THEN 'missing'
         WHEN DAY(v.form_completion_date) > 12 THEN 'certain'
         WHEN DAY(v.form_completion_date) = MONTH(v.form_completion_date) THEN 'certain'
         WHEN MAKEDATE(YEAR(v.form_completion_date), 1)
                + INTERVAL (DAY(v.form_completion_date) - 1) MONTH
                + INTERVAL (MONTH(v.form_completion_date) - 1) DAY > DATE(v.created_at) THEN 'certain'
         ELSE 'ambiguous' END;
INSERT INTO migration_issues (entity, entity_id, field, issue_code, raw_value, detail, severity)
SELECT 'trainee', v.id, 'form_completion_date', 'FORM_DATE_AMBIGUOUS', DATE_FORMAT(v.form_completion_date, '%Y-%m-%d'),
       CONCAT('Swapped reading would be ', DATE_FORMAT(MAKEDATE(YEAR(v.form_completion_date),1)
              + INTERVAL (DAY(v.form_completion_date)-1) MONTH + INTERVAL (MONTH(v.form_completion_date)-1) DAY, '%Y-%m-%d')), 'warning'
  FROM trainees v WHERE v.form_date_confidence = 'ambiguous'
ON DUPLICATE KEY UPDATE detail = VALUES(detail);

-- 9.5.4 Class history seed (one row per trainee; V1 enrollment ids kept where they exist)
INSERT INTO trainee_class_history (trainee_id, class_id, from_date, change_reason, legacy_enrollment_id)
SELECT v.id, v.class_id, DATE(COALESCE(e.enrolled_at, v.created_at)), IF(e.id IS NULL, 'registered', 'migration_enrollment'), e.id
  FROM trainees v
  LEFT JOIN pbps_mis.trainee_enrollments e ON e.trainee_id = v.id AND e.training_id = v.training_id
 WHERE NOT EXISTS (SELECT 1 FROM trainee_class_history h WHERE h.trainee_id = v.id);

-- 9.5.5 Trainee status rows (attendance/outcome columns filled by later scripts)
INSERT INTO trainee_status (trainee_id, project_id, provider_id, class_id, roster_status, sex, location_id)
SELECT v.id, v.project_id, v.provider_id, v.class_id, v.roster_status, v.sex, s.location_id
  FROM trainees v JOIN training_sites s ON s.id = v.site_id
 WHERE NOT EXISTS (SELECT 1 FROM trainee_status x WHERE x.trainee_id = v.id);
```

#### 9.5.6 `31_enrich_trainees.step.ts` (TypeScript, idempotent UPDATEs)

For every trainee (batched 500):
1. `parseEthiopianDate(dob_et_raw)` with the **ambiguity-aware** strategy: try `D/M/YYYY` (official form) and `M/D/YYYY` (Excel rewrite); accept a reading only if it is a valid ET date *and* the implied age at the form date is within ±1 of `age_years`. If exactly one reading passes → `ok`; both pass and differ → `ambiguous` (store neither, log `DOB_AMBIGUOUS`); none → `unparsable` (log `DOB_UNPARSABLE`). Two-digit years (`7/24/92`) are expanded with the age check (ET 1992 vs 1892). Writes `dob_et_year/month/day`, `dob_gregorian`, `dob_parse_status`.
2. Name normalisation and matching keys (`name_norm_*`, `name_key_fn_fa`, `name_phon_*`, `search_text`) with the same functions as the duplicates module.
3. Eligibility via `registration/eligibility.rules.ts` → `eligibility_status`, `eligibility_reasons`; copied to `trainee_status`.
4. Inclusion `is_pwd`: V1 `disability_flag`; if NULL but `disability_code` ∈ {hearing, visual, paralysis, other} → TRUE (logged as `PWD_INFERRED`).

Each UPDATE is keyed by `id` and writes only derived columns, so the step can be repeated.

### 9.6 `40_attendance.sql`

```sql
-- Sessions = distinct (class, date) in V1 rows
INSERT INTO attendance_sessions (project_id, provider_id, class_id, session_date, status, source, submitted_at)
SELECT a.project_id, a.training_provider_id, a.batch_id, a.session_date, 'submitted',
       CASE WHEN COUNT(DISTINCT COALESCE(a.source,'manual')) > 1 THEN 'migration_mixed'
            WHEN MAX(a.source) = 'csv_daily' THEN 'migration_csv' ELSE 'migration_manual' END,
       MIN(a.created_at)
  FROM pbps_mis.trainee_attendance_days a
 WHERE NOT EXISTS (SELECT 1 FROM attendance_sessions s WHERE s.class_id = a.batch_id AND s.session_date = a.session_date)
 GROUP BY a.project_id, a.training_provider_id, a.batch_id, a.session_date;

-- Marks (natural key trainee + class + date preserved; V1 row id derivable from it)
INSERT INTO attendance_marks (session_id, trainee_id, status, is_backfill, marked_at)
SELECT s.id, a.trainee_id,
       CASE a.status WHEN 'present' THEN 1 WHEN 'absent' THEN 2 WHEN 'excused' THEN 3 END,
       a.source = 'manual_backfill', a.created_at
  FROM pbps_mis.trainee_attendance_days a
  JOIN attendance_sessions s ON s.class_id = a.batch_id AND s.session_date = a.session_date
 WHERE NOT EXISTS (SELECT 1 FROM attendance_marks m WHERE m.session_id = s.id AND m.trainee_id = a.trainee_id);

-- Session counters (deterministic)
UPDATE attendance_sessions s
  JOIN (SELECT session_id, COUNT(*) c, SUM(status=1) p, SUM(status=2) ab, SUM(status=3) ex
          FROM attendance_marks GROUP BY session_id) k ON k.session_id = s.id
   SET s.marks_count = k.c, s.present_count = k.p, s.absent_count = k.ab, s.excused_count = k.ex;

-- Submitter, recovered from the V1 audit trail. V1 attendance events carry batch_id (column) and actor, but no
-- session date in meta (meta = {"upserted": n}); they are matched to the session by class + submission time (±10 s).
-- Verified on the live data: all 4,954 sessions match an attendance event.
UPDATE attendance_sessions s
  JOIN (SELECT ses.id session_id,
               (SELECT e.actor_user_id FROM pbps_mis.submission_events e
                 WHERE e.module = 'attendance' AND e.batch_id = ses.class_id
                   AND ABS(TIMESTAMPDIFF(SECOND, e.created_at, ses.submitted_at)) <= 10
                 ORDER BY ABS(TIMESTAMPDIFF(SECOND, e.created_at, ses.submitted_at)), e.id LIMIT 1) actor
          FROM attendance_sessions ses) m ON m.session_id = s.id
   SET s.submitted_by = m.actor
 WHERE s.submitted_by IS NULL AND m.actor IS NOT NULL;
```

Trainee attendance counters are computed in post-processing (§9.13) because they need the class calendars.

### 9.7 `50_outcomes.sql`

```sql
-- Reports (ids preserved)
INSERT INTO outcome_reports (id, project_id, provider_id, training_id, site_id, class_id, report_type, stage_key, version_no, status,
                             source_filename, rows_total, submitted_by, submitted_at, is_legacy_partial_roster, legacy_meta, created_at)
SELECT b.id, b.project_id, b.training_provider_id, b.training_id, b.cohort_id, b.batch_id, b.report_type,
       COALESCE(JSON_UNQUOTE(JSON_EXTRACT(b.meta,'$.stageKey')), ''), 1,
       IF(b.status = 'processed', 'accepted', 'discarded'),
       b.source_filename, b.total_rows, b.uploaded_by_user_id, b.created_at,
       b.report_type <> 'dropout',
       JSON_OBJECT('v1_status', b.status, 'v1_valid_rows', b.valid_rows, 'v1_invalid_rows', b.invalid_rows, 'v1_meta', b.meta),
       b.created_at
  FROM pbps_mis.outcome_report_batches b
 WHERE NOT EXISTS (SELECT 1 FROM outcome_reports r WHERE r.id = b.id);

-- Lines (ids preserved). event_date = the business date from meta (completion_date / certification_date / dropout_date),
-- falling back to V1 status_date. V1 status_date and meta are always kept.
INSERT INTO outcome_report_lines (id, report_id, trainee_id, value, event_date, reason_code, details_json, raw_json, legacy_status_date, created_at)
SELECT o.id, o.report_batch_id, o.trainee_id, IF(o.reported_value = 1, 'yes', 'no'),
       COALESCE(fn_parse_mdy(JSON_UNQUOTE(JSON_EXTRACT(o.meta, CONCAT('$.', o.outcome_type, '_date')))), o.status_date),
       NULLIF(JSON_UNQUOTE(JSON_EXTRACT(o.meta, '$.dropout_reason')), ''),
       JSON_OBJECT('source_type', JSON_UNQUOTE(JSON_EXTRACT(o.meta,'$.source_type')),
                   'dropout_dispute', JSON_UNQUOTE(JSON_EXTRACT(o.meta,'$.dropout_dispute'))),
       o.meta, o.status_date, o.created_at
  FROM pbps_mis.trainee_outcomes o
 WHERE NOT EXISTS (SELECT 1 FROM outcome_report_lines l WHERE l.id = o.id);

INSERT INTO migration_issues (entity, entity_id, field, issue_code, raw_value, severity)
SELECT 'outcome_line', o.id, 'event_date', 'OUTCOME_DATE_MISSING', JSON_EXTRACT(o.meta, CONCAT('$.', o.outcome_type, '_date')), 'info'
  FROM pbps_mis.trainee_outcomes o JOIN outcome_report_lines l ON l.id = o.id
 WHERE l.event_date IS NULL AND o.reported_value = 1
ON DUPLICATE KEY UPDATE raw_value = VALUES(raw_value);

-- Report counters
UPDATE outcome_reports r
  JOIN (SELECT report_id, COUNT(*) c, SUM(value='yes') y, SUM(value='no') n FROM outcome_report_lines GROUP BY report_id) k
    ON k.report_id = r.id
   SET r.rows_total = k.c, r.yes_count = k.y, r.no_count = k.n;
```

#### 9.7.1 Status derivation (`51_outcome_status.sql`) — deterministic UPDATEs

```sql
-- Reset derived outcome columns (makes the script repeatable)
UPDATE trainee_status SET dropout_status='pending', dropout_source=NULL, dropout_date=NULL, dropout_reason=NULL, dropout_report_id=NULL,
       completion_status='pending', completion_source=NULL, completion_date=NULL, completion_report_id=NULL,
       certification_status='pending', certification_source=NULL, certification_date=NULL, certification_report_id=NULL;

-- Dropout: yes wins over no (V1 rule "a positive Y anywhere always wins")
UPDATE trainee_status s
  JOIN (SELECT l.trainee_id,
               MAX(l.value='yes') any_yes,
               MAX(IF(l.value='yes', l.report_id, NULL)) yes_report,
               MAX(IF(l.value='yes', l.event_date, NULL)) yes_date,
               MAX(IF(l.value='yes', l.reason_code, NULL)) yes_reason,
               MAX(l.report_id) any_report
          FROM outcome_report_lines l JOIN outcome_reports r ON r.id = l.report_id
         WHERE r.report_type = 'dropout' AND r.status = 'accepted'
         GROUP BY l.trainee_id) d ON d.trainee_id = s.trainee_id
   SET s.dropout_status   = IF(d.any_yes, 'yes', 'no'),
       s.dropout_source   = IF(d.any_yes, 'tp_reported', NULL),
       s.dropout_date     = d.yes_date,
       s.dropout_reason   = d.yes_reason,
       s.dropout_report_id = COALESCE(d.yes_report, d.any_report);

-- Completion: reported yes
UPDATE trainee_status s
  JOIN (SELECT l.trainee_id, MAX(l.report_id) rid, MAX(l.event_date) dt
          FROM outcome_report_lines l JOIN outcome_reports r ON r.id = l.report_id
         WHERE r.report_type = 'completion' AND r.status = 'accepted' AND l.value = 'yes'
         GROUP BY l.trainee_id) c ON c.trainee_id = s.trainee_id
   SET s.completion_status = 'yes', s.completion_source = 'migration_reported',
       s.completion_date = c.dt, s.completion_report_id = c.rid;

-- Completion not applicable for dropouts
UPDATE trainee_status s SET s.completion_status = 'not_applicable'
 WHERE s.dropout_status = 'yes' AND s.completion_status = 'pending';

-- Completion INFERRED "no": class has an accepted completion report, trainee tracked, not dropout, not listed
UPDATE trainee_status s
  JOIN outcome_reports r ON r.class_id = s.class_id AND r.report_type = 'completion' AND r.status = 'accepted'
   SET s.completion_status = 'no', s.completion_source = 'migration_inferred', s.completion_report_id = r.id
 WHERE s.completion_status = 'pending'
   AND s.roster_status IN ('active','reserve')
   AND NOT EXISTS (SELECT 1 FROM outcome_report_lines l WHERE l.report_id = r.id AND l.trainee_id = s.trainee_id);

-- Certification: reported yes; not applicable unless completed; inferred no where a certification report exists
UPDATE trainee_status s
  JOIN (SELECT l.trainee_id, MAX(l.report_id) rid, MAX(l.event_date) dt
          FROM outcome_report_lines l JOIN outcome_reports r ON r.id = l.report_id
         WHERE r.report_type = 'certification' AND r.status = 'accepted' AND l.value = 'yes'
         GROUP BY l.trainee_id) c ON c.trainee_id = s.trainee_id
   SET s.certification_status = 'yes', s.certification_source = 'migration_reported',
       s.certification_date = c.dt, s.certification_report_id = c.rid;
UPDATE trainee_status s SET s.certification_status = 'not_applicable'
 WHERE s.certification_status = 'pending' AND s.completion_status IN ('no','not_applicable');
UPDATE trainee_status s
  JOIN outcome_reports r ON r.class_id = s.class_id AND r.report_type = 'certification' AND r.status = 'accepted'
   SET s.certification_status = 'no', s.certification_source = 'migration_inferred', s.certification_report_id = r.id
 WHERE s.certification_status = 'pending' AND s.completion_status = 'yes'
   AND NOT EXISTS (SELECT 1 FROM outcome_report_lines l WHERE l.report_id = r.id AND l.trainee_id = s.trainee_id);

-- Employment pathway: no V1 data → pending; not_applicable when completion is no / not_applicable
UPDATE trainee_status s
   SET s.job_linkage_status = 'not_applicable', s.decent_job_m1_status = 'not_applicable', s.decent_job_m2_status = 'not_applicable',
       s.locality_status = 'not_applicable', s.retention_3m_status = 'not_applicable'
 WHERE s.completion_status IN ('no','not_applicable');

-- Report the inferred values (for TP confirmation)
INSERT INTO migration_issues (entity, entity_id, field, issue_code, detail, severity)
SELECT 'trainee', s.trainee_id, 'completion_status', 'COMPLETION_NO_INFERRED',
       CONCAT('class ', s.class_id, ', completion report ', s.completion_report_id), 'info'
  FROM trainee_status s WHERE s.completion_source = 'migration_inferred'
ON DUPLICATE KEY UPDATE detail = VALUES(detail);
```

Effect on current data (measured read-only on the live database): completion `yes` 1,706; `not_applicable` 261 dropouts; **inferred `no` = 0** — in every class that has a completion report, every tracked non-dropout trainee is listed as a completer, so no value has to be inferred today (the rule stays for safety and for any later V1 dump); certification inferred `no` = 0; `pending` for the AAU and IBT classes that have not ended. System dropouts (attendance < 80 % after class end) are added by post-processing (§9.13) as `system_dropout_final = TRUE` — exactly as V1 computes them, never as a TP-reported value.

### 9.8 `55_indicators.sql`

```sql
-- The 11 V1 indicators (ids and codes preserved) + protocol fields
INSERT INTO indicator_definitions (id, project_id, code, version_no, status, protocol_no, name, unit, level, purpose,
                                   numerator_metric, denominator_metric, direction, default_target, comparator,
                                   verification_method, display_order, legacy_json, created_at)
SELECT i.id, i.project_id, i.code, 1, IF(i.is_active, 'active', 'retired'),
       CASE i.code WHEN 'registered_enrolled_trainees_count' THEN 3 WHEN 'eligible_enrolled_trainee_rate' THEN 4
                   WHEN 'trainee_attendance_rate' THEN 9 WHEN 'trainee_dropout_rate' THEN 10 WHEN 'training_completion_rate' THEN 11
                   WHEN 'training_certification_rate' THEN 12 WHEN 'job_linkage_rate' THEN 14 WHEN 'decent_job_placement_rate' THEN 15
                   WHEN 'job_retention_3_month_rate' THEN 16 WHEN 'locality_compliant_placement_rate' THEN 18
                   WHEN 'timely_grievance_resolution_rate' THEN 19 END,
       i.name, IF(i.computation_mode = 'count', 'count', 'percent'), 'trainee',
       CASE i.verification_mode WHEN 'sampling' THEN 'monitoring_and_verification' ELSE 'monitoring' END,
       CASE i.monitoring_numerator_variable
            WHEN 'registered_trainees' THEN 'trainees.registered' WHEN 'eligible_criteria_trainees' THEN 'trainees.eligible'
            WHEN 'attendance_present_entries' THEN 'attendance.attended_sessions'
            WHEN 'effective_dropout_trainees_protocol' THEN 'trainees.dropout_effective_buffered'
            WHEN 'completion_trainees_protocol' THEN 'trainees.completed_with_attendance_gate'
            WHEN 'certified_trainees' THEN 'trainees.certified' WHEN 'job_linkage_trainees' THEN 'trainees.job_linked'
            WHEN 'decent_job_trainees' THEN 'trainees.decent_job_final' WHEN 'locality_compliant_trainees' THEN 'trainees.locality_compliant'
            WHEN 'job_retention_3m_trainees' THEN 'trainees.retained_3m'
            WHEN 'grievances_resolved_within_7_days_count' THEN 'grievance.resolved_within_sla' END,
       CASE i.monitoring_denominator_variable
            WHEN 'provider_contract_target' THEN 'provider.contract_target'
            WHEN 'attendance_possible_entries' THEN 'attendance.eligible_sessions'
            WHEN 'completion_trainees_protocol' THEN 'trainees.completed_capped'
            WHEN 'decent_job_trainees' THEN 'trainees.decent_job_final'
            WHEN 'grievances_total_registered_count' THEN 'grievance.total_due' END,
       IF(i.code = 'trainee_dropout_rate', 'lower_is_better', 'higher_is_better'),
       i.threshold_value, IF(i.code = 'trainee_dropout_rate', '<=', '>='),
       CASE i.verification_mode WHEN 'sampling' THEN 'sampling' WHEN 'system' THEN 'system' ELSE 'none' END,
       i.protocol_order,
       JSON_OBJECT('claim_mode', i.claim_mode, 'computation_mode', i.computation_mode, 'verification_mode', i.verification_mode,
                   'mon_num', i.monitoring_numerator_variable, 'mon_den', i.monitoring_denominator_variable,
                   'ver_num', i.verification_numerator_variable, 'ver_den', i.verification_denominator_variable,
                   'cohort_filter', i.cohort_filter, 'definition_version', i.definition_version, 'is_locked', i.is_locked),
       i.created_at
  FROM pbps_mis.project_indicators i
 WHERE NOT EXISTS (SELECT 1 FROM indicator_definitions x WHERE x.id = i.id);
```

The 8 provider-level protocol indicators (#1, 2, 5, 6, 7, 8, 13, 17) and the protocol text fields (operational definition, data sources, frequency, disaggregation, computation text) for all 19 are inserted by `56_indicator_protocol_seed.sql`, generated from the protocol document (one `INSERT … WHERE NOT EXISTS` per code, `version_no = 1`) and an `UPDATE` that fills the protocol text for the 11 migrated rows.

```sql
-- Stages (ids preserved)
INSERT INTO indicator_stages (id, project_id, indicator_code, stage_key, label, offset_days, is_final, sort_order, is_active)
SELECT s.id, s.project_id, i.code, s.stage_key, s.label, s.offset_days_from_reference, s.is_required_for_payment, s.sort_order, s.is_active
  FROM pbps_mis.project_indicator_stages s JOIN pbps_mis.project_indicators i ON i.id = s.indicator_id
 WHERE NOT EXISTS (SELECT 1 FROM indicator_stages x WHERE x.id = s.id);

-- Project-default targets from V1 thresholds (history starts at project start or 2026-01-01)
INSERT INTO indicator_targets (project_id, indicator_code, provider_id, target_value, comparator, effective_from, note)
SELECT i.project_id, i.code, NULL, i.threshold_value, IF(i.code = 'trainee_dropout_rate', '<=', '>='),
       COALESCE((SELECT start_date FROM projects p WHERE p.id = i.project_id), '2026-01-01'), 'Migrated from V1 threshold'
  FROM pbps_mis.project_indicators i
 WHERE i.threshold_value IS NOT NULL
   AND NOT EXISTS (SELECT 1 FROM indicator_targets t WHERE t.project_id = i.project_id AND t.indicator_code = i.code
                     AND t.provider_id IS NULL);
```

Per-provider targets do not exist in V1; they are entered by M&E after migration (the UI pre-fills them with the project default).

### 9.9 `60_activities.sql`

```sql
INSERT INTO activity_definitions (id, project_id, code, name, description, scope, is_active, sort_order,
                                  created_by_provider_id, legacy_submission_scope, linked_indicator_code, created_at)
SELECT a.id, a.project_id, a.code, a.name, a.description,
       CASE a.submission_scope WHEN 'provider' THEN 'provider' ELSE 'class' END,
       a.is_active, a.sort_order, a.created_by_training_provider_id, a.submission_scope,
       CASE a.code WHEN 'contract_signed' THEN 'tp_contract_signed' WHEN 'inception_report' THEN 'tp_inception_report'
                   WHEN 'lmda_alignment' THEN 'tp_lmda_curriculum' WHEN 'orientation_sessions' THEN 'tp_orientation_sessions'
                   WHEN 'pretraining_report' THEN 'tp_pretraining_evaluation' WHEN 'full_training_duration' THEN 'tp_full_duration'
                   WHEN 'posttraining_report' THEN 'tp_posttraining_assessment' WHEN 'postplacement_support_program' THEN 'tp_postplacement_support' END,
       a.created_at
  FROM pbps_mis.project_activities a
 WHERE NOT EXISTS (SELECT 1 FROM activity_definitions x WHERE x.id = a.id);

INSERT INTO activity_assignments (id, definition_id, provider_id)
SELECT x.id, x.project_activity_id, x.training_provider_id FROM pbps_mis.project_activity_assignments x
 WHERE NOT EXISTS (SELECT 1 FROM activity_assignments y WHERE y.id = x.id);

-- V1 rules kept as INACTIVE legacy schedules (ids preserved) — new default schedules (MP §22.3) are inserted active
INSERT INTO activity_schedules (id, definition_id, applies_duration_id, anchor, open_offset_days, due_offset_days, grace_days,
                                is_active, legacy_rule_json, created_at)
SELECT r.id, r.project_activity_id, r.training_duration_id,
       CASE WHEN r.anchor_type LIKE 'batch%' OR r.anchor_type LIKE 'cohort%' THEN 'class_start' ELSE 'training_planned_start' END,
       COALESCE(r.open_offset_days, 0), COALESCE(r.end_offset_days, 0), r.grace_days_after_end, FALSE,
       JSON_OBJECT('anchor_type', r.anchor_type, 'open', r.open_offset_days, 'end', r.end_offset_days, 'grace', r.grace_days_after_end,
                   'active', r.is_active),
       r.created_at
  FROM pbps_mis.project_activity_rules r
 WHERE NOT EXISTS (SELECT 1 FROM activity_schedules x WHERE x.id = r.id);

-- Submissions (ids preserved); obligations are linked in post-processing after materialisation
INSERT INTO activity_submissions (id, project_id, provider_id, definition_id, version_no, note, status,
                                  is_late, submitted_by, submitted_at, reviewed_by, reviewed_at, review_note, legacy_scope_json)
SELECT s.id, s.project_id, s.training_provider_id, s.project_activity_id, 1, NULL,
       CASE s.status WHEN 'approved' THEN 'approved' WHEN 'rejected' THEN 'returned' ELSE 'submitted' END,
       COALESCE(JSON_EXTRACT(s.meta,'$.submittedLate') = TRUE, FALSE),
       s.submitted_by_user_id, COALESCE(s.submitted_at, s.created_at), s.reviewed_by_user_id, s.reviewed_at, s.review_comment,
       JSON_OBJECT('training_id', s.training_id, 'cohort_id', s.cohort_id, 'batch_id', s.batch_id, 'meta', s.meta)
  FROM pbps_mis.tp_activity_submissions s
 WHERE NOT EXISTS (SELECT 1 FROM activity_submissions x WHERE x.id = s.id);

-- Files: rows created here; bytes copied + sha256 by 61_copy_files.step.ts
INSERT INTO files (project_id, purpose, storage_key, original_name, mime_type, size_bytes, uploaded_at, legacy_path)
SELECT s.project_id, 'activity_evidence', CONCAT('legacy/', f.storage_path), f.file_name, f.mime_type, f.size_bytes, f.created_at, f.storage_path
  FROM pbps_mis.tp_activity_submission_files f JOIN pbps_mis.tp_activity_submissions s ON s.id = f.submission_id
 WHERE NOT EXISTS (SELECT 1 FROM files x WHERE x.legacy_path = f.storage_path);
INSERT INTO activity_submission_files (submission_id, file_id, legacy_file_row_id)
SELECT f.submission_id, x.id, f.id
  FROM pbps_mis.tp_activity_submission_files f JOIN files x ON x.legacy_path = f.storage_path
 WHERE NOT EXISTS (SELECT 1 FROM activity_submission_files y WHERE y.legacy_file_row_id = f.id);
```

### 9.10 `70_verification.sql`

```sql
-- The V1 ICOS parameter set as plan version 1 for each indicator that has runs
INSERT INTO verification_plans (project_id, indicator_code, version_no, status, population_metric, stratify_by_json,
                                z_value, p_value, margin_e, non_response_factor, reserve_pct, tiering, estimator, ci_z_value,
                                decision_rule, definite_codes_json, max_call_attempts, notes)
SELECT DISTINCT r.project_id, r.indicator_code, 1, 'active', 'trainees.registered', JSON_ARRAY('location','sex'),
       1.96, 0.5, 0.05, 0.9, 15, 'two_tier', 'wilson_one_sided', 1.645, 'ci_vs_target', JSON_ARRAY('V-COMP','V-NCOMP'), 3,
       'Migrated V1 ICOS method (icos_location_sex_v1)'
  FROM pbps_mis.verification_sample_runs r
 WHERE NOT EXISTS (SELECT 1 FROM verification_plans p WHERE p.project_id = r.project_id AND p.indicator_code = r.indicator_code AND p.version_no = 1);

INSERT INTO verification_runs (id, project_id, provider_id, plan_id, indicator_code, report_type, stage_key, period_key, round_no, tier,
                               parent_run_id, training_id, status, is_pre_report_draw, seed, sampling_strategy, parameters_json,
                               population_count, n0, n_fpc, sample_size, reserve_total, verified_rate_pct, ci_lower_pct, ci_upper_pct,
                               pathway, drawn_at, finalised_at, created_by, legacy_json, created_at, updated_at)
SELECT r.id, r.project_id, r.training_provider_id, p.id, r.indicator_code, r.report_type, COALESCE(r.stage_key, ''), r.period_key,
       r.round_no, r.tier, r.parent_run_id, r.training_id,
       CASE r.status WHEN 'finalized' THEN 'finalised' WHEN 'open' THEN 'in_field' ELSE 'in_field' END,
       r.pre_report_draw, r.sampling_seed, r.sampling_strategy,
       COALESCE(r.sampling_parameters, JSON_OBJECT()), r.base_population_count, r.n0, r.n_after_fpc, r.sample_size, r.reserve_sample_total,
       r.verified_rate_pct, r.ci_lower_pct, r.ci_upper_pct, r.pathway_label, r.drawn_at, r.finalized_at, r.created_by_user_id,
       JSON_OBJECT('v1_status', r.status, 'sample_ratio_pct', r.sample_ratio_pct, 'indicator_id', r.indicator_id,
                   'indicator_stage_id', r.indicator_stage_id, 'cohort_id', r.cohort_id, 'batch_id', r.batch_id),
       r.created_at, r.updated_at
  FROM pbps_mis.verification_sample_runs r
  JOIN verification_plans p ON p.project_id = r.project_id AND p.indicator_code = r.indicator_code AND p.version_no = 1
 WHERE NOT EXISTS (SELECT 1 FROM verification_runs x WHERE x.id = r.id)
 ORDER BY r.id;

INSERT INTO verification_strata (id, run_id, stratum_key, location_id, location_name, sex_key, population, primary_drawn, reserve_drawn)
SELECT s.id, s.run_id, s.stratum_key, s.location_id, s.location_name, s.sex_key, s.population, s.primary_drawn, s.reserve_drawn
  FROM pbps_mis.verification_sample_strata s
 WHERE NOT EXISTS (SELECT 1 FROM verification_strata x WHERE x.id = s.id);

INSERT INTO verification_subjects (id, run_id, trainee_id, subject_key, role, stratum_key, reserve_order, replaces_subject_id,
                                   replacement_reason, status_code, verified_value, tp_claim_value, supervisor_status, reviewer_note,
                                   verified_at, verified_by, is_auto_dropout, created_at, updated_at)
SELECT s.id, s.run_id, s.trainee_id, CONCAT('VS-', s.run_id, '-', LPAD(s.id, 6, '0')),
       CASE s.subject_role WHEN 'reserve' THEN 'reserve' WHEN 'replacement' THEN 'replacement' ELSE 'primary' END,
       s.stratum_key, s.reserve_order, s.replaced_subject_id, s.replacement_reason, s.verification_status_code, s.verified_value,
       s.tp_claim_value, IF(s.verification_status_code IS NULL, 'pending', 'approved'), s.reviewer_note, s.verified_at, s.verified_by_user_id,
       (s.verification_status_code = 'V-NCOMP' AND s.verified_by_user_id IS NULL
          AND (s.reviewer_note IS NULL OR s.reviewer_note LIKE '%Auto-marked: dropout%')),
       s.created_at, s.updated_at
  FROM pbps_mis.verification_sample_subjects s
 WHERE NOT EXISTS (SELECT 1 FROM verification_subjects x WHERE x.id = s.id)
 ORDER BY s.id;      -- replaces_subject_id resolves to lower ids

INSERT INTO verification_run_dropouts (id, run_id, trainee_id)
SELECT d.id, d.run_id, d.trainee_id FROM pbps_mis.verification_sample_run_dropouts d
 WHERE NOT EXISTS (SELECT 1 FROM verification_run_dropouts x WHERE x.id = d.id);

-- Frames: V1 did not freeze frames; reconstruct as "subjects only" and flag (the population count is stored on the run)
INSERT INTO verification_frame_members (run_id, trainee_id, stratum_key, claim_value, attrs_json)
SELECT s.run_id, s.trainee_id, COALESCE(s.stratum_key,''), s.tp_claim_value, JSON_OBJECT('reconstructed', TRUE)
  FROM pbps_mis.verification_sample_subjects s
 WHERE NOT EXISTS (SELECT 1 FROM verification_frame_members f WHERE f.run_id = s.run_id AND f.trainee_id = s.trainee_id);

-- Run counters
UPDATE verification_runs r
  JOIN (SELECT run_id, SUM(role='primary') pr, SUM(role='reserve') rs,
               SUM(status_code IS NOT NULL) done, SUM(status_code IN ('V-COMP','V-NCOMP') AND role IN ('primary','replacement')) def,
               SUM(status_code='V-COMP' AND role IN ('primary','replacement')) ok, SUM(status_code='V-UNR') unr,
               SUM(status_code='V-REF') ref, SUM(status_code='V-INC') inc
          FROM verification_subjects GROUP BY run_id) k ON k.run_id = r.id
   SET r.cnt_primary = k.pr, r.cnt_reserve = k.rs, r.cnt_completed = k.done, r.cnt_definite = k.def, r.cnt_success = k.ok,
       r.cnt_unreachable = k.unr, r.cnt_refused = k.ref, r.cnt_inconclusive = k.inc;
```

Evidence (0 rows in V1) uses the same pattern as activity files.

### 9.11 `75_grievance.sql`

```sql
INSERT INTO grievance_cases (id, project_id, provider_id, ref, category, subject, description, submitter_name, submitter_email,
                             submitter_phone, region, status, submitted_at, due_at, first_response_at, resolved_at, legacy_status,
                             created_at, updated_at)
SELECT t.id, t.project_id, t.training_provider_id, t.ref_code, t.category, t.subject, t.description, t.submitter_name,
       LOWER(TRIM(t.submitter_email)), t.submitter_phone, t.region,
       CASE WHEN t.status = 'resolved' THEN 'resolved'
            WHEN EXISTS (SELECT 1 FROM pbps_mis.feedback_messages m WHERE m.thread_id = t.id AND m.author_type <> 'public') THEN 'responded'
            ELSE 'new' END,
       t.submitted_at, t.due_at,
       COALESCE(t.first_tp_response_at, (SELECT MIN(m.created_at) FROM pbps_mis.feedback_messages m
                                          WHERE m.thread_id = t.id AND m.author_type <> 'public')),
       t.resolved_at, t.status, t.created_at, t.updated_at
  FROM pbps_mis.feedback_threads t
 WHERE NOT EXISTS (SELECT 1 FROM grievance_cases x WHERE x.id = t.id);

INSERT INTO grievance_messages (id, case_id, author_type, author_name, body, visibility, legacy_email_sent_at, legacy_email_error, created_at)
SELECT m.id, m.thread_id,
       CASE m.author_type WHEN 'public' THEN 'public' WHEN 'tp' THEN 'tp' WHEN 'admin' THEN 'admin' WHEN 'me' THEN 'me' ELSE 'system' END,
       m.author_name, m.body, 'public', m.email_sent_at, m.email_error, m.created_at
  FROM pbps_mis.feedback_messages m
 WHERE NOT EXISTS (SELECT 1 FROM grievance_messages x WHERE x.id = m.id);

-- GRM sequence for new references (yearly); legacy refs remain unique by constraint
INSERT INTO id_sequences (scope, next_value)
SELECT CONCAT('grm:', YEAR(CURRENT_DATE)), 1
ON DUPLICATE KEY UPDATE next_value = next_value;
```

### 9.12 `80_platform_legacy.sql` — duplicates, alerts, mail, audit, archive

```sql
-- Duplicates (ids preserved)
INSERT INTO duplicate_scan_runs (id, project_id, trigger_kind, algorithm_version, config_json, status, scanned_count, candidate_count,
                                 started_at, finished_at, created_by)
SELECT r.id, r.project_id, r.trigger, r.algorithm_version, r.config, IF(r.finalized_at IS NULL, 'failed', 'finished'),
       r.scanned_count, r.candidate_count, r.started_at, r.finalized_at, r.created_by_user_id
  FROM pbps_mis.trainee_duplicate_scan_runs r
 WHERE NOT EXISTS (SELECT 1 FROM duplicate_scan_runs x WHERE x.id = r.id);

INSERT INTO duplicate_candidates (id, project_id, scan_run_id, trainee_a_id, trainee_b_id, pair_key, score, risk, signals_json, status,
                                  reviewer_note, reviewed_by, reviewed_at, first_seen_at, last_seen_at)
SELECT c.id, c.project_id, c.scan_run_id, c.trainee_a_id, c.trainee_b_id, c.dedupe_key, LEAST(c.score, 100),
       IF(c.score >= 92, 'high', 'medium'), c.match_signals,
       CASE c.status WHEN 'dismissed' THEN 'not_duplicate' WHEN 'confirmed_duplicate' THEN 'confirmed_duplicate' ELSE 'pending' END,
       c.reviewer_note, c.reviewed_by_user_id, c.reviewed_at, c.first_seen_at, c.last_seen_at
  FROM pbps_mis.trainee_duplicate_candidates c
 WHERE NOT EXISTS (SELECT 1 FROM duplicate_candidates x WHERE x.id = c.id);

-- Reminder rules from V1 alert rules + new defaults
INSERT INTO reminder_rules (project_id, rule_key, is_enabled, offsets_json, severity, email_enabled, legacy_alert_rule_id)
SELECT a.project_id,
       CASE a.alert_type WHEN 'activity_due_soon' THEN 'obligation.due' WHEN 'activity_overdue' THEN 'obligation.overdue'
                         WHEN 'attendance_coverage_low' THEN 'attendance.missing' WHEN 'dropout_risk_summary' THEN 'dropout.risk_digest' END,
       a.is_enabled,
       CASE a.alert_type WHEN 'activity_due_soon' THEN JSON_ARRAY(-7,-1,0) WHEN 'activity_overdue' THEN JSON_ARRAY(1,3,7)
                         WHEN 'attendance_coverage_low' THEN JSON_ARRAY(2) ELSE JSON_ARRAY(7) END,
       a.severity, a.smtp_enabled, a.id
  FROM pbps_mis.alert_rules a
 WHERE NOT EXISTS (SELECT 1 FROM reminder_rules r WHERE r.legacy_alert_rule_id = a.id);
INSERT INTO reminder_rules (project_id, rule_key, offsets_json, repeat_after_days, severity)
SELECT p.id, k.rule_key, k.offsets, k.rep, k.sev FROM projects p
  JOIN (SELECT 'grievance.sla' rule_key, JSON_ARRAY(-2,0,1) offsets, 2 rep, 'warning' sev
        UNION ALL SELECT 'grievance.escalate', JSON_ARRAY(2), NULL, 'critical'
        UNION ALL SELECT 'outcome.report_due', JSON_ARRAY(7,14,21), 7, 'warning'
        UNION ALL SELECT 'roster.freeze_upcoming', JSON_ARRAY(-3), NULL, 'info'
        UNION ALL SELECT 'registration.window_closing', JSON_ARRAY(-7,-1), NULL, 'info') k
 WHERE NOT EXISTS (SELECT 1 FROM reminder_rules r WHERE r.project_id = p.id AND r.rule_key = k.rule_key);

-- Audit: V1 chain verbatim
INSERT INTO audit_events_legacy SELECT e.* FROM pbps_mis.submission_events e
 WHERE NOT EXISTS (SELECT 1 FROM audit_events_legacy x WHERE x.id = e.id);

-- Archive schema: verbatim copies of every V1 table (structure + rows)
-- (generated by the runner for each table name in information_schema of pbps_mis)
--   CREATE TABLE IF NOT EXISTS pbps_legacy.<t> LIKE pbps_mis.<t>;
--   INSERT INTO pbps_legacy.<t> SELECT * FROM pbps_mis.<t> s WHERE NOT EXISTS (SELECT 1 FROM pbps_legacy.<t> x WHERE x.id = s.id);
```

Mail settings: `82_mail.step.ts` reads `pbps_mis.smtp_configurations` (status = '1'), encrypts the password with `APP_ENCRYPTION_KEY` and upserts `mail_settings (id=1)`. TP SMTP rows are archived only.

### 9.13 `85_postprocess.step.ts` — runs V2 application services

In this order (each idempotent by construction):

1. **Class calendars** — `delivery.rebuildClassCalendar(classId)` for all 111 classes (holidays, approved breakdowns, exempt 14 days, weekdays, effective dates).
2. **Class counters** — sessions total / to date / submitted / missing.
3. **Trainee attendance counters** — one SQL per class:
   ```sql
   UPDATE trainee_status s
     JOIN (SELECT m.trainee_id, SUM(m.status = 1) p, SUM(m.status = 3) e, SUM(m.status = 2) a
             FROM attendance_marks m
             JOIN attendance_sessions ses ON ses.id = m.session_id
             JOIN class_calendar_days d ON d.class_id = ses.class_id AND d.cal_date = ses.session_date AND d.kind = 'session'
            WHERE ses.class_id = ? GROUP BY m.trainee_id) k ON k.trainee_id = s.trainee_id
     JOIN class_counters cc ON cc.class_id = s.class_id
      SET s.att_present = k.p, s.att_excused = k.e, s.att_absent = k.a,
          s.att_sessions_to_date = cc.sessions_to_date, s.att_sessions_total = cc.sessions_total,
          s.att_rate_to_date = IF(cc.sessions_to_date > 0, (k.p + k.e) / cc.sessions_to_date * 100, NULL),
          s.att_computed_at = NOW(3);
   ```
   Marks on non-session days (the 37 holiday rows) are kept in `attendance_marks` but excluded by the join — exactly V1's KPI behaviour — and listed in Data health.
4. **System dropout flags** (`outcomes.refreshSystemDropouts`) — `system_dropout_final`, `system_dropout_risk`, `att_rate_final`, `att_max_reachable` (V1 rules).
5. **Eligibility** copy to `trainee_status`.
6. **Obligations** — `activities.materializeObligations` with the new default schedules; then link the 28 V1 submissions to the matching obligation (provider + definition + class from `legacy_scope_json.batch_id`, else provider-level) and set obligation status from submission status.
7. **Roster baseline snapshots** — one `migration_baseline` snapshot per class (current tracked roster).
8. **ID sequences** — `id_sequences('trainee:<PROJECT>:<TP>') = max(sequence suffix) + 1` per provider.
9. **Audit genesis** — one `audit_events` row `migration.completed` per project whose `prev_hash` = last V1 `chain_hash`; `audit_chain_heads` initialised.
10. **KPI snapshots** — `indicators.recompute(projectId, asOf=today)`; also a snapshot "as of cutover" kept permanently.
11. **Duplicate keys refresh** — candidates recomputed with the V2 algorithm in *report-only* mode (V1 review decisions preserved).

---

## 10. Reconciliation — proving nothing was lost

`90_reconcile.sql` produces a table of checks; **every row must show `ok = 1`** before cutover. The runner renders it as `migration/reports/reconciliation-<label>.md`.

```sql
DROP TEMPORARY TABLE IF EXISTS recon;
CREATE TEMPORARY TABLE recon (check_name VARCHAR(120), v1 BIGINT, v2 BIGINT, ok TINYINT);

-- 10.1 Row counts (1:1 entities)
INSERT INTO recon SELECT 'users',                 (SELECT COUNT(*) FROM pbps_mis.users),                     (SELECT COUNT(*) FROM users), NULL;
INSERT INTO recon SELECT 'providers',             (SELECT COUNT(*) FROM pbps_mis.training_providers),        (SELECT COUNT(*) FROM providers), NULL;
INSERT INTO recon SELECT 'contracts',             (SELECT COUNT(*) FROM pbps_mis.training_provider_contracts),(SELECT COUNT(*) FROM provider_contracts), NULL;
INSERT INTO recon SELECT 'trainings',             (SELECT COUNT(*) FROM pbps_mis.trainings),                 (SELECT COUNT(*) FROM trainings), NULL;
INSERT INTO recon SELECT 'sites (cohorts)',       (SELECT COUNT(*) FROM pbps_mis.training_cohorts),          (SELECT COUNT(*) FROM training_sites), NULL;
INSERT INTO recon SELECT 'classes (batches)',     (SELECT COUNT(*) FROM pbps_mis.training_batches),          (SELECT COUNT(*) FROM training_classes), NULL;
INSERT INTO recon SELECT 'holidays',              (SELECT COUNT(*) FROM pbps_mis.project_holidays),          (SELECT COUNT(*) FROM holidays), NULL;
INSERT INTO recon SELECT 'breakdowns',            (SELECT COUNT(*) FROM pbps_mis.training_breakdowns),       (SELECT COUNT(*) FROM training_breakdowns), NULL;
INSERT INTO recon SELECT 'trainees',              (SELECT COUNT(*) FROM pbps_mis.trainees),                  (SELECT COUNT(*) FROM trainees), NULL;
INSERT INTO recon SELECT 'trainee_status rows',   (SELECT COUNT(*) FROM pbps_mis.trainees),                  (SELECT COUNT(*) FROM trainee_status), NULL;
INSERT INTO recon SELECT 'attendance marks',      (SELECT COUNT(*) FROM pbps_mis.trainee_attendance_days),   (SELECT COUNT(*) FROM attendance_marks), NULL;
INSERT INTO recon SELECT 'attendance sessions',   (SELECT COUNT(*) FROM (SELECT DISTINCT batch_id, session_date FROM pbps_mis.trainee_attendance_days) x),
                                                  (SELECT COUNT(*) FROM attendance_sessions), NULL;
INSERT INTO recon SELECT 'outcome reports',       (SELECT COUNT(*) FROM pbps_mis.outcome_report_batches),    (SELECT COUNT(*) FROM outcome_reports), NULL;
INSERT INTO recon SELECT 'outcome lines',         (SELECT COUNT(*) FROM pbps_mis.trainee_outcomes),          (SELECT COUNT(*) FROM outcome_report_lines), NULL;
INSERT INTO recon SELECT 'indicators (V1 rows)',  (SELECT COUNT(*) FROM pbps_mis.project_indicators),        (SELECT COUNT(*) FROM indicator_definitions WHERE id IN (SELECT id FROM pbps_mis.project_indicators)), NULL;
INSERT INTO recon SELECT 'indicator stages',      (SELECT COUNT(*) FROM pbps_mis.project_indicator_stages),  (SELECT COUNT(*) FROM indicator_stages), NULL;
INSERT INTO recon SELECT 'activity definitions',  (SELECT COUNT(*) FROM pbps_mis.project_activities),        (SELECT COUNT(*) FROM activity_definitions WHERE id IN (SELECT id FROM pbps_mis.project_activities)), NULL;
INSERT INTO recon SELECT 'activity submissions',  (SELECT COUNT(*) FROM pbps_mis.tp_activity_submissions),   (SELECT COUNT(*) FROM activity_submissions), NULL;
INSERT INTO recon SELECT 'activity files',        (SELECT COUNT(*) FROM pbps_mis.tp_activity_submission_files),(SELECT COUNT(*) FROM activity_submission_files), NULL;
INSERT INTO recon SELECT 'verification runs',     (SELECT COUNT(*) FROM pbps_mis.verification_sample_runs),  (SELECT COUNT(*) FROM verification_runs), NULL;
INSERT INTO recon SELECT 'verification subjects', (SELECT COUNT(*) FROM pbps_mis.verification_sample_subjects),(SELECT COUNT(*) FROM verification_subjects), NULL;
INSERT INTO recon SELECT 'verification strata',   (SELECT COUNT(*) FROM pbps_mis.verification_sample_strata),(SELECT COUNT(*) FROM verification_strata), NULL;
INSERT INTO recon SELECT 'verification dropouts', (SELECT COUNT(*) FROM pbps_mis.verification_sample_run_dropouts),(SELECT COUNT(*) FROM verification_run_dropouts), NULL;
INSERT INTO recon SELECT 'grievance cases',       (SELECT COUNT(*) FROM pbps_mis.feedback_threads),          (SELECT COUNT(*) FROM grievance_cases), NULL;
INSERT INTO recon SELECT 'grievance messages',    (SELECT COUNT(*) FROM pbps_mis.feedback_messages),         (SELECT COUNT(*) FROM grievance_messages), NULL;
INSERT INTO recon SELECT 'duplicate candidates',  (SELECT COUNT(*) FROM pbps_mis.trainee_duplicate_candidates),(SELECT COUNT(*) FROM duplicate_candidates), NULL;
INSERT INTO recon SELECT 'audit events (legacy)', (SELECT COUNT(*) FROM pbps_mis.submission_events),         (SELECT COUNT(*) FROM audit_events_legacy), NULL;
INSERT INTO recon SELECT 'memberships (V1 links)',(SELECT (SELECT COUNT(*) FROM pbps_mis.project_users WHERE project_role <> 'tp')
                                                         + (SELECT COUNT(*) FROM pbps_mis.tp_staff_memberships)),
                                                  (SELECT COUNT(*) FROM memberships WHERE legacy_source LIKE 'project_users:%' OR legacy_source LIKE 'tp_staff_memberships:%'), NULL;

-- 10.2 Anti-joins: every V1 id exists in V2 (expected 0 missing → stored as v1 = missing, v2 = 0)
INSERT INTO recon SELECT 'missing trainee ids',  (SELECT COUNT(*) FROM pbps_mis.trainees t WHERE NOT EXISTS (SELECT 1 FROM trainees v WHERE v.id = t.id)), 0, NULL;
INSERT INTO recon SELECT 'missing outcome ids',  (SELECT COUNT(*) FROM pbps_mis.trainee_outcomes o WHERE NOT EXISTS (SELECT 1 FROM outcome_report_lines l WHERE l.id = o.id)), 0, NULL;
INSERT INTO recon SELECT 'missing attendance rows', (SELECT COUNT(*) FROM pbps_mis.trainee_attendance_days a WHERE NOT EXISTS (
                                                     SELECT 1 FROM attendance_sessions s JOIN attendance_marks m ON m.session_id = s.id
                                                      WHERE s.class_id = a.batch_id AND s.session_date = a.session_date AND m.trainee_id = a.trainee_id)), 0, NULL;
INSERT INTO recon SELECT 'missing subject ids',  (SELECT COUNT(*) FROM pbps_mis.verification_sample_subjects s WHERE NOT EXISTS (SELECT 1 FROM verification_subjects v WHERE v.id = s.id)), 0, NULL;

-- 10.3 Value equality (sums by provider) — attendance statuses
INSERT INTO recon SELECT 'present marks', (SELECT COUNT(*) FROM pbps_mis.trainee_attendance_days WHERE status = 'present'),
                                          (SELECT COUNT(*) FROM attendance_marks WHERE status = 1), NULL;
INSERT INTO recon SELECT 'absent marks',  (SELECT COUNT(*) FROM pbps_mis.trainee_attendance_days WHERE status = 'absent'),
                                          (SELECT COUNT(*) FROM attendance_marks WHERE status = 2), NULL;
-- Outcome values
INSERT INTO recon SELECT 'outcome yes lines', (SELECT COUNT(*) FROM pbps_mis.trainee_outcomes WHERE reported_value = 1),
                                              (SELECT COUNT(*) FROM outcome_report_lines WHERE value = 'yes'), NULL;
INSERT INTO recon SELECT 'outcome no lines',  (SELECT COUNT(*) FROM pbps_mis.trainee_outcomes WHERE reported_value = 0),
                                              (SELECT COUNT(*) FROM outcome_report_lines WHERE value = 'no'), NULL;
-- Status derivation equals V1 distinct counts
INSERT INTO recon SELECT 'dropout yes trainees', (SELECT COUNT(DISTINCT trainee_id) FROM pbps_mis.trainee_outcomes WHERE outcome_type='dropout' AND reported_value=1),
                                                 (SELECT COUNT(*) FROM trainee_status WHERE dropout_status = 'yes'), NULL;
INSERT INTO recon SELECT 'completion yes trainees', (SELECT COUNT(DISTINCT trainee_id) FROM pbps_mis.trainee_outcomes WHERE outcome_type='completion' AND reported_value=1),
                                                    (SELECT COUNT(*) FROM trainee_status WHERE completion_status = 'yes'), NULL;
INSERT INTO recon SELECT 'certification yes trainees', (SELECT COUNT(DISTINCT trainee_id) FROM pbps_mis.trainee_outcomes WHERE outcome_type='certification' AND reported_value=1),
                                                       (SELECT COUNT(*) FROM trainee_status WHERE certification_status = 'yes'), NULL;
-- Roster
INSERT INTO recon SELECT 'active trainees',  (SELECT COUNT(*) FROM pbps_mis.trainees WHERE roster_role = 'active'),  (SELECT COUNT(*) FROM trainees WHERE roster_status = 'active'), NULL;
INSERT INTO recon SELECT 'reserve trainees', (SELECT COUNT(*) FROM pbps_mis.trainees WHERE roster_role = 'reserve'), (SELECT COUNT(*) FROM trainees WHERE roster_status = 'reserve'), NULL;
INSERT INTO recon SELECT 'female trainees',  (SELECT COUNT(*) FROM pbps_mis.trainees WHERE LOWER(sex) = 'female'),   (SELECT COUNT(*) FROM trainees WHERE sex = 'female'), NULL;
INSERT INTO recon SELECT 'male trainees',    (SELECT COUNT(*) FROM pbps_mis.trainees WHERE LOWER(sex) = 'male'),     (SELECT COUNT(*) FROM trainees WHERE sex = 'male'), NULL;
-- Raw preservation: every non-empty V1 value is present raw in V2
INSERT INTO recon SELECT 'phones raw preserved', (SELECT COUNT(*) FROM pbps_mis.trainees WHERE phone_primary IS NOT NULL AND phone_primary <> ''),
                                                 (SELECT COUNT(*) FROM trainees WHERE phone_raw IS NOT NULL AND phone_raw <> ''), NULL;
INSERT INTO recon SELECT 'dob raw preserved',    (SELECT COUNT(*) FROM pbps_mis.trainees WHERE date_of_birth_et_calendar IS NOT NULL AND TRIM(date_of_birth_et_calendar) <> ''),
                                                 (SELECT COUNT(*) FROM trainees WHERE dob_et_raw IS NOT NULL), NULL;
INSERT INTO recon SELECT 'raw_payload preserved',(SELECT COUNT(*) FROM pbps_mis.trainees WHERE raw_payload IS NOT NULL),
                                                 (SELECT COUNT(*) FROM trainees WHERE raw_payload IS NOT NULL), NULL;

UPDATE recon SET ok = (v1 = v2);
SELECT * FROM recon ORDER BY ok, check_name;
```

### 10.4 Per-provider / per-class parity (exported as CSV)

```sql
-- Attendance per class: V1 vs V2 present+excused and total marks
SELECT a.batch_id AS class_id, COUNT(*) v1_marks, SUM(a.status IN ('present','excused')) v1_attended,
       (SELECT COUNT(*) FROM attendance_marks m JOIN attendance_sessions s ON s.id = m.session_id WHERE s.class_id = a.batch_id) v2_marks,
       (SELECT SUM(m.status IN (1,3)) FROM attendance_marks m JOIN attendance_sessions s ON s.id = m.session_id WHERE s.class_id = a.batch_id) v2_attended
  FROM pbps_mis.trainee_attendance_days a GROUP BY a.batch_id
HAVING v1_marks <> v2_marks OR v1_attended <> v2_attended;          -- expected: no rows

-- Outcomes per provider and type
SELECT o.training_provider_id, o.outcome_type, o.reported_value, COUNT(*) v1,
       (SELECT COUNT(*) FROM outcome_report_lines l JOIN outcome_reports r ON r.id = l.report_id
         WHERE r.provider_id = o.training_provider_id AND r.report_type = o.outcome_type
           AND l.value = IF(o.reported_value = 1, 'yes', 'no')) v2
  FROM pbps_mis.trainee_outcomes o GROUP BY 1, 2, 3 HAVING v1 <> v2;  -- expected: no rows
```

### 10.5 KPI parity report

1. Before migration, save V1 output: `GET /api/projects/1/indicator-kpis` → `migration/reports/v1_kpis.json` (and the per-trainee attendance export per provider).
2. After post-processing, export V2 `kpi_snapshots` (layer monitoring, today).
3. `migration/kpi-parity.ts` produces a table indicator × provider: V1 value, V2 value, difference, **explanation code**:
   - `EQUAL` — identical (expected for registered, eligibility (if R-5 unchanged), attendance, dropout, certification);
   - `RULE_R1` — completion differs because of the per-trainee attendance gate (only if R-1 approved; otherwise V2 runs the V1 rule and must be EQUAL);
   - `BUGFIX_<id>` — documented V1 defect (e.g. date-key mismatch).
4. Sign-off by M&E is required for every non-EQUAL cell.

To make parity testing straightforward, the V2 metric library implements **both** completion variants (`trainees.completed_gate_provider_v1` and `trainees.completed_with_attendance_gate`); the active definition chooses one.

---

## 11. Re-run, rollback and incremental re-sync

| Situation | Action |
|---|---|
| A script fails during a rehearsal | Fix the script; run with `--from <script>` (scripts are insert-if-absent) or `--fresh` |
| Need to verify determinism | Run `--fresh` twice; compare table checksums (`CHECKSUM TABLE` on each V2 table) — must be identical except timestamps produced by post-processing (excluded columns listed) |
| Cutover fails go/no-go | V1 remains the system of record (it was only switched to read-only); re-enable V1 writes; nothing to undo in V1 |
| Problem found after go-live | V2 is the system of record; fix forward with an audited V2 correction; the original V1 values remain in `pbps_mis` / `pbps_legacy` and in `*_raw` columns |
| New V1 data entered between rehearsal and cutover | Irrelevant — the cutover run starts from a **fresh dump taken after V1 is frozen** |

Rollback of V2 itself = `DROP DATABASE pbps_v2;` (V1 untouched).

---

## 12. Cutover runbook

| Step | Owner | Action | Check |
|---|---|---|---|
| T−14 d | Tech lead | Rehearsal 1 on staging from a fresh production dump; review `migration_issues` | Reconciliation 100 %; issues triaged |
| T−10 d | M&E | KPI parity review; decisions in Part R signed | Signed parity report |
| T−7 d | Tech lead | Rehearsal 2 (timed), UAT on migrated data | UAT sign-off |
| T−5 d | M&E + TPs | Send TPs the data-quality lists (ambiguous dates, unknown regions, inferred non-completers, class names) for confirmation | Responses tracked |
| T−3 d | Tech lead | Rehearsal 3 with all fixes | Same result as rehearsal 2 |
| T−1 d | Comms | Announce freeze window to all users | |
| T 08:00 | Ops | Put V1 in read-only (maintenance banner; revoke write grants for the app user on `pbps_mis`) | Writes rejected |
| T 08:15 | Ops | `mysqldump --single-transaction --routines --events pbps_mis` + copy of `uploads/`; sha256 of dump | Dump checksum recorded |
| T 08:30 | Ops | Restore dump on the V2 server; `run-migration --fresh --label cutover` | All scripts `ok` |
| T 09:15 | Tech lead | Reconciliation + file checksum verification + KPI parity diff vs rehearsal 3 | 100 % / no new differences |
| T 09:45 | M&E + 2 TPs | Smoke test (login per role, trainee search, attendance sheet, outcome board, dashboard, verification run view) | Checklist passed |
| T 10:30 | Steering | **Go / no-go** | Signed |
| T 10:45 | Ops | Switch DNS / Nginx to V2; send "V2 is live" with invite/password-reset links where needed | Users can log in |
| T+1…+30 d | Support | Hyper-care; daily data-health review | |
| T+6 months | Steering | Decide archival of `pbps_mis` (keep a final encrypted dump for 7 years) | |

Users keep their passwords (bcrypt hashes migrated). Sessions are new (everyone logs in once).

---

## 13. Optional interim SQL for V1 (while V2 is being built)

The V1 slowness is algorithmic (MP §3), so indexes alone will not make the Outcomes page fast. If temporary relief is needed before V2, these are safe, additive statements (run on V1 during a quiet period, after a backup):

```sql
-- Helps the per-batch attendance queries and dropout projection filters
ALTER TABLE trainee_attendance_days ADD INDEX ix_tad_batch_status_date (batch_id, status, session_date);
-- Helps outcome lookups by type/value per provider
ALTER TABLE trainee_outcomes ADD INDEX ix_to_tp_type_value (project_id, training_provider_id, outcome_type, reported_value);
-- Enforce what the code already assumes (fails if duplicates exist — check first with the preflight query P0.6)
ALTER TABLE trainee_outcomes ADD UNIQUE KEY uq_to_report_trainee (report_batch_id, trainee_id);
```

The effective interim fix is in code (not done now, per instruction): stop calling `fetchIndicatorKpiReport` on the Outcomes and Verification pages and cache `buildIndicatorKpiPayload` per project for a few minutes. These are listed here only so the choice is visible; V2 makes them unnecessary.

---

## 14. Data-quality findings to resolve with TPs (from the live profile)

| # | Finding | Count | Proposed handling |
|---|---|---|---|
| Q1 | Form-completion dates possibly day/month swapped | **363** genuinely ambiguous (of 702 with day ≤ 12; the other 339 are resolved because the swapped reading would be after the registration date) — measured with the §9.5.3 rule | TP confirms per trainee in a short list; V2 stores confirmed date; raw kept |
| Q2 | Date of birth in mixed formats / two-digit years | to be measured by the enrichment step | Auto-resolve where age check is unique; TP confirms the rest |
| Q3 | Region spelled inconsistently / "Ethiopia" / former SNNPR | ~ 140 non-canonical spellings auto-mapped; ≈ 10 unmappable ("Ethiopia" 3, "SNNPR"/"South" 2, "0", "3", "Oriental Orthodox", blank) | Alias mapping (auto); unmappable → TP confirms |
| Q6b | Completion: non-completers not listed in V1 reports | **0** (all tracked non-dropouts in reported classes are listed as completers) | Nothing to infer; future V2 reports list Yes/No for everyone |
| Q4 | Disability type free text ("None", "No", "nothing") | ~ 12 | Alias mapping to "not a person with disability" |
| Q5 | Invalid primary phone (`9.`) | 1 | TP provides the number |
| Q6 | Inferred completion "No" (non-completers not listed in V1 reports) | computed by §9.7.1 | List per class to TP for confirmation (Yes would require a corrected report) |
| Q7 | Attendance captured on dates later declared holidays | 37 marks | Kept, excluded from rates (V1 behaviour), shown in Data health |
| Q8 | Class names that do not describe the class (code vs name mismatch) | many SCV classes | TP renames in V2 (display only) |
| Q9 | Trainings with zero trainees (AAU sections) | 3 | Keep; mark `closed` if unused (M&E decision) |
| Q10 | Training programme "Test Training" | 1 | Keep in archive; not shown in V2 (no training references it) |
| Q11 | Activity rules "+1 … +200 days" | 16 | Replaced by new default schedules; legacy kept inactive |
| Q12 | Unreviewed activity submissions | 28 | M&E reviews in V2 queue |
| Q13 | Open verification runs (pre-report, 2026-09) | 3 | Continue in V2 unchanged (same subjects, seeds, statuses) |

---

*End of document 02. Next: `03_FRONTEND_PROMPT.md`.*
