@hszrdm/create-commerce 0.0.0-stage → 1.0.1

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 (68) hide show
  1. package/README.md +50 -2
  2. package/bin/create-commerce.mjs +51 -0
  3. package/package.json +23 -4
  4. package/src/cli.mjs +585 -0
  5. package/templates/backend/.env.example +113 -0
  6. package/templates/backend/README.md +7 -0
  7. package/templates/backend/instrumentation.ts +24 -0
  8. package/templates/backend/medusa-config.ts +11 -0
  9. package/templates/backend/package.json +42 -0
  10. package/templates/backend/scripts/prepare-project.mjs +49 -0
  11. package/templates/backend/src/project/README.md +13 -0
  12. package/templates/backend/src/project/api/.gitkeep +0 -0
  13. package/templates/backend/src/project/jobs/.gitkeep +0 -0
  14. package/templates/backend/src/project/modules/.gitkeep +0 -0
  15. package/templates/backend/src/project/subscribers/.gitkeep +0 -0
  16. package/templates/backend/src/project/workflows/.gitkeep +0 -0
  17. package/templates/backend/src/scripts/core-init.ts +21 -0
  18. package/templates/backend/src/scripts/create-storefront-key.ts +12 -0
  19. package/templates/backend/src/scripts/verify-bootstrap.ts +1 -0
  20. package/templates/backend/tsconfig.json +33 -0
  21. package/templates/storefront/.env.example +5 -0
  22. package/templates/storefront/README.md +108 -0
  23. package/templates/storefront/next-env.d.ts +4 -0
  24. package/templates/storefront/next.config.ts +8 -0
  25. package/templates/storefront/package.json +24 -0
  26. package/templates/storefront/src/app/[countryCode]/categories/[handle]/page.tsx +38 -0
  27. package/templates/storefront/src/app/[countryCode]/products/[handle]/page.tsx +51 -0
  28. package/templates/storefront/src/app/[countryCode]/products/page.tsx +47 -0
  29. package/templates/storefront/src/app/account/orders/[id]/page.tsx +8 -0
  30. package/templates/storefront/src/app/account/page.tsx +11 -0
  31. package/templates/storefront/src/app/cart/page.tsx +12 -0
  32. package/templates/storefront/src/app/checkout/page.tsx +15 -0
  33. package/templates/storefront/src/app/checkout/success/page.tsx +72 -0
  34. package/templates/storefront/src/app/error.tsx +14 -0
  35. package/templates/storefront/src/app/globals.css +250 -0
  36. package/templates/storefront/src/app/layout.tsx +59 -0
  37. package/templates/storefront/src/app/legal/page.tsx +26 -0
  38. package/templates/storefront/src/app/loading.tsx +3 -0
  39. package/templates/storefront/src/app/not-found.tsx +14 -0
  40. package/templates/storefront/src/app/page.tsx +47 -0
  41. package/templates/storefront/src/app/reset-password/page.tsx +14 -0
  42. package/templates/storefront/src/app/robots.txt/route.ts +13 -0
  43. package/templates/storefront/src/app/sitemap.xml/route.ts +13 -0
  44. package/templates/storefront/src/components/account-dashboard.tsx +325 -0
  45. package/templates/storefront/src/components/add-to-cart.tsx +71 -0
  46. package/templates/storefront/src/components/analytics.tsx +90 -0
  47. package/templates/storefront/src/components/cart-provider.tsx +236 -0
  48. package/templates/storefront/src/components/cart-view.tsx +135 -0
  49. package/templates/storefront/src/components/checkout-flow.tsx +534 -0
  50. package/templates/storefront/src/components/consent-banner.tsx +131 -0
  51. package/templates/storefront/src/components/order-detail.tsx +273 -0
  52. package/templates/storefront/src/components/product-card.tsx +38 -0
  53. package/templates/storefront/src/components/product-view-tracker.tsx +37 -0
  54. package/templates/storefront/src/components/reset-password-form.tsx +65 -0
  55. package/templates/storefront/src/components/storefront-header.tsx +42 -0
  56. package/templates/storefront/src/components/stripe-payment.tsx +90 -0
  57. package/templates/storefront/src/lib/core/account.ts +170 -0
  58. package/templates/storefront/src/lib/core/after-sales.ts +50 -0
  59. package/templates/storefront/src/lib/core/catalog.ts +56 -0
  60. package/templates/storefront/src/lib/core/checkout.ts +330 -0
  61. package/templates/storefront/src/lib/core/client.ts +107 -0
  62. package/templates/storefront/src/lib/core/commerce.ts +148 -0
  63. package/templates/storefront/src/lib/core/consent.ts +111 -0
  64. package/templates/storefront/src/lib/core/legal.ts +33 -0
  65. package/templates/storefront/src/lib/core/seo.ts +88 -0
  66. package/templates/storefront/src/lib/core/tracking.ts +584 -0
  67. package/templates/storefront/src/lib/core/types.ts +123 -0
  68. package/templates/storefront/tsconfig.json +23 -0
@@ -0,0 +1,534 @@
1
+ "use client"
2
+
3
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react"
4
+ import { useRouter, useSearchParams } from "next/navigation"
5
+ import { useCart } from "./cart-provider"
6
+ import { StripePayment } from "./stripe-payment"
7
+ import { checkoutApi } from "@/lib/core/checkout"
8
+ import {
9
+ activePaymentSession,
10
+ asRecords,
11
+ cartCurrency,
12
+ cartPaymentCollection,
13
+ cartRegionId,
14
+ cartTotal,
15
+ formatMoney,
16
+ isRecord,
17
+ paymentClientSecret,
18
+ providerId,
19
+ providerLabel,
20
+ shippingMethodIsCod,
21
+ simplePayUrl,
22
+ stringValue,
23
+ type JsonRecord,
24
+ } from "@/lib/core/commerce"
25
+ import { acceptLegalDocument, listLegalDocuments } from "@/lib/core/legal"
26
+ import type { CoreConfig, LegalDocument } from "@/lib/core/types"
27
+
28
+ type AddressState = {
29
+ email: string
30
+ first_name: string
31
+ last_name: string
32
+ company: string
33
+ phone: string
34
+ country_code: string
35
+ postal_code: string
36
+ city: string
37
+ province: string
38
+ address_1: string
39
+ address_2: string
40
+ }
41
+
42
+ type PickupKind = "foxpost" | "gls" | "dpd" | "mpl" | "packeta" | null
43
+
44
+ export function CheckoutFlow({ config }: { config: CoreConfig }) {
45
+ const api = useMemo(() => checkoutApi(config), [config])
46
+ const router = useRouter()
47
+ const search = useSearchParams()
48
+ const {
49
+ cart,
50
+ cartId,
51
+ loading,
52
+ mutating,
53
+ error: cartError,
54
+ adoptCart,
55
+ refresh,
56
+ clearCart,
57
+ } = useCart()
58
+ const hydratedAddress = useRef(false)
59
+ const returnAttempted = useRef(false)
60
+
61
+ const [address, setAddress] = useState<AddressState>(() => emptyAddress(config.store.default_country))
62
+ const [shippingOptions, setShippingOptions] = useState<JsonRecord[]>([])
63
+ const [selectedShipping, setSelectedShipping] = useState<JsonRecord | null>(null)
64
+ const [pickupPoints, setPickupPoints] = useState<JsonRecord[]>([])
65
+ const [selectedPickupKey, setSelectedPickupKey] = useState("")
66
+ const [pickupSearch, setPickupSearch] = useState("")
67
+ const [packetaPointId, setPacketaPointId] = useState("")
68
+ const [packetaPointName, setPacketaPointName] = useState("")
69
+ const [providers, setProviders] = useState<JsonRecord[]>([])
70
+ const [selectedProvider, setSelectedProvider] = useState("")
71
+ const [preparedCart, setPreparedCart] = useState<JsonRecord | null>(null)
72
+ const [legalDocs, setLegalDocs] = useState<LegalDocument[]>([])
73
+ const [accepted, setAccepted] = useState<Record<string, boolean>>({})
74
+ const [busy, setBusy] = useState<string | null>(null)
75
+ const [error, setError] = useState<string | null>(null)
76
+ const [message, setMessage] = useState<string | null>(null)
77
+
78
+ const returnCartId = search.get("cart_id")
79
+ const stripeReturn = search.get("stripe_return")
80
+ const simplePayReturn = search.get("simplepay_return")
81
+
82
+ useEffect(() => {
83
+ if (returnCartId && returnCartId !== cartId) {
84
+ void adoptCart(returnCartId).catch((cause) =>
85
+ setError(cause instanceof Error ? cause.message : "A visszatérő kosár nem tölthető be."),
86
+ )
87
+ }
88
+ }, [adoptCart, cartId, returnCartId])
89
+
90
+ useEffect(() => {
91
+ void listLegalDocuments(config)
92
+ .then((result) => setLegalDocs(result.documents))
93
+ .catch(() => setLegalDocs([]))
94
+ }, [config])
95
+
96
+ useEffect(() => {
97
+ if (!cart || hydratedAddress.current) return
98
+ const shipping = isRecord(cart.shipping_address) ? cart.shipping_address : {}
99
+ setAddress({
100
+ email: stringValue(cart.email),
101
+ first_name: stringValue(shipping.first_name),
102
+ last_name: stringValue(shipping.last_name),
103
+ company: stringValue(shipping.company),
104
+ phone: stringValue(shipping.phone),
105
+ country_code: stringValue(shipping.country_code || config.store.default_country).toUpperCase(),
106
+ postal_code: stringValue(shipping.postal_code),
107
+ city: stringValue(shipping.city),
108
+ province: stringValue(shipping.province),
109
+ address_1: stringValue(shipping.address_1),
110
+ address_2: stringValue(shipping.address_2),
111
+ })
112
+ hydratedAddress.current = true
113
+ }, [cart, config.store.default_country])
114
+
115
+ const loadShippingOptions = useCallback(async () => {
116
+ if (!cartId) return
117
+ const result = await api.shippingOptions(cartId)
118
+ setShippingOptions(result.shipping_options)
119
+ }, [api, cartId])
120
+
121
+ const loadProviders = useCallback(
122
+ async (sourceCart?: JsonRecord | null) => {
123
+ const target = sourceCart || cart
124
+ const regionId = cartRegionId(target)
125
+ if (!regionId) return
126
+ const result = await api.paymentProviders(regionId)
127
+ setProviders(result.payment_providers)
128
+ },
129
+ [api, cart],
130
+ )
131
+
132
+ useEffect(() => {
133
+ if (!cartId || !cart) return
134
+ if (isRecord(cart.shipping_address) && stringValue(cart.shipping_address.postal_code)) {
135
+ void loadShippingOptions().catch(() => undefined)
136
+ }
137
+ if (asRecords(cart.shipping_methods).length) {
138
+ void loadProviders(cart).catch(() => undefined)
139
+ }
140
+ }, [cart, cartId, loadProviders, loadShippingOptions])
141
+
142
+ const requiredLegal = legalDocs.filter(
143
+ (doc) => doc.requiredAtCheckout === true || doc.required_at_checkout === true,
144
+ )
145
+ const legalReady = requiredLegal.every((doc) => accepted[doc.key] === true)
146
+
147
+ const acceptRequiredLegal = useCallback(async () => {
148
+ if (!cartId) throw new Error("Nincs aktív kosár.")
149
+ const missing = requiredLegal.filter((doc) => !accepted[doc.key])
150
+ if (missing.length) throw new Error("A rendeléshez el kell fogadnod a kötelező jogi nyilatkozatokat.")
151
+ await Promise.all(requiredLegal.map((doc) => acceptLegalDocument(config, doc.key, { cartId })))
152
+ }, [accepted, cartId, config, requiredLegal])
153
+
154
+ const completeOrder = useCallback(async () => {
155
+ if (!cartId) throw new Error("Nincs aktív kosár.")
156
+ setBusy("complete")
157
+ setError(null)
158
+ try {
159
+ const result = await api.complete(cartId)
160
+ if (result.type === "order" && isRecord(result.order)) {
161
+ const orderId = stringValue(result.order.id)
162
+ if (!orderId) throw new Error("A rendelés létrejött, de hiányzik az order ID.")
163
+ clearCart()
164
+ router.push(`/checkout/success?order_id=${encodeURIComponent(orderId)}`)
165
+ return
166
+ }
167
+ const detail = isRecord(result.cart) ? stringValue(result.cart.error || result.cart.message) : ""
168
+ throw new Error(detail || "A rendelés még nem zárható le. Ellenőrizd a fizetés állapotát.")
169
+ } finally {
170
+ setBusy(null)
171
+ }
172
+ }, [api, cartId, clearCart, router])
173
+
174
+ useEffect(() => {
175
+ if (returnAttempted.current || !cartId || !cart || (!stripeReturn && !simplePayReturn)) return
176
+ returnAttempted.current = true
177
+ setMessage(simplePayReturn
178
+ ? `SimplePay visszatérés: ${simplePayReturn}. A rendelés státuszának ellenőrzése folyamatban.`
179
+ : "A bankkártyás fizetés után visszatértél. A rendelés lezárása folyamatban.")
180
+ void completeOrder().catch((cause) => {
181
+ setError(cause instanceof Error ? cause.message : "A rendelés még nem zárható le.")
182
+ })
183
+ }, [cart, cartId, completeOrder, simplePayReturn, stripeReturn])
184
+
185
+ const saveAddress = async () => {
186
+ if (!cartId) throw new Error("A kosár még nem áll készen.")
187
+ validateAddress(address)
188
+ setBusy("address")
189
+ setError(null)
190
+ try {
191
+ const shippingAddress = {
192
+ first_name: address.first_name,
193
+ last_name: address.last_name,
194
+ company: address.company || undefined,
195
+ phone: address.phone,
196
+ country_code: address.country_code.toLowerCase(),
197
+ postal_code: address.postal_code,
198
+ city: address.city,
199
+ province: address.province || undefined,
200
+ address_1: address.address_1,
201
+ address_2: address.address_2 || undefined,
202
+ }
203
+ await api.updateCart(cartId, {
204
+ email: address.email,
205
+ shipping_address: shippingAddress,
206
+ billing_address: shippingAddress,
207
+ })
208
+ await refresh(cartId)
209
+ await loadShippingOptions()
210
+ setMessage("Kapcsolati és szállítási adatok mentve.")
211
+ } catch (cause) {
212
+ setError(cause instanceof Error ? cause.message : "A cím mentése nem sikerült.")
213
+ } finally {
214
+ setBusy(null)
215
+ }
216
+ }
217
+
218
+ const selectShippingOption = async (option: JsonRecord) => {
219
+ setSelectedShipping(option)
220
+ setSelectedPickupKey("")
221
+ setPickupPoints([])
222
+ setPickupSearch("")
223
+ const kind = pickupKind(option)
224
+ if (!kind || kind === "packeta") return
225
+ setBusy("pickup")
226
+ setError(null)
227
+ try {
228
+ if (kind === "foxpost") setPickupPoints((await api.foxpostLockers()).lockers)
229
+ if (kind === "gls") setPickupPoints((await api.glsDeliveryPoints()).deliveryPoints)
230
+ if (kind === "dpd") {
231
+ setPickupPoints((await api.dpdPickupPoints({
232
+ country: address.country_code,
233
+ postalCode: address.postal_code,
234
+ city: address.city,
235
+ limit: "100",
236
+ })).pickupPoints)
237
+ }
238
+ if (kind === "mpl") {
239
+ setPickupPoints((await api.mplDeliveryPlaces({
240
+ postCode: address.postal_code,
241
+ city: address.city,
242
+ })).deliveryPlaces)
243
+ }
244
+ } catch (cause) {
245
+ setError(cause instanceof Error ? cause.message : "A csomagpontok nem tölthetők be.")
246
+ } finally {
247
+ setBusy(null)
248
+ }
249
+ }
250
+
251
+ const saveShipping = async () => {
252
+ if (!cartId || !selectedShipping) throw new Error("Válassz szállítási módot.")
253
+ const optionId = stringValue(selectedShipping.id)
254
+ const kind = pickupKind(selectedShipping)
255
+ const selectedPoint = pickupPoints.find((point) => pickupKey(point) === selectedPickupKey) || null
256
+ const data = shippingData(kind, selectedPoint, packetaPointId, packetaPointName)
257
+ setBusy("shipping")
258
+ setError(null)
259
+ try {
260
+ const result = await api.addShippingMethod(cartId, optionId, data)
261
+ await refresh(cartId)
262
+ await loadProviders(result.cart)
263
+ setMessage("Szállítási mód kiválasztva.")
264
+ } catch (cause) {
265
+ setError(cause instanceof Error ? cause.message : "A szállítási mód nem menthető.")
266
+ } finally {
267
+ setBusy(null)
268
+ }
269
+ }
270
+
271
+ const preparePayment = async (id: string) => {
272
+ if (!cartId) throw new Error("Nincs aktív kosár.")
273
+ setBusy("payment")
274
+ setError(null)
275
+ setSelectedProvider(id)
276
+ try {
277
+ let current = (await api.getCart(cartId)).cart
278
+ let collection = cartPaymentCollection(current)
279
+ let collectionId = stringValue(collection?.id)
280
+ if (!collectionId) {
281
+ const created = await api.createPaymentCollection(cartId)
282
+ collectionId = stringValue(created.payment_collection.id)
283
+ if (!collectionId) throw new Error("A payment collection nem jött létre.")
284
+ }
285
+ const selected = await api.selectPayment(cartId, collectionId, id)
286
+ current = selected.cart
287
+ setPreparedCart(current)
288
+ await refresh(cartId)
289
+ setMessage("Fizetési mód előkészítve.")
290
+ } catch (cause) {
291
+ setPreparedCart(null)
292
+ setError(cause instanceof Error ? cause.message : "A fizetési mód nem készíthető elő.")
293
+ } finally {
294
+ setBusy(null)
295
+ }
296
+ }
297
+
298
+ if (loading) return <div className="empty-state">Pénztár betöltése…</div>
299
+ if (!cart || !cartId) {
300
+ return <div className="empty-state">A pénztárhoz előbb tegyél terméket a kosárba.</div>
301
+ }
302
+
303
+ const pickup = selectedShipping ? pickupKind(selectedShipping) : null
304
+ const filteredPoints = pickupSearch.trim()
305
+ ? pickupPoints.filter((point) => pointLabel(point).toLowerCase().includes(pickupSearch.trim().toLowerCase())).slice(0, 200)
306
+ : pickupPoints.slice(0, 200)
307
+ const effectiveCart = preparedCart || cart
308
+ const session = activePaymentSession(effectiveCart)
309
+ const activeProviderId = providerId(session) || selectedProvider
310
+ const stripeSecret = paymentClientSecret(effectiveCart)
311
+ const simplePayRedirect = simplePayUrl(effectiveCart)
312
+ const stripeSelected = activeProviderId.toLowerCase().includes("stripe")
313
+ const simplePaySelected = activeProviderId.toLowerCase().includes("simplepay")
314
+ const systemSelected = activeProviderId.toLowerCase().includes("system")
315
+ const currency = cartCurrency(cart, config.store.default_currency)
316
+
317
+ return (
318
+ <div className="checkout-layout">
319
+ <div className="stack">
320
+ <section className="panel stack">
321
+ <SectionTitle step="1" title="Kapcsolat és szállítási cím" />
322
+ <div className="form-grid two-col">
323
+ <Field label="E-mail" value={address.email} type="email" onChange={(value) => updateAddress(setAddress, "email", value)} />
324
+ <Field label="Telefon" value={address.phone} onChange={(value) => updateAddress(setAddress, "phone", value)} />
325
+ <Field label="Keresztnév" value={address.first_name} onChange={(value) => updateAddress(setAddress, "first_name", value)} />
326
+ <Field label="Vezetéknév" value={address.last_name} onChange={(value) => updateAddress(setAddress, "last_name", value)} />
327
+ <Field label="Cég (opcionális)" value={address.company} onChange={(value) => updateAddress(setAddress, "company", value)} />
328
+ <Field label="Ország" value={address.country_code} onChange={(value) => updateAddress(setAddress, "country_code", value.toUpperCase())} />
329
+ <Field label="Irányítószám" value={address.postal_code} onChange={(value) => updateAddress(setAddress, "postal_code", value)} />
330
+ <Field label="Város" value={address.city} onChange={(value) => updateAddress(setAddress, "city", value)} />
331
+ <Field label="Utca, házszám" value={address.address_1} onChange={(value) => updateAddress(setAddress, "address_1", value)} />
332
+ <Field label="Cím kiegészítés" value={address.address_2} onChange={(value) => updateAddress(setAddress, "address_2", value)} />
333
+ </div>
334
+ <button className="button secondary" type="button" disabled={busy === "address" || mutating} onClick={() => void saveAddress()}>
335
+ {busy === "address" ? "Mentés…" : "Adatok mentése és szállítás betöltése"}
336
+ </button>
337
+ </section>
338
+
339
+ <section className="panel stack">
340
+ <SectionTitle step="2" title="Szállítás" />
341
+ {!shippingOptions.length ? <p className="muted">Mentsd el a címet az elérhető szállítási módok betöltéséhez.</p> : (
342
+ <div className="choice-list">
343
+ {shippingOptions.map((option) => {
344
+ const id = stringValue(option.id)
345
+ return (
346
+ <label className={`choice-card${stringValue(selectedShipping?.id) === id ? " selected" : ""}`} key={id}>
347
+ <input type="radio" name="shipping" checked={stringValue(selectedShipping?.id) === id} onChange={() => void selectShippingOption(option)} />
348
+ <span>
349
+ <strong>{stringValue(option.name || option.id)}</strong>
350
+ {typeof option.amount === "number" ? <small>{formatMoney(option.amount, currency, config.store.locale)}</small> : null}
351
+ </span>
352
+ </label>
353
+ )
354
+ })}
355
+ </div>
356
+ )}
357
+
358
+ {pickup && pickup !== "packeta" ? (
359
+ <div className="stack-sm">
360
+ <Field label="Csomagpont keresése" value={pickupSearch} onChange={setPickupSearch} />
361
+ <label>
362
+ Átvételi pont
363
+ <select value={selectedPickupKey} onChange={(event) => setSelectedPickupKey(event.target.value)} disabled={busy === "pickup"}>
364
+ <option value="">Válassz átvételi pontot</option>
365
+ {filteredPoints.map((point) => <option key={pickupKey(point)} value={pickupKey(point)}>{pointLabel(point)}</option>)}
366
+ </select>
367
+ </label>
368
+ {pickupPoints.length > 200 ? <p className="muted small">Írj be várost vagy címet a lista szűkítéséhez.</p> : null}
369
+ </div>
370
+ ) : null}
371
+
372
+ {pickup === "packeta" ? (
373
+ <div className="notice warning stack-sm">
374
+ <strong>Packeta pont</strong>
375
+ <span>A Core nem tesz ki titkos Packeta credentialt a böngészőbe. Add meg az official Packeta widgetből kapott pont azonosítóját; ügyfél-designnál a widget ugyanebbe a mezőbe köthető.</span>
376
+ <Field label="Packeta point ID" value={packetaPointId} onChange={setPacketaPointId} />
377
+ <Field label="Pont neve" value={packetaPointName} onChange={setPacketaPointName} />
378
+ </div>
379
+ ) : null}
380
+
381
+ {selectedShipping ? (
382
+ <button className="button secondary" type="button" disabled={busy === "shipping" || (Boolean(pickup) && pickup !== "packeta" && !selectedPickupKey) || (pickup === "packeta" && !packetaPointId.trim())} onClick={() => void saveShipping()}>
383
+ {busy === "shipping" ? "Mentés…" : "Szállítás kiválasztása"}
384
+ </button>
385
+ ) : null}
386
+ </section>
387
+
388
+ <section className="panel stack">
389
+ <SectionTitle step="3" title="Fizetés" />
390
+ {!providers.length ? <p className="muted">Válassz és ments szállítási módot a fizetési lehetőségek betöltéséhez.</p> : (
391
+ <div className="choice-list">
392
+ {providers.map((provider) => {
393
+ const id = stringValue(provider.id)
394
+ const cod = shippingMethodIsCod(cart)
395
+ return (
396
+ <button className={`choice-card choice-button${selectedProvider === id ? " selected" : ""}`} type="button" key={id} disabled={busy === "payment"} onClick={() => void preparePayment(id)}>
397
+ <strong>{providerLabel(id, cod)}</strong>
398
+ <small>{id}</small>
399
+ </button>
400
+ )
401
+ })}
402
+ </div>
403
+ )}
404
+
405
+ {stripeSelected && stripeSecret && config.payments.stripe.publishable_key ? (
406
+ <StripePayment
407
+ publishableKey={config.payments.stripe.publishable_key}
408
+ clientSecret={stripeSecret}
409
+ cartId={cartId}
410
+ disabled={!legalReady || busy === "complete"}
411
+ beforeConfirm={acceptRequiredLegal}
412
+ onConfirmed={completeOrder}
413
+ />
414
+ ) : stripeSelected ? (
415
+ <div className="notice warning">A Stripe session még nem adott használható client secretet. Próbáld újra a fizetési mód kiválasztását.</div>
416
+ ) : null}
417
+
418
+ {simplePaySelected ? (
419
+ <button
420
+ className="button button-large"
421
+ type="button"
422
+ disabled={!simplePayRedirect || !legalReady}
423
+ onClick={() => void acceptRequiredLegal().then(() => { if (simplePayRedirect) window.location.assign(simplePayRedirect) }).catch((cause) => setError(cause instanceof Error ? cause.message : "A jogi elfogadás nem rögzíthető."))}
424
+ >
425
+ Tovább az OTP SimplePayhez
426
+ </button>
427
+ ) : null}
428
+
429
+ {systemSelected ? (
430
+ <button className="button button-large" type="button" disabled={!legalReady || busy === "complete"} onClick={() => void acceptRequiredLegal().then(completeOrder).catch((cause) => setError(cause instanceof Error ? cause.message : "A rendelés nem zárható le."))}>
431
+ {busy === "complete" ? "Rendelés leadása…" : shippingMethodIsCod(cart) ? "Megrendelés utánvéttel" : "Megrendelés leadása"}
432
+ </button>
433
+ ) : null}
434
+ </section>
435
+
436
+ <section className="panel stack">
437
+ <SectionTitle step="4" title="Jogi nyilatkozatok" />
438
+ {requiredLegal.length ? requiredLegal.map((doc) => (
439
+ <label className="legal-check" key={doc.key}>
440
+ <input type="checkbox" checked={Boolean(accepted[doc.key])} onChange={(event) => setAccepted((current) => ({ ...current, [doc.key]: event.target.checked }))} />
441
+ <span>
442
+ Elfogadom: <strong>{doc.title || doc.key}</strong>
443
+ {doc.pdfEndpoint ? <a href={doc.pdfEndpoint} target="_blank" rel="noreferrer"> Dokumentum megnyitása</a> : null}
444
+ </span>
445
+ </label>
446
+ )) : <p className="muted">Nincs kötelező checkout dokumentum.</p>}
447
+ </section>
448
+
449
+ {message ? <div className="notice success-box">{message}</div> : null}
450
+ {error || cartError ? <div className="notice error-box">{error || cartError}</div> : null}
451
+ {(stripeReturn || simplePayReturn) && error ? (
452
+ <button className="button secondary" type="button" disabled={busy === "complete"} onClick={() => void completeOrder().catch((cause) => setError(cause instanceof Error ? cause.message : "A rendelés még nem zárható le."))}>
453
+ Fizetés állapotának újraellenőrzése
454
+ </button>
455
+ ) : null}
456
+ </div>
457
+
458
+ <aside className="checkout-summary panel stack-sm">
459
+ <p className="eyebrow">Rendelés összesítő</p>
460
+ {asRecords(cart.items).map((item) => (
461
+ <div className="summary-line" key={stringValue(item.id)}>
462
+ <span>{stringValue(item.product_title || item.title)} × {stringValue(item.quantity)}</span>
463
+ <span>{typeof item.total === "number" ? formatMoney(item.total, currency, config.store.locale) : ""}</span>
464
+ </div>
465
+ ))}
466
+ <div className="summary-total">
467
+ <span>Összesen</span>
468
+ <strong>{formatMoney(cartTotal(cart), currency, config.store.locale)}</strong>
469
+ </div>
470
+ </aside>
471
+ </div>
472
+ )
473
+ }
474
+
475
+ function emptyAddress(country: string): AddressState {
476
+ return { email: "", first_name: "", last_name: "", company: "", phone: "", country_code: country.toUpperCase(), postal_code: "", city: "", province: "", address_1: "", address_2: "" }
477
+ }
478
+
479
+ function updateAddress(setter: React.Dispatch<React.SetStateAction<AddressState>>, key: keyof AddressState, value: string) {
480
+ setter((current) => ({ ...current, [key]: value }))
481
+ }
482
+
483
+ function validateAddress(address: AddressState) {
484
+ if (!/^\S+@\S+\.\S+$/.test(address.email)) throw new Error("Érvényes e-mail-cím szükséges.")
485
+ for (const [label, value] of [["keresztnév", address.first_name], ["vezetéknév", address.last_name], ["telefon", address.phone], ["ország", address.country_code], ["irányítószám", address.postal_code], ["város", address.city], ["cím", address.address_1]] as const) {
486
+ if (!value.trim()) throw new Error(`A(z) ${label} megadása kötelező.`)
487
+ }
488
+ }
489
+
490
+ function SectionTitle({ step, title }: { step: string; title: string }) {
491
+ return <div className="section-title"><span className="step-badge">{step}</span><h2>{title}</h2></div>
492
+ }
493
+
494
+ function Field({ label, value, onChange, type = "text" }: { label: string; value: string; onChange: (value: string) => void; type?: string }) {
495
+ return <label>{label}<input type={type} value={value} onChange={(event) => onChange(event.target.value)} /></label>
496
+ }
497
+
498
+ function pickupKind(option: JsonRecord): PickupKind {
499
+ const text = `${stringValue(option.id)} ${stringValue(option.name)} ${stringValue(option.provider_id)} ${JSON.stringify(option.data || {})}`.toLowerCase()
500
+ const isPoint = /(locker|point|pudo|automata|z-box|postapont|fixpont)/.test(text)
501
+ if (!isPoint) return null
502
+ if (text.includes("foxpost")) return "foxpost"
503
+ if (text.includes("gls")) return "gls"
504
+ if (text.includes("dpd")) return "dpd"
505
+ if (text.includes("mpl") || text.includes("posta")) return "mpl"
506
+ if (text.includes("packeta")) return "packeta"
507
+ return null
508
+ }
509
+
510
+ function pickupKey(point: JsonRecord) {
511
+ return stringValue(point.id || point.operatorId || point.placeId || point.code || point.shop_id || point.location_id || point.name)
512
+ }
513
+
514
+ function pointLabel(point: JsonRecord) {
515
+ const name = stringValue(point.name || point.label || point.title || point.shop_name || point.type)
516
+ const postal = stringValue(point.postalCode || point.postal_code || point.zipCode || point.zip_code || point.zip)
517
+ const city = stringValue(point.city || point.town)
518
+ const address = stringValue(point.address || point.address_1 || point.street || point.fullAddress)
519
+ return [name, [postal, city].filter(Boolean).join(" "), address].filter(Boolean).join(" – ") || pickupKey(point)
520
+ }
521
+
522
+ function shippingData(kind: PickupKind, point: JsonRecord | null, packetaId: string, packetaName: string): Record<string, unknown> | undefined {
523
+ if (!kind) return undefined
524
+ if (kind === "packeta") {
525
+ if (!packetaId.trim()) throw new Error("A Packeta pont azonosítója kötelező.")
526
+ return { packeta: { pickupPoint: { id: packetaId.trim(), name: packetaName.trim() || undefined } } }
527
+ }
528
+ if (!point) throw new Error("Válassz átvételi pontot.")
529
+ if (kind === "foxpost") return { foxpost: { locker: point, packageSize: "M" } }
530
+ if (kind === "gls") return { gls: { deliveryPoint: point } }
531
+ if (kind === "dpd") return { dpd: { pickupPoint: point } }
532
+ if (kind === "mpl") return { mpl: { pickupPoint: point } }
533
+ return undefined
534
+ }
@@ -0,0 +1,131 @@
1
+ "use client"
2
+
3
+ import { useEffect, useState } from "react"
4
+ import {
5
+ COOKIE_CONSENT_EVENT,
6
+ readConsentPreferences,
7
+ saveConsentPreferences,
8
+ type ConsentPreferences,
9
+ } from "@/lib/core/consent"
10
+
11
+ const COOKIE_SETTINGS_OPEN_EVENT = "core:cookie-settings-open"
12
+
13
+ export function ConsentBanner({ enabled }: { enabled: boolean }) {
14
+ const [open, setOpen] = useState(false)
15
+ const [preferences, setPreferences] = useState<ConsentPreferences | null>(null)
16
+ const [analytics, setAnalytics] = useState(false)
17
+ const [marketing, setMarketing] = useState(false)
18
+
19
+ useEffect(() => {
20
+ if (!enabled) return
21
+
22
+ const stored = readConsentPreferences()
23
+ setPreferences(stored)
24
+ setAnalytics(Boolean(stored?.analytics))
25
+ setMarketing(Boolean(stored?.marketing))
26
+ setOpen(!stored)
27
+
28
+ const onConsent = (event: Event) => {
29
+ const next = (event as CustomEvent<ConsentPreferences>).detail
30
+ if (!next) return
31
+ setPreferences(next)
32
+ setAnalytics(next.analytics)
33
+ setMarketing(next.marketing)
34
+ setOpen(false)
35
+ }
36
+ const onOpen = () => {
37
+ const latest = readConsentPreferences()
38
+ setAnalytics(Boolean(latest?.analytics))
39
+ setMarketing(Boolean(latest?.marketing))
40
+ setOpen(true)
41
+ }
42
+
43
+ window.addEventListener(COOKIE_CONSENT_EVENT, onConsent)
44
+ window.addEventListener(COOKIE_SETTINGS_OPEN_EVENT, onOpen)
45
+ return () => {
46
+ window.removeEventListener(COOKIE_CONSENT_EVENT, onConsent)
47
+ window.removeEventListener(COOKIE_SETTINGS_OPEN_EVENT, onOpen)
48
+ }
49
+ }, [enabled])
50
+
51
+ if (!enabled) return null
52
+
53
+ const save = (next: { analytics: boolean; marketing: boolean }) => {
54
+ saveConsentPreferences(next)
55
+ }
56
+
57
+ return (
58
+ <>
59
+ <button
60
+ type="button"
61
+ className="cookie-settings-trigger"
62
+ onClick={() => window.dispatchEvent(new CustomEvent(COOKIE_SETTINGS_OPEN_EVENT))}
63
+ >
64
+ Cookie-beállítások
65
+ </button>
66
+
67
+ {open ? (
68
+ <aside className="consent" aria-label="Cookie-beállítások" role="dialog" aria-modal="true">
69
+ <div className="stack consent-copy">
70
+ <div>
71
+ <strong>Cookie-beállítások</strong>
72
+ <p>
73
+ A szükséges funkciók mindig aktívak. Analitikai és marketing
74
+ tagek csak az általad engedélyezett kategóriákhoz aktiválódnak.
75
+ </p>
76
+ </div>
77
+
78
+ <label className="consent-toggle">
79
+ <input type="checkbox" checked disabled />
80
+ <span>
81
+ <strong>Szükséges</strong>
82
+ <small>A webshop működéséhez szükséges technikai tárolás.</small>
83
+ </span>
84
+ </label>
85
+
86
+ <label className="consent-toggle">
87
+ <input
88
+ type="checkbox"
89
+ checked={analytics}
90
+ onChange={(event) => setAnalytics(event.target.checked)}
91
+ />
92
+ <span>
93
+ <strong>Analitika</strong>
94
+ <small>GA4 és webshop e-commerce mérés.</small>
95
+ </span>
96
+ </label>
97
+
98
+ <label className="consent-toggle">
99
+ <input
100
+ type="checkbox"
101
+ checked={marketing}
102
+ onChange={(event) => setMarketing(event.target.checked)}
103
+ />
104
+ <span>
105
+ <strong>Marketing</strong>
106
+ <small>Hirdetési és remarketing tagek engedélyezése GTM-en keresztül.</small>
107
+ </span>
108
+ </label>
109
+ </div>
110
+
111
+ <div className="consent-actions">
112
+ <button className="button secondary" onClick={() => save({ analytics: false, marketing: false })}>
113
+ Opcionálisak elutasítása
114
+ </button>
115
+ <button className="button secondary" onClick={() => save({ analytics, marketing })}>
116
+ Beállítások mentése
117
+ </button>
118
+ <button className="button" onClick={() => save({ analytics: true, marketing: true })}>
119
+ Mindet elfogadom
120
+ </button>
121
+ {preferences ? (
122
+ <button className="button secondary" onClick={() => setOpen(false)}>
123
+ Bezárás
124
+ </button>
125
+ ) : null}
126
+ </div>
127
+ </aside>
128
+ ) : null}
129
+ </>
130
+ )
131
+ }