import { API_V1, CREDENTIALS, checkTenant, signal, UNAUTHORIZED_EVENT } from "../../apiContract"; import { refusalMessage } from "../../customer-grid/seam"; export interface Report { key: string; pid: number; name: string; description: string; format: string; } export interface ReportFile { blob: Blob; filename: string } export interface ReportSettingField { key: string; label: string; kind: string } export interface ReportSettingsData { fields: ReportSettingField[]; values: Record } const UNAVAILABLE = "Reports are unavailable. Try again."; class ReportError extends Error {} export function reportErrorMessage(error: unknown): string { return error instanceof ReportError ? error.message : UNAVAILABLE; } async function responseReason(response: Response): Promise { const text = (await response.text()).trim(); if (!text) return UNAVAILABLE; let body: unknown; try { body = JSON.parse(text); } catch { return text; } // A report refusal can be a plain text sentence. if (typeof body === "string") return body; return refusalMessage(body, response.status, UNAVAILABLE); } async function request(path: string, abort: AbortSignal, method = "GET", payload?: { values: ReportSettingsData["values"] }): Promise { const response = await fetch(`${API_V1}/reports${path}`, { method, credentials: CREDENTIALS, cache: "no-store", signal: AbortSignal.any([abort, AbortSignal.timeout(30000)]), ...(payload ? { headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) } : {}), }); if (checkTenant(response)) throw new ReportError("Your workspace changed. Reloading."); if (response.status === 401) signal(UNAUTHORIZED_EVENT); if (!response.ok) throw new ReportError(await responseReason(response)); return response; } function isReport(value: unknown): value is Report { if (!value || typeof value !== "object") return false; const row = value as Record; return Number.isSafeInteger(row.pid) && typeof row.key === "string" && !!row.key && ["name", "description", "format"].every(key => typeof row[key] === "string"); } export async function fetchReports(abort: AbortSignal): Promise { const response = await request("", abort); const body: unknown = await response.json(); if (!Array.isArray(body) || !body.every(isReport) || new Set(body.map(row => row.pid)).size !== body.length || new Set(body.map(row => row.key)).size !== body.length) throw new ReportError(UNAVAILABLE); return body; } function isSettingField(value: unknown): value is ReportSettingField { if (!value || typeof value !== "object") return false; const field = value as Record; return ["key", "label", "kind"].every(key => typeof field[key] === "string" && !!field[key]); } export async function fetchReportSettings(key: string, abort: AbortSignal): Promise { const response = await request(`/${encodeURIComponent(key)}/settings`, abort); const body: unknown = await response.json(); if (!body || typeof body !== "object") throw new ReportError(UNAVAILABLE); const { fields, values } = body as Record; if (!Array.isArray(fields) || !fields.every(isSettingField) || new Set(fields.map(field => field.key)).size !== fields.length || !values || typeof values !== "object" || Array.isArray(values)) throw new ReportError(UNAVAILABLE); const record = values as Record; if (!fields.every(field => Object.hasOwn(record, field.key) && typeof record[field.key] === "string")) { throw new ReportError(UNAVAILABLE); } return { fields, values: Object.fromEntries(fields.map(field => [field.key, record[field.key] as string])) }; } export async function saveReportSettings(key: string, values: ReportSettingsData["values"], abort: AbortSignal): Promise { await request(`/${encodeURIComponent(key)}/settings`, abort, "PUT", { values }); } export async function startReportBuild(key: string, abort: AbortSignal): Promise { const response = await request(`/${encodeURIComponent(key)}/build`, abort, "POST"); const body: unknown = await response.json(); const job = body && typeof body === "object" && "job" in body ? body.job : null; if (response.status !== 202 || typeof job !== "string" || !job) throw new ReportError(UNAVAILABLE); return job; } function filename(response: Response): string { const header = response.headers.get("Content-Disposition") ?? ""; const encoded = /filename\*=UTF-8''([^;]+)/i.exec(header)?.[1]; if (encoded) { try { return decodeURIComponent(encoded.trim()); } catch { throw new ReportError(UNAVAILABLE); } } const name = /filename=(?:"([^"]+)"|([^;]+))/i.exec(header); const value = (name?.[1] ?? name?.[2] ?? "").trim(); if (!value) throw new ReportError(UNAVAILABLE); return value; } function pause(abort: AbortSignal): Promise { return new Promise((resolve, reject) => { abort.throwIfAborted(); const cancel = () => { clearTimeout(timer); reject(abort.reason); }; const timer = setTimeout(() => { abort.removeEventListener("abort", cancel); resolve(); }, 1000); abort.addEventListener("abort", cancel, { once: true }); }); } export async function waitForReportFile(job: string, abort: AbortSignal): Promise { for (;;) { const response = await request(`/jobs/${encodeURIComponent(job)}/file`, abort); if (response.status === 200) return { blob: await response.blob(), filename: filename(response) }; if (response.status !== 202) throw new ReportError(UNAVAILABLE); await pause(abort); } } export function saveReportFile(file: ReportFile): void { const url = URL.createObjectURL(file.blob); const anchor = document.createElement("a"); anchor.href = url; anchor.download = file.filename; document.body.appendChild(anchor); try { anchor.click(); } finally { anchor.remove(); setTimeout(() => URL.revokeObjectURL(url), 0); } }