Summarise this report on every report (2.0.1)
The eight reports that list people get the AI summary too, sent as anonymised totals built on the screen (aiReportData.ts): no names, contact details, notes or comments; consent and medical only as counts. The server refuses personal columns on those reports and logs each summary in the access log (ai_report; sensitive for consent and medical). Roadmap §18: 2.0.1, then crosscode.co.za, then 2.1.0 (AI helpers on the Consent log and Access log). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -6,40 +6,33 @@ import { useAuth } from "@/hooks/useAuth";
|
||||
import { useAiStatus } from "@/hooks/useAiStatus";
|
||||
import { runAi } from "@/lib/ai";
|
||||
import type { V2Body, V2Result } from "@/lib/apiV2";
|
||||
import type { ReportPdfPayload } from "@/lib/export";
|
||||
import type { AiReportData } from "./aiReportData";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
import { AiButton, AiNotice } from "@/components/shared/AiButton";
|
||||
|
||||
type Summary = V2Result<"/ai/summarise-report", "post">["data"]["output"];
|
||||
type ReportKey = V2Body<"/ai/summarise-report", "post">["reportKey"];
|
||||
|
||||
/** Reports without people in them: only these are sent to the AI (the server checks too). */
|
||||
export const SUMMARISABLE_REPORTS: readonly string[] = ["seriesComparison", "regTypes", "usage", "revenue", "regStatus", "donations", "funnel", "discounts", "cashup", "financeReport", "profitReport"] satisfies ReportKey[];
|
||||
|
||||
/**
|
||||
* "Summarise this report": a headline, a few insights and anything to act on, from the report as
|
||||
* it is on screen (the same data as Print and Excel). Only on reports without people in them;
|
||||
* hidden on sites without AI.
|
||||
* it is on screen. Reports that list people are sent as anonymised totals (see aiReportData). Hidden
|
||||
* on sites without AI.
|
||||
*/
|
||||
export function AiReportSummary({ reportKey, getPayload }: { reportKey: string; getPayload: () => ReportPdfPayload | null }) {
|
||||
export function AiReportSummary({ reportKey, getPayload }: { reportKey: ReportKey; getPayload: () => AiReportData | null }) {
|
||||
const { token } = useAuth();
|
||||
const status = useAiStatus();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [summary, setSummary] = useState<Summary | null>(null);
|
||||
if (!status?.enabled || !SUMMARISABLE_REPORTS.includes(reportKey)) return null;
|
||||
if (!status?.enabled) return null;
|
||||
|
||||
const run = async () => {
|
||||
const p = getPayload();
|
||||
if (!token || !p?.table) { setError("This report has no figures to summarise yet."); return; }
|
||||
if (!token || !p?.rows.length) { setError("This report has no figures to summarise yet."); return; }
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
setSummary(await runAi<Summary>("summarise_report", {
|
||||
reportKey, title: p.title, subtitle: p.subtitle,
|
||||
stats: (p.stats || []).map(s => ({ label: s.label, value: s.value })),
|
||||
columns: p.table.columns, rows: p.table.rows,
|
||||
}, token));
|
||||
setSummary(await runAi<Summary>("summarise_report", { reportKey, ...p }, token));
|
||||
} catch (e) { setError(errorMessage(e) || "The AI couldn't summarise this report."); }
|
||||
setBusy(false);
|
||||
};
|
||||
|
||||
@@ -10,6 +10,7 @@ import { REPORTS, type ReportKey } from "./ReportCatalog";
|
||||
import ReportsShell from "./ReportsShell";
|
||||
import ReportViewerModal, { ReportActionButton } from "./ReportViewerModal";
|
||||
import { AiReportSummary } from "./AiReportSummary";
|
||||
import { aiReportData, type AiReportData } from "./aiReportData";
|
||||
import { AiFeedbackSummary } from "./AiFeedbackSummary";
|
||||
import { StatTile, StatTileRow } from "./StatTile";
|
||||
import { HorizontalBarChart } from "./charts/HorizontalBarChart";
|
||||
@@ -1387,6 +1388,30 @@ export default function ReportsV2({ backHref }: { backHref?: string } = {}) {
|
||||
return null;
|
||||
};
|
||||
|
||||
/** What "Summarise this report" sends: the figures, never the people (see aiReportData). */
|
||||
const buildAiPayload = (): AiReportData | null => {
|
||||
if (report === "attendees") {
|
||||
// On screen a list of names per option: the AI gets how many people and tickets per option and status.
|
||||
const rows: (string | number)[][] = [];
|
||||
for (const opt of attendeesLayer.options) {
|
||||
const byStatus = new Map<string, { people: number; qty: number }>();
|
||||
for (const u of opt.users) {
|
||||
const g = byStatus.get(u.status) ?? { people: 0, qty: 0 };
|
||||
g.people += 1;
|
||||
g.qty += u.qty || 0;
|
||||
byStatus.set(u.status, g);
|
||||
}
|
||||
for (const [status, g] of byStatus) rows.push([opt.optionName, status, g.people, g.qty]);
|
||||
}
|
||||
return {
|
||||
title: `Attendees: ${attendeesLayer.eventTitle}`, subtitle: `Generated ${new Date().toLocaleString()}${attIncludeCancelled ? " (cancelled included)" : ""}`,
|
||||
stats: [{ label: "People", value: new Set(attendeesLayer.options.flatMap(o => o.users.map(u => u.name))).size }],
|
||||
columns: ["Option", "Status", "People", "Tickets"], rows,
|
||||
};
|
||||
}
|
||||
return aiReportData(report, buildReportPayload());
|
||||
};
|
||||
|
||||
const doExportExcel = async () => {
|
||||
if (!token) { alert('Please login to export Excel'); return; }
|
||||
try {
|
||||
@@ -1568,7 +1593,7 @@ export default function ReportsV2({ backHref }: { backHref?: string } = {}) {
|
||||
{!ready && <div className="text-sm text-gray-400">Loading…</div>}
|
||||
{ready && (
|
||||
<>
|
||||
<AiReportSummary key={report} reportKey={report} getPayload={buildReportPayload} />
|
||||
<AiReportSummary key={report} reportKey={report} getPayload={buildAiPayload} />
|
||||
{report === "payments" && (
|
||||
<div>
|
||||
{paymentRows.length === 0 ? (
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
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<string, { key: (string | number)[]; count: number; sums: number[] }>();
|
||||
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 };
|
||||
}
|
||||
}
|
||||
@@ -68299,7 +68299,7 @@
|
||||
"AI"
|
||||
],
|
||||
"summary": "Summarise a report",
|
||||
"description": "A few plain-language insights on a report as it is on screen. Only reports without people in them: seriesComparison, regTypes, usage, revenue, regStatus, donations, funnel, discounts, cashup, financeReport, profitReport. Goes through the Cross Events Hub, which counts it against the site's monthly AI allowance. Errors carry a `reason`: AI_OFF, AI_HELPER_OFF, AI_CAP_REACHED, AI_DAILY_LIMIT, AI_REFUSED, AI_INCOMPLETE, AI_UNAVAILABLE.\n\n**Who:** Supervisors and admins.",
|
||||
"description": "A few plain-language insights on a report. Reports without people in them (seriesComparison, regTypes, usage, revenue, regStatus, donations, funnel, discounts, cashup, financeReport, profitReport) are sent as they are on screen; reports that list people (payments, attendees, revenueDetailed, masterOrders, cashupAudit, consentStatus, feedbackSummary, medicalList) only as anonymised totals: a column that would carry a person (name, email, notes, …) is refused with `AI_REPORT_HAS_PEOPLE`, and each one is recorded in the access log. Goes through the Cross Events Hub, which counts it against the site's monthly AI allowance. Errors carry a `reason`: AI_OFF, AI_HELPER_OFF, AI_CAP_REACHED, AI_DAILY_LIMIT, AI_REFUSED, AI_INCOMPLETE, AI_UNAVAILABLE.\n\n**Who:** Supervisors and admins.",
|
||||
"operationId": "postAiSummarise-report",
|
||||
"security": [
|
||||
{
|
||||
@@ -68327,7 +68327,15 @@
|
||||
"discounts",
|
||||
"cashup",
|
||||
"financeReport",
|
||||
"profitReport"
|
||||
"profitReport",
|
||||
"payments",
|
||||
"attendees",
|
||||
"revenueDetailed",
|
||||
"masterOrders",
|
||||
"cashupAudit",
|
||||
"consentStatus",
|
||||
"feedbackSummary",
|
||||
"medicalList"
|
||||
]
|
||||
},
|
||||
"title": {
|
||||
|
||||
+2
-2
@@ -7159,7 +7159,7 @@ export interface paths {
|
||||
put?: never;
|
||||
/**
|
||||
* Summarise a report
|
||||
* @description A few plain-language insights on a report as it is on screen. Only reports without people in them: seriesComparison, regTypes, usage, revenue, regStatus, donations, funnel, discounts, cashup, financeReport, profitReport. Goes through the Cross Events Hub, which counts it against the site's monthly AI allowance. Errors carry a `reason`: AI_OFF, AI_HELPER_OFF, AI_CAP_REACHED, AI_DAILY_LIMIT, AI_REFUSED, AI_INCOMPLETE, AI_UNAVAILABLE.
|
||||
* @description A few plain-language insights on a report. Reports without people in them (seriesComparison, regTypes, usage, revenue, regStatus, donations, funnel, discounts, cashup, financeReport, profitReport) are sent as they are on screen; reports that list people (payments, attendees, revenueDetailed, masterOrders, cashupAudit, consentStatus, feedbackSummary, medicalList) only as anonymised totals: a column that would carry a person (name, email, notes, …) is refused with `AI_REPORT_HAS_PEOPLE`, and each one is recorded in the access log. Goes through the Cross Events Hub, which counts it against the site's monthly AI allowance. Errors carry a `reason`: AI_OFF, AI_HELPER_OFF, AI_CAP_REACHED, AI_DAILY_LIMIT, AI_REFUSED, AI_INCOMPLETE, AI_UNAVAILABLE.
|
||||
*
|
||||
* **Who:** Supervisors and admins.
|
||||
*/
|
||||
@@ -37937,7 +37937,7 @@ export interface operations {
|
||||
content: {
|
||||
"application/json": {
|
||||
/** @enum {string} */
|
||||
reportKey: "seriesComparison" | "regTypes" | "usage" | "revenue" | "regStatus" | "donations" | "funnel" | "discounts" | "cashup" | "financeReport" | "profitReport";
|
||||
reportKey: "seriesComparison" | "regTypes" | "usage" | "revenue" | "regStatus" | "donations" | "funnel" | "discounts" | "cashup" | "financeReport" | "profitReport" | "payments" | "attendees" | "revenueDetailed" | "masterOrders" | "cashupAudit" | "consentStatus" | "feedbackSummary" | "medicalList";
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
stats?: {
|
||||
|
||||
Reference in New Issue
Block a user