@mailoo/market 1.35.12 → 1.35.14

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.
@@ -30,6 +30,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/wholesale-price-list/index.ts
31
31
  var wholesale_price_list_exports = {};
32
32
  __export(wholesale_price_list_exports, {
33
+ DEFAULT_PREVIEW_IMAGE_CONCURRENCY: () => DEFAULT_PREVIEW_IMAGE_CONCURRENCY,
33
34
  PRICE_LIST_BANNER_ROW_COUNT: () => PRICE_LIST_BANNER_ROW_COUNT,
34
35
  PRICE_LIST_DATA_ROW_HEIGHT_PT: () => PRICE_LIST_DATA_ROW_HEIGHT_PT,
35
36
  PRICE_LIST_DEFAULT_PHOTO_PX: () => PRICE_LIST_DEFAULT_PHOTO_PX,
@@ -40,25 +41,49 @@ __export(wholesale_price_list_exports, {
40
41
  buildTotalSumFormula: () => buildTotalSumFormula,
41
42
  buildWholesalePriceListXlsx: () => buildWholesalePriceListXlsx,
42
43
  coerceUnitPrice: () => coerceUnitPrice,
43
- createPriceListGoogleClients: () => createPriceListGoogleClients,
44
44
  excelColumnLetter: () => excelColumnLetter,
45
45
  fetchAbsoluteUrlBytes: () => fetchAbsoluteUrlBytes,
46
46
  formatGeneratedLabel: () => formatGeneratedLabel,
47
47
  googleSheetsImageFormula: () => googleSheetsImageFormula,
48
48
  isAnonymousHttpImageUrl: () => isAnonymousHttpImageUrl,
49
49
  isMailooApiKeyedImageUrl: () => isMailooApiKeyedImageUrl,
50
+ mapWithConcurrency: () => mapWithConcurrency,
50
51
  mediaIdFromMailooPublicImageUrl: () => mediaIdFromMailooPublicImageUrl,
51
52
  normalizePreviewSquare: () => normalizePreviewSquare,
52
53
  priceListFilename: () => priceListFilename,
53
54
  priceListFilenameDate: () => priceListFilenameDate,
54
55
  rasterizeLogo: () => rasterizeLogo,
55
- renderPriceListGoogleSheet: () => renderPriceListGoogleSheet,
56
56
  renderPriceListXlsx: () => renderPriceListXlsx,
57
+ resolvePreviewImageConcurrency: () => resolvePreviewImageConcurrency,
57
58
  resolvePriceListLabels: () => resolvePriceListLabels,
59
+ tryNormalizePreviewSquare: () => tryNormalizePreviewSquare,
60
+ tryRasterizeLogo: () => tryRasterizeLogo,
58
61
  validatePriceListInput: () => validatePriceListInput
59
62
  });
60
63
  module.exports = __toCommonJS(wholesale_price_list_exports);
61
64
 
65
+ // src/wholesale-price-list/concurrency.ts
66
+ var DEFAULT_PREVIEW_IMAGE_CONCURRENCY = 6;
67
+ async function mapWithConcurrency(items, concurrency, mapper) {
68
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
69
+ throw new Error("concurrency must be an integer >= 1");
70
+ }
71
+ if (items.length === 0) return [];
72
+ const results = new Array(items.length);
73
+ let nextIndex = 0;
74
+ async function worker() {
75
+ for (; ; ) {
76
+ const i = nextIndex;
77
+ nextIndex += 1;
78
+ if (i >= items.length) return;
79
+ results[i] = await mapper(items[i], i);
80
+ }
81
+ }
82
+ const workerCount = Math.min(concurrency, items.length);
83
+ await Promise.all(Array.from({ length: workerCount }, () => worker()));
84
+ return results;
85
+ }
86
+
62
87
  // src/wholesale-price-list/labels.ts
63
88
  var BUILTIN = {
64
89
  en: {
@@ -240,8 +265,13 @@ function validatePriceListInput(input) {
240
265
  if (!Array.isArray(input.rows)) {
241
266
  throw new Error("rows must be an array");
242
267
  }
243
- for (let i = 0; i < input.rows.length; i++) {
244
- const row = input.rows[i];
268
+ if (input.photoSizePx !== void 0 && (!Number.isInteger(input.photoSizePx) || input.photoSizePx < 32)) {
269
+ throw new Error("photoSizePx must be an integer >= 32");
270
+ }
271
+ if (input.previewImageConcurrency !== void 0 && (!Number.isInteger(input.previewImageConcurrency) || input.previewImageConcurrency < 1)) {
272
+ throw new Error("previewImageConcurrency must be an integer >= 1");
273
+ }
274
+ const rows = input.rows.map((row, i) => {
245
275
  if (typeof row.productId !== "string" || row.productId.trim() === "") {
246
276
  throw new Error(`rows[${i}].productId is required`);
247
277
  }
@@ -251,21 +281,28 @@ function validatePriceListInput(input) {
251
281
  if (typeof row.productUrl !== "string" || row.productUrl.trim() === "") {
252
282
  throw new Error(`rows[${i}].productUrl is required`);
253
283
  }
254
- row.unitPrice = coerceUnitPrice(
255
- typeof row.unitPrice === "number" || row.unitPrice === null ? row.unitPrice : Number.NaN
256
- );
257
- }
258
- if (input.photoSizePx !== void 0 && (!Number.isInteger(input.photoSizePx) || input.photoSizePx < 32)) {
259
- throw new Error("photoSizePx must be an integer >= 32");
260
- }
284
+ return {
285
+ ...row,
286
+ unitPrice: coerceUnitPrice(
287
+ typeof row.unitPrice === "number" || row.unitPrice === null ? row.unitPrice : Number.NaN
288
+ )
289
+ };
290
+ });
291
+ return {
292
+ ...input,
293
+ rows
294
+ };
295
+ }
296
+ function resolvePreviewImageConcurrency(input) {
297
+ return input.previewImageConcurrency ?? DEFAULT_PREVIEW_IMAGE_CONCURRENCY;
261
298
  }
262
299
  function buildPriceListLayout(input) {
263
- validatePriceListInput(input);
264
- const labels = resolvePriceListLabels(input.locale, input.labels);
265
- const photoSizePx = input.photoSizePx ?? PRICE_LIST_DEFAULT_PHOTO_PX;
300
+ const normalized = validatePriceListInput(input);
301
+ const labels = resolvePriceListLabels(normalized.locale, normalized.labels);
302
+ const photoSizePx = normalized.photoSizePx ?? PRICE_LIST_DEFAULT_PHOTO_PX;
266
303
  const headerRow = PRICE_LIST_BANNER_ROW_COUNT + 1;
267
304
  const firstDataRow = headerRow + 1;
268
- const totalRow = firstDataRow + input.rows.length;
305
+ const totalRow = firstDataRow + normalized.rows.length;
269
306
  const keys = [
270
307
  { key: "photo", header: labels.photo },
271
308
  { key: "category", header: labels.category },
@@ -290,7 +327,7 @@ function buildPriceListLayout(input) {
290
327
  return col.letter;
291
328
  };
292
329
  return {
293
- locale: input.locale,
330
+ locale: normalized.locale,
294
331
  photoSizePx,
295
332
  dataRowHeightPt: PRICE_LIST_DATA_ROW_HEIGHT_PT,
296
333
  photoColWidthChars: PRICE_LIST_PHOTO_COL_CHARS,
@@ -370,6 +407,9 @@ function buildCurrencyTotalSumIfFormula(args) {
370
407
 
371
408
  // src/wholesale-price-list/preview-image.ts
372
409
  var import_sharp = __toESM(require("sharp"), 1);
410
+ function errorMessage(e) {
411
+ return e instanceof Error ? e.message : String(e);
412
+ }
373
413
  async function normalizePreviewSquare(input, sizePx = PRICE_LIST_DEFAULT_PHOTO_PX) {
374
414
  if (!Number.isInteger(sizePx) || sizePx < 32) {
375
415
  throw new Error("sizePx must be an integer >= 32");
@@ -387,6 +427,18 @@ async function normalizePreviewSquare(input, sizePx = PRICE_LIST_DEFAULT_PHOTO_P
387
427
  background: { r: 255, g: 255, b: 255, alpha: 1 }
388
428
  }).png().toBuffer();
389
429
  }
430
+ async function tryNormalizePreviewSquare(input, sizePx = PRICE_LIST_DEFAULT_PHOTO_PX) {
431
+ try {
432
+ const png = await normalizePreviewSquare(input, sizePx);
433
+ return { png, error: null };
434
+ } catch (e) {
435
+ const msg = errorMessage(e);
436
+ if (msg.includes("Empty preview image") || msg.includes("sizePx must")) {
437
+ throw e;
438
+ }
439
+ return { png: null, error: msg };
440
+ }
441
+ }
390
442
  async function rasterizeLogo(input, opts) {
391
443
  if (input.byteLength === 0) {
392
444
  throw new Error("Empty logo image");
@@ -411,12 +463,23 @@ async function rasterizeLogo(input, opts) {
411
463
  background: { r: 255, g: 255, b: 255, alpha: 0 }
412
464
  }).png().toBuffer();
413
465
  } catch (e) {
414
- const msg = e instanceof Error ? e.message : String(e);
415
466
  throw new Error(
416
- `Failed to rasterize logo (SVG/PNG/JPEG/WebP required): ${msg}`
467
+ `Failed to rasterize logo (SVG/PNG/JPEG/WebP required): ${errorMessage(e)}`
417
468
  );
418
469
  }
419
470
  }
471
+ async function tryRasterizeLogo(input, opts) {
472
+ try {
473
+ const png = await rasterizeLogo(input, opts);
474
+ return { png, error: null };
475
+ } catch (e) {
476
+ const msg = errorMessage(e);
477
+ if (msg.includes("Empty logo image") || msg.includes("widthPx must") || msg.includes("heightPx must")) {
478
+ throw e;
479
+ }
480
+ return { png: null, error: msg };
481
+ }
482
+ }
420
483
  function googleSheetsImageFormula(url, sizePx) {
421
484
  const safe = url.replace(/"/g, '""');
422
485
  return `=IMAGE("${safe}",4,${sizePx},${sizePx})`;
@@ -424,6 +487,8 @@ function googleSheetsImageFormula(url, sizePx) {
424
487
 
425
488
  // src/wholesale-price-list/build-xlsx.ts
426
489
  var import_exceljs = __toESM(require("exceljs"), 1);
490
+
491
+ // src/wholesale-price-list/resolve-media.ts
427
492
  async function resolvePreviewBytes(input, rowIndex) {
428
493
  const row = input.rows[rowIndex];
429
494
  if (row.previewImageBytes && row.previewImageBytes.byteLength > 0) {
@@ -451,6 +516,8 @@ async function resolveLogoBytes(input) {
451
516
  if (isAnonymousHttpImageUrl(url)) return fetchAbsoluteUrlBytes(url);
452
517
  return null;
453
518
  }
519
+
520
+ // src/wholesale-price-list/build-xlsx.ts
454
521
  function uniqueCurrencies(input) {
455
522
  const set = /* @__PURE__ */ new Set();
456
523
  for (const row of input.rows) {
@@ -460,16 +527,18 @@ function uniqueCurrencies(input) {
460
527
  return [...set].sort();
461
528
  }
462
529
  async function renderPriceListXlsx(input) {
463
- validatePriceListInput(input);
464
- const labels = resolvePriceListLabels(input.locale, input.labels);
465
- const layout = buildPriceListLayout(input);
530
+ const normalized = validatePriceListInput(input);
531
+ const warnings = [];
532
+ const labels = resolvePriceListLabels(normalized.locale, normalized.labels);
533
+ const layout = buildPriceListLayout(normalized);
466
534
  const title = labels.title;
467
- const currencies = uniqueCurrencies(input);
535
+ const currencies = uniqueCurrencies(normalized);
468
536
  const multiCurrency = currencies.length > 1;
537
+ const concurrency = resolvePreviewImageConcurrency(normalized);
469
538
  const workbook = new import_exceljs.default.Workbook();
470
539
  workbook.creator = "Mailoo";
471
- workbook.created = new Date(input.header.generatedAt);
472
- const sheetName = `${input.header.siteName}`.slice(0, 31) || title.slice(0, 31);
540
+ workbook.created = new Date(normalized.header.generatedAt);
541
+ const sheetName = `${normalized.header.siteName}`.slice(0, 31) || title.slice(0, 31);
473
542
  const sheet = workbook.addWorksheet(sheetName, {
474
543
  properties: { defaultRowHeight: layout.dataRowHeightPt },
475
544
  views: [{ state: "frozen", ySplit: layout.headerRow }],
@@ -493,32 +562,36 @@ async function renderPriceListXlsx(input) {
493
562
  sheet.getColumn(col.index).hidden = true;
494
563
  }
495
564
  }
496
- sheet.getCell("A1").value = input.header.siteName;
565
+ sheet.getCell("A1").value = normalized.header.siteName;
497
566
  sheet.getCell("A1").font = { bold: true, size: 16 };
498
567
  sheet.mergeCells(1, 1, 1, Math.min(5, layout.columns.length));
499
- sheet.getCell("A2").value = input.header.contacts;
568
+ sheet.getCell("A2").value = normalized.header.contacts;
500
569
  sheet.getCell("A2").alignment = { wrapText: true, vertical: "top" };
501
- const contactLines = input.header.contacts.split(/\r?\n/).length;
570
+ const contactLines = normalized.header.contacts.split(/\r?\n/).length;
502
571
  sheet.getRow(2).height = Math.max(36, contactLines * 14);
503
572
  sheet.getCell("A3").value = formatGeneratedLabel(
504
573
  labels.generated,
505
- input.header.generatedAt,
506
- input.locale,
507
- input.header.timeZone
574
+ normalized.header.generatedAt,
575
+ normalized.locale,
576
+ normalized.header.timeZone
508
577
  );
509
578
  sheet.getCell("A3").font = { italic: true, size: 10 };
510
- const logoBytes = await resolveLogoBytes(input);
579
+ const logoBytes = await resolveLogoBytes(normalized);
511
580
  if (logoBytes) {
512
- const png = await rasterizeLogo(logoBytes);
513
- const imageId = workbook.addImage({
514
- buffer: png,
515
- extension: "png"
516
- });
517
- sheet.addImage(imageId, {
518
- tl: { col: 5, row: 0 },
519
- ext: { width: 120, height: 40 },
520
- editAs: "oneCell"
521
- });
581
+ const { png, error } = await tryRasterizeLogo(logoBytes);
582
+ if (png) {
583
+ const imageId = workbook.addImage({
584
+ buffer: png,
585
+ extension: "png"
586
+ });
587
+ sheet.addImage(imageId, {
588
+ tl: { col: 5, row: 0 },
589
+ ext: { width: 120, height: 40 },
590
+ editAs: "oneCell"
591
+ });
592
+ } else if (error) {
593
+ warnings.push(`header.logo: ${error}`);
594
+ }
522
595
  }
523
596
  const headerRow = sheet.getRow(layout.headerRow);
524
597
  headerRow.font = { bold: true };
@@ -536,9 +609,40 @@ async function renderPriceListXlsx(input) {
536
609
  };
537
610
  const sheetCells = [];
538
611
  const previewImageUrls = [];
539
- const lastDataRow = input.rows.length === 0 ? layout.firstDataRow - 1 : layout.firstDataRow + input.rows.length - 1;
540
- for (let i = 0; i < input.rows.length; i++) {
541
- const row = input.rows[i];
612
+ const lastDataRow = normalized.rows.length === 0 ? layout.firstDataRow - 1 : layout.firstDataRow + normalized.rows.length - 1;
613
+ const previewPrep = await mapWithConcurrency(
614
+ normalized.rows,
615
+ concurrency,
616
+ async (row, i) => {
617
+ const candidateUrl = row.previewImageUrl?.trim() || null;
618
+ const sheetsSafeUrl = candidateUrl && isAnonymousHttpImageUrl(candidateUrl) ? candidateUrl : null;
619
+ try {
620
+ const previewBytes = await resolvePreviewBytes(normalized, i);
621
+ if (!previewBytes) {
622
+ return { png: null, sheetsSafeUrl, warning: null };
623
+ }
624
+ const { png, error } = await tryNormalizePreviewSquare(
625
+ previewBytes,
626
+ layout.photoSizePx
627
+ );
628
+ if (png) return { png, sheetsSafeUrl, warning: null };
629
+ return {
630
+ png: null,
631
+ sheetsSafeUrl,
632
+ warning: error ? `rows[${i}].previewImage: ${error}` : `rows[${i}].previewImage: undecodable`
633
+ };
634
+ } catch (e) {
635
+ const msg = e instanceof Error ? e.message : String(e);
636
+ return {
637
+ png: null,
638
+ sheetsSafeUrl,
639
+ warning: `rows[${i}].previewImage: ${msg}`
640
+ };
641
+ }
642
+ }
643
+ );
644
+ for (let i = 0; i < normalized.rows.length; i++) {
645
+ const row = normalized.rows[i];
542
646
  const excelRow = layout.firstDataRow + i;
543
647
  const sheetRow = sheet.getRow(excelRow);
544
648
  sheetRow.height = layout.dataRowHeightPt;
@@ -590,17 +694,12 @@ async function renderPriceListXlsx(input) {
590
694
  errorTitle: labels.quantity,
591
695
  error: ">= 0"
592
696
  };
593
- const previewBytes = await resolvePreviewBytes(input, i);
594
- const candidateUrl = row.previewImageUrl?.trim() || null;
595
- const sheetsSafeUrl = candidateUrl && isAnonymousHttpImageUrl(candidateUrl) ? candidateUrl : null;
596
- previewImageUrls.push(sheetsSafeUrl);
597
- if (previewBytes) {
598
- const png = await normalizePreviewSquare(
599
- previewBytes,
600
- layout.photoSizePx
601
- );
697
+ const prep = previewPrep[i];
698
+ previewImageUrls.push(prep.sheetsSafeUrl);
699
+ if (prep.warning) warnings.push(prep.warning);
700
+ if (prep.png) {
602
701
  const imageId = workbook.addImage({
603
- buffer: png,
702
+ buffer: prep.png,
604
703
  extension: "png"
605
704
  });
606
705
  sheet.addImage(imageId, {
@@ -608,11 +707,14 @@ async function renderPriceListXlsx(input) {
608
707
  ext: { width: layout.photoSizePx, height: layout.photoSizePx },
609
708
  editAs: "oneCell"
610
709
  });
611
- } else if (sheetsSafeUrl) {
710
+ } else if (prep.sheetsSafeUrl) {
612
711
  sheetCells.push({
613
712
  a1: `${photoCol.letter}${excelRow}`,
614
713
  value: null,
615
- formula: googleSheetsImageFormula(sheetsSafeUrl, layout.photoSizePx)
714
+ formula: googleSheetsImageFormula(
715
+ prep.sheetsSafeUrl,
716
+ layout.photoSizePx
717
+ )
616
718
  });
617
719
  }
618
720
  }
@@ -662,382 +764,32 @@ async function renderPriceListXlsx(input) {
662
764
  }
663
765
  const buffer = Buffer.from(await workbook.xlsx.writeBuffer());
664
766
  const filename = priceListFilename(
665
- input.locale,
666
- input.header.generatedAt,
767
+ normalized.locale,
768
+ normalized.header.generatedAt,
667
769
  labels.filenamePrefix,
668
- input.header.timeZone
770
+ normalized.header.timeZone
669
771
  );
670
772
  const sheetModel = {
671
773
  title,
672
- locale: input.locale,
774
+ locale: normalized.locale,
673
775
  layout,
674
776
  cells: sheetCells,
675
777
  previewImageUrls,
676
- logoUrl: input.header.logoUrl?.trim() || null
778
+ logoUrl: normalized.header.logoUrl?.trim() || null
677
779
  };
678
780
  return {
679
781
  buffer,
680
782
  filename,
681
783
  contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
682
784
  layout,
683
- sheetModel
785
+ sheetModel,
786
+ warnings
684
787
  };
685
788
  }
686
789
  var buildWholesalePriceListXlsx = renderPriceListXlsx;
687
-
688
- // src/wholesale-price-list/google-sheets.ts
689
- var SCOPES = [
690
- "https://www.googleapis.com/auth/spreadsheets",
691
- "https://www.googleapis.com/auth/drive"
692
- ];
693
- function parseServiceAccountJson(raw) {
694
- if (typeof raw === "object" && raw !== null && !Array.isArray(raw)) {
695
- return raw;
696
- }
697
- if (typeof raw !== "string" || !raw.trim()) {
698
- throw new Error("serviceAccountJson is required");
699
- }
700
- try {
701
- const parsed = JSON.parse(raw);
702
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
703
- throw new Error("not an object");
704
- }
705
- return parsed;
706
- } catch {
707
- throw new Error("serviceAccountJson must be valid JSON object");
708
- }
709
- }
710
- async function createPriceListGoogleClients(serviceAccountJson) {
711
- const credentials = parseServiceAccountJson(serviceAccountJson);
712
- const { google } = await import("googleapis");
713
- const auth = new google.auth.GoogleAuth({
714
- credentials,
715
- scopes: SCOPES
716
- });
717
- return {
718
- sheets: google.sheets({
719
- version: "v4",
720
- auth
721
- }),
722
- drive: google.drive({
723
- version: "v3",
724
- auth
725
- })
726
- };
727
- }
728
- async function resolvePreviewBytes2(input, rowIndex) {
729
- const row = input.rows[rowIndex];
730
- if (row.previewImageBytes && row.previewImageBytes.byteLength > 0) {
731
- return row.previewImageBytes;
732
- }
733
- if (input.loadPreviewImage) {
734
- return input.loadPreviewImage({
735
- previewMediaId: row.previewMediaId,
736
- previewImageUrl: row.previewImageUrl
737
- });
738
- }
739
- const url = row.previewImageUrl?.trim();
740
- if (url && isAnonymousHttpImageUrl(url)) {
741
- return fetchAbsoluteUrlBytes(url);
742
- }
743
- return null;
744
- }
745
- async function resolveLogoBytes2(input) {
746
- if (input.header.logoBytes && input.header.logoBytes.byteLength > 0) {
747
- return input.header.logoBytes;
748
- }
749
- const url = input.header.logoUrl?.trim();
750
- if (!url) return null;
751
- if (input.loadLogo) return input.loadLogo(url);
752
- if (isAnonymousHttpImageUrl(url)) return fetchAbsoluteUrlBytes(url);
753
- return null;
754
- }
755
- async function uploadPngPublic(drive, name, png, folderId) {
756
- const created = await drive.files.create({
757
- requestBody: {
758
- name,
759
- mimeType: "image/png",
760
- parents: folderId ? [folderId] : void 0
761
- },
762
- media: { mimeType: "image/png", body: Buffer.from(png) },
763
- fields: "id",
764
- supportsAllDrives: true
765
- });
766
- const fileId = created.data.id;
767
- if (!fileId) throw new Error("Drive file create returned no id");
768
- await drive.permissions.create({
769
- fileId,
770
- requestBody: { role: "reader", type: "anyone" },
771
- supportsAllDrives: true
772
- });
773
- return `https://drive.google.com/uc?export=view&id=${encodeURIComponent(fileId)}`;
774
- }
775
- function colWidthPixels(layout, key) {
776
- if (key === "photo") return Math.round(layout.photoSizePx * 1.15);
777
- if (key === "product") return 180;
778
- if (key === "link" || key === "quantity" || key === "sum" || key === "price")
779
- return 100;
780
- if (key === "currencyHidden") return 1;
781
- return 120;
782
- }
783
- async function renderPriceListGoogleSheet(input, options) {
784
- validatePriceListInput(input);
785
- const labels = resolvePriceListLabels(input.locale, input.labels);
786
- const layout = buildPriceListLayout(input);
787
- const clients = options.clients ?? await createPriceListGoogleClients(options.serviceAccountJson);
788
- const { sheets, drive } = clients;
789
- const title = `${input.header.siteName} \u2014 ${labels.title} (${input.locale})`.slice(
790
- 0,
791
- 100
792
- );
793
- const created = await sheets.spreadsheets.create({
794
- requestBody: {
795
- properties: { title },
796
- sheets: [
797
- {
798
- properties: {
799
- title: labels.title.slice(0, 100),
800
- gridProperties: {
801
- frozenRowCount: layout.headerRow
802
- }
803
- }
804
- }
805
- ]
806
- },
807
- fields: "spreadsheetId,spreadsheetUrl"
808
- });
809
- const spreadsheetId = created.data.spreadsheetId;
810
- const spreadsheetUrl = created.data.spreadsheetUrl;
811
- if (!spreadsheetId || !spreadsheetUrl) {
812
- throw new Error("Sheets create returned no spreadsheetId/url");
813
- }
814
- const meta = await sheets.spreadsheets.get({
815
- spreadsheetId,
816
- fields: "sheets.properties"
817
- });
818
- const sheetId = meta.data.sheets?.[0]?.properties?.sheetId;
819
- if (sheetId == null) throw new Error("Missing sheetId");
820
- if (options.driveFolderId?.trim()) {
821
- const file = await drive.files.get({
822
- fileId: spreadsheetId,
823
- fields: "parents",
824
- supportsAllDrives: true
825
- });
826
- const prevParents = (file.data.parents ?? []).join(",");
827
- await drive.files.update({
828
- fileId: spreadsheetId,
829
- addParents: options.driveFolderId.trim(),
830
- removeParents: prevParents || void 0,
831
- supportsAllDrives: true,
832
- fields: "id,parents"
833
- });
834
- }
835
- if (options.shareWithEmail?.trim()) {
836
- await drive.permissions.create({
837
- fileId: spreadsheetId,
838
- requestBody: {
839
- type: "user",
840
- role: "writer",
841
- emailAddress: options.shareWithEmail.trim()
842
- },
843
- sendNotificationEmail: false,
844
- supportsAllDrives: true
845
- });
846
- }
847
- const folderId = options.driveFolderId?.trim() || null;
848
- let logoImageUrl = null;
849
- const logoBytes = await resolveLogoBytes2(input);
850
- if (logoBytes) {
851
- const png = await rasterizeLogo(logoBytes);
852
- logoImageUrl = await uploadPngPublic(
853
- drive,
854
- `price-list-logo-${input.locale}.png`,
855
- png,
856
- folderId
857
- );
858
- } else {
859
- const candidate = input.header.logoUrl?.trim() || null;
860
- if (candidate && !/\.svg(\?|$)/i.test(candidate) && isAnonymousHttpImageUrl(candidate)) {
861
- logoImageUrl = candidate;
862
- }
863
- }
864
- const generated = formatGeneratedLabel(
865
- labels.generated,
866
- input.header.generatedAt,
867
- input.locale,
868
- input.header.timeZone
869
- );
870
- const lastColLetter = layout.columns.find((c) => c.key === "sum").letter;
871
- const values = [];
872
- const bannerRow1 = Array(layout.columns.length).fill("");
873
- bannerRow1[0] = input.header.siteName;
874
- if (logoImageUrl) {
875
- bannerRow1[5] = googleSheetsImageFormula(logoImageUrl, 40);
876
- }
877
- values.push(bannerRow1);
878
- values.push([
879
- input.header.contacts,
880
- ...Array(layout.columns.length - 1).fill("")
881
- ]);
882
- values.push([generated, ...Array(layout.columns.length - 1).fill("")]);
883
- values.push(
884
- layout.columns.map((c) => c.key === "currencyHidden" ? "" : c.header)
885
- );
886
- const currencies = /* @__PURE__ */ new Set();
887
- for (let i = 0; i < input.rows.length; i++) {
888
- const row = input.rows[i];
889
- const excelRow = layout.firstDataRow + i;
890
- const line = Array(layout.columns.length).fill("");
891
- const photoIdx = layout.columns.findIndex((c) => c.key === "photo");
892
- let imageUrl = null;
893
- const bytes = await resolvePreviewBytes2(input, i);
894
- if (bytes) {
895
- const png = await normalizePreviewSquare(bytes, layout.photoSizePx);
896
- imageUrl = await uploadPngPublic(
897
- drive,
898
- `price-list-${row.productId}-${row.variantId ?? "p"}.png`,
899
- png,
900
- folderId
901
- );
902
- } else {
903
- const candidate = row.previewImageUrl?.trim() || null;
904
- if (candidate && isAnonymousHttpImageUrl(candidate)) {
905
- imageUrl = candidate;
906
- }
907
- }
908
- if (imageUrl && photoIdx >= 0) {
909
- line[photoIdx] = googleSheetsImageFormula(imageUrl, layout.photoSizePx);
910
- }
911
- line[layout.columns.findIndex((c) => c.key === "category")] = row.category ?? "";
912
- line[layout.columns.findIndex((c) => c.key === "product")] = row.product;
913
- line[layout.columns.findIndex((c) => c.key === "variant")] = row.variant ?? "";
914
- line[layout.columns.findIndex((c) => c.key === "packaging")] = row.packaging ?? "";
915
- const priceIdx = layout.columns.findIndex((c) => c.key === "price");
916
- if (row.unitPrice === null) {
917
- line[priceIdx] = labels.onRequest;
918
- } else {
919
- line[priceIdx] = String(row.unitPrice);
920
- }
921
- const linkIdx = layout.columns.findIndex((c) => c.key === "link");
922
- line[linkIdx] = `=HYPERLINK("${row.productUrl.replace(/"/g, '""')}","${labels.linkText.replace(/"/g, '""')}")`;
923
- const qtyIdx = layout.columns.findIndex((c) => c.key === "quantity");
924
- line[qtyIdx] = "";
925
- const sumIdx = layout.columns.findIndex((c) => c.key === "sum");
926
- line[sumIdx] = `=${buildLineSumFormula({ layout, row: excelRow })}`;
927
- const curIdx = layout.columns.findIndex((c) => c.key === "currencyHidden");
928
- const cur = row.currency?.trim() || "";
929
- line[curIdx] = cur;
930
- if (cur) currencies.add(cur);
931
- values.push(line);
932
- }
933
- const currencyList = [...currencies].sort();
934
- const multi = currencyList.length > 1;
935
- if (!multi) {
936
- const totalLine = Array(layout.columns.length).fill("");
937
- totalLine[layout.columns.findIndex((c) => c.key === "quantity")] = labels.total;
938
- const lastData = input.rows.length === 0 ? layout.firstDataRow - 1 : layout.firstDataRow + input.rows.length - 1;
939
- totalLine[layout.columns.findIndex((c) => c.key === "sum")] = `=${buildTotalSumFormula({
940
- layout,
941
- firstDataRow: layout.firstDataRow,
942
- lastDataRow: lastData
943
- })}`;
944
- values.push(totalLine);
945
- } else {
946
- const lastData = layout.firstDataRow + input.rows.length - 1;
947
- for (let i = 0; i < currencyList.length; i++) {
948
- const currency = currencyList[i];
949
- const totalLine = Array(layout.columns.length).fill("");
950
- totalLine[layout.columns.findIndex((c) => c.key === "quantity")] = i === 0 ? `${labels.total} (${currency})` : currency;
951
- totalLine[layout.columns.findIndex((c) => c.key === "sum")] = `=${buildCurrencyTotalSumIfFormula({
952
- layout,
953
- firstDataRow: layout.firstDataRow,
954
- lastDataRow: lastData,
955
- currency
956
- })}`;
957
- values.push(totalLine);
958
- }
959
- }
960
- await sheets.spreadsheets.values.update({
961
- spreadsheetId,
962
- range: `A1:${lastColLetter}${values.length}`,
963
- valueInputOption: "USER_ENTERED",
964
- requestBody: { values }
965
- });
966
- const requests = [];
967
- for (const col of layout.columns) {
968
- requests.push({
969
- updateDimensionProperties: {
970
- range: {
971
- sheetId,
972
- dimension: "COLUMNS",
973
- startIndex: col.index - 1,
974
- endIndex: col.index
975
- },
976
- properties: {
977
- pixelSize: colWidthPixels(layout, col.key),
978
- hiddenByUser: col.key === "currencyHidden"
979
- },
980
- fields: "pixelSize,hiddenByUser"
981
- }
982
- });
983
- }
984
- if (input.rows.length > 0) {
985
- requests.push({
986
- updateDimensionProperties: {
987
- range: {
988
- sheetId,
989
- dimension: "ROWS",
990
- startIndex: layout.firstDataRow - 1,
991
- endIndex: layout.firstDataRow - 1 + input.rows.length
992
- },
993
- properties: { pixelSize: 130 },
994
- fields: "pixelSize"
995
- }
996
- });
997
- }
998
- requests.push({
999
- setBasicFilter: {
1000
- filter: {
1001
- range: {
1002
- sheetId,
1003
- startRowIndex: layout.headerRow - 1,
1004
- endRowIndex: layout.headerRow + input.rows.length,
1005
- startColumnIndex: 0,
1006
- endColumnIndex: layout.columns.find((c) => c.key === "sum").index
1007
- }
1008
- }
1009
- }
1010
- });
1011
- if (input.rows.length > 0) {
1012
- const qtyCol = layout.columns.find((c) => c.key === "quantity").index - 1;
1013
- requests.push({
1014
- setDataValidation: {
1015
- range: {
1016
- sheetId,
1017
- startRowIndex: layout.firstDataRow - 1,
1018
- endRowIndex: layout.firstDataRow - 1 + input.rows.length,
1019
- startColumnIndex: qtyCol,
1020
- endColumnIndex: qtyCol + 1
1021
- },
1022
- rule: {
1023
- condition: {
1024
- type: "NUMBER_GREATER_THAN_EQ",
1025
- values: [{ userEnteredValue: "0" }]
1026
- },
1027
- strict: true,
1028
- showCustomUi: true
1029
- }
1030
- }
1031
- });
1032
- }
1033
- await sheets.spreadsheets.batchUpdate({
1034
- spreadsheetId,
1035
- requestBody: { requests }
1036
- });
1037
- return { spreadsheetId, spreadsheetUrl };
1038
- }
1039
790
  // Annotate the CommonJS export names for ESM import in node:
1040
791
  0 && (module.exports = {
792
+ DEFAULT_PREVIEW_IMAGE_CONCURRENCY,
1041
793
  PRICE_LIST_BANNER_ROW_COUNT,
1042
794
  PRICE_LIST_DATA_ROW_HEIGHT_PT,
1043
795
  PRICE_LIST_DEFAULT_PHOTO_PX,
@@ -1048,21 +800,23 @@ async function renderPriceListGoogleSheet(input, options) {
1048
800
  buildTotalSumFormula,
1049
801
  buildWholesalePriceListXlsx,
1050
802
  coerceUnitPrice,
1051
- createPriceListGoogleClients,
1052
803
  excelColumnLetter,
1053
804
  fetchAbsoluteUrlBytes,
1054
805
  formatGeneratedLabel,
1055
806
  googleSheetsImageFormula,
1056
807
  isAnonymousHttpImageUrl,
1057
808
  isMailooApiKeyedImageUrl,
809
+ mapWithConcurrency,
1058
810
  mediaIdFromMailooPublicImageUrl,
1059
811
  normalizePreviewSquare,
1060
812
  priceListFilename,
1061
813
  priceListFilenameDate,
1062
814
  rasterizeLogo,
1063
- renderPriceListGoogleSheet,
1064
815
  renderPriceListXlsx,
816
+ resolvePreviewImageConcurrency,
1065
817
  resolvePriceListLabels,
818
+ tryNormalizePreviewSquare,
819
+ tryRasterizeLogo,
1066
820
  validatePriceListInput
1067
821
  });
1068
822
  //# sourceMappingURL=index.cjs.map