// End-to-end checks on a throwaway copy of the migrated database:  npm run test:api
import "dotenv/config";
import { createHash, randomBytes } from "node:crypto";

const url = process.env["TEST_DATABASE_URL"] ?? "";
if (!/_test$/.test(url)) throw new Error("TEST_DATABASE_URL must point to a database whose name ends in _test.");
process.env["DATABASE_URL"] = url;
process.env["STORAGE_DIR"] = process.env["TEST_STORAGE_DIR"] ?? "./storage-test";
process.env["MAIL_DELIVERY"] = "off";
const { buildApp } = await import("../src/app/buildApp.js");
const { pool, query, one, execute } = await import("../src/core/db/db.js");
const { runNextJob } = await import("../src/core/jobs/jobs.js");
const { verifyChain } = await import("../src/core/audit/audit.js");
const { default: bcrypt } = await import("bcryptjs");
const { addDays, isoWeekday, today } = await import("../src/shared/dates.js");

type Any = any; // eslint-disable-line @typescript-eslint/no-explicit-any
let pass = 0;
const fails: string[] = [];
const ok = (name: string, cond: unknown, info: unknown = "") => { if (cond) pass++; else { fails.push(name); console.log("FAIL", name, typeof info === "string" ? info : JSON.stringify(info)?.slice(0, 600)); } };
const routes: { method: string; url: string }[] = [];
const app = await buildApp({ logger: false, rateLimit: false, onRoute: (r) => { for (const m of [r.method].flat()) if (m !== "HEAD") routes.push({ method: m, url: r.url }); } });
app.addHook("onError", async (req, _reply, e) => { if (e.name !== "ZodError" && (!("code" in e) || String((e as { code?: string }).code).startsWith("ER_") || e instanceof TypeError)) { ok(`server error on ${req.method} ${req.url}: ${e.message}`, false); } });
await app.ready();
const B = "/api/v2";
interface Who { token: string; csrf: string }
const sessions = new Map<string, Who>();
async function user(role: string, providerId: string | null = null, scopes: { type: string; id: string }[] = []): Promise<Who> {
  const email = `t_${randomBytes(5).toString("hex")}@test.local`, u = await execute(pool, "INSERT INTO users (name, email, password_hash, status, two_factor_method) VALUES (?,?,?,'active','none')", [`T ${role} ${email.slice(2, 6)}`, email, await bcrypt.hash("Passw0rd-test", 4)]), uid = String(u.insertId);
  const m = await execute(pool, "INSERT INTO memberships (project_id, user_id, role_id, provider_id, status) SELECT 1, ?, id, ?, 'active' FROM roles WHERE code=?", [uid, providerId, role]);
  for (const s of scopes) await execute(pool, "INSERT INTO membership_scopes (membership_id, scope_type, scope_id) VALUES (?,?,?)", [String(m.insertId), s.type, s.id]);
  const token = randomBytes(16).toString("hex");
  await execute(pool, "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)", [uid, createHash("sha256").update(token).digest("hex")]);
  const w = { token, csrf: "c" };
  sessions.set(email, w);
  return w;
}
async function call(w: Who | null, method: string, path: string, body?: unknown, headers: Record<string, string> = {}): Promise<{ status: number; data: Any; raw: Buffer; headers: Any }> {
  const form = body instanceof FormData, req = form ? new Request("http://x", { method: "POST", body }) : null;
  const r = await app.inject({ method: method as never, url: B + path, headers: { ...(w ? { cookie: `pbps_session=${w.token}; pbps_csrf=${w.csrf}`, "x-csrf-token": w.csrf } : {}), ...(req ? { "content-type": req.headers.get("content-type")! } : {}), ...headers }, ...(body === undefined ? {} : { payload: req ? Buffer.from(await req.arrayBuffer()) : (body as object) }) });
  let data: Any; try { data = r.json(); } catch { data = r.body; }
  return { status: r.statusCode, data, raw: r.rawPayload, headers: r.headers };
}
const jobs = async () => { await execute(pool, "UPDATE jobs SET run_at=UTC_TIMESTAMP(3) WHERE status='queued'"); for (let i = 0; i < 60 && (await runNextJob()); i++); };
const admin = await user("system_admin"), lead = await user("me_lead"), officer = await user("me_officer");

// 1. Every GET endpoint answers on real data.
const ids: Any = { trainee: (await one(pool, "SELECT id FROM trainees ORDER BY id LIMIT 1"))!["id"], cls: (await one(pool, "SELECT class_id FROM outcome_reports LIMIT 1"))!["class_id"], training: (await one(pool, "SELECT id FROM trainings LIMIT 1"))!["id"], report: (await one(pool, "SELECT id FROM outcome_reports LIMIT 1"))!["id"], ob: (await one(pool, "SELECT obligation_id AS o FROM activity_submissions WHERE obligation_id IS NOT NULL LIMIT 1"))!["o"], run: (await one(pool, "SELECT id FROM verification_runs LIMIT 1"))!["id"], sub: (await one(pool, "SELECT id FROM verification_subjects LIMIT 1"))!["id"], g: (await one(pool, "SELECT id FROM grievance_cases LIMIT 1"))!["id"], prov: (await one(pool, "SELECT id FROM providers LIMIT 1"))!["id"], member: (await one(pool, "SELECT id FROM memberships LIMIT 1"))!["id"] };
const idFor = (u: string) => (/trainees\//.test(u) ? ids.trainee : /trainings\//.test(u) ? ids.training : /classes\//.test(u) ? ids.cls : /outcome-reports\//.test(u) ? ids.report : /obligations\//.test(u) ? ids.ob : /runs\//.test(u) ? ids.run : /subjects\//.test(u) ? ids.sub : /grievances\//.test(u) ? ids.g : /providers?\//.test(u) ? ids.prov : /memberships\//.test(u) ? ids.member : "0");
let slow: [string, number][] = [];
for (const r of routes.filter((x) => x.method === "GET" && x.url.startsWith(B) && !/auth\/invites|grievances\/status|:file|files\/:id|jobs\/:id|imports\/:id|attendance\/template|sites\/:id\/outcomes/.test(x.url))) {
  const path = r.url.slice(B.length).replace(":p", "1").replace(":id", idFor(r.url)).replace(":code", "training_completion_rate").replace(":type", "completion") + (r.url.includes("sample-preview") ? `?indicator=training_completion_rate&providerId=${ids.prov}` : r.url.includes("schedules/preview") ? `?providerId=${ids.prov}` : ""), t = Date.now(), x = await call(admin, "GET", path);
  slow.push([path, Date.now() - t]);
  ok(`GET ${path}`, x.status < 300, `${x.status} ${JSON.stringify(x.data)?.slice(0, 300)}`);
}
slow = slow.sort((a, b) => b[1] - a[1]);
console.log("slowest pages (ms):", slow.slice(0, 5).map(([p, ms]) => `${p} ${ms}`).join(", "));

// 2. Nobody gets in without a session, without the CSRF header, or without permission.
for (const r of routes.filter((x) => x.url.startsWith(`${B}/projects`) || x.url.startsWith(`${B}/settings`) || x.url.startsWith(`${B}/roles`))) { const p = r.url.slice(B.length).replace(/:(p|id|siteId|row|file|v)/g, "1").replace(/:\w+/g, "x"); const x = await call(null, r.method, p, r.method === "GET" ? undefined : {}); ok(`no session ${r.method} ${p}`, x.status === 401, x.status); if (r.method !== "GET") { const y = await call({ ...admin, csrf: "c" }, r.method, p, {}, { "x-csrf-token": "wrong" }); ok(`csrf ${r.method} ${p}`, y.status === 403 && y.data.code === "CSRF", y); } }
const viewer = await user("funder_viewer");
for (const r of routes.filter((x) => x.method !== "GET" && x.url.startsWith(`${B}/projects/:p/`) && !/read|jobs|preview-calendar|reports\/:key|audit\/verify/.test(x.url))) { const p = r.url.slice(B.length).replace(/:(p|id|siteId|row|file|v)/g, "1").replace(/:\w+/g, "x"), x = await call(viewer, r.method, p, {}); ok(`funder cannot ${r.method} ${p}`, x.status === 403, x.status); }
ok("funder sees no phone", !(await call(viewer, "GET", `/projects/1/trainees/${ids.trainee}`)).data.phone);

// 3. A provider never reaches another provider's records.
const [pA, pB] = (await query(pool, "SELECT provider_id AS id FROM outcome_reports GROUP BY provider_id LIMIT 2")).map((p) => String(p["id"])), tp = await user("tp_admin", pA!);
for (const [name, sql, path] of [["trainee", "SELECT id FROM trainees WHERE provider_id=? LIMIT 1", "trainees/"], ["class", "SELECT id FROM training_classes WHERE provider_id=? LIMIT 1", "classes/"], ["training", "SELECT id FROM trainings WHERE provider_id=? LIMIT 1", "trainings/"], ["report", "SELECT id FROM outcome_reports WHERE provider_id=? LIMIT 1", "outcome-reports/"], ["obligation", "SELECT id FROM activity_obligations WHERE provider_id=? LIMIT 1", "obligations/"], ["case", "SELECT id FROM grievance_cases WHERE provider_id=? LIMIT 1", "grievances/"], ["provider", "SELECT id FROM providers WHERE id=? LIMIT 1", "providers/"]] as const) {
  const own = (await one(pool, sql, [pA!]))?.["id"], other = (await one(pool, sql, [pB!]))?.["id"];
  if (own) ok(`provider opens own ${name}`, (await call(tp, "GET", `/projects/1/${path}${own}`)).status === 200);
  if (other) { const x = await call(tp, "GET", `/projects/1/${path}${other}`); ok(`provider cannot open other ${name}`, [403, 404].includes(x.status), x.status); }
}
for (const p of ["trainees?pageSize=200", "classes?pageSize=200", "trainings?pageSize=200", "outcome-reports?pageSize=200", "obligations?pageSize=200", "grievances?pageSize=200", "outcomes/status?pageSize=200"]) { const other = (await one(pool, "SELECT code FROM providers WHERE id=?", [pB!]))!["code"], x = await call(tp, "GET", `/projects/1/${p}&providerId=${pB}`); ok(`list ${p} leaks nothing`, x.status === 200 && !JSON.stringify(x.data).includes(`"providerCode":"${other}"`), x.status); }
for (const p of ["runs", "my-work", "plans", "review-queue", `subjects/${ids.sub}`, `runs/${ids.run}/subjects`]) ok(`provider cannot see verification ${p}`, (await call(tp, "GET", `/projects/1/verification/${p}`)).status === 403);
const site = (await one(pool, "SELECT site_id AS s, id FROM training_classes WHERE provider_id=? LIMIT 1", [pA!]))!, lim = await user("tp_site_lead", pA!, [{ type: "site", id: String(site["s"]) }]), seen = (await call(lim, "GET", "/projects/1/classes?pageSize=200")).data.items as Any[];
ok("site lead sees only own site", seen.length > 0 && seen.every((c) => String(c.siteId) === String(site["s"])));
const outside = await one(pool, "SELECT id FROM training_classes WHERE provider_id=? AND site_id<>? LIMIT 1", [pA!, site["s"]]);
if (outside) ok("site lead cannot open another site's class", (await call(lim, "GET", `/projects/1/classes/${outside["id"]}`)).status === 404);
ok("provider admin cannot invite an administrator", (await call(tp, "POST", `/projects/1/providers/${pA}/staff`, { name: "X Y", email: "x1@y.test", roleCode: "tp_admin", scopes: [] })).status === 200 && (await call(tp, "POST", "/projects/1/memberships", { name: "X Y", email: "x2@y.test", roleCode: "system_admin" })).status === 403);
ok("M&E lead cannot create an administrator", (await call(lead, "POST", "/projects/1/memberships", { name: "X Y", email: "x3@y.test", roleCode: "system_admin" })).status === 403);

// 4. Sign-in.
const lu = await execute(pool, "INSERT INTO users (name, email, password_hash, status, two_factor_method) VALUES ('L','login@test.local',?,'active','none')", [await bcrypt.hash("Correct-horse1", 4)]);
const good = await call(null, "POST", "/auth/login", { email: "Login@test.local", password: "Correct-horse1" });
ok("login works", good.status === 200 && good.data.status === "ok" && /HttpOnly/i.test(String(good.headers["set-cookie"])), good);
for (let i = 0; i < 5; i++) await call(null, "POST", "/auth/login", { email: "login@test.local", password: "bad" });
ok("account locks after five failures", (await call(null, "POST", "/auth/login", { email: "login@test.local", password: "Correct-horse1" })).data.code === "ACCOUNT_LOCKED");
await execute(pool, "UPDATE users SET locked_until=NULL, failed_login_count=0, two_factor_method='email' WHERE id=?", [String(lu.insertId)]);
const two = await call(null, "POST", "/auth/login", { email: "login@test.local", password: "Correct-horse1" }), code = /code is (\d{6})/.exec((await one(pool, "SELECT text_body AS t FROM email_outbox WHERE to_email='login@test.local' ORDER BY id DESC LIMIT 1"))!["t"])![1];
ok("2FA refuses a wrong code", (await call(null, "POST", "/auth/2fa/verify", { challengeId: two.data.challengeId, code: code === "111111" ? "222222" : "111111" })).data.code === "CODE_INVALID");
ok("2FA accepts the emailed code once", (await call(null, "POST", "/auth/2fa/verify", { challengeId: two.data.challengeId, code })).data.status === "ok" && (await call(null, "POST", "/auth/2fa/verify", { challengeId: two.data.challengeId, code })).status === 410);
await call(null, "POST", "/auth/password/forgot", { email: "login@test.local" });
const reset = /token=(\S+)/.exec((await one(pool, "SELECT text_body AS t FROM email_outbox WHERE template_key='auth.reset' ORDER BY id DESC LIMIT 1"))!["t"])![1];
ok("weak password refused", (await call(null, "POST", "/auth/password/reset", { token: reset, new: "short" })).status === 422);
ok("password reset link works once", (await call(null, "POST", "/auth/password/reset", { token: reset, new: "Brand-new-pass1" })).status === 200 && (await call(null, "POST", "/auth/password/reset", { token: reset, new: "Brand-new-pass2" })).status === 410);

{ const st = await call(null, "GET", "/public/stats"), txt = JSON.stringify(st.data), names = await query(pool, "SELECT name, code FROM providers"), titles = await query(pool, "SELECT title FROM trainings"), persons = await query(pool, "SELECT trainee_code AS c FROM trainees LIMIT 50");
  ok("public figures open without signing in", st.status === 200 && st.data.trainees > 0 && st.data.journey.length === 6 && st.data.enrolment.length > 0, st.status);
  ok("public figures name no provider, training or person", !names.some((n) => txt.includes(String(n["name"])) || txt.includes(`"${n["code"]}"`)) && !titles.some((t) => String(t["title"]).length > 25 && txt.includes(String(t["title"]))) && !persons.some((p) => txt.includes(String(p["c"]))) && !/providerId|trainingId|classId|target_trainees/.test(txt), txt.slice(0, 300));
  const groups = [st.data.age, st.data.education, st.data.employment, st.data.regions, st.data.locations, st.data.levels, st.data.fields, st.data.inclusion, st.data.feedback.byCategory].flat() as Any[];
  ok("no public group is smaller than 10", groups.length > 20 && groups.every((g) => g.value >= 10), groups.filter((g) => g.value < 10));
  for (const k of ["age", "education", "employment", "regions", "locations", "levels", "fields"]) ok(`public ${k}: the parts add up to everyone`, (st.data[k] as Any[]).reduce((a: number, g: Any) => a + g.value, 0) === st.data.trainees); }
// 5. A whole provider's life: onboarding, classes, 100 trainees by file, attendance, dropout, completion, every later report.
const now = today(), end = addDays(now, -70), start = addDays(end, -60);
const prov = await call(admin, "POST", "/projects/1/providers", { code: "zqt", name: "Zed Academy", contactName: "A B", contactPhone: "0911223344", notificationEmail: "n@z.test", replyToEmail: "r@z.test", requiresExternalId: false, contract: { number: "C1", signedDate: start, start, end: addDays(now, 200), target: 100, levels: ["basic"], locationCodes: ["AA"] }, targets: { training_completion_rate: 85 }, admin: { name: "Z Admin", email: "za@z.test" }, registrationWindow: { from: start, until: addDays(now, 30) } });
ok("provider onboarding", prov.status === 200 && prov.data.status === "onboarding" && prov.data.maxRegistration >= 100, prov);
const P = prov.data.id, reopen = (until: string) => call(admin, "POST", `/projects/1/providers/${P}/registration-window`, { late: { until, reason: "Test of late registration" } }), zed = await user("tp_admin", P);
ok("activation", (await call(admin, "POST", `/projects/1/providers/${P}/activate`)).data.status === "active");
const tr = await call(zed, "POST", "/projects/1/trainings", { providerId: P, title: "Zed Training", level: "basic", durationMonths: 3, plannedStart: start, plannedEnd: end, weekdays: [1, 2, 3, 4, 5], locationCodes: ["AA"] });
ok("create training", tr.status === 200, tr);
const siteId = (await call(zed, "GET", `/projects/1/trainings/${tr.data.id}`)).data.sites[0].site.id, cl = await call(zed, "POST", `/projects/1/sites/${siteId}/classes`, { code: "Z1", name: "Zed class", weekdays: [1, 2, 3, 4, 5], plannedStart: start, plannedEnd: end }), K = cl.data.id;
ok("create class", cl.status === 200 && cl.data.status === "ended" && cl.data.sessionsTotal > 20, cl);
ok("after 14 days registration is closed for the class", cl.data.registrationOpen === false && cl.data.registrationClosesOn === addDays(start, 14), cl.data);
await reopen(addDays(now, 5));
const born = addDays(start, -365 * 24 - 100), dob = `${born.slice(8)}/${born.slice(5, 7)}/${born.slice(0, 4)}`, formDate = `${start.slice(8)}/${start.slice(5, 7)}/${start.slice(0, 4)}`;
const L = (n: number) => `${String.fromCharCode(65 + (n % 26))}${"bcdfghjklm"[Math.floor(n / 26)]}${"aeiou"[n % 5]}${"rstvw"[(n * 7) % 5]}${"aeiou"[(n * 3) % 5]}`;
const head = "first_name,father_name,grandfather_name,sex,age,date_of_birth,phone,region,woreda,education,employment,class_code,roster_status,form_date,consent_accuracy,consent_contact_verify", line = (n: number) => `${L(n)}x${L(99 - n)},${L((n * 37) % 100)}q${L((n * 11) % 100)},${L((n * 53) % 100)}z,${n % 2 ? "Female" : "Male"},24,${dob},09${String(77000000 + n)},Addis Ababa,05,Diploma,Not currently working,Z1,Active,${formDate},Yes,Yes`;
const importFile = async (rows: string[]) => { const f = new FormData(); f.set("file", new File([[head, ...rows].join("\n")], "t.csv", { type: "text/csv" })); f.set("providerId", P); f.set("trainingId", tr.data.id); f.set("siteId", siteId); f.set("mode", "import"); const x = await call(zed, "POST", "/projects/1/imports", f); await jobs(); return x; };
const bad = await importFile([line(0).replace("0977000000", "9.77E+08"), line(1).replace(formDate, "3/25/2026"), line(2).replace("Z1", "NOPE")]), badRows = (await call(zed, "GET", `/projects/1/imports/${bad.data.batchId}/rows?issue=error`)).data.items as Any[];
ok("import explains each bad cell", badRows.length === 3 && ["PHONE_SCIENTIFIC_NOTATION", "DATE_INVALID", "CLASS_UNKNOWN"].every((k) => JSON.stringify(badRows).includes(k)), badRows);
ok("a file with errors cannot be saved", (await call(zed, "POST", `/projects/1/imports/${bad.data.batchId}/commit`)).data.code === "IMPORT_NOT_READY");
const fix = await call(zed, "PATCH", `/projects/1/imports/${bad.data.batchId}/rows/2`, { phone: "0977000000" });
ok("a cell can be fixed in place", fix.status === 200 && !fix.data.issues.some((i: Any) => i.severity === "error"), fix);
const imp = await importFile(Array.from({ length: 100 }, (_, i) => line(i)));
for (let r = 2; r <= 101; r++) { const row = await one(pool, "SELECT status FROM import_rows WHERE batch_id=? AND row_no=?", [imp.data.batchId, r]); if (row?.["status"] === "duplicate") await call(zed, "POST", `/projects/1/imports/${imp.data.batchId}/rows/${r}/duplicate-decision`, { decision: "not_duplicate", reason: "Different person" }); }
const st = (await call(zed, "GET", `/projects/1/imports/${imp.data.batchId}`)).data;
ok("100 rows are ready", st.status === "ready", st);
await call(zed, "POST", `/projects/1/imports/${imp.data.batchId}/commit`); await jobs();
ok("100 trainees registered", (await one(pool, "SELECT COUNT(*) AS n FROM trainees WHERE provider_id=?", [P]))!["n"] === 100, (await call(zed, "GET", `/projects/1/imports/${imp.data.batchId}`)).data);
ok("IDs run from 1 without gaps", (await one(pool, "SELECT MIN(trainee_code) AS a, MAX(trainee_code) AS b FROM trainees WHERE provider_id=?", [P]))!["b"] === "PBPS-ZQT-000100");
const again = await importFile([line(5)]);
ok("registering the same person again is refused", JSON.stringify((await call(zed, "GET", `/projects/1/imports/${again.data.batchId}/rows`)).data).includes("PHONE_DUPLICATE"));
const form = (n: number, over: Any = {}) => ({ classId: K, formDate, rosterStatus: "reserve", firstName: `Form${"abcdefgh"[n]}`, fatherName: "Testy", grandfatherName: "Person", sex: "female", age: 24, dateOfBirth: born, phone: `09880000${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 });
const one1 = await call(zed, "POST", "/projects/1/trainees", form(0));
ok("register one trainee with the form", one1.status === 200 && one1.data.eligibility === "eligible" && one1.data.consentImage === false, one1);
ok("the form reports every field", (await call(zed, "POST", "/projects/1/trainees", form(1, { phone: "123", age: 60, region: "Mars" }))).data.fieldErrors?.length >= 3);
ok("without the two consents nobody is registered", JSON.stringify((await call(zed, "POST", "/projects/1/trainees", form(1, { consentAccuracy: false }))).data).includes("CONSENT_REFUSED") && JSON.stringify((await call(zed, "POST", "/projects/1/trainees", form(1, { consentVerify: false }))).data).includes("CONSENT_REFUSED"));
ok("outside 18 to 29 is registered and marked not eligible", (await call(zed, "POST", "/projects/1/trainees", form(3, { age: 31, dateOfBirth: addDays(start, -365 * 31 - 100) }))).data.eligibility === "not_eligible");
await execute(pool, "UPDATE trainee_status s JOIN trainees t ON t.id=s.trainee_id SET s.roster_status='withdrawn', t.roster_status='withdrawn' WHERE t.id=(SELECT m FROM (SELECT MAX(id) AS m FROM trainees) x)");
const ver = await call(zed, "PATCH", `/projects/1/trainees/${one1.data.id}`, { woreda: "07", version: one1.data.version }), stale = await call(zed, "PATCH", `/projects/1/trainees/${one1.data.id}`, { woreda: "08", version: one1.data.version });
ok("edit works, a stale edit is refused", ver.status === 200 && ver.data.woreda === "07" && stale.data.code === "CHANGED_BY_OTHERS", stale);
for (const url of [`/projects/1/trainees/${one1.data.id}/withdraw`, "/projects/1/trainees/replacement"]) ok(`${url.split("/").pop()} no longer exists`, (await call(admin, "POST", url, { reason: "other", note: "" })).status === 404);
await execute(pool, "UPDATE trainee_status s JOIN trainees t ON t.id=s.trainee_id SET s.roster_status='withdrawn', t.roster_status='withdrawn' WHERE t.id=?", [one1.data.id]);
const T = (await query(pool, "SELECT id FROM trainees WHERE class_id=? AND roster_status='active' ORDER BY id", [K])).map((t) => String(t["id"])), sheet = (await call(zed, "GET", `/projects/1/classes/${K}/attendance`)).data, marks = (absent: number) => Object.fromEntries(T.map((t, i) => [t, i < absent ? "A" : "P"]));
const d0 = sheet.sessionDates[0], notes = { justification: "Entered late" };
ok("incomplete attendance is refused", (await call(zed, "POST", `/projects/1/classes/${K}/attendance/${d0}`, { marks: { [T[0]!]: "P" }, ...notes })).data.code === "INCOMPLETE");
ok("a holiday or weekend is refused", (await call(zed, "POST", `/projects/1/classes/${K}/attendance/${[0, 1, 2, 3, 4, 5, 6].map((i) => addDays(d0, i)).find((d) => isoWeekday(d) === 6)}`, { marks: marks(0), ...notes })).data.code === "NOT_A_SESSION");
ok("late attendance needs a reason", (await call(zed, "POST", `/projects/1/classes/${K}/attendance/${d0}`, { marks: marks(0) })).status === 422);
const rep0 = await call(zed, "POST", `/projects/1/classes/${K}/outcomes/dropout/submit`, { lines: T.map((t) => ({ traineeId: t, value: "no" })) });
ok("dropout report waits for complete attendance", rep0.data.code === "BLOCKED" && /attendance/i.test(rep0.data.detail), rep0);
for (const d of sheet.sessionDates.slice(0, -1)) { const x = await call(zed, "POST", `/projects/1/classes/${K}/attendance/${d}`, { marks: marks(5), ...notes }); if (x.status !== 200) ok(`attendance ${d}`, false, x); }
ok("excused does not exist any more", (await call(zed, "POST", `/projects/1/classes/${K}/attendance/${d0}`, { marks: { ...marks(0), [T[0]!]: "E" }, ...notes })).status === 422);
const lastD = sheet.sessionDates.at(-1), tplA = String((await call(zed, "GET", `/projects/1/classes/${K}/attendance/template?date=${lastD}`)).data).replace(/^\uFEFF/, "").trim().split("\r\n"), tplB = tplA.map((l, i) => { const c = l.split(","); if (i) c[5] = i <= 5 ? "absent" : "present"; return c.join(","); }), upA = async (rows: string[], date: string) => { const f = new FormData(); f.set("date", date); f.set("file", new File([rows.join("\n")], "a.csv", { type: "text/csv" })); return call(zed, "POST", `/projects/1/classes/${K}/attendance/import`, f); };
ok("the attendance template is V1's, for one day", tplA.length === 101 && tplA[0] === "external_beneficiary_id,trainee_unique_id,trainee_name,roster_role,session_date,status,cohort,delivery_batch" && tplA.slice(1).every((l) => l.split(",")[4] === lastD.split("-").reverse().join("/")), tplA.slice(0, 2));
ok("a template needs a day, and a day of class", (await call(zed, "GET", `/projects/1/classes/${K}/attendance/template`)).status === 422 && /weekend|meet|holiday|not counted/.test((await call(zed, "GET", `/projects/1/classes/${K}/attendance/template?date=${start}`)).data.detail));
const twoDays = await upA(tplB.map((l, i) => (i === 7 ? l.replace(lastD.split("-").reverse().join("/"), d0) : l)), lastD);
ok("a file with a second day is refused and nothing is saved", twoDays.status === 422 && /One file holds one day/.test(JSON.stringify(twoDays.data)) && (await call(zed, "GET", `/projects/1/classes/${K}`)).data.cls.sessionsMissing === 1, twoDays.data);
ok("an empty status is refused", (await upA(tplA, lastD)).status === 422);
await call(admin, "PUT", "/projects/1/settings", { lateApproval: true });
const held = await upA(tplB, lastD);
ok("with the setting on, late attendance waits", held.data.waiting === true && (await call(zed, "GET", `/projects/1/classes/${K}`)).data.cls.sessionsMissing === 1, held.data);
ok("and cannot be sent twice", (await upA(tplB, lastD)).data.code === "ALREADY_REQUESTED");
const lq = ((await call(officer, "GET", "/projects/1/attendance/late-requests")).data as Any[])[0];
ok("a provider cannot approve it", (await call(zed, "POST", `/projects/1/attendance/late-requests/${lq.id}/decision`, { decision: "approve", note: "" })).status === 403 && lq.present === 95 && lq.absent === 5, lq);
ok("M&E approves it and it is recorded", (await call(officer, "POST", `/projects/1/attendance/late-requests/${lq.id}/decision`, { decision: "approve", note: "" })).data.status === "approved");
await call(admin, "PUT", "/projects/1/settings", { lateApproval: false });
ok("attendance is complete", (await call(zed, "GET", `/projects/1/classes/${K}`)).data.cls.sessionsMissing === 0);
ok("a second submission is refused", (await call(zed, "POST", `/projects/1/classes/${K}/attendance/${d0}`, { marks: marks(0), ...notes })).data.code === "ALREADY_SUBMITTED");
const cor = await call(zed, "POST", "/projects/1/attendance/corrections", { classId: K, date: d0, traineeId: T[50], to: "A", reason: "Was not there" });
ok("correction request", cor.status === 200 && cor.data.from === "P", cor);
ok("provider cannot approve its own correction", (await call(zed, "POST", `/projects/1/attendance/corrections/${cor.data.id}/decision`, { decision: "approve", note: "" })).status === 403);
ok("M&E approves it and the mark changes", (await call(officer, "POST", `/projects/1/attendance/corrections/${cor.data.id}/decision`, { decision: "approve", note: "" })).data.status === "approved" && (await one(pool, "SELECT m.status AS s FROM attendance_marks m JOIN attendance_sessions x ON x.id=m.session_id WHERE x.class_id=? AND x.session_date=? AND m.trainee_id=?", [K, d0, T[50]!]))!["s"] === 2);
const dctx = (await call(zed, "GET", `/projects/1/classes/${K}/outcomes/dropout/context`)).data;
ok("dropout lists all 100, five locked by attendance", dctx.lines.length === 100 && dctx.lines.filter((l: Any) => l.locked).length === 5 && dctx.gates.every((g: Any) => g.ok), dctx.gates);
ok("completion waits for dropout", (await call(zed, "POST", `/projects/1/classes/${K}/outcomes/completion/submit`, { lines: T.map((t) => ({ traineeId: t, value: "yes", eventDate: end })) })).data.code === "BLOCKED");
const drop = (n: number) => T.map((t, i) => (i < n ? { traineeId: t, value: "yes", eventDate: end, reason: "health" } : { traineeId: t, value: "no" }));
ok("low attendance cannot be reported as No", JSON.stringify((await call(zed, "POST", `/projects/1/classes/${K}/outcomes/dropout/submit`, { lines: drop(3) })).data).includes("SYSTEM_DROPOUT"));
for (const [d, k] of [["2026-02-30", "DATE_INVALID"], [addDays(now, 5), "DATE_FUTURE"], [addDays(start, -1), "DATE_TOO_EARLY"], [undefined, "DATE_REQUIRED"]] as const) ok(`outcome date ${d}: ${k}`, JSON.stringify((await call(zed, "POST", `/projects/1/classes/${K}/outcomes/dropout/submit`, { lines: drop(10).map((l, i) => (i === 0 ? { ...l, eventDate: d } : l)) })).data).includes(k));
const key = { "idempotency-key": "k1" }, dr = await call(zed, "POST", `/projects/1/classes/${K}/outcomes/dropout/submit`, { lines: drop(10) }, key), dr2 = await call(zed, "POST", `/projects/1/classes/${K}/outcomes/dropout/submit`, { lines: drop(10) }, key);
ok("dropout report accepted; a double click creates one report", dr.status === 200 && dr.data.status === "accepted" && dr.data.yesCount === 10 && dr2.data.id === dr.data.id, dr);
const gapSession = await one(pool, "SELECT id FROM attendance_sessions WHERE class_id=? ORDER BY session_date DESC LIMIT 1", [K]);
const COLS = ["completion_status", "certification_status", "placement_status", "locality_status", "retention_3m_status"], who = async (w: string) => query(pool, `SELECT ${COLS.join(",")}, completion_source FROM trainee_status WHERE class_id=? AND ${w}`, [K]);
const ten = await who("dropout_status='yes'"), ninety = await who("dropout_status='no'");
ok("the 10 dropouts are No for every later indicator", ten.length === 10 && ten.every((s) => COLS.every((k) => s[k] === "no") && s["completion_source"] === "derived_dropout"), ten[0]);
ok("the other 90 are still pending", ninety.length === 90 && ninety.every((s) => COLS.every((k) => s[k] === "pending")));
const cctx = (await call(zed, "GET", `/projects/1/classes/${K}/outcomes/completion/context`)).data;
ok("the completion report asks for exactly the 90", cctx.lines.length === 90, cctx.lines.length);
const ninetyIds: string[] = cctx.lines.map((l: Any) => l.traineeId);
ok("a dropout cannot be added to it", JSON.stringify((await call(zed, "POST", `/projects/1/classes/${K}/outcomes/completion/submit`, { lines: [...ninetyIds, T[0]!].map((t) => ({ traineeId: t, value: "yes", eventDate: end })) })).data).includes("NOT_LISTED"));
const tpl = await call(zed, "GET", `/projects/1/classes/${K}/outcomes/completion/template?format=csv`);
ok("the template keeps V1's columns", tpl.data.startsWith("external_beneficiary_id,trainee_unique_id,trainee_name,outcome_type,reported_value,status_date,completion_date,notes") && tpl.data.trim().split("\n").length === 91, String(tpl.data).slice(0, 200));
const filled = tpl.data.trim().split("\n").map((l: string, i: number) => { if (!i) return l; const c = l.trim().split(","); c[4] = i <= 85 ? "Y" : "N"; c[6] = i <= 85 ? end : ""; return c.join(","); }).join("\n"), pf = new FormData();
pf.set("file", new File([filled], "c.csv", { type: "text/csv" }));
const parsed = await call(zed, "POST", `/projects/1/classes/${K}/outcomes/completion/parse`, pf);
ok("the filled template is read back without loss", parsed.status === 200 && parsed.data.issues.length === 0 && parsed.data.lines.filter((l: Any) => l.value === "yes" && l.eventDate === end).length === 85, parsed.data.issues);
const usf = new FormData(); usf.set("file", new File([filled.replace(end, "8/27/2026")], "c.csv", { type: "text/csv" }));
ok("a month-first date is refused, not guessed", (await call(zed, "POST", `/projects/1/classes/${K}/outcomes/completion/parse`, usf)).data.issues.some((i: Any) => /8\/27\/2026/.test(i.message)));
{ const kept = (await one(pool, "SELECT trainee_id AS t FROM trainee_status WHERE class_id=? AND dropout_status='no' AND roster_status='active' LIMIT 1", [K]))!["t"], set = (v: number) => execute(pool, "UPDATE trainee_status SET system_dropout_final=? WHERE trainee_id=?", [v, kept]);
  await set(1);
  for (const type of ["completion", "certification", "employment_placement", "locality_compliant"]) { const x = await call(zed, "GET", `/projects/1/classes/${K}/outcomes/${type}/context`); ok(`${type}: closed while someone below 80 % is not reported as a dropout`, x.data.gates.some((g: Any) => !g.ok && /below 80/.test(g.label)), x.data.gates); }
  const x = await call(zed, "POST", `/projects/1/classes/${K}/outcomes/completion/submit`, { lines: parsed.data.lines.map((l: Any) => ({ traineeId: l.traineeId, value: "yes", eventDate: end })) });
  ok("someone below 80 % cannot be sent as a completer", x.data.code === "BLOCKED" && /below 80/.test(x.data.detail), x.data);
  await set(0); }
// A sample drawn BEFORE the completion report: what does the report do to it?
const early = await call(admin, "POST", "/projects/1/verification/runs", { indicator: "training_completion_rate", providerId: P, period: "2026-E", seed: "early", preReport: true }), eRun = String(early.data.runId);
const eSub = async () => (await one(pool, "SELECT SUM(v.tp_claim_value=1) AS claimed, SUM(v.status_code='V-NCOMP' AND v.is_auto_dropout=1 AND v.tp_claim_value=0) AS settled, SUM(v.status_code='V-COMP') AS done, SUM(s.dropout_status='yes') AS drops, SUM(s.completion_status='yes') AS comp, SUM(s.completion_status='yes' AND v.tp_claim_value=1 AND v.status_code IS NULL) AS good, SUM(s.completion_status='no' AND s.dropout_status='no' AND v.tp_claim_value=0 AND v.status_code IS NULL) AS failed, COUNT(*) AS n FROM verification_subjects v JOIN trainee_status s ON s.trainee_id=v.trainee_id WHERE v.run_id=?", [eRun]))!;
{ const e = await eSub(); ok("sample before the report: nobody is claimed, dropouts are settled", early.status === 200 && Number(e["claimed"]) === 0 && Number(e["drops"]) > 0 && Number(e["settled"]) === Number(e["drops"]) && Number(e["done"]) === 0, { early: early.data, e }); }
const cLines = parsed.data.lines.map((l: Any) => ({ traineeId: l.traineeId, value: l.value, ...(l.value === "yes" ? { eventDate: l.eventDate } : { reason: "failed_assessment" }) })), cr = await call(zed, "POST", `/projects/1/classes/${K}/outcomes/completion/submit`, { lines: cLines });
const autoC = await query(pool, "SELECT reason_code AS r, COUNT(*) AS n FROM outcome_report_lines WHERE report_id=? AND value='no' GROUP BY reason_code ORDER BY 1", [cr.data.id]);
ok("the completion report also holds the 10 dropouts as No", JSON.stringify(autoC) === JSON.stringify([{ r: "dropout", n: 10 }, { r: "failed_assessment", n: 5 }]), autoC);
ok("completion accepted: 85 yes, 5 no", cr.data.status === "accepted" && cr.data.yesCount === 85 && cr.data.noCount === 5, cr);
{ const e = await eSub(), d = await one(pool, "SELECT COUNT(*) AS n FROM verification_run_dropouts WHERE run_id=?", [eRun]);
  ok("the completion report turns the claim of every completer in the sample to completed", Number(e["comp"]) > 40 && Number(e["claimed"]) === Number(e["comp"]) && Number(e["good"]) === Number(e["comp"]), e);
  ok("and leaves the verified result open until someone is called", Number(e["done"]) === 0, e);
  ok("non-completers stay not claimed, dropouts stay settled", Number(e["failed"]) > 0 && Number(e["settled"]) === Number(e["drops"]) && Number(d!["n"]) === Number(e["drops"]), { e, d });
  await call(officer, "POST", `/projects/1/outcome-reports/${cr.data.id}/return`, { reason: "Check the list" });
  ok("a report taken back takes the claims back", Number((await eSub())["claimed"]) === 0, await eSub());
  const again = await call(zed, "POST", `/projects/1/classes/${K}/outcomes/completion/submit`, { lines: cLines }); ok("sent again, the claims are back", again.data.status === "accepted" && Number((await eSub())["claimed"]) === Number(e["claimed"]), again.data);
  await call(admin, "POST", `/projects/1/verification/runs/${eRun}/cancel`, { reason: "Test only" });
  const late = await call(admin, "POST", "/projects/1/verification/runs", { indicator: "training_completion_rate", providerId: P, period: "2026-L", seed: "late" }), l = await one(pool, "SELECT SUM(v.tp_claim_value <> (s.completion_status='yes')) AS wrong, SUM(s.dropout_status='yes' AND COALESCE(v.status_code,'')<>'V-NCOMP') AS open FROM verification_subjects v JOIN trainee_status s ON s.trainee_id=v.trainee_id WHERE v.run_id=?", [String(late.data.runId)]);
  ok("a sample drawn AFTER the report starts with the same claims", Number(l!["wrong"]) === 0 && Number(l!["open"]) === 0, l);
  for (const r of [String(late.data.runId)]) await call(admin, "POST", `/projects/1/verification/runs/${r}/cancel`, { reason: "Test only" }); }
const five = await who("completion_status='no' AND dropout_status='no'");
ok("the 5 non-completers are No for everything after completion", five.length === 5 && five.every((s) => COLS.every((k) => s[k] === "no")));
{ const m = await query(pool, "SELECT * FROM attendance_marks WHERE session_id=?", [gapSession!["id"]]), s0 = (await one(pool, "SELECT * FROM attendance_sessions WHERE id=?", [gapSession!["id"]]))!;
  await execute(pool, "DELETE FROM attendance_marks WHERE session_id=?", [s0["id"]]); await execute(pool, "DELETE FROM attendance_sessions WHERE id=?", [s0["id"]]);
  await call(admin, "POST", "/projects/1/jobs", { kind: "attendance" }); await jobs();
  for (const [type, stage] of [["dropout", ""], ["completion", ""], ["certification", ""], ["employment_placement", ""], ["locality_compliant", ""]] as const) { const x = await call(zed, "POST", `/projects/1/classes/${K}/outcomes/${type}/submit`, { ...(stage ? { stageKey: stage } : {}), reasonForChange: "x", lines: T.slice(0, 1).map((t) => ({ traineeId: t, value: "no" })) }); ok(`one missing day blocks the ${type} report`, x.data.code === "BLOCKED" && /attendance/i.test(x.data.detail), x.data); }
  const cols = Object.keys(s0); await execute(pool, `INSERT INTO attendance_sessions (${cols.join(",")}) VALUES (${cols.map(() => "?").join(",")})`, cols.map((k) => (typeof s0[k] === "string" && /T.*Z$/.test(s0[k]) ? s0[k].slice(0, 23).replace("T", " ") : s0[k])));
  for (const x of m) { const k = Object.keys(x); await execute(pool, `INSERT INTO attendance_marks (${k.join(",")}) VALUES (${k.map(() => "?").join(",")})`, k.map((y) => (typeof x[y] === "string" && /T.*Z$/.test(x[y]) ? x[y].slice(0, 23).replace("T", " ") : x[y]))); }
  await call(admin, "POST", "/projects/1/jobs", { kind: "attendance" }); await jobs(); }
const SUP = Object.fromEntries(["outreach_referrals", "job_fair", "interview_prep", "cv_writing", "direct_placement", "job_matching", "employer_followup"].map((k) => [`placement_support_${k}`, "yes"]));
const WAGE: Any = { ...SUP, employment_type: "wage_employed", job_title: "IT support officer", employment_start_date: end, monthly_income_etb: "8500", contract_type: "full_time_permanent", employer_name: "ABC, Trading", employer_contact_person: "Abebe K", employer_phone: "0911234567" }, FREE: Any = { ...SUP, employment_type: "self_employed_freelance", employment_start_date: end, monthly_income_etb: "4000", legal_form: "no_legal_form", has_business_license: "no" };
const ctxOf = async (type: string) => (await call(zed, "GET", `/projects/1/classes/${K}/outcomes/${type}/context`)).data, sendTo = (type: string, lines: Any[]) => call(zed, "POST", `/projects/1/classes/${K}/outcomes/${type}/submit`, { lines });
ok("placement waits for certification", (await ctxOf("employment_placement")).gates.some((g: Any) => !g.ok && /Certification/.test(g.label)) && (await sendTo("employment_placement", [{ traineeId: T[50], value: "no", details: SUP }])).data.code === "BLOCKED");
{ const x = await ctxOf("certification"), r = await sendTo("certification", x.lines.map((l: Any, n: number) => ({ traineeId: l.traineeId, value: n < 60 ? "yes" : "no", eventDate: end }))); ok("certification lists 85 and is accepted", x.lines.length === 85 && r.data.status === "accepted", r.data); }
for (const t of ["locality_compliant", "job_retention_3m"]) ok(`${t} waits for placement`, (await ctxOf(t)).gates.some((g: Any) => !g.ok && /Employment placement/.test(g.label)));
for (const t of ["job_linkage", "decent_job"]) ok(`${t} no longer exists`, (await call(zed, "GET", `/projects/1/classes/${K}/outcomes/${t}/context`)).status === 404);
const pc = await ctxOf("employment_placement"), cert = pc.lines.map((l: Any) => String(l.traineeId)) as string[], notCert = T.find((t) => !cert.includes(t))!;
ok("placement lists exactly the 60 certified", cert.length === 60, cert.length);
const prun = async (period: string) => { const r = await call(admin, "POST", "/projects/1/verification/runs", { indicator: "employment_placement_rate", providerId: P, period, seed: period, }); ok("a placement sample is drawn once the report is in", r.status === 200, r); return String(r.data.runId); };
// the template
{ const csv = String((await call(zed, "GET", `/projects/1/classes/${K}/outcomes/employment_placement/template?format=csv`)).data).replace(/^﻿/, ""), rows = csv.trim().split("\n"), head = rows[0]!.trim().split(",");
  ok("the template has the 29 columns and only the certified trainees", head.length === 29 && head[4] === "reported_value" && head[13] === "employment_type" && head[15] === "job_title" && head[28] === "notes" && rows.length === 61 && rows.slice(1).every((r) => r.split(",")[3] === "employment_placement" && r.split(",")[1] !== ""), head);
  const fill = (over: (n: number) => Record<string, string>) => [rows[0], ...rows.slice(1).map((r, n) => { const base = r.trim().split(","), v: Record<string, string> = { ...Object.fromEntries(head.map((h, k) => [h, base[k] ?? ""])), ...over(n) }; return head.map((h) => (/[",]/.test(v[h] ?? "") ? `"${v[h]}"` : v[h] ?? "")).join(","); })].join("\n");
  const good = (n: number) => (n < 30 ? { reported_value: "Yes", ...WAGE } : n < 40 ? { reported_value: "1", ...FREE } : { reported_value: "No", ...SUP });
  const up = async (body: string, url = `/projects/1/classes/${K}/outcomes/employment_placement/parse`) => { const fd = new FormData(); fd.set("file", new File([body], "p.csv", { type: "text/csv" })); return call(zed, "POST", url, fd); };
  const one2 = async (o: Record<string, string>) => ((await up(fill((n) => (n === 0 ? { ...good(0), ...o } : good(n))))).data.issues as Any[]).map((x) => x.message as string);
  const all2 = await up(fill(good)); ok("a complete file has no problems", all2.data.issues.length === 0 && all2.data.lines.length === 60 && all2.data.lines[0].details.employer_name === "ABC, Trading" && all2.data.lines[0].details.employer_phone === "+251911234567", all2.data.issues);
  for (const [o, re] of [[{ job_title: "" }, /Row 2: job_title: is required for wage_employed/], [{ contract_type: "" }, /Row 2: contract_type: is required for wage_employed/], [{ employer_phone: "9.84E+08" }, /Row 2: employer_phone/], [{ has_business_license: "No" }, /Row 2: has_business_license: must be empty/], [{ monthly_income_etb: "8,500" }, /Row 2: monthly_income_etb/], [{ employment_start_date: addDays(now, 3) }, /Row 2: employment_start_date.*future/], [{ employment_start_date: "45200" }, /Row 2: employment_start_date/], [{ reported_value: "No" }, /Row 2: employer_name: must be empty/], [{ placement_support_job_fair: "" }, /Row 2: placement_support_job_fair: Yes or No/], [{ outcome_type: "job_linkage" }, /Row 2: outcome_type must be/]] as [Record<string, string>, RegExp][]) { const m = await one2(o); ok(`file: ${JSON.stringify(o)} is refused with its row`, m.some((x) => re.test(x)), m); }
  const codeNot = (await one(pool, "SELECT trainee_code AS c FROM trainees WHERE id=?", [notCert]))!["c"], alien = await up(`${fill(good)}\n,${codeNot},X,employment_placement,No,,yes,yes,yes,yes,yes,yes,yes,,,,,,,,,,,,,,,,`);
  ok("a trainee who is not certified is refused", alien.data.issues.some((x: Any) => /does not belong/.test(x.message)), alien.data.issues);
  ok("an old job linkage file is refused", (await up("external_beneficiary_id,trainee_unique_id,trainee_name,outcome_type,reported_value,status_date,employer_name\n,X,Y,job_linkage,Y,,")).data.code === "HEADER");
  // the whole location in one file, as V1 does
  const siteId = String((await one(pool, "SELECT site_id AS s FROM training_classes WHERE id=?", [K]))!["s"]), su = `/projects/1/sites/${siteId}/outcomes/employment_placement`, sc = (await call(zed, "GET", `${su}/context`)).data, mine = sc.classes.find((k: Any) => String(k.id) === String(K));
  ok("the location shows every class and what is ready", mine.state === "ready" && mine.lines.length === 60, sc.classes.map((k: Any) => [k.code, k.state]));
  const sx = await call(zed, "GET", `${su}/template?format=csv`); ok("the location's template holds the same trainees", String(sx.data).trim().split("\n").length === 61);
  const sp = await up(fill(good), `${su}/parse`); ok("the location's file is checked per class", sp.data.issues.length === 0 && sp.data.classes.length === 1 && sp.data.classes[0].lines.length === 60, sp.data);
  const sbad = await up(`${fill(good)}\n,NOBODY,X,employment_placement,No,,yes,yes,yes,yes,yes,yes,yes,,,,,,,,,,,,,,,,`, `${su}/parse`); ok("a stranger in the location's file is named with its row", sbad.data.issues.some((x: Any) => /Row 62/.test(x.message)), sbad.data.issues);
  ok("a location of another provider is closed", (await call(await user("tp_admin", pA!), "GET", `${su}/context`)).status === 404);
  ok("wrong answers cannot be sent around the file either", JSON.stringify((await call(zed, "POST", `${su}/submit`, { classes: sp.data.classes.map((k: Any) => ({ id: String(k.id), lines: k.lines.map((l: Any, n: number) => (n ? l : { ...l, details: { ...l.details, contract_type: "" } })) })) })).data).includes("contract_type") && !(await one(pool, "SELECT 1 AS x FROM outcome_reports WHERE class_id=? AND report_type='employment_placement'", [K])));
  const key2 = { "idempotency-key": "site1" }, body2 = { filename: "p.csv", classes: sp.data.classes.map((k: Any) => ({ id: String(k.id), lines: k.lines })) }, s1 = await call(zed, "POST", `${su}/submit`, body2, key2), s2 = await call(zed, "POST", `${su}/submit`, body2, key2);
  ok("the location is submitted: one report per class, a double click makes one", s1.data.accepted === 1 && JSON.stringify(s2.data) === JSON.stringify(s1.data) && Number((await one(pool, "SELECT COUNT(*) AS n FROM outcome_reports WHERE class_id=? AND report_type='employment_placement'", [K]))!["n"]) === 1, s1.data);
  ok("and cannot be sent a second time", (await call(zed, "POST", `${su}/submit`, body2)).data.code === "NOT_READY"); }
{ const dt = await query(pool, "SELECT d.employment_type AS t, COUNT(*) AS n, MIN(d.monthly_income_etb) AS i, MIN(d.employer_phone) AS ph, MIN(d.employer_name) AS e, MIN(d.job_title) AS jt, SUM(d.support_job_fair) AS f, MIN(d.has_business_license) AS lic, MIN(d.legal_form) AS lf FROM outcome_placement_details d JOIN outcome_report_lines l ON l.id=d.line_id JOIN outcome_reports r ON r.id=l.report_id WHERE r.class_id=? AND r.status='accepted' GROUP BY 1 ORDER BY 2 DESC", [K]);
  ok("every answer is stored in its own column", dt.length === 3 && dt[0]!["t"] === "wage_employed" && Number(dt[0]!["n"]) === 30 && dt[0]!["ph"] === "+251911234567" && dt[0]!["e"] === "ABC, Trading" && dt[0]!["jt"] === "IT support officer" && Number(dt[0]!["i"]) === 8500 && dt.some((x) => x["t"] === "self_employed_freelance" && Number(x["n"]) === 10 && x["lf"] === "no_legal_form" && Number(x["lic"]) === 0) && dt.some((x) => x["t"] === null && Number(x["n"]) === 20 && Number(x["f"]) === 20), dt);
  const st = (await one(pool, "SELECT SUM(placement_status='yes') AS y, SUM(placement_status='no' AND placement_source='tp_reported') AS n, SUM(placement_status='no' AND placement_source='derived_certification') AS c, SUM(employment_type='wage_employed' AND job_start_date=?) AS w FROM trainee_status s WHERE class_id=? AND roster_status='active'", [end, K]))!;
  ok("status: 40 placed, 20 not, 30 not certified", Number(st["y"]) === 40 && Number(st["n"]) === 20 && Number(st["c"]) === 30 && Number(st["w"]) === 30, st);
  const pRun = await prun("2026-P"), v = (await one(pool, "SELECT COUNT(*) AS n, SUM(v.tp_claim_value=1) AS y, SUM(v.tp_claim_value=0) AS no, SUM(v.tp_claim_value<>(s.placement_status='yes')) AS wrong FROM verification_subjects v JOIN trainee_status s ON s.trainee_id=v.trainee_id WHERE v.run_id=?", [pRun]))!, outside = Number((await one(pool, "SELECT COUNT(*) AS n FROM verification_frame_members f JOIN trainee_status s ON s.trainee_id=f.trainee_id WHERE f.run_id=? AND s.certification_status<>'yes'", [pRun]))!["n"]);
  ok("the sample holds placed and not placed trainees, all certified, and follows the report", Number(v["y"]) > 0 && Number(v["no"]) > 0 && Number(v["wrong"]) === 0 && outside === 0, { v, outside }); await call(admin, "POST", `/projects/1/verification/runs/${pRun}/cancel`, { reason: "Test only" });
  const rid = String((await one(pool, "SELECT id FROM outcome_reports WHERE class_id=? AND report_type='employment_placement' AND status='accepted'", [K]))!["id"]), fv = JSON.stringify((await call(await user("funder_viewer"), "GET", `/projects/1/outcome-reports/${rid}`)).data);
  ok("a funder sees the report without the employers' contacts", fv.includes("wage_employed") && !fv.includes("911234567") && !fv.includes("Abebe K"), fv.slice(0, 200)); }
for (const t of ["locality_compliant", "job_retention_3m"]) { const x = await ctxOf(t), r = await sendTo(t, x.lines.map((l: Any) => ({ traineeId: l.traineeId, value: "yes", eventDate: end }))); ok(`${t} lists the 40 placed and is accepted`, x.lines.length === 40 && r.data.status === "accepted", { n: x.lines.length, r: r.data }); }
ok("at the end nobody is pending", (await one(pool, `SELECT COUNT(*) AS n FROM trainee_status s JOIN trainees t ON t.id=s.trainee_id WHERE s.class_id=? AND t.roster_status='active' AND (${COLS.map((k) => `${k}='pending'`).join(" OR ")})`, [K]))!["n"] === 0);
ok("the dropout report cannot be taken back under later reports", (await call(officer, "POST", `/projects/1/outcome-reports/${dr.data.id}/return`, { reason: "Check the dates" })).data.code === "LATER_REPORT_EXISTS");
const ret = (await call(officer, "GET", `/projects/1/outcome-reports?type=job_retention_3m&classId=${K}`)).data.items[0], rr = await call(officer, "POST", `/projects/1/outcome-reports/${ret.id}/return`, { reason: "Check the dates" });
ok("returning the last report makes it pending again", rr.data.status === "returned" && (await one(pool, "SELECT COUNT(*) AS n FROM trainee_status WHERE class_id=? AND roster_status='active' AND retention_3m_status='pending'", [K]))!["n"] === 40, rr);
const re = await call(zed, "POST", `/projects/1/classes/${K}/outcomes/certification/submit`, { reasonForChange: "One certificate was late", lines: (await call(zed, "GET", `/projects/1/classes/${K}/outcomes/certification/context`)).data.lines.map((l: Any, i: number) => ({ traineeId: l.traineeId, value: i < 61 ? "yes" : "no", eventDate: end })) });
ok("a corrected report waits for approval and changes nothing yet", re.data.status === "ready" && (await one(pool, "SELECT COUNT(*) AS n FROM trainee_status WHERE class_id=? AND certification_status='yes'", [K]))!["n"] === 60, re);
ok("approval replaces the old version", (await call(officer, "POST", `/projects/1/outcome-reports/${re.data.id}/approve-resubmission`, { decision: "approve", note: "" })).data.status === "accepted" && (await one(pool, "SELECT COUNT(*) AS n FROM trainee_status WHERE class_id=? AND certification_status='yes'", [K]))!["n"] === 61);
await jobs();
const kpi = async (c: string) => (await one(pool, "SELECT numerator AS n, denominator AS d, value AS v, target_value AS t FROM kpi_snapshots WHERE indicator_code=? AND provider_key=? AND layer='monitoring' ORDER BY as_of_date DESC LIMIT 1", [c, P]))!;
ok("KPIs: completion 85 of 100 against the provider's own target", Number((await kpi("training_completion_rate"))["n"]) === 85 && Number((await kpi("training_completion_rate"))["t"]) === 85, await kpi("training_completion_rate"));
ok("KPIs: dropout 10 %", Number((await kpi("trainee_dropout_rate"))["v"]) === 10, await kpi("trainee_dropout_rate"));

{ const marked = (await one(pool, "SELECT SUM(m.status<>2) AS p, COUNT(*) AS n FROM attendance_marks m JOIN attendance_sessions x ON x.id=m.session_id JOIN trainees t ON t.id=m.trainee_id WHERE x.class_id=? AND t.roster_status='active'", [K]))!;
  // [numerator, denominator] worked out by hand from what was entered above.
  const HAND: Record<string, [number, number | null]> = { registered_enrolled_trainees_count: [100, null], eligible_enrolled_trainee_rate: [100, 100], trainee_attendance_rate: [Number(marked["p"]), Number(marked["n"])], trainee_dropout_rate: [10, 100], training_completion_rate: [85, 100], training_certification_rate: [61, 85], employment_placement_rate: [40, 85], locality_compliant_placement_rate: [40, 85], job_retention_3_month_rate: [0, 40], timely_grievance_resolution_rate: [0, 0] };
  for (const [code2, [n, d]] of Object.entries(HAND)) { const k = await kpi(code2); ok(`indicator ${code2} is ${n} of ${d}`, Number(k["n"]) === n && (d === null ? k["d"] === null : Number(k["d"]) === d) && (d === null ? Number(k["v"]) === n : d === 0 ? k["v"] === null : Math.abs(Number(k["v"]) - (n / d) * 100) < 0.006), k); }
  const all = (await call(lead, "GET", "/projects/1/indicators")).data as Any[];
  ok("one employment indicator, none for job linkage or decent job", all.filter((x) => /placement_rate|job_linkage|decent/.test(x.code)).map((x) => x.code).sort().join() === "employment_placement_rate,locality_compliant_placement_rate" && JSON.stringify(all.filter((x) => x.no > 0).map((x) => x.no).sort((a, b) => a - b)) === JSON.stringify([...Array(18)].map((_, k) => k + 1)));
  ok("all 18 official indicators are calculated", all.filter((x) => x.no > 0).length === 18 && all.every((x) => x.current.computedAt), all.length);
  for (const x of all) { const g = (await call(lead, "GET", `/projects/1/indicators/${x.code}`)).data; ok(`${x.code} names its variables`, Boolean(g.indicator.numeratorLabel) && !/unknown|\./.test(g.indicator.numeratorLabel), g.indicator.numeratorLabel); }
  const raw = await query(pool, "SELECT k.indicator_code AS c, SUM(k.value) AS parts, (SELECT x.value FROM kpi_snapshots x WHERE x.indicator_code=k.indicator_code AND x.provider_key=0 AND x.layer='monitoring' AND x.as_of_date=k.as_of_date) AS whole FROM kpi_snapshots k WHERE k.project_id=1 AND k.layer='monitoring' AND k.provider_key<>0 AND k.denominator IS NULL AND k.as_of_date=(SELECT MAX(as_of_date) FROM kpi_snapshots) GROUP BY k.indicator_code, k.as_of_date");
  ok("every counted indicator: the project is the sum of its providers", raw.length >= 9 && raw.every((x) => Number(x["parts"]) === Number(x["whole"])), raw);
  const mets = (await call(lead, "GET", "/projects/1/metrics")).data as Any[];
  ok("the variables of V1 and every activity can be used", mets.length >= 20 && ["trainees.registered", "trainees.eligible", "trainees.dropout_effective_buffered", "trainees.completed_capped", "trainees.certified", "attendance.attended_sessions", "attendance.eligible_sessions", "trainees.placed", "trainees.locality_compliant", "trainees.retained_3m", "grievance.resolved_within_sla", "grievance.total_due", "provider.contract_target"].every((k) => mets.some((m) => m.key === k)) && mets.some((m) => m.key.startsWith("provider.activity_approved:")));
  const mk = (o: Any) => call(lead, "POST", "/projects/1/indicators", { code: "own_linkage", name: "Own linkage rate", unit: "%", level: "trainee", numeratorMetric: "trainees.placed", denominatorMetric: "trainees.registered", direction: "higher_is_better", defaultTarget: 50, ...o });
  ok("an indicator that cannot be calculated is refused", (await mk({ numeratorMetric: "trainees.nonsense" })).status === 422 && (await mk({ denominatorMetric: undefined })).status === 422 && (await mk({ unit: "#" })).status === 422);
  ok("a new indicator is built from two variables", (await mk({})).status === 200); await jobs();
  ok("and is calculated: 40 of 100 registered", Number((await kpi("own_linkage"))["v"]) === 40 && Number((await kpi("own_linkage"))["t"]) === 50, await kpi("own_linkage"));
  const pv = await call(lead, "POST", "/projects/1/indicators/own_linkage/versions", { denominatorMetric: "trainees.certified", changeNote: "Measure against certified trainees" });
  await jobs(); ok("a proposed formula changes nothing before approval", Number((await kpi("own_linkage"))["v"]) === 40 && pv.data.version === 2, pv);
  await call(lead, "POST", "/projects/1/indicators/own_linkage/versions/2/approve"); await jobs();
  ok("after approval the new formula is used: 40 of 61", Number((await kpi("own_linkage"))["v"]) === 65.57, await kpi("own_linkage"));
  ok("a wrong formula cannot be proposed", (await call(lead, "POST", "/projects/1/indicators/own_linkage/versions", { numeratorMetric: "x.y", changeNote: "Try a wrong one" })).status === 422);
  ok("a number from an activity works too", (await mk({ code: "own_inception", name: "Own inception", unit: "#", numeratorMetric: "provider.activity_approved:inception_report", denominatorMetric: undefined, defaultTarget: 1 })).status === 200);
  await call(lead, "DELETE", "/projects/1/indicators/own_linkage"); await call(lead, "DELETE", "/projects/1/indicators/own_inception"); await jobs();
  ok("a retired indicator disappears, its history stays", !((await call(lead, "GET", "/projects/1/indicators")).data as Any[]).some((x) => x.code === "own_linkage") && Boolean(await one(pool, "SELECT 1 AS x FROM indicator_definitions WHERE code='own_linkage'")));
  ok("M&E officers and funders cannot build indicators", (await call(officer, "POST", "/projects/1/indicators", {})).status === 403 && (await call(viewer, "POST", "/projects/1/indicators", {})).status === 403); }

// 6. Schedule, roster, activities, grievances, verification, reports, audit.
const before = (await call(zed, "GET", `/projects/1/classes/${K}`)).data.cls, sh = await call(zed, "POST", `/projects/1/classes/${K}/actual-start`, { date: addDays(start, 1) });
ok("a later actual start moves the end by the same days", sh.data.effectiveEnd === addDays(before.effectiveEnd, 1), sh);
ok("and can be undone", (await call(zed, "POST", `/projects/1/classes/${K}/actual-start`, { date: null })).data.effectiveEnd === before.effectiveEnd);
ok("a class with trainees cannot be removed", (await call(zed, "DELETE", `/projects/1/classes/${K}`)).data.code === "CLASS_IN_USE");
const br = await call(zed, "POST", "/projects/1/breakdowns", { classId: K, start: sheet.sessionDates[3], end: sheet.sessionDates[4], reason: "Power failure" });
ok("breakdown approved removes its sessions", (await call(lead, "POST", `/projects/1/breakdowns/${br.data.id}/decision`, { decision: "approve", note: "" })).data.status === "approved" && (await call(zed, "GET", `/projects/1/classes/${K}`)).data.cls.sessionsTotal === before.sessionsTotal - 2);
await execute(pool, "UPDATE providers SET registration_late_until=? WHERE id=?", [addDays(now, -1), P]);
for (const [what, who2] of [["provider", zed], ["administrator", admin]] as const) {
  ok(`closed window: ${what} cannot add`, (await call(who2, "POST", "/projects/1/trainees", form(2))).data.code === "REGISTRATION_CLOSED");
  ok(`closed window: ${what} cannot edit`, (await call(who2, "PATCH", `/projects/1/trainees/${T[99]}`, { firstName: "Changed" })).data.code === "REGISTRATION_CLOSED");
}
ok("only an administrator may still correct a phone number", (await call(zed, "PATCH", `/projects/1/trainees/${T[99]}`, { phone: "0977123499" })).data.code === "REGISTRATION_CLOSED" && (await call(admin, "PATCH", `/projects/1/trainees/${T[99]}`, { phone: "0977123499" })).status === 200);
const closedImp = await importFile([line(99).replace("0977000099", "0977999999").replace(/^[^,]+/, "Newname")]);
ok("closed window: a file is refused too", JSON.stringify((await call(zed, "GET", `/projects/1/imports/${closedImp.data.batchId}/rows`)).data).includes("REGISTRATION_CLOSED"));
await call(admin, "POST", `/projects/1/providers/${P}/registration-window`, { closed: true, note: "Test" });
ok("gate closed by hand: no training, site or class can change", (await call(zed, "POST", "/projects/1/trainings", { providerId: P, title: "Second", level: "basic", durationMonths: 3, plannedStart: start, plannedEnd: end, weekdays: [1], locationCodes: ["AA"] })).data.code === "REGISTRATION_CLOSED" && (await call(zed, "PATCH", `/projects/1/classes/${K}`, { name: "X" })).data.code === "REGISTRATION_CLOSED");
await call(admin, "POST", `/projects/1/providers/${P}/registration-window`, { closed: false });
const { enqueue: enq } = await import("../src/core/jobs/jobs.js"); await enq(pool, "roster.autoFreeze", {}, { projectId: "1" }); await jobs();
ok("the list of a closed class is kept as a snapshot", Boolean(await one(pool, "SELECT 1 AS x FROM roster_snapshots WHERE class_id=? AND kind='freeze'", [K])));
await call(admin, "POST", "/projects/1/jobs", { kind: "attendance" }); await jobs();
ok("a class without trainees owes no attendance", !(await one(pool, "SELECT 1 AS x FROM class_counters WHERE tracked_trainees=0 AND (sessions_missing>0 OR sessions_to_date>0)")) && Boolean(await one(pool, "SELECT 1 AS x FROM class_counters WHERE sessions_missing>0")));
const { materialize } = await import("../src/modules/activities/index.js"); await materialize(pool, "1");
const ob = (await call(zed, "GET", "/projects/1/obligations?pageSize=200")).data.items as Any[], openOb = ob.find((o) => ["open", "overdue"].includes(o.status));
ok("obligations appear for a new provider", ob.length > 5 && Boolean(openOb), ob.length);
const ext = await call(lead, "POST", `/projects/1/obligations/${openOb.id}/extend`, { closeDate: addDays(now, 10), note: "Agreed by phone" });
ok("extension", ext.data.closeDate === addDays(now, 10) && ext.data.status === "open", ext);
const pdf = (name: string, bytes: string) => { const f = new FormData(); f.set("files", new File([bytes], name)); f.set("checklist", JSON.stringify(Object.fromEntries((ext.data.activity.evidence.checklist as Any[]).map((c) => [c.key, true])))); return f; };
ok("a fake PDF is refused", (await call(zed, "POST", `/projects/1/obligations/${openOb.id}/submissions`, pdf("a.pdf", "not a pdf"))).data.code === "FILE_TYPE");
const subm = await call(zed, "POST", `/projects/1/obligations/${openOb.id}/submissions`, pdf("a.pdf", "%PDF-1.4 x"));
ok("evidence submitted", subm.data.status === "submitted" && subm.data.submissions[0].files.length === 1, subm);
ok("evidence downloads unchanged", (await call(zed, "GET", `/projects/1/obligations/${openOb.id}/files/${subm.data.submissions?.[0]?.files[0]?.id}`)).raw.toString() === "%PDF-1.4 x");
ok("another provider cannot download it", [403, 404].includes((await call(tp, "GET", `/projects/1/obligations/${openOb.id}/files/${subm.data.submissions?.[0]?.files[0]?.id}`)).status));
ok("returned, resubmitted, approved", (await call(officer, "POST", `/projects/1/obligations/${openOb.id}/review`, { decision: "return", items: {}, note: "Sign the last page" })).data.status === "returned" && (await call(zed, "POST", `/projects/1/obligations/${openOb.id}/submissions`, pdf("b.pdf", "%PDF-1.4 y"))).data.submissions[0].version === 2 && (await call(officer, "POST", `/projects/1/obligations/${openOb.id}/review`, { decision: "approve", items: {} })).data.status === "approved");
{ const o2 = ob.filter((o) => ["open", "overdue"].includes(o.status) && o.id !== openOb.id)[0], U = `/projects/1/obligations/${o2.id}`; await call(lead, "POST", `${U}/extend`, { closeDate: addDays(now, 9), note: "Agreed by phone" });
  const send = (...fs: [string, string | Buffer][]) => { const f = new FormData(); for (const [n, b] of fs) f.append("files", new File([b as string], n)); f.set("checklist", JSON.stringify(Object.fromEntries((ext.data.activity.evidence.checklist as Any[]).map((c) => [c.key, true])))); return call(zed, "POST", `${U}/submissions`, f); };
  ok("a program is refused", (await send(["setup.exe", "MZxx"])).data.code === "FILE_TYPE" && (await send(["photo.jpeg.html", "<b>"])).data.code === "FILE_TYPE" && (await send(["renamed.bin", "MZ\u0090"])).data.code === "FILE_TYPE");
  ok("26 files at once are refused", (await send(...Array.from({ length: 26 }, (_, i) => [`${i}.txt`, "x"] as [string, string]))).status === 413);
  const huge = await send(["big.pdf", Buffer.concat([Buffer.from("%PDF"), Buffer.alloc(100 * 1024 * 1024)])]); ok("a file above 100 MB is refused", huge.status === 413 && huge.data.code === "FILE_TOO_LARGE", huge.data);
  const body = Buffer.concat([Buffer.from("PK\x03\x04"), Buffer.alloc(60 * 1024 * 1024, 7)]), am = "ሪፖርት የመጀመሪያ (1).pptx", big = await send([am, body], ["call.mp3", "ID3 sound"], ...Array.from({ length: 23 }, (_, i) => [`${i}.txt`, `n${i}`] as [string, string])), list = (big.data.submissions?.[0]?.files ?? []) as Any[];
  ok("25 files of any type, one of 60 MB, as in V1", list.length === 25 && list.some((x) => x.name === am) && list.some((x) => x.name === "call.mp3"), big.data);
  const got = await call(zed, "GET", `${U}/files/${list.find((x) => x.name === am)?.id}`);
  ok("the 60 MB file comes back byte for byte with its own name", Buffer.compare(got.raw, body) === 0 && String(got.headers["content-disposition"]).includes(`filename*=UTF-8''${encodeURIComponent(am).replace(/[()]/g, (x) => `%${x.charCodeAt(0).toString(16)}`)}`), got.headers);
  const { readdir } = await import("node:fs/promises"); ok("nothing is left behind by refused uploads", (await readdir(`${process.env["STORAGE_DIR"]}/.incoming`)).length === 0);
  const vs = (await one(pool, "SELECT s.id FROM verification_subjects s JOIN verification_runs r ON r.id=s.run_id WHERE r.status='in_field' AND r.project_id=1 LIMIT 1"));
  if (vs) { const ve = (t: string, n: number) => { const f = new FormData(); f.set("evidenceType", t); for (let i = 0; i < n; i++) f.append("files", new File([`ID3 ${i}`], `call ${i}.mp3`)); return call(admin, "POST", `/projects/1/verification/subjects/${vs["id"]}/evidence`, f); };
    const r = await ve("call_recording", 10); ok("10 call recordings with their kind", r.data.items?.length === 10, r.data); ok("the kind is kept", (await call(admin, "GET", `/projects/1/verification/subjects/${vs["id"]}`)).data.evidence.filter((e: Any) => e.type === "call_recording").length === 10);
    ok("an unknown kind and an 11th file are refused", (await ve("x", 1)).status === 422 && (await ve("photo", 11)).status === 413);
    ok("a call recording opens", (await call(admin, "GET", `/projects/1/verification/subjects/${vs["id"]}/evidence/${r.data.items?.[3]?.id}`)).raw.toString() === "ID3 3"); } else console.log("no open sample: verification evidence not tried"); }
await materialize(pool, "1");
ok("recalculating schedules never touches an approved obligation", (await call(zed, "GET", `/projects/1/obligations/${openOb.id}`)).data.status === "approved");
const gr = await call(null, "POST", "/public/projects/1/grievances", { providerId: P, category: "complaint", subject: "Late stipend", description: "It has not arrived.", name: "A B", email: "a@b.test" });
ok("public grievance", /^GRM-\d{4}-\d{6}$/.test(gr.data.ref), gr);
ok("markup is refused", (await call(null, "POST", "/public/projects/1/grievances", { providerId: P, category: "complaint", subject: "<script>x</script>", description: "x", name: "A", email: "a@b.test" })).status === 422);
ok("status needs the right email", (await call(null, "GET", `/public/grievances/status?ref=${gr.data.ref}&email=x@y.z`)).status === 404 && (await call(null, "GET", `/public/grievances/status?ref=${gr.data.ref}&email=a@b.test`)).data.status === "new");
const gid = (await one(pool, "SELECT id FROM grievance_cases WHERE ref=?", [gr.data.ref]))!["id"];
ok("the provider is told", (await call(zed, "GET", "/projects/1/notifications")).data.some((n: Any) => n.type === "grievance.new_case" && n.link));
ok("cannot resolve without a reply", (await call(zed, "POST", `/projects/1/grievances/${gid}/status`, { status: "resolved" })).data.code === "NO_REPLY");
await call(zed, "POST", `/projects/1/grievances/${gid}/messages`, { body: "Internal only", visibility: "internal" });
ok("the answer resolves the case by itself", (await call(zed, "POST", `/projects/1/grievances/${gid}/messages`, { body: "It was paid.", visibility: "public" })).data.status === "resolved");
{ const seen = JSON.stringify([(await call(zed, "GET", `/projects/1/grievances/${gid}`)).data, (await call(zed, "GET", "/projects/1/grievances?pageSize=200")).data]), full = (await call(officer, "GET", `/projects/1/grievances/${gid}`)).data;
  ok("a provider never sees who sent a case", !seen.includes("a@b.test") && !seen.includes("A B") && seen.includes("Confidential"), seen.slice(0, 300));
  ok("M&E does", full.submitterEmail === "a@b.test" && full.submitterName === "A B");
  ok("and a provider cannot search by name", (await call(zed, "GET", "/projects/1/grievances?q=A%20B")).data.total === 0); }
ok("internal notes stay internal", !JSON.stringify((await call(null, "GET", `/public/grievances/status?ref=${gr.data.ref}&email=a@b.test`)).data).includes("Internal only"));
const rt = /token=(\S+)/.exec((await one(pool, "SELECT text_body AS t FROM email_outbox WHERE template_key='grievance.resolved' ORDER BY id DESC LIMIT 1"))!["t"])![1];
ok("satisfaction can be given once", (await call(null, "POST", `/public/grievances/${gr.data.ref}/satisfaction`, { token: rt, score: 5 })).status === 200 && (await call(null, "POST", `/public/grievances/${gr.data.ref}/satisfaction`, { token: rt, score: 1 })).status === 410);
const sup = await user("verification_supervisor"), enu = await user("verification_enumerator"), enuName = (await one(pool, "SELECT u.name AS n FROM user_sessions s JOIN users u ON u.id=s.user_id WHERE s.refresh_token_hash=?", [createHash("sha256").update(enu.token).digest("hex")]))!["n"];
const run = await call(sup, "POST", "/projects/1/verification/runs", { indicator: "training_completion_rate", providerId: P, period: "2026-Q4", seed: "fixed-seed" });
ok("draw a sample", run.status === 200, run);
{ const t = await query(pool, "SELECT COUNT(*) AS n FROM verification_runs WHERE COALESCE(target_used,0)=0"); ok("every sample has a target", Number(t[0]!["n"]) === 0, t);
  const keep = (await one(pool, "SELECT target_used AS t FROM verification_runs WHERE id=?", [run.data.runId]))!["t"]; await execute(pool, "UPDATE verification_runs SET target_used=NULL WHERE id=?", [run.data.runId]);
  const shown = async () => (await call(admin, "GET", `/projects/1/verification/runs/${run.data.runId}`)).data.run.targetUsed as number | undefined;
  const ownT = (await query(pool, "SELECT id FROM indicator_targets WHERE indicator_code='training_completion_rate' AND provider_id=? AND effective_from<=CURRENT_DATE AND (effective_to IS NULL OR effective_to>=CURRENT_DATE)", [P])).length, first = await shown();
  await execute(pool, "INSERT INTO indicator_targets (project_id, indicator_code, provider_id, target_value, comparator, effective_from) VALUES (1,'training_completion_rate',?,83,'>=',CURRENT_DATE)", [P]);
  ok("a provider's own pass mark (83 %) is used, also for an open sample", (await shown()) === 83 && first !== 83, { first, now: await shown(), ownT });
  await execute(pool, "DELETE FROM indicator_targets WHERE provider_id=? AND target_value=83 AND effective_from=CURRENT_DATE", [P]);
  ok("and the general one again without it", (await shown()) === first);
  const hidden = await query(pool, "SELECT id, project_id FROM indicator_targets WHERE indicator_code='training_completion_rate'"), def0 = (await one(pool, "SELECT default_target AS t FROM indicator_definitions WHERE project_id=1 AND code='training_completion_rate' AND status='active'"))!["t"];
  await execute(pool, "UPDATE indicator_targets SET indicator_code='x' WHERE indicator_code='training_completion_rate'"); await execute(pool, "UPDATE indicator_definitions SET default_target=NULL WHERE project_id=1 AND code='training_completion_rate' AND status='active'");
  const f = await call(admin, "POST", `/projects/1/verification/runs/${run.data.runId}/finalize`); ok("a sample without any target is never finished", (f.status === 409 || f.status === 422) && (await shown()) === undefined, f); await execute(pool, "UPDATE indicator_targets SET indicator_code='training_completion_rate' WHERE indicator_code='x'"); await execute(pool, "UPDATE indicator_definitions SET default_target=? WHERE project_id=1 AND code='training_completion_rate' AND status='active'", [def0]); ok("targets restored", hidden.length >= 0 && (await shown()) === first); await execute(pool, "UPDATE verification_runs SET target_used=? WHERE id=?", [keep, run.data.runId]); }
const R = run.data.runId, subs = (await call(sup, "GET", `/projects/1/verification/runs/${R}/subjects`)).data as Any[], prim = subs.filter((s) => s.role === "primary");
ok("reported dropouts are settled without a call", subs.filter((s) => s.status === "V-NCOMP").length > 0 && prim.length > 50, prim.length);
{ // V1's backfill: an open sample follows the reports, and never touches what a person recorded.
  const own = prim.find((s) => s.status === "V-NCOMP"), open = prim.filter((s) => !s.status), id = async (s: Any) => (await one(pool, "SELECT trainee_id AS t FROM verification_subjects WHERE id=?", [s.id]))!["t"], row = (s: Any) => one(pool, "SELECT v.status_code AS c, v.tp_claim_value AS k, v.is_auto_dropout AS a, (SELECT COUNT(*) FROM verification_run_dropouts d WHERE d.run_id=v.run_id AND d.trainee_id=v.trainee_id) AS d FROM verification_subjects v WHERE v.id=?", [s.id]), st = (t: unknown, d: string, k: string) => execute(pool, "UPDATE trainee_status SET dropout_status=?, completion_status=? WHERE trainee_id=?", [d, k, t as string]);
  const a = await id(open[0]), b = await id(own), c3 = await id(open[1]), before = await query(pool, "SELECT trainee_id AS t, dropout_status AS d, completion_status AS k FROM trainee_status WHERE trainee_id IN (?)", [[a, b, c3]]);
  await st(a, "yes", "no"); await st(b, "no", "yes"); await st(c3, "yes", "no");
  await execute(pool, "UPDATE verification_subjects SET status_code='V-COMP', verified_value=1 WHERE id=?", [open[1].id]);
  const u = await call(sup, "POST", `/projects/1/verification/runs/${R}/refresh`), x = await row(open[0]), y = await row(own), z = await row(open[1]);
  ok("update from reports: a new dropout is settled", u.status === 200 && x!["c"] === "V-NCOMP" && x!["a"] === 1 && x!["k"] === 0 && Number(x!["d"]) === 1, { u, x });
  ok("update from reports: a dropout taken back is opened again", y!["c"] === null && y!["k"] === 1 && Number(y!["d"]) === 0, y);
  ok("update from reports: a recorded result stays", z!["c"] === "V-COMP" && z!["k"] === 0, z);
  ok("a provider cannot use it", (await call(zed, "POST", `/projects/1/verification/runs/${R}/refresh`)).status === 403);
  await execute(pool, "UPDATE verification_subjects SET status_code=NULL, verified_value=NULL WHERE id=?", [open[1].id]);
  for (const s of before) await st(s["t"], s["d"], s["k"]);
  await call(sup, "POST", `/projects/1/verification/runs/${R}/refresh`);
  ok("and back again", (await row(open[0]))!["c"] === null && (await row(own))!["c"] === "V-NCOMP"); }
ok("assign", (await call(sup, "POST", `/projects/1/verification/runs/${R}/assign`, { subjectIds: prim.filter((s) => !s.status).map((s) => s.id), enumerator: enuName })).data.assigned === prim.filter((s) => !s.status).length);
const work = (await call(enu, "GET", "/projects/1/verification/my-work")).data as Any[];
ok("the enumerator sees the assigned work", work.length === prim.filter((s) => !s.status).length);
ok("another enumerator does not", (await call(await user("verification_enumerator"), "GET", `/projects/1/verification/subjects/${work[0].id}`)).status === 404);
await call(enu, "POST", `/projects/1/verification/subjects/${work[0].id}/unreachable`, {});
ok("unreachable is one step", (await call(enu, "GET", `/projects/1/verification/subjects/${work[0].id}`)).data.status === "V-UNR");
const rep = await call(sup, "POST", `/projects/1/verification/subjects/${work[0].id}/replace`);
ok("the next reserve of the stratum replaces it", rep.data.role === "replacement" && rep.data.stratum === work[0].stratum, rep);
for (const s of [...work.slice(1), ...(rep.data.status ? [] : [rep.data])]) await call(enu, "POST", `/projects/1/verification/subjects/${s.id}/response`, { answers: { q1: "yes", q2: "correct", q10: "yes", q11: "yes" } });
ok("nobody can finalise before review", (await call(sup, "POST", `/projects/1/verification/runs/${R}/finalize`)).data.code === "NOT_READY");
for (const s of (await call(sup, "GET", `/projects/1/verification/review-queue`)).data as Any[]) if (s.runId === R || s.runId === String(R)) await call(sup, "POST", `/projects/1/verification/subjects/${s.id}/review`, { decision: "approve" });
const fin = await call(sup, "POST", `/projects/1/verification/runs/${R}/finalize`);
ok("finalise with a result", fin.data.status === "finalised" && fin.data.result.rate > 50 && fin.data.result.target === 85, fin);
ok("a finished run is locked", (await call(enu, "POST", `/projects/1/verification/subjects/${work[1].id}/response`, { answers: { q1: "no" } })).status >= 400);
{ const pv = async (i: string) => (await call(sup, "GET", `/projects/1/verification/sample-preview?indicator=${i}&providerId=${P}`)).data.population; const a = [await pv("training_completion_rate"), await pv("training_certification_rate"), await pv("employment_placement_rate"), await pv("job_retention_3_month_rate")];
  ok("each indicator samples the people who passed the report before it", a[0] === 100 && a[1] === 85 && a[2] === 61 && a[3] === 40, a);
  ok("no indicator has 30 or 60 day stages", ((await call(sup, "GET", "/projects/1/verification/stages")).data as Any[]).length === 0); const pl = await call(sup, "POST", "/projects/1/verification/plans", { indicatorCode: "employment_placement_rate", tiering: "single" }); ok("one or two tiers is chosen per indicator", pl.data.tiering === "single" && pl.data.populationMetric === "trainees.base", pl); }
for (const g of ["indicators", "indicators/training_completion_rate", "kpis/report", "kpis/trend", "kpis/status", "metrics", "targets", "targets/template", "dashboard/programme", "verification/results", "verification/runs", "verification/plans", "verification/my-work", "verification/review-queue", "audit/events", "backups", "duplicates"]) for (const [name, w0] of [["admin", zed], ["site lead", lim], ["viewer", await user("tp_viewer", pA!)]] as const) ok(`provider ${name} cannot open ${g}`, (await call(w0, "GET", `/projects/1/${g}`)).status === 403, g);
for (const k of ["indicators_summary", "claimed_verified", "executive_pack", "verification_summary", "verification_run", "possible_duplicates"]) ok(`provider cannot export ${k}`, (await call(zed, "POST", `/projects/1/reports/${k}`, { format: "pdf" })).status === 403 && (await call(zed, "GET", "/projects/1/reports/catalogue")).data.every((x: Any) => x.key !== k), k);
ok("a provider's profile holds no indicators or targets", (await call(zed, "GET", `/projects/1/providers/${P}`)).data.kpis.length === 0 && (await call(zed, "GET", `/projects/1/providers/${P}`)).data.targets.length === 0);
for (const role of ["funder_viewer", "edi_viewer"]) { const v = await user(role); for (const [m, u, b] of [["POST", "trainees", {}], ["POST", `providers/${P}`, { name: "Changed" }], ["POST", `classes/${K}/outcomes/completion/submit`, {}], ["POST", `classes/${K}/attendance/${d0}`, {}], ["PUT", "settings", {}]] as const) ok(`${role} cannot change ${u}`, (await call(v, m, `/projects/1/${u}`, b)).status === 403); }
// A second project is a separate world.
{ const np = await call(admin, "POST", "/projects", { code: "SECOND", title: "Second project", donor: "D", location: "Adama", start: now, end: addDays(now, 300), copyFrom: "1" }), p2 = np.data.id;
  ok("an administrator creates a project", np.status === 200 && Boolean(p2), np);
  ok("nobody else can", (await call(lead, "POST", "/projects", { code: "THIRD", title: "Third", start: now, end: addDays(now, 9) })).status === 403 && (await call(zed, "POST", "/projects", { code: "THIRD", title: "Third", start: now, end: addDays(now, 9) })).status === 403);
  ok("the same code is refused", (await call(admin, "POST", "/projects", { code: "SECOND", title: "Again", start: now, end: addDays(now, 9) })).status === 422);
  ok("it is listed for its administrator only", (await call(admin, "GET", "/projects")).data.length === 2 && (await call(lead, "GET", "/projects")).data.length === 1);
  await jobs();
  const n2 = async (t: string) => (await one(pool, `SELECT COUNT(*) AS n FROM ${t} WHERE project_id=?`, [p2]))!["n"];
  ok("set-up is copied, people and results are not", (await n2("indicator_definitions")) === 18 && (await n2("activity_definitions")) > 0 && (await n2("holidays")) > 0 && (await n2("trainees")) === 0 && (await n2("providers")) === 0, [await n2("indicator_definitions"), await n2("activity_definitions"), await n2("holidays")]);
  for (const r of routes.filter((x) => x.method === "GET" && x.url.startsWith(`${B}/projects/:p/`) && !/:file|files\/:id|jobs\/:id|imports\/:id|late-requests/.test(x.url))) {
    const one3 = /:id|:siteId/.test(r.url), path = r.url.slice(B.length).replace(":p", String(p2)).replace(":id", idFor(r.url)).replace(":code", "training_completion_rate").replace(":type", "completion") + (r.url.includes("sample-preview") ? `?indicator=training_completion_rate&providerId=${ids.prov}` : r.url.includes("schedules/preview") ? `?providerId=${ids.prov}` : r.url.includes("template") ? `?date=${d0}&classId=${K}` : ""), x = await call(admin, "GET", path), t = JSON.stringify(x.data ?? "");
    ok(`project 2 never shows project 1: ${path}`, x.status < 500 && !/PBPS-(IBT|AAU|SCV|DAB|MC)-\d|"(IBT|AAU|SCV|DAB)"/.test(t) && (!one3 || x.status === 404 || x.status === 422 || /indicators|stages/.test(path)), `${x.status} ${t.slice(0, 300)}`);
  }
  ok("someone of project 1 cannot enter project 2", (await call(lead, "GET", `/projects/${p2}/trainees`)).status === 403 && (await call(zed, "GET", `/projects/${p2}/trainees`)).status === 403); }
for (const k of ((await call(admin, "GET", "/projects/1/reports/catalogue")).data as Any[])) for (const format of k.formats) { const j = await call(admin, "POST", `/projects/1/reports/${k.key}`, { format, providerId: P, traineeId: T[0], runId: R, classId: K }); await jobs(); const d = (await call(admin, "GET", `/projects/1/jobs/${j.data.jobId}`)).data, f = d.result?.href ? await call(admin, "GET", d.result.href) : null, sig = f?.raw.subarray(0, 4).toString("latin1"); ok(`report ${k.key}.${format}`, d.status === "done" && (format === "pdf" ? sig === "%PDF" : format === "csv" ? f!.raw.length > 10 : sig!.startsWith("PK")), d); }
ok("a generated file is private", (await call(lead, "GET", `/projects/1/files/${(await one(pool, "SELECT MAX(id) AS id FROM files WHERE purpose='report'"))!["id"]}`)).status === 404);
const { reminders } = await import("../src/modules/notifications/index.js"), n1 = await reminders("1"), n2 = await reminders("1");
ok("reminders are never sent twice", n1 >= 0 && n2 === 0, { n1, n2 });
{ const roles = async () => (await call(admin, "GET", "/roles")).data as Any[], tpv = (await roles()).find((r) => r.code === "tp_viewer"), save = (k: string[], w = admin) => call(w, "PUT", "/roles/tp_viewer/permissions", { permissions: k });
  const viewer2 = await user("tp_viewer", P);
  ok("a system role shows its defaults and its members", Array.isArray(tpv.defaults) && tpv.defaults.includes("report.view") && typeof tpv.members === "number");
  ok("permissions have plain names", ((await call(admin, "GET", "/permissions")).data as Any[]).find((p) => p.key === "trainee.view_pii")?.label === "See names and phone numbers");
  ok("the reports page opens for a provider viewer", (await call(viewer2, "GET", "/projects/1/reports/catalogue")).status === 200);
  ok("a provider role can be changed", (await save(tpv.permissions.filter((k: string) => k !== "report.view"))).status === 200);
  ok("and the provider viewer loses that access at once", (await call(viewer2, "GET", "/projects/1/reports/catalogue")).status === 403);
  ok("a provider role cannot get indicators, verification or audit", (await save([...tpv.permissions, "indicator.view"])).status === 422 && (await save([...tpv.permissions, "verification.view_subjects"])).status === 422 && (await save([...tpv.permissions, "audit.view"])).status === 422);
  ok("a role cannot be left empty, and the administrator role cannot change", (await save([])).status === 422 && (await call(admin, "PUT", "/roles/system_admin/permissions", { permissions: ["project.view"] })).status === 409);
  ok("only role managers change roles", (await save(tpv.defaults, lead)).status === 403 && (await save(tpv.defaults, zed)).status === 403);
  ok("back to default", (await save(tpv.defaults)).status === 200 && (await call(viewer2, "GET", "/projects/1/reports/catalogue")).status === 200);
  ok("the change is in the audit log", Boolean(await one(pool, "SELECT 1 AS x FROM audit_events WHERE action='role_permissions' AND entity_id='tp_viewer'")));
  const e = { notificationEmail: "own@provider.test", replyToEmail: "reply@provider.test" };
  ok("a provider admin changes its own email addresses", (await call(zed, "POST", `/projects/1/providers/${P}/emails`, e)).status === 200 && (await call(zed, "GET", `/projects/1/providers/${P}`)).data.provider?.notificationEmail === e.notificationEmail);
  ok("but not another provider's, nor anything else", (await call(zed, "POST", `/projects/1/providers/${pA}/emails`, e)).status === 404 && (await call(zed, "POST", `/projects/1/providers/${P}`, { name: "Renamed" })).status === 403 && (await call(viewer2, "POST", `/projects/1/providers/${P}/emails`, e)).status === 403); }
{ const v = (await one(pool, "SELECT s.trainee_id AS t, t.trainee_code AS code, s.run_id AS r FROM verification_subjects s JOIN trainees t ON t.id=s.trainee_id JOIN verification_runs r ON r.id=s.run_id WHERE r.project_id=1 AND EXISTS (SELECT 1 FROM outcome_report_lines l WHERE l.trainee_id=s.trainee_id) AND EXISTS (SELECT 1 FROM attendance_marks m WHERE m.trainee_id=s.trainee_id) LIMIT 1"))!, T = String(v["t"]), U = `/projects/1/trainees/${T}`;
  const before = await one(pool, "SELECT (SELECT COUNT(*) FROM attendance_marks WHERE trainee_id=?) AS marks, (SELECT COUNT(*) FROM outcome_report_lines WHERE trainee_id=?) AS ln", [T, T]);
  const imp = await call(admin, "GET", `${U}/delete-impact`);
  ok("the delete preview says the trainee is sampled and lists every place", imp.data.sampled === true && imp.data.warnings.length > 0 && ["Attendance", "Outcome reports", "Verification", "Registration"].every((a) => imp.data.items.some((x: Any) => x.area === a)), imp.data);
  ok("only those allowed may delete, and providers never", (await call(lead, "GET", `${U}/delete-impact`)).status === 403 && (await call(tp, "DELETE", U, { reason: "Registered by mistake", confirmCode: v["code"] })).status === 403);
  ok("a wrong code or a short reason is refused", (await call(admin, "DELETE", U, { reason: "Registered by mistake", confirmCode: "X" })).status === 422 && (await call(admin, "DELETE", U, { reason: "oops", confirmCode: v["code"] })).status === 422);
  const reports = (await query(pool, "SELECT DISTINCT report_id AS id FROM outcome_report_lines WHERE trainee_id=?", [T])).map((x) => String(x["id"]));
  const del = await call(admin, "DELETE", U, { reason: "Registered twice by mistake", confirmCode: v["code"] });
  ok("the trainee is deleted", del.status === 200 && (await call(admin, "GET", U)).status === 404, del.data);
  const left = await one(pool, `SELECT (SELECT COUNT(*) FROM attendance_marks WHERE trainee_id=?)+(SELECT COUNT(*) FROM outcome_report_lines WHERE trainee_id=?)+(SELECT COUNT(*) FROM verification_subjects WHERE trainee_id=?)+(SELECT COUNT(*) FROM verification_frame_members WHERE trainee_id=?)+(SELECT COUNT(*) FROM trainee_status WHERE trainee_id=?)+(SELECT COUNT(*) FROM duplicate_candidates WHERE trainee_a_id=? OR trainee_b_id=?) AS n`, [T, T, T, T, T, T, T]);
  ok("nothing of the trainee is left anywhere", Number(left!["n"]) === 0);
  ok("report totals are counted again", !(await one(pool, "SELECT 1 AS x FROM outcome_reports r WHERE r.id IN (?) AND r.rows_total<>(SELECT COUNT(*) FROM outcome_report_lines l WHERE l.report_id=r.id)", [reports])) && !(await one(pool, "SELECT 1 AS x FROM attendance_sessions s WHERE s.marks_count<>(SELECT COUNT(*) FROM attendance_marks m WHERE m.session_id=s.id) AND s.class_id IN (SELECT class_id FROM attendance_sessions)")));
  const ev = await one(pool, "SELECT before_json AS b FROM audit_events WHERE action='trainee_deleted' AND entity_id=?", [T]), copy = JSON.parse(ev?.["b"] ?? "{}");
  ok("a full copy of the deleted data is in the audit log", copy.trainee?.trainee_code === v["code"] && copy.marks?.length === Number(before!["marks"]) && copy.outcomeLines?.length === Number(before!["ln"]) && copy.subjects?.length > 0);
  ok("the audit chain stays intact", (await verifyChain("1")).intact); }
{ const dash = (await call(zed, "GET", `/projects/1/dashboard/provider/${P}`)).data; ok("a provider sees its results for every indicator, never the verified value, and no indicator management", dash.kpis.length === 18 && dash.kpis.every((k: Any) => k.verified === undefined) && (await call(zed, "GET", "/projects/1/indicators")).status === 403, dash.kpis?.length);
  const t = (await call(zed, "GET", `/projects/1/classes/${K}/outcomes/completion/template?format=csv`)).raw.toString(); ok("the completion template has V1's columns, and dates are DD/MM/YYYY", !/reason/.test(t.split("\n")[0]!) && /\d\d\/\d\d\/\d{4}/.test(t) && !/\d{4}-\d\d-\d\d/.test(t), t.slice(0, 300));
  const { checkTrainee } = await import("../src/modules/registration/trainee.rules.js"), { enumLookup } = await import("../src/modules/registration/lookup.js"); const lk = await enumLookup(); for (const w of ["self-employed / running own business", "Self-employed / own business", "Self-employed"]) ok(`employment "${w}" is known`, lk("employment", w) === "self_employed"); void checkTrainee; }
// 12. Backups, demo accounts, target files, assignees.
ok("only people who manage settings see backups", (await call(lead, "GET", "/projects/1/backups")).status === 403 && (await call(admin, "GET", "/projects/1/backups")).status === 200);
ok("demo accounts are off unless switched on", (await call(null, "GET", "/auth/demo")).data.length === 0);
{ const u = (await one(pool, "SELECT u.id FROM users u WHERE u.status='active' LIMIT 1"))!["id"]; ok("demo sign-in is refused when off", (await call(null, "POST", `/auth/demo/${u}`)).status === 404);
  const { env } = await import("../src/config/env.js"); (env as Any).DEMO_LOGIN = "on";
  ok("a real person's account never opens as a demo", (await call(null, "POST", `/auth/demo/${u}`)).status === 404);
  const list = (await call(null, "GET", "/auth/demo")).data as Any[];
  if (list.length) { const x = await call(null, "POST", `/auth/demo/${list[0].id}`); ok("a demo account signs in with cookies that scripts cannot read", x.status === 200 && /pbps_session=[^;]+;.*HttpOnly/i.test(String(x.headers["set-cookie"])), x.data); ok("demo accounts work only on this computer", (await call(null, "GET", "/auth/demo", undefined, { host: "mis.example.org" })).data.length === 0); }
  (env as Any).DEMO_LOGIN = "off"; }
{ const file = (text: string) => { const f = new FormData(); f.set("file", new Blob([text]), "targets.csv"); return f; }, code = (await one(pool, "SELECT code FROM providers ORDER BY id LIMIT 1"))!["code"], rows = () => one(pool, "SELECT COUNT(*) AS n FROM indicator_targets"), before = (await rows())!["n"], H = "indicator_code,provider_code,target,effective_from,note\n";
  const bad = await call(admin, "POST", "/projects/1/targets/import", file(`${H}training_completion_rate,${code},91,,x\ntraining_completion_rate,NOPE,91,,x\ntraining_completion_rate,${code},191,,x\n`));
  ok("a target file with wrong rows saves nothing", bad.status === 422 && bad.data.fieldErrors.length === 2 && (await rows())!["n"] === before, bad.data);
  const good = await call(admin, "POST", "/projects/1/targets/import", file(`${H}training_completion_rate,${code},91.5,,New\n`));
  ok("a correct target file is saved", good.status === 200 && good.data.saved === 1 && Boolean(await one(pool, "SELECT 1 AS x FROM indicator_targets WHERE target_value=91.5")), good.data);
  ok("the same file again changes nothing", (await call(admin, "POST", "/projects/1/targets/import", file(`${H}training_completion_rate,${code},91.5,,New\n`))).data.saved === 0);
  ok("the target file downloads", (await call(admin, "GET", "/projects/1/targets/template")).raw.subarray(0, 2).toString() === "PK");
  ok("an officer sees who a case can be given to", ((await call(officer, "GET", `/projects/1/grievances/${ids.g}/assignees`)).data as Any[]).length > 0); }
ok("the audit chain is intact", (await call(admin, "POST", "/projects/1/audit/verify", {})).data.intact === true);
await execute(pool, "UPDATE audit_events SET summary='changed' WHERE id=(SELECT * FROM (SELECT MIN(id)+5 FROM audit_events) x)");
ok("and a changed record is detected", (await verifyChain("1")).intact === false);
ok("no password or token is in the audit log", !(await one(pool, "SELECT 1 AS x FROM audit_events WHERE after_json LIKE '%Passw0rd%' OR after_json LIKE '%Correct-horse%' LIMIT 1")));
await app.close();
await pool.end();
console.log(`${pass} checks passed, ${fails.length} failed`);
process.exit(fails.length ? 1 : 0);
