@7365admin1/layer-common 4.16.0 → 4.17.0

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,584 @@
1
+ /**
2
+ * The Whitelist (Bulk) sheet: what a row is, when a cell is wrong, and how a
3
+ * block of cells pasted from Excel is read.
4
+ *
5
+ * All of it is plain data, apart from the component that draws the grid, so
6
+ * the rules a person meets as red cells are testable on their own - see
7
+ * `vehicle-bulk-rows.test.ts`.
8
+ */
9
+
10
+ export type BulkRowStatus = "pending" | "adding" | "added" | "failed";
11
+
12
+ /** One line of the sheet. `block`, `level` and `unit` hold ids, not names. */
13
+ export type BulkVehicleRow = {
14
+ /** This row's own id. Sent to the server and handed back with the outcome. */
15
+ id: string;
16
+ block: string;
17
+ level: string;
18
+ unit: string;
19
+ nric: string;
20
+ name: string;
21
+ /** The country's dial code for `phone`, e.g. "+65". Never blank. */
22
+ dialCode: string;
23
+ phone: string;
24
+ plateNumber: string;
25
+ status: BulkRowStatus;
26
+ /** What the server said about this row - shown behind the info icon. */
27
+ message: string;
28
+ /** The cells to paint red. */
29
+ invalid: string[];
30
+ };
31
+
32
+ /**
33
+ * The cells a person TYPES IN, left to right. The Code column is not one of
34
+ * them: every row carries a dial code from the moment it exists, so counting
35
+ * it would make an untouched row look filled in.
36
+ */
37
+ export const BULK_ROW_FIELDS = [
38
+ "block",
39
+ "level",
40
+ "unit",
41
+ "nric",
42
+ "name",
43
+ "phone",
44
+ "plateNumber",
45
+ ] as const;
46
+
47
+ /** Without these a row cannot be added. */
48
+ export const BULK_ROW_REQUIRED = [
49
+ "block",
50
+ "level",
51
+ "unit",
52
+ "name",
53
+ "plateNumber",
54
+ ] as const;
55
+
56
+ let rowSeq = 0;
57
+
58
+ export function emptyBulkRow(id?: string): BulkVehicleRow {
59
+ rowSeq += 1;
60
+ return {
61
+ id: id ?? `row-${Date.now().toString(36)}-${rowSeq}`,
62
+ block: "",
63
+ level: "",
64
+ unit: "",
65
+ nric: "",
66
+ name: "",
67
+ dialCode: DEFAULT_DIAL_CODE,
68
+ phone: "",
69
+ plateNumber: "",
70
+ status: "pending",
71
+ message: "",
72
+ invalid: [],
73
+ };
74
+ }
75
+
76
+ /** A row nobody has typed anything into. Left alone by Submit entirely. */
77
+ export function isBulkRowEmpty(row: BulkVehicleRow): boolean {
78
+ return BULK_ROW_FIELDS.every((field) => !String(row[field] ?? "").trim());
79
+ }
80
+
81
+ /**
82
+ * A phone number as the sheet holds one: DIGITS, and nothing else. The country
83
+ * is the Code column's business, so a cell keeps only the number itself - what
84
+ * a person would dial locally. Blank is fine; it is not a required column.
85
+ */
86
+ export function isValidBulkPhone(value: unknown): boolean {
87
+ const text = String(value ?? "").trim();
88
+ if (!text) return true;
89
+ return /^\d{7,15}$/.test(text);
90
+ }
91
+
92
+ /** Everything but the digits, gone: what a phone cell stores. */
93
+ export function bulkPhoneDigits(value: unknown): string {
94
+ return String(value ?? "").replace(/\D/g, "");
95
+ }
96
+
97
+ /**
98
+ * Split what somebody typed or pasted into a phone cell into the country it
99
+ * names and the number itself.
100
+ *
101
+ * "+60 12-345 6789" and "006012 3456789" both carry their own country, so the
102
+ * Code column follows the number rather than contradicting it. A plain local
103
+ * number names no country and leaves the Code alone.
104
+ */
105
+ export function splitPhoneEntry(
106
+ value: unknown,
107
+ codes: string[],
108
+ ): { dialCode: string; phone: string } {
109
+ const text = String(value ?? "").trim().replace(/[\s()\-.]/g, "");
110
+ const carriesCode = text.startsWith("+") || text.startsWith("00");
111
+ const digits = text.replace(/\D/g, "");
112
+
113
+ if (!carriesCode || !digits) return { dialCode: "", phone: digits };
114
+
115
+ const body = text.startsWith("00") ? digits.slice(2) : digits;
116
+ const match = [...codes]
117
+ .sort((a, b) => b.length - a.length)
118
+ .find((code) => body.startsWith(code.replace(/\D/g, "")));
119
+
120
+ if (!match) return { dialCode: "", phone: body };
121
+ return { dialCode: match, phone: body.slice(match.replace(/\D/g, "").length) };
122
+ }
123
+
124
+ /** What the one-vehicle form puts in front of a number with no country code. */
125
+ export const DEFAULT_DIAL_CODE = "+65";
126
+
127
+ /**
128
+ * The phone number as it is STORED, so a vehicle added from a sheet looks like
129
+ * one added through the form.
130
+ *
131
+ * The form's phone field keeps the picked country's dial code in front of the
132
+ * number, so "91234567" with Singapore picked is saved as "+6591234567". The
133
+ * sheet has the same picker in its Code column, and this puts the two
134
+ * together. A number already written with a country code keeps its own.
135
+ */
136
+ export function bulkPhoneToStore(value: unknown, dialCode?: string): string {
137
+ const digits = bulkPhoneDigits(value);
138
+ if (!digits) return "";
139
+
140
+ const code = String(dialCode ?? "").trim() || DEFAULT_DIAL_CODE;
141
+ const codeDigits = code.replace(/\D/g, "");
142
+
143
+ // A number that already carries its country's digits is not given them twice.
144
+ if (codeDigits && digits.startsWith(codeDigits) && digits.length > codeDigits.length) {
145
+ return `+${digits}`;
146
+ }
147
+
148
+ return `+${codeDigits}${digits}`;
149
+ }
150
+
151
+ /** Each dial code's number patterns, e.g. { "+65": ["^\\+65\\d{8}$"] }. */
152
+ export type BulkDialRules = Record<string, string[]>;
153
+
154
+ const compiled = new Map<string, RegExp>();
155
+
156
+ function matches(pattern: string, value: string): boolean {
157
+ let regex = compiled.get(pattern);
158
+ if (!regex) {
159
+ regex = new RegExp(pattern);
160
+ compiled.set(pattern, regex);
161
+ }
162
+ return regex.test(value);
163
+ }
164
+
165
+ /** The dial code a finished number belongs to - the longest one it starts with. */
166
+ export function bulkDialCodeOf(stored: string, codes: string[]): string {
167
+ return (
168
+ [...codes]
169
+ .sort((a, b) => b.length - a.length)
170
+ .find((code) => stored.startsWith(code)) ?? ""
171
+ );
172
+ }
173
+
174
+ /**
175
+ * Is this a number that country really has?
176
+ *
177
+ * A phone number is not required, so a blank one is fine. One that IS filled
178
+ * in has to be a number the country of its Code column would issue - the same
179
+ * check the one-vehicle form makes, and made here instead of at the camera or
180
+ * the database, where a wrong number is found out far too late.
181
+ */
182
+ export function isValidBulkNumber(
183
+ phone: unknown,
184
+ dialCode?: string,
185
+ rules?: BulkDialRules,
186
+ ): boolean {
187
+ const text = String(phone ?? "").trim();
188
+ if (!text) return true;
189
+ if (!isValidBulkPhone(text)) return false;
190
+ if (!rules) return true;
191
+
192
+ const stored = bulkPhoneToStore(text, dialCode);
193
+ const code = bulkDialCodeOf(stored, Object.keys(rules));
194
+ // A number under no country anybody knows is not a number we can store.
195
+ if (!code) return false;
196
+
197
+ const patterns = rules[code] ?? [];
198
+ // A known code with nothing to check it against passes on its shape alone.
199
+ if (!patterns.length) return true;
200
+
201
+ return patterns.some((pattern) => matches(pattern, stored));
202
+ }
203
+
204
+ /**
205
+ * An NRIC or a plate as the system keeps them: letters and digits, in capitals.
206
+ *
207
+ * The one-vehicle form's own NRIC and Vehicle Number fields strip everything
208
+ * else as you type, so "sba 1234 x" and "SBA1234X" cannot both be stored for
209
+ * one car. The sheet applies the same rule, wherever a value came from.
210
+ */
211
+ export function bulkAlphaNumeric(value: unknown): string {
212
+ return String(value ?? "").replace(/[^A-Za-z0-9]/g, "").toUpperCase();
213
+ }
214
+
215
+ /**
216
+ * An identity number as the sheet keeps one: capitals, and the separators an
217
+ * ID can really carry.
218
+ *
219
+ * Not every ID is eight letters and digits - a Malaysian IC is written
220
+ * 900101-14-5678, a permit can carry a slash - so a symbol is kept rather than
221
+ * silently dropped. What goes is only what nobody's ID contains: spaces,
222
+ * commas and full stops, which are how people space a number out when they
223
+ * write it down.
224
+ */
225
+ export function bulkIdNumber(value: unknown): string {
226
+ return String(value ?? "").replace(/[\s,.]/g, "").toUpperCase();
227
+ }
228
+
229
+ /** A plate number: letters and digits, and nothing else. */
230
+ export function isValidBulkPlate(value: unknown): boolean {
231
+ return /^[A-Za-z0-9]{1,15}$/.test(String(value ?? "").trim());
232
+ }
233
+
234
+ /** Plates written the same way once spacing and case are ignored. */
235
+ export function normaliseBulkPlate(value: unknown): string {
236
+ return String(value ?? "").replace(/\s+/g, "").toUpperCase();
237
+ }
238
+
239
+ export type BulkRowOptions = {
240
+ /** The ids the block / level / unit pickers offer for THIS row. */
241
+ blockIds: string[];
242
+ levelIds: string[];
243
+ unitIds: string[];
244
+ /** Every dial code the Code column offers, e.g. ["+65", "+60", …]. */
245
+ dialCodes?: string[];
246
+ /** What a number must look like under each of those codes. */
247
+ dialRules?: BulkDialRules;
248
+ /** Plates typed on other rows of the same sheet, normalised. */
249
+ otherPlates?: string[];
250
+ };
251
+
252
+ /**
253
+ * The cells of one row that are wrong, in the order they are shown.
254
+ *
255
+ * A cell is wrong when it is empty and required, when the block, level or unit
256
+ * is not one this site offers (a pasted name that matched nothing), when a
257
+ * phone number is not one its country would issue (blank is fine - it is not
258
+ * required), when the Code is not one the picker offers, or when the plate is
259
+ * written twice in the same sheet.
260
+ */
261
+ export function invalidBulkCells(
262
+ row: BulkVehicleRow,
263
+ options: BulkRowOptions,
264
+ ): string[] {
265
+ const invalid: string[] = [];
266
+ const value = (field: (typeof BULK_ROW_FIELDS)[number]) =>
267
+ String(row[field] ?? "").trim();
268
+
269
+ for (const field of BULK_ROW_REQUIRED) {
270
+ if (!value(field)) invalid.push(field);
271
+ }
272
+
273
+ if (value("block") && !options.blockIds.includes(value("block"))) {
274
+ invalid.push("block");
275
+ }
276
+ if (value("level") && !options.levelIds.includes(value("level"))) {
277
+ invalid.push("level");
278
+ }
279
+ if (value("unit") && !options.unitIds.includes(value("unit"))) {
280
+ invalid.push("unit");
281
+ }
282
+ if (!isValidBulkNumber(row.phone, row.dialCode, options.dialRules)) {
283
+ invalid.push("phone");
284
+ }
285
+ // The code only has to be right when there is a number for it to belong to.
286
+ if (
287
+ row.phone.trim() &&
288
+ options.dialCodes &&
289
+ !options.dialCodes.includes(String(row.dialCode ?? "").trim())
290
+ ) {
291
+ invalid.push("dialCode");
292
+ }
293
+ if (value("plateNumber") && !isValidBulkPlate(row.plateNumber)) {
294
+ invalid.push("plateNumber");
295
+ }
296
+ if (
297
+ value("plateNumber") &&
298
+ (options.otherPlates ?? []).includes(normaliseBulkPlate(row.plateNumber))
299
+ ) {
300
+ invalid.push("plateNumber");
301
+ }
302
+
303
+ return Array.from(new Set(invalid));
304
+ }
305
+
306
+ /**
307
+ * Check every row that is going to be sent, and write the red cells onto the
308
+ * rows themselves. Returns the rows that have something wrong.
309
+ *
310
+ * Rows that are already ADDED, and rows nobody has typed in, are left out of
311
+ * both the check and the answer.
312
+ */
313
+ export function validateBulkRows(
314
+ rows: BulkVehicleRow[],
315
+ optionsFor: (row: BulkVehicleRow) => BulkRowOptions,
316
+ ): BulkVehicleRow[] {
317
+ const live = rows.filter(
318
+ (row) => row.status !== "added" && !isBulkRowEmpty(row),
319
+ );
320
+
321
+ const seen = new Map<string, number>();
322
+ for (const row of rows) {
323
+ if (row.status === "added") continue;
324
+ const plate = normaliseBulkPlate(row.plateNumber);
325
+ if (plate) seen.set(plate, (seen.get(plate) ?? 0) + 1);
326
+ }
327
+
328
+ const bad: BulkVehicleRow[] = [];
329
+
330
+ for (const row of rows) {
331
+ if (!live.includes(row)) {
332
+ row.invalid = [];
333
+ continue;
334
+ }
335
+ const plate = normaliseBulkPlate(row.plateNumber);
336
+ const options = optionsFor(row);
337
+ row.invalid = invalidBulkCells(row, {
338
+ ...options,
339
+ // Its own plate counts as a repeat only when another row has it too.
340
+ otherPlates: (seen.get(plate) ?? 0) > 1 ? [plate] : [],
341
+ });
342
+ if (row.invalid.length) bad.push(row);
343
+ }
344
+
345
+ return bad;
346
+ }
347
+
348
+ /** The rows Submit sends: filled in, and not already added. */
349
+ export function bulkRowsToSubmit(rows: BulkVehicleRow[]): BulkVehicleRow[] {
350
+ return rows.filter(
351
+ (row) => row.status !== "added" && !isBulkRowEmpty(row),
352
+ );
353
+ }
354
+
355
+ export function bulkRowCounts(rows: BulkVehicleRow[]) {
356
+ let added = 0;
357
+ let failed = 0;
358
+ let pending = 0;
359
+ for (const row of rows) {
360
+ if (row.status === "added") added++;
361
+ else if (row.status === "failed") failed++;
362
+ else if (!isBulkRowEmpty(row)) pending++;
363
+ }
364
+ return { added, failed, pending, total: added + failed + pending };
365
+ }
366
+
367
+ /**
368
+ * A block of cells copied from Excel, Sheets or a CSV, as a grid of text.
369
+ *
370
+ * Tabs separate columns (what a spreadsheet puts on the clipboard) unless
371
+ * there is not a single tab, in which case commas do - someone pasting a CSV
372
+ * line means the same thing. Quoted cells keep their commas. Blank lines go.
373
+ */
374
+ export function parsePastedGrid(text: unknown): string[][] {
375
+ const body = String(text ?? "").replace(/\r\n?/g, "\n").trim();
376
+ if (!body) return [];
377
+
378
+ const byTab = body.includes("\t");
379
+
380
+ return body
381
+ .split("\n")
382
+ .map((line) => (byTab ? line.split("\t") : splitCsvLine(line)))
383
+ .map((cells) => cells.map((cell) => cell.trim()))
384
+ .filter((cells) => cells.some((cell) => cell !== ""));
385
+ }
386
+
387
+ function splitCsvLine(line: string): string[] {
388
+ const cells: string[] = [];
389
+ let cell = "";
390
+ let quoted = false;
391
+
392
+ for (let index = 0; index < line.length; index++) {
393
+ const character = line[index];
394
+ if (character === '"') {
395
+ if (quoted && line[index + 1] === '"') {
396
+ cell += '"';
397
+ index++;
398
+ } else {
399
+ quoted = !quoted;
400
+ }
401
+ // eslint-disable-next-line no-continue
402
+ continue;
403
+ }
404
+ if (character === "," && !quoted) {
405
+ cells.push(cell);
406
+ cell = "";
407
+ continue;
408
+ }
409
+ cell += character;
410
+ }
411
+
412
+ cells.push(cell);
413
+ return cells;
414
+ }
415
+
416
+ /** Find a block / level / unit by the NAME a pasted sheet carries. */
417
+ export function matchOptionByTitle(
418
+ options: Array<{ title?: string; value?: string }>,
419
+ title: unknown,
420
+ ): string {
421
+ const wanted = String(title ?? "").trim().toLowerCase();
422
+ if (!wanted) return "";
423
+ const hit = options.find(
424
+ (option) => String(option.title ?? "").trim().toLowerCase() === wanted,
425
+ );
426
+ return hit?.value ? String(hit.value) : "";
427
+ }
428
+
429
+ /* --------------------------------------------------------------------------
430
+ * The sheet behaviour: a selected range of cells, copy and paste between
431
+ * cells, and the fill handle that drags a value down a column.
432
+ *
433
+ * All of it is arithmetic over row and column numbers, so the grid component
434
+ * only has to draw what these work out.
435
+ * ----------------------------------------------------------------------- */
436
+
437
+ export type CellRef = { row: number; col: number };
438
+ export type CellRange = { top: number; left: number; bottom: number; right: number };
439
+
440
+ /** The rectangle two corners make, whichever way round they were given. */
441
+ export function normaliseRange(a: CellRef, b: CellRef): CellRange {
442
+ return {
443
+ top: Math.min(a.row, b.row),
444
+ bottom: Math.max(a.row, b.row),
445
+ left: Math.min(a.col, b.col),
446
+ right: Math.max(a.col, b.col),
447
+ };
448
+ }
449
+
450
+ export function isInRange(range: CellRange, row: number, col: number): boolean {
451
+ return (
452
+ row >= range.top && row <= range.bottom && col >= range.left && col <= range.right
453
+ );
454
+ }
455
+
456
+ /** The selected cells as text, tab-separated - what a spreadsheet expects. */
457
+ export function rangeToTsv(
458
+ range: CellRange,
459
+ valueAt: (row: number, col: number) => string,
460
+ ): string {
461
+ const lines: string[] = [];
462
+ for (let row = range.top; row <= range.bottom; row++) {
463
+ const cells: string[] = [];
464
+ for (let col = range.left; col <= range.right; col++) {
465
+ cells.push(String(valueAt(row, col) ?? ""));
466
+ }
467
+ lines.push(cells.join("\t"));
468
+ }
469
+ return lines.join("\n");
470
+ }
471
+
472
+ /**
473
+ * Where a pasted block of cells lands when it is dropped at `start`.
474
+ *
475
+ * Cells past the last column are dropped - a sheet does not grow sideways -
476
+ * and `extraRows` says how many rows have to be added at the bottom to hold
477
+ * the rest, which is what a spreadsheet does when you paste past the end.
478
+ */
479
+ export function planPaste(
480
+ grid: string[][],
481
+ start: CellRef,
482
+ size: { rows: number; cols: number },
483
+ ): { writes: Array<{ row: number; col: number; value: string }>; extraRows: number } {
484
+ const writes: Array<{ row: number; col: number; value: string }> = [];
485
+ let lastRow = start.row;
486
+
487
+ grid.forEach((cells, rowOffset) => {
488
+ const row = start.row + rowOffset;
489
+ lastRow = Math.max(lastRow, row);
490
+ cells.forEach((value, colOffset) => {
491
+ const col = start.col + colOffset;
492
+ if (col >= size.cols) return;
493
+ writes.push({ row, col, value });
494
+ });
495
+ });
496
+
497
+ return { writes, extraRows: Math.max(0, lastRow + 1 - size.rows) };
498
+ }
499
+
500
+ /**
501
+ * Dragging the fill handle from the selection down (or up) to `toRow`.
502
+ *
503
+ * The selection's own values repeat over the rows it is dragged across, which
504
+ * is what a spreadsheet does with a block of cells; one cell dragged down is
505
+ * that cell copied down. Rows inside the selection are left alone.
506
+ */
507
+ export function planFill(
508
+ selection: CellRange,
509
+ toRow: number,
510
+ valueAt: (row: number, col: number) => string,
511
+ ): Array<{ row: number; col: number; value: string }> {
512
+ const writes: Array<{ row: number; col: number; value: string }> = [];
513
+ const height = selection.bottom - selection.top + 1;
514
+
515
+ const target = (row: number, step: number) => {
516
+ for (let col = selection.left; col <= selection.right; col++) {
517
+ const source = selection.top + ((step % height) + height) % height;
518
+ writes.push({ row, col, value: String(valueAt(source, col) ?? "") });
519
+ }
520
+ };
521
+
522
+ if (toRow > selection.bottom) {
523
+ for (let row = selection.bottom + 1, step = 0; row <= toRow; row++, step++) {
524
+ target(row, step);
525
+ }
526
+ } else if (toRow < selection.top) {
527
+ for (let row = selection.top - 1, step = -1; row >= toRow; row--, step--) {
528
+ target(row, step);
529
+ }
530
+ }
531
+
532
+ return writes;
533
+ }
534
+
535
+ /** How many rows the sheet can be set to, and the one it opens with. */
536
+ export const BULK_SHEET_SIZES = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000];
537
+ export const BULK_SHEET_DEFAULT_SIZE = 100;
538
+
539
+ /** Most rows one request may carry - the endpoint's own limit. */
540
+ export const BULK_SUBMIT_BATCH = 100;
541
+
542
+ /**
543
+ * Grow or shrink the sheet to `target` rows.
544
+ *
545
+ * Growing adds empty rows at the bottom. Shrinking only ever drops rows
546
+ * NOBODY HAS TYPED IN: a row with anything in it, or one already sent, stays
547
+ * wherever it is, so choosing a smaller size can never throw work away.
548
+ */
549
+ export function resizeBulkRows(
550
+ rows: BulkVehicleRow[],
551
+ target: number,
552
+ ): BulkVehicleRow[] {
553
+ const wanted = Math.max(1, Math.floor(target) || 0);
554
+
555
+ if (rows.length < wanted) {
556
+ const grown = rows.slice();
557
+ while (grown.length < wanted) grown.push(emptyBulkRow());
558
+ return grown;
559
+ }
560
+
561
+ const kept = rows.slice();
562
+ for (let index = kept.length - 1; index >= 0 && kept.length > wanted; index--) {
563
+ const row = kept[index];
564
+ if (row.status === "added" || row.status === "failed" || !isBulkRowEmpty(row)) {
565
+ continue;
566
+ }
567
+ kept.splice(index, 1);
568
+ }
569
+
570
+ return kept.length ? kept : [emptyBulkRow()];
571
+ }
572
+
573
+ /** The rows to send, split into requests the endpoint will accept. */
574
+ export function bulkSubmitBatches(
575
+ rows: BulkVehicleRow[],
576
+ size = BULK_SUBMIT_BATCH,
577
+ ): BulkVehicleRow[][] {
578
+ const sending = bulkRowsToSubmit(rows);
579
+ const batches: BulkVehicleRow[][] = [];
580
+ for (let index = 0; index < sending.length; index += size) {
581
+ batches.push(sending.slice(index, index + size));
582
+ }
583
+ return batches;
584
+ }