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

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,723 @@
1
+ /**
2
+ * Checklist reports: raw checklist data -> visits -> a readable report.
3
+ *
4
+ * The owner asked (12 Nov 2026) for a downloadable PDF / Excel report of the
5
+ * Daily Checklist and the Extra Checks, with a date range, that anyone can read
6
+ * without help. Everything that decides what the report SAYS lives here, as
7
+ * pure functions, so it is unit tested with sample data and `node --test` runs
8
+ * it as is (no React Native imports). The file is the same in all five trade
9
+ * apps (and in layer-common for the five trade web apps: same content, plus the
10
+ * "Tasks with photos" report, which the mobile apps have too); the data loader (`checklist-report-load.ts`) and the file
11
+ * writer (`checklist-report-files.ts`) sit beside it.
12
+ *
13
+ * Words used in a report:
14
+ * visit one round of one area (the app's "Set N"); an Extra Check adds one
15
+ * item one thing to check inside a visit
16
+ * Done the item was ticked
17
+ * Needs attention the item was marked as not right (the app's "reject")
18
+ * Not done the item was never actioned
19
+ *
20
+ * Reports stay in English whatever language the app is in (owner rule, 23 Oct
21
+ * 2026), so none of these words go through the translator. Every date and time
22
+ * is Singapore time (UTC+8), not the phone's.
23
+ */
24
+
25
+ /** The longest range one report may cover. */
26
+ export const MAX_RANGE_DAYS = 92;
27
+
28
+ export type ReportKind = "summary" | "detail" | "attention" | "extra" | "photos";
29
+ export type ReportFormat = "pdf" | "excel";
30
+ export type RangePreset = "today" | "last7" | "month" | "custom";
31
+
32
+ export type DateRange = { from: string; to: string }; // YYYY-MM-DD, Singapore days, both included
33
+
34
+ export type RangeProblem = "invalid" | "order" | "tooLong";
35
+
36
+ /** The words a report uses for an item. */
37
+ export const STATUS_WORDS = {
38
+ done: "Done",
39
+ attention: "Needs attention",
40
+ pending: "Not done",
41
+ } as const;
42
+
43
+ /** The words a report uses for an Extra Check run. */
44
+ export const EXTRA_STATUS_WORDS = {
45
+ done: "Done",
46
+ doneAttention: "Done, needs attention",
47
+ missed: "Missed",
48
+ pending: "Not done yet",
49
+ } as const;
50
+
51
+ const NONE = "-";
52
+
53
+ // ---------------------------------------------------------------------------
54
+ // Singapore time
55
+ // ---------------------------------------------------------------------------
56
+
57
+ const SGT_MS = 8 * 60 * 60 * 1000;
58
+ const DAY_MS = 24 * 60 * 60 * 1000;
59
+ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
60
+
61
+ const pad = (n: number) => String(n).padStart(2, "0");
62
+
63
+ type SgParts = { y: number; m: number; d: number; h: number; min: number };
64
+
65
+ /** The Singapore calendar parts of an instant, or null when it is not a date. */
66
+ function sgParts(input: string | number | Date | null | undefined): SgParts | null {
67
+ if (input === null || input === undefined || input === "") return null;
68
+ const t = new Date(input).getTime();
69
+ if (Number.isNaN(t)) return null;
70
+ const s = new Date(t + SGT_MS);
71
+ return { y: s.getUTCFullYear(), m: s.getUTCMonth() + 1, d: s.getUTCDate(), h: s.getUTCHours(), min: s.getUTCMinutes() };
72
+ }
73
+
74
+ /** "2026-11-12": the Singapore day an instant falls on, "" if it is not a date. */
75
+ export function sgDay(input: string | number | Date | null | undefined): string {
76
+ const p = sgParts(input);
77
+ return p ? `${p.y}-${pad(p.m)}-${pad(p.d)}` : "";
78
+ }
79
+
80
+ /** "3:05 PM" in Singapore time, "" if it is not a date. */
81
+ export function sgTime(input: string | number | Date | null | undefined): string {
82
+ const p = sgParts(input);
83
+ return p ? clock(p.h, p.min) : "";
84
+ }
85
+
86
+ function clock(h: number, min: number): string {
87
+ const hour = h % 12 === 0 ? 12 : h % 12;
88
+ return `${hour}:${pad(min)} ${h < 12 ? "AM" : "PM"}`;
89
+ }
90
+
91
+ /** "08:00" (a rule's own time) -> "8:00 AM". Anything else is returned as it came. */
92
+ export function clockText(hhmm: string | null | undefined): string {
93
+ const m = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec((hhmm ?? "").trim());
94
+ return m ? clock(Number(m[1]), Number(m[2])) : (hhmm ?? "").trim();
95
+ }
96
+
97
+ /** "2026-11-12" -> "12/11/2026" (the app's day-first dates). */
98
+ export function dayText(day: string): string {
99
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(day);
100
+ return m ? `${m[3]}/${m[2]}/${m[1]}` : day;
101
+ }
102
+
103
+ /** "12/11/2026 3:05 PM" in Singapore time. */
104
+ export function sgDateTime(input: string | number | Date): string {
105
+ const day = sgDay(input);
106
+ return day ? `${dayText(day)} ${sgTime(input)}` : "";
107
+ }
108
+
109
+ /** A day picked on the phone's calendar -> "YYYY-MM-DD" (the date the person saw, never shifted). */
110
+ export function dayOfPicked(date: Date): string {
111
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
112
+ }
113
+
114
+ /** The phone-calendar Date of a "YYYY-MM-DD" day (for the date picker). */
115
+ export function pickedOfDay(day: string): Date {
116
+ const [y, m, d] = day.split("-").map(Number);
117
+ return new Date(y, (m || 1) - 1, d || 1);
118
+ }
119
+
120
+ function dayNumber(day: string): number {
121
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(day);
122
+ if (!m) return NaN;
123
+ const t = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
124
+ const back = new Date(t);
125
+ // A day that rolls over (31 Feb) is not a day.
126
+ return back.getUTCDate() === Number(m[3]) && back.getUTCMonth() === Number(m[2]) - 1 ? t : NaN;
127
+ }
128
+
129
+ function addDays(day: string, delta: number): string {
130
+ // dayNumber is UTC midnight; +8h is still the same Singapore day.
131
+ return sgDay(dayNumber(day) + delta * DAY_MS);
132
+ }
133
+
134
+ /** How many days the range covers, both ends included (NaN if either is not a day). */
135
+ export function rangeDays(range: DateRange): number {
136
+ return Math.round((dayNumber(range.to) - dayNumber(range.from)) / DAY_MS) + 1;
137
+ }
138
+
139
+ /** Today in Singapore. */
140
+ export function sgToday(now: Date = new Date()): string {
141
+ return sgDay(now);
142
+ }
143
+
144
+ /** The range behind a quick button. "Custom" is not a preset range: the person picks it. */
145
+ export function presetRange(preset: Exclude<RangePreset, "custom">, now: Date = new Date()): DateRange {
146
+ const today = sgToday(now);
147
+ if (preset === "today") return { from: today, to: today };
148
+ if (preset === "last7") return { from: addDays(today, -6), to: today };
149
+ return { from: `${today.slice(0, 7)}-01`, to: today };
150
+ }
151
+
152
+ /** What is wrong with a range, or null when it is fine. */
153
+ export function rangeProblem(range: DateRange): RangeProblem | null {
154
+ const days = rangeDays(range);
155
+ if (Number.isNaN(days)) return "invalid";
156
+ if (days < 1) return "order";
157
+ if (days > MAX_RANGE_DAYS) return "tooLong";
158
+ return null;
159
+ }
160
+
161
+ /** "1-7 Nov 2026", "28 Oct - 3 Nov 2026", "7 Nov 2026" (the en dash keeps it short in a sentence). */
162
+ export function rangeWords(range: DateRange): string {
163
+ const f = range.from.split("-").map(Number);
164
+ const t = range.to.split("-").map(Number);
165
+ const one = (p: number[], year = true) => `${p[2]} ${MONTHS[p[1] - 1]}${year ? ` ${p[0]}` : ""}`;
166
+ if (range.from === range.to) return one(f);
167
+ if (f[0] === t[0] && f[1] === t[1]) return `${f[2]}–${t[2]} ${MONTHS[t[1] - 1]} ${t[0]}`;
168
+ if (f[0] === t[0]) return `${one(f, false)} – ${one(t)}`;
169
+ return `${one(f)} – ${one(t)}`;
170
+ }
171
+
172
+ /** "01/11/2026 to 07/11/2026" for the header block. */
173
+ export function rangeHeader(range: DateRange): string {
174
+ return range.from === range.to ? dayText(range.from) : `${dayText(range.from)} to ${dayText(range.to)}`;
175
+ }
176
+
177
+ // ---------------------------------------------------------------------------
178
+ // Raw data (the shapes the API sends; only what the report reads)
179
+ // ---------------------------------------------------------------------------
180
+
181
+ export type RawUnit = {
182
+ unit?: string;
183
+ name?: string;
184
+ approve?: boolean;
185
+ reject?: boolean;
186
+ timestamp?: string | null;
187
+ remarks?: string | null;
188
+ attachment?: string[] | null;
189
+ completedByName?: string | null;
190
+ };
191
+
192
+ export type RawSet = {
193
+ set?: number | string;
194
+ isScheduleTask?: boolean;
195
+ scheduleTaskTitle?: string | null;
196
+ scheduleTaskTime?: string | null;
197
+ remarks?: string | null;
198
+ /** Photos taken for the whole visit (file ids), separate from each item's own. */
199
+ attachment?: string[] | null;
200
+ completedByName?: string | null;
201
+ units?: RawUnit[] | null;
202
+ };
203
+
204
+ export type RawArea = { _id?: string; name?: string; type?: string; sets: RawSet[] };
205
+
206
+ /** One day's checklist (the API's "parent checklist") with its areas and their visits. */
207
+ export type RawDay = { _id?: string; createdAt?: string; status?: string; areas: RawArea[] };
208
+
209
+ // ---------------------------------------------------------------------------
210
+ // Visits
211
+ // ---------------------------------------------------------------------------
212
+
213
+ export type ItemState = "done" | "attention" | "pending";
214
+
215
+ export type ReportItem = {
216
+ name: string;
217
+ state: ItemState;
218
+ at: string; // ISO instant, "" when not actioned
219
+ by: string;
220
+ remark: string;
221
+ photos: number;
222
+ /** The item's photo file ids (the API's unit `attachment`). */
223
+ photoIds: string[];
224
+ };
225
+
226
+ export type ReportVisit = {
227
+ day: string; // YYYY-MM-DD, Singapore
228
+ area: string;
229
+ areaType: string;
230
+ visit: number;
231
+ extraTitle: string; // "" for a normal visit
232
+ extraTime: string; // "HH:mm", "" for a normal visit
233
+ /** True once the day is over, or the system closed it: an unfinished visit is then "missed". */
234
+ closed: boolean;
235
+ items: ReportItem[];
236
+ /** Photos for the whole visit (the API's visit `attachment`), who finished it and its remark. */
237
+ visitPhotoIds: string[];
238
+ visitBy: string;
239
+ visitRemark: string;
240
+ };
241
+
242
+ const cmp = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
243
+
244
+ const text = (value: unknown): string => (typeof value === "string" ? value.trim() : "");
245
+
246
+ const ids = (value: unknown): string[] =>
247
+ Array.isArray(value) ? value.filter((id): id is string => typeof id === "string" && id.trim() !== "") : [];
248
+
249
+ function itemState(unit: RawUnit): ItemState {
250
+ if (unit.approve) return "done";
251
+ if (unit.reject) return "attention";
252
+ return "pending";
253
+ }
254
+
255
+ /**
256
+ * The visits of the days that fall inside `range` (Singapore days), oldest day
257
+ * first, then by area name and visit number. A day outside the range is dropped
258
+ * here as well as by the server, so a wider answer never leaks into a report.
259
+ */
260
+ export function buildVisits(days: RawDay[], range: DateRange, now: Date = new Date()): ReportVisit[] {
261
+ const today = sgToday(now);
262
+ const out: ReportVisit[] = [];
263
+
264
+ for (const day of days) {
265
+ const d = sgDay(day.createdAt);
266
+ if (!d || d < range.from || d > range.to) continue;
267
+ const closed = text(day.status).toLowerCase() === "closed" || d < today;
268
+
269
+ for (const area of day.areas ?? []) {
270
+ for (const set of area.sets ?? []) {
271
+ const units = set.units ?? [];
272
+ if (units.length === 0) continue;
273
+ out.push({
274
+ day: d,
275
+ area: text(area.name) || NONE,
276
+ areaType: text(area.type),
277
+ visit: Number(set.set) || 0,
278
+ extraTitle: set.isScheduleTask ? text(set.scheduleTaskTitle) || "Extra check" : "",
279
+ extraTime: set.isScheduleTask ? text(set.scheduleTaskTime) : "",
280
+ closed,
281
+ visitPhotoIds: ids(set.attachment),
282
+ visitBy: text(set.completedByName),
283
+ visitRemark: text(set.remarks),
284
+ items: units.map((unit) => ({
285
+ name: text(unit.name) || NONE,
286
+ state: itemState(unit),
287
+ at: itemState(unit) === "pending" ? "" : text(unit.timestamp),
288
+ by: itemState(unit) === "pending" ? "" : text(unit.completedByName) || text(set.completedByName),
289
+ remark: text(unit.remarks) || text(set.remarks),
290
+ photos: Array.isArray(unit.attachment) ? unit.attachment.length : 0,
291
+ photoIds: ids(unit.attachment),
292
+ })),
293
+ });
294
+ }
295
+ }
296
+ }
297
+
298
+ return out.sort(
299
+ (a, b) => cmp(a.day, b.day) || cmp(a.area, b.area) || a.visit - b.visit || cmp(a.extraTitle, b.extraTitle),
300
+ );
301
+ }
302
+
303
+ const count = (items: ReportItem[], state: ItemState) => items.filter((item) => item.state === state).length;
304
+
305
+ /** A visit is done once every item in it has been actioned (the app's own rule). */
306
+ export const visitFinished = (visit: ReportVisit) => visit.items.length > 0 && count(visit.items, "pending") === 0;
307
+
308
+ const percent = (part: number, whole: number) => (whole > 0 ? Math.round((part / whole) * 100) : 0);
309
+
310
+ export type Totals = {
311
+ days: number;
312
+ areas: number;
313
+ visits: number;
314
+ visitsDone: number;
315
+ items: number;
316
+ itemsDone: number;
317
+ attention: number;
318
+ pending: number;
319
+ /** Visits done / visits, whole percent. */
320
+ visitPct: number;
321
+ /** Items done / items, whole percent. */
322
+ itemPct: number;
323
+ };
324
+
325
+ export function totalsOf(visits: ReportVisit[]): Totals {
326
+ const items = visits.flatMap((visit) => visit.items);
327
+ const visitsDone = visits.filter(visitFinished).length;
328
+ const itemsDone = count(items, "done");
329
+ return {
330
+ days: new Set(visits.map((visit) => visit.day)).size,
331
+ areas: new Set(visits.map((visit) => visit.area)).size,
332
+ visits: visits.length,
333
+ visitsDone,
334
+ items: items.length,
335
+ itemsDone,
336
+ attention: count(items, "attention"),
337
+ pending: count(items, "pending"),
338
+ visitPct: percent(visitsDone, visits.length),
339
+ itemPct: percent(itemsDone, items.length),
340
+ };
341
+ }
342
+
343
+ // ---------------------------------------------------------------------------
344
+ // Extra Check runs
345
+ // ---------------------------------------------------------------------------
346
+
347
+ export type ExtraStatus = keyof typeof EXTRA_STATUS_WORDS;
348
+
349
+ /** Done / done but something needs attention / missed (day over, not finished) / not done yet. */
350
+ export function extraStatus(visit: ReportVisit): ExtraStatus {
351
+ if (visitFinished(visit)) return count(visit.items, "attention") > 0 ? "doneAttention" : "done";
352
+ return visit.closed ? "missed" : "pending";
353
+ }
354
+
355
+ // ---------------------------------------------------------------------------
356
+ // The report
357
+ // ---------------------------------------------------------------------------
358
+
359
+ export type Cell = string | number;
360
+
361
+ export type Section = {
362
+ /** The Excel sheet name (31 characters at most, none of : \ / ? * [ ]). */
363
+ name: string;
364
+ heading: string;
365
+ columns: string[];
366
+ /** Column widths in characters: the Excel width, and the share of the PDF page. */
367
+ widths: number[];
368
+ rows: Cell[][];
369
+ /** Said instead of a table when there are no rows. */
370
+ emptyNote: string;
371
+ /** Photo file ids per row (same order as `rows`): drawn under the row in a PDF, linked in Excel. */
372
+ photos?: string[][];
373
+ };
374
+
375
+ export type Report = {
376
+ kind: ReportKind;
377
+ title: string;
378
+ /** Lower-case file name stem, no extension. */
379
+ fileStem: string;
380
+ meta: [string, string][];
381
+ sentence: string;
382
+ figures: [string, string][];
383
+ sections: Section[];
384
+ /** True when there is nothing at all to report on in these dates (the screen says so instead of generating). */
385
+ empty: boolean;
386
+ };
387
+
388
+ export type ReportContext = {
389
+ company: string;
390
+ site: string;
391
+ range: DateRange;
392
+ generatedAt: Date;
393
+ /** Who made it: "Name (email)" (owner, 13 Nov 2026: the person and the account). */
394
+ generatedBy: string;
395
+ };
396
+
397
+ export const REPORT_TITLES: Record<ReportKind, string> = {
398
+ summary: "Daily Checklist - Summary by Day",
399
+ detail: "Daily Checklist - Area and Item Detail",
400
+ attention: "Daily Checklist - Items Needing Attention",
401
+ extra: "Extra Checks",
402
+ photos: "Tasks with Photos",
403
+ };
404
+
405
+ const FILE_STEMS: Record<ReportKind, string> = {
406
+ summary: "daily-checklist-summary",
407
+ detail: "area-and-item-detail",
408
+ attention: "items-needing-attention",
409
+ extra: "extra-checks",
410
+ photos: "tasks-with-photos",
411
+ };
412
+
413
+ const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
414
+
415
+ function attentionSentence(n: number): string {
416
+ if (n === 0) return "No items need attention.";
417
+ return n === 1 ? "1 item needs attention." : `${n} items need attention.`;
418
+ }
419
+
420
+ function notDoneSentence(n: number): string {
421
+ if (n === 0) return "";
422
+ return n === 1 ? " 1 item was not done." : ` ${n} items were not done.`;
423
+ }
424
+
425
+ const lead = (range: DateRange) => (range.from === range.to ? `On ${rangeWords(range)}` : `Between ${rangeWords(range)}`);
426
+
427
+ function metaFor(kind: ReportKind, ctx: ReportContext): [string, string][] {
428
+ return [
429
+ ["Company", ctx.company || NONE],
430
+ ["Site", ctx.site || NONE],
431
+ ["Report", REPORT_TITLES[kind]],
432
+ ["Dates", rangeHeader(ctx.range)],
433
+ ["Generated", `${sgDateTime(ctx.generatedAt)} (Singapore time)`],
434
+ ["Generated by", ctx.generatedBy || NONE],
435
+ ];
436
+ }
437
+
438
+ const visitLabel = (visit: ReportVisit) =>
439
+ `Visit ${visit.visit}${visit.extraTitle ? ` (extra check: ${visit.extraTitle})` : ""}`;
440
+
441
+ const DETAIL_COLUMNS = ["Date", "Area", "Visit", "Item", "Status", "Time", "Done by", "Remark"];
442
+ const DETAIL_WIDTHS = [11, 18, 16, 26, 15, 10, 16, 28];
443
+
444
+ function detailRows(visits: ReportVisit[], only?: ItemState): Cell[][] {
445
+ const rows: Cell[][] = [];
446
+ for (const visit of visits) {
447
+ for (const item of visit.items) {
448
+ if (only && item.state !== only) continue;
449
+ rows.push([
450
+ dayText(visit.day),
451
+ visit.area,
452
+ visitLabel(visit),
453
+ item.name,
454
+ STATUS_WORDS[item.state],
455
+ sgTime(item.at) || NONE,
456
+ item.by || NONE,
457
+ item.remark || NONE,
458
+ ]);
459
+ }
460
+ }
461
+ return rows;
462
+ }
463
+
464
+ function groupTotals<K extends string>(visits: ReportVisit[], keyOf: (visit: ReportVisit) => K): Map<K, Totals> {
465
+ const groups = new Map<K, ReportVisit[]>();
466
+ for (const visit of visits) {
467
+ const key = keyOf(visit);
468
+ groups.set(key, [...(groups.get(key) ?? []), visit]);
469
+ }
470
+ return new Map([...groups.entries()].map(([key, list]) => [key, totalsOf(list)]));
471
+ }
472
+
473
+ function commonFigures(t: Totals): [string, string][] {
474
+ return [
475
+ ["Days covered", String(t.days)],
476
+ ["Areas", String(t.areas)],
477
+ ["Visits done", `${t.visitsDone} of ${t.visits}`],
478
+ ["Items done", `${t.itemsDone} of ${t.items}`],
479
+ ["Items needing attention", String(t.attention)],
480
+ ["Items not done", String(t.pending)],
481
+ ["Completion (visits)", `${t.visitPct}%`],
482
+ ];
483
+ }
484
+
485
+ function summaryReport(visits: ReportVisit[], ctx: ReportContext): Report {
486
+ const t = totalsOf(visits);
487
+ const byDay = groupTotals(visits, (visit) => visit.day);
488
+ const byArea = groupTotals(visits, (visit) => visit.area);
489
+
490
+ const dayRows: Cell[][] = [...byDay.entries()]
491
+ .sort(([a], [b]) => cmp(a, b))
492
+ .map(([day, d]) => [dayText(day), d.areas, d.visitsDone, d.visits, d.itemsDone, d.attention, d.pending, `${d.visitPct}%`]);
493
+ dayRows.push(["Total", t.areas, t.visitsDone, t.visits, t.itemsDone, t.attention, t.pending, `${t.visitPct}%`]);
494
+
495
+ const areaRows: Cell[][] = [...byArea.entries()]
496
+ .sort(([a], [b]) => cmp(a, b))
497
+ .map(([area, a]) => [area, a.visitsDone, a.visits, a.itemsDone, a.attention, a.pending, `${a.visitPct}%`]);
498
+
499
+ return {
500
+ kind: "summary",
501
+ title: REPORT_TITLES.summary,
502
+ fileStem: FILE_STEMS.summary,
503
+ meta: metaFor("summary", ctx),
504
+ sentence: `${lead(ctx.range)}: ${t.visitsDone} of ${t.visits} visits done (${t.visitPct}%). ${attentionSentence(t.attention)}${notDoneSentence(t.pending)}`,
505
+ figures: commonFigures(t),
506
+ sections: [
507
+ {
508
+ name: "By day",
509
+ heading: "By day",
510
+ columns: ["Date", "Areas", "Visits done", "Visits planned", "Items done", "Items needing attention", "Items not done", "Completion"],
511
+ widths: [12, 8, 12, 14, 12, 18, 14, 12],
512
+ rows: dayRows,
513
+ emptyNote: "No checklist records in these dates.",
514
+ },
515
+ {
516
+ name: "By area",
517
+ heading: "By area",
518
+ columns: ["Area", "Visits done", "Visits planned", "Items done", "Items needing attention", "Items not done", "Completion"],
519
+ widths: [28, 12, 14, 12, 18, 14, 12],
520
+ rows: areaRows,
521
+ emptyNote: "No checklist records in these dates.",
522
+ },
523
+ ],
524
+ empty: visits.length === 0,
525
+ };
526
+ }
527
+
528
+ function detailReport(visits: ReportVisit[], ctx: ReportContext): Report {
529
+ const t = totalsOf(visits);
530
+ return {
531
+ kind: "detail",
532
+ title: REPORT_TITLES.detail,
533
+ fileStem: FILE_STEMS.detail,
534
+ meta: metaFor("detail", ctx),
535
+ sentence: `${lead(ctx.range)}: ${t.itemsDone} of ${t.items} items done (${t.itemPct}%). ${attentionSentence(t.attention)}${notDoneSentence(t.pending)}`,
536
+ figures: commonFigures(t),
537
+ sections: [
538
+ {
539
+ name: "Details",
540
+ heading: "Every item, area by area",
541
+ columns: DETAIL_COLUMNS,
542
+ widths: DETAIL_WIDTHS,
543
+ rows: detailRows(visits),
544
+ emptyNote: "No checklist records in these dates.",
545
+ },
546
+ ],
547
+ empty: visits.length === 0,
548
+ };
549
+ }
550
+
551
+ function attentionReport(visits: ReportVisit[], ctx: ReportContext): Report {
552
+ const t = totalsOf(visits);
553
+ const flagged = visits.filter((visit) => visit.items.some((item) => item.state === "attention"));
554
+ const areas = new Set(flagged.map((visit) => visit.area)).size;
555
+ const sentence =
556
+ t.attention === 0
557
+ ? `${lead(ctx.range)}: no items need attention.`
558
+ : `${lead(ctx.range)}: ${plural(t.attention, "item needs", "items need")} attention, across ${plural(areas, "area", "areas")}.`;
559
+ return {
560
+ kind: "attention",
561
+ title: REPORT_TITLES.attention,
562
+ fileStem: FILE_STEMS.attention,
563
+ meta: metaFor("attention", ctx),
564
+ sentence,
565
+ figures: [
566
+ ["Items needing attention", String(t.attention)],
567
+ ["Areas affected", String(areas)],
568
+ ["Items checked in these dates", String(t.items)],
569
+ ],
570
+ sections: [
571
+ {
572
+ name: "Follow-up",
573
+ heading: "Items to follow up",
574
+ columns: DETAIL_COLUMNS,
575
+ widths: DETAIL_WIDTHS,
576
+ rows: detailRows(visits, "attention"),
577
+ emptyNote: "No items need attention in these dates.",
578
+ },
579
+ ],
580
+ empty: visits.length === 0,
581
+ };
582
+ }
583
+
584
+ function extraReport(visits: ReportVisit[], ctx: ReportContext): Report {
585
+ const runs = visits.filter((visit) => visit.extraTitle);
586
+ const statuses = runs.map(extraStatus);
587
+ const n = (s: ExtraStatus) => statuses.filter((x) => x === s).length;
588
+ const finished = n("done") + n("doneAttention");
589
+ const rows: Cell[][] = runs.map((visit, i) => {
590
+ const doneItems = visit.items.filter((item) => item.state !== "pending");
591
+ const latest = doneItems.map((item) => item.at).filter(Boolean).sort().pop() ?? "";
592
+ const by = [...new Set(doneItems.map((item) => item.by).filter(Boolean))].join(", ");
593
+ const remarks = [...new Set(visit.items.map((item) => item.remark).filter(Boolean))].join("; ");
594
+ return [
595
+ dayText(visit.day),
596
+ visit.extraTitle,
597
+ visit.area,
598
+ clockText(visit.extraTime) || NONE,
599
+ EXTRA_STATUS_WORDS[statuses[i]],
600
+ `${doneItems.length} of ${visit.items.length}`,
601
+ latest ? sgTime(latest) : NONE,
602
+ by || NONE,
603
+ remarks || NONE,
604
+ ];
605
+ });
606
+
607
+ const missed = n("missed");
608
+ return {
609
+ kind: "extra",
610
+ title: REPORT_TITLES.extra,
611
+ fileStem: FILE_STEMS.extra,
612
+ meta: metaFor("extra", ctx),
613
+ sentence: `${lead(ctx.range)}: ${finished} of ${runs.length} extra checks done (${percent(finished, runs.length)}%). ${
614
+ missed === 0 ? "None missed." : `${missed} missed.`
615
+ }${n("doneAttention") > 0 ? ` ${plural(n("doneAttention"), "check was", "checks were")} done but something needs attention.` : ""}`,
616
+ figures: [
617
+ ["Extra checks scheduled", String(runs.length)],
618
+ ["Done", String(n("done") + n("doneAttention"))],
619
+ ["Missed", String(missed)],
620
+ ["Not done yet", String(n("pending"))],
621
+ ["Done, needs attention", String(n("doneAttention"))],
622
+ ["Completion", `${percent(finished, runs.length)}%`],
623
+ ],
624
+ sections: [
625
+ {
626
+ name: "Extra checks",
627
+ heading: "Each extra check",
628
+ columns: ["Date", "Extra check", "Area", "Scheduled time", "Status", "Items done", "Done at", "Done by", "Remark"],
629
+ widths: [15, 22, 18, 14, 16, 11, 10, 16, 22],
630
+ rows,
631
+ emptyNote: "No extra checks in these dates.",
632
+ },
633
+ ],
634
+ empty: runs.length === 0,
635
+ };
636
+ }
637
+
638
+ /**
639
+ * Tasks with photos (owner, 13 Nov 2026: "see the task and the attached
640
+ * photo"): every item that has photos, and every visit's own finish photos,
641
+ * with who did it and when.
642
+ */
643
+ function photosReport(visits: ReportVisit[], ctx: ReportContext): Report {
644
+ const rows: Cell[][] = [];
645
+ const photos: string[][] = [];
646
+ for (const visit of visits) {
647
+ for (const item of visit.items) {
648
+ if (item.photoIds.length === 0) continue;
649
+ rows.push([
650
+ dayText(visit.day),
651
+ visit.area,
652
+ visitLabel(visit),
653
+ item.name,
654
+ STATUS_WORDS[item.state],
655
+ sgTime(item.at) || NONE,
656
+ item.by || NONE,
657
+ item.remark || NONE,
658
+ item.photoIds.length,
659
+ ]);
660
+ photos.push(item.photoIds);
661
+ }
662
+ if (visit.visitPhotoIds.length > 0) {
663
+ const latest = visit.items.map((item) => item.at).filter(Boolean).sort().pop() ?? "";
664
+ rows.push([
665
+ dayText(visit.day),
666
+ visit.area,
667
+ visitLabel(visit),
668
+ "Whole visit",
669
+ visitFinished(visit) ? STATUS_WORDS.done : STATUS_WORDS.pending,
670
+ sgTime(latest) || NONE,
671
+ visit.visitBy || NONE,
672
+ visit.visitRemark || NONE,
673
+ visit.visitPhotoIds.length,
674
+ ]);
675
+ photos.push(visit.visitPhotoIds);
676
+ }
677
+ }
678
+ const total = photos.reduce((n, list) => n + list.length, 0);
679
+ const areas = new Set(rows.map((row) => row[1])).size;
680
+ return {
681
+ kind: "photos",
682
+ title: REPORT_TITLES.photos,
683
+ fileStem: FILE_STEMS.photos,
684
+ meta: metaFor("photos", ctx),
685
+ sentence:
686
+ rows.length === 0
687
+ ? `${lead(ctx.range)}: no photos were attached.`
688
+ : `${lead(ctx.range)}: ${plural(total, "photo", "photos")} on ${plural(rows.length, "task", "tasks")}, across ${plural(areas, "area", "areas")}.`,
689
+ figures: [
690
+ ["Tasks with photos", String(rows.length)],
691
+ ["Photos", String(total)],
692
+ ["Areas", String(areas)],
693
+ ["Needing attention", String(rows.filter((row) => row[4] === STATUS_WORDS.attention).length)],
694
+ ],
695
+ sections: [
696
+ {
697
+ name: "Tasks with photos",
698
+ heading: "Each task and its photos",
699
+ columns: [...DETAIL_COLUMNS, "Photos"],
700
+ widths: [...DETAIL_WIDTHS, 8],
701
+ rows,
702
+ photos,
703
+ emptyNote: "No photos in these dates.",
704
+ },
705
+ ],
706
+ empty: visits.length === 0,
707
+ };
708
+ }
709
+
710
+ /** The report for `kind` from the visits of the chosen dates. */
711
+ export function buildReport(kind: ReportKind, visits: ReportVisit[], ctx: ReportContext): Report {
712
+ if (kind === "summary") return summaryReport(visits, ctx);
713
+ if (kind === "detail") return detailReport(visits, ctx);
714
+ if (kind === "attention") return attentionReport(visits, ctx);
715
+ if (kind === "photos") return photosReport(visits, ctx);
716
+ return extraReport(visits, ctx);
717
+ }
718
+
719
+ /** "daily-checklist-summary_2026-11-06_to_2026-11-12.pdf" */
720
+ export function reportFileName(report: Report, range: DateRange, format: ReportFormat): string {
721
+ const when = range.from === range.to ? range.from : `${range.from}_to_${range.to}`;
722
+ return `${report.fileStem}_${when}.${format === "pdf" ? "pdf" : "xlsx"}`;
723
+ }