@jarwizz/create-jarshop 0.1.9 → 0.4.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 (120) 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 +28 -0
  9. package/dist/presets.js +105 -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 +37 -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 +365 -0
  28. package/dist/template/src/jarshop-config.ts +462 -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/migrations/1788100000000-jarshop-guest-order-session.ts +27 -0
  32. package/dist/template/src/operation-codes.ts +34 -0
  33. package/dist/template/src/packeta-config.test.ts +95 -0
  34. package/dist/template/src/packeta-countries.test.ts +161 -0
  35. package/dist/template/src/packeta-countries.ts +120 -0
  36. package/dist/template/src/packeta-validation.test.ts +35 -0
  37. package/dist/template/src/packeta-validation.ts +52 -0
  38. package/dist/template/src/payment-return-url.test.ts +57 -0
  39. package/dist/template/src/payment-return-url.ts +34 -0
  40. package/dist/template/src/plugins/jarshop-checkout/confirmation-view.test.ts +79 -0
  41. package/dist/template/src/plugins/jarshop-checkout/confirmation.ts +51 -0
  42. package/dist/template/src/plugins/jarshop-checkout/dashboard/index.tsx +1 -0
  43. package/dist/template/src/plugins/jarshop-checkout/index.ts +4 -0
  44. package/dist/template/src/plugins/jarshop-checkout/invoice-delivery.plugin.ts +79 -0
  45. package/dist/template/src/plugins/jarshop-checkout/invoice-email-events.ts +35 -0
  46. package/dist/template/src/plugins/jarshop-checkout/invoice-email-lifecycle.ts +235 -0
  47. package/dist/template/src/plugins/jarshop-checkout/invoice-email-worker.test.ts +426 -0
  48. package/dist/template/src/plugins/jarshop-checkout/invoice-email.test.ts +107 -0
  49. package/dist/template/src/plugins/jarshop-checkout/jarshop-checkout.plugin.ts +167 -58
  50. package/dist/template/src/plugins/jarshop-checkout/market-active-order-core.ts +108 -0
  51. package/dist/template/src/plugins/jarshop-checkout/market-active-order.test.ts +205 -0
  52. package/dist/template/src/plugins/jarshop-checkout/market-active-order.ts +186 -0
  53. package/dist/template/src/plugins/jarshop-checkout/market-channels.test.ts +58 -0
  54. package/dist/template/src/plugins/jarshop-checkout/market-channels.ts +87 -0
  55. package/dist/template/src/plugins/jarshop-checkout/operation-code-check.ts +36 -0
  56. package/dist/template/src/plugins/jarshop-checkout/order-email-configuration.entity.ts +1 -1
  57. package/dist/template/src/plugins/jarshop-checkout/order-email-configuration.ts +1 -0
  58. package/dist/template/src/plugins/jarshop-checkout/order-email-delivery-core.ts +94 -1
  59. package/dist/template/src/plugins/jarshop-checkout/order-email-delivery.entity.ts +1 -0
  60. package/dist/template/src/plugins/jarshop-checkout/order-email-outbox.ts +83 -1
  61. package/dist/template/src/plugins/jarshop-checkout/order-email-worker.ts +136 -1
  62. package/dist/template/src/plugins/jarshop-checkout/shipping-tax.test.ts +109 -0
  63. package/dist/template/src/plugins/jarshop-checkout/shipping.test.ts +156 -0
  64. package/dist/template/src/plugins/jarshop-checkout/shipping.ts +75 -11
  65. package/dist/template/src/seed.ts +473 -185
  66. package/dist/template/src/vendure-config.ts +258 -113
  67. package/dist/template/storefront/README.md +7 -0
  68. package/dist/template/storefront/app/[locale]/[slug]/page.tsx +3 -2
  69. package/dist/template/storefront/app/[locale]/account/login/page.tsx +3 -2
  70. package/dist/template/storefront/app/[locale]/account/page.tsx +10 -4
  71. package/dist/template/storefront/app/[locale]/account/password-reset/callback/route.ts +4 -2
  72. package/dist/template/storefront/app/[locale]/account/password-reset/complete/page.tsx +3 -2
  73. package/dist/template/storefront/app/[locale]/account/password-reset/page.tsx +3 -2
  74. package/dist/template/storefront/app/[locale]/account/register/page.tsx +3 -2
  75. package/dist/template/storefront/app/[locale]/account/verify/complete/route.ts +4 -2
  76. package/dist/template/storefront/app/[locale]/account/verify/page.tsx +3 -2
  77. package/dist/template/storefront/app/[locale]/cart/page.tsx +3 -2
  78. package/dist/template/storefront/app/[locale]/checkout/actions.ts +43 -0
  79. package/dist/template/storefront/app/[locale]/checkout/checkout-form.tsx +188 -36
  80. package/dist/template/storefront/app/[locale]/checkout/confirmation/route.ts +2 -2
  81. package/dist/template/storefront/app/[locale]/checkout/packeta-chooser.tsx +96 -0
  82. package/dist/template/storefront/app/[locale]/checkout/page.tsx +60 -2
  83. package/dist/template/storefront/app/[locale]/checkout/payment-return/actions.ts +55 -0
  84. package/dist/template/storefront/app/[locale]/checkout/payment-return/page.tsx +32 -0
  85. package/dist/template/storefront/app/[locale]/checkout/payment-return/payment-return.tsx +84 -0
  86. package/dist/template/storefront/app/[locale]/checkout/success/page.tsx +32 -2
  87. package/dist/template/storefront/app/[locale]/layout.tsx +3 -2
  88. package/dist/template/storefront/app/[locale]/page.tsx +3 -2
  89. package/dist/template/storefront/app/globals.css +16 -0
  90. package/dist/template/storefront/app/layout.tsx +6 -2
  91. package/dist/template/storefront/lib/cart.ts +2 -4
  92. package/dist/template/storefront/lib/checkout-contract.test.ts +18 -1
  93. package/dist/template/storefront/lib/checkout-contract.ts +8 -0
  94. package/dist/template/storefront/lib/checkout-countries.test.ts +61 -0
  95. package/dist/template/storefront/lib/checkout-countries.ts +67 -0
  96. package/dist/template/storefront/lib/checkout.ts +22 -11
  97. package/dist/template/storefront/lib/commerce.ts +262 -2
  98. package/dist/template/storefront/lib/confirmation.test.ts +116 -0
  99. package/dist/template/storefront/lib/confirmation.ts +13 -7
  100. package/dist/template/storefront/lib/i18n.test.ts +32 -12
  101. package/dist/template/storefront/lib/i18n.ts +29 -8
  102. package/dist/template/storefront/lib/market-config.ts +40 -0
  103. package/dist/template/storefront/lib/market-routing.test.ts +107 -0
  104. package/dist/template/storefront/lib/market-routing.ts +57 -0
  105. package/dist/template/storefront/lib/market.ts +51 -0
  106. package/dist/template/storefront/lib/packeta-selection.test.ts +141 -0
  107. package/dist/template/storefront/lib/packeta-selection.ts +98 -0
  108. package/dist/template/storefront/lib/payment-return-actions.test.ts +61 -0
  109. package/dist/template/storefront/lib/payment-return-page.test.ts +30 -0
  110. package/dist/template/storefront/lib/payment-return-polling.test.ts +37 -0
  111. package/dist/template/storefront/lib/payment-return-polling.ts +58 -0
  112. package/dist/template/storefront/messages/en.json +13 -1
  113. package/dist/template/storefront/messages/sk.json +13 -1
  114. package/dist/template/storefront/package.json +2 -1
  115. package/dist/template/storefront/proxy.ts +35 -0
  116. package/dist/template/turbo.json +5 -1
  117. package/dist/template-manifest.json +1 -1
  118. package/dist/template.js +1 -0
  119. package/dist/template.js.map +1 -1
  120. package/package.json +1 -1
@@ -9,6 +9,7 @@ import type {
9
9
  FulfillmentLifecycleEmailKind,
10
10
  FulfillmentLifecycleEmailSnapshot,
11
11
  OrderCancellationEmailSnapshot,
12
+ OrderEmailShippingAddressSnapshot,
12
13
  } from "./order-email-outbox.js";
13
14
 
14
15
  const fileTransport = "file";
@@ -22,6 +23,11 @@ export type OrderConfirmationEmail = {
22
23
  subject: string;
23
24
  text: string;
24
25
  html: string;
26
+ attachments?: Array<{
27
+ filename: string;
28
+ contentType: string;
29
+ content: Buffer;
30
+ }>;
25
31
  };
26
32
 
27
33
  export type OrderEmailTransport = {
@@ -60,6 +66,7 @@ export type OrderConfirmationEmailInput = {
60
66
  shippingWithTax: number;
61
67
  paymentMethod: string;
62
68
  shippingMethod: string;
69
+ shippingAddress?: OrderEmailShippingAddressSnapshot;
63
70
  confirmationUrl: string;
64
71
  lines: ReadonlyArray<{
65
72
  name: string;
@@ -207,6 +214,7 @@ export function createSmtpOrderEmailTransport(
207
214
  subject: string;
208
215
  text: string;
209
216
  html: string;
217
+ attachments?: OrderConfirmationEmail["attachments"];
210
218
  }) => Promise<unknown>,
211
219
  ): OrderEmailTransport {
212
220
  return {
@@ -218,6 +226,7 @@ export function createSmtpOrderEmailTransport(
218
226
  subject: email.subject,
219
227
  text: email.text,
220
228
  html: email.html,
229
+ ...(email.attachments ? { attachments: email.attachments } : {}),
221
230
  });
222
231
  },
223
232
  };
@@ -237,6 +246,7 @@ export function renderOrderConfirmationEmail(
237
246
  (line) => `- ${line.quantity}× ${line.name}: ${money(line.totalWithTax)}`,
238
247
  );
239
248
  const brand = input.brandConfiguration ?? defaultBrandConfiguration;
249
+ const shippingAddressLines = toShippingAddressLines(input.shippingAddress);
240
250
 
241
251
  const text = [
242
252
  `${copy.greeting} #${input.orderCode}.`,
@@ -245,6 +255,9 @@ export function renderOrderConfirmationEmail(
245
255
  ...lines,
246
256
  "",
247
257
  `${copy.shipping}: ${input.shippingMethod || copy.notAvailable} (${money(input.shippingWithTax)})`,
258
+ ...(shippingAddressLines.length > 0
259
+ ? [`${copy.shippingAddress}:`, ...shippingAddressLines]
260
+ : []),
248
261
  `${copy.payment}: ${input.paymentMethod || copy.notAvailable}`,
249
262
  `${copy.total}: ${money(input.totalWithTax)}`,
250
263
  "",
@@ -265,6 +278,9 @@ export function renderOrderConfirmationEmail(
265
278
  currencyCode: input.currencyCode,
266
279
  details: [
267
280
  [copy.shipping, input.shippingMethod || copy.notAvailable],
281
+ ...(shippingAddressLines.length > 0
282
+ ? ([[copy.shippingAddress, shippingAddressLines.join(", ")]] as const)
283
+ : []),
268
284
  [copy.payment, input.paymentMethod || copy.notAvailable],
269
285
  [copy.total, money(input.totalWithTax)],
270
286
  ],
@@ -337,6 +353,58 @@ export function renderOrderLifecycleEmail(
337
353
  };
338
354
  }
339
355
 
356
+ export function renderInvoiceEmail(input: {
357
+ recipient: string;
358
+ languageCode: string;
359
+ document: {
360
+ invoiceNumber: number;
361
+ isCreditInvoice: boolean;
362
+ orderCode: string;
363
+ filename: string;
364
+ contentType: string;
365
+ content: Buffer;
366
+ };
367
+ brandConfiguration: Parameters<typeof renderBrandedEmailHtml>[0]["brand"];
368
+ }): OrderConfirmationEmail {
369
+ const languageCode = toOrderEmailLanguageCode(input.languageCode);
370
+ const { document } = input;
371
+ const title =
372
+ languageCode === "sk"
373
+ ? document.isCreditInvoice
374
+ ? "Dobropis"
375
+ : "Faktúra"
376
+ : document.isCreditInvoice
377
+ ? "Credit note"
378
+ : "Invoice";
379
+ const intro =
380
+ languageCode === "sk"
381
+ ? `V prílohe vám posielame ${document.isCreditInvoice ? "dobropis" : "faktúru"} k objednávke #${document.orderCode}.`
382
+ : `Please find the ${document.isCreditInvoice ? "credit note" : "invoice"} for order #${document.orderCode} attached.`;
383
+ return {
384
+ recipient: input.recipient,
385
+ subject: `${title} ${document.invoiceNumber}`,
386
+ text: [intro, "", ...renderTextBrandFooter(input.brandConfiguration)].join(
387
+ "\n",
388
+ ),
389
+ html: renderBrandedEmailHtml({
390
+ brand: input.brandConfiguration,
391
+ languageCode,
392
+ heading: `${title} ${document.invoiceNumber}`,
393
+ intro,
394
+ lines: [],
395
+ currencyCode: "EUR",
396
+ details: [],
397
+ }),
398
+ attachments: [
399
+ {
400
+ filename: document.filename,
401
+ contentType: document.contentType,
402
+ content: document.content,
403
+ },
404
+ ],
405
+ };
406
+ }
407
+
340
408
  export async function writeSanitizedFileTransport(input: {
341
409
  deliveryId: number;
342
410
  email: OrderConfirmationEmail;
@@ -382,9 +450,12 @@ export function sanitizeFileTransportEmail(
382
450
  export function createOrderConfirmationUrl(
383
451
  languageCode: OrderEmailLanguageCode,
384
452
  token: string,
453
+ storefrontOrigin?: URL,
385
454
  ): string {
386
455
  const storefrontUrl =
387
- process.env.JARSHOP_STOREFRONT_URL ?? defaultStorefrontUrl;
456
+ storefrontOrigin ??
457
+ process.env.JARSHOP_STOREFRONT_URL ??
458
+ defaultStorefrontUrl;
388
459
  return new URL(
389
460
  `/${languageCode}/checkout/confirmation?token=${encodeURIComponent(token)}`,
390
461
  storefrontUrl,
@@ -430,6 +501,7 @@ const emailCopy = {
430
501
  greeting: "Ďakujeme za objednávku",
431
502
  items: "Položky objednávky:",
432
503
  shipping: "Doprava",
504
+ shippingAddress: "Doručovacia adresa",
433
505
  payment: "Platba",
434
506
  total: "Celkom s DPH",
435
507
  confirmation: "Potvrdenie objednávky",
@@ -440,6 +512,7 @@ const emailCopy = {
440
512
  greeting: "Thank you for your order",
441
513
  items: "Order items:",
442
514
  shipping: "Shipping",
515
+ shippingAddress: "Shipping address",
443
516
  payment: "Payment",
444
517
  total: "Total including tax",
445
518
  confirmation: "Order confirmation",
@@ -447,6 +520,26 @@ const emailCopy = {
447
520
  },
448
521
  } as const;
449
522
 
523
+ function toShippingAddressLines(
524
+ address: OrderEmailShippingAddressSnapshot | undefined,
525
+ ): string[] {
526
+ if (!address) return [];
527
+ const streetLine2 = address.streetLine2.trim();
528
+ const locality = [address.postalCode, address.city]
529
+ .map((value) => value.trim())
530
+ .filter(Boolean)
531
+ .join(" ");
532
+ return [
533
+ address.fullName,
534
+ address.streetLine1,
535
+ streetLine2,
536
+ locality === streetLine2 ? "" : locality,
537
+ address.countryCode,
538
+ ]
539
+ .map((value) => value.trim())
540
+ .filter(Boolean);
541
+ }
542
+
450
543
  const lifecycleEmailCopy = {
451
544
  sk: {
452
545
  "pickup-ready": {
@@ -12,6 +12,7 @@ export type OrderEmailDeliveryStatus =
12
12
  "pending" | "processing" | "sent" | "failed";
13
13
 
14
14
  export type OrderEmailDeliveryKind =
15
+ | "invoice-issued"
15
16
  | "order-confirmation"
16
17
  | "pickup-ready"
17
18
  | "pickup-picked-up"
@@ -13,6 +13,15 @@ export type OrderEmailLineSnapshot = {
13
13
  totalWithTax: number;
14
14
  };
15
15
 
16
+ export type OrderEmailShippingAddressSnapshot = {
17
+ fullName: string;
18
+ streetLine1: string;
19
+ streetLine2: string;
20
+ postalCode: string;
21
+ city: string;
22
+ countryCode: string;
23
+ };
24
+
16
25
  export type OrderConfirmationEmailSnapshot = {
17
26
  recipient: string;
18
27
  languageCode: string;
@@ -22,10 +31,15 @@ export type OrderConfirmationEmailSnapshot = {
22
31
  shippingWithTax: number;
23
32
  paymentMethod: string;
24
33
  shippingMethod: string;
34
+ shippingAddress?: OrderEmailShippingAddressSnapshot;
25
35
  confirmationToken: string;
26
36
  lines: readonly OrderEmailLineSnapshot[];
27
37
  };
28
38
 
39
+ type NewOrderConfirmationEmailSnapshot = OrderConfirmationEmailSnapshot & {
40
+ shippingAddress: OrderEmailShippingAddressSnapshot;
41
+ };
42
+
29
43
  export type FulfillmentLifecycleEmailKind =
30
44
  | "pickup-ready"
31
45
  | "pickup-picked-up"
@@ -57,7 +71,15 @@ export type OrderCancellationEmailSnapshot = {
57
71
  lines: readonly OrderEmailLineSnapshot[];
58
72
  };
59
73
 
74
+ export type InvoiceEmailSnapshot = {
75
+ invoiceId: string;
76
+ channelId: string;
77
+ recipient: string;
78
+ languageCode: string;
79
+ };
80
+
60
81
  export type OrderEmailOutboxPayload =
82
+ | { kind: "invoice-issued"; snapshot: InvoiceEmailSnapshot }
61
83
  | LegacyOrderConfirmationOutboxPayload
62
84
  | {
63
85
  kind: "order-confirmation";
@@ -79,7 +101,7 @@ export function assertOrderEmailOutboxEncryptionConfiguration(): void {
79
101
  export function createPendingOrderEmailDelivery(input: {
80
102
  orderId: number;
81
103
  checkoutAttemptId: string;
82
- snapshot: OrderConfirmationEmailSnapshot;
104
+ snapshot: NewOrderConfirmationEmailSnapshot;
83
105
  now?: Date;
84
106
  encodedKey?: string;
85
107
  }) {
@@ -136,6 +158,36 @@ export function createPendingCancellationEmailDelivery(input: {
136
158
  });
137
159
  }
138
160
 
161
+ export function createPendingInvoiceEmailDelivery(input: {
162
+ orderId: number;
163
+ snapshot: InvoiceEmailSnapshot;
164
+ now?: Date;
165
+ encodedKey?: string;
166
+ }) {
167
+ return createPendingLifecycleEmailDelivery({
168
+ ...input,
169
+ kind: "invoice-issued",
170
+ eventKey: `invoice:${requireEventSourceId(input.snapshot.invoiceId)}:issued`,
171
+ });
172
+ }
173
+
174
+ export function createPendingInvoiceEmailRedelivery(input: {
175
+ orderId: number;
176
+ snapshot: InvoiceEmailSnapshot;
177
+ requestId: string;
178
+ now?: Date;
179
+ encodedKey?: string;
180
+ }) {
181
+ if (!/^[A-Za-z0-9_-]{16,64}$/.test(input.requestId)) {
182
+ throw new Error("invoice redelivery request id is invalid");
183
+ }
184
+ return createPendingLifecycleEmailDelivery({
185
+ ...input,
186
+ kind: "invoice-issued",
187
+ eventKey: `invoice:${requireEventSourceId(input.snapshot.invoiceId)}:redelivery:${input.requestId}`,
188
+ });
189
+ }
190
+
139
191
  export function encryptOrderEmailOutboxPayload(
140
192
  payload: OrderEmailOutboxPayload,
141
193
  encodedKey = process.env.JARSHOP_ORDER_EMAIL_ENCRYPTION_KEY,
@@ -216,6 +268,17 @@ function parseOrderConfirmationSnapshotPayload(
216
268
  const payload = asRecord(value);
217
269
  const kind = requireString(payload, "kind");
218
270
  const snapshot = asRecord(payload.snapshot);
271
+ if (kind === "invoice-issued") {
272
+ return {
273
+ kind,
274
+ snapshot: {
275
+ invoiceId: requireEventSourceId(requireString(snapshot, "invoiceId")),
276
+ channelId: requireEventSourceId(requireString(snapshot, "channelId")),
277
+ recipient: requireString(snapshot, "recipient"),
278
+ languageCode: requireString(snapshot, "languageCode"),
279
+ },
280
+ };
281
+ }
219
282
  if (kind === "order-confirmation") {
220
283
  return {
221
284
  kind,
@@ -242,6 +305,10 @@ function parseOrderConfirmationSnapshot(
242
305
  ): OrderConfirmationEmailSnapshot {
243
306
  const lines = snapshot.lines;
244
307
  if (!Array.isArray(lines)) throw new Error("missing order email lines");
308
+ const shippingAddress =
309
+ snapshot.shippingAddress === undefined
310
+ ? undefined
311
+ : parseOrderEmailShippingAddress(snapshot.shippingAddress);
245
312
  return {
246
313
  recipient: requireString(snapshot, "recipient"),
247
314
  languageCode: requireString(snapshot, "languageCode"),
@@ -251,11 +318,26 @@ function parseOrderConfirmationSnapshot(
251
318
  shippingWithTax: requireInteger(snapshot, "shippingWithTax"),
252
319
  paymentMethod: requireString(snapshot, "paymentMethod", true),
253
320
  shippingMethod: requireString(snapshot, "shippingMethod", true),
321
+ ...(shippingAddress ? { shippingAddress } : {}),
254
322
  confirmationToken: requireString(snapshot, "confirmationToken"),
255
323
  lines: parseOrderEmailLines(lines),
256
324
  };
257
325
  }
258
326
 
327
+ function parseOrderEmailShippingAddress(
328
+ value: unknown,
329
+ ): OrderEmailShippingAddressSnapshot {
330
+ const address = asRecord(value);
331
+ return {
332
+ fullName: requireString(address, "fullName", true),
333
+ streetLine1: requireString(address, "streetLine1", true),
334
+ streetLine2: requireString(address, "streetLine2", true),
335
+ postalCode: requireString(address, "postalCode", true),
336
+ city: requireString(address, "city", true),
337
+ countryCode: requireString(address, "countryCode", true),
338
+ };
339
+ }
340
+
259
341
  function parseFulfillmentLifecycleSnapshot(
260
342
  snapshot: Record<string, unknown>,
261
343
  ): FulfillmentLifecycleEmailSnapshot {
@@ -1,6 +1,12 @@
1
1
  import { Inject, Injectable, OnApplicationBootstrap } from "@nestjs/common";
2
+ import { ModuleRef } from "@nestjs/core";
3
+ import { findJarShopInvoiceEmailOutbox } from "./invoice-email-lifecycle.js";
4
+ import { readJarShopInvoicePdf } from "@jarwizz/jarshop-invoicing/server";
2
5
  import {
3
6
  LanguageCode,
7
+ Logger,
8
+ Channel,
9
+ Injector,
4
10
  Order,
5
11
  OrderService,
6
12
  ProcessContext,
@@ -10,6 +16,10 @@ import {
10
16
  } from "@vendure/core";
11
17
  import { randomUUID } from "node:crypto";
12
18
  import { In } from "typeorm";
19
+ import {
20
+ marketForOrderChannels,
21
+ storefrontOriginForMarket,
22
+ } from "../../jarshop-config-loader.js";
13
23
  import { JarShopEmailBrandConfiguration } from "./order-email-configuration.entity.js";
14
24
  import { isLifecycleEmailEnabled } from "./order-email-configuration.js";
15
25
  import { JarShopOrderEmailDelivery } from "./order-email-delivery.entity.js";
@@ -21,6 +31,7 @@ import {
21
31
  registerUniqueScheduledTask,
22
32
  renderOrderConfirmationEmail,
23
33
  renderOrderLifecycleEmail,
34
+ renderInvoiceEmail,
24
35
  scheduleOrderEmailRetry,
25
36
  toOrderEmailLanguageCode,
26
37
  type OrderEmailTransport,
@@ -39,7 +50,15 @@ import {
39
50
  type DeliveryResult =
40
51
  | { outcome: "idle" }
41
52
  | { outcome: "sent"; deliveryId: number }
42
- | { outcome: "failed"; deliveryId: number; errorCode: string };
53
+ | { outcome: "failed"; deliveryId: number; errorCode: string }
54
+ | { outcome: "deferred"; deliveryId: number; errorCode: string };
55
+
56
+ /**
57
+ * How long an invoice email waits while invoicing is switched off. It is a
58
+ * deferral, not a failed attempt: the row keeps its attempt budget and is sent
59
+ * on the first pass after invoicing is registered again.
60
+ */
61
+ export const invoicingDisabledDeferralMs = 60 * 60 * 1_000;
43
62
 
44
63
  type ClaimedDelivery = {
45
64
  delivery: JarShopOrderEmailDelivery;
@@ -65,6 +84,8 @@ export class JarShopOrderEmailWorker implements OnApplicationBootstrap {
65
84
  private readonly requestContextService: RequestContextService,
66
85
  @Inject(ProcessContext)
67
86
  private readonly processContext: ProcessContext,
87
+ @Inject(ModuleRef)
88
+ private readonly moduleRef: ModuleRef,
68
89
  ) {}
69
90
 
70
91
  onApplicationBootstrap(): void {
@@ -86,12 +107,50 @@ export class JarShopOrderEmailWorker implements OnApplicationBootstrap {
86
107
  email = this.renderSnapshotOrderConfirmation(
87
108
  payload.snapshot,
88
109
  await this.getBrandConfiguration(delivery.delivery.orderId),
110
+ await this.getStorefrontOrigin(delivery.delivery.orderId),
89
111
  );
90
112
  } else if (isLegacyOrderConfirmationOutboxPayload(payload)) {
91
113
  email = await this.renderLegacyOrderConfirmation(
92
114
  delivery.delivery,
93
115
  payload,
94
116
  );
117
+ } else if (payload.kind === "invoice-issued") {
118
+ // A delivery queued before invoicing was switched off stays in the
119
+ // outbox and is deferred here without spending an attempt; its
120
+ // invoice and PDF are left untouched until invoicing is back.
121
+ if (!findJarShopInvoiceEmailOutbox(new Injector(this.moduleRef))) {
122
+ throw new OrderEmailWorkerError("INVOICING_DISABLED");
123
+ }
124
+ const brandConfiguration = await this.connection.rawConnection
125
+ .getRepository(JarShopEmailBrandConfiguration)
126
+ .findOne({
127
+ where: { channelId: Number(payload.snapshot.channelId) },
128
+ });
129
+ if (!isLifecycleEmailEnabled(brandConfiguration, "invoice-issued")) {
130
+ throw new OrderEmailWorkerError("EMAIL_KIND_NOT_ENABLED");
131
+ }
132
+ const channel = await this.connection.rawConnection
133
+ .getRepository(Channel)
134
+ .findOne({ where: { id: payload.snapshot.channelId } });
135
+ if (!channel) throw new OrderEmailWorkerError("ORDER_CHANNEL_MISSING");
136
+ const ctx = await this.requestContextService.create({
137
+ apiType: "admin",
138
+ channelOrToken: channel.token,
139
+ });
140
+ const document = await readJarShopInvoicePdf(
141
+ ctx,
142
+ new Injector(this.moduleRef),
143
+ {
144
+ invoiceId: payload.snapshot.invoiceId,
145
+ orderId: String(delivery.delivery.orderId),
146
+ recipient: payload.snapshot.recipient,
147
+ },
148
+ );
149
+ email = renderInvoiceEmail({
150
+ ...payload.snapshot,
151
+ document,
152
+ brandConfiguration,
153
+ });
95
154
  } else {
96
155
  const brandConfiguration = await this.getBrandConfiguration(
97
156
  delivery.delivery.orderId,
@@ -123,6 +182,20 @@ export class JarShopOrderEmailWorker implements OnApplicationBootstrap {
123
182
  return { outcome: "sent", deliveryId: delivery.delivery.id };
124
183
  } catch (error) {
125
184
  const errorCode = toOrderEmailWorkerErrorCode(error);
185
+ if (errorCode === "INVOICING_DISABLED") {
186
+ await this.markDeferred(
187
+ delivery.delivery.id,
188
+ delivery.leaseToken,
189
+ delivery.delivery.attemptCount - 1,
190
+ errorCode,
191
+ new Date(now.getTime() + invoicingDisabledDeferralMs),
192
+ );
193
+ return {
194
+ outcome: "deferred",
195
+ deliveryId: delivery.delivery.id,
196
+ errorCode,
197
+ };
198
+ }
126
199
  const outcome = await this.markFailure(
127
200
  delivery.delivery.id,
128
201
  delivery.leaseToken,
@@ -187,6 +260,7 @@ export class JarShopOrderEmailWorker implements OnApplicationBootstrap {
187
260
  private renderSnapshotOrderConfirmation(
188
261
  snapshot: OrderConfirmationEmailSnapshot,
189
262
  brandConfiguration: JarShopEmailBrandConfiguration | undefined,
263
+ storefrontOrigin: URL,
190
264
  ): OrderConfirmationEmail {
191
265
  return renderOrderConfirmationEmail({
192
266
  ...snapshot,
@@ -194,10 +268,24 @@ export class JarShopOrderEmailWorker implements OnApplicationBootstrap {
194
268
  confirmationUrl: createOrderConfirmationUrl(
195
269
  toOrderEmailLanguageCode(snapshot.languageCode),
196
270
  snapshot.confirmationToken,
271
+ storefrontOrigin,
197
272
  ),
198
273
  });
199
274
  }
200
275
 
276
+ /** The confirmation link opens on the storefront of the order's market. */
277
+ private async getStorefrontOrigin(orderId: number): Promise<URL> {
278
+ const sourceOrder = await this.connection.rawConnection
279
+ .getRepository(Order)
280
+ .findOne({ where: { id: orderId }, relations: ["channels"] });
281
+ if (!sourceOrder) throw new OrderEmailWorkerError("ORDER_NOT_FOUND");
282
+ return storefrontOriginForMarket(
283
+ marketForOrderChannels(
284
+ sourceOrder.channels.map((channel) => channel.token),
285
+ ),
286
+ );
287
+ }
288
+
201
289
  private async renderLegacyOrderConfirmation(
202
290
  delivery: JarShopOrderEmailDelivery,
203
291
  payload: LegacyOrderConfirmationOutboxPayload,
@@ -249,6 +337,11 @@ export class JarShopOrderEmailWorker implements OnApplicationBootstrap {
249
337
  confirmationUrl: createOrderConfirmationUrl(
250
338
  languageCode,
251
339
  payload.confirmationToken,
340
+ storefrontOriginForMarket(
341
+ marketForOrderChannels(
342
+ sourceOrder.channels.map((item) => item.token),
343
+ ),
344
+ ),
252
345
  ),
253
346
  lines: order.lines.map((line) => ({
254
347
  name: line.productVariant.name,
@@ -303,6 +396,37 @@ export class JarShopOrderEmailWorker implements OnApplicationBootstrap {
303
396
  }
304
397
  }
305
398
 
399
+ /**
400
+ * Returns a claimed delivery to `pending` without spending an attempt: the
401
+ * claim's increment is undone, so a deferral can never exhaust the budget.
402
+ */
403
+ private async markDeferred(
404
+ deliveryId: number,
405
+ leaseToken: string,
406
+ attemptCount: number,
407
+ errorCode: string,
408
+ nextAttemptAt: Date,
409
+ ): Promise<void> {
410
+ const result = await this.connection.rawConnection
411
+ .getRepository(JarShopOrderEmailDelivery)
412
+ .update(
413
+ { id: deliveryId, status: "processing", leaseToken },
414
+ {
415
+ status: "pending",
416
+ attemptCount: Math.max(0, attemptCount),
417
+ nextAttemptAt,
418
+ leaseToken: null,
419
+ leaseExpiresAt: null,
420
+ lastErrorCode: errorCode,
421
+ },
422
+ );
423
+ if (result.affected !== 1) {
424
+ throw new Error(
425
+ "order email delivery was no longer owned by this worker",
426
+ );
427
+ }
428
+ }
429
+
306
430
  private async markFailure(
307
431
  deliveryId: number,
308
432
  leaseToken: string,
@@ -340,6 +464,17 @@ export const jarShopOrderEmailWorkerTask = new ScheduledTask({
340
464
  schedule: (cron) => cron.every(1).minutes(),
341
465
  timeout: 30_000,
342
466
  execute: async ({ injector }) => {
467
+ try {
468
+ // Without the invoicing Feature there are no invoices to reconcile.
469
+ await findJarShopInvoiceEmailOutbox(injector)?.reconcile();
470
+ } catch {
471
+ // A later scheduler pass retries missing intents; other emails keep moving.
472
+ // Never propagate a delivery failure to invoice issuance.
473
+ Logger.error(
474
+ "INVOICE_EMAIL_RECONCILIATION_FAILED",
475
+ "JarShopInvoiceEmailOutbox",
476
+ );
477
+ }
343
478
  return injector.get(JarShopOrderEmailWorker).processNextDueDelivery();
344
479
  },
345
480
  });
@@ -0,0 +1,109 @@
1
+ import {
2
+ ConfigService,
3
+ TaxCategoryService,
4
+ TaxRateService,
5
+ ZoneService,
6
+ type Injector,
7
+ } from "@vendure/core";
8
+ import { createTariffShippingCalculator } from "@jarwizz/feature-adapter-kit/server";
9
+ import { describe, expect, it } from "vitest";
10
+
11
+ import { seededShippingRates } from "./shipping-rates.js";
12
+
13
+ /**
14
+ * Two market Channels, each with its own tax zone and its own TaxRate for the same
15
+ * TaxCategory, as the seed lays them out. Vendure's services are reduced to the answers
16
+ * the calculator asks for; the rates are the only thing that differs per market.
17
+ */
18
+ const rateByZone: Record<string, number> = { "sk-zone": 23, "cz-zone": 21 };
19
+
20
+ const injector = {
21
+ get: (token: unknown) =>
22
+ new Map<unknown, unknown>([
23
+ [
24
+ ConfigService,
25
+ {
26
+ taxOptions: {
27
+ taxZoneStrategy: {
28
+ determineTaxZone: (
29
+ _ctx: unknown,
30
+ _zones: unknown,
31
+ channel: never,
32
+ ) => (channel as { defaultTaxZone: unknown }).defaultTaxZone,
33
+ },
34
+ },
35
+ },
36
+ ],
37
+ [ZoneService, { getAllWithMembers: async () => [] }],
38
+ [
39
+ TaxCategoryService,
40
+ {
41
+ findAll: async () => ({
42
+ items: [{ name: "standard", isDefault: true }],
43
+ }),
44
+ },
45
+ ],
46
+ [
47
+ TaxRateService,
48
+ {
49
+ getApplicableTaxRate: async (
50
+ _ctx: unknown,
51
+ zone: { name: string },
52
+ ) => ({
53
+ value: rateByZone[zone.name],
54
+ }),
55
+ },
56
+ ],
57
+ ]).get(token),
58
+ } as unknown as Injector;
59
+
60
+ const marketCtx = (zone: string, pricesIncludeTax: boolean) =>
61
+ ({
62
+ channel: { pricesIncludeTax, defaultTaxZone: { id: zone, name: zone } },
63
+ }) as never;
64
+
65
+ const courierArgs = (includesTax: string) =>
66
+ [
67
+ { name: "rate", value: String(seededShippingRates.courier) },
68
+ { name: "includesTax", value: includesTax },
69
+ ] as never;
70
+
71
+ async function quote(
72
+ zone: string,
73
+ pricesIncludeTax: boolean,
74
+ includesTax: string,
75
+ ) {
76
+ const calculator = createTariffShippingCalculator();
77
+ await calculator.init(injector);
78
+ return calculator.calculate(
79
+ marketCtx(zone, pricesIncludeTax),
80
+ {} as never,
81
+ courierArgs(includesTax),
82
+ {} as never,
83
+ );
84
+ }
85
+
86
+ describe("starter shipping tax", () => {
87
+ it("applies each market zone's rate to the same courier method", async () => {
88
+ const [sk, cz] = await Promise.all([
89
+ quote("sk-zone", true, "auto"),
90
+ quote("cz-zone", true, "auto"),
91
+ ]);
92
+
93
+ expect(sk).toEqual({ price: 490, priceIncludesTax: true, taxRate: 23 });
94
+ expect(cz).toEqual({ price: 490, priceIncludesTax: true, taxRate: 21 });
95
+ });
96
+
97
+ it("charges different gross prices when the tariff is net of tax", async () => {
98
+ const [sk, cz] = await Promise.all([
99
+ quote("sk-zone", false, "auto"),
100
+ quote("cz-zone", false, "auto"),
101
+ ]);
102
+ const gross = (result: typeof sk) =>
103
+ Math.round(result!.price * (1 + result!.taxRate / 100));
104
+
105
+ expect(sk).toMatchObject({ priceIncludesTax: false, taxRate: 23 });
106
+ expect(gross(sk)).toBe(603);
107
+ expect(gross(cz)).toBe(593);
108
+ });
109
+ });