@hszrdm/create-commerce 1.19.0 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/package.json +1 -1
  2. package/src/cli.mjs +2 -1
  3. package/templates/backend/.env.example +33 -217
  4. package/templates/backend/medusa-config.ts +14 -1
  5. package/templates/backend/package.json +1 -1
  6. package/templates/backend/src/scripts/core-init.ts +0 -5
  7. package/templates/storefront/package.json +5 -1
  8. package/templates/storefront/src/app/[countryCode]/products/[handle]/page.tsx +2 -2
  9. package/templates/storefront/src/app/globals.css +8 -0
  10. package/templates/storefront/src/app/layout.tsx +6 -0
  11. package/templates/storefront/src/components/account-access-gate.tsx +88 -0
  12. package/templates/storefront/src/components/account-dashboard.tsx +56 -19
  13. package/templates/storefront/src/components/account-verification-panel.tsx +145 -0
  14. package/templates/storefront/src/components/checkout-flow.tsx +83 -30
  15. package/templates/storefront/src/components/product-card.tsx +2 -1
  16. package/templates/storefront/src/lib/core/account.ts +49 -8
  17. package/templates/storefront/src/lib/core/checkout-feedback-state.ts +15 -0
  18. package/templates/storefront/src/lib/core/checkout-payment-choices.ts +38 -0
  19. package/templates/storefront/src/lib/core/checkout-summary.ts +120 -0
  20. package/templates/storefront/src/lib/core/checkout.ts +25 -19
  21. package/templates/storefront/src/lib/core/commerce.ts +14 -0
  22. package/templates/storefront/src/lib/core/use-checkout-feedback.ts +53 -0
  23. package/templates/storefront/tests/account-verification.test.mjs +40 -0
  24. package/templates/storefront/tests/checkout-feedback.test.mjs +27 -0
  25. package/templates/storefront/tests/checkout-payment-choices.test.mjs +59 -0
  26. package/templates/storefront/tests/checkout-summary.test.mjs +168 -0
  27. package/templates/storefront/tests/product-image.test.mjs +31 -0
@@ -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
+ }
@@ -10,7 +10,6 @@ import {
10
10
  import {
11
11
  asRecords,
12
12
  isRecord,
13
- shippingMethodIsCod,
14
13
  stringValue,
15
14
  } from "./commerce"
16
15
  import type { CoreConfig } from "./types"
@@ -65,26 +64,33 @@ export function checkoutApi(config: CoreConfig) {
65
64
  { method: "POST", body: JSON.stringify({ provider_id: providerId }) },
66
65
  )
67
66
 
68
- const markPaymentMode = async (cartId: string, selectedProviderId: string) => {
69
- const current = (await getCart(cartId)).cart
70
- const metadata = isRecord(current.metadata) ? current.metadata : {}
71
- const systemProvider = selectedProviderId.toLowerCase().includes("system")
72
- let marker = "online"
73
-
74
- if (systemProvider && shippingMethodIsCod(current)) {
75
- marker = "cod"
76
- } else if (systemProvider && config.payments.bank_transfer.enabled) {
67
+ const markPaymentMode = async (
68
+ cartId: string, selectedProviderId: string,
69
+ choice: "cod" | "bank_transfer" | "online" = "online",
70
+ ) => {
71
+ // Price authority is the backend. Never send a fee/amount from the browser.
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
+ }
80
+ await medusaFetch<Record<string, unknown>>(
81
+ `/store/carts/${encodeURIComponent(cartId)}/cod`, {
82
+ method: "POST", body: JSON.stringify({ mode }),
83
+ },
84
+ )
85
+ if (mode === "bank_transfer" && config.payments.bank_transfer.enabled) {
86
+ const current = (await getCart(cartId)).cart
87
+ const metadata = isRecord(current.metadata) ? current.metadata : {}
77
88
  const details = await bankTransferDetails()
78
89
  const configured = isRecord(details.cart_metadata) ? details.cart_metadata : {}
79
- await updateCart(cartId, { metadata: { ...metadata, ...configured } })
80
- return
81
- } else if (systemProvider) {
82
- marker = "manual"
90
+ await updateCart(cartId, {
91
+ metadata: { ...metadata, ...configured, core_payment_method: "bank_transfer" },
92
+ })
83
93
  }
84
-
85
- await updateCart(cartId, {
86
- metadata: { ...metadata, core_payment_method: marker },
87
- })
88
94
  }
89
95
 
90
96
  const saveFoxpostSelection = (
@@ -177,6 +183,7 @@ export function checkoutApi(config: CoreConfig) {
177
183
  },
178
184
 
179
185
  updateCart,
186
+ markPaymentMode,
180
187
 
181
188
  saveBillingTaxDetails: (cartId: string, data: {
182
189
  is_company: boolean
@@ -346,7 +353,6 @@ export function checkoutApi(config: CoreConfig) {
346
353
  paymentCollectionId: string,
347
354
  selectedProviderId: string,
348
355
  ) => {
349
- await markPaymentMode(cartId, selectedProviderId)
350
356
  const result = await initializePaymentSession(paymentCollectionId, selectedProviderId)
351
357
  const { cart } = await getCart(cartId)
352
358
  trackPaymentInfo(config.analytics, cart, selectedProviderId)
@@ -22,6 +22,17 @@ export function stringValue(value: unknown) {
22
22
  return typeof value === "string" ? value : value == null ? "" : String(value)
23
23
  }
24
24
 
25
+ /** Product hero and card image: prefer thumbnail, then the first usable gallery image. */
26
+ export function productImageUrl(product: JsonRecord | null | undefined): string {
27
+ const thumbnail = stringValue(product?.thumbnail).trim()
28
+ if (thumbnail) return thumbnail
29
+ for (const image of asRecords(product?.images)) {
30
+ const url = stringValue(image.url).trim()
31
+ if (url) return url
32
+ }
33
+ return ""
34
+ }
35
+
25
36
  export function numberValue(value: unknown, fallback = 0) {
26
37
  const number = typeof value === "number" ? value : Number(value)
27
38
  return Number.isFinite(number) ? number : fallback
@@ -205,6 +216,9 @@ export function providerLabel(
205
216
  ) {
206
217
  const normalized = id.toLowerCase()
207
218
  const english = locale.toLowerCase().startsWith("en")
219
+ if (normalized === "pp_cod_cod") {
220
+ return english ? "Cash on delivery" : "Utánvét"
221
+ }
208
222
  if (normalized.startsWith("pp_stripe_") || normalized.includes("stripe")) {
209
223
  return english ? "Card (Stripe)" : "Bankkártya (Stripe)"
210
224
  }
@@ -0,0 +1,53 @@
1
+ "use client"
2
+
3
+ import { useCallback, useEffect, useRef, useState } from "react"
4
+ import { useToast } from "@/components/toast-provider"
5
+ import {
6
+ checkoutErrorMessage,
7
+ checkoutNoticeMessage,
8
+ shouldShowCheckoutNotice,
9
+ } from "@/lib/core/checkout-feedback-state"
10
+
11
+ /**
12
+ * Common Core checkout notification bridge.
13
+ * Keep the existing inline field validation and payment retry UI; only
14
+ * transient checkout errors/success messages are mirrored into toast notices.
15
+ */
16
+ export function useCheckoutFeedback(cartError?: string | null) {
17
+ const { showToast } = useToast()
18
+ const [error, setError] = useState<string | null>(null)
19
+ const [message, setMessage] = useState<string | null>(null)
20
+ const lastError = useRef<string | null>(null)
21
+ const lastMessage = useRef<string | null>(null)
22
+
23
+ const activeError = checkoutErrorMessage(error, cartError)
24
+ const activeMessage = checkoutNoticeMessage(message)
25
+
26
+ useEffect(() => {
27
+ if (!activeError) {
28
+ lastError.current = null
29
+ return
30
+ }
31
+ if (!shouldShowCheckoutNotice(lastError.current, activeError)) return
32
+ lastError.current = activeError
33
+ showToast({ tone: "error", message: activeError, durationMs: 7000 })
34
+ }, [activeError, showToast])
35
+
36
+ useEffect(() => {
37
+ if (!activeMessage) {
38
+ lastMessage.current = null
39
+ return
40
+ }
41
+ if (!shouldShowCheckoutNotice(lastMessage.current, activeMessage)) return
42
+ lastMessage.current = activeMessage
43
+ showToast({ tone: "success", message: activeMessage, durationMs: 7000 })
44
+ }, [activeMessage, showToast])
45
+
46
+ // Form-wide errors that do not need to persist as checkout state.
47
+ const notifyError = useCallback((text: string) => {
48
+ const next = checkoutNoticeMessage(text)
49
+ if (next) showToast({ tone: "error", message: next, durationMs: 7000 })
50
+ }, [showToast])
51
+
52
+ return { error, setError, message, setMessage, notifyError }
53
+ }
@@ -0,0 +1,40 @@
1
+ import assert from "node:assert/strict"
2
+ import { readFileSync } from "node:fs"
3
+ import { join } from "node:path"
4
+ import test from "node:test"
5
+ import { fileURLToPath } from "node:url"
6
+
7
+ // Resolve relative to the test file, not process.cwd(): this test is copied
8
+ // into the create-commerce template and also runs from the generator root.
9
+ const srcDir = fileURLToPath(new URL("../src/", import.meta.url))
10
+ const read = (file) => readFileSync(join(srcDir, file), "utf8")
11
+
12
+ test("account requires verified email and retains one shared Core verification API", () => {
13
+ const account = read("lib/core/account.ts")
14
+ const dashboard = read("components/account-dashboard.tsx")
15
+ const gate = read("components/account-access-gate.tsx")
16
+ const panel = read("components/account-verification-panel.tsx")
17
+
18
+ assert.match(account, /isAccountEmailVerified/)
19
+ assert.match(account, /email_verified_address/)
20
+ assert.match(account, /emailVerificationStatus/)
21
+ assert.match(account, /requestEmailVerification/)
22
+ assert.match(account, /confirmEmailVerification/)
23
+ assert.match(dashboard, /if \(!isAccountEmailVerified\(customer\)\)/)
24
+ assert.match(dashboard, /AccountVerificationPanel/)
25
+ assert.match(gate, /router\.replace\("\/account"\)/)
26
+ assert.match(gate, /state === "unverified"/)
27
+ assert.match(panel, /retry_after_seconds/)
28
+ assert.match(panel, /resend_available_at/)
29
+ assert.match(panel, /retrySeconds > 0/)
30
+ assert.match(panel, /onLogout/)
31
+ assert.match(panel, /onVerified/)
32
+ assert.doesNotMatch(panel, /localStorage|sessionStorage/)
33
+ })
34
+
35
+ test("cart ownership is transferred only after email confirmation", () => {
36
+ const dashboard = read("components/account-dashboard.tsx")
37
+ assert.match(dashboard, /if \(registered\.customer && isAccountEmailVerified\(registered\.customer\)\)/)
38
+ assert.match(dashboard, /if \(signedIn && isAccountEmailVerified\(signedIn\)\)/)
39
+ assert.match(dashboard, /if \(updated && isAccountEmailVerified\(updated\)\)/)
40
+ })
@@ -0,0 +1,27 @@
1
+ import test from "node:test"
2
+ import assert from "node:assert/strict"
3
+ import {
4
+ checkoutErrorMessage,
5
+ checkoutNoticeMessage,
6
+ shouldShowCheckoutNotice,
7
+ } from "../src/lib/core/checkout-feedback-state.ts"
8
+
9
+ test("checkout feedback prioritizes the local error over cart errors", () => {
10
+ assert.equal(checkoutErrorMessage("Form error", "Cart error"), "Form error")
11
+ assert.equal(checkoutErrorMessage(null, "Cart error"), "Cart error")
12
+ assert.equal(checkoutErrorMessage(" ", "Cart error"), "Cart error")
13
+ assert.equal(checkoutErrorMessage("", null), null)
14
+ })
15
+
16
+ test("checkout feedback ignores blank messages and normalizes whitespace", () => {
17
+ assert.equal(checkoutNoticeMessage(" Saved! "), "Saved!")
18
+ assert.equal(checkoutNoticeMessage(" "), null)
19
+ assert.equal(checkoutNoticeMessage(undefined), null)
20
+ })
21
+
22
+ test("checkout feedback does not repeat unchanged, empty notices", () => {
23
+ assert.equal(shouldShowCheckoutNotice(null, "Saved"), true)
24
+ assert.equal(shouldShowCheckoutNotice("Saved", "Saved"), false)
25
+ assert.equal(shouldShowCheckoutNotice("Saved", "Error"), true)
26
+ assert.equal(shouldShowCheckoutNotice(null, null), false)
27
+ })
@@ -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
+ })
@@ -0,0 +1,31 @@
1
+ import assert from "node:assert/strict"
2
+ import { readFileSync } from "node:fs"
3
+ import test from "node:test"
4
+ import { productImageUrl } from "../src/lib/core/commerce.ts"
5
+
6
+ test("a configured thumbnail takes precedence over gallery images", () => {
7
+ assert.equal(productImageUrl({
8
+ thumbnail: "https://example.com/primary.webp",
9
+ images: [{ url: "https://example.com/gallery.webp" }],
10
+ }), "https://example.com/primary.webp")
11
+ })
12
+
13
+ test("a product with no thumbnail uses its first usable gallery image", () => {
14
+ assert.equal(productImageUrl({
15
+ thumbnail: null,
16
+ images: [{ url: "" }, { url: " https://example.com/gallery.webp " }],
17
+ }), "https://example.com/gallery.webp")
18
+ })
19
+
20
+ test("missing, empty or malformed image data stays an empty image", () => {
21
+ assert.equal(productImageUrl({ images: [{ invalid: "x" }] }), "")
22
+ assert.equal(productImageUrl({ thumbnail: " ", images: null }), "")
23
+ assert.equal(productImageUrl(null), "")
24
+ })
25
+
26
+ test("catalog cards and product details share the fallback resolver", () => {
27
+ const card = readFileSync(new URL("../src/components/product-card.tsx", import.meta.url), "utf8")
28
+ const detail = readFileSync(new URL("../src/app/[countryCode]/products/[handle]/page.tsx", import.meta.url), "utf8")
29
+ assert.match(card, /const thumbnail = productImageUrl\(product\)/)
30
+ assert.match(detail, /const thumbnail = productImageUrl\(product\)/)
31
+ })