@hszrdm/create-commerce 1.5.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 (29) hide show
  1. package/package.json +1 -1
  2. package/templates/backend/package.json +1 -1
  3. package/templates/storefront/README.md +35 -12
  4. package/templates/storefront/src/app/[countryCode]/products/[handle]/page.tsx +3 -2
  5. package/templates/storefront/src/app/blog/page.tsx +46 -8
  6. package/templates/storefront/src/app/cart/page.tsx +2 -0
  7. package/templates/storefront/src/app/cart/shared/[token]/page.tsx +25 -0
  8. package/templates/storefront/src/app/knowledge-base/page.tsx +46 -8
  9. package/templates/storefront/src/app/layout.tsx +5 -2
  10. package/templates/storefront/src/app/legal/page.tsx +18 -2
  11. package/templates/storefront/src/app/page.tsx +33 -4
  12. package/templates/storefront/src/app/pages/page.tsx +43 -0
  13. package/templates/storefront/src/components/add-to-cart.tsx +76 -2
  14. package/templates/storefront/src/components/analytics.tsx +37 -17
  15. package/templates/storefront/src/components/cart-provider.tsx +40 -3
  16. package/templates/storefront/src/components/cart-share-button.tsx +93 -0
  17. package/templates/storefront/src/components/cms-taxonomy-filters.tsx +86 -0
  18. package/templates/storefront/src/components/customer-cart-resume-gate.tsx +112 -0
  19. package/templates/storefront/src/components/fogyasztobarat-embed.tsx +32 -0
  20. package/templates/storefront/src/components/shared-cart-view.tsx +257 -0
  21. package/templates/storefront/src/lib/core/catalog.ts +12 -0
  22. package/templates/storefront/src/lib/core/checkout.ts +86 -4
  23. package/templates/storefront/src/lib/core/customer-cart-resume.ts +51 -0
  24. package/templates/storefront/src/lib/core/google-ads.ts +58 -0
  25. package/templates/storefront/src/lib/core/legal.ts +14 -0
  26. package/templates/storefront/src/lib/core/shared-cart.ts +37 -0
  27. package/templates/storefront/src/lib/core/types.ts +18 -0
  28. package/templates/storefront/src/lib/storefront-routes.ts +9 -0
  29. package/templates/storefront/src/proxy.ts +7 -0
@@ -35,7 +35,13 @@ gtag('consent','default',{
35
35
  });
36
36
  `
37
37
 
38
- export function AnalyticsGate({ analytics }: { analytics: CoreConfig["analytics"] }) {
38
+ export function AnalyticsGate({
39
+ analytics,
40
+ googleAds,
41
+ }: {
42
+ analytics: CoreConfig["analytics"]
43
+ googleAds: CoreConfig["marketing"]["google_ads"]
44
+ }) {
39
45
  const pathname = usePathname()
40
46
  const [preferences, setPreferences] = useState<ConsentPreferences | null>(null)
41
47
  const [ready, setReady] = useState(false)
@@ -71,26 +77,40 @@ export function AnalyticsGate({ analytics }: { analytics: CoreConfig["analytics"
71
77
  const analyticsGranted = Boolean(preferences?.analytics)
72
78
  const marketingGranted = Boolean(preferences?.marketing)
73
79
 
74
- // GTM is the single loader whenever a container is configured. This prevents
75
- // a direct GA4 snippet and a GA4 tag inside GTM from double-counting events.
80
+ // GTM remains the single loader whenever a container is configured. Without
81
+ // GTM, GA4 and Google Ads share one gtag.js loader, while each public ID is
82
+ // configured only after its own consent category has been granted.
76
83
  const loadGtm = mode === "gtm" && (analyticsGranted || marketingGranted)
77
- const loadGa4 = mode === "ga4" && analyticsGranted
84
+ const loadGa4 = mode === "ga4" && analyticsGranted && Boolean(analytics.google_analytics.measurement_id)
85
+ const loadDirectAds = mode !== "gtm" && marketingGranted && googleAds.enabled && Boolean(googleAds.conversion_id)
86
+ const directGoogleTagId = loadGa4
87
+ ? analytics.google_analytics.measurement_id
88
+ : loadDirectAds
89
+ ? googleAds.conversion_id
90
+ : null
91
+ const configureGa4 = loadGa4
92
+ const configureAds = loadDirectAds
78
93
 
79
94
  return (
80
95
  <>
81
- {loadGa4 && analytics.google_analytics.measurement_id ? (
82
- <>
83
- <Script
84
- id="core-ga4-loader"
85
- src={`https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(
86
- analytics.google_analytics.measurement_id,
87
- )}`}
88
- strategy="afterInteractive"
89
- />
90
- <Script id="core-ga4-config" strategy="afterInteractive">
91
- {`gtag('js',new Date());gtag('config','${analytics.google_analytics.measurement_id}');`}
92
- </Script>
93
- </>
96
+ {directGoogleTagId ? (
97
+ <Script
98
+ id="core-google-tag-loader"
99
+ src={`https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(directGoogleTagId)}`}
100
+ strategy="afterInteractive"
101
+ />
102
+ ) : null}
103
+
104
+ {configureGa4 ? (
105
+ <Script id="core-ga4-config" strategy="afterInteractive">
106
+ {`gtag('js',new Date());gtag('config','${analytics.google_analytics.measurement_id}');`}
107
+ </Script>
108
+ ) : null}
109
+
110
+ {configureAds ? (
111
+ <Script id="core-google-ads-config" strategy="afterInteractive">
112
+ {`gtag('config','${googleAds.conversion_id}',{'allow_ad_personalization_signals':${googleAds.remarketing_enabled ? "true" : "false"}});`}
113
+ </Script>
94
114
  ) : null}
95
115
 
96
116
  {loadGtm && analytics.google_tag_manager.container_id ? (
@@ -12,6 +12,11 @@ import {
12
12
  import { usePathname } from "next/navigation"
13
13
  import { checkoutApi } from "@/lib/core/checkout"
14
14
  import { cartItemCount, stringValue, type JsonRecord } from "@/lib/core/commerce"
15
+ import {
16
+ announceCustomerCartResumeConflict,
17
+ isUnauthenticatedCartResume,
18
+ resolveCustomerCartResume,
19
+ } from "@/lib/core/customer-cart-resume"
15
20
  import type { CoreConfig } from "@/lib/core/types"
16
21
  import { localeFromPathname, medusaLocale } from "@/lib/storefront-routes"
17
22
 
@@ -212,11 +217,42 @@ export function CartProvider({
212
217
  await mutate((id) => api.removePromotion(id, code))
213
218
  },
214
219
  transferToCustomer: async () => {
215
- if (!cartId) return
216
220
  setMutating(true)
221
+ setError(null)
217
222
  try {
218
- const result = await api.transferCart(cartId)
219
- setCart(result.cart)
223
+ let decision
224
+ try {
225
+ decision = await resolveCustomerCartResume(cartId)
226
+ } catch (cause) {
227
+ if (isUnauthenticatedCartResume(cause)) return
228
+ throw cause
229
+ }
230
+
231
+ if (decision.action === "merge-required") {
232
+ announceCustomerCartResumeConflict(decision)
233
+ return
234
+ }
235
+
236
+ if (decision.action === "resume" && decision.target_cart_id) {
237
+ await adoptCart(decision.target_cart_id)
238
+ return
239
+ }
240
+
241
+ if (decision.action === "keep-current") {
242
+ const targetId = decision.target_cart_id || cartId
243
+ if (!targetId) return
244
+ if (decision.current_cart?.customer_id) {
245
+ if (targetId !== cartId) await adoptCart(targetId)
246
+ return
247
+ }
248
+ const result = await api.transferCart(targetId)
249
+ const localizedCart = await syncLocale(targetId, result.cart)
250
+ setCart(localizedCart)
251
+ storeCartId(targetId)
252
+ }
253
+ } catch (cause) {
254
+ setError(cause instanceof Error ? cause.message : "A vásárlói kosár nem állítható helyre.")
255
+ throw cause
220
256
  } finally {
221
257
  setMutating(false)
222
258
  }
@@ -240,6 +276,7 @@ export function CartProvider({
240
276
  mutating,
241
277
  refresh,
242
278
  storeCartId,
279
+ syncLocale,
243
280
  ],
244
281
  )
245
282
 
@@ -0,0 +1,93 @@
1
+ "use client"
2
+
3
+ import { usePathname } from "next/navigation"
4
+ import { useState } from "react"
5
+ import { ShareButton } from "./share-button"
6
+ import { useCart } from "./cart-provider"
7
+ import { useToast } from "./toast-provider"
8
+ import {
9
+ cartCurrency,
10
+ cartItems,
11
+ cartRegionId,
12
+ numberValue,
13
+ stringValue,
14
+ } from "@/lib/core/commerce"
15
+ import { createSharedCart } from "@/lib/core/shared-cart"
16
+ import type { CoreConfig } from "@/lib/core/types"
17
+ import { localeFromPathname, sharedCartPath } from "@/lib/storefront-routes"
18
+
19
+ export function CartShareButton({ config }: { config: CoreConfig }) {
20
+ const { cart, mutating } = useCart()
21
+ const { showToast } = useToast()
22
+ const pathname = usePathname()
23
+ const locale = localeFromPathname(pathname)
24
+ const en = locale === "en"
25
+ const [creating, setCreating] = useState(false)
26
+ const [shareUrl, setShareUrl] = useState<string | null>(null)
27
+ const [expiresAt, setExpiresAt] = useState<string | null>(null)
28
+ const currentItems = cartItems(cart)
29
+
30
+ if (!currentItems.length) return null
31
+
32
+ const create = async () => {
33
+ const items = currentItems
34
+ .map((item) => ({
35
+ product_id: stringValue(item.product_id) || null,
36
+ variant_id: stringValue(item.variant_id),
37
+ quantity: Math.max(1, Math.trunc(numberValue(item.quantity, 1))),
38
+ }))
39
+ .filter((item) => item.variant_id)
40
+
41
+ if (!items.length) return
42
+ setCreating(true)
43
+ try {
44
+ const result = await createSharedCart({
45
+ items,
46
+ region_id: cartRegionId(cart) || null,
47
+ currency_code: cartCurrency(cart, config.store.default_currency),
48
+ })
49
+ setShareUrl(`${window.location.origin}${sharedCartPath(locale, result.token)}`)
50
+ setExpiresAt(result.expires_at)
51
+ showToast({ message: en ? "Share link created." : "A megosztási link elkészült.", tone: "success" })
52
+ } catch (error) {
53
+ showToast({
54
+ message: error instanceof Error ? error.message : en ? "The cart could not be shared." : "A kosár megosztása nem sikerült.",
55
+ tone: "error",
56
+ })
57
+ } finally {
58
+ setCreating(false)
59
+ }
60
+ }
61
+
62
+ return (
63
+ <div className="panel stack-sm">
64
+ <div>
65
+ <strong>{en ? "Share cart" : "Kosár megosztása"}</strong>
66
+ <p className="muted">
67
+ {en
68
+ ? "Only products, variants and quantities are shared. Personal data and coupons are excluded."
69
+ : "Csak a termékek, variánsok és mennyiségek kerülnek a megosztásba. Személyes adat és kupon nem."}
70
+ </p>
71
+ </div>
72
+ {!shareUrl ? (
73
+ <button className="button secondary" type="button" disabled={mutating || creating} onClick={() => void create()}>
74
+ {creating ? (en ? "Creating link…" : "Link készítése…") : (en ? "Share cart" : "Kosár megosztása")}
75
+ </button>
76
+ ) : (
77
+ <>
78
+ <input aria-label={en ? "Shared cart link" : "Megosztott kosár linkje"} readOnly value={shareUrl} />
79
+ <ShareButton
80
+ url={shareUrl}
81
+ title={`${config.store.name} – ${en ? "shared cart" : "megosztott kosár"}`}
82
+ text={en ? "I shared this cart with you." : "Megosztottam veled ezt a kosarat."}
83
+ />
84
+ {expiresAt ? (
85
+ <span className="muted">
86
+ {en ? "Expires" : "Lejárat"}: {new Date(expiresAt).toLocaleDateString(en ? "en-US" : "hu-HU")}
87
+ </span>
88
+ ) : null}
89
+ </>
90
+ )}
91
+ </div>
92
+ )
93
+ }
@@ -0,0 +1,86 @@
1
+ import Link from "next/link"
2
+ import type { CmsTaxonomyTerm } from "@/lib/core/cms"
3
+ import type { StorefrontLocale } from "@/lib/storefront-routes"
4
+
5
+ export function CmsTaxonomyFilters({
6
+ basePath,
7
+ terms,
8
+ locale,
9
+ activeCategory,
10
+ activeTag,
11
+ }: {
12
+ basePath: string
13
+ terms: CmsTaxonomyTerm[]
14
+ locale: StorefrontLocale
15
+ activeCategory?: string
16
+ activeTag?: string
17
+ }) {
18
+ const categories = terms.filter((term) => term.taxonomy === "category")
19
+ const tags = terms.filter((term) => term.taxonomy === "tag")
20
+ const en = locale === "en"
21
+
22
+ if (!categories.length && !tags.length) return null
23
+
24
+ return (
25
+ <section className="panel stack-sm" aria-label={en ? "Content filters" : "Tartalomszűrők"}>
26
+ <div className="section-title-row">
27
+ <div>
28
+ <p className="eyebrow">{en ? "Browse" : "Böngészés"}</p>
29
+ <h2>{en ? "Filter content" : "Tartalom szűrése"}</h2>
30
+ </div>
31
+ {(activeCategory || activeTag) ? (
32
+ <Link className="text-link" href={basePath}>
33
+ {en ? "Clear filters" : "Szűrők törlése"}
34
+ </Link>
35
+ ) : null}
36
+ </div>
37
+
38
+ {categories.length ? (
39
+ <div className="stack-sm">
40
+ <strong>{en ? "Categories" : "Kategóriák"}</strong>
41
+ <div className="category-row">
42
+ {categories.map((term) => (
43
+ <Link
44
+ className={`category-chip${activeCategory === term.slug ? " active" : ""}`}
45
+ href={filterHref(basePath, { category: term.slug, tag: activeTag })}
46
+ aria-current={activeCategory === term.slug ? "page" : undefined}
47
+ key={term.id}
48
+ >
49
+ {term.name}
50
+ </Link>
51
+ ))}
52
+ </div>
53
+ </div>
54
+ ) : null}
55
+
56
+ {tags.length ? (
57
+ <div className="stack-sm">
58
+ <strong>{en ? "Tags" : "Címkék"}</strong>
59
+ <div className="category-row">
60
+ {tags.map((term) => (
61
+ <Link
62
+ className={`category-chip${activeTag === term.slug ? " active" : ""}`}
63
+ href={filterHref(basePath, { category: activeCategory, tag: term.slug })}
64
+ aria-current={activeTag === term.slug ? "page" : undefined}
65
+ key={term.id}
66
+ >
67
+ {term.name}
68
+ </Link>
69
+ ))}
70
+ </div>
71
+ </div>
72
+ ) : null}
73
+ </section>
74
+ )
75
+ }
76
+
77
+ function filterHref(
78
+ basePath: string,
79
+ filters: { category?: string; tag?: string },
80
+ ) {
81
+ const params = new URLSearchParams()
82
+ if (filters.category) params.set("category", filters.category)
83
+ if (filters.tag) params.set("tag", filters.tag)
84
+ const query = params.toString()
85
+ return query ? `${basePath}?${query}` : basePath
86
+ }
@@ -0,0 +1,112 @@
1
+ "use client"
2
+
3
+ import { useEffect, useMemo, useRef, useState } from "react"
4
+ import { usePathname } from "next/navigation"
5
+ import { checkoutApi } from "@/lib/core/checkout"
6
+ import {
7
+ CUSTOMER_CART_RESUME_CONFLICT_EVENT,
8
+ type CustomerCartResumeDecision,
9
+ } from "@/lib/core/customer-cart-resume"
10
+ import type { CoreConfig } from "@/lib/core/types"
11
+ import { localeFromPathname } from "@/lib/storefront-routes"
12
+ import { useCart } from "./cart-provider"
13
+
14
+ export function CustomerCartResumeGate({ config }: { config: CoreConfig }) {
15
+ const api = useMemo(() => checkoutApi(config), [config])
16
+ const pathname = usePathname()
17
+ const locale = localeFromPathname(pathname)
18
+ const {
19
+ loading,
20
+ mutating,
21
+ adoptCart,
22
+ transferToCustomer,
23
+ } = useCart()
24
+ const initialReconcileAttempted = useRef(false)
25
+ const [conflict, setConflict] = useState<CustomerCartResumeDecision | null>(null)
26
+ const [busy, setBusy] = useState<"saved" | "current" | null>(null)
27
+ const [error, setError] = useState<string | null>(null)
28
+
29
+ useEffect(() => {
30
+ const listener = (event: Event) => {
31
+ const detail = (event as CustomEvent<CustomerCartResumeDecision>).detail
32
+ if (detail?.action === "merge-required") {
33
+ setConflict(detail)
34
+ setError(null)
35
+ }
36
+ }
37
+ window.addEventListener(CUSTOMER_CART_RESUME_CONFLICT_EVENT, listener)
38
+ return () => window.removeEventListener(CUSTOMER_CART_RESUME_CONFLICT_EVENT, listener)
39
+ }, [])
40
+
41
+ useEffect(() => {
42
+ if (loading || initialReconcileAttempted.current) return
43
+ initialReconcileAttempted.current = true
44
+ void transferToCustomer().catch(() => undefined)
45
+ }, [loading, transferToCustomer])
46
+
47
+ if (!conflict) return null
48
+
49
+ const savedId = conflict.active_cart?.id || ""
50
+ const currentId = conflict.current_cart?.id || ""
51
+ const savedCount = Number(conflict.active_cart?.item_count || 0)
52
+ const currentCount = Number(conflict.current_cart?.item_count || 0)
53
+ const en = locale === "en"
54
+
55
+ const chooseSaved = async () => {
56
+ if (!savedId) return
57
+ setBusy("saved")
58
+ setError(null)
59
+ try {
60
+ await adoptCart(savedId)
61
+ setConflict(null)
62
+ } catch (cause) {
63
+ setError(cause instanceof Error ? cause.message : en ? "The saved cart could not be loaded." : "A mentett kosár nem tölthető be.")
64
+ } finally {
65
+ setBusy(null)
66
+ }
67
+ }
68
+
69
+ const chooseCurrent = async () => {
70
+ if (!currentId) return
71
+ setBusy("current")
72
+ setError(null)
73
+ try {
74
+ await api.transferCart(currentId)
75
+ await adoptCart(currentId)
76
+ setConflict(null)
77
+ } catch (cause) {
78
+ setError(cause instanceof Error ? cause.message : en ? "The current cart could not be kept." : "A jelenlegi kosár nem tartható meg.")
79
+ } finally {
80
+ setBusy(null)
81
+ }
82
+ }
83
+
84
+ return (
85
+ <section className="shell page-section" aria-live="polite">
86
+ <div className="notice warning-box stack-sm" role="dialog" aria-modal="false" aria-labelledby="cart-resume-title">
87
+ <div>
88
+ <p className="eyebrow">{en ? "Cart sync" : "Kosár egyeztetés"}</p>
89
+ <h2 id="cart-resume-title">{en ? "You have two active carts" : "Két aktív kosarad van"}</h2>
90
+ <p className="muted">
91
+ {en
92
+ ? "We did not overwrite either cart. Choose which one you want to continue with."
93
+ : "Egyik kosarat sem írtuk felül. Válaszd ki, melyiket szeretnéd folytatni."}
94
+ </p>
95
+ </div>
96
+ <div className="button-row">
97
+ <button className="button" type="button" disabled={Boolean(busy) || mutating || !savedId} onClick={() => void chooseSaved()}>
98
+ {busy === "saved"
99
+ ? (en ? "Loading…" : "Betöltés…")
100
+ : (en ? `Continue saved cart (${savedCount})` : `Mentett kosár folytatása (${savedCount})`)}
101
+ </button>
102
+ <button className="button secondary" type="button" disabled={Boolean(busy) || mutating || !currentId} onClick={() => void chooseCurrent()}>
103
+ {busy === "current"
104
+ ? (en ? "Keeping…" : "Megtartás…")
105
+ : (en ? `Keep current cart (${currentCount})` : `Jelenlegi kosár megtartása (${currentCount})`)}
106
+ </button>
107
+ </div>
108
+ {error ? <p className="error" role="alert">{error}</p> : null}
109
+ </div>
110
+ </section>
111
+ )
112
+ }
@@ -0,0 +1,32 @@
1
+ "use client"
2
+
3
+ import { useEffect, useRef } from "react"
4
+ import type { LegalEmbedConfig } from "@/lib/core/legal"
5
+
6
+ export function FogyasztobaratEmbed({ embed }: { embed: LegalEmbedConfig }) {
7
+ const hostRef = useRef<HTMLDivElement | null>(null)
8
+
9
+ useEffect(() => {
10
+ const host = hostRef.current
11
+ if (!host || !embed.enabled || embed.provider !== "fogyasztobarat") return
12
+ const scriptUrl = String(embed.scriptUrl || "").trim()
13
+ const dataId = String(embed.dataId || "").trim()
14
+ if (!scriptUrl.startsWith("https://admin.fogyasztobarat.hu/") || !dataId) return
15
+
16
+ const script = document.createElement("script")
17
+ script.src = scriptUrl
18
+ script.async = true
19
+ script.dataset.id = dataId
20
+ script.dataset.type = String(embed.dataType || "def")
21
+ host.appendChild(script)
22
+
23
+ return () => {
24
+ script.remove()
25
+ host.replaceChildren()
26
+ }
27
+ }, [embed])
28
+
29
+ if (!embed.enabled || embed.provider !== "fogyasztobarat") return null
30
+
31
+ return <div ref={hostRef} className="fogyasztobarat-embed" data-provider="fogyasztobarat" />
32
+ }