File size: 6,040 Bytes
3e19b1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
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);
  }
}