@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
@@ -0,0 +1,43 @@
1
+ "use server";
2
+
3
+ import type {
4
+ CommerceResult,
5
+ ShippingSelection,
6
+ } from "@jarwizz/commerce-sdk/types";
7
+
8
+ import type { CommerceLocale } from "../../../lib/commerce";
9
+ import {
10
+ releaseActiveOrderShippingAddress,
11
+ setShippingSelection,
12
+ } from "../../../lib/commerce";
13
+
14
+ export async function choosePacketaPoint(
15
+ locale: CommerceLocale,
16
+ input: {
17
+ methodCode: string;
18
+ countryCode: string;
19
+ id: string;
20
+ },
21
+ ): Promise<CommerceResult<ShippingSelection>> {
22
+ return setShippingSelection(locale, {
23
+ shippingMethodCode: input.methodCode,
24
+ countryCode: input.countryCode,
25
+ payload: { pickupPointType: "internal", id: input.id },
26
+ });
27
+ }
28
+
29
+ /**
30
+ * A new destination releases the order's address, which a pickup point or a
31
+ * courier address pinned to the previous country, so the next render can
32
+ * quote the new country and a pickup point there can be chosen.
33
+ */
34
+ export async function releaseCheckoutDestination(
35
+ locale: CommerceLocale,
36
+ ): Promise<boolean> {
37
+ try {
38
+ await releaseActiveOrderShippingAddress(locale);
39
+ return true;
40
+ } catch {
41
+ return false;
42
+ }
43
+ }
@@ -1,28 +1,119 @@
1
1
  "use client";
2
2
 
3
- import { useActionState, useState } from "react";
3
+ import { useRouter } from "next/navigation";
4
+ import { useActionState, useReducer, useTransition } from "react";
4
5
 
5
- import type { CommerceLocale } from "../../../lib/commerce";
6
6
  import type {
7
- CheckoutActionState,
8
- CheckoutShippingMethod,
9
- } from "../../../lib/checkout";
7
+ PaymentMethod,
8
+ ShippingMethod,
9
+ } from "@jarwizz/commerce-sdk/types";
10
+
11
+ import type { PacketaConfigurationState } from "../../../lib/checkout-countries";
12
+ import type { CommerceLocale } from "../../../lib/commerce";
13
+ import type { CheckoutActionState } from "../../../lib/checkout";
10
14
  import { createTranslator } from "../../../lib/i18n";
15
+ import {
16
+ checkoutSelectionReducer,
17
+ initialCheckoutSelectionState,
18
+ isCheckoutSelectionBusy,
19
+ visiblePickupPoint,
20
+ } from "../../../lib/packeta-selection";
21
+ import { releaseCheckoutDestination } from "./actions";
22
+ import { PacketaChooser } from "./packeta-chooser";
23
+
24
+ interface CheckoutCountryOption {
25
+ readonly code: string;
26
+ readonly name: string;
27
+ }
11
28
 
12
29
  interface CheckoutFormProps {
30
+ /** Destination choices. */
31
+ countries: readonly CheckoutCountryOption[];
32
+ /** The preselected destination: the order's own country once it has one. */
33
+ initialCountry: string;
13
34
  locale: CommerceLocale;
35
+ /**
36
+ * Eligible shipping methods per destination country code. A country that
37
+ * is absent was not quoted because the order is pinned to another one.
38
+ */
39
+ methodsByCountry: Readonly<Record<string, ShippingMethod[]>>;
40
+ paymentMethods: PaymentMethod[];
41
+ /** Packeta widget configuration state per quoted country. */
42
+ packetaConfigurations: Readonly<Record<string, PacketaConfigurationState>>;
14
43
  action: (
15
44
  previousState: CheckoutActionState,
16
45
  formData: FormData,
17
46
  ) => Promise<CheckoutActionState>;
18
47
  }
19
48
 
20
- export function CheckoutForm({ locale, action }: CheckoutFormProps) {
49
+ export function CheckoutForm({
50
+ countries,
51
+ initialCountry: preselectedCountry,
52
+ locale,
53
+ methodsByCountry,
54
+ paymentMethods,
55
+ packetaConfigurations,
56
+ action,
57
+ }: CheckoutFormProps) {
21
58
  const [state, formAction, pending] = useActionState(action, { ok: true });
22
- const [shippingMethod, setShippingMethod] =
23
- useState<CheckoutShippingMethod>("pickup");
59
+ const router = useRouter();
60
+ const [destinationPending, startDestinationChange] = useTransition();
61
+ const initialCountry =
62
+ preselectedCountry ||
63
+ countries[0]?.code ||
64
+ initialCheckoutSelectionState.countryCode;
65
+ const initialMethods = methodsByCountry[initialCountry] ?? [];
66
+ const [selectionState, dispatch] = useReducer(checkoutSelectionReducer, {
67
+ ...initialCheckoutSelectionState,
68
+ countryCode: initialCountry,
69
+ methodCode:
70
+ initialMethods.find((method) => method.code === "pickup")?.code ??
71
+ initialMethods[0]?.code ??
72
+ "",
73
+ });
24
74
  const t = createTranslator(locale);
25
- const courier = shippingMethod === "courier";
75
+ const packetaState: PacketaConfigurationState = packetaConfigurations[
76
+ selectionState.countryCode
77
+ ] ?? { status: "unavailable" };
78
+ const packetaConfiguration =
79
+ packetaState.status === "ready" ? packetaState.configuration : null;
80
+ // A method that needs a pickup point is offered where Packeta serves the
81
+ // destination; a transient configuration failure keeps it visible with a
82
+ // retryable error rather than silently hiding it.
83
+ const visibleMethods = (
84
+ methodsByCountry[selectionState.countryCode] ?? []
85
+ ).filter(
86
+ (method) =>
87
+ !method.requiresSelection || packetaState.status !== "unavailable",
88
+ );
89
+ const quoted = selectionState.countryCode in methodsByCountry;
90
+ const reloading = destinationPending || !quoted;
91
+ function changeCountry(countryCode: string) {
92
+ dispatch({ type: "country-changed", countryCode });
93
+ startDestinationChange(async () => {
94
+ // The order may be pinned to the previous country by a pickup point or
95
+ // a courier address; release it, then quote the new country if this
96
+ // render could not.
97
+ await releaseCheckoutDestination(locale);
98
+ if (!(countryCode in methodsByCountry)) {
99
+ startDestinationChange(() => router.refresh());
100
+ }
101
+ });
102
+ }
103
+ function retryPacketa() {
104
+ startDestinationChange(() => router.refresh());
105
+ }
106
+ const selectedMethod = visibleMethods.find(
107
+ (method) => method.code === selectionState.methodCode,
108
+ );
109
+ const courier = selectedMethod?.code === "courier";
110
+ const pickupPoint = visiblePickupPoint(selectionState);
111
+ const selectionRequired = selectedMethod?.requiresSelection === true;
112
+ const selectionBusy =
113
+ isCheckoutSelectionBusy(selectionState) || destinationPending;
114
+ const selectionReady =
115
+ selectedMethod !== undefined &&
116
+ (!selectionRequired || pickupPoint !== null);
26
117
 
27
118
  return (
28
119
  <form action={formAction} className="checkout-form">
@@ -42,29 +133,81 @@ export function CheckoutForm({ locale, action }: CheckoutFormProps) {
42
133
  {t("checkout.phone")}
43
134
  <input name="phoneNumber" type="tel" required />
44
135
  </label>
45
- <fieldset>
136
+ <label>
137
+ {t("checkout.country")}
138
+ <select
139
+ disabled={selectionBusy}
140
+ name="countryCode"
141
+ value={selectionState.countryCode}
142
+ onChange={(event) => changeCountry(event.target.value)}
143
+ >
144
+ {countries.map((country) => (
145
+ <option key={country.code} value={country.code}>
146
+ {country.name}
147
+ </option>
148
+ ))}
149
+ </select>
150
+ </label>
151
+ <fieldset aria-busy={reloading} disabled={selectionBusy}>
46
152
  <legend>{t("checkout.shippingMethod")}</legend>
47
- <label>
48
- <input
49
- name="shippingMethodCode"
50
- type="radio"
51
- value="pickup"
52
- checked={shippingMethod === "pickup"}
53
- onChange={() => setShippingMethod("pickup")}
54
- />
55
- {t("checkout.pickup")}
56
- </label>
57
- <label>
58
- <input
59
- name="shippingMethodCode"
60
- type="radio"
61
- value="courier"
62
- checked={shippingMethod === "courier"}
63
- onChange={() => setShippingMethod("courier")}
64
- />
65
- {t("checkout.courier")}
66
- </label>
153
+ {visibleMethods.map((method) => (
154
+ <label key={method.code}>
155
+ <input
156
+ name="shippingMethodCode"
157
+ type="radio"
158
+ value={method.code}
159
+ checked={selectionState.methodCode === method.code}
160
+ onChange={() =>
161
+ dispatch({ type: "method-changed", methodCode: method.code })
162
+ }
163
+ />
164
+ {method.name}
165
+ </label>
166
+ ))}
167
+ </fieldset>
168
+ {selectionRequired && packetaConfiguration ? (
169
+ <PacketaChooser
170
+ configuration={packetaConfiguration}
171
+ countryCode={selectionState.countryCode}
172
+ dispatch={dispatch}
173
+ locale={locale}
174
+ methodCode={selectedMethod?.code ?? ""}
175
+ state={selectionState}
176
+ />
177
+ ) : selectionRequired ? (
178
+ <p role="alert">
179
+ {t("checkout.packetaConfigurationFailure")}{" "}
180
+ <button
181
+ disabled={destinationPending}
182
+ onClick={retryPacketa}
183
+ type="button"
184
+ >
185
+ {t("checkout.packetaRetry")}
186
+ </button>
187
+ </p>
188
+ ) : null}
189
+ <fieldset disabled={selectionBusy}>
190
+ <legend>{t("checkout.paymentMethod")}</legend>
191
+ {paymentMethods.map((method) => (
192
+ <label key={method.code}>
193
+ <input
194
+ name="paymentMethodCode"
195
+ type="radio"
196
+ value={method.code}
197
+ defaultChecked={method.code === "cod"}
198
+ />
199
+ {method.name}
200
+ </label>
201
+ ))}
67
202
  </fieldset>
203
+ {pickupPoint ? (
204
+ <address aria-label={t("checkout.acceptedPickupPoint")}>
205
+ <strong>{pickupPoint.label}</strong>
206
+ {pickupPoint.addressLines.map((line) => (
207
+ <div key={line}>{line}</div>
208
+ ))}
209
+ </address>
210
+ ) : null}
68
211
  {courier ? (
69
212
  <fieldset>
70
213
  <legend>{t("checkout.courier")}</legend>
@@ -82,14 +225,16 @@ export function CheckoutForm({ locale, action }: CheckoutFormProps) {
82
225
  </label>
83
226
  <label>
84
227
  {t("checkout.country")}
85
- <select name="countryCode" defaultValue="SK" required>
86
- <option value="SK">{t("checkout.slovakia")}</option>
87
- </select>
228
+ <input value={selectionState.countryCode} readOnly />
88
229
  </label>
89
230
  </fieldset>
90
231
  ) : null}
91
232
  <p>
92
- {courier ? t("checkout.courierSummary") : t("checkout.pickupSummary")}
233
+ {courier
234
+ ? t("checkout.courierSummary")
235
+ : selectionRequired
236
+ ? t("checkout.packetaSummary")
237
+ : t("checkout.pickupSummary")}
93
238
  </p>
94
239
  {!state.ok ? (
95
240
  <p role="alert">
@@ -104,8 +249,15 @@ export function CheckoutForm({ locale, action }: CheckoutFormProps) {
104
249
  <input name="termsAccepted" type="checkbox" required />{" "}
105
250
  {t("checkout.terms")}
106
251
  </label>
107
- <button type="submit" disabled={pending}>
108
- {courier ? t("checkout.submitCourier") : t("checkout.submitPickup")}
252
+ <button
253
+ type="submit"
254
+ disabled={pending || selectionBusy || reloading || !selectionReady}
255
+ >
256
+ {courier
257
+ ? t("checkout.submitCourier")
258
+ : selectionRequired
259
+ ? t("checkout.submitPacketa")
260
+ : t("checkout.submitPickup")}
109
261
  </button>
110
262
  </form>
111
263
  );
@@ -1,14 +1,14 @@
1
1
  import { NextResponse, type NextRequest } from "next/server";
2
2
 
3
3
  import { exchangeOrderConfirmation } from "../../../../lib/confirmation";
4
- import { parseLocale } from "../../../../lib/i18n";
4
+ import { resolveRequestLocale } from "../../../../lib/market";
5
5
 
6
6
  export async function GET(
7
7
  request: NextRequest,
8
8
  context: { params: Promise<{ locale: string }> },
9
9
  ) {
10
10
  const { locale } = await context.params;
11
- const language = parseLocale(locale);
11
+ const { language } = await resolveRequestLocale(locale);
12
12
  const token = request.nextUrl.searchParams.get("token");
13
13
  const confirmation = token
14
14
  ? await exchangeOrderConfirmation(language, token)
@@ -0,0 +1,96 @@
1
+ "use client";
2
+
3
+ import type { Dispatch } from "react";
4
+
5
+ import {
6
+ openPacketaWidget,
7
+ type PacketaWidgetConfiguration,
8
+ } from "@jarwizz/feature-packeta/storefront";
9
+
10
+ import type { CommerceLocale } from "../../../lib/commerce";
11
+ import type {
12
+ CheckoutSelectionEvent,
13
+ CheckoutSelectionState,
14
+ } from "../../../lib/packeta-selection";
15
+ import { choosePacketaPoint } from "./actions";
16
+
17
+ interface PacketaChooserProps {
18
+ configuration: PacketaWidgetConfiguration;
19
+ countryCode: string;
20
+ dispatch: Dispatch<CheckoutSelectionEvent>;
21
+ locale: CommerceLocale;
22
+ methodCode: string;
23
+ state: CheckoutSelectionState;
24
+ }
25
+
26
+ export function PacketaChooser({
27
+ configuration,
28
+ countryCode,
29
+ dispatch,
30
+ locale,
31
+ methodCode,
32
+ state,
33
+ }: PacketaChooserProps) {
34
+ const busy = state.status === "opening" || state.status === "saving";
35
+ const labels =
36
+ locale === "sk"
37
+ ? {
38
+ choose: "Vybrať výdajné miesto Packeta",
39
+ opening: "Otváram Packetu…",
40
+ saving: "Overujem výdajné miesto…",
41
+ failure: "Výdajné miesto sa nepodarilo overiť. Skús to znova.",
42
+ }
43
+ : {
44
+ choose: "Choose a Packeta pickup point",
45
+ opening: "Opening Packeta…",
46
+ saving: "Verifying the pickup point…",
47
+ failure: "The pickup point could not be verified. Try again.",
48
+ };
49
+
50
+ async function choose(): Promise<void> {
51
+ const revision = state.revision;
52
+ dispatch({ type: "opening" });
53
+ try {
54
+ await openPacketaWidget(configuration, (selection) => {
55
+ if (selection === null) {
56
+ dispatch({ type: "cancelled" });
57
+ return;
58
+ }
59
+ dispatch({ type: "saving" });
60
+ void choosePacketaPoint(locale, {
61
+ methodCode,
62
+ countryCode,
63
+ id: selection.id,
64
+ }).then(
65
+ (result) => {
66
+ if (result.ok) {
67
+ dispatch({
68
+ type: "accepted",
69
+ revision,
70
+ selection: result.data,
71
+ });
72
+ } else {
73
+ dispatch({ type: "failed", message: labels.failure });
74
+ }
75
+ },
76
+ () => dispatch({ type: "failed", message: labels.failure }),
77
+ );
78
+ });
79
+ } catch {
80
+ dispatch({ type: "failed", message: labels.failure });
81
+ }
82
+ }
83
+
84
+ return (
85
+ <div className="packeta-chooser">
86
+ <button type="button" disabled={busy} onClick={() => void choose()}>
87
+ {state.status === "opening"
88
+ ? labels.opening
89
+ : state.status === "saving"
90
+ ? labels.saving
91
+ : labels.choose}
92
+ </button>
93
+ {state.error ? <p role="alert">{state.error}</p> : null}
94
+ </div>
95
+ );
96
+ }
@@ -1,6 +1,20 @@
1
+ import type { ShippingMethod } from "@jarwizz/commerce-sdk/types";
2
+
1
3
  import { placeOrder } from "../../../lib/checkout";
2
4
  import { getCart } from "../../../lib/cart";
3
- import { createTranslator, parseLocale } from "../../../lib/i18n";
5
+ import {
6
+ planCheckoutCountries,
7
+ resolvePacketaConfiguration,
8
+ type PacketaConfigurationState,
9
+ } from "../../../lib/checkout-countries";
10
+ import {
11
+ getActiveOrderShippingCountry,
12
+ getEligibleShippingMethods,
13
+ getEligiblePaymentMethods,
14
+ getPacketaWidgetConfiguration,
15
+ } from "../../../lib/commerce";
16
+ import { createTranslator } from "../../../lib/i18n";
17
+ import { resolveRequestLocale } from "../../../lib/market";
4
18
  import { CheckoutForm } from "./checkout-form";
5
19
 
6
20
  interface CheckoutPageProps {
@@ -9,10 +23,49 @@ interface CheckoutPageProps {
9
23
 
10
24
  export default async function CheckoutPage({ params }: CheckoutPageProps) {
11
25
  const { locale } = await params;
12
- const language = parseLocale(locale);
26
+ const { market, language } = await resolveRequestLocale(locale);
13
27
  const attemptId = crypto.randomUUID();
14
28
  const cart = await getCart(language);
29
+ const countryCodes = market.countries;
30
+ const plan = planCheckoutCountries(
31
+ countryCodes,
32
+ await getActiveOrderShippingCountry(language).catch(() => null),
33
+ );
34
+ // Shipping quotes are computed against the active order's address, so the
35
+ // destinations are asked one after another rather than concurrently. A
36
+ // country left out of the plan is quoted after the form releases the
37
+ // order's address for it.
38
+ const methodsByCountry: Record<string, ShippingMethod[]> = {};
39
+ for (const code of plan.quotedCountries) {
40
+ const eligible = await getEligibleShippingMethods(language, code);
41
+ methodsByCountry[code] = eligible.ok ? eligible.data : [];
42
+ }
43
+ const [paymentMethods, packetaEntries] = await Promise.all([
44
+ getEligiblePaymentMethods(language),
45
+ // Packeta's widget configuration is read only where an eligible method
46
+ // needs a pickup point; a failure there is transient and retryable.
47
+ Promise.all(
48
+ plan.quotedCountries.map(
49
+ async (code) =>
50
+ [
51
+ code,
52
+ await resolvePacketaConfiguration(
53
+ methodsByCountry[code] ?? [],
54
+ () => getPacketaWidgetConfiguration(language, code),
55
+ ),
56
+ ] as const,
57
+ ),
58
+ ),
59
+ ]);
60
+ const packetaConfigurations: Record<string, PacketaConfigurationState> =
61
+ Object.fromEntries(packetaEntries);
15
62
  const t = createTranslator(language);
63
+ const countryNames = new Intl.DisplayNames([language], { type: "region" });
64
+ // The destinations are exactly the countries of the request's market.
65
+ const countries = countryCodes.map((code) => ({
66
+ code,
67
+ name: countryNames.of(code) ?? code,
68
+ }));
16
69
 
17
70
  return (
18
71
  <main className="page checkout-page" lang={language}>
@@ -21,7 +74,12 @@ export default async function CheckoutPage({ params }: CheckoutPageProps) {
21
74
  <h1>{t("checkout.title")}</h1>
22
75
  </div>
23
76
  <CheckoutForm
77
+ countries={countries}
78
+ initialCountry={plan.initialCountry}
24
79
  locale={language}
80
+ methodsByCountry={methodsByCountry}
81
+ paymentMethods={paymentMethods.ok ? paymentMethods.data : []}
82
+ packetaConfigurations={packetaConfigurations}
25
83
  action={placeOrder.bind(
26
84
  null,
27
85
  language,
@@ -0,0 +1,55 @@
1
+ "use server";
2
+
3
+ import type { GuestOrderConfirmation } from "@jarwizz/commerce-sdk/types";
4
+
5
+ import type { CommerceLocale } from "../../../../lib/commerce";
6
+ import {
7
+ getGuestOrderConfirmation,
8
+ reconcileGuestPayment,
9
+ } from "../../../../lib/commerce";
10
+
11
+ export type PaymentReturnState =
12
+ | { readonly kind: "paid"; readonly confirmation: GuestOrderConfirmation }
13
+ | { readonly kind: "failed"; readonly confirmation: GuestOrderConfirmation }
14
+ | { readonly kind: "pending"; readonly confirmation: GuestOrderConfirmation }
15
+ | { readonly kind: "unavailable" };
16
+
17
+ function stateForConfirmation(
18
+ confirmation: GuestOrderConfirmation,
19
+ ): PaymentReturnState {
20
+ if (
21
+ confirmation.state === "PaymentSettled" ||
22
+ confirmation.state === "PaymentAuthorized"
23
+ ) {
24
+ return { kind: "paid", confirmation };
25
+ }
26
+ if (confirmation.state === "Cancelled") {
27
+ return { kind: "failed", confirmation };
28
+ }
29
+ return { kind: "pending", confirmation };
30
+ }
31
+
32
+ /**
33
+ * A return actively asks the provider once, then all later observations come
34
+ * from the protected confirmation. Neither the URL nor the reconciliation
35
+ * result itself decides what the customer sees.
36
+ */
37
+ export async function refreshPaymentReturn(
38
+ locale: CommerceLocale,
39
+ orderCode: string,
40
+ ): Promise<PaymentReturnState> {
41
+ const reconciled = await reconcileGuestPayment(locale, orderCode);
42
+ if (!reconciled.ok) return { kind: "unavailable" };
43
+ return readPaymentReturn(locale, orderCode);
44
+ }
45
+
46
+ /** Polling reads the durable order only; it never repeats the provider trigger. */
47
+ export async function readPaymentReturn(
48
+ locale: CommerceLocale,
49
+ orderCode: string,
50
+ ): Promise<PaymentReturnState> {
51
+ const confirmation = await getGuestOrderConfirmation(locale, orderCode);
52
+ return confirmation.ok
53
+ ? stateForConfirmation(confirmation.data)
54
+ : { kind: "unavailable" };
55
+ }
@@ -0,0 +1,32 @@
1
+ import { resolveRequestLocale } from "../../../../lib/market";
2
+ import { PaymentReturn } from "./payment-return";
3
+
4
+ interface PaymentReturnPageProps {
5
+ readonly params: Promise<{ locale: string }>;
6
+ readonly searchParams: Promise<{
7
+ order?: string;
8
+ paid?: string;
9
+ status?: string;
10
+ }>;
11
+ }
12
+
13
+ /** One provider-neutral return page. The URL may name an order, never its outcome. */
14
+ export default async function PaymentReturnPage({
15
+ params,
16
+ searchParams,
17
+ }: PaymentReturnPageProps) {
18
+ const { locale } = await params;
19
+ const { order } = await searchParams;
20
+ const { language } = await resolveRequestLocale(locale);
21
+
22
+ return (
23
+ <main lang={language}>
24
+ <h1>JarShop</h1>
25
+ {order ? (
26
+ <PaymentReturn locale={language} orderCode={order} />
27
+ ) : (
28
+ <p>Order confirmation is not available.</p>
29
+ )}
30
+ </main>
31
+ );
32
+ }
@@ -0,0 +1,84 @@
1
+ "use client";
2
+
3
+ import Link from "next/link";
4
+ import { useEffect, useState } from "react";
5
+
6
+ import type { CommerceLocale } from "../../../../lib/commerce";
7
+ import { createTranslator } from "../../../../lib/i18n";
8
+ import {
9
+ nextPaymentReturnPollDelay,
10
+ storefrontPaymentReturnPollingConfiguration,
11
+ } from "../../../../lib/payment-return-polling";
12
+ import {
13
+ readPaymentReturn,
14
+ refreshPaymentReturn,
15
+ type PaymentReturnState,
16
+ } from "./actions";
17
+
18
+ interface PaymentReturnProps {
19
+ readonly locale: CommerceLocale;
20
+ readonly orderCode: string;
21
+ }
22
+
23
+ export function PaymentReturn({ locale, orderCode }: PaymentReturnProps) {
24
+ const t = createTranslator(locale);
25
+ const [state, setState] = useState<PaymentReturnState | null>(null);
26
+
27
+ useEffect(() => {
28
+ const configuration = storefrontPaymentReturnPollingConfiguration();
29
+ const startedAt = Date.now();
30
+ let active = true;
31
+ let timer: ReturnType<typeof setTimeout> | undefined;
32
+
33
+ const refresh = async (triggerReconciliation: boolean) => {
34
+ const next = triggerReconciliation
35
+ ? await refreshPaymentReturn(locale, orderCode)
36
+ : await readPaymentReturn(locale, orderCode);
37
+ if (!active) return;
38
+ setState(next);
39
+ if (next.kind !== "pending") return;
40
+ const delay = nextPaymentReturnPollDelay({
41
+ configuration,
42
+ startedAt,
43
+ now: Date.now(),
44
+ });
45
+ if (delay === null) return;
46
+ timer = setTimeout(() => void refresh(false), delay);
47
+ };
48
+
49
+ void refresh(true);
50
+ return () => {
51
+ active = false;
52
+ if (timer) clearTimeout(timer);
53
+ };
54
+ }, [locale, orderCode]);
55
+
56
+ if (!state) return <p>{t("paymentReturn.checking")}</p>;
57
+ if (state.kind === "paid") {
58
+ return (
59
+ <>
60
+ <p>{t("paymentReturn.paid")}</p>
61
+ <p>
62
+ {t("success.orderCode")}: {state.confirmation.orderCode}
63
+ </p>
64
+ </>
65
+ );
66
+ }
67
+ if (state.kind === "failed") {
68
+ return (
69
+ <>
70
+ <p>{t("paymentReturn.failed")}</p>
71
+ <Link href={`/${locale}/checkout`}>{t("paymentReturn.retry")}</Link>
72
+ </>
73
+ );
74
+ }
75
+ if (state.kind === "pending") {
76
+ return (
77
+ <p>
78
+ {t("paymentReturn.pending")} {t("success.orderCode")}:{" "}
79
+ {state.confirmation.orderCode}
80
+ </p>
81
+ );
82
+ }
83
+ return <p>{t("paymentReturn.unavailable")}</p>;
84
+ }