// The whole life of one real training provider, through the running server over HTTP:  npm run test:e2e
//   E2E_URL=http://localhost:8090  TEST_DATABASE_URL=...e2e_test  E2E_SOURCE_DB=<the V2 database to take the provider from>
// Part A: two new classes of ten days, every rule tried from both sides. Part B: the provider's real classes are reported
// again and must give exactly the results of the source database. Every expected number is worked out here, not read from the app.
import { createHash, randomBytes } from "node:crypto";
import mysql, { type RowDataPacket } from "mysql2/promise";
import { CODE_HEAD } from "./e2e-data.js";

/* eslint-disable @typescript-eslint/no-explicit-any */
type Any = any;
const BASE = process.env["E2E_URL"]!, SRC = process.env["E2E_SOURCE_DB"]!, PROV = process.env["E2E_PROVIDER"] ?? "6", url = new URL(process.env["TEST_DATABASE_URL"] ?? "");
if (!/_test$/.test(url.pathname)) throw new Error("TEST_DATABASE_URL must end in _test.");
const db = await mysql.createConnection({ uri: url.href, timezone: "Z", dateStrings: true, supportBigNumbers: true });
await db.query("SET time_zone='+00:00'");
const q = async (sql: string, a: unknown[] = []): Promise<Any[]> => (await db.query<RowDataPacket[]>(sql, a))[0] as Any[], q1 = async (sql: string, a: unknown[] = []): Promise<Any> => (await q(sql, a))[0];
let pass = 0; const fails: string[] = [];
const ok = (name: string, c: unknown, info: unknown = "") => { if (c) pass++; else { fails.push(name); console.log("FAIL", name, JSON.stringify(info)?.slice(0, 700)); } };
const part = (t: string) => console.log(`${String(pass).padStart(4)}  ${t}`);
interface Who { token: string }
async function user(role: string, provider: string | null = null): Promise<Who> {
  const email = `e_${randomBytes(5).toString("hex")}@test.local`, u: Any = await q("INSERT INTO users (name,email,password_hash,status,two_factor_method) VALUES (?,?,?,'active','none')", [`E2E ${role}`, email, "x"]), token = randomBytes(16).toString("hex");
  await q("INSERT INTO memberships (project_id,user_id,role_id,provider_id,status) SELECT 1,?,id,?,'active' FROM roles WHERE code=?", [u.insertId, provider, role]);
  await q("INSERT INTO user_sessions (user_id,family_id,refresh_token_hash,last_used_at,expires_at) VALUES (?,UUID(),?,UTC_TIMESTAMP(3),UTC_TIMESTAMP(3)+INTERVAL 1 DAY)", [u.insertId, createHash("sha256").update(token).digest("hex")]);
  return { token };
}
async function call(w: Who | null, method: string, path: string, body?: unknown, headers: Record<string, string> = {}): Promise<{ status: number; data: Any; text: string }> {
  for (let n = 0; ; n++) {
    const form = body instanceof FormData, r = await fetch(`${BASE}/api/v2${path}`, { method, headers: { ...(w ? { cookie: `pbps_session=${w.token}; pbps_csrf=c`, "x-csrf-token": "c", origin: BASE } : {}), ...(form || body === undefined ? {} : { "content-type": "application/json" }), ...headers }, ...(body === undefined ? {} : { body: form ? body : JSON.stringify(body) }) });
    if (r.status === 429 && n < 20) { await new Promise((s) => setTimeout(s, 4000)); continue; }
    const text = await r.text(); let data: Any; try { data = JSON.parse(text); } catch { data = text; }
    if (r.status >= 500) ok(`no server error on ${method} ${path}`, false, data);
    return { status: r.status, data, text };
  }
}
const file = (text: string, extra: Record<string, string> = {}) => { const f = new FormData(); for (const [k, v] of Object.entries(extra)) f.set(k, v); f.set("file", new File([text], "f.csv", { type: "text/csv" })); return f; };
const csvRows = (t: string) => t.replace(/^﻿/, "").trim().split(/\r?\n/).map((l) => { const out: string[] = []; let c = "", o = false; for (const ch of l) { if (ch === '"') o = !o; else if (ch === "," && !o) { out.push(c); c = ""; } else c += ch; } out.push(c); return out; });
const toCsv = (rows: string[][]) => rows.map((r) => r.map((c) => (/[",]/.test(c) ? `"${c}"` : c)).join(",")).join("\n");
const add = (d: string, n: number) => new Date(Date.parse(`${d}T00:00:00Z`) + n * 864e5).toISOString().slice(0, 10), dow = (d: string) => new Date(`${d}T00:00:00Z`).getUTCDay() || 7;
const now = new Date(Date.now() + 3 * 36e5).toISOString().slice(0, 10);
const waitFor = async (name: string, f: () => Promise<unknown>, s = 90) => { for (let i = 0; i < s * 2; i++) { if (await f()) return; await new Promise((r) => setTimeout(r, 500)); } ok(`in time: ${name}`, false); };
const admin = await user("system_admin"), officer = await user("me_officer"), lead = await user("me_lead"), sup = await user("verification_supervisor"), enu = await user("verification_enumerator"), bank = await user("funder_viewer"), tp = await user("tp_admin", PROV), clerk = await user("tp_attendance_clerk", PROV);
await q("INSERT INTO providers (project_id, code, name, status) VALUES (1,'OTHER','Another provider','active')"); const stranger = await user("tp_admin", String((await q1("SELECT id FROM providers WHERE code='OTHER'")).id));
const X = "/projects/1", problems = (r: Any) => JSON.stringify(r.data);
const lines = async (w: Who, k: string, type: string) => (await call(w, "GET", `${X}/classes/${k}/outcomes/${type}/context`)).data;
const send = (w: Who, k: string, type: string, l: Any[], why?: string) => call(w, "POST", `${X}/classes/${k}/outcomes/${type}/submit`, { lines: l, ...(why ? { reasonForChange: why } : {}) });

/* ---------- A. two new classes of ten days ---------- */
const code = (await q1("SELECT code FROM providers WHERE id=?", [PROV])).code as string, before = await q1("SELECT COUNT(*) n FROM trainees");
ok("the test database holds one provider only", Number((await q1("SELECT COUNT(*) n FROM providers WHERE code<>'OTHER'")).n) === 1 && Number((await q1("SELECT COUNT(DISTINCT provider_id) n FROM trainees")).n) === 1);
// Ten class days that ended last week, after the 14 exempt days, on days that are not holidays.
const holidays = new Set((await q("SELECT holiday_date d FROM holidays WHERE project_id=1")).map((h) => h.d as string)), days: string[] = [];
for (let d = add(now, -8); days.length < 10; d = add(d, -1)) if (dow(d) <= 5 && !holidays.has(d)) days.unshift(d);
let first = days[0]!, gap = 14; const END = days[9]!, START = add(first, -gap);
await call(admin, "POST", `${X}/providers/${PROV}/registration-window`, { closed: true, note: "Gate test" });
const trBody = { providerId: PROV, title: "E2E Training", level: "basic", durationMonths: 1, plannedStart: START, plannedEnd: END, weekdays: [1, 2, 3, 4, 5], locationCodes: ["AA"] };
ok("provider gate closed: no training", (await call(tp, "POST", `${X}/trainings`, trBody)).data.code === "REGISTRATION_CLOSED");
ok("provider gate closed: shown to the provider", (await call(tp, "GET", `${X}/trainees/summary`)).data.registrationOpen === false);
await call(admin, "POST", `${X}/providers/${PROV}/registration-window`, { closed: false });
await call(admin, "PUT", `${X}/settings`, { registrationOpen: false, registrationCloseNote: "Project gate test" });
ok("project gate closed: blocks an open provider", (await call(tp, "POST", `${X}/trainings`, trBody)).data.code === "REGISTRATION_CLOSED");
await call(admin, "PUT", `${X}/settings`, { registrationOpen: true });
const tr = await call(tp, "POST", `${X}/trainings`, trBody); ok("both gates open: training created", tr.status === 200, tr.data);
const site = String((await call(tp, "GET", `${X}/trainings/${tr.data.id}`)).data.sites[0].site.id), mk = (c: string, s = START, e = END) => call(tp, "POST", `${X}/sites/${site}/classes`, { code: c, name: c, weekdays: [1, 2, 3, 4, 5], plannedStart: s, plannedEnd: e });
const c1 = await mk("E1"), c2 = await mk("E2"), future = await mk("E3", add(now, -20), add(now, 30)), K1 = String(c1.data.id), K2 = String(c2.data.id), K3 = String(future.data.id);
ok("two classes with exactly ten session days", c1.data.sessionsTotal === 10 && c2.data.sessionsTotal === 10, [c1.data.sessionsTotal, days]);
ok("14 days after the start registration is closed by itself", c1.data.registrationOpen === false && c1.data.registrationClosesOn === add(START, 14), c1.data);
ok("the World Bank account cannot change anything", (await call(bank, "POST", `${X}/trainings`, trBody)).status === 403);
const dob = `${START.slice(8)}/${START.slice(5, 7)}/${Number(START.slice(0, 4)) - 24}`, fdate = `${START.slice(8)}/${START.slice(5, 7)}/${START.slice(0, 4)}`, NAMES = ["Abel", "Bethel", "Chala", "Dawit", "Eden", "Fikir", "Girma", "Hana", "Ilili", "Jemal", "Kidus", "Lulit", "Meron", "Natnael", "Obse"], FATH = ["Worku", "Zenebe", "Tolosa", "Gudeta"];
const regRow = (n: number, cls: string) => `${NAMES[n % 15]}${"abcdefghij"[Math.floor(n / 15)]}${"klmnopqrst"[n % 10]},${FATH[n % 4]}${"uvwxyzabcd"[(n * 7) % 10]}${"efghijklmn"[Math.floor(n / 10)]},Test${"opqrstuvwx"[(n * 3) % 10]},${n % 2 ? "Female" : "Male"},24,${dob},09${String(66000000 + n)},Addis Ababa,05,Diploma,Not currently working,${cls},${n % 5 ? "Active" : "Reserve"},${fdate},Yes,Yes`;
const imp = async (rows: string[]) => { const x = await call(tp, "POST", `${X}/imports`, file([CODE_HEAD, ...rows].join("\n"), { providerId: PROV, trainingId: tr.data.id, siteId: site, mode: "import" })); await waitFor("import checked", async () => !["uploaded", "parsing", "validating", "queued", "pending", "processing"].includes((await call(tp, "GET", `${X}/imports/${x.data.batchId}`)).data.status)); return String(x.data.batchId); };
const closedB = await imp([regRow(0, "E1")]); ok("after the 14 days a file is refused", problems(await call(tp, "GET", `${X}/imports/${closedB}/rows`)).includes("REGISTRATION_CLOSED"));
const form = (n: number, over: Any = {}) => ({ classId: K1, formDate: fdate, rosterStatus: "active", firstName: `Formo${"abcdefgh"[n]}`, fatherName: "Testera", grandfatherName: "Persona", sex: "female", age: 24, dateOfBirth: `${Number(START.slice(0, 4)) - 24}${START.slice(4)}`, phone: `09660001${10 + n}`, woreda: "05", region: "Addis Ababa", emergencyName: "E M", emergencyPhone: "0911223344", education: "Diploma", previouslyParticipated: false, employment: "Not currently working", plan: "Wage employment", inclusion: ["None of the above"], consentAccuracy: true, consentFollowup: true, consentVerify: true, consentImage: false, ...over });
ok("after the 14 days the form is refused", (await call(tp, "POST", `${X}/trainees`, form(0))).data.code === "REGISTRATION_CLOSED");
await call(admin, "POST", `${X}/providers/${PROV}/registration-window`, { late: { until: add(now, 2), reason: "E2E late registration" } });
ok("M&E reopens it and the class is open", (await call(tp, "GET", `${X}/classes/${K1}`)).data.cls.registrationOpen === true);
const f0 = await call(tp, "POST", `${X}/trainees`, form(0)); ok("registration form works", f0.status === 200 && f0.data.eligibility === "eligible", f0.data);
for (const [name, over, re] of [["same phone twice", {}, /PHONE|duplicate/i], ["bad phone", { phone: "123" }, /phone/i], ["scientific phone", { phone: "9.84E+08" }, /phone/i], ["no consent", { consentVerify: false, phone: "0966000199" }, /CONSENT/], ["unknown region", { region: "Mars", phone: "0966000198" }, /region/i], ["birth date and age differ", { age: 29, phone: "0966000197" }, /age|birth/i]] as [string, Any, RegExp][]) { const r = await call(tp, "POST", `${X}/trainees`, form(0, over)); ok(`form refuses: ${name}`, r.status >= 400 && r.status < 500 && re.test(problems(r)), r.data); }
const badB = await imp([regRow(1, "NOPE"), regRow(2, "E1").replace("0966000002", "9.66E+08"), regRow(3, "E1").replace(fdate, "3/25/2026")]), badR = problems(await call(tp, "GET", `${X}/imports/${badB}/rows?issue=error`)); ok("registration file: every bad cell is named", ["CLASS_UNKNOWN", "PHONE_SCIENTIFIC_NOTATION", "DATE_INVALID"].every((k) => badR.includes(k)), badR);
ok("and cannot be saved", (await call(tp, "POST", `${X}/imports/${badB}/commit`)).data.code === "IMPORT_NOT_READY");
// 19 + 1 (form) in E1, 20 in E2
const goodB = await imp([...Array(39)].map((_, n) => regRow(n, n < 19 ? "E1" : "E2")));
for (const r of (await call(tp, "GET", `${X}/imports/${goodB}/rows?pageSize=200`)).data.items as Any[]) if (r.status === "duplicate") await call(tp, "POST", `${X}/imports/${goodB}/rows/${r.rowNo ?? r.row}/duplicate-decision`, { decision: "not_duplicate", reason: "Different people" });
const gb = (await call(tp, "GET", `${X}/imports/${goodB}`)).data; ok("a correct file is ready", gb.status === "ready", gb);
if (await q1("SELECT 1 x FROM provider_contracts k JOIN projects p ON p.id=k.project_id WHERE k.provider_id=? AND k.status='active' AND FLOOR(k.target_trainees*(1+p.over_enrolment_pct/100)) < (SELECT COUNT(*) FROM trainees t WHERE t.provider_id=k.provider_id)+39", [PROV])) { const c0 = await call(tp, "POST", `${X}/imports/${goodB}/commit`); ok("the limit of the contract is told at once", c0.data.code === "CAPACITY_REACHED" && /limit is/.test(c0.data.detail), c0.data); ok("and the file can still be saved later", (await call(tp, "GET", `${X}/imports/${goodB}`)).data.status === "ready");
  ok("a provider cannot raise its own limit", (await call(tp, "POST", `${X}/providers/${PROV}/contracts/amend`, { target: 400, effectiveFrom: START, note: "E2E" })).status === 403); await call(admin, "POST", `${X}/providers/${PROV}/contracts/amend`, { target: Number(process.env["E2E_TARGET"] ?? 300), effectiveFrom: START, note: "E2E amendment" }); }
await call(tp, "POST", `${X}/imports/${goodB}/commit`); await waitFor("39 trainees saved", async () => Number((await q1("SELECT COUNT(*) n FROM trainees WHERE training_id=?", [tr.data.id])).n) === 40);
const T1 = (await q("SELECT id FROM trainees WHERE class_id=? ORDER BY id", [K1])).map((t) => String(t.id)), T2 = (await q("SELECT id FROM trainees WHERE class_id=? ORDER BY id", [K2])).map((t) => String(t.id));
ok("40 trainees, 20 per class, reserves included", T1.length === 20 && T2.length === 20 && Number((await q1("SELECT COUNT(*) n FROM trainees WHERE training_id=? AND roster_status='reserve'", [tr.data.id])).n) === 8);
await call(admin, "POST", `${X}/providers/${PROV}/registration-window`, { late: { until: now, reason: "E2E end" } });
await q("UPDATE providers SET registration_late_until=? WHERE id=?", [add(now, -1), PROV]);
ok("closed again: no edit, no new trainee", (await call(tp, "PATCH", `${X}/trainees/${T1[0]}`, { firstName: "Changed" })).data.code === "REGISTRATION_CLOSED" && (await call(tp, "POST", `${X}/trainees`, form(1))).data.code === "REGISTRATION_CLOSED");
part("registration, gates, form and file");

// Attendance: class 1 on the sheet, class 2 by file. Absences per trainee are fixed here.
const absent1 = T1.map((_, i) => (i === 0 ? 10 : i === 1 ? 3 : i === 2 ? 3 : i === 3 ? 2 : i === 4 ? 5 : i % 3)); // 10 %, 70, 70, exactly 80, 50 ...
absent1[5] = 2; absent1[6] = 0; for (let i = 7; i < 20; i++) absent1[i] = i % 3;
const absent2 = T2.map((_, i) => (i < 2 ? 4 : i % 3)), mark = (a: number[], i: number, d: number) => (d < a[i]! ? "A" : "P"), LATE = { justification: "Entered during the test" };
const sh = (await call(clerk, "GET", `${X}/classes/${K1}/attendance`)).data; ok("the sheet offers exactly the ten days", JSON.stringify(sh.sessionDates) === JSON.stringify(days), sh.sessionDates);
const marksOf = (ts: string[], a: number[], d: number) => Object.fromEntries(ts.map((t, i) => [t, mark(a, i, d)])), post = (k: string, d: string, m: Any, o: Any = LATE) => call(clerk, "POST", `${X}/classes/${k}/attendance/${d}`, { marks: m, ...o });
ok("a day with a missing trainee is refused", (await post(K1, days[0]!, { [T1[0]!]: "P" })).data.code === "INCOMPLETE");
ok("a weekend is refused", (await post(K1, [0, 1, 2, 3, 4, 5, 6].map((n) => add(days[0]!, n)).find((d) => dow(d) === 6)!, marksOf(T1, absent1, 0))).data.code === "NOT_A_SESSION");
ok("an exempt day is refused", (await post(K1, [0, 1, 2, 3].map((n) => add(START, n)).find((d) => dow(d) <= 5)!, marksOf(T1, absent1, 0))).status >= 400);
ok("a future day is refused", (await post(K3, [1, 2, 3, 4].map((n) => add(now, n)).find((d) => dow(d) <= 5)!, {})).status >= 400);
ok("'excused' is refused", (await post(K1, days[0]!, { ...marksOf(T1, absent1, 0), [T1[0]!]: "E" })).status === 422);
for (let d = 0; d < 9; d++) { const r = await post(K1, days[d]!, marksOf(T1, absent1, d)); ok(`sheet day ${d + 1}`, r.status === 200, r.data); }
ok("the same day twice is refused", (await post(K1, days[0]!, marksOf(T1, absent1, 0))).data.code === "ALREADY_SUBMITTED");
ok("another provider's user cannot see the sheet", [403, 404].includes((await call(stranger, "GET", `${X}/classes/${K1}/attendance`)).status));
const gates = async (k: string, t: string) => ((await lines(tp, k, t)).gates as Any[]).filter((g) => !g.ok).map((g) => `${g.label} ${g.detail ?? ""}`);
for (const t of ["dropout", "completion", "certification", "employment_placement", "locality_compliant", "job_retention_3m"]) ok(`one missing day blocks ${t}`, (await gates(K1, t)).some((g) => /Attendance/.test(g)) && (await send(tp, K1, t, [{ traineeId: T1[0], value: "no" }])).data.code === "BLOCKED");
const r10 = await post(K1, days[9]!, marksOf(T1, absent1, 9)); ok("sheet day 10", r10.status === 200, r10.data);
for (let d = 0; d < 10; d++) {
  const t = csvRows((await call(clerk, "GET", `${X}/classes/${K2}/attendance/template?date=${days[d]}`)).text), codeAt = t[0]!.indexOf("trainee_unique_id"), st = t[0]!.indexOf("status"), dt = t[0]!.indexOf("session_date"), ids = new Map((await q("SELECT id, trainee_code c FROM trainees WHERE class_id=?", [K2])).map((x) => [x.c as string, T2.indexOf(String(x.id))]));
  const full = t.map((r, n) => (n ? r.map((c, j) => (j === st ? (mark(absent2, ids.get(r[codeAt]!)!, d) === "A" ? "absent" : "present") : c)) : r));
  if (!d) {
    ok("attendance template: 20 trainees, one day", t.length === 21 && t.slice(1).every((r) => r[dt] === days[0]!.split("-").reverse().join("/")));
    const up = (rows: string[][]) => call(clerk, "POST", `${X}/classes/${K2}/attendance/import`, file(toCsv(rows), { date: days[0]! }));
    ok("attendance file: empty status refused", (await up(t)).status === 422); ok("attendance file: a second day refused", (await up(full.map((r, n) => (n === 3 ? r.map((c, j) => (j === dt ? days[1]! : c)) : r)))).status === 422);
    ok("attendance file: a missing trainee refused", (await up(full.slice(0, -1))).status >= 400); ok("attendance file: a stranger refused", (await up([...full, full[1]!.map((c, j) => (j === codeAt ? "PBPS-XX-000001" : c))])).status >= 400);
    ok("after the refused files nothing is saved", Number((await q1("SELECT COUNT(*) n FROM attendance_sessions WHERE class_id=?", [K2])).n) === 0);
  }
  const r = await call(clerk, "POST", `${X}/classes/${K2}/attendance/import`, file(toCsv(full), { date: days[d]!, ...LATE })); ok(`file day ${d + 1}`, r.status === 200, r.data);
}
const rates = async (k: string) => new Map((await q("SELECT trainee_id t, att_rate_final r, system_dropout_final f FROM trainee_status WHERE class_id=?", [k])).map((x) => [String(x.t), [Number(x.r), Number(x.f)]]));
const rt1 = await rates(K1), rt2 = await rates(K2); ok("every rate is exactly what was entered", T1.every((t, i) => rt1.get(t)![0] === 100 - absent1[i]! * 10) && T2.every((t, i) => rt2.get(t)![0] === 100 - absent2[i]! * 10), [...rt1].slice(0, 6));
const low1 = T1.filter((_, i) => absent1[i]! > 2), low2 = T2.filter((_, i) => absent2[i]! > 2); ok("below 80 % is flagged, exactly 80 % is not", T1.every((t) => rt1.get(t)![1] === (low1.includes(t) ? 1 : 0)) && rt1.get(T1[3]!)![0] === 80 && low1.length === 4 && low2.length === 2, [low1.length, low2.length]);
part("attendance by sheet and by file");

// Dropout
const ctx = await lines(tp, K1, "dropout"); ok("dropout: the people below 80 % are locked on Yes, nobody else", ctx.lines.length === 20 && ctx.lines.every((l: Any) => Boolean(l.locked) === low1.includes(String(l.traineeId)) && (!l.locked || l.value === "yes")), ctx.lines);
const dt = csvRows((await call(tp, "GET", `${X}/classes/${K1}/outcomes/dropout/template?format=csv`)).text), H = dt[0]!, at = (n: string) => H.indexOf(n), idOf = new Map((await q("SELECT id, trainee_code c FROM trainees WHERE training_id=?", [tr.data.id])).map((x) => [x.c as string, String(x.id)]));
ok("dropout template: Y for the people below 80 %, N for the others, 20 rows", dt.length === 21 && dt.slice(1).every((r) => (r[at("reported_value")] === "Y") === low1.includes(idOf.get(r[at("trainee_unique_id")]!)!)), dt.slice(0, 3));
const parse = (k: string, t: string, rows: string[][], w = tp) => call(w, "POST", `${X}/classes/${k}/outcomes/${t}/parse`, file(toCsv(rows)));
const flip = dt.map((r, n) => (n && idOf.get(r[at("trainee_unique_id")]!) === low1[1] ? r.map((c, j) => (j === at("reported_value") ? "N" : c)) : r)), fp = await parse(K1, "dropout", flip); ok("file: No for someone below 80 % is refused with the rate", fp.data.issues.some((i: Any) => /below 80/.test(i.message)), fp.data.issues);
ok("file: leaving out someone below 80 % is refused", (await parse(K1, "dropout", dt.filter((r) => idOf.get(r[at("trainee_unique_id")]!) !== low1[2]))).data.issues.some((i: Any) => /Missing/.test(i.message)));
const D = (over: Record<string, Any> = {}) => T1.map((t) => ({ traineeId: t, value: low1.includes(t) ? "yes" : "no", ...(low1.includes(t) ? { reason: "low_attendance_auto", eventDate: END } : {}), ...over[t] }));
for (const [name, l, re] of [["No for someone below 80 %", D({ [low1[0]!]: { value: "no" } }), /SYSTEM_DROPOUT/], ["someone below 80 % left out", D().filter((x) => x.traineeId !== low1[0]), /REQUIRED/], ["no reason", D({ [low1[0]!]: { reason: undefined } }), /REASON_REQUIRED/], ["a date in the future", D({ [low1[0]!]: { eventDate: add(now, 2) } }), /DATE_FUTURE/], ["a date before the class", D({ [low1[0]!]: { eventDate: add(START, -3) } }), /DATE_TOO_EARLY/], ["someone of another class", [...D(), { traineeId: T2[0], value: "no" }], /NOT_LISTED/], ["the same person twice", [...D(), D()[0]], /DUPLICATE/]] as [string, Any[], RegExp][]) { const r = await send(tp, K1, "dropout", l); ok(`server refuses dropout: ${name}`, r.status >= 400 && re.test(problems(r)), r.data); }
ok("an attendance clerk cannot report outcomes", (await send(clerk, K1, "dropout", D())).status === 403);
ok("nothing was stored by the refused attempts", Number((await q1("SELECT COUNT(*) n FROM outcome_reports WHERE class_id IN (?,?)", [K1, K2])).n) === 0);
ok("completion is closed before dropout", (await send(tp, K1, "completion", T1.map((t) => ({ traineeId: t, value: "yes", eventDate: END })))).data.code === "BLOCKED");
ok("a class that has not ended cannot report", (await gates(K3, "dropout")).some((g) => /ended/.test(g)));
const vol = T1[6]!; // above 80 %, but left: allowed with a reason
const dr = await send(tp, K1, "dropout", D({ [vol]: { value: "yes", reason: "voluntary_withdrawal", eventDate: END } })); ok("dropout accepted: 4 by attendance and 1 who left", dr.data.status === "accepted" && dr.data.yesCount === 5 && dr.data.noCount === 15, dr.data);
// Completion
const stay1 = T1.filter((t) => !low1.includes(t) && t !== vol), cc = await lines(tp, K1, "completion"); ok("completion lists the 15 others, no dropout", JSON.stringify(cc.lines.map((l: Any) => String(l.traineeId)).sort()) === JSON.stringify([...stay1].sort()));
const ctT = csvRows((await call(tp, "GET", `${X}/classes/${K1}/outcomes/completion/template?format=csv`)).text); ok("the completion template has no dropout either", ctT.length === 16 && ctT.slice(1).every((r) => stay1.includes(idOf.get(r[ctT[0]!.indexOf("trainee_unique_id")]!)!)));
const C = (over: Record<string, Any> = {}) => stay1.map((t) => ({ traineeId: t, value: "yes", eventDate: END, ...over[t] }));
for (const [name, l, re] of [["a dropout by attendance as completer", [...C(), { traineeId: low1[0], value: "yes", eventDate: END }], /NOT_LISTED/], ["someone who left as completer", [...C(), { traineeId: vol, value: "yes", eventDate: END }], /NOT_LISTED/], ["no date", C({ [stay1[0]!]: { eventDate: undefined } }), /DATE_REQUIRED/], ["someone left out", C().slice(1), /REQUIRED/]] as [string, Any[], RegExp][]) { const r = await send(tp, K1, "completion", l); ok(`server refuses completion: ${name}`, r.status >= 400 && re.test(problems(r)), r.data); }
// Attendance corrected after the dropout report: the two must agree again before anything else.
const victim = stay1.find((t) => rt1.get(t)![0] === 80)!, dP = days[9]!, cor = await call(tp, "POST", `${X}/attendance/corrections`, { classId: K1, date: dP, traineeId: victim, to: "A", reason: "Was absent" }); ok("a provider cannot decide its own correction", (await call(tp, "POST", `${X}/attendance/corrections/${cor.data.id}/decision`, { decision: "approve", note: "" })).status === 403);
await call(officer, "POST", `${X}/attendance/corrections/${cor.data.id}/decision`, { decision: "approve", note: "" });
ok("the correction brings the rate to 70 %", Number((await q1("SELECT att_rate_final r FROM trainee_status WHERE trainee_id=?", [victim])).r) === 70);
const bl = await send(tp, K1, "completion", C()); ok("completion is closed: someone below 80 % is not a dropout", bl.data.code === "BLOCKED" && /below 80/.test(bl.data.detail), bl.data);
const D2 = D({ [vol]: { value: "yes", reason: "voluntary_withdrawal", eventDate: END }, [victim]: { value: "yes", reason: "low_attendance_auto", eventDate: END } }), re1 = await send(tp, K1, "dropout", D2, "Attendance corrected"); ok("the corrected dropout report waits for M&E", re1.data.status === "ready");
ok("a provider cannot approve it", (await call(tp, "POST", `${X}/outcome-reports/${re1.data.id}/approve-resubmission`, { decision: "approve", note: "" })).status === 403);
ok("M&E approves it", (await call(officer, "POST", `${X}/outcome-reports/${re1.data.id}/approve-resubmission`, { decision: "approve", note: "" })).data.status === "accepted");
const stay = stay1.filter((t) => t !== victim), noComp = stay[0]!, cr = await send(tp, K1, "completion", stay.map((t) => (t === noComp ? { traineeId: t, value: "no" } : { traineeId: t, value: "yes", eventDate: END }))); ok("completion accepted: 13 yes, 1 no", cr.data.status === "accepted" && cr.data.yesCount === 13, cr.data);
ok("completion also stores the 6 dropouts as No", Number((await q1("SELECT COUNT(*) n FROM outcome_report_lines WHERE report_id=? AND value='no' AND reason_code='dropout'", [cr.data.id])).n) === 6);
ok("dropout cannot be taken back under completion", (await call(officer, "POST", `${X}/outcome-reports/${re1.data.id}/return`, { reason: "Check the list" })).data.code === "LATER_REPORT_EXISTS");
const done = stay.filter((t) => t !== noComp), ce = await lines(tp, K1, "certification"); ok("certification lists the 13 completers", ce.lines.length === 13 && ce.lines.every((l: Any) => done.includes(String(l.traineeId))));
ok("certification refuses a non-completer and a dropout", /NOT_LISTED/.test(problems(await send(tp, K1, "certification", [...done.map((t) => ({ traineeId: t, value: "yes", eventDate: END })), { traineeId: noComp, value: "yes", eventDate: END }, { traineeId: low1[0], value: "yes", eventDate: END }]))));
const cert = done.slice(0, 11); await send(tp, K1, "certification", done.map((t) => ({ traineeId: t, value: cert.includes(t) ? "yes" : "no", ...(cert.includes(t) ? { eventDate: END } : {}) })));
// Employment placement by file
const pt = csvRows((await call(tp, "GET", `${X}/classes/${K1}/outcomes/employment_placement/template?format=csv`)).text), PH = pt[0]!, sup7 = PH.filter((h) => h.startsWith("placement_support_")); ok("placement template: 29 columns, 11 certified, prefilled", PH.length === 29 && pt.length === 12 && pt.slice(1).every((r) => cert.includes(idOf.get(r[1]!)!) && r[2] && r[3] === "employment_placement") && PH[15] === "job_title" && sup7.length === 7, PH);
const base7 = Object.fromEntries(sup7.map((k) => [k, "Yes"])), wage: Any = { reported_value: "Yes", ...base7, employment_type: "wage_employed", job_title: "Network technician", employment_start_date: END, monthly_income_etb: "9500", contract_type: "contract_12_months_or_more", employer_name: "Sample PLC", employer_contact_person: "Sara T", employer_phone: "0911223344" }, biz: Any = { reported_value: "true", ...base7, employment_type: "self_employed_business", employment_start_date: END, monthly_income_etb: "7000.50", legal_form: "other", legal_form_other_text: "Cooperative", has_business_license: "Yes" }, oth: Any = { reported_value: "1", ...base7, employment_type: "other", employment_type_other_text: "Seasonal", employment_start_date: END, monthly_income_etb: "1200" }, none: Any = { reported_value: "No", ...base7 };
const pf = (g: (n: number) => Any) => pt.map((r, n) => (n ? PH.map((h, j) => g(n - 1)[h] ?? r[j]!) : r)), kinds = (n: number) => (n < 5 ? wage : n < 6 ? biz : n < 7 ? oth : none);
for (const [name, o, re] of [["job_title missing", { job_title: "" }, /job_title/], ["contract missing", { contract_type: "" }, /contract_type/], ["no way to reach the employer", { employer_phone: "" }, /employer_phone/], ["legal form on a wage row", { legal_form: "plc" }, /legal_form/], ["licence on a wage row", { has_business_license: "No" }, /has_business_license/], ["income with a comma", { monthly_income_etb: "9,500" }, /monthly_income/], ["income with text", { monthly_income_etb: "9500 ETB" }, /monthly_income/], ["income zero", { monthly_income_etb: "0" }, /monthly_income/], ["Excel phone", { employer_phone: "9.84E+08" }, /employer_phone/], ["Excel date", { employment_start_date: "46000" }, /employment_start_date/], ["month first date", { employment_start_date: "10/25/2026" }, /employment_start_date/], ["future date", { employment_start_date: add(now, 5) }, /future/], ["other contract unexplained", { contract_type: "other" }, /contract_type_other_text/], ["unknown type", { employment_type: "volunteer" }, /employment_type/], ["support not answered", { placement_support_cv_writing: "" }, /cv_writing/], ["No with an employer", { reported_value: "No" }, /must be empty/], ["no answer", { reported_value: "" }, /Y or N|Yes or No|reported_value/]] as [string, Any, RegExp][]) { const r = await parse(K1, "employment_placement", pf((n) => (n ? kinds(n) : { ...wage, ...o }))); ok(`placement file refuses: ${name}`, (r.data.issues as Any[]).some((i) => /^Row 2:/.test(i.message) && re.test(i.message)), r.data.issues); }
const extra = (t: string) => PH.map((h) => ({ ...none, outcome_type: "employment_placement", trainee_unique_id: [...idOf].find(([, v]) => v === t)![0] } as Any)[h] ?? ""), strangers = await parse(K1, "employment_placement", [...pf(kinds), extra(done[12]!), extra(low1[0]!), extra(noComp)]); ok("placement file refuses: not certified, dropout, non-completer", (strangers.data.issues as Any[]).filter((i) => /does not belong/.test(i.message)).length === 3, strangers.data.issues);
const pg = await parse(K1, "employment_placement", pf(kinds)); ok("a correct placement file has no problem", pg.data.issues.length === 0, pg.data.issues);
const ps = await send(tp, K1, "employment_placement", pg.data.lines.map((l: Any) => ({ traineeId: String(l.traineeId), value: l.value, details: l.details }))); ok("placement accepted: 7 placed, 4 not", ps.data.status === "accepted" && ps.data.yesCount === 7, ps.data);
const pd = await q("SELECT d.* FROM outcome_placement_details d JOIN outcome_report_lines l ON l.id=d.line_id WHERE l.report_id=? ORDER BY l.trainee_id", [ps.data.id]); ok("every placement answer is stored", pd.length === 11 && pd.filter((x) => x.employment_type === "wage_employed" && x.job_title === "Network technician" && x.employer_phone === "+251911223344" && Number(x.monthly_income_etb) === 9500 && x.contract_type === "contract_12_months_or_more").length === 5 && pd.some((x) => x.legal_form_other_text === "Cooperative" && Number(x.has_business_license) === 1 && Number(x.monthly_income_etb) === 7000.5) && pd.some((x) => x.employment_type_other_text === "Seasonal") && pd.filter((x) => x.employment_type === null).length === 4, pd[0]);
const placed = (await q("SELECT trainee_id t FROM trainee_status WHERE class_id=? AND placement_status='yes'", [K1])).map((x) => String(x.t));
for (const t of ["locality_compliant", "job_retention_3m"]) { const x = await lines(tp, K1, t); ok(`${t} lists only the 7 placed`, x.lines.length === 7 && x.lines.every((l: Any) => placed.includes(String(l.traineeId)))); ok(`${t} refuses someone not placed`, /NOT_LISTED/.test(problems(await send(tp, K1, t, [...placed.map((p) => ({ traineeId: p, value: "yes", eventDate: END })), { traineeId: cert.find((y) => !placed.includes(y)), value: "yes", eventDate: END }])))); const r = await send(tp, K1, t, placed.map((p, n) => ({ traineeId: p, value: n < 4 ? "yes" : "no", eventDate: END }))); ok(`${t} accepted`, r.data.status === "accepted", r.data); }
const open = await q1("SELECT SUM(completion_status='pending' OR certification_status='pending' OR placement_status='pending' OR locality_status='pending' OR retention_3m_status='pending') n FROM trainee_status WHERE class_id=?", [K1]); ok("at the end every trainee of the class has every result", Number(open.n) === 0, open);
part("dropout to retention, every refusal and every acceptance");

/* ---------- B. the real classes, reported again by location ---------- */
const real = await q(`SELECT id, site_id s, code, effective_end e FROM training_classes WHERE provider_id=? AND training_id<>? AND is_cancelled=0 ORDER BY id`, [PROV, tr.data.id]), ended = real.filter((k) => k.e < now);
ok("the source provider's classes are all here", ended.length > 5, ended.length);
// The rates are counted again from the marks, independently of the application.
const marks = await q("SELECT m.trainee_id t, SUM(m.status IN (1,3)) p FROM attendance_marks m JOIN attendance_sessions s ON s.id=m.session_id JOIN class_calendar_days c ON c.class_id=s.class_id AND c.cal_date=s.session_date AND c.kind='session' JOIN training_classes k ON k.id=s.class_id WHERE k.provider_id=? GROUP BY 1", [PROV]);
{ const n = await q("SELECT class_id k, COUNT(*) n FROM class_calendar_days WHERE kind='session' GROUP BY 1"), st = await q("SELECT trainee_id t, class_id k, att_rate_final r, att_possible_final f FROM trainee_status WHERE att_rate_final IS NOT NULL"), p = new Map(marks.map((m) => [String(m.t), Number(m.p)])), c = new Map(n.map((x) => [String(x.k), Number(x.n)])); const wrong = st.filter((s) => Number(s.f) === c.get(String(s.k)) && Math.abs(Math.round(((p.get(String(s.t)) ?? 0) / Number(s.f)) * 10000) / 100 - Number(s.r)) > 0.006); ok(`attendance rate of ${st.length} trainees counted again`, st.length > 100 && wrong.length === 0, wrong.slice(0, 3)); console.log(`      ${st.filter((s) => Number(s.f) === c.get(String(s.k))).length} attendance rates counted again from the marks`); }
const want = new Map((await q(`SELECT trainee_id t, class_id k, dropout_status d, dropout_reason dr, completion_status c, certification_status ce, system_dropout_final f, roster_status r FROM ${SRC}.trainee_status WHERE provider_id=?`, [PROV])).map((x) => [String(x.t), x]));
const codes = new Map((await q("SELECT id, trainee_code c FROM trainees WHERE provider_id=?", [PROV])).map((x) => [x.c as string, String(x.id)]));
for (const type of ["dropout", "completion", "certification"]) for (const s of [...new Set(ended.map((k) => String(k.s)))]) {
  const u = `${X}/sites/${s}/outcomes/${type}`, head = (await call(tp, "GET", `${u}/context`)).data, expected = ended.filter((k) => String(k.s) === s && (type !== "certification" || [...want.values()].some((w) => String(w.k) === String(k.id) && w.ce === "yes")));
  if (!expected.length) continue;
  ok(`${type} location ${s}: every ended class is ready`, expected.every((k) => head.classes.some((x: Any) => String(x.id) === String(k.id) && x.state === "ready")), head.classes?.map((x: Any) => [x.code, x.state, x.reason]));
  const t = csvRows((await call(tp, "GET", `${u}/template?format=csv`)).text), h = t[0]!, i = (n: string) => h.indexOf(n), key = { dropout: "d", completion: "c", certification: "ce" }[type]!;
  const should = [...want].filter(([, w]) => head.classes.some((x: Any) => x.state === "ready" && String(x.id) === String(w.k)) && ["active", "reserve"].includes(w.r) && (type === "dropout" || (type === "completion" ? w.d !== "yes" : w.c === "yes"))).map(([id]) => id).sort();
  ok(`${type} location ${s}: the template holds exactly the right ${should.length} people`, JSON.stringify(t.slice(1).map((r) => codes.get(r[i("trainee_unique_id")]!)).sort()) === JSON.stringify(should), [t.length - 1, should.length]);
  if (type === "dropout") ok(`dropout location ${s}: the template marks everyone below 80 %`, t.slice(1).every((r) => (r[i("reported_value")] === "Y") === Boolean(Number(want.get(codes.get(r[i("trainee_unique_id")]!)!)!.f))));
  const fill = t.map((r, n) => { if (!n) return r; const id = codes.get(r[i("trainee_unique_id")]!)!, w = want.get(id)!, yes = w[key] === "yes", e = ended.find((k) => String(k.id) === String(w.k))!.e as string; return r.map((c, j) => (h[j] === "reported_value" ? (yes ? "Y" : "N") : h[j] === `${type}_date` ? (yes ? e : "") : h[j] === "dropout_reason" ? (yes && type === "dropout" ? w.dr ?? "other" : "") : h[j] === "noncompletion_reason" ? (!yes && type === "completion" ? "failed_assessment" : "") : h[j] === "status_date" ? "" : c)); });
  if (type === "dropout") { const lowRow = fill.findIndex((r, n) => n > 0 && Boolean(Number(want.get(codes.get(r[i("trainee_unique_id")]!)!)!.f))); if (lowRow > 0) { const b = await call(tp, "POST", `${u}/parse`, file(toCsv(fill.map((r, n) => (n === lowRow ? r.map((c, j) => (h[j] === "reported_value" ? "N" : c)) : r))))); ok(`dropout location ${s}: No for a real trainee below 80 % is refused`, b.data.issues.some((x: Any) => /below 80/.test(x.message)), b.data.issues); } }
  const p = await call(tp, "POST", `${u}/parse`, file(toCsv(fill))), body = { classes: (p.data.classes ?? []).map((k: Any) => ({ id: String(k.id), lines: k.lines.map((l: Any) => ({ traineeId: String(l.traineeId), value: l.value, ...(l.eventDate ? { eventDate: l.eventDate } : {}), ...(l.reason ? { reason: l.reason } : {}), ...(type === "completion" && l.value === "no" && !l.reason ? { reason: "failed_assessment" } : {}) })) })) };
  ok(`${type} location ${s}: the filled file has no problem`, p.data.issues?.length === 0, p.data.issues ?? p.data);
  const r = await call(tp, "POST", `${u}/submit`, body); ok(`${type} location ${s}: accepted`, r.data.accepted === expected.length, r.data);
}
const got = await q("SELECT trainee_id t, dropout_status d, completion_status c, certification_status ce FROM trainee_status WHERE provider_id=? AND class_id IN (?)", [PROV, ended.map((k) => k.id)]), norm = (v: string) => (v === "not_applicable" ? "no" : v), diff = got.filter((g) => { const w = want.get(String(g.t))!; return g.d !== w.d || norm(g.c) !== norm(w.c) || norm(g.ce) !== norm(w.ce); });
ok(`all ${got.length} real trainees end with the same dropout, completion and certification`, diff.length === 0, diff.slice(0, 5).map((g) => [g, want.get(String(g.t))]));
part(`the real provider: ${ended.length} classes, ${got.length} trainees, three reports by location`);
// Placement for a whole real location, with every kind of answer
if ([...want.values()].some((w) => w.ce === "yes")) {
const ps0 = ended.map((k) => String(k.s)).find((s) => [...want.values()].some((w) => w.ce === "yes" && ended.some((k) => String(k.s) === s && String(k.id) === String(w.k))))!, pu = `${X}/sites/${ps0}/outcomes/employment_placement`, rt = csvRows((await call(tp, "GET", `${pu}/template?format=csv`)).text), certified = [...want].filter(([, w]) => w.ce === "yes" && ended.some((k) => String(k.s) === ps0 && String(k.id) === String(w.k))).map(([id]) => id);
ok(`placement for a real location: exactly its ${certified.length} certified trainees`, JSON.stringify(rt.slice(1).map((r) => codes.get(r[1]!)).sort()) === JSON.stringify([...certified].sort()));
const rf = rt.map((r, n) => (n ? PH.map((h, j) => ({ ...(n % 4 === 0 ? none : n % 4 === 1 ? wage : n % 4 === 2 ? biz : { ...biz, employment_type: "self_employed_freelance", legal_form: "no_legal_form", legal_form_other_text: "", has_business_license: "No" }), ...(n % 4 === 0 ? {} : { job_title: n % 4 === 1 ? "Technician" : "Owner" }) } as Any)[h] ?? r[j]!) : r)), rp = await call(tp, "POST", `${pu}/parse`, file(toCsv(rf))); ok("the real placement file has no problem", rp.data.issues.length === 0, rp.data.issues);
const broken = rp.data.classes.map((k: Any, n: number) => ({ id: String(k.id), lines: k.lines.map((l: Any, m: number) => ({ traineeId: String(l.traineeId), value: l.value, details: n === rp.data.classes.length - 1 && m === 0 ? { ...l.details, placement_support_job_fair: "" } : l.details })) }));
ok("one wrong class stops the whole location, nothing is half saved", (await call(tp, "POST", `${pu}/submit`, { classes: broken })).status === 422 && Number((await q1("SELECT COUNT(*) n FROM outcome_reports r JOIN training_classes k ON k.id=r.class_id WHERE k.site_id=? AND report_type='employment_placement'", [ps0])).n) === 0);
const rs = await call(tp, "POST", `${pu}/submit`, { classes: rp.data.classes.map((k: Any) => ({ id: String(k.id), lines: k.lines.map((l: Any) => ({ traineeId: String(l.traineeId), value: l.value, details: l.details })) })) }); ok("the whole location is accepted", rs.data.accepted === rp.data.classes.length, rs.data);
ok("every placed person of the file is placed in the system", Number((await q1("SELECT COUNT(*) n FROM trainee_status WHERE trainee_id IN (?) AND placement_status='yes'", [certified])).n) === rf.slice(1).filter((_, n) => (n + 1) % 4 !== 0).length);
} else console.log("      this provider has no certified trainees, so there is no real placement to report");

/* ---------- C. indicators, sampling, verification ---------- */
await call(admin, "POST", `${X}/jobs`, { kind: "recompute" });
const tgt = Number((await q1("SELECT target_trainees t FROM provider_contracts WHERE provider_id=? AND status='active' ORDER BY id DESC LIMIT 1", [PROV])).t), S = await q1("SELECT COUNT(*) n, SUM(eligibility_status='eligible') e, SUM(dropout_status='yes' OR system_dropout_final) d, SUM(completion_status='yes') c, SUM(certification_status='yes') ce, SUM(placement_status='yes') p, SUM(locality_status='yes') l, SUM(retention_3m_status='yes') r, SUM(att_present_to_date) ap, SUM(att_sessions_to_date) an FROM trainee_status WHERE provider_id=? AND roster_status IN ('active','reserve')", [PROV]), cap = (n: number) => Math.min(Number(n), tgt), comp = cap(S.c), pct = (a: number, b: number) => Math.round((a / b) * 10000) / 100;
const exp: Record<string, number> = { registered_enrolled_trainees_count: Number(S.n), eligible_enrolled_trainee_rate: pct(cap(S.e), tgt), trainee_attendance_rate: pct(Number(S.ap), Number(S.an)), trainee_dropout_rate: pct(Math.min(tgt, Math.max(0, Number(S.d) - Math.max(0, Number(S.n) - tgt))), tgt), training_completion_rate: pct(comp, tgt), training_certification_rate: pct(Number(S.ce), comp), employment_placement_rate: pct(Number(S.p), comp), locality_compliant_placement_rate: pct(Number(S.l), comp), job_retention_3_month_rate: pct(Number(S.r), Number(S.p)) };
await waitFor("indicators calculated", async () => { const k = await q1("SELECT value v FROM kpi_snapshots WHERE indicator_code='employment_placement_rate' AND provider_key=? AND layer='monitoring' ORDER BY as_of_date DESC, computed_at DESC LIMIT 1", [PROV]); return k && Math.abs(Number(k.v) - exp["employment_placement_rate"]!) < 0.006; });
for (const [c, v] of Object.entries(exp)) { const k = await q1("SELECT value v FROM kpi_snapshots WHERE indicator_code=? AND provider_key=? AND layer='monitoring' ORDER BY as_of_date DESC, computed_at DESC LIMIT 1", [c, PROV]); ok(`indicator ${c} is ${v}`, Math.abs(Number(k?.v) - v) < 0.006, k); }
ok("a provider sees no indicator, target or sample", (await Promise.all(["indicators", "targets", "verification/runs", "kpis/report"].map((u) => call(tp, "GET", `${X}/${u}`)))).every((r) => r.status === 403));
const cochran = (N: number) => { const n0 = (1.96 ** 2 * 0.25) / 0.05 ** 2; return { n0, n: n0 / (1 + (n0 - 1) / N) }; };
for (const [ind, sql] of [["training_completion_rate", "1=1"], ["training_certification_rate", "completion_status='yes'"], ["employment_placement_rate", "certification_status='yes'"], ["locality_compliant_placement_rate", "placement_status='yes'"], ["job_retention_3_month_rate", "placement_status='yes'"]] as const) {
  const N = Number((await q1(`SELECT COUNT(*) n FROM trainee_status WHERE provider_id=? AND roster_status IN ('active','reserve') AND ${sql}`, [PROV])).n), p = (await call(sup, "GET", `${X}/verification/sample-preview?indicator=${ind}&providerId=${PROV}`)).data, c = cochran(N), inflated = Math.min(N, Math.ceil(Math.ceil(c.n) / 0.9));
  ok(`${ind}: population ${N}, Cochran sample ${inflated}`, p.population === N && Math.abs(p.nTarget - inflated) <= p.strata.length, { p, want: inflated }); ok(`${ind}: the strata add up`, p.strata.reduce((a: number, x: Any) => a + x.population, 0) === N && p.strata.reduce((a: number, x: Any) => a + x.primary, 0) === p.nTarget, p.strata);
}
const draw = (ind: string, period: string, seed = "e2e-seed", w = sup) => call(w, "POST", `${X}/verification/runs`, { indicator: ind, providerId: PROV, period, seed, preReport: true });
ok("a provider cannot draw a sample", (await draw("training_completion_rate", "2026-12", "x", tp)).status === 403);
const d1 = await draw("training_completion_rate", "2026-12"); ok("a completion sample is drawn", d1.status === 200, d1.data); const R = String(d1.data.runId);
ok("with an open run nobody has to draw again: a second draw is refused, for any period", (await draw("training_completion_rate", "2026-12")).data.code === "RUN_OPEN" && (await draw("training_completion_rate", "2027-01")).data.code === "RUN_OPEN");
const subs = async (r = R) => q("SELECT v.*, s.completion_status c, s.dropout_status d, s.placement_status pl, s.certification_status ce FROM verification_subjects v JOIN trainee_status s ON s.trainee_id=v.trainee_id WHERE v.run_id=?", [r]); let V = await subs();
ok("sample: dropouts are settled, completers claimed, nobody is verified yet", V.every((v) => (v.d === "yes" ? v.status_code === "V-NCOMP" && !v.tp_claim_value : v.status_code === null && Number(v.tp_claim_value) === (v.c === "yes" ? 1 : 0))));
ok("sample: nobody twice, strata by location and sex", new Set(V.map((v) => String(v.trainee_id))).size === V.length && V.every((v) => /^location:.+\|sex:(male|female)$/.test(v.stratum_key)));
const ids1 = V.map((v) => `${v.trainee_id}:${v.role}`).sort().join();
// A returned and repeated completion report must reach the open sample.
for (const t of ["job_retention_3m", "locality_compliant", "employment_placement", "certification", "completion"]) { const r = await q1("SELECT id FROM outcome_reports WHERE class_id=? AND report_type=? AND status='accepted'", [K1, t]), x = await call(officer, "POST", `${X}/outcome-reports/${r.id}/return`, { reason: "E2E return test" }); ok(`${t} can be returned in the right order`, x.data.status === "returned", x.data); }
V = await subs(); ok("returned completion: the claims of that class are gone", V.filter((v) => done.includes(String(v.trainee_id))).every((v) => Number(v.tp_claim_value) === 0) && V.some((v) => done.includes(String(v.trainee_id))));
const again = await send(tp, K1, "completion", stay.map((t) => (t === noComp ? { traineeId: t, value: "no", reason: "failed_assessment" } : { traineeId: t, value: "yes", eventDate: END }))); V = await subs(); ok("sent again: the claims are back", again.data.status === "accepted" && V.filter((v) => done.includes(String(v.trainee_id))).every((v) => Number(v.tp_claim_value) === 1), again.data);
const enuName = (await q1("SELECT u.name n FROM users u JOIN user_sessions s ON s.user_id=u.id WHERE s.refresh_token_hash=?", [createHash("sha256").update(enu.token).digest("hex")])).n, todo = V.filter((v) => v.role === "primary" && v.status_code === null);
ok("assign", (await call(sup, "POST", `${X}/verification/runs/${R}/assign`, { subjectIds: todo.map((v) => String(v.id)), enumerator: enuName })).data.assigned === todo.length);
let yes = 0, no = 0, refused = 0;
for (const [n, v] of todo.entries()) { const a = n % 10 === 0 ? { q1: "yes", q10: "no" } : { q1: "yes", q10: "yes" }; if (n === 3) { const u = await call(enu, "POST", `${X}/verification/subjects/${v.id}/unreachable`, { note: "No answer" }); ok("unreachable is one step", u.data.status === "V-UNR", u.data); refused++; continue; } const r = await call(enu, "POST", `${X}/verification/subjects/${v.id}/response`, { answers: a }); if (r.status !== 200) ok("response", false, r.data); if (n % 10) yes++; else no++; }
ok("a result cannot be approved by the one who recorded it", (await call(enu, "POST", `${X}/verification/subjects/${todo[0].id}/review`, { decision: "approve" })).status === 403);
const rep = await call(sup, "POST", `${X}/verification/subjects/${todo[3].id}/replace`); ok("a reserve of the same stratum replaces the unreachable one", rep.status === 200 && rep.data.role === "replacement" && rep.data.stratum === todo[3].stratum_key, rep.data);
if (rep.status === 200 && !rep.data.status) { await call(sup, "POST", `${X}/verification/runs/${R}/assign`, { subjectIds: [String(rep.data.id)], enumerator: enuName }); await call(enu, "POST", `${X}/verification/subjects/${rep.data.id}/response`, { answers: { q1: "yes", q10: "yes" } }); yes++; } else if (rep.data.status === "V-NCOMP") no++;
ok("an unreviewed run cannot be finished", (await call(sup, "POST", `${X}/verification/runs/${R}/finalize`)).status >= 400);
for (const s of await q("SELECT id FROM verification_subjects WHERE run_id=? AND supervisor_status='pending' AND status_code IS NOT NULL", [R])) await call(sup, "POST", `${X}/verification/subjects/${s.id}/review`, { decision: "approve" });
const fin = await call(sup, "POST", `${X}/verification/runs/${R}/finalize`), auto = V.filter((v) => v.role === "primary" && v.status_code === "V-NCOMP").length, n = yes + no + auto, ph = yes / n, z = 1.645, den = 1 + z ** 2 / n, mid = ph + z ** 2 / (2 * n), half = z * Math.sqrt((ph * (1 - ph)) / n + z ** 2 / (4 * n * n)), lo = ((mid - half) / den) * 100, hi = ((mid + half) / den) * 100;
ok("finished: the rate and Wilson interval are right", fin.data.status === "finalised" && Math.abs(fin.data.result.rate - ph * 100) < 0.06 && Math.abs(fin.data.result.ciLow - lo) < 0.2 && Math.abs(fin.data.result.ciHigh - hi) < 0.2, { r: fin.data.result ?? fin.data, hand: [ph * 100, lo, hi, yes, no, auto, refused] });
ok("finished: the decision follows the pass mark of 90 %", fin.data.result?.target === 90 && fin.data.result.pathway === (lo > 90 ? "clear_pass" : hi < 90 ? "clear_fail" : "inconclusive"), fin.data.result);
ok("a finished run is closed for ever", (await call(enu, "POST", `${X}/verification/subjects/${todo[1].id}/response`, { answers: { q1: "no" } })).status >= 400 && (await call(sup, "POST", `${X}/verification/runs/${R}/refresh`)).status >= 400);
const s2 = await draw("training_completion_rate", "2027-01"), V2 = await subs(String(s2.data.runId)); ok("the same seed draws the same people again", V2.map((v) => `${v.trainee_id}:${v.role}`).sort().join() === ids1, s2.data);
part("indicators, sampling and verification");
ok("only the 40 test trainees were added", Number((await q1("SELECT COUNT(*) n FROM trainees")).n) - Number(before.n) === 40);
ok("the audit chain is unbroken", (await call(admin, "POST", `${X}/audit/verify`, {})).data.intact === true);
ok("the provider never sees verification, not even in its notifications", !/sample|verification run/i.test(problems(await call(tp, "GET", `${X}/notifications`))));
console.log(`\n${pass} checks passed, ${fails.length} failed (provider ${code})`);
await db.end();
process.exit(fails.length ? 1 : 0);
