@mailoo/market 1.35.10 → 1.35.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,822 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/wholesale-price-list/index.ts
31
+ var wholesale_price_list_exports = {};
32
+ __export(wholesale_price_list_exports, {
33
+ DEFAULT_PREVIEW_IMAGE_CONCURRENCY: () => DEFAULT_PREVIEW_IMAGE_CONCURRENCY,
34
+ PRICE_LIST_BANNER_ROW_COUNT: () => PRICE_LIST_BANNER_ROW_COUNT,
35
+ PRICE_LIST_DATA_ROW_HEIGHT_PT: () => PRICE_LIST_DATA_ROW_HEIGHT_PT,
36
+ PRICE_LIST_DEFAULT_PHOTO_PX: () => PRICE_LIST_DEFAULT_PHOTO_PX,
37
+ PRICE_LIST_PHOTO_COL_CHARS: () => PRICE_LIST_PHOTO_COL_CHARS,
38
+ buildCurrencyTotalSumIfFormula: () => buildCurrencyTotalSumIfFormula,
39
+ buildLineSumFormula: () => buildLineSumFormula,
40
+ buildPriceListLayout: () => buildPriceListLayout,
41
+ buildTotalSumFormula: () => buildTotalSumFormula,
42
+ buildWholesalePriceListXlsx: () => buildWholesalePriceListXlsx,
43
+ coerceUnitPrice: () => coerceUnitPrice,
44
+ excelColumnLetter: () => excelColumnLetter,
45
+ fetchAbsoluteUrlBytes: () => fetchAbsoluteUrlBytes,
46
+ formatGeneratedLabel: () => formatGeneratedLabel,
47
+ googleSheetsImageFormula: () => googleSheetsImageFormula,
48
+ isAnonymousHttpImageUrl: () => isAnonymousHttpImageUrl,
49
+ isMailooApiKeyedImageUrl: () => isMailooApiKeyedImageUrl,
50
+ mapWithConcurrency: () => mapWithConcurrency,
51
+ mediaIdFromMailooPublicImageUrl: () => mediaIdFromMailooPublicImageUrl,
52
+ normalizePreviewSquare: () => normalizePreviewSquare,
53
+ priceListFilename: () => priceListFilename,
54
+ priceListFilenameDate: () => priceListFilenameDate,
55
+ rasterizeLogo: () => rasterizeLogo,
56
+ renderPriceListXlsx: () => renderPriceListXlsx,
57
+ resolvePreviewImageConcurrency: () => resolvePreviewImageConcurrency,
58
+ resolvePriceListLabels: () => resolvePriceListLabels,
59
+ tryNormalizePreviewSquare: () => tryNormalizePreviewSquare,
60
+ tryRasterizeLogo: () => tryRasterizeLogo,
61
+ validatePriceListInput: () => validatePriceListInput
62
+ });
63
+ module.exports = __toCommonJS(wholesale_price_list_exports);
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
+
87
+ // src/wholesale-price-list/labels.ts
88
+ var BUILTIN = {
89
+ en: {
90
+ title: "Price list",
91
+ photo: "Photo",
92
+ category: "Category",
93
+ product: "Product",
94
+ variant: "Variant",
95
+ packaging: "Packaging",
96
+ price: "Price",
97
+ onRequest: "on request",
98
+ link: "Link",
99
+ linkText: "Open",
100
+ quantity: "Quantity",
101
+ sum: "Sum",
102
+ total: "Total",
103
+ generated: "Generated: {date}",
104
+ filenamePrefix: "price-list"
105
+ },
106
+ ru: {
107
+ title: "\u041F\u0440\u0430\u0439\u0441-\u043B\u0438\u0441\u0442",
108
+ photo: "\u0424\u043E\u0442\u043E",
109
+ category: "\u041A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F",
110
+ product: "\u0422\u043E\u0432\u0430\u0440",
111
+ variant: "\u0412\u0430\u0440\u0438\u0430\u043D\u0442",
112
+ packaging: "\u0423\u043F\u0430\u043A\u043E\u0432\u043A\u0430",
113
+ price: "\u0426\u0435\u043D\u0430",
114
+ onRequest: "\u043F\u043E \u0437\u0430\u043F\u0440\u043E\u0441\u0443",
115
+ link: "\u0421\u0441\u044B\u043B\u043A\u0430",
116
+ linkText: "\u041E\u0442\u043A\u0440\u044B\u0442\u044C",
117
+ quantity: "\u041A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E",
118
+ sum: "\u0421\u0443\u043C\u043C\u0430",
119
+ total: "\u0418\u0442\u043E\u0433\u043E",
120
+ generated: "\u0421\u0444\u043E\u0440\u043C\u0438\u0440\u043E\u0432\u0430\u043D\u043E: {date}",
121
+ filenamePrefix: "price-list"
122
+ },
123
+ hy: {
124
+ title: "\u0533\u0576\u0561\u0581\u0578\u0582\u0581\u0561\u056F",
125
+ photo: "\u053C\u0578\u0582\u057D\u0561\u0576\u056F\u0561\u0580",
126
+ category: "\u053F\u0561\u057F\u0565\u0563\u0578\u0580\u056B\u0561",
127
+ product: "\u0531\u057A\u0580\u0561\u0576\u0584",
128
+ variant: "\u054F\u0561\u0580\u0562\u0565\u0580\u0561\u056F",
129
+ packaging: "\u0553\u0561\u0569\u0565\u0569\u0561\u057E\u0578\u0580\u0578\u0582\u0574",
130
+ price: "\u0533\u056B\u0576",
131
+ onRequest: "\u0568\u057D\u057F \u0570\u0561\u0580\u0581\u0574\u0561\u0576",
132
+ link: "\u0540\u0572\u0578\u0582\u0574",
133
+ linkText: "\u0532\u0561\u0581\u0565\u056C",
134
+ quantity: "\u0554\u0561\u0576\u0561\u056F",
135
+ sum: "\u0533\u0578\u0582\u0574\u0561\u0580",
136
+ total: "\u0538\u0576\u0564\u0561\u0574\u0565\u0576\u0568",
137
+ generated: "\u054D\u057F\u0565\u0572\u056E\u057E\u0561\u056E \u0567\u055D {date}",
138
+ filenamePrefix: "price-list"
139
+ },
140
+ de: {
141
+ title: "Preisliste",
142
+ photo: "Foto",
143
+ category: "Kategorie",
144
+ product: "Produkt",
145
+ variant: "Variante",
146
+ packaging: "Verpackung",
147
+ price: "Preis",
148
+ onRequest: "auf Anfrage",
149
+ link: "Link",
150
+ linkText: "\xD6ffnen",
151
+ quantity: "Menge",
152
+ sum: "Summe",
153
+ total: "Gesamt",
154
+ generated: "Erstellt: {date}",
155
+ filenamePrefix: "price-list"
156
+ },
157
+ es: {
158
+ title: "Lista de precios",
159
+ photo: "Foto",
160
+ category: "Categor\xEDa",
161
+ product: "Producto",
162
+ variant: "Variante",
163
+ packaging: "Embalaje",
164
+ price: "Precio",
165
+ onRequest: "bajo petici\xF3n",
166
+ link: "Enlace",
167
+ linkText: "Abrir",
168
+ quantity: "Cantidad",
169
+ sum: "Suma",
170
+ total: "Total",
171
+ generated: "Generado: {date}",
172
+ filenamePrefix: "price-list"
173
+ }
174
+ };
175
+ var BUILTIN_LOCALES = /* @__PURE__ */ new Set(["hy", "ru", "en", "de", "es"]);
176
+ function resolvePriceListLabels(locale, overrides) {
177
+ const code = locale.trim().toLowerCase();
178
+ const base = BUILTIN_LOCALES.has(code) ? BUILTIN[code] : BUILTIN.en;
179
+ return { ...base, ...overrides };
180
+ }
181
+ function formatGeneratedLabel(template, generatedAt, locale, timeZone) {
182
+ const d = new Date(generatedAt);
183
+ if (Number.isNaN(d.getTime())) {
184
+ throw new Error(`header.generatedAt is not a valid ISO date: ${generatedAt}`);
185
+ }
186
+ const tz = timeZone && timeZone.trim() !== "" ? timeZone.trim() : "UTC";
187
+ const date = new Intl.DateTimeFormat(locale, {
188
+ dateStyle: "medium",
189
+ timeStyle: "short",
190
+ timeZone: tz
191
+ }).format(d);
192
+ return template.replace(/\{date\}/g, date);
193
+ }
194
+ function priceListFilenameDate(generatedAt, timeZone) {
195
+ const d = new Date(generatedAt);
196
+ if (Number.isNaN(d.getTime())) {
197
+ throw new Error(`header.generatedAt is not a valid ISO date: ${generatedAt}`);
198
+ }
199
+ const tz = timeZone && timeZone.trim() !== "" ? timeZone.trim() : "UTC";
200
+ const parts = new Intl.DateTimeFormat("en-US", {
201
+ timeZone: tz,
202
+ year: "numeric",
203
+ month: "2-digit",
204
+ day: "2-digit"
205
+ }).formatToParts(d);
206
+ const y = parts.find((p) => p.type === "year")?.value;
207
+ const m = parts.find((p) => p.type === "month")?.value;
208
+ const day = parts.find((p) => p.type === "day")?.value;
209
+ if (!y || !m || !day) {
210
+ throw new Error(`Failed to format filename date for timeZone=${tz}`);
211
+ }
212
+ return `${y}-${m}-${day}`;
213
+ }
214
+ function priceListFilename(locale, generatedAt, prefix, timeZone) {
215
+ const date = priceListFilenameDate(generatedAt, timeZone);
216
+ return `${prefix}-${locale}-${date}.xlsx`;
217
+ }
218
+
219
+ // src/wholesale-price-list/unit-price.ts
220
+ function coerceUnitPrice(value) {
221
+ if (value === null) return null;
222
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
223
+ return null;
224
+ }
225
+ return value;
226
+ }
227
+
228
+ // src/wholesale-price-list/layout.ts
229
+ var PRICE_LIST_DEFAULT_PHOTO_PX = 120;
230
+ var PRICE_LIST_DATA_ROW_HEIGHT_PT = 96;
231
+ var PRICE_LIST_PHOTO_COL_CHARS = 18;
232
+ var PRICE_LIST_BANNER_ROW_COUNT = 3;
233
+ function excelColumnLetter(index1Based) {
234
+ if (!Number.isInteger(index1Based) || index1Based < 1) {
235
+ throw new Error(`Invalid column index: ${index1Based}`);
236
+ }
237
+ let n = index1Based;
238
+ let s = "";
239
+ while (n > 0) {
240
+ const rem = (n - 1) % 26;
241
+ s = String.fromCharCode(65 + rem) + s;
242
+ n = Math.floor((n - 1) / 26);
243
+ }
244
+ return s;
245
+ }
246
+ function validatePriceListInput(input) {
247
+ if (!input || typeof input !== "object") {
248
+ throw new Error("PriceListInput is required");
249
+ }
250
+ if (typeof input.locale !== "string" || input.locale.trim() === "") {
251
+ throw new Error("locale is required");
252
+ }
253
+ if (!input.header || typeof input.header !== "object") {
254
+ throw new Error("header is required");
255
+ }
256
+ if (typeof input.header.siteName !== "string" || input.header.siteName.trim() === "") {
257
+ throw new Error("header.siteName is required");
258
+ }
259
+ if (typeof input.header.contacts !== "string") {
260
+ throw new Error("header.contacts must be a string");
261
+ }
262
+ if (typeof input.header.generatedAt !== "string" || Number.isNaN(new Date(input.header.generatedAt).getTime())) {
263
+ throw new Error("header.generatedAt must be a valid ISO date string");
264
+ }
265
+ if (!Array.isArray(input.rows)) {
266
+ throw new Error("rows must be an array");
267
+ }
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) => {
275
+ if (typeof row.productId !== "string" || row.productId.trim() === "") {
276
+ throw new Error(`rows[${i}].productId is required`);
277
+ }
278
+ if (typeof row.product !== "string" || row.product.trim() === "") {
279
+ throw new Error(`rows[${i}].product is required`);
280
+ }
281
+ if (typeof row.productUrl !== "string" || row.productUrl.trim() === "") {
282
+ throw new Error(`rows[${i}].productUrl is required`);
283
+ }
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;
298
+ }
299
+ function buildPriceListLayout(input) {
300
+ const normalized = validatePriceListInput(input);
301
+ const labels = resolvePriceListLabels(normalized.locale, normalized.labels);
302
+ const photoSizePx = normalized.photoSizePx ?? PRICE_LIST_DEFAULT_PHOTO_PX;
303
+ const headerRow = PRICE_LIST_BANNER_ROW_COUNT + 1;
304
+ const firstDataRow = headerRow + 1;
305
+ const totalRow = firstDataRow + normalized.rows.length;
306
+ const keys = [
307
+ { key: "photo", header: labels.photo },
308
+ { key: "category", header: labels.category },
309
+ { key: "product", header: labels.product },
310
+ { key: "variant", header: labels.variant },
311
+ { key: "packaging", header: labels.packaging },
312
+ { key: "price", header: labels.price },
313
+ { key: "link", header: labels.link },
314
+ { key: "quantity", header: labels.quantity },
315
+ { key: "sum", header: labels.sum },
316
+ { key: "currencyHidden", header: "" }
317
+ ];
318
+ const columns = keys.map((c, i) => ({
319
+ key: c.key,
320
+ header: c.header,
321
+ index: i + 1,
322
+ letter: excelColumnLetter(i + 1)
323
+ }));
324
+ const letter = (key) => {
325
+ const col = columns.find((c) => c.key === key);
326
+ if (!col) throw new Error(`Missing column ${key}`);
327
+ return col.letter;
328
+ };
329
+ return {
330
+ locale: normalized.locale,
331
+ photoSizePx,
332
+ dataRowHeightPt: PRICE_LIST_DATA_ROW_HEIGHT_PT,
333
+ photoColWidthChars: PRICE_LIST_PHOTO_COL_CHARS,
334
+ headerRow,
335
+ firstDataRow,
336
+ totalRow,
337
+ columns,
338
+ priceColLetter: letter("price"),
339
+ quantityColLetter: letter("quantity"),
340
+ sumColLetter: letter("sum"),
341
+ currencyColLetter: letter("currencyHidden"),
342
+ linkColLetter: letter("link")
343
+ };
344
+ }
345
+
346
+ // src/wholesale-price-list/fetch-url.ts
347
+ async function fetchAbsoluteUrlBytes(url) {
348
+ const trimmed = url.trim();
349
+ if (!/^https?:\/\//i.test(trimmed)) return null;
350
+ try {
351
+ const res = await fetch(trimmed);
352
+ if (!res.ok) return null;
353
+ const buf = new Uint8Array(await res.arrayBuffer());
354
+ return buf.byteLength > 0 ? buf : null;
355
+ } catch {
356
+ return null;
357
+ }
358
+ }
359
+ function isMailooApiKeyedImageUrl(url) {
360
+ try {
361
+ const u = new URL(url.trim());
362
+ return u.pathname.includes("/api/v1/images/public/content");
363
+ } catch {
364
+ return false;
365
+ }
366
+ }
367
+ function mediaIdFromMailooPublicImageUrl(url) {
368
+ try {
369
+ const u = new URL(url.trim());
370
+ if (!u.pathname.includes("/api/v1/images/public/content")) return null;
371
+ const id = u.searchParams.get("id")?.trim();
372
+ return id || null;
373
+ } catch {
374
+ return null;
375
+ }
376
+ }
377
+ function isAnonymousHttpImageUrl(url) {
378
+ const trimmed = url.trim();
379
+ if (!/^https?:\/\//i.test(trimmed)) return false;
380
+ if (isMailooApiKeyedImageUrl(trimmed)) return false;
381
+ return true;
382
+ }
383
+
384
+ // src/wholesale-price-list/sum-formula.ts
385
+ function buildLineSumFormula(args) {
386
+ const { layout, row } = args;
387
+ const q = `${layout.quantityColLetter}${row}`;
388
+ const p = `${layout.priceColLetter}${row}`;
389
+ return `IFERROR(IF(N(${q})<=0,"",IF(NOT(ISNUMBER(${p})),"",${q}*${p})),"")`;
390
+ }
391
+ function buildTotalSumFormula(args) {
392
+ const { layout, firstDataRow, lastDataRow } = args;
393
+ if (lastDataRow < firstDataRow) return "0";
394
+ const range = `${layout.sumColLetter}${firstDataRow}:${layout.sumColLetter}${lastDataRow}`;
395
+ return `SUM(${range})`;
396
+ }
397
+ function buildCurrencyTotalSumIfFormula(args) {
398
+ const { layout, firstDataRow, lastDataRow, currency } = args;
399
+ if (lastDataRow < firstDataRow) return "0";
400
+ if (!currency || currency.includes('"')) {
401
+ throw new Error("currency for SUMIF must be a non-empty string without quotes");
402
+ }
403
+ const sumRange = `${layout.sumColLetter}${firstDataRow}:${layout.sumColLetter}${lastDataRow}`;
404
+ const curRange = `${layout.currencyColLetter}${firstDataRow}:${layout.currencyColLetter}${lastDataRow}`;
405
+ return `SUMIF(${curRange},"${currency}",${sumRange})`;
406
+ }
407
+
408
+ // src/wholesale-price-list/preview-image.ts
409
+ var import_sharp = __toESM(require("sharp"), 1);
410
+ function errorMessage(e) {
411
+ return e instanceof Error ? e.message : String(e);
412
+ }
413
+ async function normalizePreviewSquare(input, sizePx = PRICE_LIST_DEFAULT_PHOTO_PX) {
414
+ if (!Number.isInteger(sizePx) || sizePx < 32) {
415
+ throw new Error("sizePx must be an integer >= 32");
416
+ }
417
+ if (input.byteLength === 0) {
418
+ throw new Error("Empty preview image");
419
+ }
420
+ return (0, import_sharp.default)(Buffer.from(input), {
421
+ limitInputPixels: 268435456,
422
+ failOn: "error"
423
+ }).rotate().resize({
424
+ width: sizePx,
425
+ height: sizePx,
426
+ fit: "contain",
427
+ background: { r: 255, g: 255, b: 255, alpha: 1 }
428
+ }).png().toBuffer();
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
+ }
442
+ async function rasterizeLogo(input, opts) {
443
+ if (input.byteLength === 0) {
444
+ throw new Error("Empty logo image");
445
+ }
446
+ const widthPx = opts?.widthPx ?? 120;
447
+ const heightPx = opts?.heightPx ?? 40;
448
+ if (!Number.isInteger(widthPx) || widthPx < 16) {
449
+ throw new Error("logo widthPx must be an integer >= 16");
450
+ }
451
+ if (!Number.isInteger(heightPx) || heightPx < 16) {
452
+ throw new Error("logo heightPx must be an integer >= 16");
453
+ }
454
+ try {
455
+ return await (0, import_sharp.default)(Buffer.from(input), {
456
+ limitInputPixels: 268435456,
457
+ failOn: "error",
458
+ density: 288
459
+ }).resize({
460
+ width: widthPx,
461
+ height: heightPx,
462
+ fit: "contain",
463
+ background: { r: 255, g: 255, b: 255, alpha: 0 }
464
+ }).png().toBuffer();
465
+ } catch (e) {
466
+ throw new Error(
467
+ `Failed to rasterize logo (SVG/PNG/JPEG/WebP required): ${errorMessage(e)}`
468
+ );
469
+ }
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
+ }
483
+ function googleSheetsImageFormula(url, sizePx) {
484
+ const safe = url.replace(/"/g, '""');
485
+ return `=IMAGE("${safe}",4,${sizePx},${sizePx})`;
486
+ }
487
+
488
+ // src/wholesale-price-list/build-xlsx.ts
489
+ var import_exceljs = __toESM(require("exceljs"), 1);
490
+
491
+ // src/wholesale-price-list/resolve-media.ts
492
+ async function resolvePreviewBytes(input, rowIndex) {
493
+ const row = input.rows[rowIndex];
494
+ if (row.previewImageBytes && row.previewImageBytes.byteLength > 0) {
495
+ return row.previewImageBytes;
496
+ }
497
+ if (input.loadPreviewImage) {
498
+ return input.loadPreviewImage({
499
+ previewMediaId: row.previewMediaId,
500
+ previewImageUrl: row.previewImageUrl
501
+ });
502
+ }
503
+ const url = row.previewImageUrl?.trim();
504
+ if (url && isAnonymousHttpImageUrl(url)) {
505
+ return fetchAbsoluteUrlBytes(url);
506
+ }
507
+ return null;
508
+ }
509
+ async function resolveLogoBytes(input) {
510
+ if (input.header.logoBytes && input.header.logoBytes.byteLength > 0) {
511
+ return input.header.logoBytes;
512
+ }
513
+ const url = input.header.logoUrl?.trim();
514
+ if (!url) return null;
515
+ if (input.loadLogo) return input.loadLogo(url);
516
+ if (isAnonymousHttpImageUrl(url)) return fetchAbsoluteUrlBytes(url);
517
+ return null;
518
+ }
519
+
520
+ // src/wholesale-price-list/build-xlsx.ts
521
+ function uniqueCurrencies(input) {
522
+ const set = /* @__PURE__ */ new Set();
523
+ for (const row of input.rows) {
524
+ const c = row.currency?.trim();
525
+ if (c) set.add(c);
526
+ }
527
+ return [...set].sort();
528
+ }
529
+ async function renderPriceListXlsx(input) {
530
+ const normalized = validatePriceListInput(input);
531
+ const warnings = [];
532
+ const labels = resolvePriceListLabels(normalized.locale, normalized.labels);
533
+ const layout = buildPriceListLayout(normalized);
534
+ const title = labels.title;
535
+ const currencies = uniqueCurrencies(normalized);
536
+ const multiCurrency = currencies.length > 1;
537
+ const concurrency = resolvePreviewImageConcurrency(normalized);
538
+ const workbook = new import_exceljs.default.Workbook();
539
+ workbook.creator = "Mailoo";
540
+ workbook.created = new Date(normalized.header.generatedAt);
541
+ const sheetName = `${normalized.header.siteName}`.slice(0, 31) || title.slice(0, 31);
542
+ const sheet = workbook.addWorksheet(sheetName, {
543
+ properties: { defaultRowHeight: layout.dataRowHeightPt },
544
+ views: [{ state: "frozen", ySplit: layout.headerRow }],
545
+ pageSetup: {
546
+ orientation: "landscape",
547
+ fitToPage: true,
548
+ fitToWidth: 1,
549
+ fitToHeight: 0
550
+ }
551
+ });
552
+ for (const col of layout.columns) {
553
+ let width = 16;
554
+ if (col.key === "photo") width = layout.photoColWidthChars;
555
+ else if (col.key === "link") width = 14;
556
+ else if (col.key === "quantity" || col.key === "sum" || col.key === "price")
557
+ width = 12;
558
+ else if (col.key === "currencyHidden") width = 0;
559
+ else if (col.key === "product") width = 28;
560
+ sheet.getColumn(col.index).width = width;
561
+ if (col.key === "currencyHidden") {
562
+ sheet.getColumn(col.index).hidden = true;
563
+ }
564
+ }
565
+ sheet.getCell("A1").value = normalized.header.siteName;
566
+ sheet.getCell("A1").font = { bold: true, size: 16 };
567
+ sheet.mergeCells(1, 1, 1, Math.min(5, layout.columns.length));
568
+ sheet.getCell("A2").value = normalized.header.contacts;
569
+ sheet.getCell("A2").alignment = { wrapText: true, vertical: "top" };
570
+ const contactLines = normalized.header.contacts.split(/\r?\n/).length;
571
+ sheet.getRow(2).height = Math.max(36, contactLines * 14);
572
+ sheet.getCell("A3").value = formatGeneratedLabel(
573
+ labels.generated,
574
+ normalized.header.generatedAt,
575
+ normalized.locale,
576
+ normalized.header.timeZone
577
+ );
578
+ sheet.getCell("A3").font = { italic: true, size: 10 };
579
+ const logoBytes = await resolveLogoBytes(normalized);
580
+ if (logoBytes) {
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
+ }
595
+ }
596
+ const headerRow = sheet.getRow(layout.headerRow);
597
+ headerRow.font = { bold: true };
598
+ headerRow.height = 22;
599
+ for (const col of layout.columns) {
600
+ if (col.key === "currencyHidden") continue;
601
+ headerRow.getCell(col.index).value = col.header;
602
+ }
603
+ sheet.autoFilter = {
604
+ from: { row: layout.headerRow, column: 1 },
605
+ to: {
606
+ row: layout.headerRow,
607
+ column: layout.columns.find((c) => c.key === "sum").index
608
+ }
609
+ };
610
+ const sheetCells = [];
611
+ const previewImageUrls = [];
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];
646
+ const excelRow = layout.firstDataRow + i;
647
+ const sheetRow = sheet.getRow(excelRow);
648
+ sheetRow.height = layout.dataRowHeightPt;
649
+ const photoCol = layout.columns.find((c) => c.key === "photo");
650
+ const catCol = layout.columns.find((c) => c.key === "category");
651
+ const prodCol = layout.columns.find((c) => c.key === "product");
652
+ const varCol = layout.columns.find((c) => c.key === "variant");
653
+ const packCol = layout.columns.find((c) => c.key === "packaging");
654
+ const priceCol = layout.columns.find((c) => c.key === "price");
655
+ const linkCol = layout.columns.find((c) => c.key === "link");
656
+ const qtyCol = layout.columns.find((c) => c.key === "quantity");
657
+ const sumCol = layout.columns.find((c) => c.key === "sum");
658
+ const curCol = layout.columns.find((c) => c.key === "currencyHidden");
659
+ sheetRow.getCell(catCol.index).value = row.category ?? "";
660
+ sheetRow.getCell(prodCol.index).value = row.product;
661
+ sheetRow.getCell(varCol.index).value = row.variant ?? "";
662
+ sheetRow.getCell(packCol.index).value = row.packaging ?? "";
663
+ if (row.unitPrice === null) {
664
+ sheetRow.getCell(priceCol.index).value = labels.onRequest;
665
+ } else {
666
+ sheetRow.getCell(priceCol.index).value = row.unitPrice;
667
+ sheetRow.getCell(priceCol.index).numFmt = "#,##0.00";
668
+ }
669
+ sheetRow.getCell(linkCol.index).value = {
670
+ text: labels.linkText,
671
+ hyperlink: row.productUrl
672
+ };
673
+ sheetCells.push({
674
+ a1: `${linkCol.letter}${excelRow}`,
675
+ value: labels.linkText,
676
+ formula: `HYPERLINK("${row.productUrl.replace(/"/g, '""')}","${labels.linkText.replace(/"/g, '""')}")`
677
+ });
678
+ sheetRow.getCell(qtyCol.index).value = null;
679
+ const sumFormula = buildLineSumFormula({ layout, row: excelRow });
680
+ sheetRow.getCell(sumCol.index).value = { formula: sumFormula };
681
+ sheetRow.getCell(sumCol.index).numFmt = "#,##0.00";
682
+ sheetCells.push({
683
+ a1: `${sumCol.letter}${excelRow}`,
684
+ value: null,
685
+ formula: sumFormula
686
+ });
687
+ sheetRow.getCell(curCol.index).value = row.currency?.trim() || "";
688
+ sheetRow.getCell(qtyCol.index).dataValidation = {
689
+ type: "whole",
690
+ operator: "greaterThanOrEqual",
691
+ formulae: [0],
692
+ allowBlank: true,
693
+ showErrorMessage: true,
694
+ errorTitle: labels.quantity,
695
+ error: ">= 0"
696
+ };
697
+ const prep = previewPrep[i];
698
+ previewImageUrls.push(prep.sheetsSafeUrl);
699
+ if (prep.warning) warnings.push(prep.warning);
700
+ if (prep.png) {
701
+ const imageId = workbook.addImage({
702
+ buffer: prep.png,
703
+ extension: "png"
704
+ });
705
+ sheet.addImage(imageId, {
706
+ tl: { col: photoCol.index - 1, row: excelRow - 1 },
707
+ ext: { width: layout.photoSizePx, height: layout.photoSizePx },
708
+ editAs: "oneCell"
709
+ });
710
+ } else if (prep.sheetsSafeUrl) {
711
+ sheetCells.push({
712
+ a1: `${photoCol.letter}${excelRow}`,
713
+ value: null,
714
+ formula: googleSheetsImageFormula(
715
+ prep.sheetsSafeUrl,
716
+ layout.photoSizePx
717
+ )
718
+ });
719
+ }
720
+ }
721
+ const totalExcelRow = layout.totalRow;
722
+ const qtyColIdx = layout.columns.find((c) => c.key === "quantity").index;
723
+ const sumColIdx = layout.columns.find((c) => c.key === "sum").index;
724
+ sheet.getRow(totalExcelRow).getCell(qtyColIdx).value = labels.total;
725
+ sheet.getRow(totalExcelRow).getCell(qtyColIdx).font = { bold: true };
726
+ if (!multiCurrency) {
727
+ const totalFormula = buildTotalSumFormula({
728
+ layout,
729
+ firstDataRow: layout.firstDataRow,
730
+ lastDataRow
731
+ });
732
+ sheet.getRow(totalExcelRow).getCell(sumColIdx).value = {
733
+ formula: totalFormula
734
+ };
735
+ sheet.getRow(totalExcelRow).getCell(sumColIdx).font = { bold: true };
736
+ sheet.getRow(totalExcelRow).getCell(sumColIdx).numFmt = "#,##0.00";
737
+ sheetCells.push({
738
+ a1: `${layout.sumColLetter}${totalExcelRow}`,
739
+ value: null,
740
+ formula: totalFormula
741
+ });
742
+ } else {
743
+ let offset = 0;
744
+ for (const currency of currencies) {
745
+ const r = totalExcelRow + offset;
746
+ sheet.getRow(r).getCell(qtyColIdx).value = offset === 0 ? `${labels.total} (${currency})` : currency;
747
+ sheet.getRow(r).getCell(qtyColIdx).font = { bold: true };
748
+ const f = buildCurrencyTotalSumIfFormula({
749
+ layout,
750
+ firstDataRow: layout.firstDataRow,
751
+ lastDataRow,
752
+ currency
753
+ });
754
+ sheet.getRow(r).getCell(sumColIdx).value = { formula: f };
755
+ sheet.getRow(r).getCell(sumColIdx).font = { bold: true };
756
+ sheet.getRow(r).getCell(sumColIdx).numFmt = "#,##0.00";
757
+ sheetCells.push({
758
+ a1: `${layout.sumColLetter}${r}`,
759
+ value: null,
760
+ formula: f
761
+ });
762
+ offset += 1;
763
+ }
764
+ }
765
+ const buffer = Buffer.from(await workbook.xlsx.writeBuffer());
766
+ const filename = priceListFilename(
767
+ normalized.locale,
768
+ normalized.header.generatedAt,
769
+ labels.filenamePrefix,
770
+ normalized.header.timeZone
771
+ );
772
+ const sheetModel = {
773
+ title,
774
+ locale: normalized.locale,
775
+ layout,
776
+ cells: sheetCells,
777
+ previewImageUrls,
778
+ logoUrl: normalized.header.logoUrl?.trim() || null
779
+ };
780
+ return {
781
+ buffer,
782
+ filename,
783
+ contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
784
+ layout,
785
+ sheetModel,
786
+ warnings
787
+ };
788
+ }
789
+ var buildWholesalePriceListXlsx = renderPriceListXlsx;
790
+ // Annotate the CommonJS export names for ESM import in node:
791
+ 0 && (module.exports = {
792
+ DEFAULT_PREVIEW_IMAGE_CONCURRENCY,
793
+ PRICE_LIST_BANNER_ROW_COUNT,
794
+ PRICE_LIST_DATA_ROW_HEIGHT_PT,
795
+ PRICE_LIST_DEFAULT_PHOTO_PX,
796
+ PRICE_LIST_PHOTO_COL_CHARS,
797
+ buildCurrencyTotalSumIfFormula,
798
+ buildLineSumFormula,
799
+ buildPriceListLayout,
800
+ buildTotalSumFormula,
801
+ buildWholesalePriceListXlsx,
802
+ coerceUnitPrice,
803
+ excelColumnLetter,
804
+ fetchAbsoluteUrlBytes,
805
+ formatGeneratedLabel,
806
+ googleSheetsImageFormula,
807
+ isAnonymousHttpImageUrl,
808
+ isMailooApiKeyedImageUrl,
809
+ mapWithConcurrency,
810
+ mediaIdFromMailooPublicImageUrl,
811
+ normalizePreviewSquare,
812
+ priceListFilename,
813
+ priceListFilenameDate,
814
+ rasterizeLogo,
815
+ renderPriceListXlsx,
816
+ resolvePreviewImageConcurrency,
817
+ resolvePriceListLabels,
818
+ tryNormalizePreviewSquare,
819
+ tryRasterizeLogo,
820
+ validatePriceListInput
821
+ });
822
+ //# sourceMappingURL=index.cjs.map