@hszrdm/create-commerce 1.22.0 → 1.24.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 (26) hide show
  1. package/package.json +2 -2
  2. package/src/cli.mjs +7 -1
  3. package/templates/backend/package.json +1 -1
  4. package/templates/backend/scripts/commerce-ops.mjs +12 -5
  5. package/templates/backend/scripts/core-restore.mjs +20 -19
  6. package/templates/backend/scripts/lib/core-backup-common.mjs +83 -0
  7. package/templates/backend/scripts/production-assets/restore.sh +1 -1
  8. package/templates/storefront/README.md +16 -5
  9. package/templates/storefront/package-lock.json +1646 -0
  10. package/templates/storefront/package.json +5 -2
  11. package/templates/storefront/src/app/api/checkout/trusted-shop/route.ts +19 -0
  12. package/templates/storefront/src/app/checkout/success/actions.ts +17 -0
  13. package/templates/storefront/src/app/checkout/success/page.tsx +32 -22
  14. package/templates/storefront/src/components/arukereso-trusted-shop.tsx +5 -5
  15. package/templates/storefront/src/components/checkout-flow.tsx +7 -1
  16. package/templates/storefront/src/components/cms-content.tsx +3 -1
  17. package/templates/storefront/src/components/order-detail.tsx +79 -47
  18. package/templates/storefront/src/lib/core/abandoned-cart.ts +5 -1
  19. package/templates/storefront/src/lib/core/after-sales.ts +50 -13
  20. package/templates/storefront/src/lib/core/checkout-confirmation-server.ts +16 -0
  21. package/templates/storefront/src/lib/core/checkout-proof.ts +16 -0
  22. package/templates/storefront/src/lib/core/checkout.ts +5 -10
  23. package/templates/storefront/src/lib/core/sanitize-cms-html.ts +30 -0
  24. package/templates/storefront/src/lib/storefront-copy.ts +8 -0
  25. package/templates/storefront/tests/cms-html.test.mjs +49 -0
  26. package/templates/storefront/tests/ga4-bootstrap.test.mjs +1 -1
@@ -19,19 +19,22 @@
19
19
  "test:account-verification": "node --test tests/account-verification.test.mjs",
20
20
  "test:product-images": "node --experimental-strip-types --test tests/product-image.test.mjs",
21
21
  "test:checkout-summary": "node --experimental-strip-types --test tests/checkout-summary.test.mjs",
22
+ "test:cms": "node --experimental-strip-types --test tests/cms-html.test.mjs",
22
23
  "test:checkout-payment-choices": "node --experimental-strip-types --test tests/checkout-payment-choices.test.mjs"
23
24
  },
24
25
  "dependencies": {
25
26
  "@stripe/react-stripe-js": "7.0.0",
26
27
  "@stripe/stripe-js": "10.2.0",
27
- "next": "16.4.3",
28
+ "next": "16.4.6",
28
29
  "react": "19.3.1",
29
- "react-dom": "19.3.1"
30
+ "react-dom": "19.3.1",
31
+ "sanitize-html": "2.18.2"
30
32
  },
31
33
  "devDependencies": {
32
34
  "@types/node": "26.6.5",
33
35
  "@types/react": "19.3.0",
34
36
  "@types/react-dom": "19.3.0",
37
+ "@types/sanitize-html": "2.16.2",
35
38
  "typescript": "7.0.2"
36
39
  }
37
40
  }
@@ -0,0 +1,19 @@
1
+ import { checkoutConfirmation } from "@/lib/core/checkout-confirmation-server"
2
+ import { medusaRawFetch } from "@/lib/core/client"
3
+
4
+ export async function POST(request: Request) {
5
+ const confirmation = await checkoutConfirmation()
6
+ const headers = { "Cache-Control": "private, no-store" }
7
+ const input = await request.json().catch(() => null)
8
+ if (!confirmation || confirmation.id !== input?.order_id) {
9
+ return new Response(null, { status: 404, headers })
10
+ }
11
+ const result = await medusaRawFetch(
12
+ `/store/arukereso/trusted-shop/${encodeURIComponent(confirmation.id)}`,
13
+ { method: "POST", body: "{}", headers: confirmation.headers, cache: "no-store" },
14
+ )
15
+ return new Response(result.body, {
16
+ status: result.status,
17
+ headers: { ...headers, "Content-Type": result.headers.get("Content-Type") || "application/json" },
18
+ })
19
+ }
@@ -0,0 +1,17 @@
1
+ "use server"
2
+
3
+ import { cookies } from "next/headers"
4
+ import { CONFIRMATION_COOKIE } from "@/lib/core/checkout-proof"
5
+ import { validConfirmationInput } from "@/lib/core/checkout-confirmation-server"
6
+
7
+ export async function saveCheckoutConfirmation(id: string, proof: string) {
8
+ if (!validConfirmationInput(id, proof)) throw new Error("Invalid checkout confirmation.")
9
+ // The Store API verifies the signature and current order ownership on every read.
10
+ ;(await cookies()).set(CONFIRMATION_COOKIE, `${id}.${proof}`, {
11
+ httpOnly: true,
12
+ sameSite: "lax",
13
+ secure: process.env.NODE_ENV === "production",
14
+ path: "/",
15
+ maxAge: 3600,
16
+ })
17
+ }
@@ -3,7 +3,7 @@ import { notFound } from "next/navigation"
3
3
  import { ArukeresoTrustedShop } from "@/components/arukereso-trusted-shop"
4
4
  import { GoogleAdsPurchase } from "@/components/google-ads-purchase"
5
5
  import { GoogleAnalyticsPurchase } from "@/components/google-analytics-purchase"
6
- import { checkoutApi } from "@/lib/core/checkout"
6
+ import { checkoutConfirmation } from "@/lib/core/checkout-confirmation-server"
7
7
  import { endpoint, getCoreConfig, medusaFetch } from "@/lib/core/client"
8
8
  import { asRecords, formatMoney, isRecord, stringValue, type JsonRecord } from "@/lib/core/commerce"
9
9
  import { storefrontCopy } from "@/lib/storefront-copy"
@@ -14,34 +14,47 @@ type SearchParams = Promise<{ order_id?: string }>
14
14
 
15
15
  export default async function CheckoutSuccessPage({ searchParams }: { searchParams: SearchParams }) {
16
16
  const query = await searchParams
17
- const orderId = query.order_id?.trim()
18
- if (!orderId) notFound()
17
+ const confirmation = await checkoutConfirmation()
18
+ if (!confirmation || (query.order_id && query.order_id !== confirmation.id)) notFound()
19
+ const orderId = confirmation.id
19
20
  const config = await getCoreConfig()
20
21
  const locale = await requestStorefrontLocale()
21
22
  const copy = storefrontCopy(locale)
22
23
  const routes = STOREFRONT_ROUTES[locale]
23
24
  const numberLocale = medusaLocale(locale)
24
25
  const orderEndpoint = endpoint(config.account.endpoints.order, { id: orderId })
25
- const { order } = await medusaFetch<{ order: JsonRecord }>(
26
- `${orderEndpoint}?fields=+items,+shipping_methods,+metadata`,
27
- { cache: "no-store" },
28
- ).catch(() => ({ order: null as unknown as JsonRecord }))
29
- if (!order) notFound()
26
+ const result = await medusaFetch<{ order: JsonRecord; checkout_payment?: JsonRecord }>(
27
+ `${orderEndpoint}?fields=+items,+shipping_methods,+customer_id`,
28
+ { headers: confirmation.headers, cache: "no-store" },
29
+ ).catch(() => null)
30
+ if (!result?.order) notFound()
31
+ const { order, checkout_payment: payment } = result
30
32
 
31
33
  const currency = stringValue(order.currency_code || config.store.default_currency).toUpperCase()
32
34
  const shippingMethods = asRecords(order.shipping_methods)
33
- const cod = shippingMethods.some((method) => isRecord(method.data) && (method.data.cod === true || method.data.cod === "true"))
34
- const metadata = isRecord(order.metadata) ? order.metadata : {}
35
- const transferSnapshot = isRecord(metadata.bank_transfer) ? metadata.bank_transfer : null
36
- const bankTransfer = config.payments.bank_transfer.enabled && !cod
37
- ? await checkoutApi(config).bankTransferDetails().catch(() => null)
35
+ const analyticsOrder = {
36
+ id: order.id, display_id: order.display_id, currency_code: order.currency_code,
37
+ total: order.total, shipping_total: order.shipping_total, tax_total: order.tax_total,
38
+ items: asRecords(order.items).map((item) => ({
39
+ id: item.id, variant_id: item.variant_id, product_id: item.product_id,
40
+ variant_sku: item.variant_sku, variant_title: item.variant_title, product_type: item.product_type,
41
+ product_title: item.product_title, title: item.title, quantity: item.quantity,
42
+ subtotal: item.subtotal, total: item.total, unit_price: item.unit_price, discount_total: item.discount_total,
43
+ })),
44
+ }
45
+ const cod = payment?.method === "cod" && payment.status === "pending"
46
+ const bank = isRecord(payment?.bank_transfer) ? payment.bank_transfer : null
47
+ const paymentMessage =
48
+ payment?.status === "paid" ? copy.confirmationPaymentPaid
49
+ : payment?.status === "canceled" ? copy.confirmationPaymentCanceled
50
+ : payment?.status === "failed" ? copy.confirmationPaymentFailed
51
+ : payment?.status === "pending" && !cod ? copy.confirmationPaymentPending
38
52
  : null
39
- const bank = bankTransfer && isRecord(bankTransfer.bank) ? bankTransfer.bank : null
40
53
 
41
54
  return (
42
55
  <div className="stack page-section narrow-page">
43
- <GoogleAnalyticsPurchase analytics={config.analytics} order={order} />
44
- <GoogleAdsPurchase googleAds={config.marketing.google_ads} order={order} />
56
+ <GoogleAnalyticsPurchase analytics={config.analytics} order={analyticsOrder} />
57
+ <GoogleAdsPurchase googleAds={config.marketing.google_ads} order={analyticsOrder} />
45
58
  <ArukeresoTrustedShop orderId={orderId} />
46
59
 
47
60
  <section className="success-hero panel stack">
@@ -50,6 +63,7 @@ export default async function CheckoutSuccessPage({ searchParams }: { searchPara
50
63
  <p className="eyebrow">{copy.orderRecorded}</p>
51
64
  <h1>{copy.thankYou}</h1>
52
65
  <p className="muted">{copy.orderNumber}: <strong>#{stringValue(order.display_id || order.id)}</strong></p>
66
+ {paymentMessage ? <p className="muted">{paymentMessage}</p> : null}
53
67
  </div>
54
68
  <div className="button-row">
55
69
  <Link className="button" href={routes.products}>{copy.continueShopping}</Link>
@@ -80,12 +94,8 @@ export default async function CheckoutSuccessPage({ searchParams }: { searchPara
80
94
  {bank.account_number ? <Info label={copy.bankAccount} value={stringValue(bank.account_number)} /> : null}
81
95
  {bank.iban ? <Info label="IBAN" value={stringValue(bank.iban)} /> : null}
82
96
  {bank.bic ? <Info label="BIC / SWIFT" value={stringValue(bank.bic)} /> : null}
83
- {transferSnapshot?.reference ? <Info label={copy.reference} value={stringValue(transferSnapshot.reference)} /> : null}
84
- {transferSnapshot?.dueDate
85
- ? <Info label={copy.paymentDeadline} value={stringValue(transferSnapshot.dueDate)} />
86
- : bankTransfer?.due_days
87
- ? <Info label={copy.paymentDeadline} value={`${stringValue(bankTransfer.due_days)} ${copy.days}`} />
88
- : null}
97
+ <Info label={copy.reference} value={stringValue(bank.reference)} />
98
+ {bank.due_date ? <Info label={copy.paymentDeadline} value={stringValue(bank.due_date)} /> : null}
89
99
  <p className="muted small">{copy.referenceHint}</p>
90
100
  </section>
91
101
  ) : null}
@@ -1,7 +1,6 @@
1
1
  "use client"
2
2
 
3
3
  import { useEffect } from "react"
4
- import { medusaRawFetch } from "@/lib/core/client"
5
4
 
6
5
  const STORAGE_PREFIX = "hszrdm:arukereso-trusted-shop:v2:"
7
6
 
@@ -30,10 +29,11 @@ export function ArukeresoTrustedShop({ orderId }: { orderId: string }) {
30
29
 
31
30
  void (async () => {
32
31
  try {
33
- const response = await medusaRawFetch(
34
- `/store/arukereso/trusted-shop/${encodeURIComponent(orderId)}`,
35
- { method: "POST", body: JSON.stringify({}) },
36
- )
32
+ const response = await fetch("/api/checkout/trusted-shop", {
33
+ method: "POST",
34
+ headers: { "Content-Type": "application/json" },
35
+ body: JSON.stringify({ order_id: orderId }),
36
+ })
37
37
  if (cancelled || response.status === 204 || !response.ok) return
38
38
 
39
39
  const data = (await response.json()) as TrustedShopResponse
@@ -1,5 +1,8 @@
1
1
  "use client"
2
2
 
3
+ import { saveCheckoutConfirmation } from "@/app/checkout/success/actions"
4
+ import { forgetCartProof } from "@/lib/core/checkout-proof"
5
+
3
6
  import { useCallback, useEffect, useMemo, useRef, useState, useId } from "react"
4
7
  import { usePathname, useRouter, useSearchParams } from "next/navigation"
5
8
  import { useCart } from "./cart-provider"
@@ -400,8 +403,11 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
400
403
  ),
401
404
  )
402
405
  }
406
+ const proof = stringValue(result.order_confirmation_proof)
407
+ await saveCheckoutConfirmation(orderId, proof)
408
+ forgetCartProof(cartId)
403
409
  clearCart()
404
- router.push(`${routes.checkoutSuccess}?order_id=${encodeURIComponent(orderId)}`)
410
+ router.push(routes.checkoutSuccess)
405
411
  return
406
412
  }
407
413
  const detail = isRecord(result.cart) ? stringValue(result.cart.error || result.cart.message) : ""
@@ -1,4 +1,6 @@
1
1
  import Link from "next/link"
2
+ import { sanitizeCmsHtml } from "@/lib/core/sanitize-cms-html"
3
+
2
4
  import type { CmsEntry } from "@/lib/core/cms"
3
5
 
4
6
  type Locale = "hu" | "en"
@@ -38,7 +40,7 @@ export function CmsEntryMeta({ entry, locale }: { entry: CmsEntry; locale: Local
38
40
 
39
41
  export function CmsEntryBody({ entry }: { entry: CmsEntry }) {
40
42
  if (entry.body_format === "html" && entry.body) {
41
- return <div className="cms-body" dangerouslySetInnerHTML={{ __html: entry.body }} />
43
+ return <div className="cms-body" dangerouslySetInnerHTML={{ __html: sanitizeCmsHtml(entry.body) }} />
42
44
  }
43
45
 
44
46
  if (entry.body_format === "blocks" && Array.isArray(entry.blocks)) {
@@ -2,10 +2,10 @@
2
2
 
3
3
  import Link from "next/link"
4
4
  import { usePathname } from "next/navigation"
5
- import { useCallback, useEffect, useMemo, useState } from "react"
5
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react"
6
6
  import { accountApi } from "@/lib/core/account"
7
7
  import { afterSalesApi, type AfterSalesCaseType } from "@/lib/core/after-sales"
8
- import { medusaFetch } from "@/lib/core/client"
8
+ import { CoreApiError, medusaFetch } from "@/lib/core/client"
9
9
  import {
10
10
  asRecords,
11
11
  formatMoney,
@@ -41,6 +41,7 @@ export function OrderDetail({ config, orderId }: { config: CoreConfig; orderId:
41
41
  const [variants, setVariants] = useState<JsonRecord[]>([])
42
42
  const [loading, setLoading] = useState(true)
43
43
  const [error, setError] = useState<string | null>(null)
44
+ const [actionError, setActionError] = useState<string | null>(null)
44
45
  const [message, setMessage] = useState<string | null>(null)
45
46
  const [mode, setMode] = useState<CaseMode>("return")
46
47
  const [itemId, setItemId] = useState("")
@@ -51,6 +52,7 @@ export function OrderDetail({ config, orderId }: { config: CoreConfig; orderId:
51
52
  const [newVariantId, setNewVariantId] = useState("")
52
53
  const [description, setDescription] = useState("")
53
54
  const [busy, setBusy] = useState(false)
55
+ const submitting = useRef(false)
54
56
 
55
57
  const load = useCallback(async () => {
56
58
  setLoading(true)
@@ -110,6 +112,8 @@ export function OrderDetail({ config, orderId }: { config: CoreConfig; orderId:
110
112
  const selectedItem = items.find((item) => stringValue(item.id) === itemId) || items[0]
111
113
  const currency = stringValue(order.currency_code || config.store.default_currency).toUpperCase()
112
114
  const afterConfig = after && isRecord(after.config) ? after.config : {}
115
+ const operation = isRecord(after?.operation) ? after.operation : null
116
+ const blocked = operation?.state === "processing" || operation?.state === "recovery_required"
113
117
  const returns = asRecords(after?.returns)
114
118
  const exchanges = asRecords(after?.exchanges)
115
119
  const claims = asRecords(after?.claims)
@@ -119,57 +123,69 @@ export function OrderDetail({ config, orderId }: { config: CoreConfig; orderId:
119
123
  ...claims.map((entry) => ({ ...entry, __case_type: "claim" as const })),
120
124
  ].sort((a: VisibleCase, b: VisibleCase) => stringValue(b.created_at).localeCompare(stringValue(a.created_at)))
121
125
 
122
- const submit = async () => {
123
- if (!selectedItem) {
124
- throw new Error(localized(locale, "Válassz rendelési tételt.", "Choose an order item."))
125
- }
126
+ const runAction = async (action: () => Promise<void>) => {
127
+ if (submitting.current || blocked) return
128
+ submitting.current = true
126
129
  setBusy(true)
127
- setError(null)
130
+ setActionError(null)
128
131
  setMessage(null)
129
132
  try {
130
- const baseItem = {
131
- id: stringValue(selectedItem.id),
132
- quantity,
133
- note: description || undefined,
134
- }
135
- if (mode === "return") {
136
- await afterSales.createReturn(orderId, {
137
- items: [{ ...baseItem, reason_id: reasonId || undefined }],
138
- description: description || undefined,
139
- locale: apiLocale,
140
- })
141
- } else if (mode === "exchange") {
142
- if (!newVariantId) {
143
- throw new Error(localized(locale, "Válassz csereterméket.", "Choose a replacement product."))
133
+ await action()
134
+ } catch (cause) {
135
+ if (cause instanceof CoreApiError && isRecord(cause.payload) && isRecord(cause.payload.operation)) {
136
+ const blockedOperation = cause.payload.operation
137
+ if (blockedOperation.state === "processing" || blockedOperation.state === "recovery_required") {
138
+ setAfter(current => ({ ...current, operation: blockedOperation }))
139
+ return
144
140
  }
145
- await afterSales.createExchange(orderId, {
146
- return_items: [{ ...baseItem, reason_id: reasonId || undefined }],
147
- new_items: [{ variant_id: newVariantId, quantity }],
148
- description: description || undefined,
149
- locale: apiLocale,
150
- })
151
- } else {
152
- await afterSales.createClaim(orderId, {
153
- type: claimType,
154
- items: [{ ...baseItem, reason: claimReason }],
155
- description: description || undefined,
156
- locale: apiLocale,
157
- })
158
141
  }
159
- setMessage(localized(locale, "A kérelem elküldve.", "Request submitted."))
160
- setDescription("")
161
- await load()
162
- } catch (cause) {
163
- setError(
164
- cause instanceof Error
165
- ? cause.message
166
- : localized(locale, "A kérelem nem küldhető el.", "The request could not be submitted."),
167
- )
142
+ setActionError(cause instanceof Error
143
+ ? cause.message
144
+ : localized(locale, "A művelet sikertelen.", "The operation could not be completed."))
168
145
  } finally {
146
+ submitting.current = false
169
147
  setBusy(false)
170
148
  }
171
149
  }
172
150
 
151
+ const submit = () => runAction(async () => {
152
+ if (!selectedItem) {
153
+ throw new Error(localized(locale, "Válassz rendelési tételt.", "Choose an order item."))
154
+ }
155
+ const baseItem = {
156
+ id: stringValue(selectedItem.id),
157
+ quantity,
158
+ note: description || undefined,
159
+ }
160
+ if (mode === "return") {
161
+ await afterSales.createReturn(orderId, {
162
+ items: [{ ...baseItem, reason_id: reasonId || undefined }],
163
+ description: description || undefined,
164
+ locale: apiLocale,
165
+ })
166
+ } else if (mode === "exchange") {
167
+ if (!newVariantId) {
168
+ throw new Error(localized(locale, "Válassz csereterméket.", "Choose a replacement product."))
169
+ }
170
+ await afterSales.createExchange(orderId, {
171
+ return_items: [{ ...baseItem, reason_id: reasonId || undefined }],
172
+ new_items: [{ variant_id: newVariantId, quantity }],
173
+ description: description || undefined,
174
+ locale: apiLocale,
175
+ })
176
+ } else {
177
+ await afterSales.createClaim(orderId, {
178
+ type: claimType,
179
+ items: [{ ...baseItem, reason: claimReason }],
180
+ description: description || undefined,
181
+ locale: apiLocale,
182
+ })
183
+ }
184
+ setMessage(localized(locale, "A kérelem elküldve.", "Request submitted."))
185
+ setDescription("")
186
+ await load()
187
+ })
188
+
173
189
  const canReturn = config.after_sales.enabled && config.after_sales.returns && afterConfig.returnsEnabled !== false
174
190
  const canExchange = config.after_sales.enabled && config.after_sales.exchanges && afterConfig.exchangesEnabled !== false
175
191
  const canClaim = config.after_sales.enabled && config.after_sales.claims && afterConfig.claimsEnabled !== false
@@ -254,9 +270,22 @@ export function OrderDetail({ config, orderId }: { config: CoreConfig; orderId:
254
270
  ) : null}
255
271
  </div>
256
272
  <label>{copy.description}<textarea value={description} rows={4} onChange={(event) => setDescription(event.target.value)} placeholder={copy.requestDescriptionPlaceholder} /></label>
257
- <button className="button" type="button" disabled={busy} onClick={() => void submit()}>{busy ? copy.sending : copy.sendRequest}</button>
273
+ <button className="button" type="button" disabled={busy || blocked} onClick={() => void submit()}>{busy ? copy.sending : copy.sendRequest}</button>
258
274
  {message ? <p className="success">{message}</p> : null}
259
- {error ? <p className="error">{error}</p> : null}
275
+ {actionError ? <p className="error" role="alert">{actionError}</p> : null}
276
+ {blocked ? (
277
+ <div className="notice" role="status">
278
+ <p>{operation?.state === "processing"
279
+ ? localized(locale, "A művelet feldolgozása folyamatban van.", "The request is being processed.")
280
+ : localized(locale, "Az ügy állapota ellenőrzést igényel. Kérjük, keresd az ügyfélszolgálatot.", "This case needs review. Please contact support.")}</p>
281
+ {operation?.id
282
+ ? <p>{localized(locale, "Műveletazonosító", "Operation ID")} {stringValue(operation.id)}</p>
283
+ : operation?.case_id
284
+ ? <p>{localized(locale, "Ügyazonosító", "Case ID")} {stringValue(operation.case_id)}</p>
285
+ : null}
286
+ <button type="button" className="text-button" onClick={() => void load()}>{localized(locale, "Állapot frissítése", "Refresh status")}</button>
287
+ </div>
288
+ ) : null}
260
289
  </section>
261
290
  ) : null}
262
291
 
@@ -271,8 +300,11 @@ export function OrderDetail({ config, orderId }: { config: CoreConfig; orderId:
271
300
  </div>
272
301
  <div>
273
302
  <span className="status-pill">{stringValue(entry.request_status || entry.status || entry.change_status || "—")}</span>
274
- {stringValue(entry.request_status) === "submitted"
275
- ? <button className="text-button danger" type="button" onClick={() => void afterSales.cancel(orderId, entry.__case_type, stringValue(entry.id)).then(load)}>{copy.withdraw}</button>
303
+ {(entry.customer_cancelable ?? (entry.request_status === "submitted")) === true
304
+ ? <button className="text-button danger" type="button" disabled={busy || blocked} onClick={() => void runAction(async () => {
305
+ await afterSales.cancel(orderId, entry.__case_type, stringValue(entry.id))
306
+ await load()
307
+ })}>{copy.withdraw}</button>
276
308
  : null}
277
309
  </div>
278
310
  </div>
@@ -1,10 +1,12 @@
1
1
  import { CoreApiError, medusaFetch } from "./client"
2
+ import { rememberCartProof } from "./checkout-proof"
2
3
  import type { CoreConfig } from "./types"
3
4
 
4
5
  export type AbandonedCartRecoveryResult = {
5
6
  valid: boolean
6
7
  reason?: string
7
8
  cart_id?: string
9
+ cart_proof?: string
8
10
  locale?: "hu-HU" | "en-US" | string
9
11
  coupon_code?: string | null
10
12
  }
@@ -18,10 +20,12 @@ export function abandonedCartApi(config: CoreConfig) {
18
20
  recover: async (token: string) => {
19
21
  const query = new URLSearchParams({ token })
20
22
  try {
21
- return await medusaFetch<AbandonedCartRecoveryResult>(
23
+ const result = await medusaFetch<AbandonedCartRecoveryResult>(
22
24
  `${recoveryEndpoint}?${query.toString()}`,
23
25
  { cache: "no-store" },
24
26
  )
27
+ if (result.valid && result.cart_id) rememberCartProof(result.cart_id, result.cart_proof)
28
+ return result
25
29
  } catch (cause) {
26
30
  if (
27
31
  cause instanceof CoreApiError &&
@@ -1,8 +1,54 @@
1
- import { endpoint, medusaFetch } from "./client"
1
+ import { CoreApiError, endpoint, medusaFetch } from "./client"
2
2
  import type { CoreConfig } from "./types"
3
3
 
4
4
  export type AfterSalesCaseType = "return" | "exchange" | "claim"
5
5
 
6
+ async function submitRequest(path: string, body: Record<string, unknown>) {
7
+ const payload = JSON.stringify(body)
8
+ const key = await getAttemptKey(path, payload)
9
+ try {
10
+ const result = await medusaFetch(path, {
11
+ method: "POST",
12
+ body: payload,
13
+ headers: key ? { "Idempotency-Key": key.id } : undefined,
14
+ })
15
+ key?.finish()
16
+ return result
17
+ } catch (cause) {
18
+ if (key && cause instanceof CoreApiError &&
19
+ cause.payload && typeof cause.payload === "object" &&
20
+ "code" in cause.payload && cause.payload.code === "after_sales_failed_compensated") {
21
+ // A subsequent click can start a new attempt after verified rollback.
22
+ key.finish()
23
+ }
24
+ throw cause
25
+ }
26
+ }
27
+
28
+ async function getAttemptKey(path: string, payload: string) {
29
+ if (typeof window === "undefined" || !globalThis.crypto?.subtle) return null
30
+ try {
31
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`${path}\n${payload}`))
32
+ const storageKey = `hszrdm-after-sales:${Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, "0")).join("")}`
33
+ const storage = window.sessionStorage
34
+ const id = storage.getItem(storageKey) || crypto.randomUUID()
35
+ storage.setItem(storageKey, id)
36
+ return {
37
+ id,
38
+ finish: () => {
39
+ try {
40
+ if (storage.getItem(storageKey) === id) storage.removeItem(storageKey)
41
+ } catch {
42
+ // The server already has the receipt even if browser storage is unavailable.
43
+ }
44
+ },
45
+ }
46
+ } catch {
47
+ // Restricted storage and non-secure origins use the server's legacy payload key.
48
+ return null
49
+ }
50
+ }
51
+
6
52
  export function afterSalesApi(config: CoreConfig) {
7
53
  const paths = config.after_sales.endpoints
8
54
 
@@ -20,22 +66,13 @@ export function afterSalesApi(config: CoreConfig) {
20
66
  ),
21
67
 
22
68
  createReturn: (orderId: string, body: Record<string, unknown>) =>
23
- medusaFetch(endpoint(paths.returns, { id: orderId }), {
24
- method: "POST",
25
- body: JSON.stringify(body),
26
- }),
69
+ submitRequest(endpoint(paths.returns, { id: orderId }), body),
27
70
 
28
71
  createExchange: (orderId: string, body: Record<string, unknown>) =>
29
- medusaFetch(endpoint(paths.exchanges, { id: orderId }), {
30
- method: "POST",
31
- body: JSON.stringify(body),
32
- }),
72
+ submitRequest(endpoint(paths.exchanges, { id: orderId }), body),
33
73
 
34
74
  createClaim: (orderId: string, body: Record<string, unknown>) =>
35
- medusaFetch(endpoint(paths.claims, { id: orderId }), {
36
- method: "POST",
37
- body: JSON.stringify(body),
38
- }),
75
+ submitRequest(endpoint(paths.claims, { id: orderId }), body),
39
76
 
40
77
  cancel: (orderId: string, caseType: AfterSalesCaseType, caseId: string) =>
41
78
  medusaFetch(
@@ -0,0 +1,16 @@
1
+ import { cookies } from "next/headers"
2
+ import { CONFIRMATION_COOKIE, CONFIRMATION_HEADER } from "./checkout-proof"
3
+
4
+ export function validConfirmationInput(id: unknown, proof: unknown) {
5
+ return typeof id === "string" && /^[A-Za-z0-9_-]{1,100}$/.test(id) &&
6
+ typeof proof === "string" && proof.length <= 1024 && /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{43}$/.test(proof)
7
+ }
8
+
9
+ export async function checkoutConfirmation() {
10
+ const value = (await cookies()).get(CONFIRMATION_COOKIE)?.value
11
+ if (!value) return null
12
+ const [id, payload, signature] = value.split(".")
13
+ const proof = `${payload}.${signature}`
14
+ if (!validConfirmationInput(id, proof)) return null
15
+ return { id, headers: { [CONFIRMATION_HEADER]: proof } }
16
+ }
@@ -0,0 +1,16 @@
1
+ const CART_PROOF_KEY = "hszrdm:checkout-cart-proof:"
2
+ export const CONFIRMATION_COOKIE = "hszrdm_order_confirmation"
3
+ export const CONFIRMATION_HEADER = "x-hszrdm-order-proof"
4
+
5
+ export function rememberCartProof(cartId: string, proof: unknown) {
6
+ if (typeof proof === "string") window.localStorage.setItem(CART_PROOF_KEY + cartId, proof)
7
+ }
8
+
9
+ export function cartProofHeaders(cartId: string): Record<string, string> {
10
+ const proof = window.localStorage.getItem(CART_PROOF_KEY + cartId)
11
+ return proof ? { "x-hszrdm-cart-proof": proof } : {}
12
+ }
13
+
14
+ export function forgetCartProof(cartId: string) {
15
+ window.localStorage.removeItem(CART_PROOF_KEY + cartId)
16
+ }
@@ -1,3 +1,4 @@
1
+ import { cartProofHeaders, rememberCartProof } from "./checkout-proof"
1
2
  import { endpoint, medusaFetch } from "./client"
2
3
  import { trackGoogleAdsPurchase } from "./google-ads"
3
4
  import {
@@ -82,15 +83,6 @@ export function checkoutApi(config: CoreConfig) {
82
83
  method: "POST", body: JSON.stringify({ mode }),
83
84
  },
84
85
  )
85
- if (mode === "bank_transfer" && config.payments.bank_transfer.enabled) {
86
- const current = (await getCart(cartId)).cart
87
- const metadata = isRecord(current.metadata) ? current.metadata : {}
88
- const details = await bankTransferDetails()
89
- const configured = isRecord(details.cart_metadata) ? details.cart_metadata : {}
90
- await updateCart(cartId, {
91
- metadata: { ...metadata, ...configured, core_payment_method: "bank_transfer" },
92
- })
93
- }
94
86
  }
95
87
 
96
88
  const saveFoxpostSelection = (
@@ -156,10 +148,12 @@ export function checkoutApi(config: CoreConfig) {
156
148
  const region = await resolveDefaultRegion()
157
149
  regionId = String(region.id)
158
150
  }
159
- return medusaFetch<{ cart: Record<string, unknown> }>(paths.create_cart, {
151
+ const result = await medusaFetch<{ cart: Record<string, unknown>; cart_proof?: string }>(paths.create_cart, {
160
152
  method: "POST",
161
153
  body: JSON.stringify({ region_id: regionId, locale: config.store.locale, ...body }),
162
154
  })
155
+ rememberCartProof(stringValue(result.cart.id), result.cart_proof)
156
+ return result
163
157
  },
164
158
 
165
159
  getCart,
@@ -367,6 +361,7 @@ export function checkoutApi(config: CoreConfig) {
367
361
  {
368
362
  method: "POST",
369
363
  body: JSON.stringify({}),
364
+ headers: cartProofHeaders(cartId),
370
365
  },
371
366
  )
372
367
  if (result.type === "order" && isRecord(result.order)) {
@@ -0,0 +1,30 @@
1
+ import sanitizeHtml from "sanitize-html"
2
+
3
+ /** Render translated or original CMS fragments with the same server-side policy. */
4
+ export function sanitizeCmsHtml(html: string): string {
5
+ return sanitizeHtml(html, {
6
+ allowedTags: [
7
+ "p", "br", "div", "span", "h1", "h2", "h3", "h4", "h5", "h6",
8
+ "b", "strong", "i", "em", "u", "s", "del", "ul", "ol", "li",
9
+ "blockquote", "pre", "code", "hr", "a", "img", "figure", "figcaption",
10
+ "table", "caption", "thead", "tbody", "tfoot", "tr", "th", "td",
11
+ ],
12
+ allowedAttributes: {
13
+ a: ["href", "title", "rel"],
14
+ img: ["src", "alt", "title", "width", "height"],
15
+ ol: ["start"],
16
+ th: ["colspan", "rowspan", "scope"],
17
+ td: ["colspan", "rowspan"],
18
+ },
19
+ allowedSchemes: ["http", "https", "mailto", "tel"],
20
+ allowedSchemesByTag: { img: ["http", "https"] },
21
+ allowedSchemesAppliedToAttributes: ["href", "src"],
22
+ allowProtocolRelative: false,
23
+ parseStyleAttributes: false,
24
+ nonTextTags: [
25
+ "script", "style", "textarea", "option", "iframe", "object", "embed",
26
+ "svg", "math", "template", "noscript", "xmp",
27
+ ],
28
+ transformTags: { a: sanitizeHtml.simpleTransform("a", { rel: "noopener noreferrer" }) },
29
+ })
30
+ }
@@ -194,6 +194,10 @@ const hu = {
194
194
  previousRequests: "Korábbi kérelmek",
195
195
  withdraw: "Visszavonás",
196
196
  orderRecorded: "Rendelés rögzítve",
197
+ confirmationPaymentPending: "A fizetés még függőben van.",
198
+ confirmationPaymentPaid: "A fizetés megtörtént.",
199
+ confirmationPaymentCanceled: "A fizetést törölték.",
200
+ confirmationPaymentFailed: "A fizetés sikertelen volt.",
197
201
  thankYou: "Köszönjük a rendelésed!",
198
202
  orderNumber: "Rendelésszám",
199
203
  continueShopping: "Tovább vásárolok",
@@ -409,6 +413,10 @@ const en: Record<CopyKey, string> = {
409
413
  previousRequests: "Previous requests",
410
414
  withdraw: "Withdraw",
411
415
  orderRecorded: "Order received",
416
+ confirmationPaymentPending: "Payment is still pending.",
417
+ confirmationPaymentPaid: "Payment received.",
418
+ confirmationPaymentCanceled: "Payment was canceled.",
419
+ confirmationPaymentFailed: "Payment failed.",
412
420
  thankYou: "Thank you for your order!",
413
421
  orderNumber: "Order number",
414
422
  continueShopping: "Continue shopping",