@7365admin1/layer-common 4.97.1-staging.687 → 4.97.1-staging.689

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,458 @@
1
+ /**
2
+ * A `Report` (see checklist-report.ts) written out as the two files the owner
3
+ * asked for: an A4 landscape PDF and an Excel workbook. The same content as the
4
+ * mobile apps' files; the writers differ because the web has other tools:
5
+ *
6
+ * - PDF: drawn with jsPDF (already in layer-common, via html2pdf.js) as real
7
+ * text, not a screenshot, so a 92-day detail report of thousands of rows
8
+ * still fits (a screenshot-based PDF runs out of canvas height after a dozen
9
+ * pages). Every page has the brand/title header and "Page X of Y"; a table
10
+ * that carries on repeats its header row; photos are drawn under their row.
11
+ * - Excel: a plain .xlsx built here (zipFiles from vehicle-qr-export.ts), so no
12
+ * new dependency: one "Summary" sheet then one sheet per table, header row
13
+ * bold, frozen and filterable, photos as "Photo 1", "Photo 2" links.
14
+ *
15
+ * Pure (the jsPDF document is handed in), so `node --test` checks the output.
16
+ */
17
+ import { zipFiles } from "../vehicle-qr-export.ts";
18
+ import type { Cell, Report, Section } from "./checklist-report.ts";
19
+ import { EXTRA_STATUS_WORDS, STATUS_WORDS } from "./checklist-report.ts";
20
+
21
+ export type Brand = { name: string; color: string };
22
+
23
+ /** A photo ready for the PDF: a JPEG data URL and its size in pixels. */
24
+ export type PdfImage = { data: string; width: number; height: number };
25
+
26
+ export const XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
27
+
28
+ // ---------------------------------------------------------------------------
29
+ // Excel
30
+ // ---------------------------------------------------------------------------
31
+
32
+ /** Excel sheet names: 31 characters at most and none of : \ / ? * [ ] */
33
+ export function sheetName(name: string): string {
34
+ return name.replace(/[:\\/?*[\]]/g, " ").trim().slice(0, 31) || "Sheet";
35
+ }
36
+
37
+ /** 0 -> A, 25 -> Z, 26 -> AA. */
38
+ export function columnName(index: number): string {
39
+ let n = index + 1;
40
+ let out = "";
41
+ while (n > 0) {
42
+ const r = (n - 1) % 26;
43
+ out = String.fromCharCode(65 + r) + out;
44
+ n = Math.floor((n - 1) / 26);
45
+ }
46
+ return out;
47
+ }
48
+
49
+ const xml = (value: unknown): string =>
50
+ String(value ?? "")
51
+ // Characters XML 1.0 cannot carry at all.
52
+ .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, "")
53
+ .replace(/&/g, "&")
54
+ .replace(/</g, "&lt;")
55
+ .replace(/>/g, "&gt;")
56
+ .replace(/"/g, "&quot;");
57
+
58
+ type XCell = Cell | { link: string; text: string } | null;
59
+
60
+ /** Style ids in styles.xml below: 0 plain, 1 bold, 2 link (blue, underlined). */
61
+ function cellXml(cell: XCell, ref: string, bold: boolean): string {
62
+ if (cell === null || cell === "") return "";
63
+ if (typeof cell === "number") return `<c r="${ref}"${bold ? ' s="1"' : ""}><v>${cell}</v></c>`;
64
+ if (typeof cell === "object") {
65
+ const f = `HYPERLINK("${cell.link.replace(/"/g, '""')}","${cell.text.replace(/"/g, '""')}")`;
66
+ return `<c r="${ref}" s="2" t="str"><f>${xml(f)}</f><v>${xml(cell.text)}</v></c>`;
67
+ }
68
+ return `<c r="${ref}"${bold ? ' s="1"' : ""} t="inlineStr"><is><t xml:space="preserve">${xml(cell)}</t></is></c>`;
69
+ }
70
+
71
+ type Sheet = { name: string; rows: XCell[][]; widths: number[]; header: boolean; boldRows: number[] };
72
+
73
+ function sheetXml(sheet: Sheet): string {
74
+ const rows = sheet.rows
75
+ .map((row, r) => {
76
+ const bold = (sheet.header && r === 0) || sheet.boldRows.includes(r);
77
+ return `<row r="${r + 1}">${row.map((cell, c) => cellXml(cell, `${columnName(c)}${r + 1}`, bold)).join("")}</row>`;
78
+ })
79
+ .join("");
80
+ const cols = sheet.widths.map((w, i) => `<col min="${i + 1}" max="${i + 1}" width="${w}" customWidth="1"/>`).join("");
81
+ const width = Math.max(1, ...sheet.rows.map((row) => row.length));
82
+ const filter = sheet.header && sheet.rows.length > 1 ? `<autoFilter ref="A1:${columnName(width - 1)}${sheet.rows.length}"/>` : "";
83
+ const pane = sheet.header
84
+ ? '<sheetViews><sheetView workbookViewId="0"><pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/></sheetView></sheetViews>'
85
+ : '<sheetViews><sheetView workbookViewId="0"/></sheetViews>';
86
+ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
87
+ <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">${pane}<cols>${cols}</cols><sheetData>${rows}</sheetData>${filter}</worksheet>`;
88
+ }
89
+
90
+ const STYLES = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
91
+ <styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
92
+ <fonts count="3"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></font><font><u/><sz val="11"/><color rgb="FF0563C1"/><name val="Calibri"/></font></fonts>
93
+ <fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>
94
+ <borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>
95
+ <cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>
96
+ <cellXfs count="3"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/><xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/><xf numFmtId="0" fontId="2" fillId="0" borderId="0" xfId="0" applyFont="1"/></cellXfs>
97
+ <cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>
98
+ </styleSheet>`;
99
+
100
+ /** The sheets of a report: "Summary", then one per table (photos as link columns). */
101
+ export function reportSheets(report: Report, brand: Brand, photoUrl: (id: string) => string): Sheet[] {
102
+ const summaryRows: XCell[][] = [
103
+ [`${brand.name} - ${report.title}`],
104
+ [],
105
+ ...report.meta,
106
+ [],
107
+ ["Summary"],
108
+ [report.sentence],
109
+ [],
110
+ ...report.figures,
111
+ ];
112
+ const sheets: Sheet[] = [
113
+ { name: "Summary", rows: summaryRows, widths: [30, 70], header: false, boldRows: [0, report.meta.length + 3] },
114
+ ];
115
+
116
+ for (const section of report.sections) {
117
+ const most = Math.max(0, ...(section.photos ?? []).map((list) => list.length));
118
+ const columns = [...section.columns, ...Array.from({ length: most }, (_, i) => `Photo ${i + 1}`)];
119
+ const body: XCell[][] =
120
+ section.rows.length === 0
121
+ ? [[section.emptyNote]]
122
+ : section.rows.map((row, r) => [
123
+ ...row,
124
+ ...(section.photos?.[r] ?? []).map((id, i) => ({ link: photoUrl(id), text: `Photo ${i + 1}` })),
125
+ ]);
126
+ const totalRow = section.rows.findIndex((row) => String(row[0]) === "Total");
127
+ sheets.push({
128
+ name: sheetName(section.name),
129
+ rows: [columns, ...body],
130
+ widths: [...section.widths, ...Array.from({ length: most }, () => 10)],
131
+ header: section.rows.length > 0,
132
+ boldRows: totalRow >= 0 ? [totalRow + 1] : [],
133
+ });
134
+ }
135
+ return sheets;
136
+ }
137
+
138
+ /** The .xlsx file's bytes. */
139
+ export function reportToXlsx(report: Report, brand: Brand, photoUrl: (id: string) => string): Uint8Array {
140
+ const sheets = reportSheets(report, brand, photoUrl);
141
+ const enc = new TextEncoder();
142
+ const names = new Set<string>();
143
+ const unique = sheets.map((s) => {
144
+ let name = s.name;
145
+ for (let n = 2; names.has(name.toLowerCase()); n += 1) name = `${s.name.slice(0, 28)} ${n}`;
146
+ names.add(name.toLowerCase());
147
+ return name;
148
+ });
149
+ const filters = sheets
150
+ .map((s, i) => {
151
+ const width = Math.max(1, ...s.rows.map((row) => row.length));
152
+ return s.header && s.rows.length > 1
153
+ ? `<definedName name="_xlnm._FilterDatabase" localSheetId="${i}" hidden="1">'${xml(unique[i].replace(/'/g, "''"))}'!$A$1:$${columnName(width - 1)}$${s.rows.length}</definedName>`
154
+ : "";
155
+ })
156
+ .join("");
157
+
158
+ const files = [
159
+ {
160
+ name: "[Content_Types].xml",
161
+ text: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
162
+ <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>${sheets
163
+ .map((_, i) => `<Override PartName="/xl/worksheets/sheet${i + 1}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`)
164
+ .join("")}</Types>`,
165
+ },
166
+ {
167
+ name: "_rels/.rels",
168
+ text: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
169
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>`,
170
+ },
171
+ {
172
+ name: "xl/workbook.xml",
173
+ text: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
174
+ <workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets>${unique
175
+ .map((name, i) => `<sheet name="${xml(name)}" sheetId="${i + 1}" r:id="rId${i + 1}"/>`)
176
+ .join("")}</sheets>${filters ? `<definedNames>${filters}</definedNames>` : ""}</workbook>`,
177
+ },
178
+ {
179
+ name: "xl/_rels/workbook.xml.rels",
180
+ text: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
181
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${sheets
182
+ .map((_, i) => `<Relationship Id="rId${i + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet${i + 1}.xml"/>`)
183
+ .join("")}<Relationship Id="rId${sheets.length + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>`,
184
+ },
185
+ { name: "xl/styles.xml", text: STYLES },
186
+ ...sheets.map((s, i) => ({ name: `xl/worksheets/sheet${i + 1}.xml`, text: sheetXml(s) })),
187
+ ];
188
+ return zipFiles(files.map((f) => ({ name: f.name, data: enc.encode(f.text) })));
189
+ }
190
+
191
+ // ---------------------------------------------------------------------------
192
+ // PDF
193
+ // ---------------------------------------------------------------------------
194
+
195
+ /** The jsPDF calls used here (jsPDF itself in the app, the real jsPDF in the test). */
196
+ export type PdfDoc = {
197
+ addPage: () => unknown;
198
+ setPage: (n: number) => unknown;
199
+ getNumberOfPages: () => number;
200
+ setFont: (name: string, style: string) => unknown;
201
+ setFontSize: (size: number) => unknown;
202
+ setTextColor: (r: number, g: number, b: number) => unknown;
203
+ setDrawColor: (r: number, g: number, b: number) => unknown;
204
+ setFillColor: (r: number, g: number, b: number) => unknown;
205
+ setLineWidth: (w: number) => unknown;
206
+ line: (x1: number, y1: number, x2: number, y2: number) => unknown;
207
+ rect: (x: number, y: number, w: number, h: number, style?: string) => unknown;
208
+ text: (text: string | string[], x: number, y: number, options?: Record<string, unknown>) => unknown;
209
+ splitTextToSize: (text: string, width: number) => string[];
210
+ addImage: (data: string, format: string, x: number, y: number, w: number, h: number) => unknown;
211
+ link: (x: number, y: number, w: number, h: number, options: { url: string }) => unknown;
212
+ };
213
+
214
+ /** A4 landscape, in mm. */
215
+ export const PDF_PAGE = { width: 297, height: 210 };
216
+ const M = 12; // page margin
217
+ const TOP = M + 12; // first line of content under the header
218
+ const BOTTOM = PDF_PAGE.height - M - 8; // last line of content over the footer
219
+ const CONTENT_W = PDF_PAGE.width - 2 * M;
220
+ const FONT = 8.5;
221
+ const LINE = 3.8; // mm per line at FONT
222
+ const CELL_PAD = 1.6;
223
+ const HEAD_H = 7.5;
224
+ const PHOTO_W = 44;
225
+ const PHOTO_H = 33;
226
+ const PHOTO_GAP = 3;
227
+ /** Photos drawn under one row; any more are in the Excel file (one link each). */
228
+ export const MAX_PHOTOS_PER_ROW = 12;
229
+ /** A longer cell is cut in the PDF (the Excel file keeps all of it). */
230
+ const MAX_CELL = 240;
231
+
232
+ const INK: [number, number, number] = [27, 31, 36];
233
+ const MUTED: [number, number, number] = [91, 101, 115];
234
+ const RULE: [number, number, number] = [201, 209, 220];
235
+ const ALT: [number, number, number] = [244, 246, 250];
236
+
237
+ const STATUS_COLOR: Record<string, [number, number, number]> = {
238
+ [STATUS_WORDS.done]: [22, 101, 52],
239
+ [STATUS_WORDS.attention]: [185, 28, 28],
240
+ [STATUS_WORDS.pending]: [146, 64, 14],
241
+ [EXTRA_STATUS_WORDS.doneAttention]: [185, 28, 28],
242
+ [EXTRA_STATUS_WORDS.missed]: [185, 28, 28],
243
+ [EXTRA_STATUS_WORDS.pending]: [146, 64, 14],
244
+ };
245
+
246
+ /** "#E0241C" -> [224, 36, 28]; anything else -> the default red. */
247
+ export function hexColor(hex: string): [number, number, number] {
248
+ const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());
249
+ if (!m) return [224, 36, 28];
250
+ const n = parseInt(m[1], 16);
251
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
252
+ }
253
+
254
+ const clip = (value: Cell): string => {
255
+ // ponytail: jsPDF's built-in Helvetica has Latin letters only, so a name typed in
256
+ // Chinese or Tamil prints garbled in the PDF (the Excel file is fine). Embed a
257
+ // Unicode font with pdf.addFont if that turns up.
258
+ const t = String(value ?? "").replace(/[\r\n\t]+/g, " ");
259
+ return t.length > MAX_CELL ? `${t.slice(0, MAX_CELL - 1)}…` : t;
260
+ };
261
+
262
+ /** How many photos fit across the page, and the height of `count` photos laid out that way. */
263
+ const PHOTOS_PER_LINE = Math.floor((CONTENT_W + PHOTO_GAP) / (PHOTO_W + PHOTO_GAP));
264
+ export function photoBlockHeight(count: number): number {
265
+ const shown = Math.min(count, MAX_PHOTOS_PER_ROW);
266
+ return shown === 0 ? 0 : Math.ceil(shown / PHOTOS_PER_LINE) * (PHOTO_H + PHOTO_GAP) + PHOTO_GAP;
267
+ }
268
+
269
+ /**
270
+ * Draws the report onto `pdf` (a new jsPDF, A4 landscape, mm). `images` holds
271
+ * the photos that could be loaded, by file id; one that is missing is drawn as
272
+ * a grey box. Every photo links to its full-size file (`photoUrl`).
273
+ */
274
+ export function drawReportPdf(
275
+ pdf: PdfDoc,
276
+ report: Report,
277
+ brand: Brand,
278
+ images: Map<string, PdfImage>,
279
+ photoUrl: (id: string) => string,
280
+ ): void {
281
+ const color = hexColor(brand.color);
282
+ let y = TOP;
283
+
284
+ const newPage = () => {
285
+ pdf.addPage();
286
+ y = TOP;
287
+ };
288
+
289
+ // --- Summary block (page 1) ---
290
+ pdf.setFontSize(9.5);
291
+ for (const [k, v] of report.meta) {
292
+ pdf.setFont("helvetica", "bold");
293
+ pdf.setTextColor(...MUTED);
294
+ pdf.text(k, M, y + 3.5);
295
+ pdf.setFont("helvetica", "normal");
296
+ pdf.setTextColor(...INK);
297
+ pdf.text(pdf.splitTextToSize(clip(v), CONTENT_W - 40)[0] ?? "", M + 34, y + 3.5);
298
+ y += 5;
299
+ }
300
+ y += 3;
301
+ pdf.setFont("helvetica", "bold");
302
+ pdf.setFontSize(12);
303
+ const sentence = pdf.splitTextToSize(report.sentence, CONTENT_W - 10);
304
+ const sentenceH = sentence.length * 5.4 + 5;
305
+ pdf.setFillColor(...ALT);
306
+ pdf.rect(M, y, CONTENT_W, sentenceH, "F");
307
+ pdf.setFillColor(...color);
308
+ pdf.rect(M, y, 1.4, sentenceH, "F");
309
+ pdf.setTextColor(...INK);
310
+ pdf.text(sentence, M + 5, y + 6);
311
+ y += sentenceH + 4;
312
+
313
+ const perLine = 4;
314
+ const figW = (CONTENT_W - (perLine - 1) * 3) / perLine;
315
+ report.figures.forEach(([label, value], i) => {
316
+ const x = M + (i % perLine) * (figW + 3);
317
+ const fy = y + Math.floor(i / perLine) * 16;
318
+ pdf.setDrawColor(...RULE);
319
+ pdf.setLineWidth(0.25);
320
+ pdf.rect(x, fy, figW, 13);
321
+ pdf.setFont("helvetica", "bold");
322
+ pdf.setFontSize(13);
323
+ pdf.setTextColor(...INK);
324
+ pdf.text(clip(value), x + 3, fy + 6);
325
+ pdf.setFont("helvetica", "normal");
326
+ pdf.setFontSize(8);
327
+ pdf.setTextColor(...MUTED);
328
+ pdf.text(clip(label), x + 3, fy + 10.5);
329
+ });
330
+ y += Math.ceil(report.figures.length / perLine) * 16 + 4;
331
+
332
+ // --- Tables ---
333
+ for (const section of report.sections) {
334
+ const sum = section.widths.reduce((a, b) => a + b, 0) || 1;
335
+ const colW = section.widths.map((w) => (w / sum) * CONTENT_W);
336
+ const lines = (row: Cell[]) => row.map((cell, i) => pdf.splitTextToSize(clip(cell), Math.max(4, colW[i] - 2 * CELL_PAD)));
337
+
338
+ const heading = (continued: boolean) => {
339
+ pdf.setFont("helvetica", "bold");
340
+ pdf.setFontSize(11);
341
+ pdf.setTextColor(...INK);
342
+ pdf.text(`${section.heading}${continued ? " (continued)" : ""}`, M, y + 4);
343
+ y += 7;
344
+ pdf.setFillColor(...color);
345
+ pdf.rect(M, y, CONTENT_W, HEAD_H, "F");
346
+ pdf.setFontSize(FONT);
347
+ pdf.setTextColor(255, 255, 255);
348
+ let x = M;
349
+ section.columns.forEach((c, i) => {
350
+ pdf.text(pdf.splitTextToSize(c, colW[i] - 2 * CELL_PAD)[0] ?? "", x + CELL_PAD, y + 4.8);
351
+ x += colW[i];
352
+ });
353
+ y += HEAD_H;
354
+ };
355
+
356
+ // A heading, the header row and one row must fit, or the table starts on a new page.
357
+ if (y + 7 + HEAD_H + LINE + 2 * CELL_PAD > BOTTOM) newPage();
358
+ heading(false);
359
+
360
+ if (section.rows.length === 0) {
361
+ pdf.setFont("helvetica", "normal");
362
+ pdf.setFontSize(FONT);
363
+ pdf.setTextColor(...MUTED);
364
+ pdf.text(section.emptyNote, M + CELL_PAD, y + 5);
365
+ y += 9;
366
+ }
367
+
368
+ section.rows.forEach((row, r) => {
369
+ const cellLines = lines(row);
370
+ const rowH = Math.max(...cellLines.map((l) => l.length)) * LINE + 2 * CELL_PAD;
371
+ const ids = section.photos?.[r] ?? [];
372
+ const photosH = photoBlockHeight(ids.length);
373
+ // A row and its photos stay together (unless they could not fit even on an empty page).
374
+ if (y + rowH + photosH > BOTTOM && y > TOP + 7 + HEAD_H) {
375
+ newPage();
376
+ heading(true);
377
+ }
378
+ const total = String(row[0]) === "Total";
379
+ if (r % 2 === 1 && !total) {
380
+ pdf.setFillColor(...ALT);
381
+ pdf.rect(M, y, CONTENT_W, rowH + photosH, "F");
382
+ }
383
+ pdf.setFont("helvetica", total ? "bold" : "normal");
384
+ pdf.setFontSize(FONT);
385
+ let x = M;
386
+ cellLines.forEach((l, i) => {
387
+ const tone = STATUS_COLOR[String(row[i])];
388
+ pdf.setTextColor(...(tone ?? INK));
389
+ if (tone && !total) pdf.setFont("helvetica", "bold");
390
+ pdf.text(l, x + CELL_PAD, y + CELL_PAD + 2.8);
391
+ if (tone && !total) pdf.setFont("helvetica", "normal");
392
+ x += colW[i];
393
+ });
394
+ y += rowH;
395
+
396
+ ids.slice(0, MAX_PHOTOS_PER_ROW).forEach((id, i) => {
397
+ const px = M + (i % PHOTOS_PER_LINE) * (PHOTO_W + PHOTO_GAP);
398
+ const py = y + PHOTO_GAP + Math.floor(i / PHOTOS_PER_LINE) * (PHOTO_H + PHOTO_GAP);
399
+ const img = images.get(id);
400
+ if (img && img.width > 0 && img.height > 0) {
401
+ const k = Math.min(PHOTO_W / img.width, PHOTO_H / img.height);
402
+ const w = img.width * k;
403
+ const h = img.height * k;
404
+ pdf.addImage(img.data, "JPEG", px + (PHOTO_W - w) / 2, py + (PHOTO_H - h) / 2, w, h);
405
+ } else {
406
+ pdf.setFillColor(230, 233, 238);
407
+ pdf.rect(px, py, PHOTO_W, PHOTO_H, "F");
408
+ pdf.setFont("helvetica", "normal");
409
+ pdf.setFontSize(7.5);
410
+ pdf.setTextColor(...MUTED);
411
+ pdf.text("Photo could not be loaded", px + PHOTO_W / 2, py + PHOTO_H / 2, { align: "center" });
412
+ pdf.text("(click to open)", px + PHOTO_W / 2, py + PHOTO_H / 2 + 3.5, { align: "center" });
413
+ }
414
+ pdf.link(px, py, PHOTO_W, PHOTO_H, { url: photoUrl(id) });
415
+ });
416
+ if (ids.length > MAX_PHOTOS_PER_ROW) {
417
+ pdf.setFont("helvetica", "normal");
418
+ pdf.setFontSize(7.5);
419
+ pdf.setTextColor(...MUTED);
420
+ pdf.text(`+${ids.length - MAX_PHOTOS_PER_ROW} more photos: see the Excel file`, M + CONTENT_W, y + photosH - 0.8, { align: "right" });
421
+ }
422
+ y += photosH;
423
+
424
+ pdf.setDrawColor(...(total ? INK : RULE));
425
+ pdf.setLineWidth(total ? 0.4 : 0.2);
426
+ pdf.line(M, total ? y - rowH : y, M + CONTENT_W, total ? y - rowH : y);
427
+ });
428
+ y += 6;
429
+ }
430
+
431
+ // --- Header and footer on every page ---
432
+ const generated = report.meta.find(([k]) => k === "Generated")?.[1] ?? "";
433
+ const by = report.meta.find(([k]) => k === "Generated by")?.[1] ?? "";
434
+ const pages = pdf.getNumberOfPages();
435
+ for (let page = 1; page <= pages; page += 1) {
436
+ pdf.setPage(page);
437
+ pdf.setFont("helvetica", "bold");
438
+ pdf.setFontSize(13);
439
+ pdf.setTextColor(...color);
440
+ pdf.text(clip(brand.name), M, M + 4);
441
+ pdf.setFontSize(11);
442
+ pdf.setTextColor(...INK);
443
+ pdf.text(report.title, PDF_PAGE.width - M, M + 4, { align: "right" });
444
+ pdf.setDrawColor(...color);
445
+ pdf.setLineWidth(0.6);
446
+ pdf.line(M, M + 7, PDF_PAGE.width - M, M + 7);
447
+
448
+ const fy = PDF_PAGE.height - M;
449
+ pdf.setDrawColor(...RULE);
450
+ pdf.setLineWidth(0.25);
451
+ pdf.line(M, fy - 4.5, PDF_PAGE.width - M, fy - 4.5);
452
+ pdf.setFont("helvetica", "normal");
453
+ pdf.setFontSize(8);
454
+ pdf.setTextColor(...MUTED);
455
+ pdf.text(clip(`Generated ${generated}${by && by !== "-" ? ` by ${by}` : ""}`), M, fy);
456
+ pdf.text(`Page ${page} of ${pages}`, PDF_PAGE.width - M, fy, { align: "right" });
457
+ }
458
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Reads everything a checklist report needs, through the calls the app already
3
+ * makes (the day's list -> its areas -> each area's visits and items). Those
4
+ * calls take no "whole range" shortcut for items, so the loader pages through
5
+ * them. The calls are handed in, so the unit test runs this with sample
6
+ * answers and no network. Pure (no React Native imports).
7
+ *
8
+ * A call that fails fails the whole report: a PDF that quietly leaves a day
9
+ * out would be worse than no PDF.
10
+ */
11
+ import type { RawArea, RawDay, RawSet } from "./checklist-report.ts";
12
+
13
+ export type LoaderCalls = {
14
+ /** The day lists in the chosen dates (the server filters by Singapore day). */
15
+ listDays: (page: number, limit: number) => Promise<unknown>;
16
+ listAreas: (dayId: string, page: number, limit: number) => Promise<unknown>;
17
+ listVisits: (areaId: string, page: number, limit: number) => Promise<unknown>;
18
+ };
19
+
20
+ export type LoadOptions = {
21
+ /** Called as days finish: (days read so far, days to read). */
22
+ onProgress?: (done: number, total: number) => void;
23
+ /** Return true to stop (the person left the screen); the load then throws LoadCancelled. */
24
+ cancelled?: () => boolean;
25
+ pageSize?: number;
26
+ /** Days read at once, and areas read at once inside each day. */
27
+ parallel?: number;
28
+ };
29
+
30
+ export class LoadCancelled extends Error {
31
+ constructor() {
32
+ super("cancelled");
33
+ this.name = "LoadCancelled";
34
+ }
35
+ }
36
+
37
+ const PAGE_SIZE = 100;
38
+ /** A runaway guard: 50 pages of 100 is far beyond one site's range. */
39
+ const MAX_PAGES = 50;
40
+
41
+ type Page = { items?: unknown[]; pages?: number } | unknown[] | null | undefined;
42
+
43
+ const itemsOf = (reply: Page): any[] =>
44
+ Array.isArray(reply) ? reply : Array.isArray(reply?.items) ? (reply?.items as any[]) : [];
45
+
46
+ /** Every row of a paged call, page 1 first, stopping at the last page. */
47
+ export async function readAllPages(
48
+ read: (page: number, limit: number) => Promise<unknown>,
49
+ limit: number = PAGE_SIZE,
50
+ ): Promise<any[]> {
51
+ const all: any[] = [];
52
+ for (let page = 1; page <= MAX_PAGES; page += 1) {
53
+ const reply = (await read(page, limit)) as Page;
54
+ const items = itemsOf(reply);
55
+ all.push(...items);
56
+ const pages = !Array.isArray(reply) && typeof reply?.pages === "number" ? reply.pages : undefined;
57
+ if (items.length < limit || (pages !== undefined && page >= pages)) break;
58
+ }
59
+ return all;
60
+ }
61
+
62
+ /** Runs `work` over `list`, `n` at a time, keeping the order of the answers. */
63
+ async function mapLimit<T, R>(list: T[], n: number, work: (item: T) => Promise<R>): Promise<R[]> {
64
+ const out: R[] = new Array(list.length);
65
+ let next = 0;
66
+ const lane = async () => {
67
+ while (next < list.length) {
68
+ const index = next++;
69
+ out[index] = await work(list[index]);
70
+ }
71
+ };
72
+ await Promise.all(Array.from({ length: Math.min(n, list.length) }, lane));
73
+ return out;
74
+ }
75
+
76
+ export async function loadChecklistData(calls: LoaderCalls, options: LoadOptions = {}): Promise<RawDay[]> {
77
+ const limit = options.pageSize ?? PAGE_SIZE;
78
+ const parallel = options.parallel ?? 3;
79
+ const stop = () => {
80
+ if (options.cancelled?.()) throw new LoadCancelled();
81
+ };
82
+
83
+ const days = await readAllPages((page, size) => calls.listDays(page, size), limit);
84
+ let done = 0;
85
+ options.onProgress?.(0, days.length);
86
+
87
+ return mapLimit(days, parallel, async (day): Promise<RawDay> => {
88
+ stop();
89
+ const areaRows = await readAllPages((page, size) => calls.listAreas(String(day._id), page, size), limit);
90
+ const areas = await mapLimit(areaRows, parallel, async (area): Promise<RawArea> => {
91
+ stop();
92
+ const sets = (await readAllPages((page, size) => calls.listVisits(String(area._id), page, size), limit)) as RawSet[];
93
+ return { _id: area._id, name: area.name, type: area.type, sets };
94
+ });
95
+ done += 1;
96
+ options.onProgress?.(done, days.length);
97
+ return { _id: day._id, createdAt: day.createdAt, status: day.status, areas };
98
+ });
99
+ }