@hszrdm/create-commerce 1.17.0 → 1.20.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 (29) hide show
  1. package/package.json +1 -1
  2. package/templates/backend/.env.example +19 -24
  3. package/templates/backend/medusa-config.ts +14 -1
  4. package/templates/backend/package.json +1 -1
  5. package/templates/backend/scripts/core-backup.mjs +3 -1
  6. package/templates/backend/scripts/core-restore.mjs +17 -2
  7. package/templates/backend/scripts/lib/core-backup-common.mjs +32 -0
  8. package/templates/backend/src/scripts/core-init.ts +0 -5
  9. package/templates/storefront/package.json +3 -1
  10. package/templates/storefront/src/app/[countryCode]/products/[handle]/page.tsx +2 -2
  11. package/templates/storefront/src/app/layout.tsx +6 -0
  12. package/templates/storefront/src/components/account-access-gate.tsx +88 -0
  13. package/templates/storefront/src/components/account-dashboard.tsx +112 -24
  14. package/templates/storefront/src/components/account-verification-panel.tsx +145 -0
  15. package/templates/storefront/src/components/address-street-fields.tsx +47 -0
  16. package/templates/storefront/src/components/checkout-flow.tsx +132 -34
  17. package/templates/storefront/src/components/product-card.tsx +2 -1
  18. package/templates/storefront/src/lib/core/account.ts +49 -8
  19. package/templates/storefront/src/lib/core/checkout-addresses.ts +14 -6
  20. package/templates/storefront/src/lib/core/checkout-feedback-state.ts +15 -0
  21. package/templates/storefront/src/lib/core/checkout.ts +18 -19
  22. package/templates/storefront/src/lib/core/commerce.ts +11 -0
  23. package/templates/storefront/src/lib/core/structured-address.ts +92 -0
  24. package/templates/storefront/src/lib/core/use-checkout-feedback.ts +53 -0
  25. package/templates/storefront/tests/account-verification.test.mjs +40 -0
  26. package/templates/storefront/tests/checkout-addresses.test.mjs +59 -0
  27. package/templates/storefront/tests/checkout-feedback.test.mjs +27 -0
  28. package/templates/storefront/tests/product-image.test.mjs +31 -0
  29. package/templates/storefront/tsconfig.json +1 -0
@@ -1,9 +1,15 @@
1
1
  "use client"
2
2
 
3
- import { useCallback, useEffect, useMemo, useRef, useState, useId } from "react"
3
+ import { Fragment, 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"
12
+ import { useCheckoutFeedback } from "@/lib/core/use-checkout-feedback"
7
13
  import { stripeCheckoutPhase } from "@/lib/core/stripe-checkout-phase"
8
14
  import { carrierPointToShippingData, type CarrierPickupPoint } from "./carrier-pickup-map"
9
15
  import { CarrierPickupDialog } from "./carrier-pickup-dialog"
@@ -113,13 +119,13 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
113
119
  const [pickupDialogOpen, setPickupDialogOpen] = useState(false)
114
120
  const [providers, setProviders] = useState<JsonRecord[]>([])
115
121
  const [selectedProvider, setSelectedProvider] = useState("")
122
+ const [selectedPaymentMode, setSelectedPaymentMode] = useState<"cod" | "bank_transfer" | "online">("online")
116
123
  const [preparedCart, setPreparedCart] = useState<JsonRecord | null>(null)
117
124
  const [stripeInitError, setStripeInitError] = useState<string | null>(null)
118
125
  const [legalDocs, setLegalDocs] = useState<LegalDocument[]>([])
119
126
  const [accepted, setAccepted] = useState<Record<string, boolean>>({})
120
127
  const [busy, setBusy] = useState<string | null>(null)
121
- const [error, setError] = useState<string | null>(null)
122
- const [message, setMessage] = useState<string | null>(null)
128
+ const { error, setError, setMessage } = useCheckoutFeedback(cartError)
123
129
 
124
130
  const setBillingTaxDefaults = useCallback((
125
131
  cartData: JsonRecord,
@@ -285,22 +291,24 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
285
291
  isCompany: billingIsCompany, company: candidate.company,
286
292
  billingTaxNumber, billingEuTaxNumber,
287
293
  }) : null
294
+ const snapshot = addressStructuredSnapshot(candidate)
288
295
  await account.createAddress({
289
296
  ...checkoutAddressPayload(candidate),
290
- ...(tax ? {
291
- company: tax.isCompany ? tax.company : undefined,
292
- metadata: {
297
+ ...(tax ? { company: tax.isCompany ? tax.company : undefined } : {}),
298
+ metadata: {
299
+ ...(snapshot ? { core_structured_address: snapshot } : {}),
300
+ ...(tax ? {
293
301
  billing_is_company: tax.isCompany,
294
302
  billing_tax_number: tax.billingTaxNumber,
295
303
  billing_eu_tax_number: tax.billingEuTaxNumber,
296
- },
297
- } : {}),
304
+ } : {}),
305
+ },
298
306
  })
299
307
  const { addresses } = await account.addresses()
300
308
  setSavedAddresses(addresses)
301
309
  const created = addresses.find(item =>
302
310
  !knownIds.has(stringValue(item.id)) &&
303
- stringValue(item.address_1) === candidate.address_1.trim() &&
311
+ stringValue(item.address_1) === addressLine1(candidate) &&
304
312
  stringValue(item.postal_code) === candidate.postal_code.trim())
305
313
  if (created?.id) {
306
314
  if (kind === "shipping") setShippingAddressSelection(stringValue(created.id))
@@ -497,6 +505,35 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
497
505
  billing_tax_number: validTax.billingTaxNumber,
498
506
  billing_eu_tax_number: validTax.billingEuTaxNumber,
499
507
  })
508
+ // Native Medusa metadata: no address schema changes, no new DB tables.
509
+ const latestCart = (await api.getCart(cartId)).cart
510
+ const metadata = isRecord(latestCart.metadata) ? latestCart.metadata : {}
511
+ const snapshots = {
512
+ shipping: addressStructuredSnapshot(address),
513
+ billing: addressStructuredSnapshot(billingSameAsShipping ? address : billingAddress),
514
+ }
515
+ await api.updateCart(cartId, {
516
+ metadata: { ...metadata, [CART_STRUCTURED_ADDRESSES_KEY]: snapshots },
517
+ })
518
+ const verified = (await api.getCart(cartId)).cart
519
+ const stored = isRecord(verified.metadata)
520
+ ? verified.metadata[CART_STRUCTURED_ADDRESSES_KEY] : null
521
+ // Metadata is jsonb in PostgreSQL: key order need not match the client.
522
+ // Check the stored fields semantically rather than comparing JSON strings.
523
+ const persisted = isRecord(stored) ? stored : {}
524
+ const matchesSnapshot = (key: "shipping" | "billing") => {
525
+ const expected = snapshots[key]
526
+ const actual = persisted[key]
527
+ if (expected === null) return actual == null
528
+ return isRecord(actual) && Object.entries(expected).every(
529
+ ([field, value]) => actual[field] === value,
530
+ )
531
+ }
532
+ if (!matchesSnapshot("shipping") || !matchesSnapshot("billing")) {
533
+ throw new Error(localized(locale,
534
+ "A részletes címadatok mentése nem ellenőrizhető.",
535
+ "The structured address details could not be verified."))
536
+ }
500
537
  setBillingTaxNumber(validTax.billingTaxNumber)
501
538
  setBillingEuTaxNumber(validTax.billingEuTaxNumber)
502
539
  setAddressOnCart(true)
@@ -580,6 +617,11 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
580
617
  const verifiedPoint = await verifyCarrierPickupPoint(kind, selectedPickupPoint)
581
618
  const data = shippingData(kind, verifiedPoint, locale)
582
619
  const result = await api.addShippingMethod(cartId, optionId, data)
620
+ // Shipping choice invalidates the previously selected payment and its fee.
621
+ await api.markPaymentMode(cartId, "online", "online")
622
+ setSelectedProvider("")
623
+ setSelectedPaymentMode("online")
624
+ setPreparedCart(null)
583
625
  await refresh(cartId)
584
626
  await loadProviders(result.cart)
585
627
  setMessage(localized(locale, "Szállítási mód kiválasztva.", "Shipping method selected."))
@@ -594,7 +636,7 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
594
636
  }
595
637
  }
596
638
 
597
- const preparePayment = async (id: string) => {
639
+ const preparePayment = async (id: string, mode: "cod" | "bank_transfer" | "online") => {
598
640
  if (!addressOnCart) {
599
641
  setError(localized(locale,
600
642
  "Előbb mentsd a szállítási és számlázási címet.",
@@ -609,7 +651,10 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
609
651
  setStripeInitError(null)
610
652
  setPreparedCart(null)
611
653
  setSelectedProvider(id)
654
+ setSelectedPaymentMode(mode)
612
655
  try {
656
+ // Apply the surcharge and refresh any existing collection BEFORE creating a payment session.
657
+ await api.markPaymentMode(cartId, id, mode)
613
658
  let current = (await api.getCart(cartId)).cart
614
659
  let collection = cartPaymentCollection(current)
615
660
  let collectionId = stringValue(collection?.id)
@@ -633,6 +678,7 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
633
678
  setMessage(copy.paymentPrepared)
634
679
  } catch (cause) {
635
680
  setPreparedCart(null)
681
+ setSelectedProvider("")
636
682
  const message = cause instanceof Error
637
683
  ? cause.message
638
684
  : localized(locale, "A fizetési mód nem készíthető elő.", "The payment method could not be prepared.")
@@ -691,6 +737,21 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
691
737
  const simplePaySelected = activeProviderId.toLowerCase().includes("simplepay")
692
738
  const systemSelected = activeProviderId.toLowerCase().includes("system")
693
739
  const currency = cartCurrency(cart, config.store.default_currency)
740
+ const selectedMethod = asRecords(cart.shipping_methods)[0]
741
+ const activeShippingOption = shippingOptions.find(option =>
742
+ stringValue(option.id) === stringValue(selectedMethod?.shipping_option_id))
743
+ const optionData = isRecord(activeShippingOption?.data) ? activeShippingOption.data : {}
744
+ const selectedShippingData = isRecord(selectedMethod?.data) ? selectedMethod.data : {}
745
+ const csomagpiacData = isRecord(selectedShippingData.csomagpiac) ? selectedShippingData.csomagpiac : {}
746
+ const codAvailable = currency === "HUF" &&
747
+ activeShippingOption?.price_type === "flat" &&
748
+ csomagpiacData.codEnabled !== false &&
749
+ (optionData.hszrdm_cod_enabled === true ||
750
+ (optionData.hszrdm_cod_enabled === undefined && optionData.cod === true)) &&
751
+ asRecords(cart.shipping_methods).length === 1
752
+ const appliedCodFee = shippingMethodIsCod(cart)
753
+ ? Number(selectedShippingData.hszrdm_cod_applied_fee_huf || 0)
754
+ : 0
694
755
 
695
756
  return (
696
757
  <div className="checkout-layout">
@@ -735,9 +796,9 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
735
796
  <Field label={copy.country} value={address.country_code} error={addressErrors.country_code} onBlur={() => blurAddressField("country_code")} onChange={(value) => setAddressField("country_code", value.toUpperCase())} />
736
797
  <Field label={copy.postalCode} value={address.postal_code} error={addressErrors.postal_code} onBlur={() => blurAddressField("postal_code")} onChange={(value) => setAddressField("postal_code", value)} />
737
798
  <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
799
  </div>
800
+ <AddressStreetFields address={address} locale={locale} errors={addressErrors}
801
+ onChange={setAddressField} onBlur={blurAddressField} />
741
802
  {signedIn && shippingAddressSelection === NEW_CHECKOUT_ADDRESS ? (
742
803
  <button className="text-button" type="button" disabled={Boolean(savingCustomerAddress)}
743
804
  onClick={() => void addAddressToBook("shipping")}>
@@ -863,13 +924,14 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
863
924
  onChange={value => setBillingField("postal_code", value)} />
864
925
  <Field label={copy.city} value={billingAddress.city} error={billingErrors.city}
865
926
  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
927
  <Field label={localized(locale, "Megye / tartomány (opcionális)", "State / province (optional)")}
871
928
  value={billingAddress.province} onChange={value => setBillingField("province", value)} />
872
929
  </div>
930
+ <AddressStreetFields address={billingAddress} locale={locale} errors={billingErrors}
931
+ onChange={setBillingField}
932
+ onBlur={key => setBillingErrors(current => ({
933
+ ...current, [key]: checkoutBillingAddressErrors(billingAddress, locale)[key],
934
+ }))} />
873
935
  {signedIn && billingAddressSelection === NEW_CHECKOUT_ADDRESS ? (
874
936
  <button className="text-button" type="button" disabled={Boolean(savingCustomerAddress)}
875
937
  onClick={() => void addAddressToBook("billing")}>
@@ -972,18 +1034,33 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
972
1034
  <div className="choice-list">
973
1035
  {providers.map((provider) => {
974
1036
  const id = stringValue(provider.id)
975
- const cod = shippingMethodIsCod(cart)
1037
+ const system = id.toLowerCase().includes("system")
1038
+ const normalMode = system ? "bank_transfer" : "online"
976
1039
  return (
977
- <button
978
- className={`choice-card choice-button${selectedProvider === id ? " selected" : ""}`}
979
- type="button"
980
- key={id}
981
- disabled={busy === "payment" || !addressOnCart}
982
- onClick={() => void preparePayment(id)}
983
- >
984
- <strong>{providerLabel(id, cod)}</strong>
985
- <small>{id}</small>
986
- </button>
1040
+ <Fragment key={id}>
1041
+ {system && codAvailable ? (
1042
+ <button
1043
+ className={`choice-card choice-button${selectedProvider === id && selectedPaymentMode === "cod" ? " selected" : ""}`}
1044
+ type="button"
1045
+ disabled={busy === "payment" || !addressOnCart}
1046
+ onClick={() => void preparePayment(id, "cod")}
1047
+ >
1048
+ <strong>{localized(locale, "Utánvét", "Cash on delivery")}</strong>
1049
+ <small>{localized(locale, "Fizetés kézbesítéskor", "Pay on delivery")}</small>
1050
+ </button>
1051
+ ) : null}
1052
+ {(!system || config.payments.bank_transfer.enabled) ? (
1053
+ <button
1054
+ className={`choice-card choice-button${selectedProvider === id && selectedPaymentMode === normalMode ? " selected" : ""}`}
1055
+ type="button"
1056
+ disabled={busy === "payment" || !addressOnCart}
1057
+ onClick={() => void preparePayment(id, normalMode)}
1058
+ >
1059
+ <strong>{providerLabel(id, false)}</strong>
1060
+ <small>{id}</small>
1061
+ </button>
1062
+ ) : null}
1063
+ </Fragment>
987
1064
  )
988
1065
  })}
989
1066
  </div>
@@ -1014,7 +1091,7 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
1014
1091
  className="button secondary"
1015
1092
  type="button"
1016
1093
  disabled={busy === "payment" || !addressOnCart}
1017
- onClick={() => void preparePayment(activeProviderId)}
1094
+ onClick={() => void preparePayment(activeProviderId, "online")}
1018
1095
  >
1019
1096
  {localized(locale, "Stripe fizetés újrapróbálása", "Retry Stripe payment")}
1020
1097
  </button>
@@ -1063,7 +1140,7 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
1063
1140
  >
1064
1141
  {busy === "complete"
1065
1142
  ? copy.orderSubmitting
1066
- : shippingMethodIsCod(cart)
1143
+ : (selectedPaymentMode === "cod" || (!selectedProvider && shippingMethodIsCod(cart)))
1067
1144
  ? copy.orderSubmitCod
1068
1145
  : copy.orderSubmit}
1069
1146
  </button>
@@ -1095,8 +1172,6 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
1095
1172
  )}
1096
1173
  </section>
1097
1174
 
1098
- {message ? <div className="notice success-box">{message}</div> : null}
1099
- {error || cartError ? <div className="notice error-box">{error || cartError}</div> : null}
1100
1175
  {(stripeReturn || simplePayReturn) && error ? (
1101
1176
  <button
1102
1177
  className="button secondary"
@@ -1125,6 +1200,12 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
1125
1200
  <span>{typeof item.total === "number" ? formatMoney(item.total, currency, numberLocale) : ""}</span>
1126
1201
  </div>
1127
1202
  ))}
1203
+ {appliedCodFee > 0 && Number.isFinite(appliedCodFee) ? (
1204
+ <div className="summary-line">
1205
+ <span>{localized(locale, "Ebből utánvét kezelési díj", "Including COD handling fee")}</span>
1206
+ <span>{formatMoney(appliedCodFee, currency, numberLocale)}</span>
1207
+ </div>
1208
+ ) : null}
1128
1209
  <div className="summary-total">
1129
1210
  <span>{copy.total}</span>
1130
1211
  <strong>{formatMoney(cartTotal(cart), currency, numberLocale)}</strong>
@@ -1143,7 +1224,14 @@ function updateAddress(
1143
1224
  key: keyof AddressState,
1144
1225
  value: string,
1145
1226
  ) {
1146
- setter((current) => ({ ...current, [key]: value }))
1227
+ setter((current) => {
1228
+ const next = { ...current, [key]: value }
1229
+ if (isHungarianAddress(next)) {
1230
+ next.address_1 = addressLine1(next)
1231
+ next.address_2 = addressLine2(next)
1232
+ }
1233
+ return next
1234
+ })
1147
1235
  }
1148
1236
 
1149
1237
  type CheckoutCarrier = "FOXPOST" | "GLS" | "MPL" | "Packeta" | "DPD" | null
@@ -1171,7 +1259,9 @@ function checkoutAddressErrors(
1171
1259
  ["country_code", localized(locale, "Országkód", "Country code")],
1172
1260
  ["postal_code", localized(locale, "Irányítószám", "Postal code")],
1173
1261
  ["city", localized(locale, "Város", "City")],
1174
- ["address_1", localized(locale, "Utca és házszám", "Street address")],
1262
+ ...(!isHungarianAddress(address) ? [
1263
+ ["address_1", localized(locale, "Cím első sora", "Street address")] as [keyof CheckoutAddress, string],
1264
+ ] : []),
1175
1265
  ]
1176
1266
  for (const [field, label] of requiredFields) {
1177
1267
  try {
@@ -1180,6 +1270,9 @@ function checkoutAddressErrors(
1180
1270
  errors[field] = cause instanceof Error ? cause.message : localized(locale, "Kötelező mező.", "Required field.")
1181
1271
  }
1182
1272
  }
1273
+ for (const field of missingAddressParts(address)) {
1274
+ errors[field] = localized(locale, "Kötelező címmező.", "Required address field.")
1275
+ }
1183
1276
  if (address.country_code.trim() && !/^[A-Za-z]{2}$/.test(address.country_code.trim())) {
1184
1277
  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
1278
  }
@@ -1211,7 +1304,9 @@ function checkoutBillingAddressErrors(
1211
1304
  ["country_code", localized(locale, "Országkód", "Country code")],
1212
1305
  ["postal_code", localized(locale, "Irányítószám", "Postal code")],
1213
1306
  ["city", localized(locale, "Város", "City")],
1214
- ["address_1", localized(locale, "Utca és házszám", "Street address")],
1307
+ ...(!isHungarianAddress(address) ? [
1308
+ ["address_1", localized(locale, "Cím első sora", "Street address")] as [keyof CheckoutAddress, string],
1309
+ ] : []),
1215
1310
  ]
1216
1311
  for (const [key, label] of required) {
1217
1312
  try {
@@ -1220,6 +1315,9 @@ function checkoutBillingAddressErrors(
1220
1315
  errors[key] = cause instanceof Error ? cause.message : localized(locale, "Kötelező mező.", "Required field.")
1221
1316
  }
1222
1317
  }
1318
+ for (const field of missingAddressParts(address)) {
1319
+ errors[field] = localized(locale, "Kötelező címmező.", "Required address field.")
1320
+ }
1223
1321
  if (address.country_code.trim() && !/^[A-Za-z]{2}$/.test(address.country_code.trim())) {
1224
1322
  errors.country_code = localized(locale, "Kétbetűs országkód szükséges.", "Enter a two-letter country code.")
1225
1323
  }
@@ -3,6 +3,7 @@ import { PriceDisplay } from "./price-display"
3
3
  import {
4
4
  asRecords,
5
5
  isRecord,
6
+ productImageUrl,
6
7
  productVariantPriceBreakdown,
7
8
  stringValue,
8
9
  } from "@/lib/core/commerce"
@@ -27,7 +28,7 @@ export function ProductCard({
27
28
  const formatLocale = activeLocale === "en" ? "en-US" : "hu-HU"
28
29
  const copy = storefrontCopy(activeLocale)
29
30
  const href = productPath(activeLocale, handle)
30
- const thumbnail = stringValue(product.thumbnail)
31
+ const thumbnail = productImageUrl(product)
31
32
  const categories = asRecords(product.categories)
32
33
  const title = stringValue(product.title)
33
34
 
@@ -1,7 +1,21 @@
1
1
  import { endpoint, medusaFetch } from "./client"
2
2
  import type { CoreConfig } from "./types"
3
+
4
+ export function isAccountEmailVerified(customer: Record<string, unknown>) {
5
+ const metadata = customer.metadata
6
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return false
7
+ const state = metadata as Record<string, unknown>
8
+ const email = String(customer.email ?? "").trim().toLowerCase()
9
+ return Boolean(email) && state.email_verified === true
10
+ && String(state.email_verified_address ?? "").trim().toLowerCase() === email
11
+ }
3
12
  import { mergeGuestWishlistAfterLogin } from "./wishlist"
4
13
 
14
+ export const ACCOUNT_AUTH_CHANGED_EVENT = "hszrdm:account-auth-changed"
15
+ function notifyAuthChanged() {
16
+ if (typeof window !== "undefined") window.dispatchEvent(new Event(ACCOUNT_AUTH_CHANGED_EVENT))
17
+ }
18
+
5
19
  export function accountApi(config: CoreConfig) {
6
20
  const paths = config.account.endpoints
7
21
 
@@ -53,8 +67,12 @@ export function accountApi(config: CoreConfig) {
53
67
  method: "POST",
54
68
  headers: { Authorization: `Bearer ${login.token}` },
55
69
  })
56
- await mergeGuestWishlistAfterLogin().catch(() => undefined)
57
- return profile()
70
+ const result = await profile()
71
+ notifyAuthChanged()
72
+ if (isAccountEmailVerified(result.customer)) {
73
+ await mergeGuestWishlistAfterLogin().catch(() => undefined)
74
+ }
75
+ return result
58
76
  },
59
77
 
60
78
  login: async (email: string, password: string) => {
@@ -66,11 +84,19 @@ export function accountApi(config: CoreConfig) {
66
84
  method: "POST",
67
85
  headers: { Authorization: `Bearer ${result.token}` },
68
86
  })
69
- await mergeGuestWishlistAfterLogin().catch(() => undefined)
87
+ const current = await profile().catch(() => null)
88
+ if (current?.customer && isAccountEmailVerified(current.customer)) {
89
+ await mergeGuestWishlistAfterLogin().catch(() => undefined)
90
+ }
91
+ notifyAuthChanged()
70
92
  return result
71
93
  },
72
94
 
73
- logout: () => medusaFetch(paths.logout, { method: "DELETE" }),
95
+ logout: async () => {
96
+ const result = await medusaFetch(paths.logout, { method: "DELETE" })
97
+ notifyAuthChanged()
98
+ return result
99
+ },
74
100
 
75
101
  profile,
76
102
 
@@ -137,17 +163,32 @@ export function accountApi(config: CoreConfig) {
137
163
  body: JSON.stringify({ email, password }),
138
164
  }),
139
165
 
166
+ emailVerificationStatus: () =>
167
+ medusaFetch<{
168
+ verified: boolean
169
+ retry_after_seconds: number
170
+ resend_available_at: string | null
171
+ }>(paths.email_verification, { cache: "no-store" }),
172
+
140
173
  requestEmailVerification: () =>
141
- medusaFetch(paths.email_verification, {
174
+ medusaFetch<{
175
+ success: boolean
176
+ retry_after_seconds: number
177
+ resend_available_at: string | null
178
+ }>(paths.email_verification, {
142
179
  method: "PUT",
143
180
  body: JSON.stringify({}),
144
181
  }),
145
182
 
146
- confirmEmailVerification: (code: string) =>
147
- medusaFetch(paths.email_verification, {
183
+ confirmEmailVerification: async (code: string) => {
184
+ const result = await medusaFetch(paths.email_verification, {
148
185
  method: "POST",
149
186
  body: JSON.stringify({ code }),
150
- }),
187
+ })
188
+ await mergeGuestWishlistAfterLogin().catch(() => undefined)
189
+ notifyAuthChanged()
190
+ return result
191
+ },
151
192
 
152
193
  requestEmailChange: (currentPassword: string, newEmail: string) =>
153
194
  medusaFetch(paths.email_change, {
@@ -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,15 @@
1
+ /**
2
+ * Shared checkout notice policy. The checkout owns the domain errors; the
3
+ * notification layer only decides which safe, already-localized text to show.
4
+ */
5
+ export function checkoutErrorMessage(error?: string | null, cartError?: string | null): string | null {
6
+ return error?.trim() || cartError?.trim() || null
7
+ }
8
+
9
+ export function checkoutNoticeMessage(message?: string | null): string | null {
10
+ return message?.trim() || null
11
+ }
12
+
13
+ export function shouldShowCheckoutNotice(previous: string | null, next: string | null): boolean {
14
+ return Boolean(next && next !== previous)
15
+ }
@@ -10,7 +10,6 @@ import {
10
10
  import {
11
11
  asRecords,
12
12
  isRecord,
13
- shippingMethodIsCod,
14
13
  stringValue,
15
14
  } from "./commerce"
16
15
  import type { CoreConfig } from "./types"
@@ -65,26 +64,26 @@ export function checkoutApi(config: CoreConfig) {
65
64
  { method: "POST", body: JSON.stringify({ provider_id: providerId }) },
66
65
  )
67
66
 
68
- const markPaymentMode = async (cartId: string, selectedProviderId: string) => {
69
- const current = (await getCart(cartId)).cart
70
- const metadata = isRecord(current.metadata) ? current.metadata : {}
71
- const systemProvider = selectedProviderId.toLowerCase().includes("system")
72
- let marker = "online"
73
-
74
- if (systemProvider && shippingMethodIsCod(current)) {
75
- marker = "cod"
76
- } else if (systemProvider && config.payments.bank_transfer.enabled) {
67
+ const markPaymentMode = async (
68
+ cartId: string, selectedProviderId: string,
69
+ choice: "cod" | "bank_transfer" | "online" = "online",
70
+ ) => {
71
+ // Price authority is the backend. Never send a fee/amount from the browser.
72
+ const mode = selectedProviderId.toLowerCase().includes("system") ? choice : "online"
73
+ await medusaFetch<Record<string, unknown>>(
74
+ `/store/carts/${encodeURIComponent(cartId)}/cod`, {
75
+ method: "POST", body: JSON.stringify({ mode }),
76
+ },
77
+ )
78
+ if (mode === "bank_transfer" && config.payments.bank_transfer.enabled) {
79
+ const current = (await getCart(cartId)).cart
80
+ const metadata = isRecord(current.metadata) ? current.metadata : {}
77
81
  const details = await bankTransferDetails()
78
82
  const configured = isRecord(details.cart_metadata) ? details.cart_metadata : {}
79
- await updateCart(cartId, { metadata: { ...metadata, ...configured } })
80
- return
81
- } else if (systemProvider) {
82
- marker = "manual"
83
+ await updateCart(cartId, {
84
+ metadata: { ...metadata, ...configured, core_payment_method: "bank_transfer" },
85
+ })
83
86
  }
84
-
85
- await updateCart(cartId, {
86
- metadata: { ...metadata, core_payment_method: marker },
87
- })
88
87
  }
89
88
 
90
89
  const saveFoxpostSelection = (
@@ -177,6 +176,7 @@ export function checkoutApi(config: CoreConfig) {
177
176
  },
178
177
 
179
178
  updateCart,
179
+ markPaymentMode,
180
180
 
181
181
  saveBillingTaxDetails: (cartId: string, data: {
182
182
  is_company: boolean
@@ -346,7 +346,6 @@ export function checkoutApi(config: CoreConfig) {
346
346
  paymentCollectionId: string,
347
347
  selectedProviderId: string,
348
348
  ) => {
349
- await markPaymentMode(cartId, selectedProviderId)
350
349
  const result = await initializePaymentSession(paymentCollectionId, selectedProviderId)
351
350
  const { cart } = await getCart(cartId)
352
351
  trackPaymentInfo(config.analytics, cart, selectedProviderId)
@@ -22,6 +22,17 @@ export function stringValue(value: unknown) {
22
22
  return typeof value === "string" ? value : value == null ? "" : String(value)
23
23
  }
24
24
 
25
+ /** Product hero and card image: prefer thumbnail, then the first usable gallery image. */
26
+ export function productImageUrl(product: JsonRecord | null | undefined): string {
27
+ const thumbnail = stringValue(product?.thumbnail).trim()
28
+ if (thumbnail) return thumbnail
29
+ for (const image of asRecords(product?.images)) {
30
+ const url = stringValue(image.url).trim()
31
+ if (url) return url
32
+ }
33
+ return ""
34
+ }
35
+
25
36
  export function numberValue(value: unknown, fallback = 0) {
26
37
  const number = typeof value === "number" ? value : Number(value)
27
38
  return Number.isFinite(number) ? number : fallback