loopable / web /src /apps /reports /reportsApi.ts
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
3e19b1e verified
Raw History Blame Contribute Delete
6.04 kB
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<string, string> }
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<string> {
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<Response> {
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<string, unknown>;
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<Report[]> {
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<string, unknown>;
return ["key", "label", "kind"].every(key => typeof field[key] === "string" && !!field[key]);
}
export async function fetchReportSettings(key: string, abort: AbortSignal): Promise<ReportSettingsData> {
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<string, unknown>;
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<string, unknown>;
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<void> {
await request(`/${encodeURIComponent(key)}/settings`, abort, "PUT", { values });
}
export async function startReportBuild(key: string, abort: AbortSignal): Promise<string> {
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<void> {
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<ReportFile> {
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);
}
}