@hszrdm/create-commerce 1.10.1 → 1.11.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 (36) hide show
  1. package/package.json +1 -1
  2. package/src/cli.mjs +18 -3
  3. package/src/upgrade.mjs +39 -3
  4. package/templates/backend/.env.example +8 -0
  5. package/templates/backend/package.json +1 -1
  6. package/templates/backend/scripts/commerce-instance-status.mjs +135 -0
  7. package/templates/backend/scripts/commerce-ops.mjs +58 -2
  8. package/templates/backend/scripts/core-restore.mjs +40 -5
  9. package/templates/backend/scripts/lib/core-backup-common.mjs +91 -11
  10. package/templates/backend/scripts/production-assets/backup.sh +6 -51
  11. package/templates/backend/scripts/production-assets/deploy.sh +10 -62
  12. package/templates/backend/scripts/production-assets/install.sh +23 -195
  13. package/templates/backend/scripts/production-assets/restore.sh +17 -66
  14. package/templates/storefront/package.json +5 -1
  15. package/templates/storefront/src/app/checkout/success/page.tsx +2 -0
  16. package/templates/storefront/src/app/globals.css +32 -0
  17. package/templates/storefront/src/app/layout.tsx +7 -1
  18. package/templates/storefront/src/app/legal/page.tsx +3 -3
  19. package/templates/storefront/src/components/analytics.tsx +10 -8
  20. package/templates/storefront/src/components/checkout-flow.tsx +539 -75
  21. package/templates/storefront/src/components/fogyasztobarat-embed.tsx +6 -2
  22. package/templates/storefront/src/components/google-analytics-purchase.tsx +33 -0
  23. package/templates/storefront/src/components/stripe-payment.tsx +186 -62
  24. package/templates/storefront/src/lib/core/checkout-addresses.ts +166 -0
  25. package/templates/storefront/src/lib/core/checkout.ts +12 -0
  26. package/templates/storefront/src/lib/core/commerce.ts +12 -2
  27. package/templates/storefront/src/lib/core/company-tax.ts +132 -0
  28. package/templates/storefront/src/lib/core/ga4-bootstrap.ts +35 -0
  29. package/templates/storefront/src/lib/core/legal.ts +1 -0
  30. package/templates/storefront/src/lib/core/public-error.ts +1 -0
  31. package/templates/storefront/src/lib/core/stripe-checkout-phase.ts +23 -0
  32. package/templates/storefront/src/lib/core/tracking.ts +11 -2
  33. package/templates/storefront/tests/checkout-addresses.test.mjs +148 -0
  34. package/templates/storefront/tests/company-tax.test.mjs +68 -0
  35. package/templates/storefront/tests/ga4-bootstrap.test.mjs +74 -0
  36. package/templates/storefront/tests/stripe-checkout-phase.test.mjs +92 -0
@@ -11,20 +11,24 @@ export function FogyasztobaratEmbed({ embed }: { embed: LegalEmbedConfig }) {
11
11
  if (!host || !embed.enabled || embed.provider !== "fogyasztobarat") return
12
12
  const scriptUrl = String(embed.scriptUrl || "").trim()
13
13
  const dataId = String(embed.dataId || "").trim()
14
- if (!scriptUrl.startsWith("https://admin.fogyasztobarat.hu/") || !dataId) return
14
+ if (!["https://admin.fogyasztobarat.hu/e-api.js", "https://admin.fogyasztobarat.hu/h-api.js"].includes(scriptUrl) || !dataId) return
15
15
 
16
16
  const script = document.createElement("script")
17
+ script.id = "fbarat-embed"
17
18
  script.src = scriptUrl
18
19
  script.async = true
19
20
  script.dataset.id = dataId
20
21
  script.dataset.type = String(embed.dataType || "def")
22
+ script.onerror = () => {
23
+ console.warn("[Fogyasztó Barát] A szolgáltató beillesztőkódja nem tölthető be.")
24
+ }
21
25
  host.appendChild(script)
22
26
 
23
27
  return () => {
24
28
  script.remove()
25
29
  host.replaceChildren()
26
30
  }
27
- }, [embed])
31
+ }, [embed.enabled, embed.provider, embed.scriptUrl, embed.dataId, embed.dataType])
28
32
 
29
33
  if (!embed.enabled || embed.provider !== "fogyasztobarat") return null
30
34
 
@@ -0,0 +1,33 @@
1
+ "use client"
2
+
3
+ import { useEffect } from "react"
4
+ import { COOKIE_CONSENT_EVENT } from "@/lib/core/consent"
5
+ import { trackPurchase } from "@/lib/core/tracking"
6
+ import type { CoreConfig } from "@/lib/core/types"
7
+
8
+ /**
9
+ * The success page can be reached after Stripe/SimplePay redirects or a
10
+ * server-completed order. Replay the canonical purchase event even if the
11
+ * checkout complete() response was not observed by this browser.
12
+ *
13
+ * The tracker deduplicates Google purchase events by order ID in localStorage,
14
+ * and the first-party event has a stable server-side event_key.
15
+ */
16
+ export function GoogleAnalyticsPurchase({
17
+ analytics,
18
+ order,
19
+ }: {
20
+ analytics: CoreConfig["analytics"]
21
+ order: Record<string, unknown>
22
+ }) {
23
+ useEffect(() => {
24
+ const send = () => { trackPurchase(analytics, order) }
25
+ send()
26
+ // If consent is granted only on the thank-you page, still measure purchase
27
+ // exactly once in GA4. A declined preference never sends to Google.
28
+ window.addEventListener(COOKIE_CONSENT_EVENT, send)
29
+ return () => window.removeEventListener(COOKIE_CONSENT_EVENT, send)
30
+ }, [analytics, order])
31
+
32
+ return null
33
+ }
@@ -1,15 +1,18 @@
1
1
  "use client"
2
2
 
3
- import { useMemo, useRef, useState } from "react"
3
+ import { useEffect, useMemo, useRef, useState } from "react"
4
4
  import { usePathname } from "next/navigation"
5
5
  import { Elements, ExpressCheckoutElement, PaymentElement, useElements, useStripe } from "@stripe/react-stripe-js"
6
6
  import { loadStripe } from "@stripe/stripe-js/pure"
7
- import { localeFromPathname, STOREFRONT_ROUTES } from "@/lib/storefront-routes"
7
+ import type { Stripe } from "@stripe/stripe-js"
8
+ import { localeFromPathname, STOREFRONT_ROUTES, type StorefrontLocale } from "@/lib/storefront-routes"
8
9
  import { CoreApiError } from "@/lib/core/client"
9
10
  import { stripePublicError } from "@/lib/core/public-error"
10
11
 
11
12
  class CustomerPaymentError extends Error {}
12
13
 
14
+ type StripeLoadStatus = "loading" | "ready" | "error"
15
+
13
16
  export function StripePayment({
14
17
  publishableKey,
15
18
  clientSecret,
@@ -25,40 +28,131 @@ export function StripePayment({
25
28
  beforeConfirm?: () => Promise<void>
26
29
  onConfirmed: () => Promise<void>
27
30
  }) {
28
- const stripePromise = useMemo(() => loadStripe(publishableKey), [publishableKey])
31
+ const pathname = usePathname()
32
+ const locale = localeFromPathname(pathname)
33
+ const [attempt, setAttempt] = useState(0)
34
+ const [stripeInstance, setStripeInstance] = useState<Stripe | null>(null)
35
+ const [sdkStatus, setSdkStatus] = useState<StripeLoadStatus>("loading")
36
+ const [elementReady, setElementReady] = useState(false)
37
+ const [initializationError, setInitializationError] = useState<string | null>(null)
38
+ const options = useMemo(() => ({ clientSecret, loader: "auto" as const }), [clientSecret])
39
+
40
+ useEffect(() => {
41
+ let active = true
42
+ setStripeInstance(null)
43
+ setSdkStatus("loading")
44
+ setElementReady(false)
45
+ setInitializationError(null)
46
+
47
+ // Resolve Stripe.js explicitly: rendering Elements while the SDK and
48
+ // Payment Element are pending must not look like a missing client_secret.
49
+ void loadStripe(publishableKey)
50
+ .then((loaded) => {
51
+ if (!active) return
52
+ if (!loaded) {
53
+ setSdkStatus("error")
54
+ setInitializationError(localized(locale,
55
+ "A Stripe fizetési felülete nem tölthető be. Ellenőrizd az internetkapcsolatot.",
56
+ "The Stripe payment form could not load. Check your connection."))
57
+ return
58
+ }
59
+ setStripeInstance(loaded)
60
+ setSdkStatus("ready")
61
+ })
62
+ .catch(() => {
63
+ if (!active) return
64
+ setSdkStatus("error")
65
+ setInitializationError(localized(locale,
66
+ "A Stripe fizetési felülete nem tölthető be. Ellenőrizd az internetkapcsolatot.",
67
+ "The Stripe payment form could not load. Check your connection."))
68
+ })
69
+
70
+ return () => { active = false }
71
+ }, [attempt, locale, publishableKey])
72
+
73
+ const retry = () => {
74
+ setStripeInstance(null)
75
+ setSdkStatus("loading")
76
+ setElementReady(false)
77
+ setInitializationError(null)
78
+ setAttempt(previous => previous + 1)
79
+ }
80
+
81
+ if (sdkStatus === "error" || initializationError) {
82
+ return (
83
+ <div className="stack-sm">
84
+ <div className="notice error-box" role="alert">
85
+ {initializationError || localized(locale,
86
+ "A Stripe fizetési felülete nem indítható.", "The Stripe payment form could not start.")}
87
+ </div>
88
+ <button className="button secondary" type="button" onClick={retry}>
89
+ {localized(locale, "Stripe betöltésének újrapróbálása", "Retry loading Stripe")}
90
+ </button>
91
+ </div>
92
+ )
93
+ }
94
+
95
+ if (sdkStatus !== "ready" || !stripeInstance) {
96
+ return <StripeLoading locale={locale} />
97
+ }
98
+
29
99
  return (
30
- <Elements stripe={stripePromise} options={{ clientSecret }}>
100
+ <Elements key={attempt} stripe={stripeInstance} options={options}>
31
101
  <StripePaymentForm
32
102
  cartId={cartId}
33
103
  disabled={disabled}
34
104
  beforeConfirm={beforeConfirm}
35
105
  onConfirmed={onConfirmed}
106
+ elementReady={elementReady}
107
+ onPaymentReady={() => setElementReady(true)}
108
+ onPaymentError={(message) => {
109
+ setElementReady(false)
110
+ setInitializationError(message)
111
+ }}
112
+ locale={locale}
36
113
  />
37
114
  </Elements>
38
115
  )
39
116
  }
40
117
 
118
+ function StripeLoading({ locale }: { locale: StorefrontLocale }) {
119
+ return (
120
+ <div className="stripe-payment-loading" role="status" aria-live="polite" aria-busy="true">
121
+ <span className="stripe-loading-spinner" aria-hidden="true" />
122
+ <span>{localized(locale,
123
+ "Biztonságos kártyás fizetés betöltése…", "Loading secure card payment…")}</span>
124
+ </div>
125
+ )
126
+ }
127
+
41
128
  function StripePaymentForm({
42
129
  cartId,
43
130
  disabled,
44
131
  beforeConfirm,
45
132
  onConfirmed,
133
+ elementReady,
134
+ onPaymentReady,
135
+ onPaymentError,
136
+ locale,
46
137
  }: {
47
138
  cartId: string
48
139
  disabled: boolean
49
140
  beforeConfirm?: () => Promise<void>
50
141
  onConfirmed: () => Promise<void>
142
+ elementReady: boolean
143
+ onPaymentReady: () => void
144
+ onPaymentError: (message: string) => void
145
+ locale: StorefrontLocale
51
146
  }) {
52
147
  const stripe = useStripe()
53
148
  const elements = useElements()
54
- const pathname = usePathname()
55
- const locale = localeFromPathname(pathname)
56
149
  const checkoutPath = STOREFRONT_ROUTES[locale].checkout
57
150
  const [busy, setBusy] = useState(false)
58
151
  const [error, setError] = useState<string | null>(null)
59
152
  const [walletAvailable, setWalletAvailable] = useState(false)
60
153
  const [revolutSelected, setRevolutSelected] = useState(false)
61
154
  const paymentSection = useRef<HTMLDivElement>(null)
155
+ const ready = Boolean(stripe && elements && elementReady)
62
156
 
63
157
  const returnUrl = () => {
64
158
  const url = new URL(checkoutPath, window.location.origin)
@@ -68,7 +162,7 @@ function StripePaymentForm({
68
162
  }
69
163
 
70
164
  const confirmWallet = async () => {
71
- if (!stripe || !elements || disabled || busy) return
165
+ if (!ready || !stripe || !elements || disabled || busy) return
72
166
  setBusy(true)
73
167
  setError(null)
74
168
  try {
@@ -98,7 +192,7 @@ function StripePaymentForm({
98
192
  }
99
193
 
100
194
  const submit = async () => {
101
- if (!stripe || !elements || disabled) return
195
+ if (!ready || !stripe || !elements || disabled || busy) return
102
196
  setBusy(true)
103
197
  setError(null)
104
198
  try {
@@ -110,7 +204,7 @@ function StripePaymentForm({
110
204
  confirmParams: { return_url: returnUrl() },
111
205
  })
112
206
  if (result.error) {
113
- throw new Error(stripePublicError(result.error, locale))
207
+ throw new CustomerPaymentError(stripePublicError(result.error, locale))
114
208
  }
115
209
  await onConfirmed()
116
210
  } catch (cause) {
@@ -124,62 +218,92 @@ function StripePaymentForm({
124
218
  }
125
219
 
126
220
  return (
127
- <div className="stack-sm">
128
- <div className="stack-sm">
129
- <strong>{locale === "en" ? "Express payment" : "Gyorsfizetés"}</strong>
130
- <div
131
- style={{ display: "grid", gridTemplateColumns: walletAvailable ? "minmax(0, 2fr) minmax(0, 1fr)" : "1fr", gap: 10 }}
132
- >
133
- <div style={{ minWidth: 0 }}>
134
- <ExpressCheckoutElement
135
- options={{
136
- paymentMethods: {
137
- applePay: "auto",
138
- googlePay: "auto",
139
- link: "never",
140
- amazonPay: "never",
141
- paypal: "never",
142
- klarna: "never",
143
- },
144
- layout: { maxColumns: 2, maxRows: 1 },
145
- buttonHeight: 48,
146
- }}
147
- onReady={(event) => setWalletAvailable(
148
- Boolean(event.availablePaymentMethods?.applePay || event.availablePaymentMethods?.googlePay),
149
- )}
150
- onConfirm={() => void confirmWallet()}
151
- />
152
- </div>
153
- <button
154
- type="button"
155
- className="button secondary"
156
- disabled={disabled || busy}
157
- onClick={chooseRevolut}
158
- style={{ minHeight: 48, width: "100%" }}
221
+ <div className="stripe-payment-stage stack-sm">
222
+ {!ready ? <StripeLoading locale={locale} /> : null}
223
+ {/*
224
+ Stripe PaymentElement must stay mounted for onReady and confirmPayment.
225
+ Never conditionally remove it while waiting: conceal the iframe with an
226
+ overlay instead of display:none or unmounting it during confirmation.
227
+ */}
228
+ <div
229
+ className="stripe-payment-fields"
230
+ aria-hidden={!ready}
231
+ style={!ready ? {
232
+ opacity: 0,
233
+ pointerEvents: "none",
234
+ position: "absolute",
235
+ inset: 0,
236
+ width: "100%",
237
+ } : undefined}
238
+ >
239
+ <div className="stack-sm">
240
+ <strong>{locale === "en" ? "Express payment" : "Gyorsfizetés"}</strong>
241
+ <div
242
+ style={{ display: "grid", gridTemplateColumns: walletAvailable ? "minmax(0, 2fr) minmax(0, 1fr)" : "1fr", gap: 10 }}
159
243
  >
160
- Revolut Pay
161
- </button>
244
+ <div style={{ minWidth: 0 }}>
245
+ <ExpressCheckoutElement
246
+ options={{
247
+ paymentMethods: {
248
+ applePay: "auto",
249
+ googlePay: "auto",
250
+ link: "never",
251
+ amazonPay: "never",
252
+ paypal: "never",
253
+ klarna: "never",
254
+ },
255
+ layout: { maxColumns: 2, maxRows: 1 },
256
+ buttonHeight: 48,
257
+ }}
258
+ onReady={(event) => setWalletAvailable(
259
+ Boolean(event.availablePaymentMethods?.applePay || event.availablePaymentMethods?.googlePay),
260
+ )}
261
+ onLoadError={() => setWalletAvailable(false)}
262
+ onConfirm={() => void confirmWallet()}
263
+ />
264
+ </div>
265
+ <button
266
+ type="button"
267
+ className="button secondary"
268
+ disabled={!ready || disabled || busy}
269
+ onClick={chooseRevolut}
270
+ style={{ minHeight: 48, width: "100%" }}
271
+ >
272
+ Revolut Pay
273
+ </button>
274
+ </div>
275
+ {revolutSelected ? (
276
+ <p className="muted" role="status">
277
+ {locale === "en"
278
+ ? "Select Revolut Pay in the Stripe payment methods below. Availability depends on the merchant's enabled methods."
279
+ : "A lenti Stripe fizetési módok között válaszd a Revolut Payt. Csak akkor jelenik meg, ha a kereskedő Stripe-fiókjában elérhető és engedélyezett."}
280
+ </p>
281
+ ) : null}
282
+ </div>
283
+ <div ref={paymentSection} className="stripe-element">
284
+ <PaymentElement
285
+ onReady={onPaymentReady}
286
+ onLoadError={() => onPaymentError(localized(locale,
287
+ "A Stripe kártyamezők nem tölthetők be. Próbáld újra.",
288
+ "The Stripe payment fields could not load. Please try again."))}
289
+ />
162
290
  </div>
163
- {revolutSelected ? (
164
- <p className="muted" role="status">
165
- {locale === "en"
166
- ? "Select Revolut Pay in the Stripe payment methods below. Availability depends on the merchant's enabled methods."
167
- : "A lenti Stripe fizetési módok között válaszd a Revolut Payt. Csak akkor jelenik meg, ha a kereskedő Stripe-fiókjában elérhető és engedélyezett."}
168
- </p>
169
- ) : null}
291
+ {error ? <p className="error" role="alert">{error}</p> : null}
292
+ <button
293
+ className="button button-large"
294
+ type="button"
295
+ disabled={!ready || disabled || busy}
296
+ onClick={() => void submit()}
297
+ >
298
+ {busy
299
+ ? locale === "en" ? "Processing payment…" : "Fizetés feldolgozása…"
300
+ : locale === "en" ? "Pay by card" : "Fizetés bankkártyával"}
301
+ </button>
170
302
  </div>
171
- <div ref={paymentSection} className="stripe-element"><PaymentElement /></div>
172
- {error ? <p className="error">{error}</p> : null}
173
- <button
174
- className="button button-large"
175
- type="button"
176
- disabled={!stripe || !elements || disabled || busy}
177
- onClick={() => void submit()}
178
- >
179
- {busy
180
- ? locale === "en" ? "Processing payment…" : "Fizetés feldolgozása…"
181
- : locale === "en" ? "Pay by card" : "Fizetés bankkártyával"}
182
- </button>
183
303
  </div>
184
304
  )
185
305
  }
306
+
307
+ function localized(locale: StorefrontLocale, hu: string, en: string) {
308
+ return locale === "en" ? en : hu
309
+ }
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Checkout address drafts are independent from the customer's saved address book.
3
+ * Only /store/carts/:id is written during checkout; customer-address mutations
4
+ * belong exclusively to the explicit address book management screen.
5
+ */
6
+ export type CheckoutAddress = {
7
+ email: string
8
+ first_name: string
9
+ last_name: string
10
+ company: string
11
+ phone: string
12
+ country_code: string
13
+ postal_code: string
14
+ city: string
15
+ province: string
16
+ address_1: string
17
+ address_2: string
18
+ }
19
+
20
+ export type CustomerAddress = Record<string, unknown> & { id?: unknown }
21
+
22
+ export type InitialCheckoutAddresses = {
23
+ shipping: CheckoutAddress
24
+ billing: CheckoutAddress
25
+ shippingSelection: string
26
+ billingSelection: string
27
+ billingSameAsShipping: boolean
28
+ addressOnCart: boolean
29
+ }
30
+
31
+ export const NEW_CHECKOUT_ADDRESS = "__new"
32
+ export const CART_CHECKOUT_ADDRESS = "__cart"
33
+
34
+ function value(input: unknown) {
35
+ return typeof input === "string" ? input.trim() : ""
36
+ }
37
+
38
+ function record(input: unknown): Record<string, unknown> {
39
+ return input && typeof input === "object" && !Array.isArray(input)
40
+ ? input as Record<string, unknown>
41
+ : {}
42
+ }
43
+
44
+ export function emptyCheckoutAddress(country = "HU", email = ""): CheckoutAddress {
45
+ return {
46
+ email,
47
+ first_name: "", last_name: "", company: "", phone: "",
48
+ country_code: country.toUpperCase(), postal_code: "",
49
+ city: "", province: "", address_1: "", address_2: "",
50
+ }
51
+ }
52
+
53
+ export function checkoutAddressFromRecord(
54
+ source: unknown,
55
+ country: string,
56
+ email = "",
57
+ ): CheckoutAddress {
58
+ const item = record(source)
59
+ return {
60
+ email,
61
+ first_name: value(item.first_name),
62
+ last_name: value(item.last_name),
63
+ company: value(item.company),
64
+ phone: value(item.phone),
65
+ country_code: (value(item.country_code) || country).toUpperCase(),
66
+ postal_code: value(item.postal_code),
67
+ city: value(item.city),
68
+ province: value(item.province),
69
+ address_1: value(item.address_1),
70
+ address_2: value(item.address_2),
71
+ }
72
+ }
73
+
74
+ export function checkoutAddressPayload(address: CheckoutAddress) {
75
+ return {
76
+ first_name: address.first_name.trim(),
77
+ last_name: address.last_name.trim(),
78
+ company: address.company.trim() || undefined,
79
+ phone: address.phone.trim() || undefined,
80
+ country_code: address.country_code.trim().toLowerCase(),
81
+ postal_code: address.postal_code.trim(),
82
+ city: address.city.trim(),
83
+ province: address.province.trim() || undefined,
84
+ address_1: address.address_1.trim(),
85
+ address_2: address.address_2.trim() || undefined,
86
+ }
87
+ }
88
+
89
+ export function checkoutAddressPresent(source: unknown) {
90
+ const data = record(source)
91
+ return Boolean(value(data.address_1) || value(data.postal_code) || value(data.city))
92
+ }
93
+
94
+ export function checkoutAddressesMatch(a: CheckoutAddress, b: CheckoutAddress) {
95
+ return ([
96
+ "first_name", "last_name", "company", "phone", "country_code",
97
+ "postal_code", "city", "province", "address_1", "address_2",
98
+ ] as const).every(field => a[field].trim().toLowerCase() === b[field].trim().toLowerCase())
99
+ }
100
+
101
+ export function checkoutAddressLabel(address: CustomerAddress) {
102
+ const customName = value(address.address_name)
103
+ const person = [value(address.first_name), value(address.last_name)].filter(Boolean).join(" ")
104
+ const place = [value(address.postal_code), value(address.city), value(address.address_1)].filter(Boolean).join(" ")
105
+ return [customName || person || "Mentett cím", place].filter(Boolean).join(" – ")
106
+ }
107
+
108
+ function addressId(address: CustomerAddress | undefined) {
109
+ return value(address?.id)
110
+ }
111
+
112
+ export function initialCheckoutAddresses(input: {
113
+ cart: Record<string, unknown>
114
+ customer?: Record<string, unknown> | null
115
+ savedAddresses?: CustomerAddress[]
116
+ country: string
117
+ }): InitialCheckoutAddresses {
118
+ const { cart, country } = input
119
+ const customer = input.customer || {}
120
+ const saved = (input.savedAddresses || []).filter(item => addressId(item))
121
+ const email = value(cart.email) || value(customer.email)
122
+ const existingShipping = checkoutAddressPresent(cart.shipping_address)
123
+ const existingBilling = checkoutAddressPresent(cart.billing_address)
124
+ // Medusa exposes both customer default address IDs and address flags.
125
+ // Prefer the explicit customer IDs when available.
126
+ const defaultShipping = saved.find(item => addressId(item) === value(customer.default_shipping_address_id)) ||
127
+ saved.find(item => item.is_default_shipping === true) || saved[0]
128
+ const defaultBilling = saved.find(item => addressId(item) === value(customer.default_billing_address_id)) ||
129
+ saved.find(item => item.is_default_billing === true)
130
+
131
+ const shipping = existingShipping
132
+ ? checkoutAddressFromRecord(cart.shipping_address, country, email)
133
+ : defaultShipping
134
+ ? checkoutAddressFromRecord(defaultShipping, country, email)
135
+ : emptyCheckoutAddress(country, email)
136
+
137
+ const selectedShipping = existingShipping
138
+ ? saved.find(item => checkoutAddressesMatch(
139
+ shipping, checkoutAddressFromRecord(item, country, email),
140
+ ))
141
+ : defaultShipping
142
+
143
+ const billing = existingBilling
144
+ ? checkoutAddressFromRecord(cart.billing_address, country, email)
145
+ : defaultBilling
146
+ ? checkoutAddressFromRecord(defaultBilling, country, email)
147
+ : { ...shipping }
148
+ const selectedBilling = existingBilling
149
+ ? saved.find(item => checkoutAddressesMatch(
150
+ billing, checkoutAddressFromRecord(item, country, email),
151
+ ))
152
+ : defaultBilling
153
+ const sameBilling = checkoutAddressesMatch(shipping, billing)
154
+
155
+ return {
156
+ shipping,
157
+ billing,
158
+ shippingSelection: addressId(selectedShipping) ||
159
+ (existingShipping ? CART_CHECKOUT_ADDRESS : NEW_CHECKOUT_ADDRESS),
160
+ billingSelection: addressId(selectedBilling) ||
161
+ (existingBilling ? CART_CHECKOUT_ADDRESS : NEW_CHECKOUT_ADDRESS),
162
+ billingSameAsShipping: sameBilling,
163
+ // A default address book choice has not been applied to the cart yet.
164
+ addressOnCart: existingShipping && existingBilling && Boolean(value(cart.email)),
165
+ }
166
+ }
@@ -178,6 +178,18 @@ export function checkoutApi(config: CoreConfig) {
178
178
 
179
179
  updateCart,
180
180
 
181
+ saveBillingTaxDetails: (cartId: string, data: {
182
+ is_company: boolean
183
+ billing_tax_number: string
184
+ billing_eu_tax_number: string
185
+ }) =>
186
+ medusaFetch<{ tax: Record<string, unknown> }>(
187
+ `/store/carts/${encodeURIComponent(cartId)}/billing-tax`, {
188
+ method: "POST",
189
+ body: JSON.stringify(data),
190
+ },
191
+ ),
192
+
181
193
  addLineItem: async (cartId: string, variantId: string, quantity = 1) => {
182
194
  const result = await medusaFetch<{ cart: Record<string, unknown> }>(
183
195
  endpoint(paths.add_line_item, { id: cartId }),
@@ -83,8 +83,18 @@ export function paymentSessionData(session: JsonRecord | null | undefined) {
83
83
  return isRecord(session?.data) ? session.data : {}
84
84
  }
85
85
 
86
- export function paymentClientSecret(cart: JsonRecord | null | undefined) {
87
- const data = paymentSessionData(activePaymentSession(cart))
86
+ export function paymentClientSecret(
87
+ cart: JsonRecord | null | undefined,
88
+ preferredProviderId?: string,
89
+ ) {
90
+ // A cart can contain several payment sessions when the buyer changes
91
+ // methods. Never take another provider's client_secret from sessions[0].
92
+ const normalized = preferredProviderId?.trim().toLowerCase()
93
+ const session = normalized
94
+ ? paymentSessions(cart).find(candidate =>
95
+ stringValue(candidate.provider_id).toLowerCase() === normalized) || null
96
+ : activePaymentSession(cart)
97
+ const data = paymentSessionData(session)
88
98
  return stringValue(data.client_secret || data.clientSecret) || null
89
99
  }
90
100