@jarwizz/create-jarshop 0.1.8 → 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 (116) 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 +5 -0
  17. package/dist/template/pnpm-lock.yaml +3291 -1809
  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/vite.config.mts +13 -2
  113. package/dist/template-manifest.json +1 -1
  114. package/dist/template.js +1 -0
  115. package/dist/template.js.map +1 -1
  116. package/package.json +1 -1
@@ -1,4 +1,8 @@
1
+ import "server-only";
2
+
3
+ import { cookies } from "next/headers";
1
4
  import { createCommerceClient } from "@jarwizz/commerce-sdk/server";
5
+ import type { PacketaWidgetConfiguration } from "@jarwizz/feature-packeta/storefront";
2
6
  import type {
3
7
  AccountSession,
4
8
  AccountSummary,
@@ -9,18 +13,33 @@ import type {
9
13
  CatalogPage,
10
14
  ChangePasswordInput,
11
15
  CommerceResult,
16
+ GuestOrderConfirmation,
17
+ GuestPaymentReconciliation,
12
18
  LoginInput,
19
+ PaymentMethod,
20
+ PaymentRedirectTarget,
13
21
  ProductDetail,
14
22
  ProductListOptions,
15
23
  ProductSummary,
16
24
  RegisterAccountInput,
17
25
  ResetPasswordInput,
18
26
  SessionStore,
27
+ ShippingMethod,
28
+ ShippingSelection,
29
+ ShippingSelectionInput,
19
30
  UpdateAccountProfileInput,
20
31
  UpdateAccountAddressInput,
21
32
  } from "@jarwizz/commerce-sdk/types";
33
+ import {
34
+ commerceSessionAuthorization,
35
+ createCommerceSessionStore,
36
+ persistCommerceSession,
37
+ } from "./commerce-session";
38
+ import { CONFIRMATION_COOKIE_NAME } from "./confirmation-cookie";
39
+ import { marketFetch } from "./market";
22
40
 
23
- export type CommerceLocale = "sk" | "en";
41
+ /** A language the request market serves; see `lib/market.ts`. */
42
+ export type CommerceLocale = string;
24
43
 
25
44
  function endpointFor(locale: CommerceLocale): string {
26
45
  const endpoint = new URL(
@@ -33,11 +52,252 @@ function endpointFor(locale: CommerceLocale): string {
33
52
  function client(locale: CommerceLocale, sessionStore?: SessionStore) {
34
53
  return createCommerceClient({
35
54
  endpoint: endpointFor(locale),
36
- channelToken: process.env.JARSHOP_CHANNEL_TOKEN,
55
+ fetch: marketFetch,
37
56
  sessionStore,
38
57
  });
39
58
  }
40
59
 
60
+ function confirmationClient(
61
+ locale: CommerceLocale,
62
+ store: Awaited<ReturnType<typeof cookies>>,
63
+ ) {
64
+ return createCommerceClient({
65
+ endpoint: endpointFor(locale),
66
+ fetch: marketFetch,
67
+ confirmationCookieName: CONFIRMATION_COOKIE_NAME,
68
+ confirmationContextStore: {
69
+ get: () => store.get(CONFIRMATION_COOKIE_NAME)?.value,
70
+ set: () => undefined,
71
+ },
72
+ });
73
+ }
74
+
75
+ async function setTemporaryShippingCountry(
76
+ locale: CommerceLocale,
77
+ countryCode: string,
78
+ unset = false,
79
+ ): Promise<void> {
80
+ const store = await cookies();
81
+ const endpoint = new URL(
82
+ process.env.JARSHOP_COMMERCE_ENDPOINT ?? "http://localhost:3000/shop-api",
83
+ );
84
+ endpoint.searchParams.set("languageCode", locale);
85
+ const response = await marketFetch(endpoint, {
86
+ method: "POST",
87
+ headers: {
88
+ "content-type": "application/json",
89
+ ...(commerceSessionAuthorization(store)
90
+ ? { authorization: commerceSessionAuthorization(store)! }
91
+ : {}),
92
+ },
93
+ body: JSON.stringify(
94
+ unset
95
+ ? { query: "mutation { unsetOrderShippingAddress { __typename } }" }
96
+ : {
97
+ query:
98
+ "mutation SetShippingCountry($input: CreateAddressInput!) { setOrderShippingAddress(input: $input) { __typename } }",
99
+ variables: {
100
+ input: { streetLine1: "JarShop checkout", countryCode },
101
+ },
102
+ },
103
+ ),
104
+ cache: "no-store",
105
+ });
106
+ persistCommerceSession(store, response.headers);
107
+ if (!response.ok) {
108
+ throw new Error(`Commerce API returned ${response.status}`);
109
+ }
110
+ const body = (await response.json()) as {
111
+ errors?: readonly { message?: string }[];
112
+ };
113
+ if (body.errors?.length) {
114
+ throw new Error(body.errors[0]?.message ?? "Shipping country failed");
115
+ }
116
+ }
117
+
118
+ /**
119
+ * The country of the active order's shipping address, or `null` before one is
120
+ * set. A Packeta pickup point or a courier address pins the order to it.
121
+ */
122
+ export async function getActiveOrderShippingCountry(
123
+ locale: CommerceLocale,
124
+ ): Promise<string | null> {
125
+ const store = await cookies();
126
+ const endpoint = new URL(
127
+ process.env.JARSHOP_COMMERCE_ENDPOINT ?? "http://localhost:3000/shop-api",
128
+ );
129
+ endpoint.searchParams.set("languageCode", locale);
130
+ const response = await marketFetch(endpoint, {
131
+ method: "POST",
132
+ headers: {
133
+ "content-type": "application/json",
134
+ ...(commerceSessionAuthorization(store)
135
+ ? { authorization: commerceSessionAuthorization(store)! }
136
+ : {}),
137
+ },
138
+ body: JSON.stringify({
139
+ query: "query { activeOrder { shippingAddress { countryCode } } }",
140
+ }),
141
+ cache: "no-store",
142
+ });
143
+ persistCommerceSession(store, response.headers);
144
+ if (!response.ok) {
145
+ throw new Error(`Commerce API returned ${response.status}`);
146
+ }
147
+ const body = (await response.json()) as {
148
+ data?: { activeOrder?: { shippingAddress?: { countryCode?: string } } };
149
+ errors?: readonly { message?: string }[];
150
+ };
151
+ if (body.errors?.length) {
152
+ throw new Error(body.errors[0]?.message ?? "Shipping country read failed");
153
+ }
154
+ return body.data?.activeOrder?.shippingAddress?.countryCode ?? null;
155
+ }
156
+
157
+ /**
158
+ * Releases the active order's destination when the shopper picks another
159
+ * country, so shipping methods and a pickup point can be chosen for it. The
160
+ * order's earlier Packeta point no longer applies to the new country anyway.
161
+ */
162
+ export async function releaseActiveOrderShippingAddress(
163
+ locale: CommerceLocale,
164
+ ): Promise<void> {
165
+ await setTemporaryShippingCountry(locale, "", true);
166
+ }
167
+
168
+ /**
169
+ * Vendure evaluates shipping adapters against the active order address. The
170
+ * checkout asks for quotes for one destination, then removes this provisional
171
+ * address; a provider-validated snapshot is the only pickup address retained.
172
+ */
173
+ export async function getEligibleShippingMethods(
174
+ locale: CommerceLocale,
175
+ countryCode: string,
176
+ ): Promise<CommerceResult<ShippingMethod[]>> {
177
+ const existingCountry = await getActiveOrderShippingCountry(locale);
178
+ if (existingCountry) {
179
+ if (existingCountry !== countryCode) {
180
+ return {
181
+ ok: false,
182
+ error: {
183
+ code: "SHIPPING_METHOD_INELIGIBLE",
184
+ message: `The order already ships to ${existingCountry}`,
185
+ },
186
+ };
187
+ }
188
+ const store = await cookies();
189
+ return client(
190
+ locale,
191
+ createCommerceSessionStore(store),
192
+ ).getEligibleShippingMethods();
193
+ }
194
+ await setTemporaryShippingCountry(locale, countryCode);
195
+ try {
196
+ const store = await cookies();
197
+ return await client(
198
+ locale,
199
+ createCommerceSessionStore(store),
200
+ ).getEligibleShippingMethods();
201
+ } finally {
202
+ await setTemporaryShippingCountry(locale, countryCode, true);
203
+ }
204
+ }
205
+
206
+ export async function getPacketaWidgetConfiguration(
207
+ locale: CommerceLocale,
208
+ countryCode: string,
209
+ ): Promise<PacketaWidgetConfiguration> {
210
+ const store = await cookies();
211
+ const endpoint = new URL(
212
+ process.env.JARSHOP_COMMERCE_ENDPOINT ?? "http://localhost:3000/shop-api",
213
+ );
214
+ endpoint.searchParams.set("languageCode", locale);
215
+ const response = await marketFetch(endpoint, {
216
+ method: "POST",
217
+ headers: {
218
+ "content-type": "application/json",
219
+ ...(commerceSessionAuthorization(store)
220
+ ? { authorization: commerceSessionAuthorization(store)! }
221
+ : {}),
222
+ },
223
+ body: JSON.stringify({
224
+ query: `query PacketaWidgetConfiguration($countryCode: String) {
225
+ jarShopPacketaWidgetConfiguration(countryCode: $countryCode) {
226
+ apiKey
227
+ options { country carriers vendors { country group } }
228
+ }
229
+ }`,
230
+ variables: { countryCode },
231
+ }),
232
+ cache: "no-store",
233
+ });
234
+ persistCommerceSession(store, response.headers);
235
+ if (!response.ok) {
236
+ throw new Error(`Packeta configuration returned ${response.status}`);
237
+ }
238
+ const body = (await response.json()) as {
239
+ data?: { jarShopPacketaWidgetConfiguration?: PacketaWidgetConfiguration };
240
+ errors?: readonly { message?: string }[];
241
+ };
242
+ const configuration = body.data?.jarShopPacketaWidgetConfiguration;
243
+ if (body.errors?.length || !configuration) {
244
+ throw new Error(
245
+ body.errors?.[0]?.message ?? "Packeta configuration is unavailable",
246
+ );
247
+ }
248
+ return configuration;
249
+ }
250
+
251
+ export async function getEligiblePaymentMethods(
252
+ locale: CommerceLocale,
253
+ ): Promise<CommerceResult<PaymentMethod[]>> {
254
+ const store = await cookies();
255
+ return client(
256
+ locale,
257
+ createCommerceSessionStore(store),
258
+ ).getEligiblePaymentMethods();
259
+ }
260
+
261
+ export async function startPayment(
262
+ locale: CommerceLocale,
263
+ paymentMethodCode: string,
264
+ ): Promise<CommerceResult<PaymentRedirectTarget>> {
265
+ const store = await cookies();
266
+ return client(locale, createCommerceSessionStore(store)).startPayment(
267
+ paymentMethodCode,
268
+ );
269
+ }
270
+
271
+ /**
272
+ * The gateway return has no active-order authority. It uses only the separate
273
+ * confirmation credential, which is bound to the order named by the URL.
274
+ */
275
+ export async function reconcileGuestPayment(
276
+ locale: CommerceLocale,
277
+ orderCode: string,
278
+ ): Promise<CommerceResult<GuestPaymentReconciliation>> {
279
+ const store = await cookies();
280
+ return confirmationClient(locale, store).reconcileGuestPayment(orderCode);
281
+ }
282
+
283
+ export async function getGuestOrderConfirmation(
284
+ locale: CommerceLocale,
285
+ orderCode: string,
286
+ ): Promise<CommerceResult<GuestOrderConfirmation>> {
287
+ const store = await cookies();
288
+ return confirmationClient(locale, store).getGuestOrderConfirmation(orderCode);
289
+ }
290
+
291
+ export async function setShippingSelection(
292
+ locale: CommerceLocale,
293
+ input: ShippingSelectionInput,
294
+ ): Promise<CommerceResult<ShippingSelection>> {
295
+ const store = await cookies();
296
+ return client(locale, createCommerceSessionStore(store)).setShippingSelection(
297
+ input,
298
+ );
299
+ }
300
+
41
301
  export function getCatalog(
42
302
  locale: CommerceLocale,
43
303
  options?: ProductListOptions,
@@ -0,0 +1,116 @@
1
+ import { renderToStaticMarkup } from "react-dom/server";
2
+ import { afterEach, describe, expect, it, vi } from "vitest";
3
+
4
+ const cookieStore = vi.hoisted(() => ({
5
+ get: vi.fn(() => ({ value: "confirmation-credential" })),
6
+ set: vi.fn(),
7
+ }));
8
+
9
+ vi.mock("next/headers", () => ({
10
+ cookies: async () => cookieStore,
11
+ // No configured domain matches, so the request uses the default market.
12
+ headers: async () => new Headers({ host: "localhost:3001" }),
13
+ }));
14
+
15
+ import CheckoutSuccess from "../app/[locale]/checkout/success/page";
16
+ import { defaultJarShopMarket } from "./market-config";
17
+
18
+ afterEach(() => {
19
+ vi.unstubAllGlobals();
20
+ cookieStore.get.mockClear();
21
+ cookieStore.set.mockClear();
22
+ });
23
+
24
+ describe("checkout success confirmation", () => {
25
+ it("shows the durable pickup-point address from the confirmation view", async () => {
26
+ let requestBody = "";
27
+ let channelToken: string | null = null;
28
+ vi.stubGlobal(
29
+ "fetch",
30
+ vi.fn(async (_input, init) => {
31
+ requestBody = String(init?.body ?? "");
32
+ channelToken = new Headers(init?.headers).get("vendure-token");
33
+ return new Response(
34
+ JSON.stringify({
35
+ data: {
36
+ jarShopProtectedOrderConfirmation: {
37
+ orderId: "42",
38
+ orderCode: "ORDER-42",
39
+ state: "PaymentAuthorized",
40
+ totalWithTax: 2_590,
41
+ currencyCode: "EUR",
42
+ shippingAddress: {
43
+ fullName: "Z-BOX, Hlavná 1, Bratislava",
44
+ streetLine1: "Hlavná 1",
45
+ streetLine2: "811 01 Bratislava",
46
+ postalCode: "811 01",
47
+ city: "Bratislava",
48
+ countryCode: "SK",
49
+ },
50
+ },
51
+ },
52
+ }),
53
+ { status: 200, headers: { "content-type": "application/json" } },
54
+ );
55
+ }),
56
+ );
57
+
58
+ const view = await CheckoutSuccess({
59
+ params: Promise.resolve({ locale: "sk" }),
60
+ searchParams: Promise.resolve({ order: "ORDER-42" }),
61
+ });
62
+ const html = renderToStaticMarkup(view);
63
+
64
+ expect(requestBody).toContain(
65
+ "shippingAddress { fullName streetLine1 streetLine2 postalCode city countryCode }",
66
+ );
67
+ expect(channelToken).toBe(defaultJarShopMarket.channelToken);
68
+ expect(html).toContain("Doručovacia adresa");
69
+ expect(html).toContain("Z-BOX, Hlavná 1, Bratislava");
70
+ expect(html).toContain("Hlavná 1");
71
+ expect(html).toContain("811 01 Bratislava");
72
+ expect(html).toContain("SK");
73
+ });
74
+
75
+ it("omits missing optional address lines without rendering blank rows", async () => {
76
+ vi.stubGlobal(
77
+ "fetch",
78
+ vi.fn(
79
+ async () =>
80
+ new Response(
81
+ JSON.stringify({
82
+ data: {
83
+ jarShopProtectedOrderConfirmation: {
84
+ orderId: "42",
85
+ orderCode: "ORDER-42",
86
+ state: "PaymentAuthorized",
87
+ totalWithTax: 2_590,
88
+ currencyCode: "EUR",
89
+ shippingAddress: {
90
+ fullName: "Z-BOX Bratislava",
91
+ streetLine1: " ",
92
+ streetLine2: "",
93
+ postalCode: "",
94
+ city: " Bratislava ",
95
+ countryCode: "SK",
96
+ },
97
+ },
98
+ },
99
+ }),
100
+ { status: 200, headers: { "content-type": "application/json" } },
101
+ ),
102
+ ),
103
+ );
104
+
105
+ const view = await CheckoutSuccess({
106
+ params: Promise.resolve({ locale: "sk" }),
107
+ searchParams: Promise.resolve({ order: "ORDER-42" }),
108
+ });
109
+ const html = renderToStaticMarkup(view);
110
+
111
+ expect(html).toContain("Z-BOX Bratislava");
112
+ expect(html).toContain("Bratislava");
113
+ expect(html).not.toContain("> </div>");
114
+ expect(html).not.toContain("><div></div>");
115
+ });
116
+ });
@@ -3,6 +3,7 @@
3
3
  import { cookies } from "next/headers";
4
4
 
5
5
  import type { CommerceLocale } from "./commerce";
6
+ import { marketFetch } from "./market";
6
7
  import {
7
8
  confirmationCookieOptions,
8
9
  CONFIRMATION_COOKIE_NAME,
@@ -14,6 +15,14 @@ export interface OrderConfirmationView {
14
15
  state: string;
15
16
  totalWithTax: number;
16
17
  currencyCode: string;
18
+ shippingAddress: {
19
+ fullName: string;
20
+ streetLine1: string;
21
+ streetLine2: string;
22
+ postalCode: string;
23
+ city: string;
24
+ countryCode: string;
25
+ } | null;
17
26
  }
18
27
 
19
28
  interface ConfirmationExchange {
@@ -32,9 +41,6 @@ function endpointFor(locale: CommerceLocale): string {
32
41
  function commerceHeaders(cookie?: string): HeadersInit {
33
42
  return {
34
43
  "content-type": "application/json",
35
- ...(process.env.JARSHOP_CHANNEL_TOKEN
36
- ? { "vendure-token": process.env.JARSHOP_CHANNEL_TOKEN }
37
- : {}),
38
44
  ...(cookie ? { cookie } : {}),
39
45
  };
40
46
  }
@@ -44,11 +50,11 @@ export async function exchangeOrderConfirmation(
44
50
  token: string,
45
51
  ): Promise<OrderConfirmationView | null> {
46
52
  const store = await cookies();
47
- const response = await fetch(endpointFor(locale), {
53
+ const response = await marketFetch(endpointFor(locale), {
48
54
  method: "POST",
49
55
  headers: commerceHeaders(),
50
56
  body: JSON.stringify({
51
- query: `mutation ExchangeConfirmation($token: String!) { exchangeJarShopOrderConfirmation(token: $token) { credential confirmation { orderId orderCode state totalWithTax currencyCode } } }`,
57
+ query: `mutation ExchangeConfirmation($token: String!) { exchangeJarShopOrderConfirmation(token: $token) { credential confirmation { orderId orderCode state totalWithTax currencyCode shippingAddress { fullName streetLine1 streetLine2 postalCode city countryCode } } } }`,
52
58
  variables: { token },
53
59
  }),
54
60
  cache: "no-store",
@@ -75,13 +81,13 @@ export async function getOrderConfirmation(
75
81
  const store = await cookies();
76
82
  const credential = store.get(CONFIRMATION_COOKIE_NAME)?.value;
77
83
  if (!credential) return null;
78
- const response = await fetch(endpointFor(locale), {
84
+ const response = await marketFetch(endpointFor(locale), {
79
85
  method: "POST",
80
86
  headers: commerceHeaders(
81
87
  `${CONFIRMATION_COOKIE_NAME}=${encodeURIComponent(credential)}`,
82
88
  ),
83
89
  body: JSON.stringify({
84
- query: `query ProtectedConfirmation($orderCode: String!) { jarShopProtectedOrderConfirmation(orderCode: $orderCode) { orderId orderCode state totalWithTax currencyCode } }`,
90
+ query: `query ProtectedConfirmation($orderCode: String!) { jarShopProtectedOrderConfirmation(orderCode: $orderCode) { orderId orderCode state totalWithTax currencyCode shippingAddress { fullName streetLine1 streetLine2 postalCode city countryCode } } }`,
85
91
  variables: { orderCode },
86
92
  }),
87
93
  cache: "no-store",
@@ -1,5 +1,6 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import {
3
+ catalogLanguage,
3
4
  createTranslator,
4
5
  formatMessage,
5
6
  isSupportedLocale,
@@ -7,30 +8,49 @@ import {
7
8
  parseLocale,
8
9
  supportedLocales,
9
10
  } from "./i18n";
11
+ import { defaultJarShopMarket, jarShopLanguages } from "./market-config";
10
12
 
11
13
  describe("JarShop storefront i18n contract", () => {
12
- it("keeps every supported locale aligned with the typed message keys", () => {
13
- const keys = Object.keys(messages.sk).sort();
14
+ it("keeps every message catalogue aligned with the typed message keys", () => {
15
+ const keys = Object.keys(messages.sk!).sort();
14
16
 
15
- for (const locale of supportedLocales) {
16
- expect(Object.keys(messages[locale]).sort()).toEqual(keys);
17
+ for (const catalog of Object.values(messages)) {
18
+ expect(Object.keys(catalog).sort()).toEqual(keys);
17
19
  }
18
20
  });
19
21
 
20
22
  it("loads catalogues from the conventional locale JSON resources", () => {
21
- expect(messages.sk["catalog.title"]).toBe("Produkty");
22
- expect(messages.en["catalog.title"]).toBe("Products");
23
+ expect(messages.sk!["catalog.title"]).toBe("Produkty");
24
+ expect(messages.en!["catalog.title"]).toBe("Products");
23
25
  });
24
26
 
25
- it("normalizes regional tags and falls back safely to Slovak", () => {
26
- expect(parseLocale("en-US")).toBe("en");
27
- expect(parseLocale("sk-SK")).toBe("sk");
28
- expect(parseLocale("de")).toBe("sk");
29
- expect(parseLocale(undefined)).toBe("sk");
30
- expect(isSupportedLocale("en")).toBe(true);
27
+ it("supports exactly the languages jarshop.config.ts declares", () => {
28
+ expect(supportedLocales).toEqual(jarShopLanguages);
29
+ expect(supportedLocales[0]).toBe(defaultJarShopMarket.defaultLanguage);
30
+ });
31
+
32
+ it("normalizes regional tags and falls back to the default market language", () => {
33
+ const fallback = defaultJarShopMarket.defaultLanguage;
34
+ expect(parseLocale("en-US")).toBe(
35
+ isSupportedLocale("en") ? "en" : fallback,
36
+ );
37
+ expect(parseLocale("sk-SK")).toBe(
38
+ isSupportedLocale("sk") ? "sk" : fallback,
39
+ );
40
+ expect(parseLocale("xx")).toBe(fallback);
41
+ expect(parseLocale(undefined)).toBe(fallback);
31
42
  expect(isSupportedLocale("en-US")).toBe(false);
32
43
  });
33
44
 
45
+ it("renders a configured language without its own catalogue in English", () => {
46
+ expect(catalogLanguage("en")).toBe("en");
47
+ for (const language of supportedLocales) {
48
+ expect(catalogLanguage(language)).toBe(
49
+ messages[language] ? language : "en",
50
+ );
51
+ }
52
+ });
53
+
34
54
  it("returns localized UI copy without changing commerce locale semantics", () => {
35
55
  expect(createTranslator("sk")("checkout.submitPickup")).toBe(
36
56
  "Objednať osobný odber na dobierku",
@@ -1,35 +1,56 @@
1
1
  import englishMessages from "../messages/en.json";
2
2
  import slovakMessages from "../messages/sk.json";
3
+ import { defaultJarShopMarket, jarShopLanguages } from "./market-config";
3
4
 
4
- export const supportedLocales = ["sk", "en"] as const;
5
+ /** Every language a market in `jarshop.config.ts` serves. */
6
+ export const supportedLocales: readonly string[] = jarShopLanguages;
5
7
 
6
- export type SupportedLocale = (typeof supportedLocales)[number];
8
+ export type SupportedLocale = string;
7
9
  export type MessageKey = keyof typeof slovakMessages;
8
10
  export type MessageCatalog = Record<MessageKey, string>;
9
11
 
10
12
  const typedEnglishMessages = englishMessages satisfies MessageCatalog;
11
13
 
12
- export const messages = {
14
+ /**
15
+ * UI copy catalogues by language. A configured language without its own
16
+ * catalogue renders the English copy until `messages/<language>.json` is added
17
+ * here.
18
+ */
19
+ export const messages: Readonly<Record<string, MessageCatalog>> = {
13
20
  sk: slovakMessages,
14
21
  en: typedEnglishMessages,
15
- } satisfies Record<SupportedLocale, MessageCatalog>;
22
+ };
23
+
24
+ const fallbackCatalogLanguage = "en";
16
25
 
17
26
  export function isSupportedLocale(
18
27
  value: string | undefined,
19
28
  ): value is SupportedLocale {
20
- return value === "sk" || value === "en";
29
+ return value !== undefined && supportedLocales.includes(value);
21
30
  }
22
31
 
32
+ /**
33
+ * Normalizes a language tag to a configured language. Pages restrict it
34
+ * further to the request market through `resolveRequestLocale`.
35
+ */
23
36
  export function parseLocale(value: string | undefined): SupportedLocale {
24
37
  const language = value?.toLowerCase().split("-")[0];
25
- return language === "en" ? "en" : "sk";
38
+ return isSupportedLocale(language)
39
+ ? language
40
+ : defaultJarShopMarket.defaultLanguage;
41
+ }
42
+
43
+ export function catalogLanguage(value: string | SupportedLocale): string {
44
+ const locale = parseLocale(value);
45
+ return messages[locale] ? locale : fallbackCatalogLanguage;
26
46
  }
27
47
 
28
48
  export type Translator = (key: MessageKey) => string;
29
49
 
30
50
  export function createTranslator(value: string | SupportedLocale): Translator {
31
- const locale = parseLocale(value);
32
- return (key) => messages[locale][key] ?? messages.sk[key];
51
+ const catalog = messages[catalogLanguage(value)]!;
52
+ const fallback = messages[fallbackCatalogLanguage]!;
53
+ return (key) => catalog[key] ?? fallback[key];
33
54
  }
34
55
 
35
56
  export function formatMessage(
@@ -0,0 +1,40 @@
1
+ import projectConfig from "../../jarshop.config";
2
+ import {
3
+ configuredLanguages,
4
+ defaultMarket,
5
+ parseJarShopConfig,
6
+ type JarShopConfig,
7
+ type JarShopMarket,
8
+ } from "../../src/jarshop-config";
9
+
10
+ export type { JarShopConfig, JarShopMarket };
11
+ export {
12
+ findMarket,
13
+ marketServesCountry,
14
+ normalizeHost,
15
+ resolveMarketForHost,
16
+ resolveMarketLanguage,
17
+ routeMarketPath,
18
+ } from "../../src/jarshop-config";
19
+
20
+ /**
21
+ * The project's validated `jarshop.config.ts`. It is bundled at build time, so
22
+ * an invalid configuration fails `next build` and the first import in tests
23
+ * with the full list of problems. The data is public: domains, languages,
24
+ * currencies and channel tokens are all visible to shoppers anyway.
25
+ */
26
+ export const jarShopConfig: JarShopConfig = parseJarShopConfig(projectConfig);
27
+
28
+ export const defaultJarShopMarket: JarShopMarket = defaultMarket(jarShopConfig);
29
+
30
+ /** Every language any market serves, default market languages first. */
31
+ export const jarShopLanguages: readonly string[] =
32
+ configuredLanguages(jarShopConfig);
33
+
34
+ /** A BCP 47 tag for number and currency formatting in a market. */
35
+ export function formattingLocale(
36
+ market: JarShopMarket,
37
+ language: string,
38
+ ): string {
39
+ return language === "en" ? "en-GB" : `${language}-${market.countries[0]}`;
40
+ }