@hszrdm/create-commerce 1.4.0 → 1.6.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 (48) hide show
  1. package/package.json +1 -1
  2. package/templates/backend/.env.example +13 -0
  3. package/templates/backend/README.md +4 -0
  4. package/templates/backend/package.json +3 -1
  5. package/templates/backend/scripts/core-backup.mjs +281 -0
  6. package/templates/backend/scripts/core-restore.mjs +179 -0
  7. package/templates/backend/scripts/lib/core-backup-common.mjs +237 -0
  8. package/templates/backend/scripts/production-assets/deploy.sh +2 -1
  9. package/templates/backend/scripts/production-assets/install.sh +2 -1
  10. package/templates/backend/scripts/production-assets/restore.sh +4 -1
  11. package/templates/backend/src/scripts/core-init.ts +3 -1
  12. package/templates/storefront/README.md +35 -12
  13. package/templates/storefront/src/app/[countryCode]/products/[handle]/page.tsx +3 -2
  14. package/templates/storefront/src/app/blog/page.tsx +46 -8
  15. package/templates/storefront/src/app/cart/page.tsx +2 -0
  16. package/templates/storefront/src/app/cart/shared/[token]/page.tsx +25 -0
  17. package/templates/storefront/src/app/cart-recovery/page.tsx +35 -0
  18. package/templates/storefront/src/app/ertekeles/page.tsx +25 -0
  19. package/templates/storefront/src/app/fiok-aktivalas/page.tsx +35 -0
  20. package/templates/storefront/src/app/knowledge-base/page.tsx +46 -8
  21. package/templates/storefront/src/app/layout.tsx +5 -2
  22. package/templates/storefront/src/app/legal/page.tsx +18 -2
  23. package/templates/storefront/src/app/page.tsx +33 -4
  24. package/templates/storefront/src/app/pages/page.tsx +43 -0
  25. package/templates/storefront/src/components/abandoned-cart-recovery.tsx +139 -0
  26. package/templates/storefront/src/components/account-activation-form.tsx +333 -0
  27. package/templates/storefront/src/components/add-to-cart.tsx +132 -2
  28. package/templates/storefront/src/components/analytics.tsx +52 -19
  29. package/templates/storefront/src/components/cart-provider.tsx +40 -3
  30. package/templates/storefront/src/components/cart-share-button.tsx +93 -0
  31. package/templates/storefront/src/components/cms-taxonomy-filters.tsx +86 -0
  32. package/templates/storefront/src/components/customer-cart-resume-gate.tsx +112 -0
  33. package/templates/storefront/src/components/fogyasztobarat-embed.tsx +32 -0
  34. package/templates/storefront/src/components/review-request-form.tsx +419 -0
  35. package/templates/storefront/src/components/shared-cart-view.tsx +257 -0
  36. package/templates/storefront/src/lib/core/abandoned-cart.ts +47 -0
  37. package/templates/storefront/src/lib/core/account-activation.ts +75 -0
  38. package/templates/storefront/src/lib/core/back-in-stock.ts +25 -0
  39. package/templates/storefront/src/lib/core/catalog.ts +12 -0
  40. package/templates/storefront/src/lib/core/checkout.ts +86 -4
  41. package/templates/storefront/src/lib/core/customer-cart-resume.ts +51 -0
  42. package/templates/storefront/src/lib/core/google-ads.ts +58 -0
  43. package/templates/storefront/src/lib/core/legal.ts +14 -0
  44. package/templates/storefront/src/lib/core/reviews.ts +37 -5
  45. package/templates/storefront/src/lib/core/shared-cart.ts +37 -0
  46. package/templates/storefront/src/lib/core/types.ts +18 -0
  47. package/templates/storefront/src/lib/storefront-routes.ts +12 -0
  48. package/templates/storefront/src/proxy.ts +11 -0
@@ -0,0 +1,419 @@
1
+ "use client"
2
+
3
+ import Link from "next/link"
4
+ import { usePathname, useSearchParams } from "next/navigation"
5
+ import { useEffect, useMemo, useState, type FormEvent } from "react"
6
+ import { accountApi } from "@/lib/core/account"
7
+ import { CoreApiError } from "@/lib/core/client"
8
+ import {
9
+ loadReviewRequest,
10
+ submitProductReview,
11
+ type ReviewRequest,
12
+ type ReviewRequestProduct,
13
+ } from "@/lib/core/reviews"
14
+ import type { CoreConfig } from "@/lib/core/types"
15
+ import {
16
+ localeFromPathname,
17
+ productPath,
18
+ storefrontLocale,
19
+ STOREFRONT_ROUTES,
20
+ type StorefrontLocale,
21
+ } from "@/lib/storefront-routes"
22
+
23
+ type Draft = {
24
+ rating: number
25
+ body: string
26
+ busy: boolean
27
+ error: string | null
28
+ submittedStatus: "pending" | "published" | "rejected" | null
29
+ }
30
+
31
+ export function ReviewRequestForm({ config }: { config: CoreConfig }) {
32
+ const pathname = usePathname()
33
+ const search = useSearchParams()
34
+ const fallbackLocale = storefrontLocale(config.store.locale)
35
+ const locale = localeFromPathname(pathname, fallbackLocale)
36
+ const copy = reviewCopy(locale)
37
+ const routes = STOREFRONT_ROUTES[locale]
38
+ const token = search.get("token")?.trim() || ""
39
+ const account = useMemo(() => accountApi(config), [config])
40
+
41
+ const [request, setRequest] = useState<ReviewRequest | null>(null)
42
+ const [drafts, setDrafts] = useState<Record<string, Draft>>({})
43
+ const [loading, setLoading] = useState(true)
44
+ const [loadError, setLoadError] = useState<string | null>(null)
45
+ const [authenticated, setAuthenticated] = useState<boolean | null>(null)
46
+ const [loginEmail, setLoginEmail] = useState("")
47
+ const [loginPassword, setLoginPassword] = useState("")
48
+ const [loginBusy, setLoginBusy] = useState(false)
49
+ const [loginError, setLoginError] = useState<string | null>(null)
50
+
51
+ useEffect(() => {
52
+ let cancelled = false
53
+ if (!token) {
54
+ setLoadError(copy.missingToken)
55
+ setLoading(false)
56
+ return
57
+ }
58
+
59
+ setLoading(true)
60
+ setLoadError(null)
61
+ void loadReviewRequest(token)
62
+ .then((payload) => {
63
+ if (cancelled) return
64
+ setRequest(payload)
65
+ setDrafts((current) => {
66
+ const next = { ...current }
67
+ for (const product of payload.products) {
68
+ next[product.product_id] ||= emptyDraft()
69
+ }
70
+ return next
71
+ })
72
+ })
73
+ .catch((cause) => {
74
+ if (cancelled) return
75
+ setLoadError(reviewRequestError(cause, locale))
76
+ })
77
+ .finally(() => {
78
+ if (!cancelled) setLoading(false)
79
+ })
80
+
81
+ return () => {
82
+ cancelled = true
83
+ }
84
+ }, [copy.missingToken, locale, token])
85
+
86
+ useEffect(() => {
87
+ let cancelled = false
88
+ void account
89
+ .profile()
90
+ .then(() => {
91
+ if (!cancelled) setAuthenticated(true)
92
+ })
93
+ .catch((cause) => {
94
+ if (cancelled) return
95
+ if (cause instanceof CoreApiError && cause.status === 401) {
96
+ setAuthenticated(false)
97
+ return
98
+ }
99
+ setAuthenticated(false)
100
+ })
101
+ return () => {
102
+ cancelled = true
103
+ }
104
+ }, [account])
105
+
106
+ async function login(event: FormEvent<HTMLFormElement>) {
107
+ event.preventDefault()
108
+ if (loginBusy) return
109
+ setLoginBusy(true)
110
+ setLoginError(null)
111
+ try {
112
+ await account.login(loginEmail.trim(), loginPassword)
113
+ setAuthenticated(true)
114
+ setLoginPassword("")
115
+ } catch (cause) {
116
+ setLoginError(cause instanceof Error ? cause.message : copy.loginFailed)
117
+ } finally {
118
+ setLoginBusy(false)
119
+ }
120
+ }
121
+
122
+ async function submit(product: ReviewRequestProduct, event: FormEvent<HTMLFormElement>) {
123
+ event.preventDefault()
124
+ const draft = drafts[product.product_id] || emptyDraft()
125
+ if (!authenticated) {
126
+ setDraft(product.product_id, { error: copy.loginRequired })
127
+ return
128
+ }
129
+ if (!draft.body.trim() || draft.busy || product.reviewed) return
130
+
131
+ setDraft(product.product_id, { busy: true, error: null })
132
+ try {
133
+ const result = await submitProductReview(product.product_id, {
134
+ rating: draft.rating,
135
+ body: draft.body.trim(),
136
+ review_request_token: token,
137
+ })
138
+ const status = result.review.status || "pending"
139
+ setDraft(product.product_id, {
140
+ busy: false,
141
+ body: "",
142
+ submittedStatus: status,
143
+ })
144
+ setRequest((current) => {
145
+ if (!current) return current
146
+ const products = current.products.map((item) =>
147
+ item.product_id === product.product_id ? { ...item, reviewed: true } : item,
148
+ )
149
+ if (products.length > 0 && products.every((item) => item.reviewed) && typeof window !== "undefined") {
150
+ window.history.replaceState(window.history.state, "", pathname)
151
+ }
152
+ return { ...current, products }
153
+ })
154
+ } catch (cause) {
155
+ if (cause instanceof CoreApiError && cause.status === 401) {
156
+ setAuthenticated(false)
157
+ setDraft(product.product_id, { busy: false, error: copy.loginRequired })
158
+ return
159
+ }
160
+ setDraft(product.product_id, {
161
+ busy: false,
162
+ error: cause instanceof Error ? cause.message : copy.submitFailed,
163
+ })
164
+ }
165
+ }
166
+
167
+ function setDraft(productId: string, patch: Partial<Draft>) {
168
+ setDrafts((current) => ({
169
+ ...current,
170
+ [productId]: { ...(current[productId] || emptyDraft()), ...patch },
171
+ }))
172
+ }
173
+
174
+ if (loading) return <div className="empty-state">{copy.checking}</div>
175
+
176
+ if (loadError || !request) {
177
+ return (
178
+ <section className="panel stack narrow-card">
179
+ <div>
180
+ <p className="eyebrow">{copy.eyebrow}</p>
181
+ <h1>{copy.invalidTitle}</h1>
182
+ </div>
183
+ <p className="error">{loadError || copy.invalidText}</p>
184
+ <Link className="button secondary" href={routes.home}>{copy.backHome}</Link>
185
+ </section>
186
+ )
187
+ }
188
+
189
+ const remaining = request.products.filter((product) => !product.reviewed).length
190
+
191
+ return (
192
+ <div className="stack">
193
+ <section className="panel stack-sm">
194
+ <div>
195
+ <p className="eyebrow">{copy.eyebrow}</p>
196
+ <h1>{copy.title}</h1>
197
+ </div>
198
+ <p className="muted">
199
+ {copy.orderLabel} #{String(request.order.display_id || request.order.id)} · {remaining
200
+ ? copy.remaining.replace("{count}", String(remaining))
201
+ : copy.complete}
202
+ </p>
203
+ {request.reward?.available_after_publish ? (
204
+ <p className="muted small">{copy.rewardHint}</p>
205
+ ) : null}
206
+ </section>
207
+
208
+ {authenticated === false ? (
209
+ <section className="panel stack narrow-card">
210
+ <div>
211
+ <p className="eyebrow">{copy.signInEyebrow}</p>
212
+ <h2>{copy.signInTitle}</h2>
213
+ </div>
214
+ <p className="muted">{copy.signInText}</p>
215
+ <form className="stack-sm" onSubmit={login}>
216
+ <label>
217
+ {copy.email}
218
+ <input
219
+ autoComplete="email"
220
+ type="email"
221
+ required
222
+ value={loginEmail}
223
+ onChange={(event) => setLoginEmail(event.target.value)}
224
+ />
225
+ </label>
226
+ <label>
227
+ {copy.password}
228
+ <input
229
+ autoComplete="current-password"
230
+ type="password"
231
+ required
232
+ value={loginPassword}
233
+ onChange={(event) => setLoginPassword(event.target.value)}
234
+ />
235
+ </label>
236
+ {loginError ? <p className="error">{loginError}</p> : null}
237
+ <button className="button button-large" disabled={loginBusy} type="submit">
238
+ {loginBusy ? copy.signingIn : copy.signIn}
239
+ </button>
240
+ </form>
241
+ <Link className="text-link" href={routes.account}>{copy.accountHelp}</Link>
242
+ </section>
243
+ ) : null}
244
+
245
+ {request.products.length ? (
246
+ <div className="stack">
247
+ {request.products.map((product) => {
248
+ const draft = drafts[product.product_id] || emptyDraft()
249
+ const reviewed = product.reviewed
250
+ return (
251
+ <section className="panel stack" key={product.product_id}>
252
+ <div className="section-title-row">
253
+ <div>
254
+ <p className="eyebrow">{copy.productEyebrow}</p>
255
+ <h2>{product.title}</h2>
256
+ </div>
257
+ {reviewed ? <span className="status-pill success-pill">{copy.reviewed}</span> : null}
258
+ </div>
259
+
260
+ {product.handle ? (
261
+ <Link className="text-link" href={productPath(locale, product.handle)}>{copy.viewProduct}</Link>
262
+ ) : null}
263
+
264
+ {reviewed ? (
265
+ <div className="empty-state">
266
+ {draft.submittedStatus === "published" ? copy.publishedSuccess : draft.submittedStatus === "pending" ? copy.pendingSuccess : copy.alreadyReviewed}
267
+ </div>
268
+ ) : (
269
+ <form className="stack-sm review-form" onSubmit={(event) => void submit(product, event)}>
270
+ <fieldset disabled={draft.busy || authenticated !== true} className="stack-sm">
271
+ <legend className="field-label">{copy.rating}</legend>
272
+ <div className="button-row" role="radiogroup" aria-label={copy.rating}>
273
+ {[1, 2, 3, 4, 5].map((value) => (
274
+ <button
275
+ className="button secondary"
276
+ aria-checked={draft.rating === value}
277
+ role="radio"
278
+ type="button"
279
+ key={value}
280
+ onClick={() => setDraft(product.product_id, { rating: value })}
281
+ >
282
+ {draft.rating >= value ? "★" : "☆"}
283
+ </button>
284
+ ))}
285
+ </div>
286
+ </fieldset>
287
+ <label>
288
+ {copy.reviewBody}
289
+ <textarea
290
+ rows={5}
291
+ maxLength={5000}
292
+ required
293
+ disabled={draft.busy || authenticated !== true}
294
+ value={draft.body}
295
+ onChange={(event) => setDraft(product.product_id, { body: event.target.value })}
296
+ placeholder={copy.placeholder}
297
+ />
298
+ </label>
299
+ {authenticated !== true ? <p className="muted small">{copy.loginRequired}</p> : null}
300
+ {draft.error ? <p className="error">{draft.error}</p> : null}
301
+ <button
302
+ className="button"
303
+ type="submit"
304
+ disabled={draft.busy || authenticated !== true || !draft.body.trim()}
305
+ >
306
+ {draft.busy ? copy.submitting : copy.submit}
307
+ </button>
308
+ </form>
309
+ )}
310
+ </section>
311
+ )
312
+ })}
313
+ </div>
314
+ ) : (
315
+ <div className="empty-state">{copy.noProducts}</div>
316
+ )}
317
+ </div>
318
+ )
319
+ }
320
+
321
+ function emptyDraft(): Draft {
322
+ return {
323
+ rating: 5,
324
+ body: "",
325
+ busy: false,
326
+ error: null,
327
+ submittedStatus: null,
328
+ }
329
+ }
330
+
331
+ function reviewRequestError(cause: unknown, locale: StorefrontLocale) {
332
+ if (cause instanceof CoreApiError) {
333
+ if (cause.status === 400) return locale === "en" ? "This review link is invalid or has expired." : "Ez az értékelési link érvénytelen vagy lejárt."
334
+ if (cause.status === 404) return locale === "en" ? "The order linked to this review request could not be found." : "Az értékelési linkhez tartozó rendelés nem található."
335
+ }
336
+ return cause instanceof Error
337
+ ? cause.message
338
+ : locale === "en"
339
+ ? "The review request could not be loaded."
340
+ : "Az értékelési kérés betöltése nem sikerült."
341
+ }
342
+
343
+ function reviewCopy(locale: StorefrontLocale) {
344
+ if (locale === "en") {
345
+ return {
346
+ eyebrow: "Product reviews",
347
+ title: "Tell us what you think",
348
+ checking: "Checking review link…",
349
+ missingToken: "The review token is missing. Open the full link from the email you received.",
350
+ invalidTitle: "Review link unavailable",
351
+ invalidText: "This review link cannot be used.",
352
+ backHome: "Back to store",
353
+ orderLabel: "Order",
354
+ remaining: "{count} product(s) left to review",
355
+ complete: "all products reviewed",
356
+ rewardHint: "If review rewards are enabled, the reward is issued after the review is published and may arrive by email.",
357
+ signInEyebrow: "Verification",
358
+ signInTitle: "Sign in to submit your review",
359
+ signInText: "The signed review link identifies the order, and signing in confirms that you are the customer who placed it.",
360
+ email: "Email",
361
+ password: "Password",
362
+ signingIn: "Signing in…",
363
+ signIn: "Sign in",
364
+ loginFailed: "Sign in failed.",
365
+ accountHelp: "Account and password help",
366
+ productEyebrow: "Purchased product",
367
+ reviewed: "Reviewed",
368
+ viewProduct: "View product",
369
+ rating: "Rating",
370
+ reviewBody: "Your review",
371
+ placeholder: "Share your experience with this product.",
372
+ loginRequired: "Sign in with the account that placed this order to submit a review.",
373
+ submitting: "Submitting…",
374
+ submit: "Submit review",
375
+ submitFailed: "The review could not be submitted.",
376
+ publishedSuccess: "Thank you! Your review has been published.",
377
+ pendingSuccess: "Thank you! Your review was submitted for moderation.",
378
+ alreadyReviewed: "You have already reviewed this product.",
379
+ noProducts: "There are no reviewable products in this order.",
380
+ }
381
+ }
382
+
383
+ return {
384
+ eyebrow: "Termékértékelés",
385
+ title: "Írd meg a véleményed",
386
+ checking: "Értékelési link ellenőrzése…",
387
+ missingToken: "Hiányzik az értékelési token. Nyisd meg újra az e-mailben kapott teljes hivatkozást.",
388
+ invalidTitle: "Az értékelési link nem használható",
389
+ invalidText: "Ez az értékelési link nem használható.",
390
+ backHome: "Vissza a webshopba",
391
+ orderLabel: "Rendelés",
392
+ remaining: "Még {count} termék vár értékelésre",
393
+ complete: "minden terméket értékeltél",
394
+ rewardHint: "Ha a webshopban aktív az értékelési jutalom, a kedvezmény a vélemény publikálása után jár, és e-mailben is megérkezhet.",
395
+ signInEyebrow: "Azonosítás",
396
+ signInTitle: "Jelentkezz be az értékeléshez",
397
+ signInText: "Az aláírt értékelési link azonosítja a rendelést, a bejelentkezés pedig megerősíti, hogy te vagy a vásárló.",
398
+ email: "E-mail",
399
+ password: "Jelszó",
400
+ signingIn: "Bejelentkezés…",
401
+ signIn: "Bejelentkezés",
402
+ loginFailed: "A bejelentkezés nem sikerült.",
403
+ accountHelp: "Fiók- és jelszókezelés",
404
+ productEyebrow: "Megvásárolt termék",
405
+ reviewed: "Értékelve",
406
+ viewProduct: "Termék megtekintése",
407
+ rating: "Értékelés",
408
+ reviewBody: "Véleményed",
409
+ placeholder: "Írd le a tapasztalatodat a termékről.",
410
+ loginRequired: "Az értékelés elküldéséhez jelentkezz be azzal a fiókkal, amellyel a rendelést leadtad.",
411
+ submitting: "Küldés…",
412
+ submit: "Vélemény elküldése",
413
+ submitFailed: "A véleményt nem sikerült elküldeni.",
414
+ publishedSuccess: "Köszönjük! A véleményed megjelent.",
415
+ pendingSuccess: "Köszönjük! A véleményed moderálásra elküldtük.",
416
+ alreadyReviewed: "Ezt a terméket már értékelted.",
417
+ noProducts: "Ebben a rendelésben nincs értékelhető termék.",
418
+ }
419
+ }
@@ -0,0 +1,257 @@
1
+ "use client"
2
+
3
+ import { useEffect, useMemo, useState } from "react"
4
+ import { usePathname, useRouter } from "next/navigation"
5
+ import { useCart } from "./cart-provider"
6
+ import { useToast } from "./toast-provider"
7
+ import { getProductById } from "@/lib/core/catalog"
8
+ import { checkoutApi } from "@/lib/core/checkout"
9
+ import {
10
+ asRecords,
11
+ cartItems,
12
+ formatMoney,
13
+ numberValue,
14
+ productVariantCurrency,
15
+ productVariantPrice,
16
+ stringValue,
17
+ type JsonRecord,
18
+ } from "@/lib/core/commerce"
19
+ import { getSharedCart, type SharedCartPayload } from "@/lib/core/shared-cart"
20
+ import type { CoreConfig } from "@/lib/core/types"
21
+ import { localeFromPathname, STOREFRONT_ROUTES } from "@/lib/storefront-routes"
22
+
23
+ type PreviewItem = {
24
+ productId: string | null
25
+ variantId: string
26
+ quantity: number
27
+ productTitle: string
28
+ variantTitle: string
29
+ thumbnail: string
30
+ sku: string
31
+ price: number
32
+ currency: string
33
+ available: boolean
34
+ availability: number | null
35
+ manageInventory: boolean
36
+ allowBackorder: boolean
37
+ }
38
+
39
+ export function SharedCartView({ token, config }: { token: string; config: CoreConfig }) {
40
+ const api = useMemo(() => checkoutApi(config), [config])
41
+ const { cart, cartId, adoptCart, refresh } = useCart()
42
+ const { showToast } = useToast()
43
+ const router = useRouter()
44
+ const pathname = usePathname()
45
+ const locale = localeFromPathname(pathname)
46
+ const routes = STOREFRONT_ROUTES[locale]
47
+ const [shared, setShared] = useState<SharedCartPayload | null>(null)
48
+ const [preview, setPreview] = useState<PreviewItem[]>([])
49
+ const [loading, setLoading] = useState(true)
50
+ const [applying, setApplying] = useState(false)
51
+ const [error, setError] = useState<string | null>(null)
52
+
53
+ useEffect(() => {
54
+ let cancelled = false
55
+ setLoading(true)
56
+ setError(null)
57
+
58
+ void getSharedCart(token)
59
+ .then(async ({ shared_cart }) => {
60
+ const productIds = [...new Set(
61
+ shared_cart.items
62
+ .map((item) => item.product_id)
63
+ .filter((id): id is string => Boolean(id)),
64
+ )]
65
+ const productResults = await Promise.all(
66
+ productIds.map(async (id) => {
67
+ try {
68
+ const result = await getProductById(id, shared_cart.region_id || undefined)
69
+ return [id, result.product] as const
70
+ } catch {
71
+ return [id, null] as const
72
+ }
73
+ }),
74
+ )
75
+ const products = new Map<string, JsonRecord | null>(productResults)
76
+ const rows = shared_cart.items.map((item) =>
77
+ buildPreviewItem(
78
+ item,
79
+ products.get(item.product_id || "") || null,
80
+ shared_cart.currency_code || config.store.default_currency,
81
+ ),
82
+ )
83
+ if (!cancelled) {
84
+ setShared(shared_cart)
85
+ setPreview(rows)
86
+ }
87
+ })
88
+ .catch((cause) => {
89
+ if (!cancelled) setError(cause instanceof Error ? cause.message : "A megosztott kosár nem tölthető be.")
90
+ })
91
+ .finally(() => {
92
+ if (!cancelled) setLoading(false)
93
+ })
94
+
95
+ return () => { cancelled = true }
96
+ }, [config.store.default_currency, token])
97
+
98
+ const existingItems = cartItems(cart)
99
+ const hasExistingCart = existingItems.length > 0
100
+ const availableItems = preview.filter((item) => item.available)
101
+
102
+ const apply = async (mode: "merge" | "replace") => {
103
+ if (!shared || !availableItems.length) return
104
+ setApplying(true)
105
+ try {
106
+ let targetCartId = mode === "merge" ? cartId : null
107
+ let currentLines = mode === "merge" ? cartItems(cart) : []
108
+
109
+ if (!targetCartId) {
110
+ const created = await api.createCart({
111
+ ...(shared.region_id ? { region_id: shared.region_id } : {}),
112
+ })
113
+ targetCartId = stringValue(created.cart.id)
114
+ currentLines = []
115
+ if (!targetCartId) throw new Error("Nem sikerült új kosarat létrehozni.")
116
+ }
117
+
118
+ const lineByVariant = new Map(
119
+ currentLines
120
+ .map((line) => [stringValue(line.variant_id), line] as const)
121
+ .filter(([variantId]) => Boolean(variantId)),
122
+ )
123
+
124
+ if (mode === "merge") {
125
+ for (const item of availableItems) {
126
+ const existing = lineByVariant.get(item.variantId)
127
+ const nextQuantity = numberValue(existing?.quantity, 0) + item.quantity
128
+ if (
129
+ item.manageInventory &&
130
+ !item.allowBackorder &&
131
+ item.availability != null &&
132
+ nextQuantity > item.availability
133
+ ) {
134
+ throw new Error(
135
+ `${item.productTitle}: az egyesített mennyiség (${nextQuantity}) meghaladja az aktuális készletet (${item.availability}).`,
136
+ )
137
+ }
138
+ }
139
+ }
140
+
141
+ for (const item of availableItems) {
142
+ const existing = lineByVariant.get(item.variantId)
143
+ if (mode === "merge" && existing) {
144
+ const lineId = stringValue(existing.id)
145
+ const nextQuantity = numberValue(existing.quantity, 0) + item.quantity
146
+ await api.updateLineItem(targetCartId, lineId, nextQuantity)
147
+ existing.quantity = nextQuantity
148
+ } else {
149
+ const result = await api.addLineItem(targetCartId, item.variantId, item.quantity)
150
+ const added = cartItems(result.cart).find((line) => stringValue(line.variant_id) === item.variantId)
151
+ if (added) lineByVariant.set(item.variantId, added)
152
+ }
153
+ }
154
+
155
+ if (mode === "replace" || targetCartId !== cartId) await adoptCart(targetCartId)
156
+ else await refresh(targetCartId)
157
+
158
+ const skipped = preview.length - availableItems.length
159
+ showToast({
160
+ message: skipped
161
+ ? `A kosár betöltve. ${skipped} jelenleg nem elérhető tételt kihagytunk.`
162
+ : "A megosztott kosár betöltve.",
163
+ tone: skipped ? "info" : "success",
164
+ })
165
+ router.push(routes.cart)
166
+ } catch (cause) {
167
+ showToast({
168
+ message: cause instanceof Error ? cause.message : "A kosár betöltése nem sikerült.",
169
+ tone: "error",
170
+ })
171
+ } finally {
172
+ setApplying(false)
173
+ }
174
+ }
175
+
176
+ if (loading) return <div className="empty-state" role="status">Megosztott kosár betöltése…</div>
177
+ if (error || !shared) return <div className="empty-state"><strong>{error || "A megosztott kosár nem található."}</strong></div>
178
+
179
+ return (
180
+ <div className="stack">
181
+ <div className="stack-sm">
182
+ <strong>Megosztott kosár</strong>
183
+ <span className="muted">Az árak és a készlet most, a megnyitás pillanatában kerültek lekérésre.</span>
184
+ <span className="muted">A link lejárata: {new Date(shared.expires_at).toLocaleString("hu-HU")}</span>
185
+ </div>
186
+
187
+ <div className="cart-lines">
188
+ {preview.map((item) => (
189
+ <div className="cart-line" key={item.variantId}>
190
+ <div className="cart-line-image">
191
+ {item.thumbnail ? <img src={item.thumbnail} alt={item.productTitle} loading="lazy" /> : <span className="media-placeholder" aria-hidden="true" />}
192
+ </div>
193
+ <div className="cart-line-copy">
194
+ <strong>{item.productTitle}</strong>
195
+ {item.variantTitle ? <span className="muted">{item.variantTitle}</span> : null}
196
+ {item.sku ? <span className="muted">SKU: {item.sku}</span> : null}
197
+ <span>{item.quantity} × {Number.isFinite(item.price) ? formatMoney(item.price, item.currency, "hu-HU") : "Aktuális ár nem érhető el"}</span>
198
+ <span className={item.available ? "muted" : "error"}>
199
+ {item.available ? "Elérhető" : "Jelenleg nem elérhető"}
200
+ {item.manageInventory && item.availability != null ? ` · készlet: ${item.availability}` : ""}
201
+ </span>
202
+ </div>
203
+ </div>
204
+ ))}
205
+ </div>
206
+
207
+ {!availableItems.length ? <p className="error">A megosztott kosár egyik tétele sem rendelhető jelenleg.</p> : null}
208
+
209
+ <div className="button-row">
210
+ {hasExistingCart ? (
211
+ <>
212
+ <button className="button" type="button" disabled={applying || !availableItems.length} onClick={() => void apply("merge")}>Kosarak egyesítése</button>
213
+ <button className="button secondary" type="button" disabled={applying || !availableItems.length} onClick={() => void apply("replace")}>Saját kosár lecserélése</button>
214
+ </>
215
+ ) : (
216
+ <button className="button" type="button" disabled={applying || !availableItems.length} onClick={() => void apply("replace")}>Kosár betöltése</button>
217
+ )}
218
+ <button className="button secondary" type="button" disabled={applying} onClick={() => router.push(routes.cart)}>Elvetés</button>
219
+ </div>
220
+ </div>
221
+ )
222
+ }
223
+
224
+ function buildPreviewItem(
225
+ item: SharedCartPayload["items"][number],
226
+ product: JsonRecord | null,
227
+ fallbackCurrency: string,
228
+ ): PreviewItem {
229
+ const variants = asRecords(product?.variants)
230
+ const variant = variants.find((candidate) => stringValue(candidate.id) === item.variant_id) || null
231
+ const manageInventory = variant?.manage_inventory === true
232
+ const allowBackorder = variant?.allow_backorder === true
233
+ const availability = typeof item.availability === "number" && Number.isFinite(item.availability)
234
+ ? item.availability
235
+ : null
236
+ const available = Boolean(
237
+ variant && (!manageInventory || allowBackorder || availability == null || availability >= item.quantity),
238
+ )
239
+ const images = asRecords(product?.images)
240
+ const thumbnail = stringValue(product?.thumbnail || images[0]?.url)
241
+
242
+ return {
243
+ productId: item.product_id,
244
+ variantId: item.variant_id,
245
+ quantity: item.quantity,
246
+ productTitle: stringValue(product?.title) || "Ismeretlen termék",
247
+ variantTitle: stringValue(variant?.title),
248
+ thumbnail,
249
+ sku: stringValue(variant?.sku),
250
+ price: productVariantPrice(variant),
251
+ currency: productVariantCurrency(variant, fallbackCurrency),
252
+ available,
253
+ availability,
254
+ manageInventory,
255
+ allowBackorder,
256
+ }
257
+ }