@jarwizz/create-jarshop 0.1.9 → 0.3.1

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 (115) hide show
  1. package/README.md +15 -0
  2. package/dist/cli.d.ts +1 -0
  3. package/dist/cli.js +1 -0
  4. package/dist/cli.js.map +1 -1
  5. package/dist/generator.d.ts +11 -1
  6. package/dist/generator.js +45 -11
  7. package/dist/generator.js.map +1 -1
  8. package/dist/presets.d.ts +26 -0
  9. package/dist/presets.js +94 -0
  10. package/dist/presets.js.map +1 -0
  11. package/dist/template/CONTEXT.md +4 -2
  12. package/dist/template/README.md +255 -3
  13. package/dist/template/env.example.template +19 -0
  14. package/dist/template/gitignore.template +1 -0
  15. package/dist/template/jarshop.config.ts +31 -0
  16. package/dist/template/package.json +4 -0
  17. package/dist/template/pnpm-lock.yaml +3284 -1815
  18. package/dist/template/pnpm-workspace.yaml +6 -1
  19. package/dist/template/src/client/features.ts +41 -0
  20. package/dist/template/src/client/invoicing.ts +29 -0
  21. package/dist/template/src/dev-storefront-environment.test.ts +45 -0
  22. package/dist/template/src/dev-storefront-environment.ts +32 -0
  23. package/dist/template/src/dev-storefront.ts +3 -12
  24. package/dist/template/src/environment.d.ts +8 -0
  25. package/dist/template/src/invoice-email-recover.ts +59 -0
  26. package/dist/template/src/jarshop-config-loader.ts +118 -0
  27. package/dist/template/src/jarshop-config.test.ts +335 -0
  28. package/dist/template/src/jarshop-config.ts +439 -0
  29. package/dist/template/src/jarshop-features.test.ts +222 -0
  30. package/dist/template/src/jarshop-features.ts +112 -0
  31. package/dist/template/src/operation-codes.ts +34 -0
  32. package/dist/template/src/packeta-config.test.ts +95 -0
  33. package/dist/template/src/packeta-countries.test.ts +161 -0
  34. package/dist/template/src/packeta-countries.ts +120 -0
  35. package/dist/template/src/packeta-validation.test.ts +35 -0
  36. package/dist/template/src/packeta-validation.ts +52 -0
  37. package/dist/template/src/payment-return-url.test.ts +57 -0
  38. package/dist/template/src/payment-return-url.ts +34 -0
  39. package/dist/template/src/plugins/jarshop-checkout/confirmation-view.test.ts +79 -0
  40. package/dist/template/src/plugins/jarshop-checkout/confirmation.ts +51 -0
  41. package/dist/template/src/plugins/jarshop-checkout/dashboard/index.tsx +1 -0
  42. package/dist/template/src/plugins/jarshop-checkout/invoice-delivery.plugin.ts +79 -0
  43. package/dist/template/src/plugins/jarshop-checkout/invoice-email-events.ts +35 -0
  44. package/dist/template/src/plugins/jarshop-checkout/invoice-email-lifecycle.ts +235 -0
  45. package/dist/template/src/plugins/jarshop-checkout/invoice-email-worker.test.ts +426 -0
  46. package/dist/template/src/plugins/jarshop-checkout/invoice-email.test.ts +107 -0
  47. package/dist/template/src/plugins/jarshop-checkout/jarshop-checkout.plugin.ts +161 -57
  48. package/dist/template/src/plugins/jarshop-checkout/market-channels.test.ts +58 -0
  49. package/dist/template/src/plugins/jarshop-checkout/market-channels.ts +87 -0
  50. package/dist/template/src/plugins/jarshop-checkout/operation-code-check.ts +36 -0
  51. package/dist/template/src/plugins/jarshop-checkout/order-email-configuration.entity.ts +1 -1
  52. package/dist/template/src/plugins/jarshop-checkout/order-email-configuration.ts +1 -0
  53. package/dist/template/src/plugins/jarshop-checkout/order-email-delivery-core.ts +94 -1
  54. package/dist/template/src/plugins/jarshop-checkout/order-email-delivery.entity.ts +1 -0
  55. package/dist/template/src/plugins/jarshop-checkout/order-email-outbox.ts +83 -1
  56. package/dist/template/src/plugins/jarshop-checkout/order-email-worker.ts +136 -1
  57. package/dist/template/src/plugins/jarshop-checkout/shipping-tax.test.ts +109 -0
  58. package/dist/template/src/plugins/jarshop-checkout/shipping.test.ts +156 -0
  59. package/dist/template/src/plugins/jarshop-checkout/shipping.ts +75 -11
  60. package/dist/template/src/seed.ts +427 -184
  61. package/dist/template/src/vendure-config.ts +258 -113
  62. package/dist/template/storefront/README.md +7 -0
  63. package/dist/template/storefront/app/[locale]/[slug]/page.tsx +3 -2
  64. package/dist/template/storefront/app/[locale]/account/login/page.tsx +3 -2
  65. package/dist/template/storefront/app/[locale]/account/page.tsx +10 -4
  66. package/dist/template/storefront/app/[locale]/account/password-reset/callback/route.ts +4 -2
  67. package/dist/template/storefront/app/[locale]/account/password-reset/complete/page.tsx +3 -2
  68. package/dist/template/storefront/app/[locale]/account/password-reset/page.tsx +3 -2
  69. package/dist/template/storefront/app/[locale]/account/register/page.tsx +3 -2
  70. package/dist/template/storefront/app/[locale]/account/verify/complete/route.ts +4 -2
  71. package/dist/template/storefront/app/[locale]/account/verify/page.tsx +3 -2
  72. package/dist/template/storefront/app/[locale]/cart/page.tsx +3 -2
  73. package/dist/template/storefront/app/[locale]/checkout/actions.ts +43 -0
  74. package/dist/template/storefront/app/[locale]/checkout/checkout-form.tsx +188 -36
  75. package/dist/template/storefront/app/[locale]/checkout/confirmation/route.ts +2 -2
  76. package/dist/template/storefront/app/[locale]/checkout/packeta-chooser.tsx +96 -0
  77. package/dist/template/storefront/app/[locale]/checkout/page.tsx +60 -2
  78. package/dist/template/storefront/app/[locale]/checkout/payment-return/actions.ts +55 -0
  79. package/dist/template/storefront/app/[locale]/checkout/payment-return/page.tsx +32 -0
  80. package/dist/template/storefront/app/[locale]/checkout/payment-return/payment-return.tsx +84 -0
  81. package/dist/template/storefront/app/[locale]/checkout/success/page.tsx +32 -2
  82. package/dist/template/storefront/app/[locale]/layout.tsx +3 -2
  83. package/dist/template/storefront/app/[locale]/page.tsx +3 -2
  84. package/dist/template/storefront/app/globals.css +16 -0
  85. package/dist/template/storefront/app/layout.tsx +6 -2
  86. package/dist/template/storefront/lib/cart.ts +2 -4
  87. package/dist/template/storefront/lib/checkout-contract.test.ts +18 -1
  88. package/dist/template/storefront/lib/checkout-contract.ts +8 -0
  89. package/dist/template/storefront/lib/checkout-countries.test.ts +61 -0
  90. package/dist/template/storefront/lib/checkout-countries.ts +67 -0
  91. package/dist/template/storefront/lib/checkout.ts +22 -11
  92. package/dist/template/storefront/lib/commerce.ts +262 -2
  93. package/dist/template/storefront/lib/confirmation.test.ts +116 -0
  94. package/dist/template/storefront/lib/confirmation.ts +13 -7
  95. package/dist/template/storefront/lib/i18n.test.ts +32 -12
  96. package/dist/template/storefront/lib/i18n.ts +29 -8
  97. package/dist/template/storefront/lib/market-config.ts +40 -0
  98. package/dist/template/storefront/lib/market-routing.test.ts +107 -0
  99. package/dist/template/storefront/lib/market-routing.ts +57 -0
  100. package/dist/template/storefront/lib/market.ts +51 -0
  101. package/dist/template/storefront/lib/packeta-selection.test.ts +141 -0
  102. package/dist/template/storefront/lib/packeta-selection.ts +98 -0
  103. package/dist/template/storefront/lib/payment-return-actions.test.ts +61 -0
  104. package/dist/template/storefront/lib/payment-return-page.test.ts +30 -0
  105. package/dist/template/storefront/lib/payment-return-polling.test.ts +37 -0
  106. package/dist/template/storefront/lib/payment-return-polling.ts +58 -0
  107. package/dist/template/storefront/messages/en.json +13 -1
  108. package/dist/template/storefront/messages/sk.json +13 -1
  109. package/dist/template/storefront/package.json +2 -1
  110. package/dist/template/storefront/proxy.ts +35 -0
  111. package/dist/template/turbo.json +5 -1
  112. package/dist/template-manifest.json +1 -1
  113. package/dist/template.js +1 -0
  114. package/dist/template.js.map +1 -1
  115. package/package.json +1 -1
@@ -0,0 +1,426 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import { Readable } from "node:stream";
3
+ import {
4
+ Channel,
5
+ EventBus,
6
+ LanguageCode,
7
+ Logger,
8
+ Order,
9
+ OrderService,
10
+ RequestContext,
11
+ TransactionalConnection,
12
+ } from "@vendure/core";
13
+ import {
14
+ JarShopInvoiceCreatedEvent,
15
+ JarShopInvoicingPlugin,
16
+ } from "@jarwizz/jarshop-invoicing/server";
17
+ import { JarShopInvoiceEmailOutbox } from "./invoice-email-lifecycle.js";
18
+ import {
19
+ JarShopOrderEmailWorker,
20
+ invoicingDisabledDeferralMs,
21
+ jarShopOrderEmailWorkerTask,
22
+ } from "./order-email-worker.js";
23
+ import { JarShopOrderEmailDelivery } from "./order-email-delivery.entity.js";
24
+ import { JarShopEmailBrandConfiguration } from "./order-email-configuration.entity.js";
25
+ import { createPendingOrderEmailDelivery } from "./order-email-outbox.js";
26
+
27
+ const smtp = vi.hoisted(() => ({
28
+ sendMail: vi.fn(async (_message: unknown) => {}),
29
+ }));
30
+ vi.mock("nodemailer", () => ({ default: { createTransport: () => smtp } }));
31
+ afterEach(() => {
32
+ vi.unstubAllEnvs();
33
+ vi.clearAllMocks();
34
+ });
35
+
36
+ function fixture(
37
+ languageCode = LanguageCode.sk,
38
+ { invoicingRegistered = true } = {},
39
+ ) {
40
+ // Mutable so a test can switch invoicing back on between worker passes.
41
+ const registration = { invoicingRegistered };
42
+ vi.stubEnv(
43
+ "JARSHOP_ORDER_EMAIL_ENCRYPTION_KEY",
44
+ Buffer.alloc(32, 1).toString("base64"),
45
+ );
46
+ vi.stubEnv("JARSHOP_EMAIL_TRANSPORT", "smtp");
47
+ vi.stubEnv("JARSHOP_EMAIL_SMTP_SECURE", "false");
48
+ vi.stubEnv("JARSHOP_EMAIL_SMTP_HOST", "smtp.example.invalid");
49
+ vi.stubEnv("JARSHOP_EMAIL_SMTP_PORT", "587");
50
+ vi.stubEnv("JARSHOP_EMAIL_SMTP_USERNAME", "test");
51
+ vi.stubEnv("JARSHOP_EMAIL_SMTP_PASSWORD", "test");
52
+ vi.stubEnv("JARSHOP_EMAIL_SMTP_FROM", "shop@example.invalid");
53
+ const channel = new Channel({ id: 2, token: "test" });
54
+ const ctx = new RequestContext({
55
+ apiType: "admin",
56
+ channel,
57
+ isAuthorized: true,
58
+ authorizedAsOwnerOnly: false,
59
+ languageCode,
60
+ });
61
+ const order = new Order({
62
+ id: 12,
63
+ code: "ORDER-12",
64
+ customer: { emailAddress: "buyer@example.invalid" },
65
+ });
66
+ const invoices = new Map<string, JarShopInvoiceCreatedEvent["newInvoice"]>();
67
+ const document = (id: number, isCreditInvoice = false) => {
68
+ const invoice = {
69
+ id,
70
+ channelId: "2",
71
+ orderId: "12",
72
+ invoiceNumber: 20260100 + id,
73
+ isCreditInvoice,
74
+ storageReference: "private",
75
+ } as JarShopInvoiceCreatedEvent["newInvoice"];
76
+ invoices.set(String(id), invoice);
77
+ return invoice;
78
+ };
79
+ const brand = {
80
+ channelId: 2,
81
+ enabledEvents: ["invoice-issued"],
82
+ brandName: "Shop",
83
+ logoUrl: null,
84
+ primaryColor: "#123456",
85
+ websiteUrl: "https://example.invalid",
86
+ supportEmail: "support@example.invalid",
87
+ companyName: "Shop",
88
+ companyAddress: "Test 1",
89
+ };
90
+ // In-memory database adapter: the event-key uniqueness and lease predicates
91
+ // mirror the existing outbox contract; this is not PostgreSQL concurrency proof.
92
+ const rows: JarShopOrderEmailDelivery[] = [];
93
+ const matches = (row: object, where: object) =>
94
+ Object.entries(where).every(
95
+ ([key, value]) => Reflect.get(row, key) === value,
96
+ );
97
+ const repository = {
98
+ find: async () => rows,
99
+ findOne: async ({ where }: { where: object }) =>
100
+ rows.find((row) => matches(row, where)) ?? null,
101
+ save: async (row: JarShopOrderEmailDelivery) => row,
102
+ update: async (where: object, values: object) => {
103
+ const row = rows.find((row) => matches(row, where));
104
+ if (row) Object.assign(row, values);
105
+ return { affected: row ? 1 : 0 };
106
+ },
107
+ createQueryBuilder: () => {
108
+ let values: JarShopOrderEmailDelivery[] = [];
109
+ let now = new Date();
110
+ const builder = {
111
+ insert: () => builder,
112
+ values: (input: JarShopOrderEmailDelivery[]) => {
113
+ values = input;
114
+ return builder;
115
+ },
116
+ orIgnore: () => builder,
117
+ execute: async () => {
118
+ for (const row of values)
119
+ if (!rows.some((saved) => saved.eventKey === row.eventKey))
120
+ rows.push({ ...row, id: rows.length + 1 });
121
+ },
122
+ setLock: () => builder,
123
+ setOnLocked: () => builder,
124
+ where: (_query: string, parameters: { now: Date }) => {
125
+ now = parameters.now;
126
+ return builder;
127
+ },
128
+ orderBy: () => builder,
129
+ addOrderBy: () => builder,
130
+ getOne: async () =>
131
+ rows.find(
132
+ (row) => row.status === "pending" && row.nextAttemptAt <= now,
133
+ ) ?? null,
134
+ };
135
+ return builder;
136
+ },
137
+ };
138
+ const getRepository = (entity: { name: string }) => {
139
+ if (entity === JarShopOrderEmailDelivery) return repository;
140
+ if (entity === JarShopEmailBrandConfiguration)
141
+ return { findOne: async () => brand, find: async () => [brand] };
142
+ if (entity === Channel) return { findOne: async () => channel };
143
+ if (entity.name === "InvoiceEntity")
144
+ return {
145
+ find: async () => [...invoices.values()],
146
+ findOne: async ({ where }: { where: { id: string } }) =>
147
+ invoices.get(String(where.id)),
148
+ };
149
+ throw new Error(`Unexpected test entity ${entity.name}`);
150
+ };
151
+ const connection = {
152
+ getRepository: (_ctx: unknown, entity: { name: string }) =>
153
+ getRepository(entity),
154
+ rawConnection: {
155
+ getRepository,
156
+ transaction: async (callback: (manager: object) => unknown) =>
157
+ callback({ getRepository }),
158
+ },
159
+ } as unknown as TransactionalConnection;
160
+ const orderService = {
161
+ findOne: async () => order,
162
+ } as unknown as OrderService;
163
+ // Without the invoicing Feature, JarShopInvoiceDeliveryPlugin and with it the
164
+ // invoice outbox are not registered, so Nest cannot resolve the outbox.
165
+ const moduleRef = {
166
+ get: (token: { name: string }) => {
167
+ if (token === JarShopInvoiceEmailOutbox) {
168
+ if (!registration.invoicingRegistered)
169
+ throw new Error("Nest could not find JarShopInvoiceEmailOutbox");
170
+ return outbox;
171
+ }
172
+ return token.name === "TransactionalConnection"
173
+ ? connection
174
+ : orderService;
175
+ },
176
+ };
177
+ JarShopInvoicingPlugin.init({ vendureHost: "https://example.invalid" });
178
+ const readPdf = vi.fn(() => Readable.from([Buffer.from("%PDF-synthetic")]));
179
+ Object.assign(JarShopInvoicingPlugin.config.storageStrategy, {
180
+ streamFile: readPdf,
181
+ });
182
+ const outbox = new JarShopInvoiceEmailOutbox(
183
+ connection,
184
+ {} as EventBus,
185
+ { create: async () => ctx } as never,
186
+ moduleRef as never,
187
+ );
188
+ const worker = new JarShopOrderEmailWorker(
189
+ connection,
190
+ orderService,
191
+ { create: async () => ctx } as never,
192
+ {} as never,
193
+ moduleRef as never,
194
+ );
195
+ const event = (
196
+ newInvoice: ReturnType<typeof document>,
197
+ creditInvoice?: ReturnType<typeof document>,
198
+ ) =>
199
+ new JarShopInvoiceCreatedEvent({
200
+ ctx,
201
+ order,
202
+ newInvoice,
203
+ ...(creditInvoice ? { creditInvoice } : {}),
204
+ });
205
+ return {
206
+ outbox,
207
+ worker,
208
+ event,
209
+ document,
210
+ rows,
211
+ readPdf,
212
+ brand,
213
+ registration,
214
+ };
215
+ }
216
+
217
+ it("delivers one PDF after replaying the invoice event twice", async () => {
218
+ const f = fixture();
219
+ const event = f.event(f.document(41));
220
+ await f.outbox.enqueue(event);
221
+ await f.outbox.enqueue(event);
222
+ expect(f.readPdf).not.toHaveBeenCalled();
223
+ expect((await f.worker.processNextDueDelivery()).outcome).toBe("sent");
224
+ expect((await f.worker.processNextDueDelivery()).outcome).toBe("idle");
225
+ expect(smtp.sendMail).toHaveBeenCalledTimes(1);
226
+ expect(smtp.sendMail).toHaveBeenCalledWith(
227
+ expect.objectContaining({
228
+ to: "buyer@example.invalid",
229
+ attachments: [
230
+ {
231
+ filename: "invoice-20260141.pdf",
232
+ contentType: "application/pdf",
233
+ content: Buffer.from("%PDF-synthetic"),
234
+ },
235
+ ],
236
+ }),
237
+ );
238
+ });
239
+
240
+ it("delivers both the credit note and replacement, without resending on replay", async () => {
241
+ const f = fixture();
242
+ const event = f.event(f.document(43), f.document(42, true));
243
+ await f.outbox.enqueue(event);
244
+ await f.worker.processNextDueDelivery();
245
+ await f.worker.processNextDueDelivery();
246
+ await f.outbox.enqueue(event);
247
+ expect((await f.worker.processNextDueDelivery()).outcome).toBe("idle");
248
+ expect(
249
+ smtp.sendMail.mock.calls.map(
250
+ ([message]) => (message as { subject: string }).subject,
251
+ ),
252
+ ).toEqual(["Dobropis 20260142", "Faktúra 20260143"]);
253
+ });
254
+
255
+ it("retries a PDF storage failure through the same outbox without issuing a document", async () => {
256
+ const f = fixture();
257
+ f.readPdf.mockImplementationOnce(() => {
258
+ throw new Error("private path and billing details");
259
+ });
260
+ await f.outbox.enqueue(f.event(f.document(41)));
261
+ const now = new Date();
262
+ expect((await f.worker.processNextDueDelivery(now)).outcome).toBe("idle");
263
+ expect(smtp.sendMail).not.toHaveBeenCalled();
264
+ expect(f.rows[0]?.lastErrorCode).toBe("DELIVERY_FAILED");
265
+ expect(
266
+ (await f.worker.processNextDueDelivery(new Date(now.getTime() + 60_000)))
267
+ .outcome,
268
+ ).toBe("sent");
269
+ expect(smtp.sendMail).toHaveBeenCalledTimes(1);
270
+ });
271
+
272
+ it("recovers exhausted delivery without resending a sent invoice", async () => {
273
+ const f = fixture();
274
+ const sent = f.event(f.document(41));
275
+ await f.outbox.enqueue(sent);
276
+ await f.worker.processNextDueDelivery();
277
+ await f.outbox.recover(sent);
278
+ expect((await f.worker.processNextDueDelivery()).outcome).toBe("idle");
279
+ const failed = f.event(f.document(42, true));
280
+ await f.outbox.enqueue(failed);
281
+ smtp.sendMail.mockRejectedValue(new Error("synthetic SMTP failure"));
282
+ const now = Date.now();
283
+ for (let attempt = 0; attempt < 5; attempt++)
284
+ await f.worker.processNextDueDelivery(
285
+ new Date(now + attempt * 3 * 60 * 60_000),
286
+ );
287
+ expect(f.rows[1]?.status).toBe("failed");
288
+ smtp.sendMail.mockResolvedValue();
289
+ await f.outbox.recover(failed);
290
+ expect((await f.worker.processNextDueDelivery()).outcome).toBe("sent");
291
+ expect(f.rows).toHaveLength(2);
292
+ });
293
+
294
+ it("intentionally redelivers one existing invoice once per operator request", async () => {
295
+ const f = fixture();
296
+ const event = f.event(f.document(41));
297
+ await f.outbox.enqueue(event);
298
+ await f.worker.processNextDueDelivery();
299
+
300
+ await f.outbox.redeliver(event, "01JARSHOPTESTREQUEST000001");
301
+ await f.outbox.redeliver(event, "01JARSHOPTESTREQUEST000001");
302
+
303
+ expect((await f.worker.processNextDueDelivery()).outcome).toBe("sent");
304
+ expect((await f.worker.processNextDueDelivery()).outcome).toBe("idle");
305
+ expect(f.rows).toHaveLength(2);
306
+ expect(f.rows[1]?.eventKey).toBe(
307
+ "invoice:41:redelivery:01JARSHOPTESTREQUEST000001",
308
+ );
309
+ expect(smtp.sendMail).toHaveBeenCalledTimes(2);
310
+ });
311
+
312
+ it("preserves the customer's checkout language for intentional redelivery", async () => {
313
+ const f = fixture(LanguageCode.en);
314
+ f.rows.push({
315
+ ...createPendingOrderEmailDelivery({
316
+ orderId: 12,
317
+ checkoutAttemptId: "checkout-12",
318
+ snapshot: {
319
+ recipient: "buyer@example.invalid",
320
+ languageCode: "sk",
321
+ orderCode: "ORDER-12",
322
+ currencyCode: "EUR",
323
+ totalWithTax: 1000,
324
+ shippingWithTax: 0,
325
+ paymentMethod: "cod",
326
+ shippingMethod: "pickup",
327
+ shippingAddress: {
328
+ fullName: "Buyer",
329
+ streetLine1: "Test 1",
330
+ streetLine2: "",
331
+ postalCode: "01001",
332
+ city: "Žilina",
333
+ countryCode: "SK",
334
+ },
335
+ confirmationToken: "confirmation-token",
336
+ lines: [],
337
+ },
338
+ }),
339
+ id: 1,
340
+ status: "sent",
341
+ sentAt: new Date(),
342
+ } as JarShopOrderEmailDelivery);
343
+ const event = f.event(f.document(41));
344
+
345
+ await f.outbox.redeliver(event, "01JARSHOPTESTREQUEST000002");
346
+ await f.worker.processNextDueDelivery();
347
+
348
+ expect(smtp.sendMail).toHaveBeenCalledWith(
349
+ expect.objectContaining({ subject: "Faktúra 20260141" }),
350
+ );
351
+ });
352
+
353
+ it("automatically delivers an issued invoice whose event was lost before enqueue", async () => {
354
+ const f = fixture();
355
+ f.document(41);
356
+ expect(f.rows).toHaveLength(0);
357
+ await f.outbox.reconcile();
358
+ expect((await f.worker.processNextDueDelivery()).outcome).toBe("sent");
359
+ await f.outbox.reconcile();
360
+ expect((await f.worker.processNextDueDelivery()).outcome).toBe("idle");
361
+ expect(smtp.sendMail).toHaveBeenCalledTimes(1);
362
+ });
363
+
364
+ it("defers a leftover invoice delivery without spending attempts while invoicing is off", async () => {
365
+ const f = fixture(LanguageCode.sk, { invoicingRegistered: false });
366
+ // Queued while invoicing was still registered.
367
+ await f.outbox.enqueue(f.event(f.document(41)));
368
+ const now = new Date(Date.now() + 1_000);
369
+ expect(await f.worker.processNextDueDelivery(now)).toMatchObject({
370
+ outcome: "deferred",
371
+ errorCode: "INVOICING_DISABLED",
372
+ });
373
+ expect(f.readPdf).not.toHaveBeenCalled();
374
+ expect(smtp.sendMail).not.toHaveBeenCalled();
375
+ expect(f.rows[0]).toMatchObject({
376
+ kind: "invoice-issued",
377
+ status: "pending",
378
+ attemptCount: 0,
379
+ lastErrorCode: "INVOICING_DISABLED",
380
+ nextAttemptAt: new Date(now.getTime() + invoicingDisabledDeferralMs),
381
+ });
382
+
383
+ // Many deferrals later the row has still spent no attempt and never failed.
384
+ let later = now;
385
+ for (let pass = 0; pass < 10; pass += 1) {
386
+ later = new Date(later.getTime() + invoicingDisabledDeferralMs);
387
+ expect((await f.worker.processNextDueDelivery(later)).outcome).toBe(
388
+ "deferred",
389
+ );
390
+ }
391
+ expect(f.rows[0]).toMatchObject({ status: "pending", attemptCount: 0 });
392
+
393
+ // Not due before the deferral ends; sent on the first pass once invoicing
394
+ // is registered again.
395
+ f.registration.invoicingRegistered = true;
396
+ expect((await f.worker.processNextDueDelivery(later)).outcome).toBe("idle");
397
+ const reEnabled = new Date(later.getTime() + invoicingDisabledDeferralMs);
398
+ expect((await f.worker.processNextDueDelivery(reEnabled)).outcome).toBe(
399
+ "sent",
400
+ );
401
+ expect(smtp.sendMail).toHaveBeenCalledWith(
402
+ expect.objectContaining({ subject: "Faktúra 20260141" }),
403
+ );
404
+ expect(f.rows[0]).toMatchObject({ status: "sent", attemptCount: 1 });
405
+ });
406
+
407
+ it("skips invoice reconciliation when the invoicing Feature is not registered", async () => {
408
+ const f = fixture(LanguageCode.sk, { invoicingRegistered: false });
409
+ const logError = vi.spyOn(Logger, "error");
410
+ const injector = {
411
+ get: (token: unknown) => {
412
+ if (token === JarShopOrderEmailWorker) return f.worker;
413
+ throw new Error("Nest could not find the element");
414
+ },
415
+ };
416
+ await expect(
417
+ jarShopOrderEmailWorkerTask.options.execute({
418
+ injector: injector as never,
419
+ scheduledContext: {} as never,
420
+ params: {},
421
+ }),
422
+ ).resolves.toEqual({ outcome: "idle" });
423
+ // No reconciliation attempt, so no reconciliation failure either.
424
+ expect(logError).not.toHaveBeenCalled();
425
+ logError.mockRestore();
426
+ });
@@ -0,0 +1,107 @@
1
+ import { expect, it, vi } from "vitest";
2
+ import {
3
+ createSmtpOrderEmailTransport,
4
+ renderInvoiceEmail,
5
+ } from "./order-email-delivery-core.js";
6
+ import {
7
+ createPendingInvoiceEmailDelivery,
8
+ decryptOrderEmailOutboxPayload,
9
+ } from "./order-email-outbox.js";
10
+
11
+ it.each([
12
+ ["sk", false, "Faktúra"],
13
+ ["en", false, "Invoice"],
14
+ ["sk", true, "Dobropis"],
15
+ ["en", true, "Credit note"],
16
+ ])(
17
+ "renders %s credit=%s as an attachment message",
18
+ (languageCode, credit, title) => {
19
+ const email = renderInvoiceEmail({
20
+ recipient: "buyer@example.invalid",
21
+ languageCode: String(languageCode),
22
+ document: {
23
+ invoiceNumber: 20260144,
24
+ isCreditInvoice: Boolean(credit),
25
+ orderCode: "ORDER-12",
26
+ filename: "invoice.pdf",
27
+ contentType: "application/pdf",
28
+ content: Buffer.from("%PDF"),
29
+ },
30
+ brandConfiguration: {
31
+ brandName: "Shop",
32
+ logoUrl: null,
33
+ primaryColor: "#123456",
34
+ websiteUrl: "https://example.invalid",
35
+ supportEmail: "support@example.invalid",
36
+ companyName: "Shop",
37
+ companyAddress: "Test 1",
38
+ },
39
+ });
40
+ expect(email.subject).toBe(`${title} 20260144`);
41
+ expect(email.attachments?.[0]?.content.toString()).toBe("%PDF");
42
+ expect(email.html).not.toContain("?email=");
43
+ },
44
+ );
45
+
46
+ it("stores only invoice identity in the encrypted outbox with a stable replay key", () => {
47
+ const snapshot = {
48
+ invoiceId: "41",
49
+ channelId: "2",
50
+ recipient: "customer@example.invalid",
51
+ languageCode: "sk",
52
+ };
53
+ const encodedKey = Buffer.alloc(32, 1).toString("base64");
54
+ const first = createPendingInvoiceEmailDelivery({
55
+ orderId: 12,
56
+ snapshot,
57
+ encodedKey,
58
+ });
59
+ const replay = createPendingInvoiceEmailDelivery({
60
+ orderId: 12,
61
+ snapshot,
62
+ encodedKey,
63
+ });
64
+ expect(first.eventKey).toBe("invoice:41:issued");
65
+ expect(replay.eventKey).toBe(first.eventKey);
66
+ expect(
67
+ decryptOrderEmailOutboxPayload(first.payloadCiphertext, encodedKey),
68
+ ).toEqual({ kind: "invoice-issued", snapshot });
69
+ expect(JSON.stringify(first)).not.toContain(snapshot.recipient);
70
+ });
71
+
72
+ it("passes the invoice PDF attachment to the existing SMTP transport", async () => {
73
+ const send = vi.fn(async () => {});
74
+ const transport = createSmtpOrderEmailTransport(
75
+ {
76
+ kind: "smtp",
77
+ host: "smtp.example.invalid",
78
+ port: 587,
79
+ secure: false,
80
+ from: "shop@example.invalid",
81
+ username: "test",
82
+ password: "test",
83
+ },
84
+ send,
85
+ );
86
+ const attachment = {
87
+ filename: "invoice-20260144.pdf",
88
+ contentType: "application/pdf",
89
+ content: Buffer.from("%PDF-synthetic"),
90
+ };
91
+ await transport.deliver({
92
+ deliveryId: 1,
93
+ email: {
94
+ recipient: "customer@example.invalid",
95
+ subject: "Faktúra",
96
+ text: "V prílohe",
97
+ html: "<p>V prílohe</p>",
98
+ attachments: [attachment],
99
+ },
100
+ });
101
+ expect(send).toHaveBeenCalledWith(
102
+ expect.objectContaining({
103
+ to: "customer@example.invalid",
104
+ attachments: [attachment],
105
+ }),
106
+ );
107
+ });