@hszrdm/create-commerce 1.20.0 → 1.22.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.
@@ -1,6 +1,6 @@
1
1
  "use client"
2
2
 
3
- import { Fragment, useCallback, useEffect, useMemo, useRef, useState, useId } from "react"
3
+ import { useCallback, useEffect, useMemo, useRef, useState, useId } from "react"
4
4
  import { usePathname, useRouter, useSearchParams } from "next/navigation"
5
5
  import { useCart } from "./cart-provider"
6
6
  import { AddressStreetFields } from "./address-street-fields"
@@ -34,13 +34,14 @@ import {
34
34
  type CustomerAddress,
35
35
  } from "@/lib/core/checkout-addresses"
36
36
  import { normalizeShippingPhone, requireShippingText, validateShippingEmail } from "@/lib/core/shipping-input-validation"
37
+ import { checkoutOrderSummary } from "@/lib/core/checkout-summary"
38
+ import { checkoutPaymentChoices } from "@/lib/core/checkout-payment-choices"
37
39
  import {
38
40
  activePaymentSession,
39
41
  asRecords,
40
42
  cartCurrency,
41
43
  cartPaymentCollection,
42
44
  cartRegionId,
43
- cartTotal,
44
45
  formatMoney,
45
46
  isRecord,
46
47
  paymentClientSecret,
@@ -735,23 +736,11 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
735
736
  initializationError: stripeInitError,
736
737
  })
737
738
  const simplePaySelected = activeProviderId.toLowerCase().includes("simplepay")
738
- const systemSelected = activeProviderId.toLowerCase().includes("system")
739
+ // Both offline providers submit the native Medusa order without card UI.
740
+ const offlineSelected = activeProviderId === "pp_system_default" || activeProviderId === "pp_cod_cod"
739
741
  const currency = cartCurrency(cart, config.store.default_currency)
740
- const selectedMethod = asRecords(cart.shipping_methods)[0]
741
- const activeShippingOption = shippingOptions.find(option =>
742
- stringValue(option.id) === stringValue(selectedMethod?.shipping_option_id))
743
- const optionData = isRecord(activeShippingOption?.data) ? activeShippingOption.data : {}
744
- const selectedShippingData = isRecord(selectedMethod?.data) ? selectedMethod.data : {}
745
- const csomagpiacData = isRecord(selectedShippingData.csomagpiac) ? selectedShippingData.csomagpiac : {}
746
- const codAvailable = currency === "HUF" &&
747
- activeShippingOption?.price_type === "flat" &&
748
- csomagpiacData.codEnabled !== false &&
749
- (optionData.hszrdm_cod_enabled === true ||
750
- (optionData.hszrdm_cod_enabled === undefined && optionData.cod === true)) &&
751
- asRecords(cart.shipping_methods).length === 1
752
- const appliedCodFee = shippingMethodIsCod(cart)
753
- ? Number(selectedShippingData.hszrdm_cod_applied_fee_huf || 0)
754
- : 0
742
+ const paymentChoices = checkoutPaymentChoices(providers, config.payments.bank_transfer.enabled)
743
+ const orderSummary = checkoutOrderSummary(cart, currency)
755
744
 
756
745
  return (
757
746
  <div className="checkout-layout">
@@ -1032,37 +1021,24 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
1032
1021
  <p className="muted">{copy.chooseShippingForPayments}</p>
1033
1022
  ) : (
1034
1023
  <div className="choice-list">
1035
- {providers.map((provider) => {
1036
- const id = stringValue(provider.id)
1037
- const system = id.toLowerCase().includes("system")
1038
- const normalMode = system ? "bank_transfer" : "online"
1039
- return (
1040
- <Fragment key={id}>
1041
- {system && codAvailable ? (
1042
- <button
1043
- className={`choice-card choice-button${selectedProvider === id && selectedPaymentMode === "cod" ? " selected" : ""}`}
1044
- type="button"
1045
- disabled={busy === "payment" || !addressOnCart}
1046
- onClick={() => void preparePayment(id, "cod")}
1047
- >
1048
- <strong>{localized(locale, "Utánvét", "Cash on delivery")}</strong>
1049
- <small>{localized(locale, "Fizetés kézbesítéskor", "Pay on delivery")}</small>
1050
- </button>
1051
- ) : null}
1052
- {(!system || config.payments.bank_transfer.enabled) ? (
1053
- <button
1054
- className={`choice-card choice-button${selectedProvider === id && selectedPaymentMode === normalMode ? " selected" : ""}`}
1055
- type="button"
1056
- disabled={busy === "payment" || !addressOnCart}
1057
- onClick={() => void preparePayment(id, normalMode)}
1058
- >
1059
- <strong>{providerLabel(id, false)}</strong>
1060
- <small>{id}</small>
1061
- </button>
1062
- ) : null}
1063
- </Fragment>
1064
- )
1065
- })}
1024
+ {paymentChoices.map((choice) => (
1025
+ <button
1026
+ key={`${choice.providerId}:${choice.mode}`}
1027
+ className={`choice-card choice-button${selectedProvider === choice.providerId && selectedPaymentMode === choice.mode ? " selected" : ""}`}
1028
+ type="button"
1029
+ disabled={busy === "payment" || !addressOnCart}
1030
+ onClick={() => void preparePayment(choice.providerId, choice.mode)}
1031
+ >
1032
+ <strong>{choice.mode === "cod"
1033
+ ? localized(locale, "Utánvét", "Cash on delivery")
1034
+ : providerLabel(choice.providerId, false)}</strong>
1035
+ <small>{choice.mode === "cod"
1036
+ ? localized(locale, "Fizetés kézbesítéskor", "Pay on delivery")
1037
+ : choice.mode === "bank_transfer"
1038
+ ? localized(locale, "Fizetés banki átutalással", "Pay by bank transfer")
1039
+ : localized(locale, "Online fizetés", "Online payment")}</small>
1040
+ </button>
1041
+ ))}
1066
1042
  </div>
1067
1043
  )}
1068
1044
 
@@ -1121,7 +1097,7 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
1121
1097
  </button>
1122
1098
  ) : null}
1123
1099
 
1124
- {systemSelected ? (
1100
+ {offlineSelected ? (
1125
1101
  <button
1126
1102
  className="button button-large"
1127
1103
  type="button"
@@ -1192,23 +1168,56 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
1192
1168
  ) : null}
1193
1169
  </div>
1194
1170
 
1195
- <aside className="checkout-summary panel stack-sm">
1196
- <p className="eyebrow">{copy.orderSummary}</p>
1171
+ <aside className="checkout-summary panel stack-sm" aria-label={copy.orderSummary}>
1172
+ <h2 className="checkout-summary-heading">{copy.orderSummary}</h2>
1197
1173
  {asRecords(cart.items).map((item) => (
1198
1174
  <div className="summary-line" key={stringValue(item.id)}>
1199
1175
  <span>{stringValue(item.product_title || item.title)} × {stringValue(item.quantity)}</span>
1200
1176
  <span>{typeof item.total === "number" ? formatMoney(item.total, currency, numberLocale) : ""}</span>
1201
1177
  </div>
1202
1178
  ))}
1203
- {appliedCodFee > 0 && Number.isFinite(appliedCodFee) ? (
1179
+
1180
+ <section className="checkout-summary-group" aria-label={localized(locale, "Termékek", "Products")}>
1181
+ <h3>{localized(locale, "Termékek", "Products")}</h3>
1182
+ {orderSummary.taxDetailsVisible ? (
1183
+ <>
1184
+ <div className="summary-line"><span>{localized(locale, "Nettó", "Net")}</span><span>{formatMoney(orderSummary.items.net, currency, numberLocale)}</span></div>
1185
+ <div className="summary-line"><span>{localized(locale, "ÁFA", "VAT")}</span><span>{formatMoney(orderSummary.items.tax, currency, numberLocale)}</span></div>
1186
+ </>
1187
+ ) : null}
1188
+ <div className="summary-line checkout-summary-gross"><span>{localized(locale, "Bruttó", "Gross")}</span><strong>{formatMoney(orderSummary.items.gross, currency, numberLocale)}</strong></div>
1189
+ </section>
1190
+
1191
+ <section className="checkout-summary-group" aria-label={localized(locale, "Szállítási költség", "Shipping cost")}>
1192
+ <h3>{localized(locale, "Szállítási költség", "Shipping cost")}</h3>
1193
+ {orderSummary.shipping ? (
1194
+ <>
1195
+ {orderSummary.taxDetailsVisible ? (
1196
+ <>
1197
+ <div className="summary-line"><span>{localized(locale, "Nettó", "Net")}</span><span>{formatMoney(orderSummary.shipping.net, currency, numberLocale)}</span></div>
1198
+ <div className="summary-line"><span>{localized(locale, "ÁFA", "VAT")}</span><span>{formatMoney(orderSummary.shipping.tax, currency, numberLocale)}</span></div>
1199
+ </>
1200
+ ) : null}
1201
+ <div className="summary-line checkout-summary-gross"><span>{localized(locale, "Bruttó", "Gross")}</span><strong>{formatMoney(orderSummary.shipping.gross, currency, numberLocale)}</strong></div>
1202
+ </>
1203
+ ) : <p className="muted small">{localized(locale, "Még nincs kiválasztva", "Not selected yet")}</p>}
1204
+ </section>
1205
+
1206
+ {orderSummary.codGross !== null ? (
1207
+ <div className="checkout-summary-cod summary-line">
1208
+ <span>{localized(locale, "Utánvét (bruttó)", "Cash on delivery (gross)")}</span>
1209
+ <strong>{formatMoney(orderSummary.codGross, currency, numberLocale)}</strong>
1210
+ </div>
1211
+ ) : null}
1212
+ {Math.abs(orderSummary.adjustment) > 0.005 ? (
1204
1213
  <div className="summary-line">
1205
- <span>{localized(locale, "Ebből utánvét kezelési díj", "Including COD handling fee")}</span>
1206
- <span>{formatMoney(appliedCodFee, currency, numberLocale)}</span>
1214
+ <span>{localized(locale, "Egyéb jóváírás / korrekció", "Other credit / adjustment")}</span>
1215
+ <span>{formatMoney(orderSummary.adjustment, currency, numberLocale)}</span>
1207
1216
  </div>
1208
1217
  ) : null}
1209
1218
  <div className="summary-total">
1210
- <span>{copy.total}</span>
1211
- <strong>{formatMoney(cartTotal(cart), currency, numberLocale)}</strong>
1219
+ <span>{localized(locale, "Bruttó végösszeg", "Gross total")}</span>
1220
+ <strong>{formatMoney(orderSummary.grossTotal, currency, numberLocale)}</strong>
1212
1221
  </div>
1213
1222
  </aside>
1214
1223
  </div>
@@ -66,6 +66,11 @@ export function ConsentBanner({ enabled }: { enabled: boolean }) {
66
66
 
67
67
  {open ? (
68
68
  <aside className="consent" aria-label="Cookie-beállítások" role="dialog" aria-modal="true">
69
+ {preferences ? (
70
+ <button type="button" className="consent-dismiss" aria-label="Cookie-beállítások bezárása" onClick={() => setOpen(false)}>
71
+ ×
72
+ </button>
73
+ ) : null}
69
74
  <div className="stack consent-copy">
70
75
  <div>
71
76
  <strong>Cookie-beállítások</strong>
@@ -109,20 +114,15 @@ export function ConsentBanner({ enabled }: { enabled: boolean }) {
109
114
  </div>
110
115
 
111
116
  <div className="consent-actions">
112
- <button className="button secondary" onClick={() => save({ analytics: false, marketing: false })}>
113
- Opcionálisak elutasítása
117
+ <button type="button" className="button" onClick={() => save({ analytics: true, marketing: true })}>
118
+ Mindet elfogadom
114
119
  </button>
115
- <button className="button secondary" onClick={() => save({ analytics, marketing })}>
120
+ <button type="button" className="button secondary" onClick={() => save({ analytics, marketing })}>
116
121
  Beállítások mentése
117
122
  </button>
118
- <button className="button" onClick={() => save({ analytics: true, marketing: true })}>
119
- Mindet elfogadom
123
+ <button type="button" className="button secondary consent-reject" onClick={() => save({ analytics: false, marketing: false })}>
124
+ Opcionálisak elutasítása
120
125
  </button>
121
- {preferences ? (
122
- <button className="button secondary" onClick={() => setOpen(false)}>
123
- Bezárás
124
- </button>
125
- ) : null}
126
126
  </div>
127
127
  </aside>
128
128
  ) : null}
@@ -173,6 +173,8 @@ export function accountApi(config: CoreConfig) {
173
173
  requestEmailVerification: () =>
174
174
  medusaFetch<{
175
175
  success: boolean
176
+ already_verified?: boolean
177
+ verification_requested?: boolean
176
178
  retry_after_seconds: number
177
179
  resend_available_at: string | null
178
180
  }>(paths.email_verification, {
@@ -0,0 +1,38 @@
1
+ import type { JsonRecord } from "./commerce"
2
+
3
+ export type CheckoutPaymentMode = "online" | "bank_transfer" | "cod"
4
+
5
+ export type CheckoutPaymentChoice = {
6
+ providerId: string
7
+ mode: CheckoutPaymentMode
8
+ }
9
+
10
+ /**
11
+ * Payment options are user choices, not shipping-price conditions.
12
+ *
13
+ * Cash on delivery (pp_cod_cod) and bank transfer (pp_system_default)
14
+ * have separate Medusa provider IDs, separate sessions and separate regional
15
+ * enablement. COD eligibility and the fee are still checked by the Core
16
+ * backend; the frontend must not duplicate shipping eligibility rules.
17
+ */
18
+ export function checkoutPaymentChoices(
19
+ providers: JsonRecord[],
20
+ bankTransferEnabled: boolean,
21
+ ): CheckoutPaymentChoice[] {
22
+ const choices: CheckoutPaymentChoice[] = []
23
+ for (const provider of providers) {
24
+ const id = typeof provider.id === "string" ? provider.id : ""
25
+ if (!id) continue
26
+
27
+ if (id === "pp_cod_cod") {
28
+ choices.push({ providerId: id, mode: "cod" })
29
+ } else if (id === "pp_system_default") {
30
+ if (bankTransferEnabled) {
31
+ choices.push({ providerId: id, mode: "bank_transfer" })
32
+ }
33
+ } else {
34
+ choices.push({ providerId: id, mode: "online" })
35
+ }
36
+ }
37
+ return choices
38
+ }
@@ -0,0 +1,120 @@
1
+ import type { JsonRecord } from "./commerce"
2
+
3
+ function isRecord(value: unknown): value is JsonRecord {
4
+ return value !== null && typeof value === "object" && !Array.isArray(value)
5
+ }
6
+
7
+ function asRecords(value: unknown): JsonRecord[] {
8
+ return Array.isArray(value) ? value.filter(isRecord) : []
9
+ }
10
+
11
+ export type CheckoutAmountBreakdown = {
12
+ net: number
13
+ tax: number
14
+ gross: number
15
+ }
16
+
17
+ export type CheckoutOrderSummary = {
18
+ items: CheckoutAmountBreakdown
19
+ shipping: CheckoutAmountBreakdown | null
20
+ codGross: number | null
21
+ taxDetailsVisible: boolean
22
+ adjustment: number
23
+ grossTotal: number
24
+ }
25
+
26
+ function optionalAmount(value: unknown): number | null {
27
+ return typeof value === "number" && Number.isFinite(value) ? value : null
28
+ }
29
+
30
+ function amount(value: unknown): number {
31
+ return optionalAmount(value) ?? 0
32
+ }
33
+
34
+ function precision(currency: string): number {
35
+ return currency.toUpperCase() === "HUF" ? 0 : 2
36
+ }
37
+
38
+ function rounded(value: number, digits: number): number {
39
+ const factor = 10 ** digits
40
+ return Math.round((value + Number.EPSILON) * factor) / factor
41
+ }
42
+
43
+ function taxLinesPresent(cart: JsonRecord): boolean {
44
+ return asRecords(cart.items).some(item => asRecords(item.tax_lines).length > 0) ||
45
+ asRecords(cart.shipping_methods).some(method => asRecords(method.tax_lines).length > 0)
46
+ }
47
+
48
+ /**
49
+ * This is presentation only. Medusa owns cart.item_total, cart.shipping_total,
50
+ * their tax totals, discounts and cart.total. Never use cart.subtotal as an
51
+ * item-only figure: it also contains shipping.
52
+ *
53
+ * Core stores COD as part of the native shipping method. Its applied
54
+ * gross fee is shown separately, and the original Medusa shipping tax is
55
+ * preserved for an exact net / VAT / gross presentation.
56
+ */
57
+ export function checkoutOrderSummary(
58
+ cart: JsonRecord,
59
+ currency: string,
60
+ ): CheckoutOrderSummary {
61
+ const digits = precision(currency)
62
+ const itemGross = amount(cart.item_total)
63
+ const itemTax = amount(cart.item_tax_total)
64
+ const items = {
65
+ gross: itemGross,
66
+ tax: itemTax,
67
+ net: rounded(itemGross - itemTax, digits),
68
+ }
69
+
70
+ const methods = asRecords(cart.shipping_methods)
71
+ const hasShipping = methods.length > 0
72
+ const method = methods[0]
73
+ const data = isRecord(method?.data) ? method.data : {}
74
+ const codSelected = methods.length === 1 && (data.cod === true || data.cod === "true")
75
+ const rawFee = optionalAmount(data.hszrdm_cod_applied_fee_huf)
76
+ const shippingGrossWithCod = amount(cart.shipping_total)
77
+ const codGross = codSelected && rawFee !== null && Number.isInteger(rawFee) &&
78
+ rawFee >= 0 && rawFee <= shippingGrossWithCod
79
+ ? rawFee : codSelected ? 0 : null
80
+
81
+ const shippingTaxWithCod = amount(cart.shipping_tax_total)
82
+ const shippingGross = rounded(shippingGrossWithCod - (codGross ?? 0), digits)
83
+
84
+ // Core stores the exact native shipping tax from before the COD change,
85
+ // avoiding VAT rounding inaccuracies after the fee joins the method amount.
86
+ // Existing carts without that snapshot can still fall back to tax lines or
87
+ // Medusa's overall shipping tax ratio for a presentation-only estimate.
88
+ const baseTaxSnapshot = optionalAmount(data.hszrdm_cod_base_shipping_tax_huf)
89
+ const baseTaxValid = codGross !== null && baseTaxSnapshot !== null &&
90
+ baseTaxSnapshot >= 0 && baseTaxSnapshot <= shippingTaxWithCod
91
+ const taxLines = asRecords(method?.tax_lines)
92
+ const rates = taxLines.map(line => optionalAmount(line.rate))
93
+ const hasRates = rates.length > 0 && rates.every(rate => rate !== null && rate >= 0)
94
+ const combinedRate = hasRates ? rates.reduce<number>((sum, rate) => sum + (rate ?? 0), 0) / 100 : null
95
+ const shippingTax = baseTaxValid
96
+ ? baseTaxSnapshot
97
+ : codGross !== null && codGross > 0 && shippingGrossWithCod > 0
98
+ ? rounded(
99
+ combinedRate !== null
100
+ ? Math.min(shippingTaxWithCod, shippingGross * combinedRate / (1 + combinedRate))
101
+ : shippingTaxWithCod * shippingGross / shippingGrossWithCod,
102
+ digits,
103
+ )
104
+ : shippingTaxWithCod
105
+ const shipping = hasShipping ? {
106
+ gross: shippingGross,
107
+ tax: shippingTax,
108
+ net: rounded(shippingGross - shippingTax, digits),
109
+ } : null
110
+
111
+ const grossTotal = amount(cart.total)
112
+ // Medusa's item/shipping totals already include ordinary discounts. A
113
+ // difference can represent a credit line or another native cart adjustment.
114
+ const adjustment = rounded(grossTotal - itemGross - shippingGrossWithCod, digits)
115
+ const taxDetailsVisible =
116
+ amount(cart.tax_total) !== 0 || itemTax !== 0 || shippingTaxWithCod !== 0 ||
117
+ taxLinesPresent(cart)
118
+
119
+ return { items, shipping, codGross, taxDetailsVisible, adjustment, grossTotal }
120
+ }
@@ -69,7 +69,14 @@ export function checkoutApi(config: CoreConfig) {
69
69
  choice: "cod" | "bank_transfer" | "online" = "online",
70
70
  ) => {
71
71
  // Price authority is the backend. Never send a fee/amount from the browser.
72
- const mode = selectedProviderId.toLowerCase().includes("system") ? choice : "online"
72
+ const mode = choice === "cod" && selectedProviderId === "pp_cod_cod"
73
+ ? "cod"
74
+ : choice === "bank_transfer" && selectedProviderId === "pp_system_default"
75
+ ? "bank_transfer"
76
+ : "online"
77
+ if ((choice === "cod" || choice === "bank_transfer") && mode === "online") {
78
+ throw new Error("A kiválasztott fizetési módhoz nem megfelelő Medusa payment provider tartozik.")
79
+ }
73
80
  await medusaFetch<Record<string, unknown>>(
74
81
  `/store/carts/${encodeURIComponent(cartId)}/cod`, {
75
82
  method: "POST", body: JSON.stringify({ mode }),
@@ -216,6 +216,9 @@ export function providerLabel(
216
216
  ) {
217
217
  const normalized = id.toLowerCase()
218
218
  const english = locale.toLowerCase().startsWith("en")
219
+ if (normalized === "pp_cod_cod") {
220
+ return english ? "Cash on delivery" : "Utánvét"
221
+ }
219
222
  if (normalized.startsWith("pp_stripe_") || normalized.includes("stripe")) {
220
223
  return english ? "Card (Stripe)" : "Bankkártya (Stripe)"
221
224
  }
@@ -38,3 +38,15 @@ test("cart ownership is transferred only after email confirmation", () => {
38
38
  assert.match(dashboard, /if \(signedIn && isAccountEmailVerified\(signedIn\)\)/)
39
39
  assert.match(dashboard, /if \(updated && isAccountEmailVerified\(updated\)\)/)
40
40
  })
41
+
42
+
43
+ test("verification links are removed before login and handed to the verification panel", () => {
44
+ const dashboard = read("components/account-dashboard.tsx")
45
+ const panel = read("components/account-verification-panel.tsx")
46
+ assert.match(dashboard, /new URLSearchParams\(url\.hash\.slice\(1\)\)/)
47
+ assert.match(dashboard, /window\.history\.replaceState/)
48
+ assert.match(dashboard, /linkCode=\{verificationLink\}/)
49
+ assert.match(panel, /void confirm\(linkCode\)/)
50
+ assert.match(panel, /inFlight\.current/)
51
+ assert.doesNotMatch(dashboard, /sessionStorage|localStorage/)
52
+ })
@@ -0,0 +1,59 @@
1
+ import assert from "node:assert/strict"
2
+ import { readFileSync } from "node:fs"
3
+ import test from "node:test"
4
+ import { checkoutPaymentChoices } from "../src/lib/core/checkout-payment-choices.ts"
5
+
6
+ const stripe = { id: "pp_stripe_stripe" }
7
+ const manual = { id: "pp_system_default" }
8
+ const cod = { id: "pp_cod_cod" }
9
+ const simplepay = { id: "pp_simplepay_simplepay" }
10
+
11
+ test("COD has its own Medusa provider and is independent of bank transfer", () => {
12
+ assert.deepEqual(checkoutPaymentChoices([stripe, cod, manual], true), [
13
+ { providerId: stripe.id, mode: "online" },
14
+ { providerId: cod.id, mode: "cod" },
15
+ { providerId: manual.id, mode: "bank_transfer" },
16
+ ])
17
+ })
18
+
19
+ test("COD remains available when bank transfer is disabled or provider is absent", () => {
20
+ assert.deepEqual(checkoutPaymentChoices([cod, manual], false), [
21
+ { providerId: cod.id, mode: "cod" },
22
+ ])
23
+ assert.deepEqual(checkoutPaymentChoices([cod], true), [
24
+ { providerId: cod.id, mode: "cod" },
25
+ ])
26
+ })
27
+
28
+ test("system-only provider never offers COD without its own regional provider", () => {
29
+ assert.deepEqual(checkoutPaymentChoices([manual], true), [
30
+ { providerId: manual.id, mode: "bank_transfer" },
31
+ ])
32
+ assert.deepEqual(checkoutPaymentChoices([manual], false), [])
33
+ })
34
+
35
+ test("online providers stay unchanged and missing COD provider creates no fake COD", () => {
36
+ assert.deepEqual(checkoutPaymentChoices([stripe, simplepay], true), [
37
+ { providerId: stripe.id, mode: "online" },
38
+ { providerId: simplepay.id, mode: "online" },
39
+ ])
40
+ assert.deepEqual(checkoutPaymentChoices([], true), [])
41
+ assert.deepEqual(checkoutPaymentChoices([{ id: "" }], true), [])
42
+ })
43
+
44
+ test("Core checkout uses separate providers with backend-owned COD pricing", () => {
45
+ const flow = readFileSync(new URL("../src/components/checkout-flow.tsx", import.meta.url), "utf8")
46
+ const api = readFileSync(new URL("../src/lib/core/checkout.ts", import.meta.url), "utf8")
47
+ assert.match(flow, /checkoutPaymentChoices\(providers, config\.payments\.bank_transfer\.enabled\)/)
48
+ assert.match(flow, /paymentChoices\.map\(\(choice\) => \(/)
49
+ assert.match(flow, /preparePayment\(choice\.providerId, choice\.mode\)/)
50
+ assert.match(flow, /choice\.mode === "cod"/)
51
+ assert.doesNotMatch(flow, /\bcodAvailable\b/)
52
+ assert.doesNotMatch(flow, /hszrdm_cod_enabled/)
53
+ assert.ok(flow.includes('activeProviderId === "pp_system_default" || activeProviderId === "pp_cod_cod"'))
54
+ assert.ok(flow.includes("{offlineSelected ? ("))
55
+ assert.match(api, /selectedProviderId === "pp_cod_cod"/)
56
+ assert.match(api, /selectedProviderId === "pp_system_default"/)
57
+ assert.match(api, /\/store\/carts\/\$\{encodeURIComponent\(cartId\)\}\/cod/)
58
+ assert.match(api, /JSON\.stringify\(\{ mode \}\)/)
59
+ })
@@ -0,0 +1,168 @@
1
+ import assert from "node:assert/strict"
2
+ import { readFileSync } from "node:fs"
3
+ import test from "node:test"
4
+ import { checkoutOrderSummary } from "../src/lib/core/checkout-summary.ts"
5
+
6
+ function cart(overrides = {}) {
7
+ return {
8
+ currency_code: "huf",
9
+ item_total: 1905,
10
+ item_tax_total: 405,
11
+ shipping_total: 2000,
12
+ shipping_tax_total: 425,
13
+ tax_total: 830,
14
+ total: 3905,
15
+ subtotal: 3075, // combined net item + shipping, must never be labeled products
16
+ items: [{ id: "item_1", total: 1905, tax_total: 405 }],
17
+ shipping_methods: [{ id: "sm_1", data: {}, tax_lines: [{ rate: 27 }] }],
18
+ ...overrides,
19
+ }
20
+ }
21
+
22
+ test("uses only Medusa item totals for products; subtotal must not include shipping", () => {
23
+ const actual = checkoutOrderSummary(cart(), "HUF")
24
+ assert.equal(actual.taxDetailsVisible, true)
25
+ assert.deepEqual(actual.items, { net: 1500, tax: 405, gross: 1905 })
26
+ assert.deepEqual(actual.shipping, { net: 1575, tax: 425, gross: 2000 })
27
+ assert.equal(actual.codGross, null)
28
+ assert.equal(actual.grossTotal, 3905)
29
+ assert.equal(actual.adjustment, 0)
30
+ assert.equal(actual.items.gross + actual.shipping.gross, actual.grossTotal)
31
+ })
32
+
33
+ test("COD is a separate fixed gross row, with shipping's original net/tax/gross preserved", () => {
34
+ const withCod = cart({
35
+ shipping_total: 2350,
36
+ shipping_tax_total: 500,
37
+ tax_total: 905,
38
+ total: 4255,
39
+ shipping_methods: [{
40
+ id: "sm_1",
41
+ data: { cod: true, hszrdm_cod_applied_fee_huf: 350, hszrdm_cod_base_shipping_tax_huf: 425 },
42
+ tax_lines: [{ rate: 27 }],
43
+ }],
44
+ })
45
+ const actual = checkoutOrderSummary(withCod, "HUF")
46
+ assert.deepEqual(actual.items, { net: 1500, tax: 405, gross: 1905 })
47
+ assert.deepEqual(actual.shipping, { net: 1575, tax: 425, gross: 2000 })
48
+ assert.equal(actual.codGross, 350)
49
+ assert.equal(actual.grossTotal, 4255)
50
+ assert.equal(actual.items.gross + actual.shipping.gross + actual.codGross, actual.grossTotal)
51
+ })
52
+
53
+ test("authoritative tax snapshot stays exact even when tax lines are not expanded", () => {
54
+ const withCod = cart({
55
+ shipping_total: 2350,
56
+ shipping_tax_total: 500,
57
+ tax_total: 905,
58
+ total: 4255,
59
+ shipping_methods: [{ id: "sm_1", data: {
60
+ cod: true, hszrdm_cod_applied_fee_huf: 350, hszrdm_cod_base_shipping_tax_huf: 425,
61
+ } }],
62
+ })
63
+ const actual = checkoutOrderSummary(withCod, "HUF")
64
+ assert.deepEqual(actual.shipping, { net: 1575, tax: 425, gross: 2000 })
65
+ assert.equal(actual.codGross, 350)
66
+ })
67
+
68
+ test("COD tax is apportioned from Medusa's native tax totals without a fixed VAT rate", () => {
69
+ const withCod = cart({
70
+ shipping_total: 2350,
71
+ shipping_tax_total: 500,
72
+ tax_total: 905,
73
+ total: 4255,
74
+ shipping_methods: [{ id: "sm_1", data: { cod: true, hszrdm_cod_applied_fee_huf: 350 } }],
75
+ })
76
+ const actual = checkoutOrderSummary(withCod, "HUF")
77
+ assert.equal(actual.shipping.gross, 2000)
78
+ assert.equal(actual.shipping.net + actual.shipping.tax, 2000)
79
+ assert.equal(actual.codGross, 350)
80
+ assert.equal(actual.grossTotal, 4255)
81
+ assert.equal(actual.items.gross + actual.shipping.gross + actual.codGross, actual.grossTotal)
82
+ })
83
+
84
+ test("VAT rows are omitted if the cart has no tax amounts or tax lines", () => {
85
+ const withoutTax = cart({
86
+ item_total: 1500,
87
+ item_tax_total: 0,
88
+ shipping_total: 1000,
89
+ shipping_tax_total: 0,
90
+ tax_total: 0,
91
+ total: 2500,
92
+ items: [{ id: "item_1", total: 1500, tax_total: 0 }],
93
+ shipping_methods: [{ id: "sm_1", data: {} }],
94
+ })
95
+ const actual = checkoutOrderSummary(withoutTax, "HUF")
96
+ assert.equal(actual.taxDetailsVisible, false)
97
+ assert.deepEqual(actual.items, { net: 1500, tax: 0, gross: 1500 })
98
+ assert.deepEqual(actual.shipping, { net: 1000, tax: 0, gross: 1000 })
99
+ })
100
+
101
+ test("keeps zero-tax tax lines visible and zero-fee COD as a separate row", () => {
102
+ const zero = cart({
103
+ item_total: 1500,
104
+ item_tax_total: 0,
105
+ shipping_total: 1000,
106
+ shipping_tax_total: 0,
107
+ tax_total: 0,
108
+ total: 2500,
109
+ items: [{ id: "item_1", tax_lines: [{ rate: 0 }] }],
110
+ shipping_methods: [{
111
+ id: "sm_1",
112
+ data: { cod: true, hszrdm_cod_applied_fee_huf: 0 },
113
+ tax_lines: [{ rate: 0 }],
114
+ }],
115
+ })
116
+ const actual = checkoutOrderSummary(zero, "HUF")
117
+ assert.equal(actual.taxDetailsVisible, true)
118
+ assert.equal(actual.codGross, 0)
119
+ assert.equal(actual.shipping.gross, 1000)
120
+ })
121
+
122
+ test("discounted item totals and native credit lines are not charged twice", () => {
123
+ const credited = cart({
124
+ item_total: 1800,
125
+ item_tax_total: 383,
126
+ shipping_total: 2000,
127
+ shipping_tax_total: 425,
128
+ tax_total: 808,
129
+ total: 3400,
130
+ subtotal: 9000,
131
+ })
132
+ const actual = checkoutOrderSummary(credited, "HUF")
133
+ assert.equal(actual.items.gross, 1800)
134
+ assert.equal(actual.adjustment, -400)
135
+ assert.equal(actual.items.gross + actual.shipping.gross + actual.adjustment, actual.grossTotal)
136
+ })
137
+
138
+ test("no selected shipping remains unselected, not a fabricated zero-cost delivery", () => {
139
+ const noShipping = cart({
140
+ shipping_total: 0,
141
+ shipping_tax_total: 0,
142
+ tax_total: 405,
143
+ total: 1905,
144
+ shipping_methods: [],
145
+ })
146
+ const actual = checkoutOrderSummary(noShipping, "HUF")
147
+ assert.equal(actual.shipping, null)
148
+ assert.equal(actual.codGross, null)
149
+ assert.equal(actual.grossTotal, 1905)
150
+ })
151
+
152
+ test("Core starter summary renders tax groups, COD and the Medusa gross total", () => {
153
+ const flow = readFileSync(new URL("../src/components/checkout-flow.tsx", import.meta.url), "utf8")
154
+ const style = readFileSync(new URL("../src/app/globals.css", import.meta.url), "utf8")
155
+ assert.match(flow, /checkoutOrderSummary\(cart, currency\)/)
156
+ assert.match(flow, /orderSummary\.taxDetailsVisible/)
157
+ assert.match(flow, /orderSummary\.items\.net/)
158
+ assert.match(flow, /orderSummary\.items\.tax/)
159
+ assert.match(flow, /orderSummary\.items\.gross/)
160
+ assert.match(flow, /orderSummary\.shipping\.net/)
161
+ assert.match(flow, /orderSummary\.shipping\.tax/)
162
+ assert.match(flow, /orderSummary\.shipping\.gross/)
163
+ assert.match(flow, /orderSummary\.codGross !== null/)
164
+ assert.match(flow, /Bruttó végösszeg/)
165
+ assert.match(style, /\.checkout-summary-group/)
166
+ assert.doesNotMatch(flow, /Ebből utánvét kezelési díj/)
167
+ assert.doesNotMatch(flow, /cartSubtotal\(cart\)/)
168
+ })