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