@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.
@@ -1,395 +1,37 @@
1
- // src/wholesale-price-list/labels.ts
2
- var BUILTIN = {
3
- en: {
4
- title: "Price list",
5
- photo: "Photo",
6
- category: "Category",
7
- product: "Product",
8
- variant: "Variant",
9
- packaging: "Packaging",
10
- price: "Price",
11
- onRequest: "on request",
12
- link: "Link",
13
- linkText: "Open",
14
- quantity: "Quantity",
15
- sum: "Sum",
16
- total: "Total",
17
- generated: "Generated: {date}",
18
- filenamePrefix: "price-list"
19
- },
20
- ru: {
21
- title: "\u041F\u0440\u0430\u0439\u0441-\u043B\u0438\u0441\u0442",
22
- photo: "\u0424\u043E\u0442\u043E",
23
- category: "\u041A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F",
24
- product: "\u0422\u043E\u0432\u0430\u0440",
25
- variant: "\u0412\u0430\u0440\u0438\u0430\u043D\u0442",
26
- packaging: "\u0423\u043F\u0430\u043A\u043E\u0432\u043A\u0430",
27
- price: "\u0426\u0435\u043D\u0430",
28
- onRequest: "\u043F\u043E \u0437\u0430\u043F\u0440\u043E\u0441\u0443",
29
- link: "\u0421\u0441\u044B\u043B\u043A\u0430",
30
- linkText: "\u041E\u0442\u043A\u0440\u044B\u0442\u044C",
31
- quantity: "\u041A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E",
32
- sum: "\u0421\u0443\u043C\u043C\u0430",
33
- total: "\u0418\u0442\u043E\u0433\u043E",
34
- generated: "\u0421\u0444\u043E\u0440\u043C\u0438\u0440\u043E\u0432\u0430\u043D\u043E: {date}",
35
- filenamePrefix: "price-list"
36
- },
37
- hy: {
38
- title: "\u0533\u0576\u0561\u0581\u0578\u0582\u0581\u0561\u056F",
39
- photo: "\u053C\u0578\u0582\u057D\u0561\u0576\u056F\u0561\u0580",
40
- category: "\u053F\u0561\u057F\u0565\u0563\u0578\u0580\u056B\u0561",
41
- product: "\u0531\u057A\u0580\u0561\u0576\u0584",
42
- variant: "\u054F\u0561\u0580\u0562\u0565\u0580\u0561\u056F",
43
- packaging: "\u0553\u0561\u0569\u0565\u0569\u0561\u057E\u0578\u0580\u0578\u0582\u0574",
44
- price: "\u0533\u056B\u0576",
45
- onRequest: "\u0568\u057D\u057F \u0570\u0561\u0580\u0581\u0574\u0561\u0576",
46
- link: "\u0540\u0572\u0578\u0582\u0574",
47
- linkText: "\u0532\u0561\u0581\u0565\u056C",
48
- quantity: "\u0554\u0561\u0576\u0561\u056F",
49
- sum: "\u0533\u0578\u0582\u0574\u0561\u0580",
50
- total: "\u0538\u0576\u0564\u0561\u0574\u0565\u0576\u0568",
51
- generated: "\u054D\u057F\u0565\u0572\u056E\u057E\u0561\u056E \u0567\u055D {date}",
52
- filenamePrefix: "price-list"
53
- },
54
- de: {
55
- title: "Preisliste",
56
- photo: "Foto",
57
- category: "Kategorie",
58
- product: "Produkt",
59
- variant: "Variante",
60
- packaging: "Verpackung",
61
- price: "Preis",
62
- onRequest: "auf Anfrage",
63
- link: "Link",
64
- linkText: "\xD6ffnen",
65
- quantity: "Menge",
66
- sum: "Summe",
67
- total: "Gesamt",
68
- generated: "Erstellt: {date}",
69
- filenamePrefix: "price-list"
70
- },
71
- es: {
72
- title: "Lista de precios",
73
- photo: "Foto",
74
- category: "Categor\xEDa",
75
- product: "Producto",
76
- variant: "Variante",
77
- packaging: "Embalaje",
78
- price: "Precio",
79
- onRequest: "bajo petici\xF3n",
80
- link: "Enlace",
81
- linkText: "Abrir",
82
- quantity: "Cantidad",
83
- sum: "Suma",
84
- total: "Total",
85
- generated: "Generado: {date}",
86
- filenamePrefix: "price-list"
87
- }
88
- };
89
- var BUILTIN_LOCALES = /* @__PURE__ */ new Set(["hy", "ru", "en", "de", "es"]);
90
- function resolvePriceListLabels(locale, overrides) {
91
- const code = locale.trim().toLowerCase();
92
- const base = BUILTIN_LOCALES.has(code) ? BUILTIN[code] : BUILTIN.en;
93
- return { ...base, ...overrides };
94
- }
95
- function formatGeneratedLabel(template, generatedAt, locale, timeZone) {
96
- const d = new Date(generatedAt);
97
- if (Number.isNaN(d.getTime())) {
98
- throw new Error(`header.generatedAt is not a valid ISO date: ${generatedAt}`);
99
- }
100
- const tz = timeZone && timeZone.trim() !== "" ? timeZone.trim() : "UTC";
101
- const date = new Intl.DateTimeFormat(locale, {
102
- dateStyle: "medium",
103
- timeStyle: "short",
104
- timeZone: tz
105
- }).format(d);
106
- return template.replace(/\{date\}/g, date);
107
- }
108
- function priceListFilenameDate(generatedAt, timeZone) {
109
- const d = new Date(generatedAt);
110
- if (Number.isNaN(d.getTime())) {
111
- throw new Error(`header.generatedAt is not a valid ISO date: ${generatedAt}`);
112
- }
113
- const tz = timeZone && timeZone.trim() !== "" ? timeZone.trim() : "UTC";
114
- const parts = new Intl.DateTimeFormat("en-US", {
115
- timeZone: tz,
116
- year: "numeric",
117
- month: "2-digit",
118
- day: "2-digit"
119
- }).formatToParts(d);
120
- const y = parts.find((p) => p.type === "year")?.value;
121
- const m = parts.find((p) => p.type === "month")?.value;
122
- const day = parts.find((p) => p.type === "day")?.value;
123
- if (!y || !m || !day) {
124
- throw new Error(`Failed to format filename date for timeZone=${tz}`);
125
- }
126
- return `${y}-${m}-${day}`;
127
- }
128
- function priceListFilename(locale, generatedAt, prefix, timeZone) {
129
- const date = priceListFilenameDate(generatedAt, timeZone);
130
- return `${prefix}-${locale}-${date}.xlsx`;
131
- }
132
-
133
- // src/wholesale-price-list/unit-price.ts
134
- function coerceUnitPrice(value) {
135
- if (value === null) return null;
136
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
137
- return null;
138
- }
139
- return value;
140
- }
141
-
142
- // src/wholesale-price-list/layout.ts
143
- var PRICE_LIST_DEFAULT_PHOTO_PX = 120;
144
- var PRICE_LIST_DATA_ROW_HEIGHT_PT = 96;
145
- var PRICE_LIST_PHOTO_COL_CHARS = 18;
146
- var PRICE_LIST_BANNER_ROW_COUNT = 3;
147
- function excelColumnLetter(index1Based) {
148
- if (!Number.isInteger(index1Based) || index1Based < 1) {
149
- throw new Error(`Invalid column index: ${index1Based}`);
150
- }
151
- let n = index1Based;
152
- let s = "";
153
- while (n > 0) {
154
- const rem = (n - 1) % 26;
155
- s = String.fromCharCode(65 + rem) + s;
156
- n = Math.floor((n - 1) / 26);
157
- }
158
- return s;
159
- }
160
- function validatePriceListInput(input) {
161
- if (!input || typeof input !== "object") {
162
- throw new Error("PriceListInput is required");
163
- }
164
- if (typeof input.locale !== "string" || input.locale.trim() === "") {
165
- throw new Error("locale is required");
166
- }
167
- if (!input.header || typeof input.header !== "object") {
168
- throw new Error("header is required");
169
- }
170
- if (typeof input.header.siteName !== "string" || input.header.siteName.trim() === "") {
171
- throw new Error("header.siteName is required");
172
- }
173
- if (typeof input.header.contacts !== "string") {
174
- throw new Error("header.contacts must be a string");
175
- }
176
- if (typeof input.header.generatedAt !== "string" || Number.isNaN(new Date(input.header.generatedAt).getTime())) {
177
- throw new Error("header.generatedAt must be a valid ISO date string");
178
- }
179
- if (!Array.isArray(input.rows)) {
180
- throw new Error("rows must be an array");
181
- }
182
- for (let i = 0; i < input.rows.length; i++) {
183
- const row = input.rows[i];
184
- if (typeof row.productId !== "string" || row.productId.trim() === "") {
185
- throw new Error(`rows[${i}].productId is required`);
186
- }
187
- if (typeof row.product !== "string" || row.product.trim() === "") {
188
- throw new Error(`rows[${i}].product is required`);
189
- }
190
- if (typeof row.productUrl !== "string" || row.productUrl.trim() === "") {
191
- throw new Error(`rows[${i}].productUrl is required`);
192
- }
193
- row.unitPrice = coerceUnitPrice(
194
- typeof row.unitPrice === "number" || row.unitPrice === null ? row.unitPrice : Number.NaN
195
- );
196
- }
197
- if (input.photoSizePx !== void 0 && (!Number.isInteger(input.photoSizePx) || input.photoSizePx < 32)) {
198
- throw new Error("photoSizePx must be an integer >= 32");
199
- }
200
- }
201
- function buildPriceListLayout(input) {
202
- validatePriceListInput(input);
203
- const labels = resolvePriceListLabels(input.locale, input.labels);
204
- const photoSizePx = input.photoSizePx ?? PRICE_LIST_DEFAULT_PHOTO_PX;
205
- const headerRow = PRICE_LIST_BANNER_ROW_COUNT + 1;
206
- const firstDataRow = headerRow + 1;
207
- const totalRow = firstDataRow + input.rows.length;
208
- const keys = [
209
- { key: "photo", header: labels.photo },
210
- { key: "category", header: labels.category },
211
- { key: "product", header: labels.product },
212
- { key: "variant", header: labels.variant },
213
- { key: "packaging", header: labels.packaging },
214
- { key: "price", header: labels.price },
215
- { key: "link", header: labels.link },
216
- { key: "quantity", header: labels.quantity },
217
- { key: "sum", header: labels.sum },
218
- { key: "currencyHidden", header: "" }
219
- ];
220
- const columns = keys.map((c, i) => ({
221
- key: c.key,
222
- header: c.header,
223
- index: i + 1,
224
- letter: excelColumnLetter(i + 1)
225
- }));
226
- const letter = (key) => {
227
- const col = columns.find((c) => c.key === key);
228
- if (!col) throw new Error(`Missing column ${key}`);
229
- return col.letter;
230
- };
231
- return {
232
- locale: input.locale,
233
- photoSizePx,
234
- dataRowHeightPt: PRICE_LIST_DATA_ROW_HEIGHT_PT,
235
- photoColWidthChars: PRICE_LIST_PHOTO_COL_CHARS,
236
- headerRow,
237
- firstDataRow,
238
- totalRow,
239
- columns,
240
- priceColLetter: letter("price"),
241
- quantityColLetter: letter("quantity"),
242
- sumColLetter: letter("sum"),
243
- currencyColLetter: letter("currencyHidden"),
244
- linkColLetter: letter("link")
245
- };
246
- }
247
-
248
- // src/wholesale-price-list/fetch-url.ts
249
- async function fetchAbsoluteUrlBytes(url) {
250
- const trimmed = url.trim();
251
- if (!/^https?:\/\//i.test(trimmed)) return null;
252
- try {
253
- const res = await fetch(trimmed);
254
- if (!res.ok) return null;
255
- const buf = new Uint8Array(await res.arrayBuffer());
256
- return buf.byteLength > 0 ? buf : null;
257
- } catch {
258
- return null;
259
- }
260
- }
261
- function isMailooApiKeyedImageUrl(url) {
262
- try {
263
- const u = new URL(url.trim());
264
- return u.pathname.includes("/api/v1/images/public/content");
265
- } catch {
266
- return false;
267
- }
268
- }
269
- function mediaIdFromMailooPublicImageUrl(url) {
270
- try {
271
- const u = new URL(url.trim());
272
- if (!u.pathname.includes("/api/v1/images/public/content")) return null;
273
- const id = u.searchParams.get("id")?.trim();
274
- return id || null;
275
- } catch {
276
- return null;
277
- }
278
- }
279
- function isAnonymousHttpImageUrl(url) {
280
- const trimmed = url.trim();
281
- if (!/^https?:\/\//i.test(trimmed)) return false;
282
- if (isMailooApiKeyedImageUrl(trimmed)) return false;
283
- return true;
284
- }
285
-
286
- // src/wholesale-price-list/sum-formula.ts
287
- function buildLineSumFormula(args) {
288
- const { layout, row } = args;
289
- const q = `${layout.quantityColLetter}${row}`;
290
- const p = `${layout.priceColLetter}${row}`;
291
- return `IFERROR(IF(N(${q})<=0,"",IF(NOT(ISNUMBER(${p})),"",${q}*${p})),"")`;
292
- }
293
- function buildTotalSumFormula(args) {
294
- const { layout, firstDataRow, lastDataRow } = args;
295
- if (lastDataRow < firstDataRow) return "0";
296
- const range = `${layout.sumColLetter}${firstDataRow}:${layout.sumColLetter}${lastDataRow}`;
297
- return `SUM(${range})`;
298
- }
299
- function buildCurrencyTotalSumIfFormula(args) {
300
- const { layout, firstDataRow, lastDataRow, currency } = args;
301
- if (lastDataRow < firstDataRow) return "0";
302
- if (!currency || currency.includes('"')) {
303
- throw new Error("currency for SUMIF must be a non-empty string without quotes");
304
- }
305
- const sumRange = `${layout.sumColLetter}${firstDataRow}:${layout.sumColLetter}${lastDataRow}`;
306
- const curRange = `${layout.currencyColLetter}${firstDataRow}:${layout.currencyColLetter}${lastDataRow}`;
307
- return `SUMIF(${curRange},"${currency}",${sumRange})`;
308
- }
309
-
310
- // src/wholesale-price-list/preview-image.ts
311
- import sharp from "sharp";
312
- async function normalizePreviewSquare(input, sizePx = PRICE_LIST_DEFAULT_PHOTO_PX) {
313
- if (!Number.isInteger(sizePx) || sizePx < 32) {
314
- throw new Error("sizePx must be an integer >= 32");
315
- }
316
- if (input.byteLength === 0) {
317
- throw new Error("Empty preview image");
318
- }
319
- return sharp(Buffer.from(input), {
320
- limitInputPixels: 268435456,
321
- failOn: "error"
322
- }).rotate().resize({
323
- width: sizePx,
324
- height: sizePx,
325
- fit: "contain",
326
- background: { r: 255, g: 255, b: 255, alpha: 1 }
327
- }).png().toBuffer();
328
- }
329
- async function rasterizeLogo(input, opts) {
330
- if (input.byteLength === 0) {
331
- throw new Error("Empty logo image");
332
- }
333
- const widthPx = opts?.widthPx ?? 120;
334
- const heightPx = opts?.heightPx ?? 40;
335
- if (!Number.isInteger(widthPx) || widthPx < 16) {
336
- throw new Error("logo widthPx must be an integer >= 16");
337
- }
338
- if (!Number.isInteger(heightPx) || heightPx < 16) {
339
- throw new Error("logo heightPx must be an integer >= 16");
340
- }
341
- try {
342
- return await sharp(Buffer.from(input), {
343
- limitInputPixels: 268435456,
344
- failOn: "error",
345
- density: 288
346
- }).resize({
347
- width: widthPx,
348
- height: heightPx,
349
- fit: "contain",
350
- background: { r: 255, g: 255, b: 255, alpha: 0 }
351
- }).png().toBuffer();
352
- } catch (e) {
353
- const msg = e instanceof Error ? e.message : String(e);
354
- throw new Error(
355
- `Failed to rasterize logo (SVG/PNG/JPEG/WebP required): ${msg}`
356
- );
357
- }
358
- }
359
- function googleSheetsImageFormula(url, sizePx) {
360
- const safe = url.replace(/"/g, '""');
361
- return `=IMAGE("${safe}",4,${sizePx},${sizePx})`;
362
- }
1
+ import {
2
+ DEFAULT_PREVIEW_IMAGE_CONCURRENCY,
3
+ PRICE_LIST_BANNER_ROW_COUNT,
4
+ PRICE_LIST_DATA_ROW_HEIGHT_PT,
5
+ PRICE_LIST_DEFAULT_PHOTO_PX,
6
+ PRICE_LIST_PHOTO_COL_CHARS,
7
+ buildCurrencyTotalSumIfFormula,
8
+ buildLineSumFormula,
9
+ buildPriceListLayout,
10
+ buildTotalSumFormula,
11
+ coerceUnitPrice,
12
+ excelColumnLetter,
13
+ fetchAbsoluteUrlBytes,
14
+ formatGeneratedLabel,
15
+ googleSheetsImageFormula,
16
+ isAnonymousHttpImageUrl,
17
+ isMailooApiKeyedImageUrl,
18
+ mapWithConcurrency,
19
+ mediaIdFromMailooPublicImageUrl,
20
+ normalizePreviewSquare,
21
+ priceListFilename,
22
+ priceListFilenameDate,
23
+ rasterizeLogo,
24
+ resolveLogoBytes,
25
+ resolvePreviewBytes,
26
+ resolvePreviewImageConcurrency,
27
+ resolvePriceListLabels,
28
+ tryNormalizePreviewSquare,
29
+ tryRasterizeLogo,
30
+ validatePriceListInput
31
+ } from "../chunk-SNYTGUGW.js";
363
32
 
364
33
  // src/wholesale-price-list/build-xlsx.ts
365
34
  import ExcelJS from "exceljs";
366
- async function resolvePreviewBytes(input, rowIndex) {
367
- const row = input.rows[rowIndex];
368
- if (row.previewImageBytes && row.previewImageBytes.byteLength > 0) {
369
- return row.previewImageBytes;
370
- }
371
- if (input.loadPreviewImage) {
372
- return input.loadPreviewImage({
373
- previewMediaId: row.previewMediaId,
374
- previewImageUrl: row.previewImageUrl
375
- });
376
- }
377
- const url = row.previewImageUrl?.trim();
378
- if (url && isAnonymousHttpImageUrl(url)) {
379
- return fetchAbsoluteUrlBytes(url);
380
- }
381
- return null;
382
- }
383
- async function resolveLogoBytes(input) {
384
- if (input.header.logoBytes && input.header.logoBytes.byteLength > 0) {
385
- return input.header.logoBytes;
386
- }
387
- const url = input.header.logoUrl?.trim();
388
- if (!url) return null;
389
- if (input.loadLogo) return input.loadLogo(url);
390
- if (isAnonymousHttpImageUrl(url)) return fetchAbsoluteUrlBytes(url);
391
- return null;
392
- }
393
35
  function uniqueCurrencies(input) {
394
36
  const set = /* @__PURE__ */ new Set();
395
37
  for (const row of input.rows) {
@@ -399,16 +41,18 @@ function uniqueCurrencies(input) {
399
41
  return [...set].sort();
400
42
  }
401
43
  async function renderPriceListXlsx(input) {
402
- validatePriceListInput(input);
403
- const labels = resolvePriceListLabels(input.locale, input.labels);
404
- const layout = buildPriceListLayout(input);
44
+ const normalized = validatePriceListInput(input);
45
+ const warnings = [];
46
+ const labels = resolvePriceListLabels(normalized.locale, normalized.labels);
47
+ const layout = buildPriceListLayout(normalized);
405
48
  const title = labels.title;
406
- const currencies = uniqueCurrencies(input);
49
+ const currencies = uniqueCurrencies(normalized);
407
50
  const multiCurrency = currencies.length > 1;
51
+ const concurrency = resolvePreviewImageConcurrency(normalized);
408
52
  const workbook = new ExcelJS.Workbook();
409
53
  workbook.creator = "Mailoo";
410
- workbook.created = new Date(input.header.generatedAt);
411
- const sheetName = `${input.header.siteName}`.slice(0, 31) || title.slice(0, 31);
54
+ workbook.created = new Date(normalized.header.generatedAt);
55
+ const sheetName = `${normalized.header.siteName}`.slice(0, 31) || title.slice(0, 31);
412
56
  const sheet = workbook.addWorksheet(sheetName, {
413
57
  properties: { defaultRowHeight: layout.dataRowHeightPt },
414
58
  views: [{ state: "frozen", ySplit: layout.headerRow }],
@@ -432,32 +76,36 @@ async function renderPriceListXlsx(input) {
432
76
  sheet.getColumn(col.index).hidden = true;
433
77
  }
434
78
  }
435
- sheet.getCell("A1").value = input.header.siteName;
79
+ sheet.getCell("A1").value = normalized.header.siteName;
436
80
  sheet.getCell("A1").font = { bold: true, size: 16 };
437
81
  sheet.mergeCells(1, 1, 1, Math.min(5, layout.columns.length));
438
- sheet.getCell("A2").value = input.header.contacts;
82
+ sheet.getCell("A2").value = normalized.header.contacts;
439
83
  sheet.getCell("A2").alignment = { wrapText: true, vertical: "top" };
440
- const contactLines = input.header.contacts.split(/\r?\n/).length;
84
+ const contactLines = normalized.header.contacts.split(/\r?\n/).length;
441
85
  sheet.getRow(2).height = Math.max(36, contactLines * 14);
442
86
  sheet.getCell("A3").value = formatGeneratedLabel(
443
87
  labels.generated,
444
- input.header.generatedAt,
445
- input.locale,
446
- input.header.timeZone
88
+ normalized.header.generatedAt,
89
+ normalized.locale,
90
+ normalized.header.timeZone
447
91
  );
448
92
  sheet.getCell("A3").font = { italic: true, size: 10 };
449
- const logoBytes = await resolveLogoBytes(input);
93
+ const logoBytes = await resolveLogoBytes(normalized);
450
94
  if (logoBytes) {
451
- const png = await rasterizeLogo(logoBytes);
452
- const imageId = workbook.addImage({
453
- buffer: png,
454
- extension: "png"
455
- });
456
- sheet.addImage(imageId, {
457
- tl: { col: 5, row: 0 },
458
- ext: { width: 120, height: 40 },
459
- editAs: "oneCell"
460
- });
95
+ const { png, error } = await tryRasterizeLogo(logoBytes);
96
+ if (png) {
97
+ const imageId = workbook.addImage({
98
+ buffer: png,
99
+ extension: "png"
100
+ });
101
+ sheet.addImage(imageId, {
102
+ tl: { col: 5, row: 0 },
103
+ ext: { width: 120, height: 40 },
104
+ editAs: "oneCell"
105
+ });
106
+ } else if (error) {
107
+ warnings.push(`header.logo: ${error}`);
108
+ }
461
109
  }
462
110
  const headerRow = sheet.getRow(layout.headerRow);
463
111
  headerRow.font = { bold: true };
@@ -475,9 +123,40 @@ async function renderPriceListXlsx(input) {
475
123
  };
476
124
  const sheetCells = [];
477
125
  const previewImageUrls = [];
478
- const lastDataRow = input.rows.length === 0 ? layout.firstDataRow - 1 : layout.firstDataRow + input.rows.length - 1;
479
- for (let i = 0; i < input.rows.length; i++) {
480
- const row = input.rows[i];
126
+ const lastDataRow = normalized.rows.length === 0 ? layout.firstDataRow - 1 : layout.firstDataRow + normalized.rows.length - 1;
127
+ const previewPrep = await mapWithConcurrency(
128
+ normalized.rows,
129
+ concurrency,
130
+ async (row, i) => {
131
+ const candidateUrl = row.previewImageUrl?.trim() || null;
132
+ const sheetsSafeUrl = candidateUrl && isAnonymousHttpImageUrl(candidateUrl) ? candidateUrl : null;
133
+ try {
134
+ const previewBytes = await resolvePreviewBytes(normalized, i);
135
+ if (!previewBytes) {
136
+ return { png: null, sheetsSafeUrl, warning: null };
137
+ }
138
+ const { png, error } = await tryNormalizePreviewSquare(
139
+ previewBytes,
140
+ layout.photoSizePx
141
+ );
142
+ if (png) return { png, sheetsSafeUrl, warning: null };
143
+ return {
144
+ png: null,
145
+ sheetsSafeUrl,
146
+ warning: error ? `rows[${i}].previewImage: ${error}` : `rows[${i}].previewImage: undecodable`
147
+ };
148
+ } catch (e) {
149
+ const msg = e instanceof Error ? e.message : String(e);
150
+ return {
151
+ png: null,
152
+ sheetsSafeUrl,
153
+ warning: `rows[${i}].previewImage: ${msg}`
154
+ };
155
+ }
156
+ }
157
+ );
158
+ for (let i = 0; i < normalized.rows.length; i++) {
159
+ const row = normalized.rows[i];
481
160
  const excelRow = layout.firstDataRow + i;
482
161
  const sheetRow = sheet.getRow(excelRow);
483
162
  sheetRow.height = layout.dataRowHeightPt;
@@ -529,17 +208,12 @@ async function renderPriceListXlsx(input) {
529
208
  errorTitle: labels.quantity,
530
209
  error: ">= 0"
531
210
  };
532
- const previewBytes = await resolvePreviewBytes(input, i);
533
- const candidateUrl = row.previewImageUrl?.trim() || null;
534
- const sheetsSafeUrl = candidateUrl && isAnonymousHttpImageUrl(candidateUrl) ? candidateUrl : null;
535
- previewImageUrls.push(sheetsSafeUrl);
536
- if (previewBytes) {
537
- const png = await normalizePreviewSquare(
538
- previewBytes,
539
- layout.photoSizePx
540
- );
211
+ const prep = previewPrep[i];
212
+ previewImageUrls.push(prep.sheetsSafeUrl);
213
+ if (prep.warning) warnings.push(prep.warning);
214
+ if (prep.png) {
541
215
  const imageId = workbook.addImage({
542
- buffer: png,
216
+ buffer: prep.png,
543
217
  extension: "png"
544
218
  });
545
219
  sheet.addImage(imageId, {
@@ -547,11 +221,14 @@ async function renderPriceListXlsx(input) {
547
221
  ext: { width: layout.photoSizePx, height: layout.photoSizePx },
548
222
  editAs: "oneCell"
549
223
  });
550
- } else if (sheetsSafeUrl) {
224
+ } else if (prep.sheetsSafeUrl) {
551
225
  sheetCells.push({
552
226
  a1: `${photoCol.letter}${excelRow}`,
553
227
  value: null,
554
- formula: googleSheetsImageFormula(sheetsSafeUrl, layout.photoSizePx)
228
+ formula: googleSheetsImageFormula(
229
+ prep.sheetsSafeUrl,
230
+ layout.photoSizePx
231
+ )
555
232
  });
556
233
  }
557
234
  }
@@ -601,381 +278,31 @@ async function renderPriceListXlsx(input) {
601
278
  }
602
279
  const buffer = Buffer.from(await workbook.xlsx.writeBuffer());
603
280
  const filename = priceListFilename(
604
- input.locale,
605
- input.header.generatedAt,
281
+ normalized.locale,
282
+ normalized.header.generatedAt,
606
283
  labels.filenamePrefix,
607
- input.header.timeZone
284
+ normalized.header.timeZone
608
285
  );
609
286
  const sheetModel = {
610
287
  title,
611
- locale: input.locale,
288
+ locale: normalized.locale,
612
289
  layout,
613
290
  cells: sheetCells,
614
291
  previewImageUrls,
615
- logoUrl: input.header.logoUrl?.trim() || null
292
+ logoUrl: normalized.header.logoUrl?.trim() || null
616
293
  };
617
294
  return {
618
295
  buffer,
619
296
  filename,
620
297
  contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
621
298
  layout,
622
- sheetModel
299
+ sheetModel,
300
+ warnings
623
301
  };
624
302
  }
625
303
  var buildWholesalePriceListXlsx = renderPriceListXlsx;
626
-
627
- // src/wholesale-price-list/google-sheets.ts
628
- var SCOPES = [
629
- "https://www.googleapis.com/auth/spreadsheets",
630
- "https://www.googleapis.com/auth/drive"
631
- ];
632
- function parseServiceAccountJson(raw) {
633
- if (typeof raw === "object" && raw !== null && !Array.isArray(raw)) {
634
- return raw;
635
- }
636
- if (typeof raw !== "string" || !raw.trim()) {
637
- throw new Error("serviceAccountJson is required");
638
- }
639
- try {
640
- const parsed = JSON.parse(raw);
641
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
642
- throw new Error("not an object");
643
- }
644
- return parsed;
645
- } catch {
646
- throw new Error("serviceAccountJson must be valid JSON object");
647
- }
648
- }
649
- async function createPriceListGoogleClients(serviceAccountJson) {
650
- const credentials = parseServiceAccountJson(serviceAccountJson);
651
- const { google } = await import("googleapis");
652
- const auth = new google.auth.GoogleAuth({
653
- credentials,
654
- scopes: SCOPES
655
- });
656
- return {
657
- sheets: google.sheets({
658
- version: "v4",
659
- auth
660
- }),
661
- drive: google.drive({
662
- version: "v3",
663
- auth
664
- })
665
- };
666
- }
667
- async function resolvePreviewBytes2(input, rowIndex) {
668
- const row = input.rows[rowIndex];
669
- if (row.previewImageBytes && row.previewImageBytes.byteLength > 0) {
670
- return row.previewImageBytes;
671
- }
672
- if (input.loadPreviewImage) {
673
- return input.loadPreviewImage({
674
- previewMediaId: row.previewMediaId,
675
- previewImageUrl: row.previewImageUrl
676
- });
677
- }
678
- const url = row.previewImageUrl?.trim();
679
- if (url && isAnonymousHttpImageUrl(url)) {
680
- return fetchAbsoluteUrlBytes(url);
681
- }
682
- return null;
683
- }
684
- async function resolveLogoBytes2(input) {
685
- if (input.header.logoBytes && input.header.logoBytes.byteLength > 0) {
686
- return input.header.logoBytes;
687
- }
688
- const url = input.header.logoUrl?.trim();
689
- if (!url) return null;
690
- if (input.loadLogo) return input.loadLogo(url);
691
- if (isAnonymousHttpImageUrl(url)) return fetchAbsoluteUrlBytes(url);
692
- return null;
693
- }
694
- async function uploadPngPublic(drive, name, png, folderId) {
695
- const created = await drive.files.create({
696
- requestBody: {
697
- name,
698
- mimeType: "image/png",
699
- parents: folderId ? [folderId] : void 0
700
- },
701
- media: { mimeType: "image/png", body: Buffer.from(png) },
702
- fields: "id",
703
- supportsAllDrives: true
704
- });
705
- const fileId = created.data.id;
706
- if (!fileId) throw new Error("Drive file create returned no id");
707
- await drive.permissions.create({
708
- fileId,
709
- requestBody: { role: "reader", type: "anyone" },
710
- supportsAllDrives: true
711
- });
712
- return `https://drive.google.com/uc?export=view&id=${encodeURIComponent(fileId)}`;
713
- }
714
- function colWidthPixels(layout, key) {
715
- if (key === "photo") return Math.round(layout.photoSizePx * 1.15);
716
- if (key === "product") return 180;
717
- if (key === "link" || key === "quantity" || key === "sum" || key === "price")
718
- return 100;
719
- if (key === "currencyHidden") return 1;
720
- return 120;
721
- }
722
- async function renderPriceListGoogleSheet(input, options) {
723
- validatePriceListInput(input);
724
- const labels = resolvePriceListLabels(input.locale, input.labels);
725
- const layout = buildPriceListLayout(input);
726
- const clients = options.clients ?? await createPriceListGoogleClients(options.serviceAccountJson);
727
- const { sheets, drive } = clients;
728
- const title = `${input.header.siteName} \u2014 ${labels.title} (${input.locale})`.slice(
729
- 0,
730
- 100
731
- );
732
- const created = await sheets.spreadsheets.create({
733
- requestBody: {
734
- properties: { title },
735
- sheets: [
736
- {
737
- properties: {
738
- title: labels.title.slice(0, 100),
739
- gridProperties: {
740
- frozenRowCount: layout.headerRow
741
- }
742
- }
743
- }
744
- ]
745
- },
746
- fields: "spreadsheetId,spreadsheetUrl"
747
- });
748
- const spreadsheetId = created.data.spreadsheetId;
749
- const spreadsheetUrl = created.data.spreadsheetUrl;
750
- if (!spreadsheetId || !spreadsheetUrl) {
751
- throw new Error("Sheets create returned no spreadsheetId/url");
752
- }
753
- const meta = await sheets.spreadsheets.get({
754
- spreadsheetId,
755
- fields: "sheets.properties"
756
- });
757
- const sheetId = meta.data.sheets?.[0]?.properties?.sheetId;
758
- if (sheetId == null) throw new Error("Missing sheetId");
759
- if (options.driveFolderId?.trim()) {
760
- const file = await drive.files.get({
761
- fileId: spreadsheetId,
762
- fields: "parents",
763
- supportsAllDrives: true
764
- });
765
- const prevParents = (file.data.parents ?? []).join(",");
766
- await drive.files.update({
767
- fileId: spreadsheetId,
768
- addParents: options.driveFolderId.trim(),
769
- removeParents: prevParents || void 0,
770
- supportsAllDrives: true,
771
- fields: "id,parents"
772
- });
773
- }
774
- if (options.shareWithEmail?.trim()) {
775
- await drive.permissions.create({
776
- fileId: spreadsheetId,
777
- requestBody: {
778
- type: "user",
779
- role: "writer",
780
- emailAddress: options.shareWithEmail.trim()
781
- },
782
- sendNotificationEmail: false,
783
- supportsAllDrives: true
784
- });
785
- }
786
- const folderId = options.driveFolderId?.trim() || null;
787
- let logoImageUrl = null;
788
- const logoBytes = await resolveLogoBytes2(input);
789
- if (logoBytes) {
790
- const png = await rasterizeLogo(logoBytes);
791
- logoImageUrl = await uploadPngPublic(
792
- drive,
793
- `price-list-logo-${input.locale}.png`,
794
- png,
795
- folderId
796
- );
797
- } else {
798
- const candidate = input.header.logoUrl?.trim() || null;
799
- if (candidate && !/\.svg(\?|$)/i.test(candidate) && isAnonymousHttpImageUrl(candidate)) {
800
- logoImageUrl = candidate;
801
- }
802
- }
803
- const generated = formatGeneratedLabel(
804
- labels.generated,
805
- input.header.generatedAt,
806
- input.locale,
807
- input.header.timeZone
808
- );
809
- const lastColLetter = layout.columns.find((c) => c.key === "sum").letter;
810
- const values = [];
811
- const bannerRow1 = Array(layout.columns.length).fill("");
812
- bannerRow1[0] = input.header.siteName;
813
- if (logoImageUrl) {
814
- bannerRow1[5] = googleSheetsImageFormula(logoImageUrl, 40);
815
- }
816
- values.push(bannerRow1);
817
- values.push([
818
- input.header.contacts,
819
- ...Array(layout.columns.length - 1).fill("")
820
- ]);
821
- values.push([generated, ...Array(layout.columns.length - 1).fill("")]);
822
- values.push(
823
- layout.columns.map((c) => c.key === "currencyHidden" ? "" : c.header)
824
- );
825
- const currencies = /* @__PURE__ */ new Set();
826
- for (let i = 0; i < input.rows.length; i++) {
827
- const row = input.rows[i];
828
- const excelRow = layout.firstDataRow + i;
829
- const line = Array(layout.columns.length).fill("");
830
- const photoIdx = layout.columns.findIndex((c) => c.key === "photo");
831
- let imageUrl = null;
832
- const bytes = await resolvePreviewBytes2(input, i);
833
- if (bytes) {
834
- const png = await normalizePreviewSquare(bytes, layout.photoSizePx);
835
- imageUrl = await uploadPngPublic(
836
- drive,
837
- `price-list-${row.productId}-${row.variantId ?? "p"}.png`,
838
- png,
839
- folderId
840
- );
841
- } else {
842
- const candidate = row.previewImageUrl?.trim() || null;
843
- if (candidate && isAnonymousHttpImageUrl(candidate)) {
844
- imageUrl = candidate;
845
- }
846
- }
847
- if (imageUrl && photoIdx >= 0) {
848
- line[photoIdx] = googleSheetsImageFormula(imageUrl, layout.photoSizePx);
849
- }
850
- line[layout.columns.findIndex((c) => c.key === "category")] = row.category ?? "";
851
- line[layout.columns.findIndex((c) => c.key === "product")] = row.product;
852
- line[layout.columns.findIndex((c) => c.key === "variant")] = row.variant ?? "";
853
- line[layout.columns.findIndex((c) => c.key === "packaging")] = row.packaging ?? "";
854
- const priceIdx = layout.columns.findIndex((c) => c.key === "price");
855
- if (row.unitPrice === null) {
856
- line[priceIdx] = labels.onRequest;
857
- } else {
858
- line[priceIdx] = String(row.unitPrice);
859
- }
860
- const linkIdx = layout.columns.findIndex((c) => c.key === "link");
861
- line[linkIdx] = `=HYPERLINK("${row.productUrl.replace(/"/g, '""')}","${labels.linkText.replace(/"/g, '""')}")`;
862
- const qtyIdx = layout.columns.findIndex((c) => c.key === "quantity");
863
- line[qtyIdx] = "";
864
- const sumIdx = layout.columns.findIndex((c) => c.key === "sum");
865
- line[sumIdx] = `=${buildLineSumFormula({ layout, row: excelRow })}`;
866
- const curIdx = layout.columns.findIndex((c) => c.key === "currencyHidden");
867
- const cur = row.currency?.trim() || "";
868
- line[curIdx] = cur;
869
- if (cur) currencies.add(cur);
870
- values.push(line);
871
- }
872
- const currencyList = [...currencies].sort();
873
- const multi = currencyList.length > 1;
874
- if (!multi) {
875
- const totalLine = Array(layout.columns.length).fill("");
876
- totalLine[layout.columns.findIndex((c) => c.key === "quantity")] = labels.total;
877
- const lastData = input.rows.length === 0 ? layout.firstDataRow - 1 : layout.firstDataRow + input.rows.length - 1;
878
- totalLine[layout.columns.findIndex((c) => c.key === "sum")] = `=${buildTotalSumFormula({
879
- layout,
880
- firstDataRow: layout.firstDataRow,
881
- lastDataRow: lastData
882
- })}`;
883
- values.push(totalLine);
884
- } else {
885
- const lastData = layout.firstDataRow + input.rows.length - 1;
886
- for (let i = 0; i < currencyList.length; i++) {
887
- const currency = currencyList[i];
888
- const totalLine = Array(layout.columns.length).fill("");
889
- totalLine[layout.columns.findIndex((c) => c.key === "quantity")] = i === 0 ? `${labels.total} (${currency})` : currency;
890
- totalLine[layout.columns.findIndex((c) => c.key === "sum")] = `=${buildCurrencyTotalSumIfFormula({
891
- layout,
892
- firstDataRow: layout.firstDataRow,
893
- lastDataRow: lastData,
894
- currency
895
- })}`;
896
- values.push(totalLine);
897
- }
898
- }
899
- await sheets.spreadsheets.values.update({
900
- spreadsheetId,
901
- range: `A1:${lastColLetter}${values.length}`,
902
- valueInputOption: "USER_ENTERED",
903
- requestBody: { values }
904
- });
905
- const requests = [];
906
- for (const col of layout.columns) {
907
- requests.push({
908
- updateDimensionProperties: {
909
- range: {
910
- sheetId,
911
- dimension: "COLUMNS",
912
- startIndex: col.index - 1,
913
- endIndex: col.index
914
- },
915
- properties: {
916
- pixelSize: colWidthPixels(layout, col.key),
917
- hiddenByUser: col.key === "currencyHidden"
918
- },
919
- fields: "pixelSize,hiddenByUser"
920
- }
921
- });
922
- }
923
- if (input.rows.length > 0) {
924
- requests.push({
925
- updateDimensionProperties: {
926
- range: {
927
- sheetId,
928
- dimension: "ROWS",
929
- startIndex: layout.firstDataRow - 1,
930
- endIndex: layout.firstDataRow - 1 + input.rows.length
931
- },
932
- properties: { pixelSize: 130 },
933
- fields: "pixelSize"
934
- }
935
- });
936
- }
937
- requests.push({
938
- setBasicFilter: {
939
- filter: {
940
- range: {
941
- sheetId,
942
- startRowIndex: layout.headerRow - 1,
943
- endRowIndex: layout.headerRow + input.rows.length,
944
- startColumnIndex: 0,
945
- endColumnIndex: layout.columns.find((c) => c.key === "sum").index
946
- }
947
- }
948
- }
949
- });
950
- if (input.rows.length > 0) {
951
- const qtyCol = layout.columns.find((c) => c.key === "quantity").index - 1;
952
- requests.push({
953
- setDataValidation: {
954
- range: {
955
- sheetId,
956
- startRowIndex: layout.firstDataRow - 1,
957
- endRowIndex: layout.firstDataRow - 1 + input.rows.length,
958
- startColumnIndex: qtyCol,
959
- endColumnIndex: qtyCol + 1
960
- },
961
- rule: {
962
- condition: {
963
- type: "NUMBER_GREATER_THAN_EQ",
964
- values: [{ userEnteredValue: "0" }]
965
- },
966
- strict: true,
967
- showCustomUi: true
968
- }
969
- }
970
- });
971
- }
972
- await sheets.spreadsheets.batchUpdate({
973
- spreadsheetId,
974
- requestBody: { requests }
975
- });
976
- return { spreadsheetId, spreadsheetUrl };
977
- }
978
304
  export {
305
+ DEFAULT_PREVIEW_IMAGE_CONCURRENCY,
979
306
  PRICE_LIST_BANNER_ROW_COUNT,
980
307
  PRICE_LIST_DATA_ROW_HEIGHT_PT,
981
308
  PRICE_LIST_DEFAULT_PHOTO_PX,
@@ -986,21 +313,23 @@ export {
986
313
  buildTotalSumFormula,
987
314
  buildWholesalePriceListXlsx,
988
315
  coerceUnitPrice,
989
- createPriceListGoogleClients,
990
316
  excelColumnLetter,
991
317
  fetchAbsoluteUrlBytes,
992
318
  formatGeneratedLabel,
993
319
  googleSheetsImageFormula,
994
320
  isAnonymousHttpImageUrl,
995
321
  isMailooApiKeyedImageUrl,
322
+ mapWithConcurrency,
996
323
  mediaIdFromMailooPublicImageUrl,
997
324
  normalizePreviewSquare,
998
325
  priceListFilename,
999
326
  priceListFilenameDate,
1000
327
  rasterizeLogo,
1001
- renderPriceListGoogleSheet,
1002
328
  renderPriceListXlsx,
329
+ resolvePreviewImageConcurrency,
1003
330
  resolvePriceListLabels,
331
+ tryNormalizePreviewSquare,
332
+ tryRasterizeLogo,
1004
333
  validatePriceListInput
1005
334
  };
1006
335
  //# sourceMappingURL=index.js.map