@hszrdm/create-commerce 1.17.0 → 1.19.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hszrdm/create-commerce",
3
- "version": "1.17.0",
3
+ "version": "1.19.0",
4
4
  "description": "Create a complete HSZRDM Commerce webshop project.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -298,6 +298,10 @@ GLS_HOME_DELIVERY_PRICE_HUF=1990
298
298
  GLS_FREE_SHIPPING_THRESHOLD_HUF=
299
299
  GLS_TIMEOUT_MS=15000
300
300
  GLS_PRINTER_TYPE=A4_2x2
301
+ # Optional absolute PRIVATE directory for original GLS PDF labels.
302
+ # Default: a non-public sibling of FILE_UPLOAD_DIR (.hszrdm-gls-private-labels).
303
+ # Must survive deploy and be included in filesystem backups. Never expose via /static.
304
+ GLS_PRIVATE_LABEL_DIR=
301
305
  GLS_WEBSHOP_ENGINE=HSZRDM Commerce
302
306
  GLS_PICKUP_NAME=Example Store
303
307
  GLS_PICKUP_STREET=
@@ -23,7 +23,7 @@
23
23
  "start:prod": "cd .medusa/server && medusa start"
24
24
  },
25
25
  "dependencies": {
26
- "@hszrdm/core": "1.17.0",
26
+ "@hszrdm/core": "1.19.0",
27
27
  "@medusajs/admin-sdk": "2.22.2",
28
28
  "@medusajs/cli": "2.22.2",
29
29
  "@medusajs/draft-order": "2.22.2",
@@ -122,7 +122,9 @@ function runBackup() {
122
122
  }
123
123
 
124
124
  const copiedFiles = []
125
- for (const item of backupFileSources(projectDir, env)) {
125
+ // The archived GLS PDF scope must follow the database actually being
126
+ // backed up, including an explicit --database-url override.
127
+ for (const item of backupFileSources(projectDir, { ...env, DATABASE_URL: databaseUrl })) {
126
128
  console.log(`- ${item.key} mentése...`)
127
129
  const target = copyBackupSource(bundleDir, item)
128
130
  copiedFiles.push({ ...item, target })
@@ -13,6 +13,7 @@ import process from "node:process"
13
13
 
14
14
  import {
15
15
  backendProjectDir,
16
+ glsPrivateLabelDirectory,
16
17
  integrationSnapshotPath,
17
18
  loadRuntimeEnv,
18
19
  pgEnvironment,
@@ -65,7 +66,8 @@ if (["postgres", "template0", "template1"].includes(pg.database.toLowerCase()) |
65
66
  "Destruktív restore megtagadva. Add meg a pontos céladatbázist: --confirm-database=" + pg.database,
66
67
  )
67
68
  }
68
- assertRestoreTargets({ projectDir, bundleDir, env, overwrite: Boolean(args["overwrite-files"]) })
69
+ const restoreEnv = { ...env, DATABASE_URL: databaseUrl }
70
+ assertRestoreTargets({ projectDir, bundleDir, env: restoreEnv, overwrite: Boolean(args["overwrite-files"]) })
69
71
 
70
72
  const dumpPath = join(bundleDir, "database.dump")
71
73
  console.log("\n- PostgreSQL visszaállítása (--clean --if-exists)...")
@@ -94,7 +96,7 @@ if (existsSync(portableSource)) {
94
96
  console.log(" (szándékosan nincs automatikusan bemásolva a production .env-be)")
95
97
  }
96
98
 
97
- restoreFiles({ projectDir, bundleDir, env, overwrite: Boolean(args["overwrite-files"]) })
99
+ restoreFiles({ projectDir, bundleDir, env: restoreEnv, overwrite: Boolean(args["overwrite-files"]) })
98
100
 
99
101
  if (args.migrate) {
100
102
  console.log("- Core migrációk futtatása...")
@@ -124,6 +126,12 @@ function assertRestoreTargets({ projectDir, bundleDir, env, overwrite }) {
124
126
  }
125
127
  checks.push([uploadSource, uploadTarget])
126
128
  }
129
+ const glsSource = join(bundleDir, "files", "gls-private-labels")
130
+ if (existsSync(glsSource)) {
131
+ const glsTarget = glsPrivateLabelDirectory(env)
132
+ if (!glsTarget) throw new Error("A GLS privát PDF címkék visszaállításához abszolút FILE_UPLOAD_DIR vagy GLS_PRIVATE_LABEL_DIR és DATABASE_URL szükséges.")
133
+ checks.push([glsSource, glsTarget])
134
+ }
127
135
  for (const [source, target] of checks) {
128
136
  if (existsSync(source) && existsSync(target) && !overwrite) {
129
137
  throw new Error("A restore felülírna egy meglévő útvonalat: " + target +
@@ -158,6 +166,13 @@ function restoreFiles({ projectDir, bundleDir, env, overwrite }) {
158
166
  copyWithGuard(uploadSource, configured, overwrite)
159
167
  console.log(`- FILE_UPLOAD_DIR visszaállítva: ${configured}`)
160
168
  }
169
+ const glsSource = join(bundleDir, "files", "gls-private-labels")
170
+ if (existsSync(glsSource)) {
171
+ const target = glsPrivateLabelDirectory(env)
172
+ if (!target) throw new Error("Nem található privát GLS PDF tárolási célkönyvtár.")
173
+ copyWithGuard(glsSource, target, overwrite)
174
+ console.log("- Privát GLS PDF címkék visszaállítva a célkörnyezet elkülönített tárolójába.")
175
+ }
161
176
  }
162
177
 
163
178
  function copyWithGuard(source, target, overwrite) {
@@ -148,6 +148,33 @@ export function integrationSnapshotPath(projectDir, env) {
148
148
  return join(backendDir, ".core", "integration-settings.enc")
149
149
  }
150
150
 
151
+ /** Keep original MyGLS PDF labels alongside DB-scoped, non-public assets. */
152
+ export function glsPrivateLabelDirectory(env) {
153
+ const database = String(env.DATABASE_URL || "").trim()
154
+ if (!database) return null
155
+ const explicit = String(env.GLS_PRIVATE_LABEL_DIR || "").trim()
156
+ const uploads = String(env.FILE_UPLOAD_DIR || "").trim()
157
+ let base
158
+ if (explicit && isAbsolute(explicit) && resolve(explicit) !== "/") {
159
+ base = resolve(explicit)
160
+ } else if (!explicit && uploads && isAbsolute(uploads) && resolve(uploads) !== "/") {
161
+ base = join(dirname(resolve(uploads)), ".hszrdm-gls-private-labels")
162
+ } else {
163
+ return null
164
+ }
165
+ const url = new URL(database)
166
+ const appEnv = String(env.APP_ENV || "").trim() || (env.NODE_ENV === "production" ? "production" : "development")
167
+ // Same stable scope contract as private-label-store.ts. The connection
168
+ // host/port/user/credentials are not part of the PDF archive identity.
169
+ if (!url.pathname || url.pathname === "/") {
170
+ throw new Error("A GLS privát címketárolóhoz adatbázisnév szükséges.")
171
+ }
172
+ const scope = createHash("sha256")
173
+ .update(JSON.stringify(["gls-pdf-v2", appEnv, decodeURIComponent(url.pathname)]))
174
+ .digest("hex").slice(0, 24)
175
+ return join(base, scope)
176
+ }
177
+
151
178
  export function backupFileSources(projectDir, env) {
152
179
  const sources = []
153
180
  const backendDir = backendProjectDir(projectDir)
@@ -165,6 +192,10 @@ export function backupFileSources(projectDir, env) {
165
192
  if (configuredUpload && isAbsolute(configuredUpload) && existsSync(configuredUpload)) {
166
193
  sources.push({ key: "file_upload_dir", source: configuredUpload, relative: "files/file-upload-dir" })
167
194
  }
195
+ const glsLabels = glsPrivateLabelDirectory(env)
196
+ if (glsLabels && existsSync(glsLabels)) {
197
+ sources.push({ key: "gls_private_labels", source: glsLabels, relative: "files/gls-private-labels" })
198
+ }
168
199
  return sources
169
200
  }
170
201
 
@@ -204,6 +235,7 @@ const ARTIFACT_KINDS = new Map([
204
235
  ["files/integration-settings.enc", "file"],
205
236
  ["files/local-static", "directory"],
206
237
  ["files/file-upload-dir", "directory"],
238
+ ["files/gls-private-labels", "directory"],
207
239
  ])
208
240
  const REQUIRED_ARTIFACTS = ["database.dump", "portable-config.json", "portable-config.env"]
209
241
 
@@ -15,11 +15,17 @@ import {
15
15
  type StorefrontLocale,
16
16
  } from "@/lib/storefront-routes"
17
17
  import { useCart } from "./cart-provider"
18
+ import { AddressStreetFields } from "./address-street-fields"
19
+ import {
20
+ addressDetailsFromRecord, addressLine1, addressLine2,
21
+ addressStructuredSnapshot, emptyAddressDetails, isHungarianAddress,
22
+ missingAddressParts, type AddressDetails, CUSTOMER_STRUCTURED_ADDRESS_KEY,
23
+ } from "@/lib/core/structured-address"
18
24
 
19
25
  type AuthMode = "login" | "register" | "forgot"
20
26
  type AccountTab = "profile" | "addresses" | "orders" | "security"
21
27
 
22
- type AddressForm = {
28
+ type AddressForm = AddressDetails & {
23
29
  id: string
24
30
  address_name: string
25
31
  first_name: string
@@ -32,6 +38,7 @@ type AddressForm = {
32
38
  province: string
33
39
  address_1: string
34
40
  address_2: string
41
+ metadata: Record<string, unknown>
35
42
  }
36
43
 
37
44
  export function AccountDashboard({ config }: { config: CoreConfig }) {
@@ -266,7 +273,36 @@ function AddressesSection({
266
273
  useEffect(() => { void load() }, [load])
267
274
 
268
275
  const save = async () => {
269
- const body = { ...form, id: undefined, country_code: form.country_code.toLowerCase() }
276
+ const required = [form.first_name, form.last_name, form.postal_code, form.city, form.country_code]
277
+ if (required.some(part => !part.trim()) ||
278
+ (isHungarianAddress(form) ? missingAddressParts(form).length > 0 : !form.address_1.trim())) {
279
+ setMessage(localized(locale,
280
+ "Hiba: töltsd ki a kötelező név- és címmezőket.",
281
+ "Error: fill in all required name and address fields."))
282
+ return
283
+ }
284
+ if (!/^[a-z]{2}$/i.test(form.country_code.trim())) {
285
+ setMessage(localized(locale, "Hiba: kétbetűs országkód szükséges.", "Error: enter a two-letter country code."))
286
+ return
287
+ }
288
+ const snapshot = addressStructuredSnapshot(form)
289
+ const metadata = { ...form.metadata }
290
+ if (snapshot) metadata[CUSTOMER_STRUCTURED_ADDRESS_KEY] = snapshot
291
+ else metadata[CUSTOMER_STRUCTURED_ADDRESS_KEY] = "" // Medusa metadata deletion contract
292
+ const body = {
293
+ address_name: form.address_name,
294
+ first_name: form.first_name.trim(),
295
+ last_name: form.last_name.trim(),
296
+ company: form.company.trim() || undefined,
297
+ phone: form.phone.trim() || undefined,
298
+ country_code: form.country_code.trim().toLowerCase(),
299
+ postal_code: form.postal_code.trim(),
300
+ city: form.city.trim(),
301
+ province: form.province.trim() || undefined,
302
+ address_1: addressLine1(form),
303
+ address_2: addressLine2(form) || undefined,
304
+ metadata,
305
+ }
270
306
  if (form.id) await api.updateAddress(form.id, body)
271
307
  else await api.createAddress(body)
272
308
  setForm(emptyAddressForm(config.store.default_country))
@@ -292,10 +328,12 @@ function AddressesSection({
292
328
  <div className="divider" />
293
329
  <h2>{form.id ? copy.editAddress : copy.newAddress}</h2>
294
330
  <div className="form-grid two-col">
295
- {(["address_name", "first_name", "last_name", "company", "phone", "country_code", "postal_code", "city", "province", "address_1", "address_2"] as const).map((key) => (
331
+ {(["address_name", "first_name", "last_name", "company", "phone", "country_code", "postal_code", "city", "province"] as const).map((key) => (
296
332
  <Field key={key} label={addressLabel(key, copy)} value={form[key]} onChange={(value) => setForm((current) => ({ ...current, [key]: value }))} />
297
333
  ))}
298
334
  </div>
335
+ <AddressStreetFields address={form} locale={locale}
336
+ onChange={(key, value) => setForm(current => ({ ...current, [key]: value }))} />
299
337
  <div className="button-row">
300
338
  <button className="button" type="button" onClick={() => void save().catch((e) => setMessage(e instanceof Error ? e.message : localized(locale, "Mentési hiba.", "Save failed.")))}>{form.id ? copy.updateAddress : copy.addAddress}</button>
301
339
  {form.id ? <button className="button secondary" type="button" onClick={() => setForm(emptyAddressForm(config.store.default_country))}>{copy.cancel}</button> : null}
@@ -402,12 +440,25 @@ function Field({ label, value, onChange, type = "text", required = false }: { la
402
440
  }
403
441
 
404
442
  function emptyAddressForm(country: string): AddressForm {
405
- return { id: "", address_name: "", first_name: "", last_name: "", company: "", phone: "", country_code: country.toUpperCase(), postal_code: "", city: "", province: "", address_1: "", address_2: "" }
443
+ return {
444
+ id: "", address_name: "", first_name: "", last_name: "", company: "", phone: "",
445
+ country_code: country.toUpperCase(), postal_code: "", city: "", province: "",
446
+ address_1: "", address_2: "", metadata: {}, ...emptyAddressDetails(),
447
+ }
406
448
  }
407
449
 
408
450
  function addressToForm(address: JsonRecord, country: string): AddressForm {
409
451
  const base = emptyAddressForm(country)
410
- return Object.fromEntries(Object.keys(base).map((key) => [key, stringValue(address[key]) || base[key as keyof AddressForm]])) as unknown as AddressForm
452
+ const native = Object.fromEntries(
453
+ Object.keys(base).filter(key => key !== "metadata").map(
454
+ key => [key, stringValue(address[key]) || base[key as keyof AddressForm]],
455
+ ),
456
+ ) as unknown as AddressForm
457
+ return {
458
+ ...native,
459
+ metadata: isRecordSafe(address.metadata) ? address.metadata : {},
460
+ ...addressDetailsFromRecord(address),
461
+ }
411
462
  }
412
463
 
413
464
  function addressLabel(key: keyof Omit<AddressForm, "id">, copy: StorefrontCopy) {
@@ -0,0 +1,47 @@
1
+ "use client"
2
+
3
+ import { useId } from "react"
4
+ import { isHungarianAddress, type StructuredAddress } from "@/lib/core/structured-address"
5
+
6
+ type AddressKey = keyof StructuredAddress
7
+
8
+ /** Shared native-Medusa-compatible input for checkout and address book. */
9
+ export function AddressStreetFields({
10
+ address, locale, onChange, errors, onBlur,
11
+ }: {
12
+ address: StructuredAddress
13
+ locale: "hu" | "en"
14
+ onChange: (key: AddressKey, value: string) => void
15
+ errors?: Partial<Record<AddressKey, string>>
16
+ onBlur?: (key: AddressKey) => void
17
+ }) {
18
+ const id = useId()
19
+ const localized = (hu: string, en: string) => locale === "en" ? en : hu
20
+ const field = (key: AddressKey, hu: string, en: string) => {
21
+ const error = errors?.[key]
22
+ return <label key={key}>
23
+ {localized(hu, en)}
24
+ <input type="text" value={address[key]}
25
+ onChange={event => onChange(key, event.target.value)}
26
+ onBlur={() => onBlur?.(key)}
27
+ aria-invalid={Boolean(error)}
28
+ aria-describedby={error ? id + "-" + key : undefined} />
29
+ {error ? <small id={id + "-" + key} role="alert" className="error">{error}</small> : null}
30
+ </label>
31
+ }
32
+ if (!isHungarianAddress(address)) return <div className="form-grid two-col">
33
+ {field("address_1", "Cím első sora *", "Street address *")}
34
+ {field("address_2", "Cím második sora", "Address line 2")}
35
+ </div>
36
+ return <div className="form-grid two-col">
37
+ {field("street_name", "Közterület neve *", "Street name *")}
38
+ {field("street_type", "Közterület típusa * (utca, út, tér…)", "Street type * (street, road, square…)")}
39
+ {field("house_number", "Házszám *", "House number *")}
40
+ {field("house_number_suffix", "Házszám kiegészítés (pl. A)", "House number suffix (e.g. A)")}
41
+ {field("building", "Épület (opcionális)", "Building (optional)")}
42
+ {field("staircase", "Lépcsőház (opcionális)", "Staircase (optional)")}
43
+ {field("floor", "Emelet (opcionális)", "Floor (optional)")}
44
+ {field("door", "Ajtó (opcionális)", "Door (optional)")}
45
+ {field("address_extra", "Egyéb címadat (opcionális)", "Additional address information (optional)")}
46
+ </div>
47
+ }
@@ -3,6 +3,11 @@
3
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
+ import { AddressStreetFields } from "./address-street-fields"
7
+ import {
8
+ addressLine1, addressLine2, addressStructuredSnapshot,
9
+ CART_STRUCTURED_ADDRESSES_KEY, isHungarianAddress, missingAddressParts,
10
+ } from "@/lib/core/structured-address"
6
11
  import { StripePayment } from "./stripe-payment"
7
12
  import { stripeCheckoutPhase } from "@/lib/core/stripe-checkout-phase"
8
13
  import { carrierPointToShippingData, type CarrierPickupPoint } from "./carrier-pickup-map"
@@ -285,22 +290,24 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
285
290
  isCompany: billingIsCompany, company: candidate.company,
286
291
  billingTaxNumber, billingEuTaxNumber,
287
292
  }) : null
293
+ const snapshot = addressStructuredSnapshot(candidate)
288
294
  await account.createAddress({
289
295
  ...checkoutAddressPayload(candidate),
290
- ...(tax ? {
291
- company: tax.isCompany ? tax.company : undefined,
292
- metadata: {
296
+ ...(tax ? { company: tax.isCompany ? tax.company : undefined } : {}),
297
+ metadata: {
298
+ ...(snapshot ? { core_structured_address: snapshot } : {}),
299
+ ...(tax ? {
293
300
  billing_is_company: tax.isCompany,
294
301
  billing_tax_number: tax.billingTaxNumber,
295
302
  billing_eu_tax_number: tax.billingEuTaxNumber,
296
- },
297
- } : {}),
303
+ } : {}),
304
+ },
298
305
  })
299
306
  const { addresses } = await account.addresses()
300
307
  setSavedAddresses(addresses)
301
308
  const created = addresses.find(item =>
302
309
  !knownIds.has(stringValue(item.id)) &&
303
- stringValue(item.address_1) === candidate.address_1.trim() &&
310
+ stringValue(item.address_1) === addressLine1(candidate) &&
304
311
  stringValue(item.postal_code) === candidate.postal_code.trim())
305
312
  if (created?.id) {
306
313
  if (kind === "shipping") setShippingAddressSelection(stringValue(created.id))
@@ -497,6 +504,35 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
497
504
  billing_tax_number: validTax.billingTaxNumber,
498
505
  billing_eu_tax_number: validTax.billingEuTaxNumber,
499
506
  })
507
+ // Native Medusa metadata: no address schema changes, no new DB tables.
508
+ const latestCart = (await api.getCart(cartId)).cart
509
+ const metadata = isRecord(latestCart.metadata) ? latestCart.metadata : {}
510
+ const snapshots = {
511
+ shipping: addressStructuredSnapshot(address),
512
+ billing: addressStructuredSnapshot(billingSameAsShipping ? address : billingAddress),
513
+ }
514
+ await api.updateCart(cartId, {
515
+ metadata: { ...metadata, [CART_STRUCTURED_ADDRESSES_KEY]: snapshots },
516
+ })
517
+ const verified = (await api.getCart(cartId)).cart
518
+ const stored = isRecord(verified.metadata)
519
+ ? verified.metadata[CART_STRUCTURED_ADDRESSES_KEY] : null
520
+ // Metadata is jsonb in PostgreSQL: key order need not match the client.
521
+ // Check the stored fields semantically rather than comparing JSON strings.
522
+ const persisted = isRecord(stored) ? stored : {}
523
+ const matchesSnapshot = (key: "shipping" | "billing") => {
524
+ const expected = snapshots[key]
525
+ const actual = persisted[key]
526
+ if (expected === null) return actual == null
527
+ return isRecord(actual) && Object.entries(expected).every(
528
+ ([field, value]) => actual[field] === value,
529
+ )
530
+ }
531
+ if (!matchesSnapshot("shipping") || !matchesSnapshot("billing")) {
532
+ throw new Error(localized(locale,
533
+ "A részletes címadatok mentése nem ellenőrizhető.",
534
+ "The structured address details could not be verified."))
535
+ }
500
536
  setBillingTaxNumber(validTax.billingTaxNumber)
501
537
  setBillingEuTaxNumber(validTax.billingEuTaxNumber)
502
538
  setAddressOnCart(true)
@@ -735,9 +771,9 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
735
771
  <Field label={copy.country} value={address.country_code} error={addressErrors.country_code} onBlur={() => blurAddressField("country_code")} onChange={(value) => setAddressField("country_code", value.toUpperCase())} />
736
772
  <Field label={copy.postalCode} value={address.postal_code} error={addressErrors.postal_code} onBlur={() => blurAddressField("postal_code")} onChange={(value) => setAddressField("postal_code", value)} />
737
773
  <Field label={copy.city} value={address.city} error={addressErrors.city} onBlur={() => blurAddressField("city")} onChange={(value) => setAddressField("city", value)} />
738
- <Field label={copy.address1} value={address.address_1} error={addressErrors.address_1} onBlur={() => blurAddressField("address_1")} onChange={(value) => setAddressField("address_1", value)} />
739
- <Field label={copy.address2} value={address.address_2} error={addressErrors.address_2} onBlur={() => blurAddressField("address_2")} onChange={(value) => setAddressField("address_2", value)} />
740
774
  </div>
775
+ <AddressStreetFields address={address} locale={locale} errors={addressErrors}
776
+ onChange={setAddressField} onBlur={blurAddressField} />
741
777
  {signedIn && shippingAddressSelection === NEW_CHECKOUT_ADDRESS ? (
742
778
  <button className="text-button" type="button" disabled={Boolean(savingCustomerAddress)}
743
779
  onClick={() => void addAddressToBook("shipping")}>
@@ -863,13 +899,14 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
863
899
  onChange={value => setBillingField("postal_code", value)} />
864
900
  <Field label={copy.city} value={billingAddress.city} error={billingErrors.city}
865
901
  onChange={value => setBillingField("city", value)} />
866
- <Field label={copy.address1} value={billingAddress.address_1} error={billingErrors.address_1}
867
- onChange={value => setBillingField("address_1", value)} />
868
- <Field label={copy.address2} value={billingAddress.address_2}
869
- onChange={value => setBillingField("address_2", value)} />
870
902
  <Field label={localized(locale, "Megye / tartomány (opcionális)", "State / province (optional)")}
871
903
  value={billingAddress.province} onChange={value => setBillingField("province", value)} />
872
904
  </div>
905
+ <AddressStreetFields address={billingAddress} locale={locale} errors={billingErrors}
906
+ onChange={setBillingField}
907
+ onBlur={key => setBillingErrors(current => ({
908
+ ...current, [key]: checkoutBillingAddressErrors(billingAddress, locale)[key],
909
+ }))} />
873
910
  {signedIn && billingAddressSelection === NEW_CHECKOUT_ADDRESS ? (
874
911
  <button className="text-button" type="button" disabled={Boolean(savingCustomerAddress)}
875
912
  onClick={() => void addAddressToBook("billing")}>
@@ -1143,7 +1180,14 @@ function updateAddress(
1143
1180
  key: keyof AddressState,
1144
1181
  value: string,
1145
1182
  ) {
1146
- setter((current) => ({ ...current, [key]: value }))
1183
+ setter((current) => {
1184
+ const next = { ...current, [key]: value }
1185
+ if (isHungarianAddress(next)) {
1186
+ next.address_1 = addressLine1(next)
1187
+ next.address_2 = addressLine2(next)
1188
+ }
1189
+ return next
1190
+ })
1147
1191
  }
1148
1192
 
1149
1193
  type CheckoutCarrier = "FOXPOST" | "GLS" | "MPL" | "Packeta" | "DPD" | null
@@ -1171,7 +1215,9 @@ function checkoutAddressErrors(
1171
1215
  ["country_code", localized(locale, "Országkód", "Country code")],
1172
1216
  ["postal_code", localized(locale, "Irányítószám", "Postal code")],
1173
1217
  ["city", localized(locale, "Város", "City")],
1174
- ["address_1", localized(locale, "Utca és házszám", "Street address")],
1218
+ ...(!isHungarianAddress(address) ? [
1219
+ ["address_1", localized(locale, "Cím első sora", "Street address")] as [keyof CheckoutAddress, string],
1220
+ ] : []),
1175
1221
  ]
1176
1222
  for (const [field, label] of requiredFields) {
1177
1223
  try {
@@ -1180,6 +1226,9 @@ function checkoutAddressErrors(
1180
1226
  errors[field] = cause instanceof Error ? cause.message : localized(locale, "Kötelező mező.", "Required field.")
1181
1227
  }
1182
1228
  }
1229
+ for (const field of missingAddressParts(address)) {
1230
+ errors[field] = localized(locale, "Kötelező címmező.", "Required address field.")
1231
+ }
1183
1232
  if (address.country_code.trim() && !/^[A-Za-z]{2}$/.test(address.country_code.trim())) {
1184
1233
  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).")
1185
1234
  }
@@ -1211,7 +1260,9 @@ function checkoutBillingAddressErrors(
1211
1260
  ["country_code", localized(locale, "Országkód", "Country code")],
1212
1261
  ["postal_code", localized(locale, "Irányítószám", "Postal code")],
1213
1262
  ["city", localized(locale, "Város", "City")],
1214
- ["address_1", localized(locale, "Utca és házszám", "Street address")],
1263
+ ...(!isHungarianAddress(address) ? [
1264
+ ["address_1", localized(locale, "Cím első sora", "Street address")] as [keyof CheckoutAddress, string],
1265
+ ] : []),
1215
1266
  ]
1216
1267
  for (const [key, label] of required) {
1217
1268
  try {
@@ -1220,6 +1271,9 @@ function checkoutBillingAddressErrors(
1220
1271
  errors[key] = cause instanceof Error ? cause.message : localized(locale, "Kötelező mező.", "Required field.")
1221
1272
  }
1222
1273
  }
1274
+ for (const field of missingAddressParts(address)) {
1275
+ errors[field] = localized(locale, "Kötelező címmező.", "Required address field.")
1276
+ }
1223
1277
  if (address.country_code.trim() && !/^[A-Za-z]{2}$/.test(address.country_code.trim())) {
1224
1278
  errors.country_code = localized(locale, "Kétbetűs országkód szükséges.", "Enter a two-letter country code.")
1225
1279
  }
@@ -3,7 +3,12 @@
3
3
  * Only /store/carts/:id is written during checkout; customer-address mutations
4
4
  * belong exclusively to the explicit address book management screen.
5
5
  */
6
- export type CheckoutAddress = {
6
+ import {
7
+ addressDetailsFromRecord, addressLine1, addressLine2, emptyAddressDetails,
8
+ CART_STRUCTURED_ADDRESSES_KEY, type AddressDetails,
9
+ } from "./structured-address.ts"
10
+
11
+ export type CheckoutAddress = AddressDetails & {
7
12
  email: string
8
13
  first_name: string
9
14
  last_name: string
@@ -46,7 +51,7 @@ export function emptyCheckoutAddress(country = "HU", email = ""): CheckoutAddres
46
51
  email,
47
52
  first_name: "", last_name: "", company: "", phone: "",
48
53
  country_code: country.toUpperCase(), postal_code: "",
49
- city: "", province: "", address_1: "", address_2: "",
54
+ city: "", province: "", address_1: "", address_2: "", ...emptyAddressDetails(),
50
55
  }
51
56
  }
52
57
 
@@ -54,6 +59,7 @@ export function checkoutAddressFromRecord(
54
59
  source: unknown,
55
60
  country: string,
56
61
  email = "",
62
+ snapshot?: unknown,
57
63
  ): CheckoutAddress {
58
64
  const item = record(source)
59
65
  return {
@@ -68,6 +74,7 @@ export function checkoutAddressFromRecord(
68
74
  province: value(item.province),
69
75
  address_1: value(item.address_1),
70
76
  address_2: value(item.address_2),
77
+ ...addressDetailsFromRecord(item, snapshot),
71
78
  }
72
79
  }
73
80
 
@@ -81,8 +88,8 @@ export function checkoutAddressPayload(address: CheckoutAddress) {
81
88
  postal_code: address.postal_code.trim(),
82
89
  city: address.city.trim(),
83
90
  province: address.province.trim() || undefined,
84
- address_1: address.address_1.trim(),
85
- address_2: address.address_2.trim() || undefined,
91
+ address_1: addressLine1(address),
92
+ address_2: addressLine2(address) || undefined,
86
93
  }
87
94
  }
88
95
 
@@ -119,6 +126,7 @@ export function initialCheckoutAddresses(input: {
119
126
  const customer = input.customer || {}
120
127
  const saved = (input.savedAddresses || []).filter(item => addressId(item))
121
128
  const email = value(cart.email) || value(customer.email)
129
+ const snapshots = record(record(cart.metadata)[CART_STRUCTURED_ADDRESSES_KEY])
122
130
  const existingShipping = checkoutAddressPresent(cart.shipping_address)
123
131
  const existingBilling = checkoutAddressPresent(cart.billing_address)
124
132
  // Medusa exposes both customer default address IDs and address flags.
@@ -129,7 +137,7 @@ export function initialCheckoutAddresses(input: {
129
137
  saved.find(item => item.is_default_billing === true)
130
138
 
131
139
  const shipping = existingShipping
132
- ? checkoutAddressFromRecord(cart.shipping_address, country, email)
140
+ ? checkoutAddressFromRecord(cart.shipping_address, country, email, snapshots.shipping)
133
141
  : defaultShipping
134
142
  ? checkoutAddressFromRecord(defaultShipping, country, email)
135
143
  : emptyCheckoutAddress(country, email)
@@ -141,7 +149,7 @@ export function initialCheckoutAddresses(input: {
141
149
  : defaultShipping
142
150
 
143
151
  const billing = existingBilling
144
- ? checkoutAddressFromRecord(cart.billing_address, country, email)
152
+ ? checkoutAddressFromRecord(cart.billing_address, country, email, snapshots.billing)
145
153
  : defaultBilling
146
154
  ? checkoutAddressFromRecord(defaultBilling, country, email)
147
155
  : { ...shipping }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Hungarian address parts on top of Medusa-native address_1/address_2 and metadata.
3
+ * No database schema extension or migration.
4
+ */
5
+ export type AddressDetails = {
6
+ street_name: string
7
+ street_type: string
8
+ house_number: string
9
+ house_number_suffix: string
10
+ building: string
11
+ staircase: string
12
+ floor: string
13
+ door: string
14
+ address_extra: string
15
+ }
16
+ export type StructuredAddress = AddressDetails & {
17
+ country_code: string
18
+ address_1: string
19
+ address_2: string
20
+ }
21
+ export const CUSTOMER_STRUCTURED_ADDRESS_KEY = "core_structured_address"
22
+ export const CART_STRUCTURED_ADDRESSES_KEY = "core_structured_addresses"
23
+ const keys = [
24
+ "street_name", "street_type", "house_number", "house_number_suffix",
25
+ "building", "staircase", "floor", "door", "address_extra",
26
+ ] as const
27
+
28
+ function record(value: unknown): Record<string, unknown> {
29
+ return value && typeof value === "object" && !Array.isArray(value)
30
+ ? value as Record<string, unknown> : {}
31
+ }
32
+ function string(value: unknown) {
33
+ return typeof value === "string" ? value.trim() : ""
34
+ }
35
+ export function isHungarianAddress(address: Pick<StructuredAddress, "country_code">) {
36
+ return address.country_code.trim().toUpperCase() === "HU"
37
+ }
38
+ export function emptyAddressDetails(): AddressDetails {
39
+ return {
40
+ street_name: "", street_type: "", house_number: "", house_number_suffix: "",
41
+ building: "", staircase: "", floor: "", door: "", address_extra: "",
42
+ }
43
+ }
44
+ export function addressLine1(address: StructuredAddress): string {
45
+ if (!isHungarianAddress(address)) return address.address_1.trim()
46
+ const street = [address.street_name, address.street_type].map(v => v.trim()).filter(Boolean).join(" ")
47
+ const number = address.house_number.trim() +
48
+ (address.house_number_suffix.trim() ? "/" + address.house_number_suffix.trim() : "")
49
+ // Keep the native line if no structured parts have been entered yet.
50
+ return [street, number].filter(Boolean).join(" ") || address.address_1.trim()
51
+ }
52
+ export function addressLine2(address: StructuredAddress): string {
53
+ if (!isHungarianAddress(address)) return address.address_2.trim()
54
+ return [
55
+ address.building.trim() ? "Épület: " + address.building.trim() : "",
56
+ address.staircase.trim() ? "Lépcsőház: " + address.staircase.trim() : "",
57
+ address.floor.trim() ? "Emelet: " + address.floor.trim() : "",
58
+ address.door.trim() ? "Ajtó: " + address.door.trim() : "",
59
+ address.address_extra.trim(),
60
+ ].filter(Boolean).join(", ")
61
+ }
62
+ export function addressStructuredSnapshot(address: StructuredAddress) {
63
+ if (!isHungarianAddress(address)) return null
64
+ const result: Record<string, string | number> = {
65
+ version: 1,
66
+ country_code: "hu",
67
+ address_1: addressLine1(address),
68
+ address_2: addressLine2(address),
69
+ }
70
+ for (const key of keys) result[key] = address[key].trim()
71
+ return result
72
+ }
73
+ /** Do not use stale split data after a native address update. */
74
+ export function addressDetailsFromRecord(source: unknown, override?: unknown): AddressDetails {
75
+ const data = record(source)
76
+ const candidate = record(override === undefined
77
+ ? record(data.metadata)[CUSTOMER_STRUCTURED_ADDRESS_KEY] : override)
78
+ const matches = candidate.version === 1
79
+ && string(data.country_code).toLowerCase() === "hu"
80
+ && string(candidate.country_code).toLowerCase() === "hu"
81
+ && string(candidate.address_1) === string(data.address_1)
82
+ && string(candidate.address_2) === string(data.address_2)
83
+ if (!matches) return emptyAddressDetails()
84
+ const parts = emptyAddressDetails()
85
+ for (const key of keys) parts[key] = string(candidate[key])
86
+ return parts
87
+ }
88
+ export function missingAddressParts(address: StructuredAddress): (keyof AddressDetails)[] {
89
+ if (!isHungarianAddress(address)) return []
90
+ return (["street_name", "street_type", "house_number"] as const)
91
+ .filter(key => !address[key].trim())
92
+ }
@@ -1,5 +1,11 @@
1
1
  import test from "node:test"
2
2
  import assert from "node:assert/strict"
3
+ import {
4
+ CART_STRUCTURED_ADDRESSES_KEY,
5
+ CUSTOMER_STRUCTURED_ADDRESS_KEY,
6
+ addressLine1, addressLine2, addressStructuredSnapshot,
7
+ missingAddressParts,
8
+ } from "../src/lib/core/structured-address.ts"
3
9
  import {
4
10
  CART_CHECKOUT_ADDRESS,
5
11
  NEW_CHECKOUT_ADDRESS,
@@ -146,3 +152,56 @@ test("partial cart with shipping but no billing must still be explicitly saved",
146
152
  assert.equal(initial.billingSelection, "cadr_billing")
147
153
  assert.equal(initial.addressOnCart, false)
148
154
  })
155
+
156
+ test("HU split street fields produce native Medusa lines and preserve details", () => {
157
+ const draft = {
158
+ ...emptyCheckoutAddress("HU", "kata@example.com"),
159
+ street_name: "Fő", street_type: "utca", house_number: "12",
160
+ house_number_suffix: "A", floor: "2", door: "4",
161
+ }
162
+ assert.deepEqual(missingAddressParts(draft), [])
163
+ assert.equal(addressLine1(draft), "Fő utca 12/A")
164
+ assert.equal(addressLine2(draft), "Emelet: 2, Ajtó: 4")
165
+ const payload = checkoutAddressPayload(draft)
166
+ assert.equal(payload.address_1, "Fő utca 12/A")
167
+ assert.equal(payload.address_2, "Emelet: 2, Ajtó: 4")
168
+ assert.equal("street_name" in payload, false)
169
+ const snapshot = addressStructuredSnapshot(draft)
170
+ const saved = { ...payload, metadata: { [CUSTOMER_STRUCTURED_ADDRESS_KEY]: snapshot } }
171
+ const hydrated = checkoutAddressFromRecord(saved, "HU", draft.email)
172
+ assert.equal(hydrated.street_name, "Fő")
173
+ assert.equal(hydrated.house_number, "12")
174
+ assert.equal(hydrated.house_number_suffix, "A")
175
+ })
176
+
177
+ test("cart structured details restore independently for shipping and billing", () => {
178
+ const shipping = { ...emptyCheckoutAddress(), street_name: "Duna", street_type: "utca", house_number: "8" }
179
+ const billing = { ...emptyCheckoutAddress(), street_name: "Fő", street_type: "út", house_number: "2" }
180
+ const cart = {
181
+ email: "kata@example.com",
182
+ shipping_address: checkoutAddressPayload(shipping),
183
+ billing_address: checkoutAddressPayload(billing),
184
+ metadata: { [CART_STRUCTURED_ADDRESSES_KEY]: {
185
+ shipping: addressStructuredSnapshot(shipping),
186
+ billing: addressStructuredSnapshot(billing),
187
+ } },
188
+ }
189
+ const initial = initialCheckoutAddresses({ country: "HU", cart })
190
+ assert.equal(initial.shipping.street_name, "Duna")
191
+ assert.equal(initial.billing.street_name, "Fő")
192
+ assert.equal(initial.billing.street_type, "út")
193
+ assert.equal(initial.addressOnCart, true)
194
+ })
195
+
196
+ test("foreign addresses stay free-form, and stale metadata is ignored", () => {
197
+ const foreign = { ...emptyCheckoutAddress("DE"), address_1: "Schönhauser Allee 3", address_2: "2. OG" }
198
+ assert.deepEqual(missingAddressParts(foreign), [])
199
+ assert.equal(addressLine1(foreign), "Schönhauser Allee 3")
200
+ assert.equal(addressLine2(foreign), "2. OG")
201
+ assert.equal(addressStructuredSnapshot(foreign), null)
202
+ const hu = { ...emptyCheckoutAddress(), street_name: "Teszt", street_type: "utca", house_number: "10" }
203
+ const metadata = { [CUSTOMER_STRUCTURED_ADDRESS_KEY]: addressStructuredSnapshot(hu) }
204
+ const changed = checkoutAddressFromRecord({ ...checkoutAddressPayload(hu), address_1: "Másik utca 3", metadata }, "HU")
205
+ assert.equal(changed.street_name, "")
206
+ assert.deepEqual(missingAddressParts(changed), ["street_name", "street_type", "house_number"])
207
+ })
@@ -10,6 +10,7 @@
10
10
  "skipLibCheck": true,
11
11
  "strict": true,
12
12
  "noEmit": true,
13
+ "allowImportingTsExtensions": true,
13
14
  "esModuleInterop": true,
14
15
  "module": "esnext",
15
16
  "moduleResolution": "bundler",