@mailoo/market 1.35.10 → 1.35.12

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,1006 @@
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
+ }
363
+
364
+ // src/wholesale-price-list/build-xlsx.ts
365
+ 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
+ function uniqueCurrencies(input) {
394
+ const set = /* @__PURE__ */ new Set();
395
+ for (const row of input.rows) {
396
+ const c = row.currency?.trim();
397
+ if (c) set.add(c);
398
+ }
399
+ return [...set].sort();
400
+ }
401
+ async function renderPriceListXlsx(input) {
402
+ validatePriceListInput(input);
403
+ const labels = resolvePriceListLabels(input.locale, input.labels);
404
+ const layout = buildPriceListLayout(input);
405
+ const title = labels.title;
406
+ const currencies = uniqueCurrencies(input);
407
+ const multiCurrency = currencies.length > 1;
408
+ const workbook = new ExcelJS.Workbook();
409
+ workbook.creator = "Mailoo";
410
+ workbook.created = new Date(input.header.generatedAt);
411
+ const sheetName = `${input.header.siteName}`.slice(0, 31) || title.slice(0, 31);
412
+ const sheet = workbook.addWorksheet(sheetName, {
413
+ properties: { defaultRowHeight: layout.dataRowHeightPt },
414
+ views: [{ state: "frozen", ySplit: layout.headerRow }],
415
+ pageSetup: {
416
+ orientation: "landscape",
417
+ fitToPage: true,
418
+ fitToWidth: 1,
419
+ fitToHeight: 0
420
+ }
421
+ });
422
+ for (const col of layout.columns) {
423
+ let width = 16;
424
+ if (col.key === "photo") width = layout.photoColWidthChars;
425
+ else if (col.key === "link") width = 14;
426
+ else if (col.key === "quantity" || col.key === "sum" || col.key === "price")
427
+ width = 12;
428
+ else if (col.key === "currencyHidden") width = 0;
429
+ else if (col.key === "product") width = 28;
430
+ sheet.getColumn(col.index).width = width;
431
+ if (col.key === "currencyHidden") {
432
+ sheet.getColumn(col.index).hidden = true;
433
+ }
434
+ }
435
+ sheet.getCell("A1").value = input.header.siteName;
436
+ sheet.getCell("A1").font = { bold: true, size: 16 };
437
+ sheet.mergeCells(1, 1, 1, Math.min(5, layout.columns.length));
438
+ sheet.getCell("A2").value = input.header.contacts;
439
+ sheet.getCell("A2").alignment = { wrapText: true, vertical: "top" };
440
+ const contactLines = input.header.contacts.split(/\r?\n/).length;
441
+ sheet.getRow(2).height = Math.max(36, contactLines * 14);
442
+ sheet.getCell("A3").value = formatGeneratedLabel(
443
+ labels.generated,
444
+ input.header.generatedAt,
445
+ input.locale,
446
+ input.header.timeZone
447
+ );
448
+ sheet.getCell("A3").font = { italic: true, size: 10 };
449
+ const logoBytes = await resolveLogoBytes(input);
450
+ 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
+ });
461
+ }
462
+ const headerRow = sheet.getRow(layout.headerRow);
463
+ headerRow.font = { bold: true };
464
+ headerRow.height = 22;
465
+ for (const col of layout.columns) {
466
+ if (col.key === "currencyHidden") continue;
467
+ headerRow.getCell(col.index).value = col.header;
468
+ }
469
+ sheet.autoFilter = {
470
+ from: { row: layout.headerRow, column: 1 },
471
+ to: {
472
+ row: layout.headerRow,
473
+ column: layout.columns.find((c) => c.key === "sum").index
474
+ }
475
+ };
476
+ const sheetCells = [];
477
+ 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];
481
+ const excelRow = layout.firstDataRow + i;
482
+ const sheetRow = sheet.getRow(excelRow);
483
+ sheetRow.height = layout.dataRowHeightPt;
484
+ const photoCol = layout.columns.find((c) => c.key === "photo");
485
+ const catCol = layout.columns.find((c) => c.key === "category");
486
+ const prodCol = layout.columns.find((c) => c.key === "product");
487
+ const varCol = layout.columns.find((c) => c.key === "variant");
488
+ const packCol = layout.columns.find((c) => c.key === "packaging");
489
+ const priceCol = layout.columns.find((c) => c.key === "price");
490
+ const linkCol = layout.columns.find((c) => c.key === "link");
491
+ const qtyCol = layout.columns.find((c) => c.key === "quantity");
492
+ const sumCol = layout.columns.find((c) => c.key === "sum");
493
+ const curCol = layout.columns.find((c) => c.key === "currencyHidden");
494
+ sheetRow.getCell(catCol.index).value = row.category ?? "";
495
+ sheetRow.getCell(prodCol.index).value = row.product;
496
+ sheetRow.getCell(varCol.index).value = row.variant ?? "";
497
+ sheetRow.getCell(packCol.index).value = row.packaging ?? "";
498
+ if (row.unitPrice === null) {
499
+ sheetRow.getCell(priceCol.index).value = labels.onRequest;
500
+ } else {
501
+ sheetRow.getCell(priceCol.index).value = row.unitPrice;
502
+ sheetRow.getCell(priceCol.index).numFmt = "#,##0.00";
503
+ }
504
+ sheetRow.getCell(linkCol.index).value = {
505
+ text: labels.linkText,
506
+ hyperlink: row.productUrl
507
+ };
508
+ sheetCells.push({
509
+ a1: `${linkCol.letter}${excelRow}`,
510
+ value: labels.linkText,
511
+ formula: `HYPERLINK("${row.productUrl.replace(/"/g, '""')}","${labels.linkText.replace(/"/g, '""')}")`
512
+ });
513
+ sheetRow.getCell(qtyCol.index).value = null;
514
+ const sumFormula = buildLineSumFormula({ layout, row: excelRow });
515
+ sheetRow.getCell(sumCol.index).value = { formula: sumFormula };
516
+ sheetRow.getCell(sumCol.index).numFmt = "#,##0.00";
517
+ sheetCells.push({
518
+ a1: `${sumCol.letter}${excelRow}`,
519
+ value: null,
520
+ formula: sumFormula
521
+ });
522
+ sheetRow.getCell(curCol.index).value = row.currency?.trim() || "";
523
+ sheetRow.getCell(qtyCol.index).dataValidation = {
524
+ type: "whole",
525
+ operator: "greaterThanOrEqual",
526
+ formulae: [0],
527
+ allowBlank: true,
528
+ showErrorMessage: true,
529
+ errorTitle: labels.quantity,
530
+ error: ">= 0"
531
+ };
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
+ );
541
+ const imageId = workbook.addImage({
542
+ buffer: png,
543
+ extension: "png"
544
+ });
545
+ sheet.addImage(imageId, {
546
+ tl: { col: photoCol.index - 1, row: excelRow - 1 },
547
+ ext: { width: layout.photoSizePx, height: layout.photoSizePx },
548
+ editAs: "oneCell"
549
+ });
550
+ } else if (sheetsSafeUrl) {
551
+ sheetCells.push({
552
+ a1: `${photoCol.letter}${excelRow}`,
553
+ value: null,
554
+ formula: googleSheetsImageFormula(sheetsSafeUrl, layout.photoSizePx)
555
+ });
556
+ }
557
+ }
558
+ const totalExcelRow = layout.totalRow;
559
+ const qtyColIdx = layout.columns.find((c) => c.key === "quantity").index;
560
+ const sumColIdx = layout.columns.find((c) => c.key === "sum").index;
561
+ sheet.getRow(totalExcelRow).getCell(qtyColIdx).value = labels.total;
562
+ sheet.getRow(totalExcelRow).getCell(qtyColIdx).font = { bold: true };
563
+ if (!multiCurrency) {
564
+ const totalFormula = buildTotalSumFormula({
565
+ layout,
566
+ firstDataRow: layout.firstDataRow,
567
+ lastDataRow
568
+ });
569
+ sheet.getRow(totalExcelRow).getCell(sumColIdx).value = {
570
+ formula: totalFormula
571
+ };
572
+ sheet.getRow(totalExcelRow).getCell(sumColIdx).font = { bold: true };
573
+ sheet.getRow(totalExcelRow).getCell(sumColIdx).numFmt = "#,##0.00";
574
+ sheetCells.push({
575
+ a1: `${layout.sumColLetter}${totalExcelRow}`,
576
+ value: null,
577
+ formula: totalFormula
578
+ });
579
+ } else {
580
+ let offset = 0;
581
+ for (const currency of currencies) {
582
+ const r = totalExcelRow + offset;
583
+ sheet.getRow(r).getCell(qtyColIdx).value = offset === 0 ? `${labels.total} (${currency})` : currency;
584
+ sheet.getRow(r).getCell(qtyColIdx).font = { bold: true };
585
+ const f = buildCurrencyTotalSumIfFormula({
586
+ layout,
587
+ firstDataRow: layout.firstDataRow,
588
+ lastDataRow,
589
+ currency
590
+ });
591
+ sheet.getRow(r).getCell(sumColIdx).value = { formula: f };
592
+ sheet.getRow(r).getCell(sumColIdx).font = { bold: true };
593
+ sheet.getRow(r).getCell(sumColIdx).numFmt = "#,##0.00";
594
+ sheetCells.push({
595
+ a1: `${layout.sumColLetter}${r}`,
596
+ value: null,
597
+ formula: f
598
+ });
599
+ offset += 1;
600
+ }
601
+ }
602
+ const buffer = Buffer.from(await workbook.xlsx.writeBuffer());
603
+ const filename = priceListFilename(
604
+ input.locale,
605
+ input.header.generatedAt,
606
+ labels.filenamePrefix,
607
+ input.header.timeZone
608
+ );
609
+ const sheetModel = {
610
+ title,
611
+ locale: input.locale,
612
+ layout,
613
+ cells: sheetCells,
614
+ previewImageUrls,
615
+ logoUrl: input.header.logoUrl?.trim() || null
616
+ };
617
+ return {
618
+ buffer,
619
+ filename,
620
+ contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
621
+ layout,
622
+ sheetModel
623
+ };
624
+ }
625
+ 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
+ export {
979
+ PRICE_LIST_BANNER_ROW_COUNT,
980
+ PRICE_LIST_DATA_ROW_HEIGHT_PT,
981
+ PRICE_LIST_DEFAULT_PHOTO_PX,
982
+ PRICE_LIST_PHOTO_COL_CHARS,
983
+ buildCurrencyTotalSumIfFormula,
984
+ buildLineSumFormula,
985
+ buildPriceListLayout,
986
+ buildTotalSumFormula,
987
+ buildWholesalePriceListXlsx,
988
+ coerceUnitPrice,
989
+ createPriceListGoogleClients,
990
+ excelColumnLetter,
991
+ fetchAbsoluteUrlBytes,
992
+ formatGeneratedLabel,
993
+ googleSheetsImageFormula,
994
+ isAnonymousHttpImageUrl,
995
+ isMailooApiKeyedImageUrl,
996
+ mediaIdFromMailooPublicImageUrl,
997
+ normalizePreviewSquare,
998
+ priceListFilename,
999
+ priceListFilenameDate,
1000
+ rasterizeLogo,
1001
+ renderPriceListGoogleSheet,
1002
+ renderPriceListXlsx,
1003
+ resolvePriceListLabels,
1004
+ validatePriceListInput
1005
+ };
1006
+ //# sourceMappingURL=index.js.map