includio-cms 0.28.0 → 0.33.0

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 (99) hide show
  1. package/API.md +41 -13
  2. package/CHANGELOG.md +19 -0
  3. package/DOCS.md +1 -1
  4. package/ROADMAP.md +1 -0
  5. package/dist/admin/api/handler.js +4 -0
  6. package/dist/admin/api/integrations.d.ts +13 -0
  7. package/dist/admin/api/integrations.js +61 -0
  8. package/dist/admin/api/test-email.d.ts +9 -0
  9. package/dist/admin/api/test-email.js +39 -0
  10. package/dist/admin/auth-client.d.ts +543 -543
  11. package/dist/admin/client/index.d.ts +10 -0
  12. package/dist/admin/client/index.js +12 -0
  13. package/dist/admin/client/maintenance/maintenance-page.svelte +210 -0
  14. package/dist/admin/client/shop/coupon-schema.d.ts +1 -1
  15. package/dist/admin/client/shop/restore-order-cell.svelte +29 -0
  16. package/dist/admin/client/shop/restore-order-cell.svelte.d.ts +8 -0
  17. package/dist/admin/client/shop/shop-order-detail-page.svelte +71 -1
  18. package/dist/admin/client/shop/shop-orders-list-page.svelte +113 -53
  19. package/dist/admin/components/layout/app-sidebar.svelte +2 -0
  20. package/dist/admin/components/layout/nav-custom.svelte +26 -0
  21. package/dist/admin/components/layout/nav-custom.svelte.d.ts +3 -0
  22. package/dist/admin/components/layout/page-header.svelte +13 -3
  23. package/dist/admin/components/layout/page-header.svelte.d.ts +13 -3
  24. package/dist/admin/remote/admin.remote.d.ts +7 -0
  25. package/dist/admin/remote/admin.remote.js +10 -0
  26. package/dist/admin/remote/entry.remote.d.ts +2 -2
  27. package/dist/admin/remote/index.d.ts +1 -0
  28. package/dist/admin/remote/index.js +1 -0
  29. package/dist/admin/remote/invite.d.ts +1 -1
  30. package/dist/admin/remote/shop.remote.d.ts +71 -44
  31. package/dist/admin/remote/shop.remote.js +41 -10
  32. package/dist/admin/types.d.ts +15 -0
  33. package/dist/admin/utils/csv-export.d.ts +45 -0
  34. package/dist/admin/utils/csv-export.js +61 -0
  35. package/dist/cli/scaffold/admin.js +1 -1
  36. package/dist/components/ui/input/input.svelte.d.ts +1 -1
  37. package/dist/components/ui/input-group/input-group-input.svelte.d.ts +1 -1
  38. package/dist/components/ui/sidebar/sidebar-input.svelte.d.ts +1 -1
  39. package/dist/core/cms.d.ts +44 -2
  40. package/dist/core/cms.js +64 -0
  41. package/dist/core/index.d.ts +2 -4
  42. package/dist/core/index.js +1 -4
  43. package/dist/core/server/index.d.ts +4 -1
  44. package/dist/core/server/index.js +4 -1
  45. package/dist/db-postgres/schema/shop/order.d.ts +34 -0
  46. package/dist/db-postgres/schema/shop/order.js +4 -0
  47. package/dist/shop/adapters/fakturownia/client.d.ts +5 -0
  48. package/dist/shop/adapters/fakturownia/client.js +20 -0
  49. package/dist/shop/adapters/fakturownia/index.js +11 -0
  50. package/dist/shop/adapters/payu/index.js +11 -0
  51. package/dist/shop/index.d.ts +1 -1
  52. package/dist/shop/server/coupons.d.ts +10 -0
  53. package/dist/shop/server/coupons.js +19 -0
  54. package/dist/shop/server/email.d.ts +7 -3
  55. package/dist/shop/server/email.js +86 -112
  56. package/dist/shop/server/emailTemplateRegistry.d.ts +47 -0
  57. package/dist/shop/server/emailTemplateRegistry.js +288 -0
  58. package/dist/shop/server/orders.d.ts +60 -1
  59. package/dist/shop/server/orders.js +145 -16
  60. package/dist/shop/templates/_partials/footer.en.html +4 -0
  61. package/dist/shop/templates/_partials/footer.pl.html +4 -0
  62. package/dist/shop/templates/_partials/header.en.html +4 -0
  63. package/dist/shop/templates/_partials/header.pl.html +4 -0
  64. package/dist/shop/templates/_partials/items.en.html +14 -0
  65. package/dist/shop/templates/_partials/items.pl.html +14 -0
  66. package/dist/shop/templates/_partials/tracking.en.html +7 -0
  67. package/dist/shop/templates/_partials/tracking.pl.html +7 -0
  68. package/dist/shop/templates/awaiting-payment.en.html +6 -0
  69. package/dist/shop/templates/awaiting-payment.pl.html +6 -0
  70. package/dist/shop/templates/cancelled.en.html +6 -0
  71. package/dist/shop/templates/cancelled.pl.html +6 -0
  72. package/dist/shop/templates/low-stock.en.html +14 -0
  73. package/dist/shop/templates/low-stock.pl.html +14 -0
  74. package/dist/shop/templates/order-completed.en.html +6 -0
  75. package/dist/shop/templates/order-completed.pl.html +6 -0
  76. package/dist/shop/templates/order-received.en.html +7 -0
  77. package/dist/shop/templates/order-received.pl.html +7 -0
  78. package/dist/shop/templates/payment-received.en.html +7 -0
  79. package/dist/shop/templates/payment-received.pl.html +7 -0
  80. package/dist/shop/templates/payment-rejected.en.html +6 -0
  81. package/dist/shop/templates/payment-rejected.pl.html +6 -0
  82. package/dist/shop/templates/preparing.en.html +7 -0
  83. package/dist/shop/templates/preparing.pl.html +7 -0
  84. package/dist/shop/templates/refunded.en.html +6 -0
  85. package/dist/shop/templates/refunded.pl.html +6 -0
  86. package/dist/shop/templates/shipped.en.html +7 -0
  87. package/dist/shop/templates/shipped.pl.html +7 -0
  88. package/dist/shop/types.d.ts +63 -0
  89. package/dist/sveltekit/index.d.ts +0 -1
  90. package/dist/sveltekit/index.js +0 -1
  91. package/dist/sveltekit/server/index.d.ts +1 -0
  92. package/dist/sveltekit/server/index.js +1 -0
  93. package/dist/types/adapters/email.d.ts +13 -0
  94. package/dist/types/cms.d.ts +30 -0
  95. package/dist/types/index.d.ts +1 -1
  96. package/dist/updates/0.34.0/index.d.ts +2 -0
  97. package/dist/updates/0.34.0/index.js +17 -0
  98. package/dist/updates/index.js +3 -1
  99. package/package.json +7 -2
@@ -1,5 +1,3 @@
1
- export { getCMS } from './cms.js';
2
- export { resolveMediaWithStyles, type ResolvedMedia } from './server/fields/utils/resolveMedia.js';
3
1
  export { resolveSeo, type ResolvedSeo } from './fields/resolveSeo.js';
4
- export { createEntityAPI } from '../entity/index.js';
5
- export { getAuth } from '../server/auth.js';
2
+ export { getMailer, sendMail } from './cms.js';
3
+ export type { EmailAdapter, SendMailOptions } from '../types/adapters/email.js';
@@ -1,5 +1,2 @@
1
- export { getCMS } from './cms.js';
2
- export { resolveMediaWithStyles } from './server/fields/utils/resolveMedia.js';
3
1
  export { resolveSeo } from './fields/resolveSeo.js';
4
- export { createEntityAPI } from '../entity/index.js';
5
- export { getAuth } from '../server/auth.js';
2
+ export { getMailer, sendMail } from './cms.js';
@@ -1 +1,4 @@
1
- export {};
1
+ export { getCMS } from '../cms.js';
2
+ export { resolveMediaWithStyles, type ResolvedMedia } from './fields/utils/resolveMedia.js';
3
+ export { createEntityAPI } from '../../entity/index.js';
4
+ export { getAuth } from '../../server/auth.js';
@@ -1 +1,4 @@
1
- "use strict";
1
+ export { getCMS } from '../cms.js';
2
+ export { resolveMediaWithStyles } from './fields/utils/resolveMedia.js';
3
+ export { createEntityAPI } from '../../entity/index.js';
4
+ export { getAuth } from '../../server/auth.js';
@@ -565,6 +565,40 @@ export declare const shopOrdersTable: import("drizzle-orm/pg-core/table", { with
565
565
  identity: undefined;
566
566
  generated: undefined;
567
567
  }, {}, {}>;
568
+ deletedAt: import("drizzle-orm/pg-core", { with: { "resolution-mode": "require" } }).PgColumn<{
569
+ name: "deleted_at";
570
+ tableName: "shop_orders";
571
+ dataType: "date";
572
+ columnType: "PgTimestamp";
573
+ data: Date;
574
+ driverParam: string;
575
+ notNull: false;
576
+ hasDefault: false;
577
+ isPrimaryKey: false;
578
+ isAutoincrement: false;
579
+ hasRuntimeDefault: false;
580
+ enumValues: undefined;
581
+ baseColumn: never;
582
+ identity: undefined;
583
+ generated: undefined;
584
+ }, {}, {}>;
585
+ deletedBy: import("drizzle-orm/pg-core", { with: { "resolution-mode": "require" } }).PgColumn<{
586
+ name: "deleted_by";
587
+ tableName: "shop_orders";
588
+ dataType: "string";
589
+ columnType: "PgText";
590
+ data: string;
591
+ driverParam: string;
592
+ notNull: false;
593
+ hasDefault: false;
594
+ isPrimaryKey: false;
595
+ isAutoincrement: false;
596
+ hasRuntimeDefault: false;
597
+ enumValues: [string, ...string[]];
598
+ baseColumn: never;
599
+ identity: undefined;
600
+ generated: undefined;
601
+ }, {}, {}>;
568
602
  createdAt: import("drizzle-orm/pg-core", { with: { "resolution-mode": "require" } }).PgColumn<{
569
603
  name: "created_at";
570
604
  tableName: "shop_orders";
@@ -35,6 +35,10 @@ export const shopOrdersTable = pgTable('shop_orders', {
35
35
  accessToken: uuid('access_token').defaultRandom().notNull(),
36
36
  partialPayment: jsonb('partial_payment').$type(),
37
37
  balanceOwed: boolean('balance_owed').default(false).notNull(),
38
+ // Soft-delete: admin can hide an order from the admin list without losing
39
+ // the row (accounting/audit safety). NULL = visible. See softDeleteOrder.
40
+ deletedAt: timestamp('deleted_at', { withTimezone: true }),
41
+ deletedBy: text('deleted_by'),
38
42
  createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
39
43
  updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull()
40
44
  });
@@ -23,6 +23,11 @@ export declare class FakturowniaClient {
23
23
  constructor(opts: FakturowniaClientOptions);
24
24
  createInvoice(invoice: FakturowniaInvoiceBody): Promise<FakturowniaInvoice>;
25
25
  sendByEmail(id: number | string): Promise<void>;
26
+ /**
27
+ * Read-only account lookup — used for connectivity/auth health checks.
28
+ * Does NOT create or modify anything. A 200 means domain + token are valid.
29
+ */
30
+ getAccount(): Promise<unknown>;
26
31
  private postRaw;
27
32
  private post;
28
33
  }
@@ -40,6 +40,26 @@ export class FakturowniaClient {
40
40
  api_token: this.apiToken
41
41
  });
42
42
  }
43
+ /**
44
+ * Read-only account lookup — used for connectivity/auth health checks.
45
+ * Does NOT create or modify anything. A 200 means domain + token are valid.
46
+ */
47
+ async getAccount() {
48
+ const res = await this.fetchFn(`${this.base}/account.json?api_token=${encodeURIComponent(this.apiToken)}`, { headers: { Accept: 'application/json' } });
49
+ if (!res.ok) {
50
+ let body;
51
+ try {
52
+ body = await res.json();
53
+ }
54
+ catch {
55
+ body = await res.text().catch(() => undefined);
56
+ }
57
+ const raw = body == null ? '' : typeof body === 'string' ? body : JSON.stringify(body);
58
+ const detail = raw ? `: ${raw.slice(0, 400)}` : '';
59
+ throw new FakturowniaApiError(`Fakturownia /account.json → ${res.status}${detail}`, res.status, body);
60
+ }
61
+ return res.json();
62
+ }
43
63
  async postRaw(path, payload) {
44
64
  const res = await this.fetchFn(`${this.base}${path}`, {
45
65
  method: 'POST',
@@ -32,5 +32,16 @@ export function fakturowniaAdapter(opts) {
32
32
  await client.sendByEmail(externalId);
33
33
  };
34
34
  }
35
+ adapter.healthCheck = async () => {
36
+ // Read-only /account.json lookup — verifies domain + token without
37
+ // issuing an invoice.
38
+ try {
39
+ await client.getAccount();
40
+ return { ok: true };
41
+ }
42
+ catch (e) {
43
+ return { ok: false, message: e instanceof Error ? e.message : String(e) };
44
+ }
45
+ };
35
46
  return adapter;
36
47
  }
@@ -99,6 +99,17 @@ export function payuAdapter(opts) {
99
99
  amount: input.amount ?? 0,
100
100
  raw: result.raw
101
101
  };
102
+ },
103
+ async healthCheck() {
104
+ // OAuth client_credentials token fetch — reaches PayU and verifies
105
+ // posId/clientId/clientSecret without creating an order.
106
+ try {
107
+ await client.getAccessToken();
108
+ return { ok: true };
109
+ }
110
+ catch (e) {
111
+ return { ok: false, message: e instanceof Error ? e.message : String(e) };
112
+ }
102
113
  }
103
114
  };
104
115
  }
@@ -12,5 +12,5 @@ export type { InpostAdapterOptions, InpostSenderAddress, GeowidgetConfigPreset,
12
12
  export { fakturowniaAdapter } from './adapters/fakturownia/index.js';
13
13
  export type { FakturowniaAdapterOptions } from './adapters/fakturownia/index.js';
14
14
  export { isValidNip } from './nip.js';
15
- export type { ShopConfig, ResolvedShopConfig, Currency, OrderStatus, PaymentAdapter, PaymentCreateContext, PaymentRefundInput, PaymentRefundResult, CarrierAdapter, CarrierEvent, ShipmentCreateInput, ShipmentCreateResult, ShipmentLabel, ConsentConfig, ShopFeatures, PaymentCreateResult, PaymentEvent, OrderRef, CouponRef, I18nText, VariantAttribute, VariantAttributeText, VariantAttributeNumber, VariantAttributeDatetime, VariantAttributeSelect, VariantAttributeBoolean, VariantAttributeImage, VariantAttributeEntry, VariantAttributeSlug, VariantLabelConfig, VariantExpiryConfig, PaymentPolicy, DepositAmount, PartialPayment, InvoicingAdapter, InvoiceIssuePolicy, InvoiceBuyer, InvoiceLineItem, InvoicePayload, InvoiceCreateResult, InvoiceContext } from './types.js';
15
+ export type { ShopConfig, ResolvedShopConfig, Currency, Order, OrderStatus, PaymentAdapter, PaymentCreateContext, PaymentRefundInput, PaymentRefundResult, CarrierAdapter, CarrierEvent, ShipmentCreateInput, ShipmentCreateResult, ShipmentLabel, ConsentConfig, ShopFeatures, PaymentCreateResult, PaymentEvent, OrderRef, CouponRef, I18nText, VariantAttribute, VariantAttributeText, VariantAttributeNumber, VariantAttributeDatetime, VariantAttributeSelect, VariantAttributeBoolean, VariantAttributeImage, VariantAttributeEntry, VariantAttributeSlug, VariantLabelConfig, VariantExpiryConfig, PaymentPolicy, DepositAmount, PartialPayment, InvoicingAdapter, InvoiceIssuePolicy, InvoiceBuyer, InvoiceLineItem, InvoicePayload, InvoiceCreateResult, InvoiceContext } from './types.js';
16
16
  export { interpolateTemplate } from './template.js';
@@ -51,3 +51,13 @@ export declare function recordCouponRedemption(input: {
51
51
  * row commits.
52
52
  */
53
53
  export declare function releaseCouponSlot(couponId: string): Promise<void>;
54
+ /**
55
+ * Read the coupon applied to an order (if any), via the redemption row.
56
+ * Returns `null` when the order had no coupon or the redemption row is missing.
57
+ * Safe to call from email/admin/storefront — uses the same authoritative
58
+ * `shop_coupon_redemptions` table that `recordCouponRedemption` writes to.
59
+ */
60
+ export declare function getOrderCoupon(orderId: string): Promise<{
61
+ code: string;
62
+ discountAmount: number;
63
+ } | null>;
@@ -115,3 +115,22 @@ export async function releaseCouponSlot(couponId) {
115
115
  })
116
116
  .where(eq(shopCouponsTable.id, couponId));
117
117
  }
118
+ /**
119
+ * Read the coupon applied to an order (if any), via the redemption row.
120
+ * Returns `null` when the order had no coupon or the redemption row is missing.
121
+ * Safe to call from email/admin/storefront — uses the same authoritative
122
+ * `shop_coupon_redemptions` table that `recordCouponRedemption` writes to.
123
+ */
124
+ export async function getOrderCoupon(orderId) {
125
+ const db = getShopDb();
126
+ const [row] = await db
127
+ .select({
128
+ code: shopCouponsTable.code,
129
+ discountAmount: shopCouponRedemptionsTable.discountAmount
130
+ })
131
+ .from(shopCouponRedemptionsTable)
132
+ .innerJoin(shopCouponsTable, eq(shopCouponRedemptionsTable.couponId, shopCouponsTable.id))
133
+ .where(eq(shopCouponRedemptionsTable.orderId, orderId))
134
+ .limit(1);
135
+ return row ?? null;
136
+ }
@@ -1,11 +1,15 @@
1
1
  import type { OrderStatus } from '../types.js';
2
+ /**
3
+ * List of template names a shop install must ship in `dist/shop/templates/`.
4
+ * Consumed by `validateBuiltinTemplates` at CMS bootstrap.
5
+ * @internal
6
+ */
7
+ export declare const REQUIRED_TEMPLATE_NAMES: readonly string[];
2
8
  export declare function sendOrderStatusEmail(orderId: string, status: OrderStatus): Promise<void>;
3
9
  /**
4
10
  * Notify the shop admin that a product crossed its low-stock threshold.
5
11
  * Fire-and-forget — silently no-ops when no `shop.adminEmail` or no email
6
- * adapter is configured. Stays inside email.ts to keep the adapter call
7
- * site centralised (HTML, escaping, logging behaviour identical to status
8
- * emails).
12
+ * adapter is configured.
9
13
  *
10
14
  * @internal
11
15
  */
@@ -1,19 +1,10 @@
1
1
  import { getCMS } from '../../core/cms.js';
2
2
  import { resolveI18n } from '../pricing.js';
3
3
  import { getOrderById, getOrderItems } from './orders.js';
4
+ import { getOrderCoupon } from './coupons.js';
4
5
  import { requireShopConfig } from './db.js';
5
6
  import { buildOrderViewUrl } from './order-access-url.js';
6
- const TRACKING_LABEL = {
7
- pl: { label: 'Numer śledzenia', linkLabel: 'Sprawdź status przesyłki ↗' },
8
- en: { label: 'Tracking number', linkLabel: 'Track your shipment ↗' }
9
- };
10
- function formatPrice(cents, currency) {
11
- return new Intl.NumberFormat('pl-PL', {
12
- style: 'currency',
13
- currency,
14
- minimumFractionDigits: 2
15
- }).format(cents / 100);
16
- }
7
+ import { renderEmailTemplate } from './emailTemplateRegistry.js';
17
8
  const STATUS_SUBJECTS = {
18
9
  new: { pl: 'Zamówienie przyjęte', en: 'Order received' },
19
10
  awaitingPayment: { pl: 'Oczekiwanie na płatność', en: 'Awaiting payment' },
@@ -25,92 +16,41 @@ const STATUS_SUBJECTS = {
25
16
  paymentRejected: { pl: 'Płatność odrzucona', en: 'Payment rejected' },
26
17
  refunded: { pl: 'Zamówienie zwrócone', en: 'Order refunded' }
27
18
  };
28
- const STATUS_INTRO = {
29
- new: {
30
- pl: 'Dziękujemy! Otrzymaliśmy Twoje zamówienie i wkrótce je przetworzymy.',
31
- en: 'Thanks! We received your order and will process it shortly.'
32
- },
33
- awaitingPayment: {
34
- pl: 'Otrzymaliśmy zamówienie. Czekamy na płatność zgodnie z wybraną metodą.',
35
- en: 'Your order has been placed. Waiting for payment per the chosen method.'
36
- },
37
- paid: {
38
- pl: 'Płatność została zaksięgowana. Przekazujemy zamówienie do realizacji.',
39
- en: 'Payment has been received. Your order is moving to fulfilment.'
40
- },
41
- preparing: {
42
- pl: 'Twoje zamówienie jest pakowane.',
43
- en: 'Your order is being prepared.'
44
- },
45
- sent: {
46
- pl: 'Zamówienie zostało wysłane.',
47
- en: 'Your order has been shipped.'
48
- },
49
- done: {
50
- pl: 'Zamówienie zostało zakończone. Dziękujemy za zakupy!',
51
- en: 'Your order is complete. Thanks for shopping with us!'
52
- },
53
- cancelled: {
54
- pl: 'Zamówienie zostało anulowane.',
55
- en: 'Your order has been cancelled.'
56
- },
57
- paymentRejected: {
58
- pl: 'Płatność nie została zaksięgowana. Skontaktuj się z nami w razie pytań.',
59
- en: 'Payment was not received. Please contact us if you have questions.'
60
- },
61
- refunded: {
62
- pl: 'Środki zostały zwrócone. Powinny pojawić się na koncie w ciągu kilku dni roboczych.',
63
- en: 'Your refund has been issued. It should reach your account within a few business days.'
64
- }
19
+ const STATUS_TO_TEMPLATE = {
20
+ new: 'order-received',
21
+ awaitingPayment: 'awaiting-payment',
22
+ paid: 'payment-received',
23
+ preparing: 'preparing',
24
+ sent: 'shipped',
25
+ done: 'order-completed',
26
+ cancelled: 'cancelled',
27
+ paymentRejected: 'payment-rejected',
28
+ refunded: 'refunded'
29
+ };
30
+ const TRACKING_LABEL = {
31
+ pl: { label: 'Numer śledzenia', linkLabel: 'Sprawdź status przesyłki ↗' },
32
+ en: { label: 'Tracking number', linkLabel: 'Track your shipment ↗' }
65
33
  };
66
34
  const VIEW_LINK_LABEL = {
67
35
  pl: 'Zobacz zamówienie',
68
36
  en: 'View order'
69
37
  };
70
- function renderHtml(ctx, intro) {
71
- const itemsRows = ctx.items
72
- .map((i) => `<tr><td style="padding:6px 8px;border-bottom:1px solid #eee;">${escapeHtml(i.name)}</td><td style="padding:6px 8px;border-bottom:1px solid #eee;text-align:center;">${i.qty}</td><td style="padding:6px 8px;border-bottom:1px solid #eee;text-align:right;">${i.lineGross}</td></tr>`)
73
- .join('');
74
- return `<!doctype html>
75
- <html><body style="margin:0;padding:0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif;background:#f5f5f8;color:#1a1a2e;">
76
- <div style="max-width:560px;margin:0 auto;padding:24px;">
77
- <div style="background:#fff;border-radius:12px;padding:28px;">
78
- <h1 style="font-size:20px;font-weight:800;margin:0 0 8px;">Zamówienie ${escapeHtml(ctx.order.number)}</h1>
79
- <p style="margin:0 0 20px;color:#555566;line-height:1.5;">${escapeHtml(intro)}</p>
80
- <table style="width:100%;border-collapse:collapse;font-size:14px;">
81
- <thead><tr style="background:#f4f2fa;"><th align="left" style="padding:8px;">Pozycja</th><th style="padding:8px;">Ilość</th><th align="right" style="padding:8px;">Suma</th></tr></thead>
82
- <tbody>${itemsRows}</tbody>
83
- </table>
84
- <div style="margin-top:16px;text-align:right;font-size:14px;line-height:1.7;">
85
- <div>Wysyłka: <strong>${ctx.order.shippingGross}</strong></div>
86
- <div style="font-size:16px;">Razem (brutto): <strong style="color:#5B4A9E;">${ctx.order.totalGross}</strong></div>
87
- <div style="color:#8888A0;font-size:12px;">netto ${ctx.order.totalNet} · VAT ${ctx.order.vatAmount}</div>
88
- </div>
89
- ${ctx.tracking
90
- ? `<div style="margin-top:20px;padding:16px;background:#F4F2FA;border-radius:10px;font-size:14px;">
91
- <div style="color:#555566;margin-bottom:4px;">${escapeHtml(ctx.tracking.label)}</div>
92
- <div style="font-family:ui-monospace,monospace;font-weight:700;word-break:break-all;">${escapeHtml(ctx.tracking.number)}</div>
93
- ${ctx.tracking.url
94
- ? `<a href="${escapeHtml(ctx.tracking.url)}" style="display:inline-block;margin-top:8px;color:#5B4A9E;font-weight:600;text-decoration:none;">${escapeHtml(ctx.tracking.linkLabel)}</a>`
95
- : ''}
96
- </div>`
97
- : ''}
98
- ${ctx.viewUrl
99
- ? `<div style="margin-top:24px;text-align:center;"><a href="${escapeHtml(ctx.viewUrl)}" style="display:inline-block;background:#5B4A9E;color:#fff;text-decoration:none;padding:10px 18px;border-radius:8px;font-weight:600;">${escapeHtml(ctx.viewLinkLabel)}</a></div>`
100
- : ''}
101
- </div>
102
- <p style="text-align:center;color:#8888A0;font-size:12px;margin-top:16px;">AriaCMS · ${escapeHtml(ctx.order.customerEmail)}</p>
103
- </div>
104
- </body></html>`;
105
- }
106
- function escapeHtml(s) {
107
- return s
108
- .replace(/&/g, '&amp;')
109
- .replace(/</g, '&lt;')
110
- .replace(/>/g, '&gt;')
111
- .replace(/"/g, '&quot;')
112
- .replace(/'/g, '&#39;');
38
+ function formatPrice(cents, currency) {
39
+ return new Intl.NumberFormat('pl-PL', {
40
+ style: 'currency',
41
+ currency,
42
+ minimumFractionDigits: 2
43
+ }).format(cents / 100);
113
44
  }
45
+ /**
46
+ * List of template names a shop install must ship in `dist/shop/templates/`.
47
+ * Consumed by `validateBuiltinTemplates` at CMS bootstrap.
48
+ * @internal
49
+ */
50
+ export const REQUIRED_TEMPLATE_NAMES = [
51
+ ...Object.values(STATUS_TO_TEMPLATE),
52
+ 'low-stock'
53
+ ];
114
54
  export async function sendOrderStatusEmail(orderId, status) {
115
55
  const cms = getCMS();
116
56
  const shop = requireShopConfig();
@@ -123,6 +63,13 @@ export async function sendOrderStatusEmail(orderId, status) {
123
63
  if (!order)
124
64
  return;
125
65
  const items = await getOrderItems(orderId);
66
+ let coupon = null;
67
+ try {
68
+ coupon = await getOrderCoupon(orderId);
69
+ }
70
+ catch (err) {
71
+ console.error('[shop] Failed to load order coupon for email context:', err);
72
+ }
126
73
  const lang = (order.language || cms.languages[0] || 'pl');
127
74
  const subjectKey = (lang in STATUS_SUBJECTS[status] ? lang : 'pl');
128
75
  const viewUrl = /^https?:\/\//i.test(shop.orderViewUrl)
@@ -155,7 +102,7 @@ export async function sendOrderStatusEmail(orderId, status) {
155
102
  linkLabel: TRACKING_LABEL[subjectKey].linkLabel
156
103
  };
157
104
  }
158
- const ctx = {
105
+ const context = {
159
106
  viewUrl,
160
107
  viewLinkLabel: VIEW_LINK_LABEL[subjectKey],
161
108
  tracking,
@@ -164,11 +111,15 @@ export async function sendOrderStatusEmail(orderId, status) {
164
111
  status: order.status,
165
112
  customerName: order.customerName ?? '',
166
113
  customerEmail: order.customerEmail,
114
+ language: order.language,
167
115
  totalGross: formatPrice(order.totalGross, order.currency),
168
116
  totalNet: formatPrice(order.totalNet, order.currency),
169
117
  vatAmount: formatPrice(order.vatAmount, order.currency),
170
118
  shippingGross: formatPrice(order.shippingGross, order.currency),
171
- currency: order.currency
119
+ currency: order.currency,
120
+ couponCode: coupon?.code ?? null,
121
+ discountAmount: coupon ? formatPrice(coupon.discountAmount, order.currency) : null,
122
+ hasDiscount: Boolean(coupon && coupon.discountAmount > 0)
172
123
  },
173
124
  items: items.map((i) => ({
174
125
  name: resolveI18n(i.nameSnapshot?.product
@@ -176,11 +127,25 @@ export async function sendOrderStatusEmail(orderId, status) {
176
127
  : undefined, lang) || '—',
177
128
  qty: i.qty,
178
129
  lineGross: formatPrice(i.priceGrossSnapshot * i.qty, order.currency)
179
- }))
130
+ })),
131
+ shop: {
132
+ currency: order.currency,
133
+ adminEmail: shop.adminEmail ?? null
134
+ }
180
135
  };
181
136
  const subject = `${STATUS_SUBJECTS[status][subjectKey]} · ${order.number}`;
182
- const intro = STATUS_INTRO[status][subjectKey];
183
- const html = renderHtml(ctx, intro);
137
+ const templateName = STATUS_TO_TEMPLATE[status];
138
+ let html;
139
+ try {
140
+ html = await renderEmailTemplate(templateName, lang, context, {
141
+ projectDir: shop.emailTemplates?.dir,
142
+ strict: shop.emailTemplates?.strict
143
+ });
144
+ }
145
+ catch (err) {
146
+ console.error(`[shop] Failed to render template "${templateName}.${lang}.html" for order ${order.number}:`, err);
147
+ return;
148
+ }
184
149
  try {
185
150
  await emailAdapter.sendMail({
186
151
  to: order.customerEmail,
@@ -196,9 +161,7 @@ export async function sendOrderStatusEmail(orderId, status) {
196
161
  /**
197
162
  * Notify the shop admin that a product crossed its low-stock threshold.
198
163
  * Fire-and-forget — silently no-ops when no `shop.adminEmail` or no email
199
- * adapter is configured. Stays inside email.ts to keep the adapter call
200
- * site centralised (HTML, escaping, logging behaviour identical to status
201
- * emails).
164
+ * adapter is configured.
202
165
  *
203
166
  * @internal
204
167
  */
@@ -211,20 +174,31 @@ export async function sendLowStockEmail(input) {
211
174
  const emailAdapter = cms.emailAdapter;
212
175
  if (!emailAdapter)
213
176
  return;
177
+ const lang = (cms.languages[0] ?? 'pl');
214
178
  const subject = `Niski stan magazynowy · ${input.productTitle}`;
215
- const html = `<!doctype html>
216
- <html><body style="margin:0;padding:0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif;background:#f5f5f8;color:#1a1a2e;">
217
- <div style="max-width:560px;margin:0 auto;padding:24px;">
218
- <div style="background:#fff;border-radius:12px;padding:28px;">
219
- <h1 style="font-size:20px;font-weight:800;margin:0 0 8px;color:#C4893A;">Niski stan magazynowy</h1>
220
- <p style="margin:0 0 16px;color:#555566;line-height:1.5;">
221
- Produkt <strong>${escapeHtml(input.productTitle)}</strong>${input.variantSku ? ` (SKU ${escapeHtml(input.variantSku)})` : ''}
222
- ma już tylko <strong>${input.stock}</strong> sztuk w magazynie (próg alertu: ${input.threshold}).
223
- </p>
224
- <p style="margin:0;color:#8888A0;font-size:13px;">Uzupełnij stan w panelu admina, żeby uniknąć przerwy w sprzedaży.</p>
225
- </div>
226
- </div>
227
- </body></html>`;
179
+ const context = {
180
+ product: {
181
+ title: input.productTitle,
182
+ variantSku: input.variantSku,
183
+ stock: input.stock,
184
+ threshold: input.threshold
185
+ },
186
+ shop: {
187
+ currency: shop.currency,
188
+ adminEmail
189
+ }
190
+ };
191
+ let html;
192
+ try {
193
+ html = await renderEmailTemplate('low-stock', lang, context, {
194
+ projectDir: shop.emailTemplates?.dir,
195
+ strict: shop.emailTemplates?.strict
196
+ });
197
+ }
198
+ catch (err) {
199
+ console.error('[shop] Failed to render low-stock template:', err);
200
+ return;
201
+ }
228
202
  try {
229
203
  await emailAdapter.sendMail({ to: adminEmail, subject, html });
230
204
  }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Shop email template registry — file-based Handlebars templates with
3
+ * 4-step resolution (project override → package default) and per-template
4
+ * CMS singleton auto-fetch. Used by `sendOrderStatusEmail` and
5
+ * `sendLowStockEmail` in email.ts.
6
+ *
7
+ * @internal — exported here for testing; not part of the public API.
8
+ */
9
+ type Lang = string;
10
+ interface ResolveResult {
11
+ filePath: string;
12
+ source: string;
13
+ isOverride: boolean;
14
+ }
15
+ /**
16
+ * 4-step lookup for a single template file.
17
+ * Returns `null` only if every step misses (shouldn't happen for built-in
18
+ * templates if the package is intact).
19
+ */
20
+ declare function resolveTemplatePath(projectDir: string, name: string, lang: Lang, fallbackLang: Lang): ResolveResult | null;
21
+ /**
22
+ * Traverse Handlebars AST and collect all `cms.<slug>.*` accessor slugs.
23
+ * Returns the unique set so the renderer can prefetch them.
24
+ */
25
+ declare function extractCmsSlugs(ast: hbs.AST.Program): Set<string>;
26
+ /**
27
+ * Public render entry — used by sendOrderStatusEmail / sendLowStockEmail.
28
+ * Looks up the template, prefetches required CMS singletons, renders.
29
+ */
30
+ export declare function renderEmailTemplate(name: string, lang: Lang, context: Record<string, unknown>, opts?: {
31
+ projectDir?: string;
32
+ strict?: boolean;
33
+ }): Promise<string>;
34
+ /**
35
+ * Bootstrap-time smoke test — verify every required default template is
36
+ * present in the package. Called from initCMS after setShop.
37
+ * Lookup-only: does not compile or render, so cheap.
38
+ */
39
+ export declare function validateBuiltinTemplates(requiredNames: string[], defaultLang: Lang): void;
40
+ /** @internal — exposed for tests */
41
+ export declare const __testExports: {
42
+ extractCmsSlugs: typeof extractCmsSlugs;
43
+ resolveTemplatePath: typeof resolveTemplatePath;
44
+ PACKAGE_TEMPLATES_DIR: string;
45
+ clearCache: () => void;
46
+ };
47
+ export {};