@infuro/cms-core 1.0.45 → 1.0.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +19 -2
  2. package/dist/admin.cjs +873 -214
  3. package/dist/admin.d.cts +7 -1
  4. package/dist/admin.d.ts +7 -1
  5. package/dist/admin.js +874 -215
  6. package/dist/api.cjs +40 -37
  7. package/dist/api.d.cts +1 -1
  8. package/dist/api.d.ts +1 -1
  9. package/dist/api.js +8 -5
  10. package/dist/auth.cjs +23 -23
  11. package/dist/auth.d.cts +1 -0
  12. package/dist/auth.d.ts +1 -0
  13. package/dist/auth.js +2 -2
  14. package/dist/chunk-2KUCQVAQ.js +936 -0
  15. package/dist/chunk-3K5AIEIZ.js +256 -0
  16. package/dist/{chunk-I6NH72MO.js → chunk-57O3HZPG.js} +9 -1
  17. package/dist/chunk-7PMHZRF3.cjs +872 -0
  18. package/dist/chunk-BXYZDMTZ.cjs +953 -0
  19. package/dist/chunk-CQHXW4TR.js +107 -0
  20. package/dist/{chunk-NNQBWDCI.js → chunk-CRYKVJTO.js} +55 -959
  21. package/dist/chunk-DBPSJYLZ.js +47 -0
  22. package/dist/{chunk-TAHX46EI.cjs → chunk-FBKDMRQL.cjs} +9 -1
  23. package/dist/chunk-GUSHM5HN.js +862 -0
  24. package/dist/chunk-HY3AXLOI.cjs +265 -0
  25. package/dist/chunk-L3525VXI.js +243 -0
  26. package/dist/{chunk-ZMRQ72F6.cjs → chunk-NBY4NVTY.cjs} +3 -3
  27. package/dist/chunk-OY2YTBMP.cjs +50 -0
  28. package/dist/{chunk-BLR6H5GL.js → chunk-SF2XKMCI.js} +3 -3
  29. package/dist/{chunk-22FFHLTO.cjs → chunk-TCSGFAWB.cjs} +56 -970
  30. package/dist/{chunk-F5XFHYTG.cjs → chunk-UDVLFVEC.cjs} +661 -382
  31. package/dist/{chunk-MVXLRANV.js → chunk-UKC3HYXI.js} +591 -323
  32. package/dist/chunk-V25RDUOU.cjs +248 -0
  33. package/dist/chunk-XMRMZ6NQ.cjs +109 -0
  34. package/dist/cli.cjs +9 -4
  35. package/dist/cli.js +9 -4
  36. package/dist/{email-queue-TPZWLTIV.cjs → email-queue-6NJY6HNM.cjs} +7 -5
  37. package/dist/email-queue-OI2HSCGE.js +4 -0
  38. package/dist/erp-order-invoice-3GXDE443.js +3 -0
  39. package/dist/erp-order-invoice-EYYNR526.cjs +24 -0
  40. package/dist/index.cjs +391 -364
  41. package/dist/index.d.cts +267 -14
  42. package/dist/index.d.ts +267 -14
  43. package/dist/index.js +12 -110
  44. package/dist/migrations/1781810000000-OrderItemsVariantId.ts +44 -0
  45. package/dist/migrations/1781900000000-UserInviteStatusToken.ts +46 -0
  46. package/dist/migrations/1782000000000-ComboSlug.ts +58 -0
  47. package/dist/migrations/1782100000000-DiscountDeviceType.ts +20 -0
  48. package/dist/order-inventory-2MYRKEPC.cjs +39 -0
  49. package/dist/order-inventory-76V4XIGW.js +2 -0
  50. package/dist/order-notification-dispatcher-SBQAMM5V.cjs +21 -0
  51. package/dist/{order-notification-dispatcher-XWIJYDGA.js → order-notification-dispatcher-ZJZB2HUN.js} +5 -2
  52. package/dist/retire-soft-deleted-unique-5VXBA5XX.cjs +15 -0
  53. package/dist/retire-soft-deleted-unique-NXQIH4BC.js +2 -0
  54. package/dist/send-order-placed-emails-B5ZVJT7T.cjs +15 -0
  55. package/dist/send-order-placed-emails-WPI37KRZ.js +6 -0
  56. package/package.json +5 -4
  57. package/src/admin/admin.css +27 -24
  58. package/dist/chunk-5ELSW2UP.js +0 -150
  59. package/dist/chunk-PNOKNSG2.cjs +0 -222
  60. package/dist/chunk-WEMDMVHQ.js +0 -216
  61. package/dist/chunk-XW5ATPRW.cjs +0 -155
  62. package/dist/email-queue-CGZBVVAS.js +0 -2
  63. package/dist/erp-order-invoice-3YISSOWW.js +0 -3
  64. package/dist/erp-order-invoice-ZR5F2KTA.cjs +0 -12
  65. package/dist/order-notification-dispatcher-RU7BTGGX.cjs +0 -18
@@ -0,0 +1,953 @@
1
+ 'use strict';
2
+
3
+ var chunkUPLVMVRX_cjs = require('./chunk-UPLVMVRX.cjs');
4
+ var chunkUSNT2KNT_cjs = require('./chunk-USNT2KNT.cjs');
5
+ var pdfLib = require('pdf-lib');
6
+
7
+ // src/plugins/erp/erp-response-map.ts
8
+ function pickString(o, keys) {
9
+ for (const k of keys) {
10
+ const v = o[k];
11
+ if (typeof v === "string" && v.trim()) return v.trim();
12
+ }
13
+ return void 0;
14
+ }
15
+ chunkUSNT2KNT_cjs.__name(pickString, "pickString");
16
+ function unwrapErpReadData(json) {
17
+ if (!json || typeof json !== "object") return null;
18
+ const o = json;
19
+ const d = o.data;
20
+ if (d && typeof d === "object" && !Array.isArray(d)) return d;
21
+ return o;
22
+ }
23
+ chunkUSNT2KNT_cjs.__name(unwrapErpReadData, "unwrapErpReadData");
24
+ function firstObject(data, keys) {
25
+ for (const k of keys) {
26
+ const v = data[k];
27
+ if (v && typeof v === "object" && !Array.isArray(v)) return v;
28
+ }
29
+ return null;
30
+ }
31
+ chunkUSNT2KNT_cjs.__name(firstObject, "firstObject");
32
+ function extractEvents(src) {
33
+ const timeline = src.timeline ?? src.events ?? src.history ?? src.trackingEvents;
34
+ if (!Array.isArray(timeline) || !timeline.length) return void 0;
35
+ const events = [];
36
+ for (const row of timeline) {
37
+ if (!row || typeof row !== "object") continue;
38
+ const r = row;
39
+ const at = pickString(r, [
40
+ "at",
41
+ "timestamp",
42
+ "date",
43
+ "occurredAt"
44
+ ]) ?? (r.at instanceof Date ? r.at.toISOString() : void 0);
45
+ const label = pickString(r, [
46
+ "label",
47
+ "status",
48
+ "title",
49
+ "message",
50
+ "description"
51
+ ]);
52
+ const detail = pickString(r, [
53
+ "detail",
54
+ "notes",
55
+ "description"
56
+ ]);
57
+ if (at || label || detail) events.push({
58
+ at,
59
+ label,
60
+ detail
61
+ });
62
+ }
63
+ return events.length ? events : void 0;
64
+ }
65
+ chunkUSNT2KNT_cjs.__name(extractEvents, "extractEvents");
66
+ function mapErpPayloadToFulfillment(data) {
67
+ const nested = firstObject(data, [
68
+ "fulfillment",
69
+ "packaging",
70
+ "shipment",
71
+ "shipping",
72
+ "delivery"
73
+ ]);
74
+ const src = nested || data;
75
+ const status = pickString(src, [
76
+ "status",
77
+ "fulfillmentStatus",
78
+ "state",
79
+ "label",
80
+ "packagingStatus"
81
+ ]);
82
+ const trackingId = pickString(src, [
83
+ "trackingId",
84
+ "tracking_id",
85
+ "trackingNumber",
86
+ "awb",
87
+ "trackingUrl"
88
+ ]);
89
+ const events = extractEvents(src);
90
+ if (!status && !trackingId && !(events && events.length)) return void 0;
91
+ return {
92
+ status,
93
+ trackingId,
94
+ events
95
+ };
96
+ }
97
+ chunkUSNT2KNT_cjs.__name(mapErpPayloadToFulfillment, "mapErpPayloadToFulfillment");
98
+ function mapErpPayloadToInvoiceNumber(data) {
99
+ const nested = firstObject(data, [
100
+ "invoice",
101
+ "latestInvoice",
102
+ "postedInvoice"
103
+ ]);
104
+ const src = nested || data;
105
+ return pickString(src, [
106
+ "invoiceNumber",
107
+ "invoice_number",
108
+ "number",
109
+ "name",
110
+ "id"
111
+ ]);
112
+ }
113
+ chunkUSNT2KNT_cjs.__name(mapErpPayloadToInvoiceNumber, "mapErpPayloadToInvoiceNumber");
114
+ function extractChildOrderRefsFromSalePayload(data) {
115
+ const lists = [
116
+ data.returns,
117
+ data.returnOrders,
118
+ data.relatedReturns,
119
+ data.childOrders,
120
+ data.children
121
+ ];
122
+ const seen = /* @__PURE__ */ new Set();
123
+ const out = [];
124
+ for (const list of lists) {
125
+ if (!Array.isArray(list)) continue;
126
+ for (const item of list) {
127
+ if (!item || typeof item !== "object") continue;
128
+ const o = item;
129
+ const ref = pickString(o, [
130
+ "platformReturnId",
131
+ "platform_return_id",
132
+ "refId",
133
+ "ref_id"
134
+ ]) ?? (typeof o.id === "string" ? o.id : void 0);
135
+ if (!ref || seen.has(ref)) continue;
136
+ seen.add(ref);
137
+ const t = (pickString(o, [
138
+ "kind",
139
+ "type",
140
+ "orderKind"
141
+ ]) || "").toLowerCase();
142
+ const orderKind = /replac/.test(t) ? "replacement" : "return";
143
+ out.push({
144
+ ref,
145
+ orderKind
146
+ });
147
+ }
148
+ }
149
+ return out;
150
+ }
151
+ chunkUSNT2KNT_cjs.__name(extractChildOrderRefsFromSalePayload, "extractChildOrderRefsFromSalePayload");
152
+
153
+ // src/lib/invoice/invoice-templates.ts
154
+ var INVOICE_TEMPLATE_IDS = [
155
+ "classic",
156
+ "modern",
157
+ "compact",
158
+ "bold"
159
+ ];
160
+ var INVOICE_TEMPLATE_OPTIONS = [
161
+ {
162
+ id: "classic",
163
+ label: "Classic",
164
+ description: "Traditional invoice with header, lined items, and totals footer."
165
+ },
166
+ {
167
+ id: "modern",
168
+ label: "Modern",
169
+ description: "Clean layout with accent bar and spacious typography."
170
+ },
171
+ {
172
+ id: "compact",
173
+ label: "Compact",
174
+ description: "Dense single-page layout for high line-item counts."
175
+ },
176
+ {
177
+ id: "bold",
178
+ label: "Bold",
179
+ description: "Strong header band and clear payment summary block."
180
+ }
181
+ ];
182
+ function normalizeInvoiceTemplateId(raw) {
183
+ const v = String(raw ?? "").trim().toLowerCase();
184
+ return INVOICE_TEMPLATE_IDS.includes(v) ? v : "classic";
185
+ }
186
+ chunkUSNT2KNT_cjs.__name(normalizeInvoiceTemplateId, "normalizeInvoiceTemplateId");
187
+
188
+ // src/lib/invoice/generate-local-invoice-pdf.ts
189
+ var THEMES = {
190
+ classic: {
191
+ accent: pdfLib.rgb(0.15, 0.25, 0.45),
192
+ headerBg: pdfLib.rgb(0.96, 0.96, 0.97),
193
+ headerText: pdfLib.rgb(0.12, 0.12, 0.14),
194
+ text: pdfLib.rgb(0.12, 0.12, 0.14),
195
+ muted: pdfLib.rgb(0.4, 0.42, 0.45),
196
+ line: pdfLib.rgb(0.82, 0.84, 0.86),
197
+ bandText: pdfLib.rgb(1, 1, 1)
198
+ },
199
+ modern: {
200
+ accent: pdfLib.rgb(0.1, 0.45, 0.55),
201
+ headerBg: pdfLib.rgb(0.93, 0.97, 0.98),
202
+ headerText: pdfLib.rgb(0.1, 0.12, 0.14),
203
+ text: pdfLib.rgb(0.1, 0.12, 0.14),
204
+ muted: pdfLib.rgb(0.38, 0.42, 0.45),
205
+ line: pdfLib.rgb(0.78, 0.86, 0.88),
206
+ bandText: pdfLib.rgb(1, 1, 1)
207
+ },
208
+ compact: {
209
+ accent: pdfLib.rgb(0.2, 0.2, 0.22),
210
+ headerBg: pdfLib.rgb(0.95, 0.95, 0.95),
211
+ headerText: pdfLib.rgb(0.1, 0.1, 0.1),
212
+ text: pdfLib.rgb(0.1, 0.1, 0.1),
213
+ muted: pdfLib.rgb(0.45, 0.45, 0.45),
214
+ line: pdfLib.rgb(0.85, 0.85, 0.85),
215
+ bandText: pdfLib.rgb(1, 1, 1)
216
+ },
217
+ bold: {
218
+ accent: pdfLib.rgb(0.55, 0.12, 0.12),
219
+ headerBg: pdfLib.rgb(0.55, 0.12, 0.12),
220
+ headerText: pdfLib.rgb(1, 1, 1),
221
+ text: pdfLib.rgb(0.1, 0.1, 0.1),
222
+ muted: pdfLib.rgb(0.4, 0.4, 0.4),
223
+ line: pdfLib.rgb(0.8, 0.75, 0.75),
224
+ bandText: pdfLib.rgb(1, 1, 1)
225
+ }
226
+ };
227
+ function money(amount, currency) {
228
+ const n = Number.isFinite(amount) ? amount : 0;
229
+ const code = (currency || "INR").trim().toUpperCase() || "INR";
230
+ return `${code} ${n.toFixed(2)}`;
231
+ }
232
+ chunkUSNT2KNT_cjs.__name(money, "money");
233
+ function fmtDate(d) {
234
+ const date = d instanceof Date ? d : new Date(d);
235
+ if (Number.isNaN(date.getTime())) return String(d);
236
+ const y = date.getFullYear();
237
+ const m = String(date.getMonth() + 1).padStart(2, "0");
238
+ const day = String(date.getDate()).padStart(2, "0");
239
+ return `${day}-${m}-${y}`;
240
+ }
241
+ chunkUSNT2KNT_cjs.__name(fmtDate, "fmtDate");
242
+ function winAnsiSafe(input) {
243
+ return String(input ?? "").replace(/\u20B9/g, "INR ").replace(/\u20AC/g, "EUR ").replace(/\u00A3/g, "GBP ").replace(/[^\x09\x0A\x0D\x20-\x7E]/g, "?");
244
+ }
245
+ chunkUSNT2KNT_cjs.__name(winAnsiSafe, "winAnsiSafe");
246
+ function addrLines(a) {
247
+ if (!a) return [];
248
+ const out = [];
249
+ if (a.line1?.trim()) out.push(a.line1.trim());
250
+ if (a.line2?.trim()) out.push(a.line2.trim());
251
+ const cityLine = [
252
+ a.city,
253
+ a.state,
254
+ a.postalCode
255
+ ].filter((x) => x && String(x).trim()).join(", ");
256
+ if (cityLine) out.push(cityLine);
257
+ if (a.country?.trim()) out.push(a.country.trim());
258
+ return out.map(winAnsiSafe);
259
+ }
260
+ chunkUSNT2KNT_cjs.__name(addrLines, "addrLines");
261
+ function companyHeaderDetailLines(company) {
262
+ const lines = [];
263
+ if (company.supportEmail?.trim()) {
264
+ lines.push(`Email: ${company.supportEmail.trim()}`);
265
+ }
266
+ if (company.supportPhone?.trim()) {
267
+ lines.push(`Phone: ${company.supportPhone.trim()}`);
268
+ }
269
+ if (company.address?.trim()) {
270
+ const parts = company.address.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
271
+ if (parts.length === 1) {
272
+ lines.push(`Address: ${parts[0]}`);
273
+ } else if (parts.length > 1) {
274
+ lines.push(`Address: ${parts[0]}`);
275
+ lines.push(...parts.slice(1));
276
+ }
277
+ }
278
+ return lines.map(winAnsiSafe);
279
+ }
280
+ chunkUSNT2KNT_cjs.__name(companyHeaderDetailLines, "companyHeaderDetailLines");
281
+ function drawText(page, text, x, y, font, size, color) {
282
+ const safe = winAnsiSafe(text).slice(0, 120);
283
+ if (!safe) return;
284
+ page.drawText(safe, {
285
+ x,
286
+ y,
287
+ size,
288
+ font,
289
+ color
290
+ });
291
+ }
292
+ chunkUSNT2KNT_cjs.__name(drawText, "drawText");
293
+ function wrapText(text, font, size, maxWidth) {
294
+ const words = winAnsiSafe(text).split(/\s+/).filter(Boolean);
295
+ if (!words.length) return [
296
+ ""
297
+ ];
298
+ const lines = [];
299
+ let cur = "";
300
+ for (const w of words) {
301
+ const next = cur ? `${cur} ${w}` : w;
302
+ if (font.widthOfTextAtSize(next, size) <= maxWidth) {
303
+ cur = next;
304
+ } else {
305
+ if (cur) lines.push(cur);
306
+ cur = w;
307
+ }
308
+ }
309
+ if (cur) lines.push(cur);
310
+ return lines.slice(0, 4);
311
+ }
312
+ chunkUSNT2KNT_cjs.__name(wrapText, "wrapText");
313
+ async function tryEmbedLogo(doc, logoUrl, maxW, maxH) {
314
+ const url = String(logoUrl ?? "").trim();
315
+ if (!url || !/^https?:\/\//i.test(url)) return null;
316
+ try {
317
+ const res = await fetch(url, {
318
+ signal: AbortSignal.timeout(8e3)
319
+ });
320
+ if (!res.ok) return null;
321
+ const buf = new Uint8Array(await res.arrayBuffer());
322
+ if (buf.byteLength < 24 || buf.byteLength > 25e5) return null;
323
+ const ct = (res.headers.get("content-type") || "").toLowerCase();
324
+ const isPng = ct.includes("png") || buf[0] === 137 && buf[1] === 80 && buf[2] === 78 && buf[3] === 71;
325
+ const isJpg = ct.includes("jpeg") || ct.includes("jpg") || buf[0] === 255 && buf[1] === 216;
326
+ let image;
327
+ if (isPng) image = await doc.embedPng(buf);
328
+ else if (isJpg) image = await doc.embedJpg(buf);
329
+ else {
330
+ try {
331
+ image = await doc.embedPng(buf);
332
+ } catch {
333
+ image = await doc.embedJpg(buf);
334
+ }
335
+ }
336
+ const scale = Math.min(maxW / image.width, maxH / image.height, 1);
337
+ return {
338
+ image,
339
+ width: image.width * scale,
340
+ height: image.height * scale
341
+ };
342
+ } catch {
343
+ return null;
344
+ }
345
+ }
346
+ chunkUSNT2KNT_cjs.__name(tryEmbedLogo, "tryEmbedLogo");
347
+ async function generateLocalInvoicePdf(input) {
348
+ const templateId = normalizeInvoiceTemplateId(input.templateId);
349
+ const theme = THEMES[templateId];
350
+ const doc = await pdfLib.PDFDocument.create();
351
+ const font = await doc.embedFont(pdfLib.StandardFonts.Helvetica);
352
+ const fontBold = await doc.embedFont(pdfLib.StandardFonts.HelveticaBold);
353
+ const pageWidth = 595.28;
354
+ const pageHeight = 841.89;
355
+ const margin = templateId === "compact" ? 36 : 48;
356
+ let page = doc.addPage([
357
+ pageWidth,
358
+ pageHeight
359
+ ]);
360
+ let y = pageHeight - margin;
361
+ const companyName = input.company.name || "Store";
362
+ const logo = await tryEmbedLogo(doc, input.company.logoUrl, 120, 40);
363
+ const ensureSpace = /* @__PURE__ */ chunkUSNT2KNT_cjs.__name((need) => {
364
+ if (y - need < margin + 40) {
365
+ page = doc.addPage([
366
+ pageWidth,
367
+ pageHeight
368
+ ]);
369
+ y = pageHeight - margin;
370
+ }
371
+ }, "ensureSpace");
372
+ const companyDetails = companyHeaderDetailLines(input.company);
373
+ const detailLineH = 11;
374
+ const detailsBlockH = companyDetails.length * detailLineH;
375
+ if (templateId === "bold" || templateId === "modern") {
376
+ const contentH = 22 + 16 + detailsBlockH;
377
+ const bandH = Math.max(templateId === "bold" ? 72 : 56, logo ? logo.height + 24 : 56, contentH + 20);
378
+ page.drawRectangle({
379
+ x: 0,
380
+ y: pageHeight - bandH,
381
+ width: pageWidth,
382
+ height: bandH,
383
+ color: theme.accent
384
+ });
385
+ if (logo) {
386
+ page.drawImage(logo.image, {
387
+ x: pageWidth - margin - logo.width,
388
+ y: pageHeight - bandH + (bandH - logo.height) / 2,
389
+ width: logo.width,
390
+ height: logo.height
391
+ });
392
+ }
393
+ let hy = pageHeight - 26;
394
+ drawText(page, "TAX INVOICE", margin, hy, fontBold, 18, theme.bandText);
395
+ hy -= 18;
396
+ drawText(page, companyName, margin, hy, font, 11, theme.bandText);
397
+ hy -= 14;
398
+ for (const line of companyDetails) {
399
+ drawText(page, line, margin, hy, font, 8, theme.bandText);
400
+ hy -= detailLineH;
401
+ }
402
+ y = pageHeight - bandH - 24;
403
+ } else {
404
+ const contentH = 18 + 14 + detailsBlockH;
405
+ const headerH = Math.max(44, logo ? logo.height + 16 : 44, contentH + 20);
406
+ page.drawRectangle({
407
+ x: margin,
408
+ y: y - headerH + 16,
409
+ width: pageWidth - margin * 2,
410
+ height: headerH,
411
+ color: theme.headerBg
412
+ });
413
+ if (logo) {
414
+ page.drawImage(logo.image, {
415
+ x: pageWidth - margin - 12 - logo.width,
416
+ y: y - headerH + 16 + (headerH - logo.height) / 2,
417
+ width: logo.width,
418
+ height: logo.height
419
+ });
420
+ }
421
+ let hy = y + 2;
422
+ drawText(page, "TAX INVOICE", margin + 12, hy, fontBold, 16, theme.accent);
423
+ hy -= 16;
424
+ drawText(page, companyName, margin + 12, hy, font, 10, theme.muted);
425
+ hy -= 13;
426
+ for (const line of companyDetails) {
427
+ drawText(page, line, margin + 12, hy, font, 8, theme.muted);
428
+ hy -= detailLineH;
429
+ }
430
+ y -= headerH + 16;
431
+ }
432
+ drawText(page, `Invoice #: ${input.orderNumber}`, margin, y, fontBold, 11, theme.text);
433
+ drawText(page, `Date: ${fmtDate(input.orderDate)}`, pageWidth / 2, y, font, 10, theme.muted);
434
+ y -= 22;
435
+ ensureSpace(100);
436
+ const colW = (pageWidth - margin * 2 - 16) / 2;
437
+ drawText(page, "Bill to", margin, y, fontBold, 10, theme.accent);
438
+ drawText(page, "Ship to", margin + colW + 16, y, fontBold, 10, theme.accent);
439
+ y -= 14;
440
+ const bill = [
441
+ input.customerName,
442
+ input.customerEmail || "",
443
+ input.customerPhone || "",
444
+ ...addrLines(input.billingAddress)
445
+ ].filter(Boolean);
446
+ const ship = addrLines(input.shippingAddress).length ? [
447
+ input.customerName,
448
+ ...addrLines(input.shippingAddress)
449
+ ] : bill;
450
+ const rows = Math.max(bill.length, ship.length, 1);
451
+ for (let i = 0; i < rows; i++) {
452
+ ensureSpace(14);
453
+ if (bill[i]) drawText(page, bill[i], margin, y, font, 9, theme.text);
454
+ if (ship[i]) drawText(page, ship[i], margin + colW + 16, y, font, 9, theme.text);
455
+ y -= 12;
456
+ }
457
+ y -= 12;
458
+ const right = pageWidth - margin;
459
+ const contentRight = right - 4;
460
+ const colTotalW = 100;
461
+ const colTaxW = 100;
462
+ const colPriceW = 100;
463
+ const colQtyW = 40;
464
+ const totalRight = contentRight;
465
+ const taxRight = totalRight - colTotalW;
466
+ const priceRight = taxRight - colTaxW;
467
+ const qtyRight = priceRight - colPriceW;
468
+ const itemMaxW = Math.max(80, qtyRight - colQtyW - margin - 8);
469
+ const drawRight = /* @__PURE__ */ chunkUSNT2KNT_cjs.__name((text, rightEdge, atY, f, size, color) => {
470
+ const safe = winAnsiSafe(text).slice(0, 40);
471
+ if (!safe) return;
472
+ const w = f.widthOfTextAtSize(safe, size);
473
+ page.drawText(safe, {
474
+ x: rightEdge - w,
475
+ y: atY,
476
+ size,
477
+ font: f,
478
+ color
479
+ });
480
+ }, "drawRight");
481
+ ensureSpace(30);
482
+ const headerBarH = 20;
483
+ const headerBarBottom = y - 5;
484
+ page.drawRectangle({
485
+ x: margin,
486
+ y: headerBarBottom,
487
+ width: pageWidth - margin * 2,
488
+ height: headerBarH,
489
+ color: theme.headerBg
490
+ });
491
+ const headerTextY = headerBarBottom + 6;
492
+ drawText(page, "Item", margin + 4, headerTextY, fontBold, 9, theme.headerText);
493
+ drawRight("Qty", qtyRight, headerTextY, fontBold, 9, theme.headerText);
494
+ drawRight("Price", priceRight, headerTextY, fontBold, 9, theme.headerText);
495
+ drawRight("Tax", taxRight, headerTextY, fontBold, 9, theme.headerText);
496
+ drawRight("Total", totalRight, headerTextY, fontBold, 9, theme.headerText);
497
+ y = headerBarBottom - 10;
498
+ for (const line of input.lineItems) {
499
+ const nameLines = wrapText(line.name || "Item", font, 9, itemMaxW);
500
+ const skuText = line.sku ? winAnsiSafe(`SKU: ${line.sku}`).slice(0, 80) : "";
501
+ const nameH = Math.max(11, nameLines.length * 11);
502
+ const skuH = skuText ? 10 : 0;
503
+ const blockH = nameH + skuH + 6;
504
+ ensureSpace(blockH + 10);
505
+ let ty = y;
506
+ for (const nl of nameLines) {
507
+ drawText(page, nl, margin + 4, ty, font, 9, theme.text);
508
+ ty -= 11;
509
+ }
510
+ if (skuText) {
511
+ drawText(page, skuText, margin + 4, ty, font, 7, theme.muted);
512
+ ty -= 10;
513
+ }
514
+ drawRight(String(line.quantity), qtyRight, y, font, 9, theme.text);
515
+ drawRight(money(line.unitPrice, input.currency), priceRight, y, font, 9, theme.text);
516
+ drawRight(money(line.tax ?? 0, input.currency), taxRight, y, font, 9, theme.text);
517
+ drawRight(money(line.total, input.currency), totalRight, y, font, 9, theme.text);
518
+ const contentBottom = Math.min(ty, y - 12);
519
+ y = contentBottom - 2;
520
+ page.drawLine({
521
+ start: {
522
+ x: margin,
523
+ y
524
+ },
525
+ end: {
526
+ x: pageWidth - margin,
527
+ y
528
+ },
529
+ thickness: 0.5,
530
+ color: theme.line
531
+ });
532
+ y -= 8;
533
+ }
534
+ y -= 16;
535
+ ensureSpace(90);
536
+ const summaryLabelX = totalRight - colTotalW - colTaxW - 8;
537
+ const rowsSummary = [
538
+ [
539
+ "Subtotal",
540
+ money(input.subtotal, input.currency),
541
+ false
542
+ ],
543
+ [
544
+ "Discount",
545
+ money(input.discount, input.currency),
546
+ false
547
+ ],
548
+ [
549
+ "Tax",
550
+ money(input.tax, input.currency),
551
+ false
552
+ ],
553
+ [
554
+ "Total",
555
+ money(input.total, input.currency),
556
+ true
557
+ ]
558
+ ];
559
+ for (const [label, value, strong] of rowsSummary) {
560
+ const f = strong ? fontBold : font;
561
+ const size = strong ? 11 : 9;
562
+ drawText(page, label, summaryLabelX, y, f, size, strong ? theme.accent : theme.muted);
563
+ drawRight(value, totalRight, y, f, size, theme.text);
564
+ y -= strong ? 18 : 14;
565
+ }
566
+ y -= 20;
567
+ ensureSpace(40);
568
+ drawText(page, "Thank you for your purchase.", margin, y, font, 9, theme.muted);
569
+ y -= 12;
570
+ drawText(page, ``, margin, y, font, 7, theme.muted);
571
+ return doc.save();
572
+ }
573
+ chunkUSNT2KNT_cjs.__name(generateLocalInvoicePdf, "generateLocalInvoicePdf");
574
+
575
+ // src/lib/invoice/resolve-invoice-asset-url.ts
576
+ function resolveInvoiceAssetUrl(raw) {
577
+ const t = String(raw ?? "").trim();
578
+ if (!t) return null;
579
+ if (/^https?:\/\//i.test(t)) return t;
580
+ if (t.startsWith("//")) return `https:${t}`;
581
+ const base = (process.env.CMS_PUBLIC_URL || process.env.NEXT_PUBLIC_SITE_URL || process.env.NEXTAUTH_URL || "").trim().replace(/\/+$/, "");
582
+ if (!base) return null;
583
+ if (t.startsWith("/")) return `${base}${t}`;
584
+ return `${base}/${t}`;
585
+ }
586
+ chunkUSNT2KNT_cjs.__name(resolveInvoiceAssetUrl, "resolveInvoiceAssetUrl");
587
+
588
+ // src/plugins/email/templates/types.ts
589
+ function normalizeSocialLinkItem(o) {
590
+ const url = String(o.url ?? "").trim();
591
+ if (!url) return null;
592
+ let iconUrl = String(o.iconUrl ?? o.icon_image ?? "").trim();
593
+ let icon = String(o.icon ?? "").trim();
594
+ if (!iconUrl && /^https?:\/\//i.test(icon)) {
595
+ iconUrl = icon;
596
+ icon = "";
597
+ }
598
+ const item = {
599
+ url
600
+ };
601
+ if (iconUrl) item.iconUrl = iconUrl;
602
+ if (icon) item.icon = icon;
603
+ return item;
604
+ }
605
+ chunkUSNT2KNT_cjs.__name(normalizeSocialLinkItem, "normalizeSocialLinkItem");
606
+ function parseSocialLinksJson(raw) {
607
+ if (raw == null || raw.trim() === "") return void 0;
608
+ try {
609
+ const parsed = JSON.parse(raw);
610
+ if (!Array.isArray(parsed)) return void 0;
611
+ const out = [];
612
+ for (const item of parsed) {
613
+ if (item && typeof item === "object" && "url" in item) {
614
+ const n = normalizeSocialLinkItem(item);
615
+ if (n) out.push(n);
616
+ }
617
+ }
618
+ return out.length ? out : void 0;
619
+ } catch {
620
+ return void 0;
621
+ }
622
+ }
623
+ chunkUSNT2KNT_cjs.__name(parseSocialLinksJson, "parseSocialLinksJson");
624
+ function mergeEmailLayoutCompanyDetails(branding, emailSettings) {
625
+ const fromBranding = getCompanyDetailsFromSettings(branding);
626
+ const pick = /* @__PURE__ */ chunkUSNT2KNT_cjs.__name((emailVal, fallback) => {
627
+ const t = emailVal?.trim();
628
+ return t || fallback?.trim() || void 0;
629
+ }, "pick");
630
+ const logoUrl = pick(emailSettings.logoUrl ?? emailSettings.emailLogoUrl, fromBranding.logoUrl);
631
+ const companyName = pick(emailSettings.companyName ?? emailSettings.emailCompanyName, fromBranding.companyName);
632
+ const supportEmail = pick(emailSettings.supportEmail ?? emailSettings.emailSupportEmail, fromBranding.supportEmail);
633
+ const supportPhone = pick(emailSettings.supportPhone, void 0);
634
+ const footerDisclaimer = pick(emailSettings.footerDisclaimer, void 0);
635
+ const followUsTitle = pick(emailSettings.followUsTitle, "Follow Us") || "Follow Us";
636
+ const socialFromEmail = parseSocialLinksJson(emailSettings.socialLinks);
637
+ const socialLinks = socialFromEmail?.length ? socialFromEmail : fromBranding.socialLinks;
638
+ return {
639
+ logoUrl,
640
+ companyName,
641
+ supportEmail,
642
+ supportPhone,
643
+ socialLinks,
644
+ footerDisclaimer,
645
+ followUsTitle
646
+ };
647
+ }
648
+ chunkUSNT2KNT_cjs.__name(mergeEmailLayoutCompanyDetails, "mergeEmailLayoutCompanyDetails");
649
+ function getCompanyDetailsFromSettings(settingsGroup) {
650
+ const logoUrl = settingsGroup.logo ?? settingsGroup.logoUrl ?? "";
651
+ const companyName = settingsGroup.companyName ?? settingsGroup.company_name ?? "";
652
+ const supportEmail = settingsGroup.supportEmail ?? settingsGroup.support_email ?? "";
653
+ let socialLinks = [];
654
+ const raw = settingsGroup.socialLinks ?? settingsGroup.social_links;
655
+ if (typeof raw === "string") {
656
+ try {
657
+ const arr = JSON.parse(raw);
658
+ if (Array.isArray(arr)) {
659
+ for (const item of arr) {
660
+ if (item && typeof item === "object") {
661
+ const n = normalizeSocialLinkItem(item);
662
+ if (n) socialLinks.push(n);
663
+ }
664
+ }
665
+ }
666
+ } catch {
667
+ }
668
+ }
669
+ return {
670
+ logoUrl: logoUrl || void 0,
671
+ companyName: companyName || void 0,
672
+ supportEmail: supportEmail || void 0,
673
+ socialLinks: socialLinks.length ? socialLinks : void 0
674
+ };
675
+ }
676
+ chunkUSNT2KNT_cjs.__name(getCompanyDetailsFromSettings, "getCompanyDetailsFromSettings");
677
+
678
+ // src/lib/invoice/build-local-invoice-for-order.ts
679
+ async function loadSettingsGroup(ds, entityMap, group) {
680
+ if (!entityMap.configs) return {};
681
+ const rows = await ds.getRepository(entityMap.configs).find({
682
+ where: {
683
+ settings: group,
684
+ deleted: false
685
+ }
686
+ });
687
+ return Object.fromEntries(rows.map((r) => [
688
+ r.key,
689
+ String(r.value ?? "")
690
+ ]));
691
+ }
692
+ chunkUSNT2KNT_cjs.__name(loadSettingsGroup, "loadSettingsGroup");
693
+ function addrFromRow(row) {
694
+ if (!row || typeof row !== "object") return null;
695
+ const a = row;
696
+ return {
697
+ line1: String(a.line1 ?? "").trim() || void 0,
698
+ line2: a.line2 != null ? String(a.line2).trim() || null : null,
699
+ city: String(a.city ?? "").trim() || void 0,
700
+ state: String(a.state ?? "").trim() || void 0,
701
+ postalCode: String(a.postalCode ?? "").trim() || void 0,
702
+ country: String(a.country ?? "").trim() || void 0
703
+ };
704
+ }
705
+ chunkUSNT2KNT_cjs.__name(addrFromRow, "addrFromRow");
706
+ async function buildLocalInvoicePdfForOrder(ds, entityMap, orderId) {
707
+ if (!entityMap.orders || !entityMap.order_items) {
708
+ return {
709
+ error: "Orders not configured",
710
+ status: 503
711
+ };
712
+ }
713
+ const orderRepo = ds.getRepository(entityMap.orders);
714
+ let order = null;
715
+ try {
716
+ order = await orderRepo.findOne({
717
+ where: {
718
+ id: orderId,
719
+ deleted: false
720
+ },
721
+ relations: [
722
+ "contact",
723
+ "billingAddress",
724
+ "shippingAddress",
725
+ "items",
726
+ "items.product"
727
+ ]
728
+ });
729
+ } catch {
730
+ order = await orderRepo.findOne({
731
+ where: {
732
+ id: orderId,
733
+ deleted: false
734
+ },
735
+ relations: [
736
+ "contact",
737
+ "billingAddress",
738
+ "shippingAddress",
739
+ "items"
740
+ ]
741
+ });
742
+ }
743
+ if (!order) return {
744
+ error: "Not found",
745
+ status: 404
746
+ };
747
+ const o = order;
748
+ const kind = o.orderKind || "sale";
749
+ if (kind !== "sale") return {
750
+ error: "Invoice only for sale orders",
751
+ status: 400
752
+ };
753
+ const [store, branding, email] = await Promise.all([
754
+ loadSettingsGroup(ds, entityMap, "store"),
755
+ loadSettingsGroup(ds, entityMap, "branding"),
756
+ loadSettingsGroup(ds, entityMap, "email")
757
+ ]);
758
+ const companyDetails = mergeEmailLayoutCompanyDetails(branding, email);
759
+ const fromBranding = getCompanyDetailsFromSettings(branding);
760
+ const rawLogo = store.invoiceLogoUrl || store.companyLogo || store.logo || companyDetails.logoUrl || fromBranding.logoUrl || null;
761
+ const logoUrl = resolveInvoiceAssetUrl(rawLogo);
762
+ const companyName = store.companyName || store.invoiceCompanyName || store.name || companyDetails.companyName || fromBranding.companyName || "Store";
763
+ const supportEmail = store.companyEmail || store.invoiceEmail || store.email || companyDetails.supportEmail || fromBranding.supportEmail;
764
+ const supportPhone = store.companyPhone || store.invoicePhone || store.phone || companyDetails.supportPhone;
765
+ const address = store.companyAddress || store.invoiceAddress || store.address;
766
+ const lineItems = (o.items ?? []).map((it) => {
767
+ const name = it.product?.name && String(it.product.name).trim() || `Product #${it.productId ?? ""}`;
768
+ return {
769
+ name,
770
+ quantity: Math.max(0, Math.floor(Number(it.quantity) || 0)),
771
+ unitPrice: Number(it.unitPrice) || 0,
772
+ tax: Number(it.tax) || 0,
773
+ total: Number(it.total) || 0,
774
+ sku: it.product?.sku ?? null
775
+ };
776
+ });
777
+ const bytes = await generateLocalInvoicePdf({
778
+ templateId: normalizeInvoiceTemplateId(store.invoiceTemplate),
779
+ orderNumber: String(o.orderNumber || orderId),
780
+ orderDate: o.createdAt || /* @__PURE__ */ new Date(),
781
+ currency: String(o.currency || store.currency || "INR"),
782
+ customerName: String(o.contact?.name ?? "").trim() || "Customer",
783
+ customerEmail: o.contact?.email ?? null,
784
+ customerPhone: o.contact?.phone ?? null,
785
+ billingAddress: addrFromRow(o.billingAddress),
786
+ shippingAddress: addrFromRow(o.shippingAddress),
787
+ lineItems,
788
+ subtotal: Number(o.subtotal) || 0,
789
+ tax: Number(o.tax) || 0,
790
+ discount: Number(o.discount) || 0,
791
+ total: Number(o.total) || 0,
792
+ company: {
793
+ name: companyName,
794
+ logoUrl,
795
+ supportEmail,
796
+ supportPhone,
797
+ address
798
+ }
799
+ });
800
+ return {
801
+ bytes,
802
+ filename: `invoice-${String(o.orderNumber || orderId).replace(/[^\w.-]+/g, "_")}.pdf`
803
+ };
804
+ }
805
+ chunkUSNT2KNT_cjs.__name(buildLocalInvoicePdfForOrder, "buildLocalInvoicePdfForOrder");
806
+
807
+ // src/plugins/erp/erp-order-invoice.ts
808
+ function pickInvoiceId(data) {
809
+ const nested = data.invoice && typeof data.invoice === "object" && !Array.isArray(data.invoice) ? data.invoice : null;
810
+ const src = nested || data;
811
+ for (const k of [
812
+ "invoiceId",
813
+ "invoice_id",
814
+ "id"
815
+ ]) {
816
+ const v = src[k];
817
+ if (typeof v === "string" && v.trim()) return v.trim();
818
+ }
819
+ return void 0;
820
+ }
821
+ chunkUSNT2KNT_cjs.__name(pickInvoiceId, "pickInvoiceId");
822
+ function jsonErr(msg, status) {
823
+ return new Response(JSON.stringify({
824
+ error: msg
825
+ }), {
826
+ status,
827
+ headers: {
828
+ "Content-Type": "application/json"
829
+ }
830
+ });
831
+ }
832
+ chunkUSNT2KNT_cjs.__name(jsonErr, "jsonErr");
833
+ var ORDER_INVOICE_EMAIL_ELIGIBLE_STATUSES = /* @__PURE__ */ new Set([
834
+ "pending",
835
+ "placed",
836
+ "confirmed",
837
+ "processing",
838
+ "completed"
839
+ ]);
840
+ function isOrderEligibleForInvoiceEmail(status, orderKind) {
841
+ const kind = (orderKind || "sale").trim().toLowerCase();
842
+ if (kind !== "sale") return false;
843
+ return ORDER_INVOICE_EMAIL_ELIGIBLE_STATUSES.has(String(status ?? "").trim().toLowerCase());
844
+ }
845
+ chunkUSNT2KNT_cjs.__name(isOrderEligibleForInvoiceEmail, "isOrderEligibleForInvoiceEmail");
846
+ async function resolveOrderInvoicePdfBytes(cms, dataSource, entityMap, orderId, options = {}) {
847
+ try {
848
+ const orderRepo = dataSource.getRepository(entityMap.orders);
849
+ const order = await orderRepo.findOne({
850
+ where: {
851
+ id: orderId,
852
+ deleted: false
853
+ }
854
+ });
855
+ if (!order) return {
856
+ error: "Not found",
857
+ status: 404
858
+ };
859
+ const kind = order.orderKind || "sale";
860
+ if (kind !== "sale") return {
861
+ error: "Invoice only for sale orders",
862
+ status: 400
863
+ };
864
+ if (options.ownerContactId != null && order.contactId !== options.ownerContactId) {
865
+ return {
866
+ error: "Not found",
867
+ status: 404
868
+ };
869
+ }
870
+ const on = await chunkUPLVMVRX_cjs.isErpIntegrationEnabled(cms, dataSource, entityMap);
871
+ const erp = cms.getPlugin("erp");
872
+ if (on && erp?.submission) {
873
+ const meta = order.metadata && typeof order.metadata === "object" && !Array.isArray(order.metadata) ? order.metadata : {};
874
+ const inv = meta.invoice && typeof meta.invoice === "object" && !Array.isArray(meta.invoice) ? meta.invoice : {};
875
+ let invoiceId = typeof inv.invoiceId === "string" ? inv.invoiceId.trim() : "";
876
+ if (!invoiceId) {
877
+ const refId = String(order.orderNumber || "");
878
+ try {
879
+ const r = await erp.submission.postErpReadAction("get-invoice", {
880
+ platformOrderId: refId
881
+ });
882
+ const d = r.ok ? unwrapErpReadData(r.json) : null;
883
+ invoiceId = d ? pickInvoiceId(d) || "" : "";
884
+ } catch {
885
+ invoiceId = "";
886
+ }
887
+ }
888
+ if (invoiceId) {
889
+ const pdf = await erp.submission.fetchInvoicePdf(invoiceId);
890
+ if (pdf.ok && pdf.buffer) {
891
+ return {
892
+ bytes: new Uint8Array(pdf.buffer),
893
+ filename: `order-invoice-${orderId}.pdf`,
894
+ contentType: pdf.contentType || "application/pdf",
895
+ source: "erp"
896
+ };
897
+ }
898
+ }
899
+ }
900
+ const local = await buildLocalInvoicePdfForOrder(dataSource, entityMap, orderId);
901
+ if ("error" in local) return {
902
+ error: local.error,
903
+ status: local.status
904
+ };
905
+ return {
906
+ bytes: local.bytes,
907
+ filename: local.filename.startsWith("invoice-") ? local.filename.replace(/^invoice-/, "order-invoice-") : local.filename,
908
+ contentType: "application/pdf",
909
+ source: "local"
910
+ };
911
+ } catch (err) {
912
+ const msg = err instanceof Error ? err.message : String(err);
913
+ console.error("[invoice] resolveOrderInvoicePdfBytes failed", {
914
+ orderId,
915
+ error: msg
916
+ });
917
+ return {
918
+ error: `Invoice failed: ${msg}`,
919
+ status: 500
920
+ };
921
+ }
922
+ }
923
+ chunkUSNT2KNT_cjs.__name(resolveOrderInvoicePdfBytes, "resolveOrderInvoicePdfBytes");
924
+ async function streamOrderInvoicePdf(cms, dataSource, entityMap, orderId, options) {
925
+ const resolved = await resolveOrderInvoicePdfBytes(cms, dataSource, entityMap, orderId, options);
926
+ if ("error" in resolved) return jsonErr(resolved.error, resolved.status);
927
+ return new Response(Buffer.from(resolved.bytes), {
928
+ status: 200,
929
+ headers: {
930
+ "Content-Type": resolved.contentType,
931
+ "Content-Disposition": `attachment; filename="${resolved.filename}"`,
932
+ "X-Invoice-Source": resolved.source
933
+ }
934
+ });
935
+ }
936
+ chunkUSNT2KNT_cjs.__name(streamOrderInvoicePdf, "streamOrderInvoicePdf");
937
+
938
+ exports.INVOICE_TEMPLATE_IDS = INVOICE_TEMPLATE_IDS;
939
+ exports.INVOICE_TEMPLATE_OPTIONS = INVOICE_TEMPLATE_OPTIONS;
940
+ exports.ORDER_INVOICE_EMAIL_ELIGIBLE_STATUSES = ORDER_INVOICE_EMAIL_ELIGIBLE_STATUSES;
941
+ exports.buildLocalInvoicePdfForOrder = buildLocalInvoicePdfForOrder;
942
+ exports.extractChildOrderRefsFromSalePayload = extractChildOrderRefsFromSalePayload;
943
+ exports.generateLocalInvoicePdf = generateLocalInvoicePdf;
944
+ exports.getCompanyDetailsFromSettings = getCompanyDetailsFromSettings;
945
+ exports.isOrderEligibleForInvoiceEmail = isOrderEligibleForInvoiceEmail;
946
+ exports.mapErpPayloadToFulfillment = mapErpPayloadToFulfillment;
947
+ exports.mapErpPayloadToInvoiceNumber = mapErpPayloadToInvoiceNumber;
948
+ exports.mergeEmailLayoutCompanyDetails = mergeEmailLayoutCompanyDetails;
949
+ exports.normalizeInvoiceTemplateId = normalizeInvoiceTemplateId;
950
+ exports.resolveInvoiceAssetUrl = resolveInvoiceAssetUrl;
951
+ exports.resolveOrderInvoicePdfBytes = resolveOrderInvoicePdfBytes;
952
+ exports.streamOrderInvoicePdf = streamOrderInvoicePdf;
953
+ exports.unwrapErpReadData = unwrapErpReadData;