@hszrdm/create-commerce 1.10.0 → 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 (38) hide show
  1. package/README.md +6 -0
  2. package/package.json +1 -1
  3. package/src/cli.mjs +20 -4
  4. package/src/upgrade.mjs +79 -4
  5. package/templates/backend/.env.example +8 -0
  6. package/templates/backend/package.json +2 -1
  7. package/templates/backend/scripts/commerce-instance-status.mjs +135 -0
  8. package/templates/backend/scripts/commerce-ops.mjs +61 -2
  9. package/templates/backend/scripts/core-restore.mjs +40 -5
  10. package/templates/backend/scripts/lib/core-backup-common.mjs +91 -11
  11. package/templates/backend/scripts/production-assets/backup.sh +6 -51
  12. package/templates/backend/scripts/production-assets/deploy.sh +10 -62
  13. package/templates/backend/scripts/production-assets/install.sh +23 -195
  14. package/templates/backend/scripts/production-assets/restore.sh +17 -66
  15. package/templates/backend/src/scripts/sync-integration-runtime.ts +1 -0
  16. package/templates/storefront/package.json +5 -1
  17. package/templates/storefront/src/app/checkout/success/page.tsx +2 -0
  18. package/templates/storefront/src/app/globals.css +32 -0
  19. package/templates/storefront/src/app/layout.tsx +7 -1
  20. package/templates/storefront/src/app/legal/page.tsx +3 -3
  21. package/templates/storefront/src/components/analytics.tsx +10 -8
  22. package/templates/storefront/src/components/checkout-flow.tsx +539 -75
  23. package/templates/storefront/src/components/fogyasztobarat-embed.tsx +6 -2
  24. package/templates/storefront/src/components/google-analytics-purchase.tsx +33 -0
  25. package/templates/storefront/src/components/stripe-payment.tsx +186 -62
  26. package/templates/storefront/src/lib/core/checkout-addresses.ts +166 -0
  27. package/templates/storefront/src/lib/core/checkout.ts +12 -0
  28. package/templates/storefront/src/lib/core/commerce.ts +12 -2
  29. package/templates/storefront/src/lib/core/company-tax.ts +132 -0
  30. package/templates/storefront/src/lib/core/ga4-bootstrap.ts +35 -0
  31. package/templates/storefront/src/lib/core/legal.ts +1 -0
  32. package/templates/storefront/src/lib/core/public-error.ts +1 -0
  33. package/templates/storefront/src/lib/core/stripe-checkout-phase.ts +23 -0
  34. package/templates/storefront/src/lib/core/tracking.ts +11 -2
  35. package/templates/storefront/tests/checkout-addresses.test.mjs +148 -0
  36. package/templates/storefront/tests/company-tax.test.mjs +68 -0
  37. package/templates/storefront/tests/ga4-bootstrap.test.mjs +74 -0
  38. package/templates/storefront/tests/stripe-checkout-phase.test.mjs +92 -0
@@ -4,10 +4,29 @@ 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 { StripePayment } from "./stripe-payment"
7
+ import { stripeCheckoutPhase } from "@/lib/core/stripe-checkout-phase"
7
8
  import { carrierPointToShippingData, type CarrierPickupPoint } from "./carrier-pickup-map"
8
9
  import { CarrierPickupDialog } from "./carrier-pickup-dialog"
9
10
  import { normalizeCarrierPickupPoint } from "./carrier-pickup-adapter"
10
11
  import { checkoutApi } from "@/lib/core/checkout"
12
+ import {
13
+ CompanyTaxValidationError,
14
+ validateCompanyTaxDetails,
15
+ } from "@/lib/core/company-tax"
16
+ import { accountApi } from "@/lib/core/account"
17
+ import { CoreApiError } from "@/lib/core/client"
18
+ import {
19
+ CART_CHECKOUT_ADDRESS,
20
+ NEW_CHECKOUT_ADDRESS,
21
+ checkoutAddressFromRecord,
22
+ checkoutAddressLabel,
23
+ checkoutAddressPayload,
24
+ checkoutAddressPresent,
25
+ emptyCheckoutAddress,
26
+ initialCheckoutAddresses,
27
+ type CheckoutAddress,
28
+ type CustomerAddress,
29
+ } from "@/lib/core/checkout-addresses"
11
30
  import { normalizeShippingPhone, requireShippingText, validateShippingEmail } from "@/lib/core/shipping-input-validation"
12
31
  import {
13
32
  activePaymentSession,
@@ -36,24 +55,13 @@ import {
36
55
  type StorefrontLocale,
37
56
  } from "@/lib/storefront-routes"
38
57
 
39
- type AddressState = {
40
- email: string
41
- first_name: string
42
- last_name: string
43
- company: string
44
- phone: string
45
- country_code: string
46
- postal_code: string
47
- city: string
48
- province: string
49
- address_1: string
50
- address_2: string
51
- }
58
+ type AddressState = CheckoutAddress
52
59
 
53
60
  type PickupKind = "foxpost" | "gls" | "dpd" | "mpl" | "packeta" | null
54
61
 
55
62
  export function CheckoutFlow({ config }: { config: CoreConfig }) {
56
63
  const api = useMemo(() => checkoutApi(config), [config])
64
+ const account = useMemo(() => accountApi(config), [config])
57
65
  const router = useRouter()
58
66
  const search = useSearchParams()
59
67
  const pathname = usePathname()
@@ -71,11 +79,34 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
71
79
  refresh,
72
80
  clearCart,
73
81
  } = useCart()
74
- const hydratedAddress = useRef(false)
82
+ const hydratedCartId = useRef<string | null>(null)
83
+ const addressEdited = useRef(false)
75
84
  const returnAttempted = useRef(false)
76
85
 
77
86
  const [address, setAddress] = useState<AddressState>(() => emptyAddress(config.store.default_country))
78
87
  const [addressErrors, setAddressErrors] = useState<Partial<Record<keyof AddressState, string>>>({})
88
+ const [billingAddress, setBillingAddress] = useState<AddressState>(() => emptyAddress(config.store.default_country))
89
+ const [billingErrors, setBillingErrors] = useState<Partial<Record<keyof AddressState, string>>>({})
90
+ const [billingSameAsShipping, setBillingSameAsShipping] = useState(true)
91
+ const [billingIsCompany, setBillingIsCompany] = useState(false)
92
+ const [billingTaxNumber, setBillingTaxNumber] = useState("")
93
+ const [billingEuTaxNumber, setBillingEuTaxNumber] = useState("")
94
+ const [billingTaxErrors, setBillingTaxErrors] = useState<{
95
+ company?: string
96
+ billing_tax_number?: string
97
+ billing_eu_tax_number?: string
98
+ billing_tax_details?: string
99
+ }>({})
100
+ const [savedAddresses, setSavedAddresses] = useState<CustomerAddress[]>([])
101
+ const [cartShippingDraft, setCartShippingDraft] = useState<CheckoutAddress | null>(null)
102
+ const [cartBillingDraft, setCartBillingDraft] = useState<CheckoutAddress | null>(null)
103
+ const [shippingAddressSelection, setShippingAddressSelection] = useState(NEW_CHECKOUT_ADDRESS)
104
+ const [billingAddressSelection, setBillingAddressSelection] = useState(NEW_CHECKOUT_ADDRESS)
105
+ const [signedIn, setSignedIn] = useState(false)
106
+ const [addressOnCart, setAddressOnCart] = useState(false)
107
+ const [savedAddressLoadError, setSavedAddressLoadError] = useState<string | null>(null)
108
+ const [savedAddressLoading, setSavedAddressLoading] = useState(false)
109
+ const [savingCustomerAddress, setSavingCustomerAddress] = useState<"shipping" | "billing" | null>(null)
79
110
  const [shippingOptions, setShippingOptions] = useState<JsonRecord[]>([])
80
111
  const [selectedShipping, setSelectedShipping] = useState<JsonRecord | null>(null)
81
112
  const [selectedPickupPoint, setSelectedPickupPoint] = useState<CarrierPickupPoint | null>(null)
@@ -83,12 +114,33 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
83
114
  const [providers, setProviders] = useState<JsonRecord[]>([])
84
115
  const [selectedProvider, setSelectedProvider] = useState("")
85
116
  const [preparedCart, setPreparedCart] = useState<JsonRecord | null>(null)
117
+ const [stripeInitError, setStripeInitError] = useState<string | null>(null)
86
118
  const [legalDocs, setLegalDocs] = useState<LegalDocument[]>([])
87
119
  const [accepted, setAccepted] = useState<Record<string, boolean>>({})
88
120
  const [busy, setBusy] = useState<string | null>(null)
89
121
  const [error, setError] = useState<string | null>(null)
90
122
  const [message, setMessage] = useState<string | null>(null)
91
123
 
124
+ const setBillingTaxDefaults = useCallback((
125
+ cartData: JsonRecord,
126
+ billing: CheckoutAddress,
127
+ saved?: CustomerAddress,
128
+ ) => {
129
+ const cartMeta = isRecord(cartData.metadata) ? cartData.metadata : {}
130
+ const addressRecord = isRecord(cartData.billing_address) ? cartData.billing_address : {}
131
+ const addressMeta = isRecord(addressRecord.metadata) ? addressRecord.metadata : {}
132
+ const savedMeta = saved && isRecord(saved.metadata) ? saved.metadata : {}
133
+ const source = Object.keys(cartMeta).some(key => key.startsWith("billing_"))
134
+ ? cartMeta
135
+ : Object.keys(addressMeta).some(key => key.startsWith("billing_"))
136
+ ? addressMeta
137
+ : savedMeta
138
+ setBillingIsCompany(source.billing_is_company === true || Boolean(billing.company))
139
+ setBillingTaxNumber(stringValue(source.billing_tax_number))
140
+ setBillingEuTaxNumber(stringValue(source.billing_eu_tax_number))
141
+ setBillingTaxErrors({})
142
+ }, [])
143
+
92
144
  const returnCartId = search.get("cart_id")
93
145
  const stripeReturn = search.get("stripe_return")
94
146
  const simplePayReturn = search.get("simplepay_return")
@@ -111,24 +163,160 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
111
163
  .catch(() => setLegalDocs([]))
112
164
  }, [config])
113
165
 
166
+ // Each cart gets exactly one address-book lookup. Refreshing the cart
167
+ // must never clobber checkout edits or silently save a customer address.
114
168
  useEffect(() => {
115
- if (!cart || hydratedAddress.current) return
116
- const shipping = isRecord(cart.shipping_address) ? cart.shipping_address : {}
117
- setAddress({
118
- email: stringValue(cart.email),
119
- first_name: stringValue(shipping.first_name),
120
- last_name: stringValue(shipping.last_name),
121
- company: stringValue(shipping.company),
122
- phone: stringValue(shipping.phone),
123
- country_code: stringValue(shipping.country_code || config.store.default_country).toUpperCase(),
124
- postal_code: stringValue(shipping.postal_code),
125
- city: stringValue(shipping.city),
126
- province: stringValue(shipping.province),
127
- address_1: stringValue(shipping.address_1),
128
- address_2: stringValue(shipping.address_2),
129
- })
130
- hydratedAddress.current = true
131
- }, [cart, config.store.default_country])
169
+ if (!cart || !cartId || hydratedCartId.current === cartId) return
170
+ hydratedCartId.current = cartId
171
+ addressEdited.current = false
172
+ setSavedAddresses([])
173
+ setSignedIn(false)
174
+ setSavedAddressLoadError(null)
175
+
176
+ const initial = initialCheckoutAddresses({ cart, country: config.store.default_country })
177
+ setCartShippingDraft(checkoutAddressPresent(cart.shipping_address) ? initial.shipping : null)
178
+ setCartBillingDraft(checkoutAddressPresent(cart.billing_address) ? initial.billing : null)
179
+ setAddress(initial.shipping)
180
+ setBillingAddress(initial.billing)
181
+ setBillingTaxDefaults(cart, initial.billing)
182
+ setShippingAddressSelection(initial.shippingSelection)
183
+ setBillingAddressSelection(initial.billingSelection)
184
+ setBillingSameAsShipping(initial.billingSameAsShipping)
185
+ setAddressOnCart(initial.addressOnCart)
186
+ setAddressErrors({})
187
+ setBillingErrors({})
188
+ setSavedAddressLoading(true)
189
+
190
+ void (async () => {
191
+ try {
192
+ const { customer } = await account.profile()
193
+ if (hydratedCartId.current !== cartId) return
194
+ setSignedIn(true)
195
+ const { addresses } = await account.addresses()
196
+ if (hydratedCartId.current !== cartId) return
197
+ const saved = Array.isArray(addresses) ? addresses : []
198
+ setSavedAddresses(saved)
199
+ if (!addressEdited.current) {
200
+ const resolved = initialCheckoutAddresses({
201
+ cart, customer, savedAddresses: saved, country: config.store.default_country,
202
+ })
203
+ setAddress(resolved.shipping)
204
+ setBillingAddress(resolved.billing)
205
+ const selected = saved.find(item => stringValue(item.id) === resolved.billingSelection)
206
+ setBillingTaxDefaults(cart, resolved.billing, selected)
207
+ setShippingAddressSelection(resolved.shippingSelection)
208
+ setBillingAddressSelection(resolved.billingSelection)
209
+ setBillingSameAsShipping(resolved.billingSameAsShipping)
210
+ setAddressOnCart(resolved.addressOnCart)
211
+ }
212
+ } catch (cause) {
213
+ if (hydratedCartId.current !== cartId) return
214
+ if (!(cause instanceof CoreApiError && (cause.status === 401 || cause.status === 403))) {
215
+ setSavedAddressLoadError(localized(locale,
216
+ "A mentett címek most nem tölthetők be. A rendelés címét kézzel is megadhatod.",
217
+ "Saved addresses could not be loaded. You can enter the order address manually."))
218
+ }
219
+ } finally {
220
+ if (hydratedCartId.current === cartId) setSavedAddressLoading(false)
221
+ }
222
+ })()
223
+ }, [cartId, cart, account, config.store.default_country, locale, setBillingTaxDefaults])
224
+
225
+
226
+ const markAddressEdited = () => {
227
+ addressEdited.current = true
228
+ setAddressOnCart(false)
229
+ setMessage(null)
230
+ }
231
+
232
+ const chooseSavedShipping = (id: string) => {
233
+ markAddressEdited()
234
+ setShippingAddressSelection(id)
235
+ const saved = savedAddresses.find(item => stringValue(item.id) === id)
236
+ setAddress(current => saved
237
+ ? checkoutAddressFromRecord(saved, config.store.default_country, current.email)
238
+ : id === CART_CHECKOUT_ADDRESS && cartShippingDraft
239
+ ? { ...cartShippingDraft, email: current.email }
240
+ : emptyCheckoutAddress(config.store.default_country, current.email))
241
+ setAddressErrors({})
242
+ }
243
+
244
+ const chooseSavedBilling = (id: string) => {
245
+ markAddressEdited()
246
+ setBillingAddressSelection(id)
247
+ const saved = savedAddresses.find(item => stringValue(item.id) === id)
248
+ const next = saved
249
+ ? checkoutAddressFromRecord(saved, config.store.default_country, address.email)
250
+ : id === CART_CHECKOUT_ADDRESS && cartBillingDraft
251
+ ? { ...cartBillingDraft, email: address.email }
252
+ : emptyCheckoutAddress(config.store.default_country, address.email)
253
+ setBillingAddress(next)
254
+ const source = saved && isRecord(saved.metadata) ? saved.metadata
255
+ : id === CART_CHECKOUT_ADDRESS && isRecord(cart?.billing_address)
256
+ && isRecord(cart.billing_address.metadata) ? cart.billing_address.metadata : {}
257
+ setBillingIsCompany(source.billing_is_company === true || Boolean(next.company))
258
+ setBillingTaxNumber(stringValue(source.billing_tax_number))
259
+ setBillingEuTaxNumber(stringValue(source.billing_eu_tax_number))
260
+ setBillingTaxErrors({})
261
+ setBillingErrors({})
262
+ }
263
+
264
+ const addAddressToBook = async (kind: "shipping" | "billing") => {
265
+ if (!signedIn || savingCustomerAddress) return
266
+ const candidate = kind === "shipping" ? address : billingAddress
267
+ const validation = checkoutBillingAddressErrors(candidate, locale)
268
+ if (Object.keys(validation).length) {
269
+ if (kind === "shipping") setAddressErrors(validation)
270
+ else setBillingErrors(validation)
271
+ setError(localized(locale,
272
+ "Az új cím mentéséhez töltsd ki a kötelező címadatokat.",
273
+ "Fill in the required address fields before saving a new address."))
274
+ return
275
+ }
276
+
277
+ setSavingCustomerAddress(kind)
278
+ setError(null)
279
+ try {
280
+ const knownIds = new Set(savedAddresses.map(item => stringValue(item.id)))
281
+ // Explicit customer action only. Never auto-save a checkout edit or
282
+ // update an existing customer address. Billing metadata is included
283
+ // only when the customer explicitly asks to save this new address.
284
+ const tax = kind === "billing" ? validateCompanyTaxDetails({
285
+ isCompany: billingIsCompany, company: candidate.company,
286
+ billingTaxNumber, billingEuTaxNumber,
287
+ }) : null
288
+ await account.createAddress({
289
+ ...checkoutAddressPayload(candidate),
290
+ ...(tax ? {
291
+ company: tax.isCompany ? tax.company : undefined,
292
+ metadata: {
293
+ billing_is_company: tax.isCompany,
294
+ billing_tax_number: tax.billingTaxNumber,
295
+ billing_eu_tax_number: tax.billingEuTaxNumber,
296
+ },
297
+ } : {}),
298
+ })
299
+ const { addresses } = await account.addresses()
300
+ setSavedAddresses(addresses)
301
+ const created = addresses.find(item =>
302
+ !knownIds.has(stringValue(item.id)) &&
303
+ stringValue(item.address_1) === candidate.address_1.trim() &&
304
+ stringValue(item.postal_code) === candidate.postal_code.trim())
305
+ if (created?.id) {
306
+ if (kind === "shipping") setShippingAddressSelection(stringValue(created.id))
307
+ else setBillingAddressSelection(stringValue(created.id))
308
+ }
309
+ setMessage(localized(locale,
310
+ "Az új cím elmentve a címjegyzékbe. A rendeléshez külön mentsd a címeket.",
311
+ "The new address was saved to your account. Save the cart addresses separately."))
312
+ } catch (cause) {
313
+ setError(cause instanceof Error ? cause.message : localized(locale,
314
+ "Az új cím nem menthető a címjegyzékbe.",
315
+ "The new address could not be saved to your account."))
316
+ } finally {
317
+ setSavingCustomerAddress(null)
318
+ }
319
+ }
132
320
 
133
321
  const loadShippingOptions = useCallback(async () => {
134
322
  if (!cartId) return
@@ -180,6 +368,11 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
180
368
  }, [accepted, cartId, config, locale, requiredLegal])
181
369
 
182
370
  const completeOrder = useCallback(async () => {
371
+ if (!addressOnCart && !stripeReturn && !simplePayReturn) {
372
+ throw new Error(localized(locale,
373
+ "A rendelés előtt mentsd a módosított címeket.",
374
+ "Save the edited addresses before placing your order."))
375
+ }
183
376
  if (!cartId) {
184
377
  throw new Error(localized(locale, "Nincs aktív kosár.", "There is no active cart."))
185
378
  }
@@ -214,7 +407,7 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
214
407
  } finally {
215
408
  setBusy(null)
216
409
  }
217
- }, [api, cartId, clearCart, locale, router, routes.checkoutSuccess])
410
+ }, [addressOnCart, api, cartId, clearCart, locale, router, routes.checkoutSuccess, stripeReturn, simplePayReturn])
218
411
 
219
412
  useEffect(() => {
220
413
  if (returnAttempted.current || !cartId || !cart || (!stripeReturn && !simplePayReturn)) return
@@ -249,10 +442,30 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
249
442
  const courier = selectedShipping ? shippingCarrier(selectedShipping) : null
250
443
  const errors = checkoutAddressErrors(address, courier, locale)
251
444
  setAddressErrors(errors)
252
- if (Object.keys(errors).length) {
253
- setError(localized(locale, "Javítsd a megjelölt címzettadatokat.", "Please correct the highlighted contact fields."))
445
+ const nextBillingErrors = billingSameAsShipping ? {} : checkoutBillingAddressErrors(billingAddress, locale)
446
+ setBillingErrors(nextBillingErrors)
447
+ let validTax: ReturnType<typeof validateCompanyTaxDetails>
448
+ try {
449
+ validTax = validateCompanyTaxDetails({
450
+ isCompany: billingIsCompany,
451
+ company: billingAddress.company,
452
+ billingTaxNumber,
453
+ billingEuTaxNumber,
454
+ })
455
+ setBillingTaxErrors({})
456
+ } catch (cause) {
457
+ if (cause instanceof CompanyTaxValidationError) {
458
+ setBillingTaxErrors({ [cause.field]: cause.message })
459
+ setError(cause.message)
460
+ return
461
+ }
462
+ throw cause
463
+ }
464
+ if (Object.keys(errors).length || Object.keys(nextBillingErrors).length) {
465
+ setError(localized(locale, "Javítsd a megjelölt címzett- vagy számlázási adatokat.", "Correct the highlighted shipping or billing fields."))
254
466
  return
255
467
  }
468
+ addressEdited.current = true
256
469
  const normalizedPhone = normalizeShippingPhone(address.phone, {
257
470
  carrier: courier || "Szállítás",
258
471
  field: "Telefonszám",
@@ -263,23 +476,30 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
263
476
  setBusy("address")
264
477
  setError(null)
265
478
  try {
266
- const shippingAddress = {
267
- first_name: address.first_name,
268
- last_name: address.last_name,
269
- company: address.company || undefined,
270
- phone: normalizedPhone,
271
- country_code: address.country_code.toLowerCase(),
272
- postal_code: address.postal_code,
273
- city: address.city,
274
- province: address.province || undefined,
275
- address_1: address.address_1,
276
- address_2: address.address_2 || undefined,
479
+ const shippingAddress = checkoutAddressPayload({
480
+ ...address, phone: normalizedPhone, email: normalizedEmail,
481
+ })
482
+ const separateBilling = checkoutAddressPayload(billingAddress)
483
+ const invoiceAddress = {
484
+ ...(billingSameAsShipping ? shippingAddress : separateBilling),
485
+ company: validTax.isCompany ? validTax.company : undefined,
277
486
  }
487
+ setAddressOnCart(false)
488
+ // Native Medusa cart owns addresses; Core stores validated VAT metadata
489
+ // on BOTH the cart and its billing address, never on customer addresses.
278
490
  await api.updateCart(cartId, {
279
491
  email: normalizedEmail,
280
492
  shipping_address: shippingAddress,
281
- billing_address: shippingAddress,
493
+ billing_address: invoiceAddress,
282
494
  })
495
+ await api.saveBillingTaxDetails(cartId, {
496
+ is_company: validTax.isCompany,
497
+ billing_tax_number: validTax.billingTaxNumber,
498
+ billing_eu_tax_number: validTax.billingEuTaxNumber,
499
+ })
500
+ setBillingTaxNumber(validTax.billingTaxNumber)
501
+ setBillingEuTaxNumber(validTax.billingEuTaxNumber)
502
+ setAddressOnCart(true)
283
503
  await refresh(cartId)
284
504
  await loadShippingOptions()
285
505
  setMessage(copy.saveAddressSuccess)
@@ -336,6 +556,12 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
336
556
  if (!cartId || !selectedShipping) {
337
557
  throw new Error(localized(locale, "Válassz szállítási módot.", "Choose a shipping method."))
338
558
  }
559
+ if (!addressOnCart) {
560
+ setError(localized(locale,
561
+ "Előbb mentsd a szállítási és számlázási címet a kosárhoz.",
562
+ "Save the shipping and billing addresses to the cart first."))
563
+ return
564
+ }
339
565
  const optionId = stringValue(selectedShipping.id)
340
566
  const kind = pickupKind(selectedShipping)
341
567
  const errors = checkoutAddressErrors(address, shippingCarrier(selectedShipping), locale)
@@ -365,11 +591,19 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
365
591
  }
366
592
 
367
593
  const preparePayment = async (id: string) => {
594
+ if (!addressOnCart) {
595
+ setError(localized(locale,
596
+ "Előbb mentsd a szállítási és számlázási címet.",
597
+ "Save the shipping and billing addresses first."))
598
+ return
599
+ }
368
600
  if (!cartId) {
369
601
  throw new Error(localized(locale, "Nincs aktív kosár.", "There is no active cart."))
370
602
  }
371
603
  setBusy("payment")
372
604
  setError(null)
605
+ setStripeInitError(null)
606
+ setPreparedCart(null)
373
607
  setSelectedProvider(id)
374
608
  try {
375
609
  let current = (await api.getCart(cartId)).cart
@@ -395,11 +629,11 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
395
629
  setMessage(copy.paymentPrepared)
396
630
  } catch (cause) {
397
631
  setPreparedCart(null)
398
- setError(
399
- cause instanceof Error
400
- ? cause.message
401
- : localized(locale, "A fizetési mód nem készíthető elő.", "The payment method could not be prepared."),
402
- )
632
+ const message = cause instanceof Error
633
+ ? cause.message
634
+ : localized(locale, "A fizetési mód nem készíthető elő.", "The payment method could not be prepared.")
635
+ if (id.toLowerCase().includes("stripe")) setStripeInitError(message)
636
+ else setError(message)
403
637
  } finally {
404
638
  setBusy(null)
405
639
  }
@@ -412,9 +646,15 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
412
646
 
413
647
  const pickup = selectedShipping ? pickupKind(selectedShipping) : null
414
648
  const setAddressField = (key: keyof AddressState, value: string) => {
649
+ markAddressEdited()
415
650
  updateAddress(setAddress, key, value)
416
651
  if (addressErrors[key]) setAddressErrors((current) => ({ ...current, [key]: undefined }))
417
652
  }
653
+ const setBillingField = (key: keyof AddressState, value: string) => {
654
+ markAddressEdited()
655
+ updateAddress(setBillingAddress, key, value)
656
+ if (billingErrors[key]) setBillingErrors(current => ({ ...current, [key]: undefined }))
657
+ }
418
658
  const blurAddressField = (key: keyof AddressState) => {
419
659
  const courier = selectedShipping ? shippingCarrier(selectedShipping) : null
420
660
  const fieldError = checkoutAddressErrors(address, courier, locale)[key]
@@ -431,10 +671,19 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
431
671
  }
432
672
  const effectiveCart = preparedCart || cart
433
673
  const session = activePaymentSession(effectiveCart)
434
- const activeProviderId = providerId(session) || selectedProvider
435
- const stripeSecret = paymentClientSecret(effectiveCart)
674
+ // While the buyer switches providers, their explicit selection wins over
675
+ // any old cart session. Never read a stale provider's client_secret.
676
+ const activeProviderId = selectedProvider || providerId(session)
677
+ const stripeSecret = paymentClientSecret(effectiveCart, activeProviderId)
436
678
  const simplePayRedirect = simplePayUrl(effectiveCart)
437
- const stripeSelected = activeProviderId.toLowerCase().includes("stripe")
679
+ const stripePhase = stripeCheckoutPhase({
680
+ sessionProviderId: providerId(session),
681
+ selectedProviderId: selectedProvider,
682
+ busy,
683
+ clientSecret: stripeSecret,
684
+ publishableKey: config.payments.stripe.publishable_key,
685
+ initializationError: stripeInitError,
686
+ })
438
687
  const simplePaySelected = activeProviderId.toLowerCase().includes("simplepay")
439
688
  const systemSelected = activeProviderId.toLowerCase().includes("system")
440
689
  const currency = cartCurrency(cart, config.store.default_currency)
@@ -444,6 +693,35 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
444
693
  <div className="stack">
445
694
  <section className="panel stack">
446
695
  <SectionTitle step="1" title={copy.contactAndAddress} />
696
+ {savedAddressLoading ? (
697
+ <p className="muted">{localized(locale, "Mentett címek betöltése…", "Loading saved addresses…")}</p>
698
+ ) : null}
699
+ {savedAddressLoadError ? <div className="notice warning">{savedAddressLoadError}</div> : null}
700
+ {signedIn && savedAddresses.length ? (
701
+ <label>
702
+ {localized(locale, "Szállítási cím a címjegyzékből", "Shipping address from your address book")}
703
+ <select
704
+ className="checkout-address-select"
705
+ value={shippingAddressSelection}
706
+ onChange={(event) => chooseSavedShipping(event.target.value)}
707
+ disabled={busy === "address" || Boolean(savingCustomerAddress)}
708
+ >
709
+ {cartShippingDraft ? (
710
+ <option value={CART_CHECKOUT_ADDRESS}>
711
+ {localized(locale, "Korábban megadott rendelési cím", "Address entered for this order")}
712
+ </option>
713
+ ) : null}
714
+ {savedAddresses.map(item => (
715
+ <option key={stringValue(item.id)} value={stringValue(item.id)}>
716
+ {checkoutAddressLabel(item)}
717
+ </option>
718
+ ))}
719
+ <option value={NEW_CHECKOUT_ADDRESS}>
720
+ {localized(locale, "Új szállítási cím megadása", "Enter a new shipping address")}
721
+ </option>
722
+ </select>
723
+ </label>
724
+ ) : null}
447
725
  <div className="form-grid two-col">
448
726
  <Field label={copy.email} value={address.email} type="email" error={addressErrors.email} onBlur={() => blurAddressField("email")} onChange={(value) => setAddressField("email", value)} />
449
727
  <Field label={copy.phone} value={address.phone} type="tel" error={addressErrors.phone} onBlur={() => blurAddressField("phone")} onChange={(value) => setAddressField("phone", value)} />
@@ -456,7 +734,152 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
456
734
  <Field label={copy.address1} value={address.address_1} error={addressErrors.address_1} onBlur={() => blurAddressField("address_1")} onChange={(value) => setAddressField("address_1", value)} />
457
735
  <Field label={copy.address2} value={address.address_2} error={addressErrors.address_2} onBlur={() => blurAddressField("address_2")} onChange={(value) => setAddressField("address_2", value)} />
458
736
  </div>
459
- <button className="button secondary" type="button" disabled={busy === "address" || mutating} onClick={() => void saveAddress()}>
737
+ {signedIn && shippingAddressSelection === NEW_CHECKOUT_ADDRESS ? (
738
+ <button className="text-button" type="button" disabled={Boolean(savingCustomerAddress)}
739
+ onClick={() => void addAddressToBook("shipping")}>
740
+ {savingCustomerAddress === "shipping"
741
+ ? localized(locale, "Mentés a címjegyzékbe…", "Saving to address book…")
742
+ : localized(locale, "Új szállítási cím hozzáadása a címjegyzékhez", "Save new shipping address to your account")}
743
+ </button>
744
+ ) : null}
745
+ <div className="divider" />
746
+ <h3>{localized(locale, "Számlázási cím", "Billing address")}</h3>
747
+ <label className="legal-check">
748
+ <input
749
+ type="checkbox"
750
+ checked={billingSameAsShipping}
751
+ onChange={(event) => {
752
+ markAddressEdited()
753
+ setBillingSameAsShipping(event.target.checked)
754
+ setBillingErrors({})
755
+ }}
756
+ />
757
+ <span>{localized(locale,
758
+ "A számlázási cím megegyezik a szállítási címmel.",
759
+ "My billing address is the same as my shipping address.")}</span>
760
+ </label>
761
+ <label className="legal-check">
762
+ <input
763
+ type="checkbox"
764
+ checked={billingIsCompany}
765
+ onChange={event => {
766
+ markAddressEdited()
767
+ setBillingIsCompany(event.target.checked)
768
+ setBillingTaxErrors({})
769
+ if (!event.target.checked) {
770
+ setBillingAddress(current => ({ ...current, company: "" }))
771
+ setBillingTaxNumber("")
772
+ setBillingEuTaxNumber("")
773
+ }
774
+ }}
775
+ />
776
+ <span>{localized(locale, "Céges számlázást kérek", "I need a business invoice")}</span>
777
+ </label>
778
+ {billingIsCompany ? (
779
+ <div className="stack-sm">
780
+ <Field
781
+ label={localized(locale, "Cégnév *", "Company name *")}
782
+ value={billingAddress.company}
783
+ error={billingTaxErrors.company}
784
+ onChange={value => {
785
+ markAddressEdited()
786
+ setBillingAddress(current => ({ ...current, company: value }))
787
+ setBillingTaxErrors(current => ({ ...current, company: undefined }))
788
+ }}
789
+ />
790
+ <div className="form-grid two-col">
791
+ <Field
792
+ label={localized(locale, "Magyar adószám", "Hungarian tax number")}
793
+ value={billingTaxNumber}
794
+ error={billingTaxErrors.billing_tax_number}
795
+ onChange={value => {
796
+ markAddressEdited()
797
+ setBillingTaxNumber(value)
798
+ setBillingTaxErrors(current => ({ ...current, billing_tax_number: undefined, billing_tax_details: undefined }))
799
+ }}
800
+ />
801
+ <Field
802
+ label={localized(locale, "EU-s közösségi adószám", "EU VAT number")}
803
+ value={billingEuTaxNumber}
804
+ error={billingTaxErrors.billing_eu_tax_number}
805
+ onChange={value => {
806
+ markAddressEdited()
807
+ setBillingEuTaxNumber(value)
808
+ setBillingTaxErrors(current => ({ ...current, billing_eu_tax_number: undefined, billing_tax_details: undefined }))
809
+ }}
810
+ />
811
+ </div>
812
+ {billingTaxErrors.billing_tax_details ? (
813
+ <small className="error" role="alert">{billingTaxErrors.billing_tax_details}</small>
814
+ ) : null}
815
+ <p className="muted small">
816
+ {localized(locale,
817
+ "Legalább az egyik adószám kötelező. Magyar: 12345678-2-42; EU: HU12345678 vagy DE123456789. A formátum ellenőrzése nem NAV/VIES érvényességvizsgálat.",
818
+ "At least one number is required. HU: 12345678-2-42; EU: HU12345678 or DE123456789. Format checks do not verify VIES/NAV registration.")}
819
+ </p>
820
+ </div>
821
+ ) : null}
822
+ {!billingSameAsShipping ? (
823
+ <>
824
+ {signedIn && savedAddresses.length ? (
825
+ <label>
826
+ {localized(locale, "Számlázási cím a címjegyzékből", "Billing address from your address book")}
827
+ <select
828
+ className="checkout-address-select"
829
+ value={billingAddressSelection}
830
+ onChange={(event) => chooseSavedBilling(event.target.value)}
831
+ disabled={busy === "address" || Boolean(savingCustomerAddress)}
832
+ >
833
+ {cartBillingDraft ? (
834
+ <option value={CART_CHECKOUT_ADDRESS}>
835
+ {localized(locale, "Korábban megadott számlázási cím", "Previously entered billing address")}
836
+ </option>
837
+ ) : null}
838
+ {savedAddresses.map(item => (
839
+ <option key={stringValue(item.id)} value={stringValue(item.id)}>
840
+ {checkoutAddressLabel(item)}
841
+ </option>
842
+ ))}
843
+ <option value={NEW_CHECKOUT_ADDRESS}>
844
+ {localized(locale, "Új számlázási cím megadása", "Enter a new billing address")}
845
+ </option>
846
+ </select>
847
+ </label>
848
+ ) : null}
849
+ <div className="form-grid two-col">
850
+ <Field label={copy.firstName} value={billingAddress.first_name} error={billingErrors.first_name}
851
+ onChange={value => setBillingField("first_name", value)} />
852
+ <Field label={copy.lastName} value={billingAddress.last_name} error={billingErrors.last_name}
853
+ onChange={value => setBillingField("last_name", value)} />
854
+ <Field label={copy.phone} value={billingAddress.phone} type="tel" error={billingErrors.phone}
855
+ onChange={value => setBillingField("phone", value)} />
856
+ <Field label={copy.country} value={billingAddress.country_code} error={billingErrors.country_code}
857
+ onChange={value => setBillingField("country_code", value.toUpperCase())} />
858
+ <Field label={copy.postalCode} value={billingAddress.postal_code} error={billingErrors.postal_code}
859
+ onChange={value => setBillingField("postal_code", value)} />
860
+ <Field label={copy.city} value={billingAddress.city} error={billingErrors.city}
861
+ onChange={value => setBillingField("city", value)} />
862
+ <Field label={copy.address1} value={billingAddress.address_1} error={billingErrors.address_1}
863
+ onChange={value => setBillingField("address_1", value)} />
864
+ <Field label={copy.address2} value={billingAddress.address_2}
865
+ onChange={value => setBillingField("address_2", value)} />
866
+ <Field label={localized(locale, "Megye / tartomány (opcionális)", "State / province (optional)")}
867
+ value={billingAddress.province} onChange={value => setBillingField("province", value)} />
868
+ </div>
869
+ {signedIn && billingAddressSelection === NEW_CHECKOUT_ADDRESS ? (
870
+ <button className="text-button" type="button" disabled={Boolean(savingCustomerAddress)}
871
+ onClick={() => void addAddressToBook("billing")}>
872
+ {savingCustomerAddress === "billing"
873
+ ? localized(locale, "Mentés a címjegyzékbe…", "Saving to address book…")
874
+ : localized(locale, "Új számlázási cím hozzáadása a címjegyzékhez", "Save new billing address to your account")}
875
+ </button>
876
+ ) : null}
877
+ </>
878
+ ) : null}
879
+ <p className="muted small">{localized(locale,
880
+ "A címek szerkesztése itt csak erre a rendelésre vonatkozik; a fiókod mentett címei nem módosulnak.",
881
+ "Editing addresses here only affects this order; addresses saved in your account are not changed.")}</p>
882
+ <button className="button secondary" type="button" disabled={busy === "address" || mutating || Boolean(savingCustomerAddress)} onClick={() => void saveAddress()}>
460
883
  {busy === "address" ? copy.saving : copy.saveAddressAndLoadShipping}
461
884
  </button>
462
885
  </section>
@@ -527,6 +950,7 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
527
950
  type="button"
528
951
  disabled={
529
952
  busy === "shipping" ||
953
+ !addressOnCart ||
530
954
  (Boolean(pickup) && selectedPickupPoint?.provider !== pickup)
531
955
  }
532
956
  onClick={() => void saveShipping()}
@@ -550,7 +974,7 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
550
974
  className={`choice-card choice-button${selectedProvider === id ? " selected" : ""}`}
551
975
  type="button"
552
976
  key={id}
553
- disabled={busy === "payment"}
977
+ disabled={busy === "payment" || !addressOnCart}
554
978
  onClick={() => void preparePayment(id)}
555
979
  >
556
980
  <strong>{providerLabel(id, cod)}</strong>
@@ -561,24 +985,43 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
561
985
  </div>
562
986
  )}
563
987
 
564
- {stripeSelected && stripeSecret && config.payments.stripe.publishable_key ? (
988
+ {stripePhase === "preparing" ? (
989
+ <div className="stripe-payment-loading" role="status" aria-live="polite" aria-busy="true">
990
+ <span className="stripe-loading-spinner" aria-hidden="true" />
991
+ <span>{localized(locale,
992
+ "Stripe fizetés előkészítése…", "Preparing Stripe payment…")}</span>
993
+ </div>
994
+ ) : stripePhase === "ready" && stripeSecret && config.payments.stripe.publishable_key ? (
565
995
  <StripePayment
996
+ key={`${cartId}:${stripeSecret}`}
566
997
  publishableKey={config.payments.stripe.publishable_key}
567
998
  clientSecret={stripeSecret}
568
999
  cartId={cartId}
569
- disabled={!legalReady || busy === "complete"}
1000
+ disabled={!legalReady || !addressOnCart || busy === "complete"}
570
1001
  beforeConfirm={acceptRequiredLegal}
571
1002
  onConfirmed={completeOrder}
572
1003
  />
573
- ) : stripeSelected ? (
574
- <div className="notice warning">{copy.stripeMissingSecret}</div>
1004
+ ) : stripePhase === "error" ? (
1005
+ <div className="stack-sm">
1006
+ <div className="notice error-box" role="alert">
1007
+ {stripeInitError || copy.stripeMissingSecret}
1008
+ </div>
1009
+ <button
1010
+ className="button secondary"
1011
+ type="button"
1012
+ disabled={busy === "payment" || !addressOnCart}
1013
+ onClick={() => void preparePayment(activeProviderId)}
1014
+ >
1015
+ {localized(locale, "Stripe fizetés újrapróbálása", "Retry Stripe payment")}
1016
+ </button>
1017
+ </div>
575
1018
  ) : null}
576
1019
 
577
1020
  {simplePaySelected ? (
578
1021
  <button
579
1022
  className="button button-large"
580
1023
  type="button"
581
- disabled={!simplePayRedirect || !legalReady}
1024
+ disabled={!simplePayRedirect || !legalReady || !addressOnCart}
582
1025
  onClick={() =>
583
1026
  void acceptRequiredLegal()
584
1027
  .then(() => {
@@ -601,7 +1044,7 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
601
1044
  <button
602
1045
  className="button button-large"
603
1046
  type="button"
604
- disabled={!legalReady || busy === "complete"}
1047
+ disabled={!legalReady || !addressOnCart || busy === "complete"}
605
1048
  onClick={() =>
606
1049
  void acceptRequiredLegal()
607
1050
  .then(completeOrder)
@@ -688,19 +1131,7 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
688
1131
  }
689
1132
 
690
1133
  function emptyAddress(country: string): AddressState {
691
- return {
692
- email: "",
693
- first_name: "",
694
- last_name: "",
695
- company: "",
696
- phone: "",
697
- country_code: country.toUpperCase(),
698
- postal_code: "",
699
- city: "",
700
- province: "",
701
- address_1: "",
702
- address_2: "",
703
- }
1134
+ return emptyCheckoutAddress(country)
704
1135
  }
705
1136
 
706
1137
  function updateAddress(
@@ -765,6 +1196,39 @@ function checkoutAddressErrors(
765
1196
  return errors
766
1197
  }
767
1198
 
1199
+ function checkoutBillingAddressErrors(
1200
+ address: CheckoutAddress,
1201
+ locale: StorefrontLocale,
1202
+ ): Partial<Record<keyof CheckoutAddress, string>> {
1203
+ const errors: Partial<Record<keyof CheckoutAddress, string>> = {}
1204
+ const required: Array<[keyof CheckoutAddress, string]> = [
1205
+ ["first_name", localized(locale, "Keresztnév", "First name")],
1206
+ ["last_name", localized(locale, "Vezetéknév", "Last name")],
1207
+ ["country_code", localized(locale, "Országkód", "Country code")],
1208
+ ["postal_code", localized(locale, "Irányítószám", "Postal code")],
1209
+ ["city", localized(locale, "Város", "City")],
1210
+ ["address_1", localized(locale, "Utca és házszám", "Street address")],
1211
+ ]
1212
+ for (const [key, label] of required) {
1213
+ try {
1214
+ requireShippingText(address[key], { carrier: "Számlázás", field: label, maxLength: 150 })
1215
+ } catch (cause) {
1216
+ errors[key] = cause instanceof Error ? cause.message : localized(locale, "Kötelező mező.", "Required field.")
1217
+ }
1218
+ }
1219
+ if (address.country_code.trim() && !/^[A-Za-z]{2}$/.test(address.country_code.trim())) {
1220
+ errors.country_code = localized(locale, "Kétbetűs országkód szükséges.", "Enter a two-letter country code.")
1221
+ }
1222
+ if (address.phone.trim()) {
1223
+ try {
1224
+ normalizeShippingPhone(address.phone, { carrier: "Számlázás", field: localized(locale, "Telefonszám", "Phone") })
1225
+ } catch (cause) {
1226
+ errors.phone = cause instanceof Error ? cause.message : localized(locale, "Érvénytelen telefonszám.", "Invalid phone.")
1227
+ }
1228
+ }
1229
+ return errors
1230
+ }
1231
+
768
1232
  function SectionTitle({ step, title }: { step: string; title: string }) {
769
1233
  return <div className="section-title"><span className="step-badge">{step}</span><h2>{title}</h2></div>
770
1234
  }