@hszrdm/create-commerce 1.9.1 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,22 +1,22 @@
1
1
  #!/usr/bin/env node
2
2
  // Shared development/production operations for generated HSZRDM shops.
3
3
  // Environment selection is explicit: never reuse a production database in dev.
4
- import { existsSync, readFileSync } from "node:fs"
4
+ import { existsSync, readFileSync, mkdirSync, writeFileSync } from "node:fs"
5
5
  import { resolve, join } from "node:path"
6
6
  import { spawnSync, spawn } from "node:child_process"
7
7
 
8
8
  const [action, target, ...rest] = process.argv.slice(2)
9
- if (!["install", "deploy", "backup", "restore"].includes(action) || !["dev", "prod"].includes(target)) {
10
- console.error("Usage: node scripts/commerce-ops.mjs <install|deploy|backup|restore> <dev|prod> [--from ...] [--yes]")
9
+ if (!["install", "deploy", "backup", "restore"].includes(action) || !["dev", "staging", "prod"].includes(target)) {
10
+ console.error("Usage: node scripts/commerce-ops.mjs <install|deploy|backup|restore> <dev|staging|prod> [--from ...] [--yes]")
11
11
  process.exit(2)
12
12
  }
13
13
  const root = process.cwd()
14
14
  const backendDir = existsSync(join(root, "backend")) ? join(root, "backend") : join(root, "apps/backend")
15
- const envPath = join(backendDir, target === "prod" ? ".env.production" : ".env")
15
+ const envPath = join(backendDir, target === "prod" ? ".env.production" : target === "staging" ? ".env.staging" : ".env")
16
16
  if (!existsSync(envPath)) throw new Error(`Missing ${envPath}. Configure it before ${target} operations.`)
17
17
  const envFile = parseEnv(readFileSync(envPath, "utf8"))
18
- const expectedApp = target === "prod" ? "production" : "development"
19
- const expectedNode = target === "prod" ? "production" : "development"
18
+ const expectedApp = target === "prod" ? "production" : target === "staging" ? "staging" : "development"
19
+ const expectedNode = target === "dev" ? "development" : "production"
20
20
  if (envFile.APP_ENV && envFile.APP_ENV !== expectedApp) {
21
21
  throw new Error(`Environment mismatch: expected APP_ENV=${expectedApp} in ${envPath}`)
22
22
  }
@@ -25,14 +25,22 @@ if (envFile.NODE_ENV && envFile.NODE_ENV !== expectedNode) {
25
25
  }
26
26
  if (!envFile.DATABASE_URL) throw new Error(`DATABASE_URL is missing from ${envPath}`)
27
27
  const dbName = databaseIdentity(envFile.DATABASE_URL)
28
- const otherPath = join(backendDir, target === "prod" ? ".env" : ".env.production")
29
- if (existsSync(otherPath)) {
28
+ for (const [otherTarget, name] of [["dev", ".env"], ["staging", ".env.staging"], ["prod", ".env.production"]]) {
29
+ if (otherTarget === target) continue
30
+ const otherPath = join(backendDir, name)
31
+ if (!existsSync(otherPath)) continue
30
32
  const other = parseEnv(readFileSync(otherPath, "utf8"))
31
33
  if (other.DATABASE_URL && databaseIdentity(other.DATABASE_URL) === dbName) {
32
- throw new Error("Dev and prod may not share the same database connection.")
34
+ throw new Error(`Database conflict: ${target} and ${otherTarget} point to the same database.`)
33
35
  }
34
36
  }
35
37
  const env = { ...process.env, ...envFile, APP_ENV: expectedApp, NODE_ENV: expectedNode }
38
+ const shopName = JSON.parse(readFileSync(join(root, "package.json"), "utf8")).name
39
+ if (!shopName || !/^[a-z0-9][a-z0-9._-]*$/.test(shopName)) throw new Error("Invalid webshop package name.")
40
+ const pm2Names = target === "staging"
41
+ ? `${shopName}-staging-backend,${shopName}-staging-storefront`
42
+ : `${shopName}-backend,${shopName}-storefront`
43
+
36
44
  console.log(`HSZRDM ${action}:${target} | DB: ${new URL(envFile.DATABASE_URL).pathname.slice(1)}`)
37
45
 
38
46
  function run(command, args) {
@@ -98,8 +106,25 @@ if (action === "restore") {
98
106
  ...(rest.includes("--yes") ? ["--yes"] : []),
99
107
  ...(rest.includes("--overwrite-files") ? ["--overwrite-files"] : [])])
100
108
  }
109
+ // A deployment build writes into one shared workspace. Lock a checkout to a
110
+ // single deployed runtime so staging cannot overwrite production artifacts.
111
+ function lockDeploymentEnvironment() {
112
+ if (target === "dev") return
113
+ const stateDir = join(root, ".core")
114
+ const marker = join(stateDir, "deployment-environment")
115
+ if (existsSync(marker)) {
116
+ const previous = readFileSync(marker, "utf8").trim()
117
+ if (previous !== target) {
118
+ throw new Error(`This checkout was deployed as ${previous}. Use a separate checkout for ${target}.`)
119
+ }
120
+ } else {
121
+ mkdirSync(stateDir, { recursive: true })
122
+ writeFileSync(marker, target + "\n", { flag: "wx", mode: 0o600 })
123
+ }
124
+ }
101
125
  if (action === "install") npm(["ci"])
102
126
  if (action === "deploy") {
127
+ lockDeploymentEnvironment()
103
128
  npm(["ci"])
104
129
  backup()
105
130
  npm(["run", "db:migrate"])
@@ -110,7 +135,8 @@ if (action === "deploy") {
110
135
  if (!existsSync(join(root, "ecosystem.config.cjs"))) {
111
136
  throw new Error("Missing ecosystem.config.cjs: cannot safely reload production PM2.")
112
137
  }
113
- run("pm2", ["startOrReload", "ecosystem.config.cjs", "--env", "production", "--update-env"])
138
+ run("pm2", ["startOrReload", "ecosystem.config.cjs", "--env", target === "staging" ? "staging" : "production", "--only",
139
+ pm2Names, "--update-env"])
114
140
  run("pm2", ["save"])
115
141
  }
116
142
  }
@@ -7,7 +7,9 @@
7
7
  "build": "next build",
8
8
  "start": "next start",
9
9
  "typecheck": "tsc --noEmit",
10
- "test:pickup": "node --experimental-strip-types --test tests/carrier-pickup-adapter.test.mjs"
10
+ "test:pickup": "node --experimental-strip-types --test tests/carrier-pickup-adapter.test.mjs",
11
+ "test:validation": "node --experimental-strip-types --test tests/shipping-input-validation.test.mjs",
12
+ "test:errors": "node --experimental-strip-types --test tests/public-error.test.mjs"
11
13
  },
12
14
  "dependencies": {
13
15
  "@stripe/react-stripe-js": "7.0.0",
@@ -1,13 +1,23 @@
1
1
  "use client"
2
2
 
3
- export default function ErrorPage({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) {
3
+ import { usePathname } from "next/navigation"
4
+ import { localeFromPathname } from "@/lib/storefront-routes"
5
+
6
+ /** Never render error.message: it can include upstream credentials or internals. */
7
+ export default function ErrorPage({ reset }: { error: Error & { digest?: string }; reset: () => void }) {
8
+ const locale = localeFromPathname(usePathname())
9
+ const en = locale === "en"
4
10
  return (
5
11
  <div className="page-section narrow-page">
6
- <section className="panel stack">
7
- <p className="eyebrow">Hiba</p>
8
- <h1>Valami nem sikerült.</h1>
9
- <p className="muted">{error.message || "Az oldal betöltése közben hiba történt."}</p>
10
- <button className="button" type="button" onClick={reset}>Újrapróbálás</button>
12
+ <section className="panel stack" role="alert">
13
+ <p className="eyebrow">{en ? "Error" : "Hiba"}</p>
14
+ <h1>{en ? "Something went wrong." : "Valami nem sikerült."}</h1>
15
+ <p className="muted">{en
16
+ ? "This part of the shop is temporarily unavailable. Please try again."
17
+ : "A webshop ezen része most nem érhető el. Kérjük, próbáld újra."}</p>
18
+ <button className="button" type="button" onClick={reset}>
19
+ {en ? "Try again" : "Újrapróbálkozás"}
20
+ </button>
11
21
  </section>
12
22
  </div>
13
23
  )
@@ -0,0 +1,22 @@
1
+ "use client"
2
+
3
+ /** Last-resort Next.js UI boundary; never render raw exception messages. */
4
+ export default function GlobalError({ reset }: { error: Error & { digest?: string }; reset: () => void }) {
5
+ return (
6
+ <html lang="hu">
7
+ <body style={{ fontFamily: "system-ui, sans-serif", margin: 0, padding: "4rem 1rem", background: "#f6f7f9", color: "#18212b" }}>
8
+ <main style={{ maxWidth: 600, margin: "0 auto", padding: "2rem", background: "#ffffff", borderRadius: 16 }}>
9
+ <h1>A webshop átmenetileg nem érhető el.</h1>
10
+ <p>Kérjük, próbáld újra. Ha a probléma továbbra is fennáll, keresd az ügyfélszolgálatot.</p>
11
+ <button
12
+ type="button"
13
+ onClick={reset}
14
+ style={{ padding: "12px 20px", borderRadius: 8, background: "#195886", color: "#fff", border: 0, cursor: "pointer" }}
15
+ >
16
+ Újrapróbálkozás
17
+ </button>
18
+ </main>
19
+ </body>
20
+ </html>
21
+ )
22
+ }
@@ -1,5 +1,9 @@
1
1
  import { getCoreConfig, medusaRawFetch } from "@/lib/core/client"
2
2
 
3
+ // The Medusa backend is not running during a fresh webshop's Next.js build.
4
+ // Resolve the SEO contract at request time so build never fetches live API data.
5
+ export const dynamic = "force-dynamic"
6
+
3
7
  export async function GET() {
4
8
  const config = await getCoreConfig()
5
9
  const response = await medusaRawFetch(config.seo.robots_source_endpoint, {
@@ -1,5 +1,9 @@
1
1
  import { getCoreConfig, medusaRawFetch } from "@/lib/core/client"
2
2
 
3
+ // The Medusa backend is not running during a fresh webshop's Next.js build.
4
+ // Resolve the SEO contract at request time so build never fetches live API data.
5
+ export const dynamic = "force-dynamic"
6
+
3
7
  export async function GET() {
4
8
  const config = await getCoreConfig()
5
9
  const response = await medusaRawFetch(config.seo.sitemap_source_endpoint, {
@@ -1,6 +1,6 @@
1
1
  "use client"
2
2
 
3
- import { useCallback, useEffect, useMemo, useRef, useState } from "react"
3
+ import { useCallback, useEffect, useMemo, useRef, useState, useId } from "react"
4
4
  import { usePathname, useRouter, useSearchParams } from "next/navigation"
5
5
  import { useCart } from "./cart-provider"
6
6
  import { StripePayment } from "./stripe-payment"
@@ -8,6 +8,7 @@ import { carrierPointToShippingData, type CarrierPickupPoint } from "./carrier-p
8
8
  import { CarrierPickupDialog } from "./carrier-pickup-dialog"
9
9
  import { normalizeCarrierPickupPoint } from "./carrier-pickup-adapter"
10
10
  import { checkoutApi } from "@/lib/core/checkout"
11
+ import { normalizeShippingPhone, requireShippingText, validateShippingEmail } from "@/lib/core/shipping-input-validation"
11
12
  import {
12
13
  activePaymentSession,
13
14
  asRecords,
@@ -74,6 +75,7 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
74
75
  const returnAttempted = useRef(false)
75
76
 
76
77
  const [address, setAddress] = useState<AddressState>(() => emptyAddress(config.store.default_country))
78
+ const [addressErrors, setAddressErrors] = useState<Partial<Record<keyof AddressState, string>>>({})
77
79
  const [shippingOptions, setShippingOptions] = useState<JsonRecord[]>([])
78
80
  const [selectedShipping, setSelectedShipping] = useState<JsonRecord | null>(null)
79
81
  const [selectedPickupPoint, setSelectedPickupPoint] = useState<CarrierPickupPoint | null>(null)
@@ -241,9 +243,23 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
241
243
 
242
244
  const saveAddress = async () => {
243
245
  if (!cartId) {
244
- throw new Error(localized(locale, "A kosár még nem áll készen.", "The cart is not ready yet."))
246
+ setError(localized(locale, "A kosár még nem áll készen.", "The cart is not ready yet."))
247
+ return
245
248
  }
246
- validateAddress(address, locale)
249
+ const courier = selectedShipping ? shippingCarrier(selectedShipping) : null
250
+ const errors = checkoutAddressErrors(address, courier, locale)
251
+ 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."))
254
+ return
255
+ }
256
+ const normalizedPhone = normalizeShippingPhone(address.phone, {
257
+ carrier: courier || "Szállítás",
258
+ field: "Telefonszám",
259
+ hungarianMobileOnly: courier === "FOXPOST",
260
+ })
261
+ const normalizedEmail = validateShippingEmail(address.email, { carrier: courier || "Szállítás" })
262
+ setAddress((current) => ({ ...current, phone: normalizedPhone, email: normalizedEmail }))
247
263
  setBusy("address")
248
264
  setError(null)
249
265
  try {
@@ -251,7 +267,7 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
251
267
  first_name: address.first_name,
252
268
  last_name: address.last_name,
253
269
  company: address.company || undefined,
254
- phone: address.phone,
270
+ phone: normalizedPhone,
255
271
  country_code: address.country_code.toLowerCase(),
256
272
  postal_code: address.postal_code,
257
273
  city: address.city,
@@ -260,7 +276,7 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
260
276
  address_2: address.address_2 || undefined,
261
277
  }
262
278
  await api.updateCart(cartId, {
263
- email: address.email,
279
+ email: normalizedEmail,
264
280
  shipping_address: shippingAddress,
265
281
  billing_address: shippingAddress,
266
282
  })
@@ -280,6 +296,7 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
280
296
 
281
297
  const selectShippingOption = (option: JsonRecord) => {
282
298
  setSelectedShipping(option)
299
+ setAddressErrors(checkoutAddressErrors(address, shippingCarrier(option), locale))
283
300
  setSelectedPickupPoint(null)
284
301
  setPickupDialogOpen(false)
285
302
  setError(null)
@@ -321,6 +338,12 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
321
338
  }
322
339
  const optionId = stringValue(selectedShipping.id)
323
340
  const kind = pickupKind(selectedShipping)
341
+ const errors = checkoutAddressErrors(address, shippingCarrier(selectedShipping), locale)
342
+ setAddressErrors(errors)
343
+ if (Object.keys(errors).length) {
344
+ setError(localized(locale, "Javítsd a címzettadatokat a szállítási mód mentése előtt.", "Correct the contact details before choosing shipping."))
345
+ return
346
+ }
324
347
  setBusy("shipping")
325
348
  setError(null)
326
349
  try {
@@ -388,6 +411,24 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
388
411
  }
389
412
 
390
413
  const pickup = selectedShipping ? pickupKind(selectedShipping) : null
414
+ const setAddressField = (key: keyof AddressState, value: string) => {
415
+ updateAddress(setAddress, key, value)
416
+ if (addressErrors[key]) setAddressErrors((current) => ({ ...current, [key]: undefined }))
417
+ }
418
+ const blurAddressField = (key: keyof AddressState) => {
419
+ const courier = selectedShipping ? shippingCarrier(selectedShipping) : null
420
+ const fieldError = checkoutAddressErrors(address, courier, locale)[key]
421
+ setAddressErrors((current) => ({ ...current, [key]: fieldError }))
422
+ if (!fieldError && key === "phone" && address.phone.trim()) {
423
+ setAddress((current) => ({
424
+ ...current,
425
+ phone: normalizeShippingPhone(current.phone, {
426
+ carrier: courier || "Szállítás",
427
+ hungarianMobileOnly: courier === "FOXPOST",
428
+ }),
429
+ }))
430
+ }
431
+ }
391
432
  const effectiveCart = preparedCart || cart
392
433
  const session = activePaymentSession(effectiveCart)
393
434
  const activeProviderId = providerId(session) || selectedProvider
@@ -404,16 +445,16 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
404
445
  <section className="panel stack">
405
446
  <SectionTitle step="1" title={copy.contactAndAddress} />
406
447
  <div className="form-grid two-col">
407
- <Field label={copy.email} value={address.email} type="email" onChange={(value) => updateAddress(setAddress, "email", value)} />
408
- <Field label={copy.phone} value={address.phone} onChange={(value) => updateAddress(setAddress, "phone", value)} />
409
- <Field label={copy.firstName} value={address.first_name} onChange={(value) => updateAddress(setAddress, "first_name", value)} />
410
- <Field label={copy.lastName} value={address.last_name} onChange={(value) => updateAddress(setAddress, "last_name", value)} />
411
- <Field label={copy.companyOptional} value={address.company} onChange={(value) => updateAddress(setAddress, "company", value)} />
412
- <Field label={copy.country} value={address.country_code} onChange={(value) => updateAddress(setAddress, "country_code", value.toUpperCase())} />
413
- <Field label={copy.postalCode} value={address.postal_code} onChange={(value) => updateAddress(setAddress, "postal_code", value)} />
414
- <Field label={copy.city} value={address.city} onChange={(value) => updateAddress(setAddress, "city", value)} />
415
- <Field label={copy.address1} value={address.address_1} onChange={(value) => updateAddress(setAddress, "address_1", value)} />
416
- <Field label={copy.address2} value={address.address_2} onChange={(value) => updateAddress(setAddress, "address_2", value)} />
448
+ <Field label={copy.email} value={address.email} type="email" error={addressErrors.email} onBlur={() => blurAddressField("email")} onChange={(value) => setAddressField("email", value)} />
449
+ <Field label={copy.phone} value={address.phone} type="tel" error={addressErrors.phone} onBlur={() => blurAddressField("phone")} onChange={(value) => setAddressField("phone", value)} />
450
+ <Field label={copy.firstName} value={address.first_name} error={addressErrors.first_name} onBlur={() => blurAddressField("first_name")} onChange={(value) => setAddressField("first_name", value)} />
451
+ <Field label={copy.lastName} value={address.last_name} error={addressErrors.last_name} onBlur={() => blurAddressField("last_name")} onChange={(value) => setAddressField("last_name", value)} />
452
+ <Field label={copy.companyOptional} value={address.company} error={addressErrors.company} onBlur={() => blurAddressField("company")} onChange={(value) => setAddressField("company", value)} />
453
+ <Field label={copy.country} value={address.country_code} error={addressErrors.country_code} onBlur={() => blurAddressField("country_code")} onChange={(value) => setAddressField("country_code", value.toUpperCase())} />
454
+ <Field label={copy.postalCode} value={address.postal_code} error={addressErrors.postal_code} onBlur={() => blurAddressField("postal_code")} onChange={(value) => setAddressField("postal_code", value)} />
455
+ <Field label={copy.city} value={address.city} error={addressErrors.city} onBlur={() => blurAddressField("city")} onChange={(value) => setAddressField("city", value)} />
456
+ <Field label={copy.address1} value={address.address_1} error={addressErrors.address_1} onBlur={() => blurAddressField("address_1")} onChange={(value) => setAddressField("address_1", value)} />
457
+ <Field label={copy.address2} value={address.address_2} error={addressErrors.address_2} onBlur={() => blurAddressField("address_2")} onChange={(value) => setAddressField("address_2", value)} />
417
458
  </div>
418
459
  <button className="button secondary" type="button" disabled={busy === "address" || mutating} onClick={() => void saveAddress()}>
419
460
  {busy === "address" ? copy.saving : copy.saveAddressAndLoadShipping}
@@ -670,39 +711,58 @@ function updateAddress(
670
711
  setter((current) => ({ ...current, [key]: value }))
671
712
  }
672
713
 
673
- function validateAddress(address: AddressState, locale: StorefrontLocale) {
674
- if (!/^\S+@\S+\.\S+$/.test(address.email)) {
675
- throw new Error(localized(locale, "Érvényes e-mail-cím szükséges.", "Enter a valid email address."))
676
- }
677
- const fields = locale === "en"
678
- ? [
679
- ["first name", address.first_name],
680
- ["last name", address.last_name],
681
- ["phone", address.phone],
682
- ["country", address.country_code],
683
- ["postal code", address.postal_code],
684
- ["city", address.city],
685
- ["address", address.address_1],
686
- ] as const
687
- : [
688
- ["keresztnév", address.first_name],
689
- ["vezetéknév", address.last_name],
690
- ["telefon", address.phone],
691
- ["ország", address.country_code],
692
- ["irányítószám", address.postal_code],
693
- ["város", address.city],
694
- ["cím", address.address_1],
695
- ] as const
696
-
697
- for (const [label, value] of fields) {
698
- if (!value.trim()) {
699
- throw new Error(
700
- locale === "en"
701
- ? `The ${label} field is required.`
702
- : `A(z) ${label} megadása kötelező.`,
703
- )
714
+ type CheckoutCarrier = "FOXPOST" | "GLS" | "MPL" | "Packeta" | "DPD" | null
715
+
716
+ function shippingCarrier(option: JsonRecord): CheckoutCarrier {
717
+ const value = `${stringValue(option.id)} ${stringValue(option.name)} ${stringValue(option.provider_id)} ${JSON.stringify(option.data || {})}`.toLowerCase()
718
+ if (value.includes("foxpost")) return "FOXPOST"
719
+ if (value.includes("gls")) return "GLS"
720
+ if (value.includes("mpl") || value.includes("posta")) return "MPL"
721
+ if (value.includes("packeta")) return "Packeta"
722
+ if (value.includes("dpd")) return "DPD"
723
+ return null
724
+ }
725
+
726
+ function checkoutAddressErrors(
727
+ address: AddressState,
728
+ courier: CheckoutCarrier,
729
+ locale: StorefrontLocale,
730
+ ): Partial<Record<keyof AddressState, string>> {
731
+ const errors: Partial<Record<keyof AddressState, string>> = {}
732
+ const carrier = courier || "Szállítás"
733
+ const requiredFields: Array<[keyof AddressState, string]> = [
734
+ ["first_name", localized(locale, "Keresztnév", "First name")],
735
+ ["last_name", localized(locale, "Vezetéknév", "Last name")],
736
+ ["country_code", localized(locale, "Országkód", "Country code")],
737
+ ["postal_code", localized(locale, "Irányítószám", "Postal code")],
738
+ ["city", localized(locale, "Város", "City")],
739
+ ["address_1", localized(locale, "Utca és házszám", "Street address")],
740
+ ]
741
+ for (const [field, label] of requiredFields) {
742
+ try {
743
+ requireShippingText(address[field], { carrier, field: label, maxLength: 150 })
744
+ } catch (cause) {
745
+ errors[field] = cause instanceof Error ? cause.message : localized(locale, "Kötelező mező.", "Required field.")
704
746
  }
705
747
  }
748
+ if (address.country_code.trim() && !/^[A-Za-z]{2}$/.test(address.country_code.trim())) {
749
+ errors.country_code = localized(locale, "Kétbetűs országkód szükséges (pl. HU).", "Enter a two-letter country code (e.g. HU).")
750
+ }
751
+ try {
752
+ validateShippingEmail(address.email, { carrier, field: localized(locale, "E-mail-cím", "Email") })
753
+ } catch (cause) {
754
+ errors.email = cause instanceof Error ? cause.message : localized(locale, "Érvénytelen e-mail-cím.", "Invalid email.")
755
+ }
756
+ try {
757
+ normalizeShippingPhone(address.phone, {
758
+ carrier,
759
+ field: localized(locale, "Telefonszám", "Phone"),
760
+ hungarianMobileOnly: courier === "FOXPOST",
761
+ })
762
+ } catch (cause) {
763
+ errors.phone = cause instanceof Error ? cause.message : localized(locale, "Érvénytelen telefonszám.", "Invalid phone.")
764
+ }
765
+ return errors
706
766
  }
707
767
 
708
768
  function SectionTitle({ step, title }: { step: string; title: string }) {
@@ -713,14 +773,32 @@ function Field({
713
773
  label,
714
774
  value,
715
775
  onChange,
776
+ onBlur,
777
+ error,
716
778
  type = "text",
717
779
  }: {
718
780
  label: string
719
781
  value: string
720
782
  onChange: (value: string) => void
783
+ onBlur?: () => void
784
+ error?: string
721
785
  type?: string
722
786
  }) {
723
- return <label>{label}<input type={type} value={value} onChange={(event) => onChange(event.target.value)} /></label>
787
+ const errorId = useId()
788
+ return (
789
+ <label>
790
+ {label}
791
+ <input
792
+ type={type}
793
+ value={value}
794
+ onChange={(event) => onChange(event.target.value)}
795
+ onBlur={onBlur}
796
+ aria-invalid={Boolean(error)}
797
+ aria-describedby={error ? errorId : undefined}
798
+ />
799
+ {error ? <small id={errorId} role="alert" style={{ color: "var(--error, #b91c1c)" }}>{error}</small> : null}
800
+ </label>
801
+ )
724
802
  }
725
803
 
726
804
  function pickupKind(option: JsonRecord): PickupKind {
@@ -1,10 +1,14 @@
1
1
  "use client"
2
2
 
3
- import { useMemo, useState } from "react"
3
+ import { useMemo, useRef, useState } from "react"
4
4
  import { usePathname } from "next/navigation"
5
- import { Elements, PaymentElement, useElements, useStripe } from "@stripe/react-stripe-js"
5
+ import { Elements, ExpressCheckoutElement, PaymentElement, useElements, useStripe } from "@stripe/react-stripe-js"
6
6
  import { loadStripe } from "@stripe/stripe-js/pure"
7
7
  import { localeFromPathname, STOREFRONT_ROUTES } from "@/lib/storefront-routes"
8
+ import { CoreApiError } from "@/lib/core/client"
9
+ import { stripePublicError } from "@/lib/core/public-error"
10
+
11
+ class CustomerPaymentError extends Error {}
8
12
 
9
13
  export function StripePayment({
10
14
  publishableKey,
@@ -52,6 +56,46 @@ function StripePaymentForm({
52
56
  const checkoutPath = STOREFRONT_ROUTES[locale].checkout
53
57
  const [busy, setBusy] = useState(false)
54
58
  const [error, setError] = useState<string | null>(null)
59
+ const [walletAvailable, setWalletAvailable] = useState(false)
60
+ const [revolutSelected, setRevolutSelected] = useState(false)
61
+ const paymentSection = useRef<HTMLDivElement>(null)
62
+
63
+ const returnUrl = () => {
64
+ const url = new URL(checkoutPath, window.location.origin)
65
+ url.searchParams.set("cart_id", cartId)
66
+ url.searchParams.set("stripe_return", "1")
67
+ return url.toString()
68
+ }
69
+
70
+ const confirmWallet = async () => {
71
+ if (!stripe || !elements || disabled || busy) return
72
+ setBusy(true)
73
+ setError(null)
74
+ try {
75
+ if (beforeConfirm) await beforeConfirm()
76
+ const submitted = await elements.submit()
77
+ if (submitted.error) throw new CustomerPaymentError(stripePublicError(submitted.error, locale))
78
+ const result = await stripe.confirmPayment({
79
+ elements,
80
+ redirect: "if_required",
81
+ confirmParams: { return_url: returnUrl() },
82
+ })
83
+ if (result.error) throw new CustomerPaymentError(stripePublicError(result.error, locale))
84
+ await onConfirmed()
85
+ } catch (cause) {
86
+ setError(
87
+ cause instanceof CoreApiError || cause instanceof CustomerPaymentError
88
+ ? cause.message : stripePublicError(null, locale),
89
+ )
90
+ } finally {
91
+ setBusy(false)
92
+ }
93
+ }
94
+
95
+ const chooseRevolut = () => {
96
+ setRevolutSelected(true)
97
+ paymentSection.current?.scrollIntoView({ behavior: "smooth", block: "center" })
98
+ }
55
99
 
56
100
  const submit = async () => {
57
101
  if (!stripe || !elements || disabled) return
@@ -59,28 +103,20 @@ function StripePaymentForm({
59
103
  setError(null)
60
104
  try {
61
105
  if (beforeConfirm) await beforeConfirm()
62
- const returnUrl = new URL(checkoutPath, window.location.origin)
63
- returnUrl.searchParams.set("cart_id", cartId)
64
- returnUrl.searchParams.set("stripe_return", "1")
106
+
65
107
  const result = await stripe.confirmPayment({
66
108
  elements,
67
109
  redirect: "if_required",
68
- confirmParams: { return_url: returnUrl.toString() },
110
+ confirmParams: { return_url: returnUrl() },
69
111
  })
70
112
  if (result.error) {
71
- throw new Error(
72
- result.error.message ||
73
- (locale === "en" ? "Card payment failed." : "A bankkártyás fizetés nem sikerült."),
74
- )
113
+ throw new Error(stripePublicError(result.error, locale))
75
114
  }
76
115
  await onConfirmed()
77
116
  } catch (cause) {
78
117
  setError(
79
- cause instanceof Error
80
- ? cause.message
81
- : locale === "en"
82
- ? "Card payment failed."
83
- : "A bankkártyás fizetés nem sikerült.",
118
+ cause instanceof CoreApiError || cause instanceof CustomerPaymentError
119
+ ? cause.message : stripePublicError(null, locale),
84
120
  )
85
121
  } finally {
86
122
  setBusy(false)
@@ -89,7 +125,50 @@ function StripePaymentForm({
89
125
 
90
126
  return (
91
127
  <div className="stack-sm">
92
- <div className="stripe-element"><PaymentElement /></div>
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%" }}
159
+ >
160
+ Revolut Pay
161
+ </button>
162
+ </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}
170
+ </div>
171
+ <div ref={paymentSection} className="stripe-element"><PaymentElement /></div>
93
172
  {error ? <p className="error">{error}</p> : null}
94
173
  <button
95
174
  className="button button-large"
@@ -1,4 +1,5 @@
1
1
  import type { CoreConfig } from "./types"
2
+ import { networkError, publicApiError } from "./public-error"
2
3
  import { localeFromPathname, medusaLocale } from "@/lib/storefront-routes"
3
4
 
4
5
  type CoreFetchInit = RequestInit & {
@@ -43,11 +44,18 @@ export async function medusaRawFetch(
43
44
  headers.set("x-medusa-locale", medusaLocale(localeFromPathname(window.location.pathname)))
44
45
  }
45
46
 
46
- return fetch(`${getBackendUrl()}${normalizePath(path)}`, {
47
- ...init,
48
- headers,
49
- credentials: "include",
50
- })
47
+ try {
48
+ return await fetch(`${getBackendUrl()}${normalizePath(path)}`, {
49
+ ...init,
50
+ headers,
51
+ credentials: "include",
52
+ })
53
+ } catch (cause) {
54
+ // Timeouts, DNS failures and CORS errors must not expose low-level details.
55
+ if (cause instanceof Error && cause.name === "AbortError") throw cause
56
+ const locale = typeof window === "undefined" ? "hu" : localeFromPathname(window.location.pathname)
57
+ throw new CoreApiError(networkError(locale), 0, null)
58
+ }
51
59
  }
52
60
 
53
61
  export async function medusaFetch<T = unknown>(
@@ -61,10 +69,8 @@ export async function medusaFetch<T = unknown>(
61
69
  : await response.text().catch(() => "")
62
70
 
63
71
  if (!response.ok) {
64
- const message =
65
- payload && typeof payload === "object" && "message" in payload
66
- ? String((payload as { message?: unknown }).message || "API hiba")
67
- : `Medusa API hiba (${response.status})`
72
+ const locale = typeof window === "undefined" ? "hu" : localeFromPathname(window.location.pathname)
73
+ const message = publicApiError(response.status, payload, locale, path)
68
74
  throw new CoreApiError(message, response.status, payload)
69
75
  }
70
76