import type { ReportPdfPayload } from "@/lib/export"; /** What "Summarise this report" sends: the report's figures, never the people in it. */ export type AiReportData = { title: string; subtitle?: string; stats: { label: string; value: string | number }[]; columns: string[]; rows: (string | number)[][]; }; type Table = { columns: string[]; rows: (string | number)[][] }; /** A rand amount or a count from a report cell ("R 1 250.00", 1250, "—"). */ export function amount(v: unknown): number { if (typeof v === "number") return Number.isFinite(v) ? v : 0; const n = Number(String(v ?? "").replace(/[^0-9.-]/g, "")); return Number.isFinite(n) ? n : 0; } const r2 = (n: number) => Math.round(n * 100) / 100; /** * Group a table's rows by some columns and add up others: `count` is how many rows fell in each * group, each `sums` entry the total of that column (or of what `pick` returns per row). */ function group(t: Table, by: string[], sums: { label: string; col?: string; pick?: (row: (string | number)[], c: (name: string) => string | number) => number }[], countLabel: string): Table { const idx = (name: string) => t.columns.indexOf(name); const groups = new Map(); for (const row of t.rows) { const c = (name: string) => row[idx(name)] ?? ""; const key = by.map(b => String(c(b) || "—")); const k = key.join("\u0000"); const g = groups.get(k) ?? { key, count: 0, sums: sums.map(() => 0) }; g.count += 1; sums.forEach((s, i) => { g.sums[i] += s.pick ? s.pick(row, c) : amount(c(s.col!)); }); groups.set(k, g); } return { columns: [...by, countLabel, ...sums.map(s => s.label)], rows: [...groups.values()].map(g => [...g.key, g.count, ...g.sums.map(r2)]), }; } /** The table without the named columns. */ function without(t: Table, drop: string[]): Table { const keep = t.columns.map((c, i) => (drop.includes(c) ? -1 : i)).filter(i => i >= 0); return { columns: keep.map(i => t.columns[i]), rows: t.rows.map(r => keep.map(i => r[i] ?? "")) }; } const yes = (v: unknown) => String(v).toLowerCase() === "yes"; const filled = (v: unknown) => String(v ?? "").trim() !== ""; /** * The report as the AI helper may see it. Reports without people go as they are on screen; the * ones that list people become totals per event (or per option, status, method), with names, * contact details, notes and comments left out, and medical and consent only as counts. The server * refuses a people report that still has a personal column, so a new column here fails safe. * `attendees` is passed in already counted (see ReportsV2), as its on-screen form is a list of names. */ export function aiReportData(reportKey: string, p: ReportPdfPayload | null): AiReportData | null { if (!p?.table) return null; const base = { title: p.title, subtitle: p.subtitle, stats: (p.stats || []).map(s => ({ label: s.label, value: s.value })) }; const t = p.table; const col = (name: string) => t.columns.indexOf(name); switch (reportKey) { case "payments": { const dates = t.rows.map(r => new Date(String(r[col("Date")]))).filter(d => !Number.isNaN(d.getTime())).sort((a, b) => a.getTime() - b.getTime()); const total = t.rows.reduce((s, r) => s + amount(r[col("Amount")]), 0); const g = group(t, ["Event", "Method"], [ { label: "Amount", col: "Amount" }, { label: "Of which donations", pick: (_r, c) => (yes(c("Donation")) ? amount(c("Amount")) : 0) }, ], "Payments"); return { ...base, stats: [ { label: "Payments", value: t.rows.length }, { label: "Total", value: `R ${r2(total).toFixed(2)}` }, ...(dates.length ? [{ label: "First and last payment", value: `${dates[0].toLocaleDateString()} – ${dates[dates.length - 1].toLocaleDateString()}` }] : []), ], ...g, }; } case "revenueDetailed": return { ...base, ...group(t, ["Event", "Status"], [ { label: "Total paid", col: "Total paid" }, { label: "Outstanding", col: "Outstanding" }, { label: "Registrations still owing", pick: (_r, c) => (amount(c("Outstanding")) > 0 ? 1 : 0) }, ], "Registrations"), }; case "masterOrders": { // The person rows only (not the TOTAL, revenue-per-ticket and unassigned-donations rows below them). const people = { columns: t.columns, rows: t.rows.filter(r => filled(r[col("Name")]) || filled(r[col("Email")])) }; const numeric = t.columns.filter(c => !["Event", "Name", "Email"].includes(c)); const donations = p.extraTables?.find(x => x.title === "Donations made"); const dIdx = (name: string) => donations?.columns.indexOf(name) ?? -1; const dSum = (name: string) => r2((donations?.rows || []).reduce((s, r) => s + amount(r[dIdx(name)]), 0)); return { ...base, stats: [ ...base.stats, { label: "Orders still owing", value: people.rows.filter(r => amount(r[col("Outstanding")]) > 0).length }, ...(donations?.rows.length ? [ { label: "Donations made", value: donations.rows.length }, { label: "Donated (used / unused)", value: `R ${dSum("Donated").toFixed(2)} (R ${dSum("Used").toFixed(2)} / R ${dSum("Unused").toFixed(2)})` }, ] : []), ], ...group(people, ["Event"], numeric.map(c => ({ label: c, col: c })), "Orders"), }; } case "cashupAudit": // Who did each cashup and the free-text notes stay behind; the figures go. return { ...base, ...without(t, ["Performed by", "Notes"]) }; case "consentStatus": { const status = (r: (string | number)[]) => String(r[col("Consent")] || ""); const is = (s: string) => (r: (string | number)[]) => (status(r).startsWith(s) ? 1 : 0); return { ...base, ...group(t, ["Event"], [ { label: "Given", pick: r => is("given")(r) }, { label: "Given on an older consent text", pick: r => (status(r).startsWith("given") && status(r).includes("older text") ? 1 : 0) }, { label: "Pending", pick: r => is("pending")(r) }, { label: "Declined", pick: r => is("declined")(r) }, { label: "Missing", pick: r => is("missing")(r) }, ], "Under-18 attendees"), }; } case "medicalList": { const med = (r: (string | number)[]) => String(r[col("Medical")] || ""); const has = (what: string) => (r: (string | number)[]) => (med(r).includes(`${what}:`) ? 1 : 0); const photos = (r: (string | number)[]) => String(r[col("Photos")] || ""); return { ...base, stats: [], ...group(t, ["Event"], [ { label: "With allergies", pick: has("Allergies") }, { label: "On medication", pick: has("Medication") }, { label: "With conditions", pick: has("Conditions") }, { label: "With medical aid", pick: has("Medical aid") }, { label: "With an emergency contact", pick: r => (filled(r[col("Emergency contact")]) ? 1 : 0) }, { label: "Photos allowed", pick: r => (photos(r) === "Yes" ? 1 : 0) }, { label: "Photos not allowed", pick: r => (photos(r) === "No" ? 1 : 0) }, { label: "Medical details deleted after the event", pick: r => (med(r).startsWith("Deleted") ? 1 : 0) }, ], "Attendees"), }; } case "feedbackSummary": // The per-question results only: the comments (with who wrote them) are left out. "Summarise // feedback" on each event reads the comments themselves, without names. return { ...base, columns: t.columns, rows: t.rows.filter(r => filled(r[0]) || !String(r[1] ?? "").trimStart().startsWith("“")) }; default: return { ...base, columns: t.columns, rows: t.rows }; } }