mapa-library-ui 2.11.0 → 2.13.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,790 @@
1
+ import * as i0 from '@angular/core';
2
+ import { Injectable } from '@angular/core';
3
+
4
+ class ExcelExportCancelledError extends Error {
5
+ constructor() {
6
+ super('Exportação cancelada.');
7
+ this.name = 'ExcelExportCancelledError';
8
+ }
9
+ }
10
+
11
+ function excelFileName(value) {
12
+ return (value
13
+ .replace(/\.xlsx$/i, '')
14
+ .normalize('NFD')
15
+ .replace(/[\u0300-\u036f]/g, '')
16
+ .replace(/[^a-zA-Z0-9-_]+/g, '_')
17
+ .replace(/_{2,}/g, '_')
18
+ .replace(/^_+|_+$/g, '') || 'export');
19
+ }
20
+ function excelFileNameWithDate(name, reference = new Date()) {
21
+ return `${name}_${reference.getFullYear()}-${String(reference.getMonth() + 1).padStart(2, '0')}-${String(reference.getDate()).padStart(2, '0')}`;
22
+ }
23
+ function fitExcelSheetTitle(title, maxLength) {
24
+ if (title.length <= maxLength)
25
+ return title;
26
+ const truncated = title.slice(0, maxLength);
27
+ if (/\s/.test(title[maxLength]))
28
+ return truncated.trimEnd();
29
+ const wordEnd = truncated.lastIndexOf(' ');
30
+ return wordEnd > 0 ? truncated.slice(0, wordEnd) : truncated;
31
+ }
32
+ function excelSheetName(value) {
33
+ const name = value
34
+ .replace(/[\\/?*[\]:\x00-\x1f]/g, ' ')
35
+ .trim()
36
+ .replace(/^'+|'+$/g, '');
37
+ const fitted = fitExcelSheetTitle(name, 31).replace(/'+$/g, '');
38
+ // "History" is reserved by Excel's change tracking.
39
+ return !fitted ? 'Sheet1' : /^history$/i.test(fitted) ? `${fitted}_` : fitted;
40
+ }
41
+ function uniqueExcelSheetNames(values) {
42
+ const used = new Set();
43
+ return values.map((value) => {
44
+ const base = excelSheetName(value);
45
+ let name = base;
46
+ let counter = 2;
47
+ while (used.has(name.toLowerCase())) {
48
+ const suffix = ` (${counter++})`;
49
+ name = fitExcelSheetTitle(base, 31 - suffix.length) + suffix;
50
+ }
51
+ used.add(name.toLowerCase());
52
+ return name;
53
+ });
54
+ }
55
+
56
+ const MAPA_EXCEL_COLORS = {
57
+ orange: 'FFFF560B',
58
+ darkOrange: 'FFD94021',
59
+ pale: 'FFFFEDE6',
60
+ accent: 'FFA8321A',
61
+ ink: 'FF162F42',
62
+ text: 'FF41566A',
63
+ border: 'FFDCE5E8',
64
+ green: 'FF065156',
65
+ red: 'FFB3341B',
66
+ };
67
+ const MAPA_EXCEL_STATUS_COLORS = {
68
+ ok: { background: 'FFDDF1F2', text: 'FF065156' },
69
+ info: { background: 'FFE4EEF0', text: 'FF162F42' },
70
+ warning: { background: 'FFFFF4C7', text: 'FF6E4A00' },
71
+ neutral: { background: 'FFEEF1F3', text: 'FF4F5F6B' },
72
+ danger: { background: 'FFFDE9E4', text: 'FFB3341B' },
73
+ };
74
+ function fillExcelCell(sheet, row, col, color) {
75
+ sheet.getCell(row, col).fill = {
76
+ type: 'pattern',
77
+ pattern: 'solid',
78
+ fgColor: { argb: color },
79
+ };
80
+ }
81
+ /** The two banner geometries used by the original MF reports. */
82
+ function applyMapaExcelBanner(sheet, options) {
83
+ const heights = options.rowHeights ?? [10, 40, 32, 12, 4];
84
+ for (let row = 1; row <= 5; row++) {
85
+ for (let col = 1; col <= options.columnCount; col++) {
86
+ fillExcelCell(sheet, row, col, row === 5 ? MAPA_EXCEL_COLORS.darkOrange : MAPA_EXCEL_COLORS.orange);
87
+ }
88
+ sheet.getRow(row).height = heights[row - 1];
89
+ }
90
+ sheet.addImage(options.logoId, {
91
+ tl: { col: 0.1, row: 1.1 },
92
+ ext: { width: 150, height: 33 },
93
+ ...(options.absoluteLogo ? { editAs: 'absolute' } : {}),
94
+ });
95
+ sheet.mergeCells(3, 1, 4, options.titleEndColumn ?? options.columnCount);
96
+ const title = sheet.getCell(3, 1);
97
+ title.value = options.title;
98
+ title.font = {
99
+ name: 'Arial',
100
+ size: 18,
101
+ bold: true,
102
+ color: { argb: 'FFFFFFFF' },
103
+ };
104
+ title.alignment = options.titleAlignment ?? { vertical: 'middle', indent: 1 };
105
+ }
106
+ function styleMapaExcelHeaderCell(sheet, row, col, headerRow = 9) {
107
+ const header = row === headerRow;
108
+ fillExcelCell(sheet, row, col, header ? MAPA_EXCEL_COLORS.pale : 'FFFFFFFF');
109
+ const cell = sheet.getCell(row, col);
110
+ cell.font = {
111
+ name: 'Arial',
112
+ size: header ? 8 : 10,
113
+ bold: true,
114
+ color: { argb: MAPA_EXCEL_COLORS.accent },
115
+ };
116
+ cell.alignment = {
117
+ vertical: 'middle',
118
+ wrapText: true,
119
+ horizontal: col >= 9 ? 'right' : header ? 'center' : 'left',
120
+ indent: 1,
121
+ };
122
+ const line = {
123
+ style: 'thin',
124
+ color: { argb: MAPA_EXCEL_COLORS.orange },
125
+ };
126
+ cell.border = header ? { bottom: line } : { top: line };
127
+ }
128
+
129
+ const quote = (value) => `"${String(value).replace(/"/g, '""')}"`;
130
+ const scalar = (value) => value && typeof value === 'object' && 'formula' in value
131
+ ? value.result
132
+ : value;
133
+ /** Finalize a branded table after widths and data have been assigned. */
134
+ function finishMapaExcelTable(sheet, request) {
135
+ const columns = request.columns;
136
+ const count = Math.max(2, columns.length);
137
+ const end = request.rows.length + 9;
138
+ const range = (index) => `${sheet.getColumn(index + 1).letter}10:${sheet.getColumn(index + 1).letter}${Math.max(10, end)}`;
139
+ const values = (index) => request.rows.map((_, row) => scalar(sheet.getCell(row + 10, index + 1).value));
140
+ sheet.autoFilter = {
141
+ from: { row: 9, column: 1 },
142
+ to: { row: Math.max(9, end), column: columns.length },
143
+ };
144
+ sheet.pageSetup.printTitlesRow = '9:9';
145
+ const summaryFormula = [
146
+ request.rows.length ? `ROWS(A10:A${end})&" registros"` : '0&" registros"',
147
+ ];
148
+ const summaryResult = [
149
+ `${request.rows.length.toLocaleString('pt-BR')} registros`,
150
+ ];
151
+ for (const indicator of (request.indicators ?? []).slice(0, 2)) {
152
+ const index = columns.findIndex((column) => column.key === indicator.key);
153
+ if (index < 0)
154
+ continue;
155
+ let formula = '0';
156
+ let result = 0;
157
+ const data = values(index);
158
+ if (request.rows.length) {
159
+ if (indicator.operation === 'countIf') {
160
+ formula = `COUNTIF(${range(index)},${quote(indicator.criteria ?? '')})`;
161
+ result = data.filter((value) => String(value ?? '').toLocaleLowerCase() ===
162
+ String(indicator.criteria ?? '').toLocaleLowerCase()).length;
163
+ }
164
+ else if (indicator.operation === 'sumIf') {
165
+ // Sign criteria cover financial additions and usage without evaluating arbitrary expressions.
166
+ const sign = String(indicator.criteria);
167
+ if (!['>0', '<0'].includes(sign))
168
+ throw new Error('Critério de soma inválido. Use >0 ou <0.');
169
+ formula = `SUMIF(${range(index)},${quote(sign)})`;
170
+ result = data.reduce((sum, value) => sum +
171
+ (typeof value === 'number' &&
172
+ (sign === '>0' ? value > 0 : value < 0)
173
+ ? value
174
+ : 0), 0);
175
+ }
176
+ else {
177
+ formula = `SUM(${range(index)})`;
178
+ result = data.reduce((sum, value) => sum + (typeof value === 'number' ? value : 0), 0);
179
+ }
180
+ }
181
+ if (indicator.absolute) {
182
+ formula = `ABS(${formula})`;
183
+ result = Math.abs(result);
184
+ }
185
+ const format = indicator.numFmt ?? '#,##0';
186
+ const digits = format.match(/\.(0+)/)?.[1].length ?? 0;
187
+ const formatted = new Intl.NumberFormat('pt-BR', {
188
+ minimumFractionDigits: digits,
189
+ maximumFractionDigits: digits,
190
+ ...(format.includes('R$')
191
+ ? { style: 'currency', currency: 'BRL' }
192
+ : format.includes('%')
193
+ ? { style: 'percent' }
194
+ : {}),
195
+ }).format(result);
196
+ summaryFormula.push(`TEXT(${formula},${quote(format)})&${quote(` ${indicator.label}`)}`);
197
+ summaryResult.push(`${formatted} ${indicator.label}`);
198
+ }
199
+ const split = Math.max(1, Math.floor(count / 2));
200
+ sheet.mergeCells(3, split + 1, 4, count);
201
+ const summary = sheet.getCell(3, split + 1);
202
+ summary.value = {
203
+ formula: summaryFormula.join('&" · "&'),
204
+ result: summaryResult.join(' · '),
205
+ };
206
+ summary.font = {
207
+ name: 'Arial',
208
+ size: 14,
209
+ bold: true,
210
+ color: { argb: 'FFFFFFFF' },
211
+ };
212
+ summary.alignment = {
213
+ horizontal: 'right',
214
+ vertical: 'middle',
215
+ wrapText: true,
216
+ indent: 1,
217
+ };
218
+ if (request.context) {
219
+ const context = request.context;
220
+ const date = context.generatedAt.toLocaleString('pt-BR');
221
+ for (const row of [6, 7]) {
222
+ sheet.mergeCells(row, 1, row, count);
223
+ sheet.getRow(row).height = 24;
224
+ const cell = sheet.getCell(row, 1);
225
+ cell.font = {
226
+ name: 'Arial',
227
+ size: 9,
228
+ bold: row === 7 && context.filters.length > 0,
229
+ color: {
230
+ argb: row === 7 && context.filters.length ? MAPA_EXCEL_COLORS.accent : MAPA_EXCEL_COLORS.text,
231
+ },
232
+ };
233
+ cell.alignment = { vertical: 'middle', wrapText: true, indent: 1 };
234
+ if (row === 7 && context.filters.length)
235
+ for (let col = 1; col <= count; col++) {
236
+ sheet.getCell(row, col).fill = {
237
+ type: 'pattern',
238
+ pattern: 'solid',
239
+ fgColor: { argb: MAPA_EXCEL_COLORS.pale },
240
+ };
241
+ }
242
+ }
243
+ sheet.getCell(6, 1).value =
244
+ `${context.module} · ${context.company} · Exportado em ${date} por ${context.user}`;
245
+ sheet.getCell(7, 1).value =
246
+ `Filtros aplicados: ${context.filters.length ? context.filters.join(' · ') : 'nenhum'}`;
247
+ sheet.getRow(8).height = 6;
248
+ }
249
+ columns.forEach((column, index) => {
250
+ if (request.rows.length && column.status?.length) {
251
+ const letter = sheet.getColumn(index + 1).letter;
252
+ sheet.addConditionalFormatting({
253
+ ref: range(index),
254
+ rules: column.status.map((status, priority) => {
255
+ const tone = MAPA_EXCEL_STATUS_COLORS[status.tone];
256
+ return {
257
+ type: 'expression',
258
+ priority: priority + 1,
259
+ formulae: [`${letter}10=${quote(status.value)}`],
260
+ style: {
261
+ font: { bold: true, color: { argb: tone.text } },
262
+ fill: {
263
+ type: 'pattern',
264
+ pattern: 'solid',
265
+ bgColor: { argb: tone.background },
266
+ fgColor: { argb: tone.background },
267
+ },
268
+ },
269
+ };
270
+ }),
271
+ });
272
+ }
273
+ });
274
+ if (columns.some((column) => column.total)) {
275
+ const row = sheet.getRow(end + 1);
276
+ const labelIndex = columns.findIndex((column) => !column.total);
277
+ if (labelIndex >= 0)
278
+ row.getCell(labelIndex + 1).value = 'TOTAL';
279
+ columns.forEach((column, index) => {
280
+ const cell = row.getCell(index + 1);
281
+ if (column.total)
282
+ cell.value = {
283
+ formula: request.rows.length ? `SUM(${range(index)})` : '0',
284
+ result: values(index).reduce((sum, value) => sum + (typeof value === 'number' ? value : 0), 0),
285
+ };
286
+ cell.font = {
287
+ name: 'Arial',
288
+ size: 10,
289
+ bold: true,
290
+ color: { argb: MAPA_EXCEL_COLORS.accent },
291
+ };
292
+ cell.border = { top: { style: 'thin', color: { argb: MAPA_EXCEL_COLORS.orange } } };
293
+ if (column.numFmt)
294
+ cell.numFmt = column.numFmt;
295
+ });
296
+ row.height = 22;
297
+ }
298
+ if (request.context) {
299
+ const footerRow = end + (columns.some((column) => column.total) ? 3 : 2);
300
+ sheet.mergeCells(footerRow, 1, footerRow, count);
301
+ const footer = sheet.getCell(footerRow, 1);
302
+ footer.value =
303
+ 'Documento gerado automaticamente pela plataforma Mapa HDS. Os dados respeitam as permissões de quem exportou.';
304
+ footer.font = {
305
+ name: 'Arial',
306
+ size: 8,
307
+ italic: true,
308
+ color: { argb: MAPA_EXCEL_COLORS.text },
309
+ };
310
+ footer.alignment = { wrapText: true, vertical: 'middle', indent: 1 };
311
+ sheet.getRow(footerRow).height = 24;
312
+ sheet.pageSetup.printArea = `A1:${sheet.getColumn(count).letter}${footerRow}`;
313
+ }
314
+ }
315
+
316
+ function resolveWorkbookConstructor(module) {
317
+ const constructor = module.default?.Workbook ?? module.Workbook;
318
+ if (typeof constructor !== 'function')
319
+ throw new Error('Não foi possível carregar a biblioteca de exportação Excel.');
320
+ return constructor;
321
+ }
322
+ async function createExcelWorkbook() {
323
+ const Constructor = resolveWorkbookConstructor(await import('exceljs'));
324
+ return new Constructor();
325
+ }
326
+ async function addMapaExcelLogo(book) {
327
+ const { MAPA_EXCEL_LOGO } = await import('./mapa-library-ui-src-lib-core-excel-export-excel-export.logo-DV7jykE5.mjs');
328
+ return book.addImage({ base64: MAPA_EXCEL_LOGO, extension: 'png' });
329
+ }
330
+ function checkCancelled(isCancelled) {
331
+ if (isCancelled())
332
+ throw new ExcelExportCancelledError();
333
+ }
334
+ function cellValue(value) {
335
+ if (value == null)
336
+ return null;
337
+ if (value instanceof Date) {
338
+ if (!Number.isFinite(value.getTime()))
339
+ throw new Error('Data inválida na exportação.');
340
+ return value;
341
+ }
342
+ if (typeof value === 'number')
343
+ return Number.isFinite(value) ? value : null;
344
+ if (typeof value === 'object' && 'formula' in value) {
345
+ return { formula: value.formula, result: cellValue(value.result) };
346
+ }
347
+ if (typeof value === 'string' && value.length > 32767)
348
+ throw new Error('Uma célula excede o limite de 32.767 caracteres do Excel.');
349
+ if (!['string', 'number', 'boolean'].includes(typeof value))
350
+ throw new Error('Valor de célula inválido. Use um extrator de coluna para formatá-lo.');
351
+ return value;
352
+ }
353
+ /** Adds a table to an existing workbook; no domain or HTTP dependencies. */
354
+ async function addExcelTable(book, request, options = {}) {
355
+ const isCancelled = options.isCancelled ?? (() => false);
356
+ checkCancelled(isCancelled);
357
+ if (!request.columns.length)
358
+ throw new Error('Informe pelo menos uma coluna.');
359
+ if (request.columns.length > 16384)
360
+ throw new Error('Quantidade de colunas excede o limite do Excel.');
361
+ const branded = request.mode !== 'plain';
362
+ if ((request.metadata?.length ?? 0) > 3)
363
+ throw new Error('Informe no máximo três linhas de metadados.');
364
+ const headerRow = branded ? 9 : 1;
365
+ if (request.rows.length + headerRow > 1048576)
366
+ throw new Error('Quantidade de linhas excede o limite do Excel.');
367
+ request.columns.forEach((column) => {
368
+ if (!column.value && !column.key)
369
+ throw new Error('A coluna deve ter uma chave ou um extrator.');
370
+ if (column.width !== undefined &&
371
+ (!Number.isFinite(column.width) ||
372
+ column.width <= 0 ||
373
+ column.width > 255))
374
+ throw new Error('Largura de coluna inválida.');
375
+ });
376
+ const sheet = book.addWorksheet(request.sheetName, branded
377
+ ? {
378
+ views: [{ state: 'frozen', ySplit: 9, showGridLines: false }],
379
+ pageSetup: {
380
+ orientation: 'landscape',
381
+ fitToPage: true,
382
+ fitToWidth: 1,
383
+ fitToHeight: 0,
384
+ },
385
+ }
386
+ : {});
387
+ const count = branded
388
+ ? Math.max(request.columns.length, 2)
389
+ : request.columns.length;
390
+ sheet.getRow(headerRow).values = request.columns.map((column) => branded ? column.label.toLocaleUpperCase() : column.label);
391
+ const widths = request.columns.map((column) => column.label.length);
392
+ if (branded) {
393
+ request.columns.forEach((_, index) => styleMapaExcelHeaderCell(sheet, headerRow, index + 1));
394
+ sheet.getRow(headerRow).height = 30;
395
+ sheet.pageSetup.printTitlesRow = '9:9';
396
+ }
397
+ let lastYield = performance.now();
398
+ for (let index = 0; index < request.rows.length; index++) {
399
+ checkCancelled(isCancelled);
400
+ const row = sheet.getRow(index + headerRow + 1);
401
+ if (branded || request.rowHeight !== undefined)
402
+ row.height = request.rowHeight ?? 19.5;
403
+ request.columns.forEach((column, columnIndex) => {
404
+ const value = cellValue(column.value
405
+ ? column.value(request.rows[index], index)
406
+ : request.rows[index][column.key]);
407
+ const cell = row.getCell(columnIndex + 1);
408
+ cell.value = value;
409
+ if (branded) {
410
+ cell.font = {
411
+ name: 'Arial',
412
+ size: 10,
413
+ bold: columnIndex === 0,
414
+ color: { argb: columnIndex === 0 ? MAPA_EXCEL_COLORS.ink : MAPA_EXCEL_COLORS.text },
415
+ };
416
+ cell.alignment = { vertical: 'middle', wrapText: true, indent: 1 };
417
+ cell.border = {
418
+ bottom: { style: 'thin', color: { argb: MAPA_EXCEL_COLORS.border } },
419
+ };
420
+ }
421
+ if (column.numFmt)
422
+ cell.numFmt = column.numFmt;
423
+ else if (value instanceof Date)
424
+ cell.numFmt = 'dd/mm/yyyy hh:mm';
425
+ else if (branded && typeof value === 'number')
426
+ cell.numFmt = Number.isInteger(value) ? '#,##0' : '#,##0.###############';
427
+ widths[columnIndex] = Math.max(widths[columnIndex], value instanceof Date ? 16 : String(value ?? '').length);
428
+ });
429
+ // Let cancellation and the UI run between batches; ZIP serialization may still require a worker.
430
+ if (index % 500 === 499 && performance.now() - lastYield > 16) {
431
+ options.onProgress?.({ phase: 'building', completed: index + 1, total: request.rows.length });
432
+ await new Promise((resolve) => setTimeout(resolve, 0));
433
+ lastYield = performance.now();
434
+ }
435
+ }
436
+ request.columns.forEach((column, index) => {
437
+ sheet.getColumn(index + 1).width =
438
+ column.width ?? Math.min(60, Math.max(12, widths[index] + 2));
439
+ });
440
+ if (branded && request.columns.length === 1)
441
+ sheet.getColumn(2).width = 28;
442
+ // ExcelJS resolves fractional image anchors using the current column widths.
443
+ if (branded) {
444
+ const logoId = options.logoId ?? (await addMapaExcelLogo(book));
445
+ checkCancelled(isCancelled);
446
+ applyMapaExcelBanner(sheet, {
447
+ columnCount: count,
448
+ logoId,
449
+ title: request.title ?? request.sheetName,
450
+ titleEndColumn: Math.max(1, Math.floor(count / 2)),
451
+ rowHeights: [10, 40, 32, 12, 3],
452
+ titleAlignment: { vertical: 'middle', indent: 1, wrapText: true },
453
+ });
454
+ (request.context ? [] : request.metadata ?? []).forEach((text, index) => {
455
+ const row = index + 6;
456
+ sheet.mergeCells(row, 1, row, count);
457
+ const cell = sheet.getCell(row, 1);
458
+ cell.value = text;
459
+ cell.font = {
460
+ name: 'Arial',
461
+ size: 10,
462
+ color: { argb: MAPA_EXCEL_COLORS.ink },
463
+ };
464
+ cell.alignment = { wrapText: true, vertical: 'middle', indent: 1 };
465
+ sheet.getRow(row).height = 28;
466
+ });
467
+ finishMapaExcelTable(sheet, request);
468
+ }
469
+ options.onProgress?.({ phase: 'building', completed: request.rows.length, total: request.rows.length });
470
+ checkCancelled(isCancelled);
471
+ await request.customize?.(sheet);
472
+ return sheet;
473
+ }
474
+ async function buildExcelWorkbook(request, isCancelled = () => false, onProgress) {
475
+ checkCancelled(isCancelled);
476
+ if (!request.sheets.length)
477
+ throw new Error('Informe pelo menos uma aba.');
478
+ const book = await createExcelWorkbook();
479
+ checkCancelled(isCancelled);
480
+ book.creator = request.creator ?? 'Mapa HDS';
481
+ book.created = request.created ?? new Date();
482
+ const names = uniqueExcelSheetNames(request.sheets.map((sheet) => sheet.sheetName));
483
+ const logoId = request.sheets.some((sheet) => sheet.mode !== 'plain')
484
+ ? await addMapaExcelLogo(book)
485
+ : undefined;
486
+ const total = request.sheets.reduce((sum, sheet) => sum + sheet.rows.length, 0);
487
+ let completed = 0;
488
+ for (const [index, sheet] of request.sheets.entries()) {
489
+ await addExcelTable(book, {
490
+ ...sheet,
491
+ sheetName: names[index],
492
+ title: sheet.title ?? sheet.sheetName,
493
+ }, { logoId, isCancelled, onProgress: (progress) => onProgress?.({ ...progress, completed: completed + (progress.completed ?? 0), total }) });
494
+ completed += sheet.rows.length;
495
+ }
496
+ checkCancelled(isCancelled);
497
+ await request.customize?.(book);
498
+ checkCancelled(isCancelled);
499
+ return book;
500
+ }
501
+ async function serializeExcelWorkbook(book) {
502
+ const buffer = await book.xlsx.writeBuffer();
503
+ return new Uint8Array(buffer).buffer;
504
+ }
505
+ /** May be called from a consumer-owned module worker. Functions cannot be cloned. */
506
+ async function serializeExcelRequest(request, onProgress) {
507
+ const book = await buildExcelWorkbook(request, undefined, onProgress);
508
+ onProgress?.({ phase: 'serializing' });
509
+ return serializeExcelWorkbook(book);
510
+ }
511
+
512
+ const EXPORT_FILE_ROW_LIMIT = 100_000;
513
+ /** Encode browser-local calendar fields for timezone-free Excel and CSV cells. */
514
+ function toExportDate(value) {
515
+ if (!Number.isFinite(value.getTime()))
516
+ throw new Error('Data inválida na exportação.');
517
+ return new Date(value.getTime() - value.getTimezoneOffset() * 60_000);
518
+ }
519
+ const exportSlug = (value) => value
520
+ .normalize('NFD')
521
+ .replace(/[\u0300-\u036f]/g, '')
522
+ .toLowerCase()
523
+ .replace(/[^a-z0-9]+/g, '-')
524
+ .replace(/^-|-$/g, '') || 'exportacao';
525
+ function exportFileBase(listing, company, date) {
526
+ const pad = (value) => String(value).padStart(2, '0');
527
+ return `mapahds_${exportSlug(listing)}_${exportSlug(company)}_${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}`;
528
+ }
529
+ /** Greedy packing preserves dataset order and counts records across all sheets. */
530
+ function splitExportSheets(sheets, limit = EXPORT_FILE_ROW_LIMIT) {
531
+ if (!Number.isInteger(limit) || limit < 1)
532
+ throw new Error('Limite de registros inválido.');
533
+ const parts = [[]];
534
+ let used = 0;
535
+ for (const sheet of sheets) {
536
+ if (!sheet.rows.length) {
537
+ parts[parts.length - 1].push({ ...sheet, rows: [] });
538
+ continue;
539
+ }
540
+ for (let offset = 0; offset < sheet.rows.length;) {
541
+ if (used === limit) {
542
+ parts.push([]);
543
+ used = 0;
544
+ }
545
+ const length = Math.min(limit - used, sheet.rows.length - offset);
546
+ parts[parts.length - 1].push({
547
+ ...sheet,
548
+ rows: sheet.rows.slice(offset, offset + length),
549
+ });
550
+ offset += length;
551
+ used += length;
552
+ }
553
+ }
554
+ return parts;
555
+ }
556
+ function encodeExportCsv(sheet, onProgress) {
557
+ const encode = (input) => {
558
+ const value = input && typeof input === 'object' && 'formula' in input
559
+ ? input.result
560
+ : input;
561
+ if (value instanceof Date && !Number.isFinite(value.getTime()))
562
+ throw new Error('Data inválida na exportação.');
563
+ if (typeof value === 'number' && !Number.isFinite(value))
564
+ return '';
565
+ const text = value == null
566
+ ? ''
567
+ : value instanceof Date
568
+ ? value.toLocaleString('pt-BR', { timeZone: 'UTC' })
569
+ : String(value);
570
+ // Quoting alone does not stop spreadsheet apps interpreting user text as a formula.
571
+ const literal = typeof value === 'string' && /^[=+\-@\t\r]/.test(text)
572
+ ? `'${text}`
573
+ : text;
574
+ return /[;"\r\n]/.test(literal)
575
+ ? `"${literal.replace(/"/g, '""')}"`
576
+ : literal;
577
+ };
578
+ const lines = [sheet.columns.map((column) => encode(column.label)).join(';')];
579
+ sheet.rows.forEach((row, index) => {
580
+ lines.push(sheet.columns
581
+ .map((column) => encode(column.value ? column.value(row, index) : row[column.key]))
582
+ .join(';'));
583
+ if (index % 5_000 === 4_999)
584
+ onProgress?.(index + 1, sheet.rows.length);
585
+ });
586
+ onProgress?.(sheet.rows.length, sheet.rows.length);
587
+ return new TextEncoder().encode('\uFEFF' + lines.join('\r\n') + '\r\n')
588
+ .buffer;
589
+ }
590
+ /** HTTP and domain adaptation remain in load; this helper verifies completeness. */
591
+ async function collectExportPages(options) {
592
+ const result = [];
593
+ const keys = new Set();
594
+ let pageIndex = 1;
595
+ let pageSize = Math.max(1, options.totalCount);
596
+ let expected;
597
+ while (true) {
598
+ options.signal.throwIfAborted();
599
+ const page = await options.load(pageIndex, pageSize, options.signal);
600
+ options.signal.throwIfAborted();
601
+ if (!Number.isInteger(page.totalCount) ||
602
+ page.totalCount < 0 ||
603
+ page.totalCount !== options.totalCount ||
604
+ (expected !== undefined && expected !== page.totalCount) ||
605
+ (page.pageIndex !== undefined && page.pageIndex !== pageIndex) ||
606
+ (pageIndex > 1 && page.pageSize !== pageSize))
607
+ throw new Error('Os dados mudaram durante a exportação. Atualize a listagem e tente novamente.');
608
+ expected = page.totalCount;
609
+ for (const row of page.data) {
610
+ const key = options.key(row);
611
+ if (!key || keys.has(key))
612
+ throw new Error('Registros duplicados ou sem identificação na exportação.');
613
+ keys.add(key);
614
+ result.push(row);
615
+ }
616
+ options.onProgress?.(result.length, expected);
617
+ if (result.length === expected)
618
+ return result;
619
+ if (!page.data.length ||
620
+ result.length > expected ||
621
+ !Number.isInteger(page.pageSize) ||
622
+ page.pageSize < 1 ||
623
+ page.data.length !== page.pageSize)
624
+ throw new Error('A API retornou uma exportação incompleta.');
625
+ pageSize = page.pageSize;
626
+ pageIndex++;
627
+ }
628
+ }
629
+
630
+ class MapaExcelExportService {
631
+ createWorkbook() {
632
+ return createExcelWorkbook();
633
+ }
634
+ buildWorkbook(request, isCancelled) {
635
+ return buildExcelWorkbook(request, isCancelled);
636
+ }
637
+ serialize(book) {
638
+ return serializeExcelWorkbook(book);
639
+ }
640
+ async exportTable(request, options) {
641
+ await this.exportWorkbook({ fileName: request.fileName, sheets: [request] }, options);
642
+ }
643
+ async exportWorkbook(request, options = {}) {
644
+ const isCancelled = options.isCancelled ?? (() => false);
645
+ if (isCancelled())
646
+ return;
647
+ try {
648
+ const buffer = await this.generateWorkbook(request, options);
649
+ if (!isCancelled())
650
+ this.download(buffer, request.fileName);
651
+ }
652
+ catch (error) {
653
+ if (error instanceof ExcelExportCancelledError)
654
+ return;
655
+ throw error;
656
+ }
657
+ }
658
+ async generateWorkbook(request, options = {}) {
659
+ const cancelled = options.isCancelled ?? (() => false);
660
+ if (cancelled())
661
+ throw new ExcelExportCancelledError();
662
+ if (options.workerFactory)
663
+ return this.serializeInWorker(request, options.workerFactory, cancelled, options.onProgress);
664
+ const book = await buildExcelWorkbook(request, cancelled, options.onProgress);
665
+ options.onProgress?.({ phase: 'serializing' });
666
+ return this.serialize(book);
667
+ }
668
+ async generateCsv(request, options) {
669
+ if (options.workerFactory)
670
+ return this.serializeInWorker(request, options.workerFactory, options.isCancelled ?? (() => false), options.onProgress, 'csv');
671
+ return encodeExportCsv(request.sheets[0]);
672
+ }
673
+ async save(book, fileName, isCancelled = () => false) {
674
+ if (isCancelled())
675
+ return;
676
+ const buffer = await this.serialize(book);
677
+ if (!isCancelled())
678
+ this.download(buffer, fileName);
679
+ }
680
+ download(buffer, fileName) {
681
+ const url = URL.createObjectURL(new Blob([buffer], {
682
+ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
683
+ }));
684
+ const link = document.createElement('a');
685
+ try {
686
+ link.href = url;
687
+ link.download = `${excelFileName(fileName)}.xlsx`;
688
+ document.body.appendChild(link);
689
+ link.click();
690
+ }
691
+ finally {
692
+ link.remove();
693
+ URL.revokeObjectURL(url);
694
+ }
695
+ }
696
+ serializeInWorker(request, factory, isCancelled, onProgress, format = 'xlsx') {
697
+ return new Promise((resolve, reject) => {
698
+ const worker = factory();
699
+ const finish = (error, buffer) => {
700
+ clearInterval(cancellation);
701
+ worker.terminate();
702
+ if (error)
703
+ reject(error);
704
+ else
705
+ resolve(buffer);
706
+ };
707
+ const cancellation = setInterval(() => {
708
+ if (isCancelled())
709
+ finish(new ExcelExportCancelledError());
710
+ }, 50);
711
+ worker.onmessage = ({ data }) => {
712
+ if ('progress' in data) {
713
+ onProgress?.(data.progress);
714
+ return;
715
+ }
716
+ if ('error' in data)
717
+ finish(new Error(data.error));
718
+ else if (data.buffer instanceof ArrayBuffer)
719
+ finish(undefined, data.buffer);
720
+ else
721
+ finish(new Error('Resposta inválida do worker de exportação.'));
722
+ };
723
+ worker.onerror = (event) => finish(new Error(event.message || 'Falha no worker de exportação.'));
724
+ worker.onmessageerror = () => finish(new Error('Não foi possível receber o arquivo exportado.'));
725
+ try {
726
+ worker.postMessage({ request, format });
727
+ }
728
+ catch (error) {
729
+ finish(error instanceof Error ? error : new Error(String(error)));
730
+ }
731
+ });
732
+ }
733
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.21", ngImport: i0, type: MapaExcelExportService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
734
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.21", ngImport: i0, type: MapaExcelExportService, providedIn: 'root' }); }
735
+ }
736
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.21", ngImport: i0, type: MapaExcelExportService, decorators: [{
737
+ type: Injectable,
738
+ args: [{ providedIn: 'root' }]
739
+ }] });
740
+
741
+ /**
742
+ * A remote's worker URL can have a different origin from the shell. Bootstrap
743
+ * through a local blob, then import the self-contained module with normal CORS.
744
+ * Keep the local name `Worker` at the call site so Angular recognizes the URL.
745
+ */
746
+ function getExcelWorkerConstructor() {
747
+ return class extends globalThis.Worker {
748
+ constructor(scriptURL, options) {
749
+ const url = new URL(scriptURL, globalThis.location.href);
750
+ const bootstrap = url.origin === globalThis.location.origin
751
+ ? undefined
752
+ : URL.createObjectURL(new Blob([`import ${JSON.stringify(url.href)};`], {
753
+ type: 'text/javascript',
754
+ }));
755
+ try {
756
+ super(bootstrap ?? url, { ...options, type: 'module' });
757
+ }
758
+ catch (error) {
759
+ if (bootstrap)
760
+ URL.revokeObjectURL(bootstrap);
761
+ throw error;
762
+ }
763
+ this.bootstrapUrl = bootstrap;
764
+ this.addEventListener('message', () => this.releaseBootstrap(), {
765
+ once: true,
766
+ });
767
+ this.addEventListener('error', () => this.releaseBootstrap(), {
768
+ once: true,
769
+ });
770
+ }
771
+ terminate() {
772
+ this.releaseBootstrap();
773
+ super.terminate();
774
+ }
775
+ releaseBootstrap() {
776
+ if (this.bootstrapUrl)
777
+ URL.revokeObjectURL(this.bootstrapUrl);
778
+ this.bootstrapUrl = undefined;
779
+ }
780
+ };
781
+ }
782
+
783
+ /** Optional Excel export entry point. Never re-export from the package root. */
784
+
785
+ /**
786
+ * Generated bundle index. Do not edit.
787
+ */
788
+
789
+ export { ExcelExportCancelledError, MAPA_EXCEL_COLORS, MAPA_EXCEL_STATUS_COLORS, MapaExcelExportService, addExcelTable, addMapaExcelLogo, applyMapaExcelBanner, buildExcelWorkbook, createExcelWorkbook, excelFileName, excelFileNameWithDate, excelSheetName, fillExcelCell, fitExcelSheetTitle, getExcelWorkerConstructor, resolveWorkbookConstructor, serializeExcelRequest, serializeExcelWorkbook, styleMapaExcelHeaderCell, uniqueExcelSheetNames };
790
+ //# sourceMappingURL=mapa-library-ui-src-lib-core-excel-export.mjs.map