mapa-library-ui 2.13.1 → 2.13.3

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.
Files changed (44) hide show
  1. package/docs/TABLE_EXPORT.md +147 -2
  2. package/fesm2022/mapa-library-ui-src-lib-components-capability.mjs +3 -0
  3. package/fesm2022/mapa-library-ui-src-lib-components-capability.mjs.map +1 -1
  4. package/fesm2022/mapa-library-ui-src-lib-components-chart.mjs +3 -0
  5. package/fesm2022/mapa-library-ui-src-lib-components-chart.mjs.map +1 -1
  6. package/fesm2022/mapa-library-ui-src-lib-components-datepicker.mjs +3 -1
  7. package/fesm2022/mapa-library-ui-src-lib-components-datepicker.mjs.map +1 -1
  8. package/fesm2022/mapa-library-ui-src-lib-components-dropdown-tree.mjs +3 -0
  9. package/fesm2022/mapa-library-ui-src-lib-components-dropdown-tree.mjs.map +1 -1
  10. package/fesm2022/mapa-library-ui-src-lib-components-dropdown.mjs +3 -0
  11. package/fesm2022/mapa-library-ui-src-lib-components-dropdown.mjs.map +1 -1
  12. package/fesm2022/mapa-library-ui-src-lib-components-filters.mjs +3 -0
  13. package/fesm2022/mapa-library-ui-src-lib-components-filters.mjs.map +1 -1
  14. package/fesm2022/mapa-library-ui-src-lib-components-form.mjs +3 -1
  15. package/fesm2022/mapa-library-ui-src-lib-components-form.mjs.map +1 -1
  16. package/fesm2022/mapa-library-ui-src-lib-components-group-report.mjs +3 -1
  17. package/fesm2022/mapa-library-ui-src-lib-components-group-report.mjs.map +1 -1
  18. package/fesm2022/mapa-library-ui-src-lib-components-input.mjs +3 -0
  19. package/fesm2022/mapa-library-ui-src-lib-components-input.mjs.map +1 -1
  20. package/fesm2022/mapa-library-ui-src-lib-components-scale-parameterization.mjs +3 -0
  21. package/fesm2022/mapa-library-ui-src-lib-components-scale-parameterization.mjs.map +1 -1
  22. package/fesm2022/mapa-library-ui-src-lib-components-scale.mjs +3 -0
  23. package/fesm2022/mapa-library-ui-src-lib-components-scale.mjs.map +1 -1
  24. package/fesm2022/mapa-library-ui-src-lib-components-table.mjs +3 -1
  25. package/fesm2022/mapa-library-ui-src-lib-components-table.mjs.map +1 -1
  26. package/fesm2022/mapa-library-ui-src-lib-components-textarea.mjs +3 -0
  27. package/fesm2022/mapa-library-ui-src-lib-components-textarea.mjs.map +1 -1
  28. package/fesm2022/mapa-library-ui-src-lib-components-warning.mjs +3 -0
  29. package/fesm2022/mapa-library-ui-src-lib-components-warning.mjs.map +1 -1
  30. package/fesm2022/mapa-library-ui-src-lib-core-excel-export.mjs +242 -39
  31. package/fesm2022/mapa-library-ui-src-lib-core-excel-export.mjs.map +1 -1
  32. package/fesm2022/mapa-library-ui-src-lib-core-export.mjs +107 -26
  33. package/fesm2022/mapa-library-ui-src-lib-core-export.mjs.map +1 -1
  34. package/fesm2022/mapa-library-ui.mjs +3 -1
  35. package/fesm2022/mapa-library-ui.mjs.map +1 -1
  36. package/index.d.ts +72 -0
  37. package/mapa-library-ui-2.13.3.tgz +0 -0
  38. package/package.json +2 -2
  39. package/src/lib/core/excel-export/index.d.ts +86 -4
  40. package/src/lib/core/export/index.d.ts +215 -3
  41. package/worker/excel-export.runtime.d.ts +2 -2
  42. package/worker/excel-export.runtime.js +23 -23
  43. package/worker/excel-export.worker.js +23 -23
  44. package/mapa-library-ui-2.13.1.tgz +0 -0
@@ -8,6 +8,45 @@ class ExcelExportCancelledError extends Error {
8
8
  }
9
9
  }
10
10
 
11
+ function formatExportText(template, values) {
12
+ return template.replace(/\{(\w+)\}/g, (placeholder, key) => values[key] === undefined ? placeholder : String(values[key]));
13
+ }
14
+ /** Stable codes survive worker transport; default messages preserve the low-level API. */
15
+ class ExcelExportError extends Error {
16
+ constructor(exportCode, message) {
17
+ super(message);
18
+ this.exportCode = exportCode;
19
+ this.name = 'ExcelExportError';
20
+ }
21
+ }
22
+
23
+ /** Excel format codes; values must already be typed numbers, strings or dates. */
24
+ const EXCEL_FORMATS = {
25
+ text: '@',
26
+ integer: '#,##0',
27
+ number: '#,##0.00',
28
+ currency: '"R$" #,##0.00',
29
+ percent: '0%',
30
+ date: 'dd/mm/yyyy',
31
+ dateTime: 'dd/mm/yyyy hh:mm',
32
+ time: 'hh:mm',
33
+ };
34
+ function fraction(decimals) {
35
+ if (!Number.isInteger(decimals) || decimals < 0 || decimals > 15)
36
+ throw new ExcelExportError('errorDecimals', 'Informe de 0 a 15 casas decimais.');
37
+ return decimals ? `.${'0'.repeat(decimals)}` : '';
38
+ }
39
+ function excelNumberFormat(decimals = 2, useGrouping = true) {
40
+ return `${useGrouping ? '#,##0' : '0'}${fraction(decimals)}`;
41
+ }
42
+ function excelCurrencyFormat(symbol = 'R$', decimals = 2) {
43
+ const literal = symbol.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
44
+ return `"${literal}" ${excelNumberFormat(decimals)}`;
45
+ }
46
+ function excelPercentFormat(decimals = 0) {
47
+ return `0${fraction(decimals)}%`;
48
+ }
49
+
11
50
  function excelFileName(value) {
12
51
  return (value
13
52
  .replace(/\.xlsx$/i, '')
@@ -142,6 +181,10 @@ function hexArgb(color) {
142
181
  /** Finalize a branded table after widths and data have been assigned. */
143
182
  function finishMapaExcelTable(sheet, request) {
144
183
  const columns = request.columns;
184
+ const locale = request.localization?.locale ?? 'pt-BR';
185
+ const recordLabel = request.rows.length === 1
186
+ ? (request.localization?.record ?? 'registro')
187
+ : (request.localization?.records ?? 'registros');
145
188
  const count = Math.max(2, columns.length);
146
189
  const end = request.rows.length + 9;
147
190
  const range = (index) => `${sheet.getColumn(index + 1).letter}10:${sheet.getColumn(index + 1).letter}${Math.max(10, end)}`;
@@ -152,10 +195,10 @@ function finishMapaExcelTable(sheet, request) {
152
195
  };
153
196
  sheet.pageSetup.printTitlesRow = '9:9';
154
197
  const summaryFormula = [
155
- request.rows.length ? `ROWS(A10:A${end})&" registros"` : '0&" registros"',
198
+ `${request.rows.length ? `ROWS(A10:A${end})` : '0'}&${quote(` ${recordLabel}`)}`,
156
199
  ];
157
200
  const summaryResult = [
158
- `${request.rows.length.toLocaleString('pt-BR')} registros`,
201
+ `${request.rows.length.toLocaleString(locale)} ${recordLabel}`,
159
202
  ];
160
203
  for (const indicator of (request.indicators ?? []).slice(0, 2)) {
161
204
  const index = columns.findIndex((column) => column.key === indicator.key);
@@ -174,7 +217,7 @@ function finishMapaExcelTable(sheet, request) {
174
217
  // Sign criteria cover financial additions and usage without evaluating arbitrary expressions.
175
218
  const sign = String(indicator.criteria);
176
219
  if (!['>0', '<0'].includes(sign))
177
- throw new Error('Critério de soma inválido. Use >0 ou <0.');
220
+ throw new ExcelExportError('errorCriteria', 'Critério de soma inválido. Use >0 ou <0.');
178
221
  formula = `SUMIF(${range(index)},${quote(sign)})`;
179
222
  result = data.reduce((sum, value) => sum +
180
223
  (typeof value === 'number' &&
@@ -193,7 +236,7 @@ function finishMapaExcelTable(sheet, request) {
193
236
  }
194
237
  const format = indicator.numFmt ?? '#,##0';
195
238
  const digits = format.match(/\.(0+)/)?.[1].length ?? 0;
196
- const formatted = new Intl.NumberFormat('pt-BR', {
239
+ const formatted = new Intl.NumberFormat(locale, {
197
240
  minimumFractionDigits: digits,
198
241
  maximumFractionDigits: digits,
199
242
  ...(format.includes('R$')
@@ -226,7 +269,7 @@ function finishMapaExcelTable(sheet, request) {
226
269
  };
227
270
  if (request.context) {
228
271
  const context = request.context;
229
- const date = context.generatedAt.toLocaleString('pt-BR');
272
+ const date = context.generatedAt.toLocaleString(locale);
230
273
  for (const row of [6, 7]) {
231
274
  sheet.mergeCells(row, 1, row, count);
232
275
  sheet.getRow(row).height = 24;
@@ -249,10 +292,18 @@ function finishMapaExcelTable(sheet, request) {
249
292
  };
250
293
  }
251
294
  }
252
- sheet.getCell(6, 1).value =
253
- `${context.module} · ${context.company} · Exportado em ${date} por ${context.user}`;
254
- sheet.getCell(7, 1).value =
255
- `Filtros aplicados: ${context.filters.length ? context.filters.join(' · ') : 'nenhum'}`;
295
+ sheet.getCell(6, 1).value = formatExportText(request.localization?.sheetContext ??
296
+ '{module} · {company} · Exportado em {date} por {user}', {
297
+ module: context.module,
298
+ company: context.company,
299
+ user: context.user,
300
+ date,
301
+ });
302
+ sheet.getCell(7, 1).value = formatExportText(request.localization?.sheetFilters ?? 'Filtros aplicados: {filters}', {
303
+ filters: context.filters.length
304
+ ? context.filters.join(' · ')
305
+ : (request.localization?.sheetNoFilters ?? 'nenhum'),
306
+ });
256
307
  sheet.getRow(8).height = 6;
257
308
  }
258
309
  columns.forEach((column, index) => {
@@ -299,7 +350,8 @@ function finishMapaExcelTable(sheet, request) {
299
350
  const row = sheet.getRow(end + 1);
300
351
  const labelIndex = columns.findIndex((column) => !column.total);
301
352
  if (labelIndex >= 0)
302
- row.getCell(labelIndex + 1).value = 'TOTAL';
353
+ row.getCell(labelIndex + 1).value =
354
+ request.localization?.sheetTotal ?? 'TOTAL';
303
355
  columns.forEach((column, index) => {
304
356
  const cell = row.getCell(index + 1);
305
357
  if (column.total)
@@ -324,7 +376,8 @@ function finishMapaExcelTable(sheet, request) {
324
376
  sheet.mergeCells(footerRow, 1, footerRow, count);
325
377
  const footer = sheet.getCell(footerRow, 1);
326
378
  footer.value =
327
- 'Documento gerado automaticamente pela plataforma Mapa HDS. Os dados respeitam as permissões de quem exportou.';
379
+ request.localization?.sheetFooter ??
380
+ 'Documento gerado automaticamente pela plataforma Mapa HDS. Os dados respeitam as permissões de quem exportou.';
328
381
  footer.font = {
329
382
  name: 'Arial',
330
383
  size: 8,
@@ -337,10 +390,115 @@ function finishMapaExcelTable(sheet, request) {
337
390
  }
338
391
  }
339
392
 
393
+ function argb(color) {
394
+ const match = /^#([\da-f]{3}|[\da-f]{6})$/i.exec(color.trim());
395
+ if (!match)
396
+ throw new ExcelExportError('errorColor', 'Cor de exportação inválida. Use HEX #RGB ou #RRGGBB.');
397
+ return `FF${(match[1].length === 3 ? [...match[1]].map((c) => c + c).join('') : match[1]).toUpperCase()}`;
398
+ }
399
+ function validateExcelCellStyle(style) {
400
+ if (!style)
401
+ return;
402
+ const { alignment, font } = style;
403
+ const invalid = (font?.size !== undefined &&
404
+ (!Number.isFinite(font.size) || font.size <= 0 || font.size > 409)) ||
405
+ (alignment?.indent !== undefined &&
406
+ (!Number.isInteger(alignment.indent) ||
407
+ alignment.indent < 0 ||
408
+ alignment.indent > 250)) ||
409
+ (alignment?.textRotation !== undefined &&
410
+ alignment.textRotation !== 'vertical' &&
411
+ (!Number.isInteger(alignment.textRotation) ||
412
+ Math.abs(alignment.textRotation) > 90)) ||
413
+ (alignment?.horizontal !== undefined &&
414
+ ![
415
+ 'left',
416
+ 'center',
417
+ 'right',
418
+ 'fill',
419
+ 'justify',
420
+ 'centerContinuous',
421
+ 'distributed',
422
+ ].includes(alignment.horizontal)) ||
423
+ (alignment?.vertical !== undefined &&
424
+ !['top', 'middle', 'bottom', 'distributed', 'justify'].includes(alignment.vertical));
425
+ if (invalid)
426
+ throw new ExcelExportError('errorStyle', 'Estilo de exportação inválido. Confira fonte e alinhamento.');
427
+ for (const color of [font?.color, style.backgroundColor])
428
+ if (color !== undefined)
429
+ argb(color);
430
+ for (const line of Object.values(style.border ?? {})) {
431
+ if (![
432
+ 'thin',
433
+ 'medium',
434
+ 'thick',
435
+ 'dotted',
436
+ 'hair',
437
+ 'dashed',
438
+ 'double',
439
+ 'dashDot',
440
+ 'dashDotDot',
441
+ 'mediumDashed',
442
+ 'mediumDashDot',
443
+ 'mediumDashDotDot',
444
+ 'slantDashDot',
445
+ ].includes(line.style))
446
+ throw new ExcelExportError('errorBorder', 'Borda de exportação inválida.');
447
+ if (line.color !== undefined)
448
+ argb(line.color);
449
+ }
450
+ }
451
+ /** Merge components without sharing mutable ExcelJS style objects with the request. */
452
+ function applyExcelCellStyle(cell, style) {
453
+ if (!style)
454
+ return;
455
+ if (style.alignment)
456
+ cell.alignment = { ...cell.alignment, ...style.alignment };
457
+ if (style.font) {
458
+ const { color, ...font } = style.font;
459
+ cell.font = {
460
+ ...cell.font,
461
+ ...font,
462
+ ...(color ? { color: { argb: argb(color) } } : {}),
463
+ };
464
+ }
465
+ if (style.backgroundColor)
466
+ cell.fill = {
467
+ type: 'pattern',
468
+ pattern: 'solid',
469
+ fgColor: { argb: argb(style.backgroundColor) },
470
+ };
471
+ if (style.border) {
472
+ cell.border = { ...cell.border };
473
+ for (const side of ['top', 'bottom', 'left', 'right']) {
474
+ const line = style.border[side];
475
+ if (line)
476
+ cell.border[side] = {
477
+ ...cell.border[side],
478
+ style: line.style,
479
+ ...(line.color ? { color: { argb: argb(line.color) } } : {}),
480
+ };
481
+ }
482
+ }
483
+ }
484
+ function validateExcelAutoWidth(options) {
485
+ const min = options.min ?? 1;
486
+ const max = options.max ?? 255;
487
+ if (![min, max].every((value) => Number.isFinite(value) && value > 0 && value <= 255) ||
488
+ min > max ||
489
+ (options.padding !== undefined &&
490
+ (!Number.isFinite(options.padding) ||
491
+ options.padding < 0 ||
492
+ options.padding > 255)) ||
493
+ (options.mode !== undefined &&
494
+ !['header', 'content', 'both'].includes(options.mode)))
495
+ throw new ExcelExportError('errorAutoWidth', 'Configuração de largura automática inválida.');
496
+ }
497
+
340
498
  function resolveWorkbookConstructor(module) {
341
499
  const constructor = module.default?.Workbook ?? module.Workbook;
342
500
  if (typeof constructor !== 'function')
343
- throw new Error('Não foi possível carregar a biblioteca de exportação Excel.');
501
+ throw new ExcelExportError('errorEngine', 'Não foi possível carregar a biblioteca de exportação Excel.');
344
502
  return constructor;
345
503
  }
346
504
  async function createExcelWorkbook() {
@@ -360,7 +518,7 @@ function cellValue(value) {
360
518
  return null;
361
519
  if (value instanceof Date) {
362
520
  if (!Number.isFinite(value.getTime()))
363
- throw new Error('Data inválida na exportação.');
521
+ throw new ExcelExportError('errorDate', 'Data inválida na exportação.');
364
522
  return value;
365
523
  }
366
524
  if (typeof value === 'number')
@@ -369,9 +527,9 @@ function cellValue(value) {
369
527
  return { formula: value.formula, result: cellValue(value.result) };
370
528
  }
371
529
  if (typeof value === 'string' && value.length > 32767)
372
- throw new Error('Uma célula excede o limite de 32.767 caracteres do Excel.');
530
+ throw new ExcelExportError('errorCellLength', 'Uma célula excede o limite de 32.767 caracteres do Excel.');
373
531
  if (!['string', 'number', 'boolean'].includes(typeof value))
374
- throw new Error('Valor de célula inválido. Use um extrator de coluna para formatá-lo.');
532
+ throw new ExcelExportError('errorCellValue', 'Valor de célula inválido. Use um extrator de coluna para formatá-lo.');
375
533
  return value;
376
534
  }
377
535
  /** Adds a table to an existing workbook; no domain or HTTP dependencies. */
@@ -379,23 +537,33 @@ async function addExcelTable(book, request, options = {}) {
379
537
  const isCancelled = options.isCancelled ?? (() => false);
380
538
  checkCancelled(isCancelled);
381
539
  if (!request.columns.length)
382
- throw new Error('Informe pelo menos uma coluna.');
540
+ throw new ExcelExportError('errorColumns', 'Informe pelo menos uma coluna.');
383
541
  if (request.columns.length > 16384)
384
- throw new Error('Quantidade de colunas excede o limite do Excel.');
542
+ throw new ExcelExportError('errorColumnLimit', 'Quantidade de colunas excede o limite do Excel.');
385
543
  const branded = request.mode !== 'plain';
386
544
  if ((request.metadata?.length ?? 0) > 3)
387
- throw new Error('Informe no máximo três linhas de metadados.');
545
+ throw new ExcelExportError('errorMetadata', 'Informe no máximo três linhas de metadados.');
388
546
  const headerRow = branded ? 9 : 1;
547
+ validateExcelCellStyle(request.style);
548
+ validateExcelCellStyle(request.headerStyle);
549
+ for (const height of [request.rowHeight, request.headerHeight]) {
550
+ if (height !== undefined &&
551
+ (!Number.isFinite(height) || height <= 0 || height > 409))
552
+ throw new ExcelExportError('errorHeight', 'Altura de linha inválida. Use até 409 pontos.');
553
+ }
389
554
  if (request.rows.length + headerRow > 1048576)
390
- throw new Error('Quantidade de linhas excede o limite do Excel.');
555
+ throw new ExcelExportError('errorRowLimit', 'Quantidade de linhas excede o limite do Excel.');
391
556
  request.columns.forEach((column) => {
557
+ validateExcelAutoWidth({ ...request.autoWidth, ...column.autoWidth });
558
+ validateExcelCellStyle(column.style);
559
+ validateExcelCellStyle(column.headerStyle);
392
560
  if (!column.value && !column.key)
393
- throw new Error('A coluna deve ter uma chave ou um extrator.');
561
+ throw new ExcelExportError('errorColumnKey', 'A coluna deve ter uma chave ou um extrator.');
394
562
  if (column.width !== undefined &&
395
563
  (!Number.isFinite(column.width) ||
396
564
  column.width <= 0 ||
397
565
  column.width > 255))
398
- throw new Error('Largura de coluna inválida.');
566
+ throw new ExcelExportError('errorWidth', 'Largura de coluna inválida.');
399
567
  });
400
568
  const sheet = book.addWorksheet(request.sheetName, branded
401
569
  ? {
@@ -411,13 +579,27 @@ async function addExcelTable(book, request, options = {}) {
411
579
  const count = branded
412
580
  ? Math.max(request.columns.length, 2)
413
581
  : request.columns.length;
414
- sheet.getRow(headerRow).values = request.columns.map((column) => branded ? column.label.toLocaleUpperCase() : column.label);
415
- const widths = request.columns.map((column) => column.label.length);
582
+ const headers = request.columns.map((column) => branded ? column.label.toLocaleUpperCase() : column.label);
583
+ sheet.getRow(headerRow).values = headers;
584
+ const widths = headers.map(() => 0);
416
585
  if (branded) {
417
- request.columns.forEach((_, index) => styleMapaExcelHeaderCell(sheet, headerRow, index + 1));
586
+ request.columns.forEach((column, index) => {
587
+ styleMapaExcelHeaderCell(sheet, headerRow, index + 1);
588
+ if (column.width === undefined) {
589
+ const cell = sheet.getCell(headerRow, index + 1);
590
+ cell.alignment = { ...cell.alignment, wrapText: false };
591
+ }
592
+ });
418
593
  sheet.getRow(headerRow).height = 30;
419
594
  sheet.pageSetup.printTitlesRow = '9:9';
420
595
  }
596
+ if (request.headerHeight !== undefined)
597
+ sheet.getRow(headerRow).height = request.headerHeight;
598
+ request.columns.forEach((column, index) => {
599
+ const cell = sheet.getCell(headerRow, index + 1);
600
+ applyExcelCellStyle(cell, request.headerStyle);
601
+ applyExcelCellStyle(cell, column.headerStyle);
602
+ });
421
603
  let lastYield = performance.now();
422
604
  for (let index = 0; index < request.rows.length; index++) {
423
605
  checkCancelled(isCancelled);
@@ -448,6 +630,8 @@ async function addExcelTable(book, request, options = {}) {
448
630
  cell.numFmt = 'dd/mm/yyyy hh:mm';
449
631
  else if (branded && typeof value === 'number')
450
632
  cell.numFmt = Number.isInteger(value) ? '#,##0' : '#,##0.###############';
633
+ applyExcelCellStyle(cell, request.style);
634
+ applyExcelCellStyle(cell, column.style);
451
635
  widths[columnIndex] = Math.max(widths[columnIndex], value instanceof Date ? 16 : String(value ?? '').length);
452
636
  });
453
637
  // Let cancellation and the UI run between batches; ZIP serialization may still require a worker.
@@ -458,8 +642,21 @@ async function addExcelTable(book, request, options = {}) {
458
642
  }
459
643
  }
460
644
  request.columns.forEach((column, index) => {
645
+ const options = { ...request.autoWidth, ...column.autoWidth };
646
+ const fontSize = sheet.getCell(headerRow, index + 1).font?.size ?? (branded ? 8 : 11);
647
+ const headerLength = Math.max(...headers[index].split(/\r?\n/).map((line) => line.length));
648
+ // Header sizing is an estimate in Excel character units, with room for filters.
649
+ const headerWidth = Math.ceil(headerLength * (branded ? 1.2 : 1) * fontSize / (branded ? 8 : 11)) +
650
+ (options.padding ?? (branded ? 4 : 2));
651
+ const contentWidth = Math.min(options.max ?? 60, widths[index] + 2);
652
+ const desired = options.mode === 'header'
653
+ ? headerWidth
654
+ : options.mode === 'content'
655
+ ? contentWidth
656
+ : Math.max(headerWidth, contentWidth);
461
657
  sheet.getColumn(index + 1).width =
462
- column.width ?? Math.min(60, Math.max(12, widths[index] + 2));
658
+ column.width ??
659
+ Math.min(options.max ?? (branded ? 255 : 60), Math.max(options.min ?? 12, desired));
463
660
  });
464
661
  if (branded && request.columns.length === 1)
465
662
  sheet.getColumn(2).width = 28;
@@ -498,7 +695,7 @@ async function addExcelTable(book, request, options = {}) {
498
695
  async function buildExcelWorkbook(request, isCancelled = () => false, onProgress) {
499
696
  checkCancelled(isCancelled);
500
697
  if (!request.sheets.length)
501
- throw new Error('Informe pelo menos uma aba.');
698
+ throw new ExcelExportError('errorSheets', 'Informe pelo menos uma aba.');
502
699
  const book = await createExcelWorkbook();
503
700
  checkCancelled(isCancelled);
504
701
  book.creator = request.creator ?? 'Mapa HDS';
@@ -512,6 +709,7 @@ async function buildExcelWorkbook(request, isCancelled = () => false, onProgress
512
709
  for (const [index, sheet] of request.sheets.entries()) {
513
710
  await addExcelTable(book, {
514
711
  ...sheet,
712
+ localization: sheet.localization ?? request.localization,
515
713
  sheetName: names[index],
516
714
  title: sheet.title ?? sheet.sheetName,
517
715
  }, { logoId, isCancelled, onProgress: (progress) => onProgress?.({ ...progress, completed: completed + (progress.completed ?? 0), total }) });
@@ -537,7 +735,7 @@ const EXPORT_FILE_ROW_LIMIT = 100_000;
537
735
  /** Encode browser-local calendar fields for timezone-free Excel and CSV cells. */
538
736
  function toExportDate(value) {
539
737
  if (!Number.isFinite(value.getTime()))
540
- throw new Error('Data inválida na exportação.');
738
+ throw new ExcelExportError('errorDate', 'Data inválida na exportação.');
541
739
  return new Date(value.getTime() - value.getTimezoneOffset() * 60_000);
542
740
  }
543
741
  const exportSlug = (value) => value
@@ -553,7 +751,7 @@ function exportFileBase(listing, company, date) {
553
751
  /** Greedy packing preserves dataset order and counts records across all sheets. */
554
752
  function splitExportSheets(sheets, limit = EXPORT_FILE_ROW_LIMIT) {
555
753
  if (!Number.isInteger(limit) || limit < 1)
556
- throw new Error('Limite de registros inválido.');
754
+ throw new ExcelExportError('errorRowCount', 'Limite de registros inválido.');
557
755
  const parts = [[]];
558
756
  let used = 0;
559
757
  for (const sheet of sheets) {
@@ -583,13 +781,13 @@ function encodeExportCsv(sheet, onProgress) {
583
781
  ? input.result
584
782
  : input;
585
783
  if (value instanceof Date && !Number.isFinite(value.getTime()))
586
- throw new Error('Data inválida na exportação.');
784
+ throw new ExcelExportError('errorDate', 'Data inválida na exportação.');
587
785
  if (typeof value === 'number' && !Number.isFinite(value))
588
786
  return '';
589
787
  const text = value == null
590
788
  ? ''
591
789
  : value instanceof Date
592
- ? value.toLocaleString('pt-BR', { timeZone: 'UTC' })
790
+ ? value.toLocaleString(sheet.localization?.locale ?? 'pt-BR', { timeZone: 'UTC' })
593
791
  : String(value);
594
792
  // Quoting alone does not stop spreadsheet apps interpreting user text as a formula.
595
793
  const literal = typeof value === 'string' && /^[=+\-@\t\r]/.test(text)
@@ -628,12 +826,12 @@ async function collectExportPages(options) {
628
826
  (expected !== undefined && expected !== page.totalCount) ||
629
827
  (page.pageIndex !== undefined && page.pageIndex !== pageIndex) ||
630
828
  (pageIndex > 1 && page.pageSize !== pageSize))
631
- throw new Error('Os dados mudaram durante a exportação. Atualize a listagem e tente novamente.');
829
+ throw new ExcelExportError('errorDataChanged', 'Os dados mudaram durante a exportação. Atualize a listagem e tente novamente.');
632
830
  expected = page.totalCount;
633
831
  for (const row of page.data) {
634
832
  const key = options.key(row);
635
833
  if (!key || keys.has(key))
636
- throw new Error('Registros duplicados ou sem identificação na exportação.');
834
+ throw new ExcelExportError('errorDuplicate', 'Registros duplicados ou sem identificação na exportação.');
637
835
  keys.add(key);
638
836
  result.push(row);
639
837
  }
@@ -645,7 +843,7 @@ async function collectExportPages(options) {
645
843
  !Number.isInteger(page.pageSize) ||
646
844
  page.pageSize < 1 ||
647
845
  page.data.length !== page.pageSize)
648
- throw new Error('A API retornou uma exportação incompleta.');
846
+ throw new ExcelExportError('errorIncomplete', 'A API retornou uma exportação incompleta.');
649
847
  pageSize = page.pageSize;
650
848
  pageIndex++;
651
849
  }
@@ -692,7 +890,10 @@ class MapaExcelExportService {
692
890
  async generateCsv(request, options) {
693
891
  if (options.workerFactory)
694
892
  return this.serializeInWorker(request, options.workerFactory, options.isCancelled ?? (() => false), options.onProgress, 'csv');
695
- return encodeExportCsv(request.sheets[0]);
893
+ return encodeExportCsv({
894
+ ...request.sheets[0],
895
+ localization: request.sheets[0].localization ?? request.localization,
896
+ });
696
897
  }
697
898
  async save(book, fileName, isCancelled = () => false) {
698
899
  if (isCancelled())
@@ -738,14 +939,16 @@ class MapaExcelExportService {
738
939
  return;
739
940
  }
740
941
  if ('error' in data)
741
- finish(new Error(data.error));
942
+ finish(data.exportCode
943
+ ? new ExcelExportError(data.exportCode, data.error)
944
+ : new Error(data.error));
742
945
  else if (data.buffer instanceof ArrayBuffer)
743
946
  finish(undefined, data.buffer);
744
947
  else
745
- finish(new Error('Resposta inválida do worker de exportação.'));
948
+ finish(new ExcelExportError('errorWorkerResponse', 'Resposta inválida do worker de exportação.'));
746
949
  };
747
- worker.onerror = (event) => finish(new Error(event.message || 'Falha no worker de exportação.'));
748
- worker.onmessageerror = () => finish(new Error('Não foi possível receber o arquivo exportado.'));
950
+ worker.onerror = (event) => finish(new ExcelExportError('errorWorkerFailure', event.message || 'Falha no worker de exportação.'));
951
+ worker.onmessageerror = () => finish(new ExcelExportError('errorWorkerReceive', 'Não foi possível receber o arquivo exportado.'));
749
952
  try {
750
953
  worker.postMessage({ request, format });
751
954
  }
@@ -810,5 +1013,5 @@ function getExcelWorkerConstructor() {
810
1013
  * Generated bundle index. Do not edit.
811
1014
  */
812
1015
 
813
- 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 };
1016
+ export { EXCEL_FORMATS, ExcelExportCancelledError, ExcelExportError, MAPA_EXCEL_COLORS, MAPA_EXCEL_STATUS_COLORS, MapaExcelExportService, addExcelTable, addMapaExcelLogo, applyMapaExcelBanner, buildExcelWorkbook, createExcelWorkbook, excelCurrencyFormat, excelFileName, excelFileNameWithDate, excelNumberFormat, excelPercentFormat, excelSheetName, fillExcelCell, fitExcelSheetTitle, formatExportText, getExcelWorkerConstructor, resolveWorkbookConstructor, serializeExcelRequest, serializeExcelWorkbook, styleMapaExcelHeaderCell, uniqueExcelSheetNames };
814
1017
  //# sourceMappingURL=mapa-library-ui-src-lib-core-excel-export.mjs.map