@hszrdm/create-commerce 1.4.0 → 1.5.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 (25) 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/src/app/cart-recovery/page.tsx +35 -0
  13. package/templates/storefront/src/app/ertekeles/page.tsx +25 -0
  14. package/templates/storefront/src/app/fiok-aktivalas/page.tsx +35 -0
  15. package/templates/storefront/src/components/abandoned-cart-recovery.tsx +139 -0
  16. package/templates/storefront/src/components/account-activation-form.tsx +333 -0
  17. package/templates/storefront/src/components/add-to-cart.tsx +56 -0
  18. package/templates/storefront/src/components/analytics.tsx +15 -2
  19. package/templates/storefront/src/components/review-request-form.tsx +419 -0
  20. package/templates/storefront/src/lib/core/abandoned-cart.ts +47 -0
  21. package/templates/storefront/src/lib/core/account-activation.ts +75 -0
  22. package/templates/storefront/src/lib/core/back-in-stock.ts +25 -0
  23. package/templates/storefront/src/lib/core/reviews.ts +37 -5
  24. package/templates/storefront/src/lib/storefront-routes.ts +3 -0
  25. package/templates/storefront/src/proxy.ts +4 -0
@@ -0,0 +1,237 @@
1
+ import { createHash } from "node:crypto"
2
+ import {
3
+ cpSync,
4
+ existsSync,
5
+ mkdirSync,
6
+ readFileSync,
7
+ readdirSync,
8
+ statSync,
9
+ } from "node:fs"
10
+ import { dirname, isAbsolute, join, resolve } from "node:path"
11
+
12
+ export const PORTABLE_ENV_KEYS = [
13
+ "MEDUSA_BACKEND_URL",
14
+ "STOREFRONT_URL",
15
+ "MEDUSA_ADMIN_PATH",
16
+ "STORE_CORS",
17
+ "ADMIN_CORS",
18
+ "AUTH_CORS",
19
+ "STORE_NAME",
20
+ "STORE_SLUG",
21
+ "STORE_LOCALE",
22
+ "STORE_DEFAULT_CURRENCY",
23
+ "STORE_DEFAULT_COUNTRY",
24
+ "VITE_ADMIN_BRAND_NAME",
25
+ "ORDER_EMAIL",
26
+ "SUPPORT_EMAIL",
27
+ "BILLING_EMAIL",
28
+ "SYSTEM_EMAIL",
29
+ "AFTER_SALES_ENABLED",
30
+ "AFTER_SALES_RETURNS_ENABLED",
31
+ "AFTER_SALES_EXCHANGES_ENABLED",
32
+ "AFTER_SALES_CLAIMS_ENABLED",
33
+ "AFTER_SALES_POLICY_URL",
34
+ "AFTER_SALES_RETURN_INSTRUCTIONS",
35
+ "SEO_STOREFRONT_URL",
36
+ "SEO_STORE_NAME",
37
+ "SEO_ORGANIZATION_NAME",
38
+ "SEO_ORGANIZATION_LOGO_URL",
39
+ "SEO_DEFAULT_COUNTRY",
40
+ "SEO_DEFAULT_CURRENCY",
41
+ "SEO_PRODUCT_PATH_TEMPLATE",
42
+ "SEO_CATEGORY_PATH_TEMPLATE",
43
+ "SEO_ALLOW_INDEXING",
44
+ "SEO_ROBOTS_DISALLOW",
45
+ ]
46
+
47
+ export const CORE_DB_MODULES = [
48
+ "medusa_native",
49
+ "integration_settings",
50
+ "integration_operation",
51
+ "core_audit",
52
+ "legal_consent",
53
+ "seo",
54
+ ]
55
+
56
+ export function backendProjectDir(projectDir) {
57
+ const monorepoBackend = join(projectDir, "apps", "backend")
58
+ if (existsSync(monorepoBackend)) return monorepoBackend
59
+
60
+ const generatedBackend = join(projectDir, "backend")
61
+ if (existsSync(generatedBackend)) return generatedBackend
62
+
63
+ return projectDir
64
+ }
65
+
66
+ export function loadRuntimeEnv(projectDir, overrides = process.env) {
67
+ const file = join(backendProjectDir(projectDir), ".env")
68
+ const fromFile = existsSync(file) ? parseEnv(readFileSync(file, "utf8")) : {}
69
+ const explicitOverrides = Object.fromEntries(
70
+ Object.entries(overrides).filter(([, value]) => value != null && String(value).trim() !== ""),
71
+ )
72
+ return { ...fromFile, ...explicitOverrides }
73
+ }
74
+
75
+ export function parseEnv(source) {
76
+ const result = {}
77
+ for (const rawLine of String(source).split(/\r?\n/)) {
78
+ const line = rawLine.trim()
79
+ if (!line || line.startsWith("#")) continue
80
+ const eq = line.indexOf("=")
81
+ if (eq <= 0) continue
82
+ const key = line.slice(0, eq).trim()
83
+ let value = line.slice(eq + 1).trim()
84
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
85
+ value = value.slice(1, -1)
86
+ }
87
+ result[key] = value
88
+ }
89
+ return result
90
+ }
91
+
92
+ export function portableConfig(env) {
93
+ const values = {}
94
+ for (const key of PORTABLE_ENV_KEYS) {
95
+ const value = String(env[key] ?? "").trim()
96
+ if (value) values[key] = value
97
+ }
98
+ return values
99
+ }
100
+
101
+ export function portableEnvText(values) {
102
+ return `${Object.entries(values)
103
+ .map(([key, value]) => `${key}=${quoteEnv(value)}`)
104
+ .join("\n")}\n`
105
+ }
106
+
107
+ export function pgEnvironment(databaseUrl, base = process.env) {
108
+ const url = new URL(required(databaseUrl, "DATABASE_URL"))
109
+ if (!["postgres:", "postgresql:"].includes(url.protocol)) {
110
+ throw new Error("DATABASE_URL csak postgres/postgresql URL lehet.")
111
+ }
112
+ const database = decodeURIComponent(url.pathname.replace(/^\//, ""))
113
+ if (!database) throw new Error("DATABASE_URL adatbázisneve hiányzik.")
114
+
115
+ return {
116
+ database,
117
+ env: {
118
+ ...base,
119
+ PGHOST: url.hostname,
120
+ PGPORT: url.port || "5432",
121
+ PGUSER: decodeURIComponent(url.username || ""),
122
+ PGPASSWORD: decodeURIComponent(url.password || ""),
123
+ PGDATABASE: database,
124
+ ...(url.searchParams.get("sslmode") ? { PGSSLMODE: url.searchParams.get("sslmode") } : {}),
125
+ },
126
+ }
127
+ }
128
+
129
+ export function integrationSnapshotPath(projectDir, env) {
130
+ const backendDir = backendProjectDir(projectDir)
131
+ const configured = String(env.INTEGRATION_SETTINGS_FILE || "").trim()
132
+ if (configured) return isAbsolute(configured) ? configured : resolve(backendDir, configured)
133
+
134
+ const uploadDir = String(env.FILE_UPLOAD_DIR || "").trim()
135
+ if (uploadDir && isAbsolute(uploadDir)) {
136
+ return join(dirname(uploadDir), "integration-settings.enc")
137
+ }
138
+
139
+ return join(backendDir, ".core", "integration-settings.enc")
140
+ }
141
+
142
+ export function backupFileSources(projectDir, env) {
143
+ const sources = []
144
+ const backendDir = backendProjectDir(projectDir)
145
+ const snapshot = integrationSnapshotPath(projectDir, env)
146
+ if (existsSync(snapshot)) {
147
+ sources.push({ key: "integration_snapshot", source: snapshot, relative: "files/integration-settings.enc" })
148
+ }
149
+
150
+ const localStatic = join(backendDir, "static")
151
+ if (existsSync(localStatic)) {
152
+ sources.push({ key: "local_static", source: localStatic, relative: "files/local-static" })
153
+ }
154
+
155
+ const configuredUpload = String(env.FILE_UPLOAD_DIR || "").trim()
156
+ if (configuredUpload && isAbsolute(configuredUpload) && existsSync(configuredUpload)) {
157
+ sources.push({ key: "file_upload_dir", source: configuredUpload, relative: "files/file-upload-dir" })
158
+ }
159
+ return sources
160
+ }
161
+
162
+ export function copyBackupSource(bundleDir, item) {
163
+ const target = join(bundleDir, item.relative)
164
+ mkdirSync(dirname(target), { recursive: true })
165
+ cpSync(item.source, target, { recursive: true, force: true })
166
+ return target
167
+ }
168
+
169
+ export function sha256File(path) {
170
+ const hash = createHash("sha256")
171
+ hash.update(readFileSync(path))
172
+ return hash.digest("hex")
173
+ }
174
+
175
+ export function sha256Tree(path) {
176
+ const hash = createHash("sha256")
177
+ hashDirectory(hash, path, path)
178
+ return hash.digest("hex")
179
+ }
180
+
181
+ export function verifyManifest(bundleDir, manifest) {
182
+ const failures = []
183
+ for (const artifact of manifest.artifacts || []) {
184
+ const path = join(bundleDir, artifact.path)
185
+ if (!existsSync(path)) {
186
+ failures.push(`${artifact.path}: hiányzik`)
187
+ continue
188
+ }
189
+ const actual = artifact.kind === "directory" ? sha256Tree(path) : sha256File(path)
190
+ if (actual !== artifact.sha256) failures.push(`${artifact.path}: checksum eltérés`)
191
+ }
192
+ if (failures.length) {
193
+ throw new Error(`A backup integritásellenőrzése sikertelen:\n- ${failures.join("\n- ")}`)
194
+ }
195
+ }
196
+
197
+ export function backupTimestamp(date = new Date()) {
198
+ return date.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z")
199
+ }
200
+
201
+ export function requireEncryptionKeyWhenNeeded(manifest, env) {
202
+ if (!manifest.requires_integration_encryption_key) return
203
+ const key = String(env.INTEGRATION_SETTINGS_ENCRYPTION_KEY || "").trim()
204
+ if (key.length < 32) {
205
+ throw new Error(
206
+ "A backup titkosított Integration Settings adatot tartalmaz. A visszaállításhoz add meg az eredeti, legalább 32 karakteres INTEGRATION_SETTINGS_ENCRYPTION_KEY értéket; a kulcs szándékosan nincs a backupban.",
207
+ )
208
+ }
209
+ }
210
+
211
+ function hashDirectory(hash, root, current) {
212
+ const entries = readdirSync(current).sort((a, b) => a.localeCompare(b))
213
+ for (const name of entries) {
214
+ const full = join(current, name)
215
+ const relative = full.slice(root.length + 1)
216
+ const stat = statSync(full)
217
+ if (stat.isDirectory()) {
218
+ hash.update(`D:${relative}\n`)
219
+ hashDirectory(hash, root, full)
220
+ } else if (stat.isFile()) {
221
+ hash.update(`F:${relative}:${stat.size}\n`)
222
+ hash.update(readFileSync(full))
223
+ }
224
+ }
225
+ }
226
+
227
+ function quoteEnv(value) {
228
+ const text = String(value)
229
+ if (!/[\s#'"\\]/.test(text)) return text
230
+ return JSON.stringify(text)
231
+ }
232
+
233
+ function required(value, label) {
234
+ const text = String(value || "").trim()
235
+ if (!text) throw new Error(`${label} kötelező.`)
236
+ return text
237
+ }
@@ -40,7 +40,8 @@ git pull --ff-only
40
40
  NEW_SHA="$(git rev-parse HEAD)"
41
41
  printf 'Deploying %s -> %s\n' "$OLD_SHA" "$NEW_SHA"
42
42
 
43
- log "Install exact dependencies"
43
+ log "Clean dependency tree and install exact dependencies"
44
+ rm -rf node_modules
44
45
  npm ci
45
46
  npm --workspace backend run env:verify
46
47
 
@@ -156,7 +156,8 @@ need curl
156
156
 
157
157
  bootstrap_env
158
158
 
159
- log "Install exact dependencies"
159
+ log "Clean dependency tree and install exact dependencies"
160
+ rm -rf node_modules
160
161
  npm ci
161
162
 
162
163
  log "Verify environment schema"
@@ -59,8 +59,11 @@ if [[ -d "$TMP/runtime/uploads" ]]; then
59
59
  fi
60
60
  fi
61
61
 
62
- log "Install, migrate and verify restored application"
62
+ log "Clean dependency tree and install exact dependencies"
63
+ rm -rf node_modules
63
64
  npm ci
65
+
66
+ log "Migrate and verify restored application"
64
67
  npm --workspace backend run env:verify
65
68
  npm run db:migrate
66
69
  npm run build
@@ -5,7 +5,7 @@ import ensureShipping from "@hszrdm/core/scripts/ensure-shipping"
5
5
  import { normalizeMedusaExecArgs } from "@hszrdm/core/scripts/exec-args"
6
6
 
7
7
  export default async function runCoreInit(params: ExecArgs) {
8
- await coreInit({
8
+ const completed = await coreInit({
9
9
  ...params,
10
10
  args: normalizeMedusaExecArgs(params.args || [], {
11
11
  boolean: ["yes", "force"],
@@ -21,6 +21,8 @@ export default async function runCoreInit(params: ExecArgs) {
21
21
  }),
22
22
  })
23
23
 
24
+ if (!completed) return
25
+
24
26
  await ensureLocales({
25
27
  ...params,
26
28
  args: [],
@@ -0,0 +1,35 @@
1
+ import type { Metadata } from "next"
2
+ import { Suspense } from "react"
3
+ import { AbandonedCartRecovery } from "@/components/abandoned-cart-recovery"
4
+ import { getCoreConfig } from "@/lib/core/client"
5
+ import { requestStorefrontLocale } from "@/lib/storefront-locale-server"
6
+
7
+ export const metadata: Metadata = {
8
+ title: "Kosár visszaállítása",
9
+ robots: {
10
+ index: false,
11
+ follow: false,
12
+ },
13
+ referrer: "no-referrer",
14
+ }
15
+
16
+ export default async function CartRecoveryPage() {
17
+ const [config, locale] = await Promise.all([
18
+ getCoreConfig(),
19
+ requestStorefrontLocale(),
20
+ ])
21
+
22
+ return (
23
+ <div className="page-section narrow-page">
24
+ <Suspense
25
+ fallback={(
26
+ <div className="empty-state">
27
+ {locale === "en" ? "Restoring your cart…" : "A kosarad visszaállítása…"}
28
+ </div>
29
+ )}
30
+ >
31
+ <AbandonedCartRecovery config={config} />
32
+ </Suspense>
33
+ </div>
34
+ )
35
+ }
@@ -0,0 +1,25 @@
1
+ import type { Metadata } from "next"
2
+ import { Suspense } from "react"
3
+ import { ReviewRequestForm } from "@/components/review-request-form"
4
+ import { getCoreConfig } from "@/lib/core/client"
5
+
6
+ export const metadata: Metadata = {
7
+ title: "Értékelés",
8
+ robots: {
9
+ index: false,
10
+ follow: false,
11
+ },
12
+ referrer: "no-referrer",
13
+ }
14
+
15
+ export default async function ReviewRequestPage() {
16
+ const config = await getCoreConfig()
17
+
18
+ return (
19
+ <div className="page-section narrow-page">
20
+ <Suspense fallback={<div className="empty-state">Értékelési link ellenőrzése…</div>}>
21
+ <ReviewRequestForm config={config} />
22
+ </Suspense>
23
+ </div>
24
+ )
25
+ }
@@ -0,0 +1,35 @@
1
+ import type { Metadata } from "next"
2
+ import { Suspense } from "react"
3
+ import { AccountActivationForm } from "@/components/account-activation-form"
4
+ import { getCoreConfig } from "@/lib/core/client"
5
+ import { requestStorefrontLocale } from "@/lib/storefront-locale-server"
6
+
7
+ export const metadata: Metadata = {
8
+ title: "Fiókaktiválás",
9
+ robots: {
10
+ index: false,
11
+ follow: false,
12
+ },
13
+ referrer: "no-referrer",
14
+ }
15
+
16
+ export default async function AccountActivationPage() {
17
+ const [config, locale] = await Promise.all([
18
+ getCoreConfig(),
19
+ requestStorefrontLocale(),
20
+ ])
21
+
22
+ return (
23
+ <div className="page-section narrow-page">
24
+ <Suspense
25
+ fallback={(
26
+ <div className="empty-state">
27
+ {locale === "en" ? "Checking activation link…" : "Aktiváló link ellenőrzése…"}
28
+ </div>
29
+ )}
30
+ >
31
+ <AccountActivationForm config={config} />
32
+ </Suspense>
33
+ </div>
34
+ )
35
+ }
@@ -0,0 +1,139 @@
1
+ "use client"
2
+
3
+ import Link from "next/link"
4
+ import { usePathname, useRouter, useSearchParams } from "next/navigation"
5
+ import { useEffect, useMemo, useRef, useState } from "react"
6
+ import { useCart } from "@/components/cart-provider"
7
+ import { abandonedCartApi } from "@/lib/core/abandoned-cart"
8
+ import { checkoutApi } from "@/lib/core/checkout"
9
+ import type { CoreConfig } from "@/lib/core/types"
10
+ import { localeFromPathname, STOREFRONT_ROUTES } from "@/lib/storefront-routes"
11
+
12
+ type RecoveryState = "checking" | "invalid" | "error"
13
+
14
+ export function AbandonedCartRecovery({ config }: { config: CoreConfig }) {
15
+ const pathname = usePathname()
16
+ const search = useSearchParams()
17
+ const router = useRouter()
18
+ const locale = localeFromPathname(pathname)
19
+ const routes = STOREFRONT_ROUTES[locale]
20
+ const recovery = useMemo(() => abandonedCartApi(config), [config])
21
+ const checkout = useMemo(() => checkoutApi(config), [config])
22
+ const { adoptCart, refresh } = useCart()
23
+ const started = useRef(false)
24
+ const [state, setState] = useState<RecoveryState>("checking")
25
+ const [reason, setReason] = useState<string | null>(null)
26
+ const [error, setError] = useState<string | null>(null)
27
+
28
+ useEffect(() => {
29
+ if (started.current) return
30
+ started.current = true
31
+
32
+ const token = search.get("token")?.trim() || ""
33
+ if (!token) {
34
+ setReason("missing")
35
+ setState("invalid")
36
+ return
37
+ }
38
+
39
+ void recovery
40
+ .recover(token)
41
+ .then(async (result) => {
42
+ if (!result.valid || !result.cart_id) {
43
+ setReason(result.reason || "invalid")
44
+ setState("invalid")
45
+ return
46
+ }
47
+
48
+ const cartId = result.cart_id
49
+ const adopted = await adoptCart(cartId)
50
+ if (!adopted) throw new Error(copy(locale).cartUnavailable)
51
+
52
+ if (result.coupon_code) {
53
+ try {
54
+ await checkout.addPromotion(cartId, result.coupon_code)
55
+ await refresh(cartId)
56
+ } catch {
57
+ // The cart itself is still recoverable if a promotion was already
58
+ // used, disabled or otherwise no longer applicable.
59
+ }
60
+ }
61
+
62
+ router.replace(routes.cart)
63
+ })
64
+ .catch((cause) => {
65
+ setError(cause instanceof Error ? cause.message : copy(locale).failed)
66
+ setState("error")
67
+ })
68
+ }, [adoptCart, checkout, locale, recovery, refresh, router, routes.cart, search])
69
+
70
+ const text = copy(locale)
71
+
72
+ if (state === "checking") {
73
+ return <div className="empty-state">{text.checking}</div>
74
+ }
75
+
76
+ if (state === "invalid") {
77
+ return (
78
+ <section className="panel stack narrow-card">
79
+ <div>
80
+ <p className="eyebrow">{text.eyebrow}</p>
81
+ <h1>{text.invalidTitle}</h1>
82
+ </div>
83
+ <p className="muted">{invalidReason(reason, locale)}</p>
84
+ <Link className="button button-large" href={routes.products}>
85
+ {text.shop}
86
+ </Link>
87
+ </section>
88
+ )
89
+ }
90
+
91
+ return (
92
+ <section className="panel stack narrow-card">
93
+ <div>
94
+ <p className="eyebrow">{text.eyebrow}</p>
95
+ <h1>{text.errorTitle}</h1>
96
+ </div>
97
+ <p className="error">{error || text.failed}</p>
98
+ <Link className="button button-large" href={routes.products}>
99
+ {text.shop}
100
+ </Link>
101
+ </section>
102
+ )
103
+ }
104
+
105
+ function invalidReason(reason: string | null, locale: "hu" | "en") {
106
+ if (locale === "en") {
107
+ if (reason === "completed") return "This cart has already been checked out."
108
+ if (reason === "empty") return "This cart is empty and can no longer be restored."
109
+ if (reason === "missing") return "The recovery link is incomplete. Open the full link from the email."
110
+ return "This cart recovery link is invalid or has expired."
111
+ }
112
+
113
+ if (reason === "completed") return "Ebből a kosárból már rendelés készült."
114
+ if (reason === "empty") return "Ez a kosár már üres, ezért nem állítható vissza."
115
+ if (reason === "missing") return "A visszaállító link hiányos. Nyisd meg az e-mailben kapott teljes hivatkozást."
116
+ return "Ez a kosár-visszaállító link érvénytelen vagy lejárt."
117
+ }
118
+
119
+ function copy(locale: "hu" | "en") {
120
+ return locale === "en"
121
+ ? {
122
+ eyebrow: "Cart recovery",
123
+ checking: "Restoring your cart…",
124
+ invalidTitle: "This recovery link is no longer available",
125
+ errorTitle: "Your cart could not be restored",
126
+ failed: "Cart recovery failed.",
127
+ cartUnavailable: "The recovered cart is no longer available.",
128
+ shop: "Continue shopping",
129
+ }
130
+ : {
131
+ eyebrow: "Kosár visszaállítása",
132
+ checking: "A kosarad visszaállítása…",
133
+ invalidTitle: "Ez a visszaállító link már nem használható",
134
+ errorTitle: "A kosár visszaállítása nem sikerült",
135
+ failed: "A kosár visszaállítása nem sikerült.",
136
+ cartUnavailable: "A visszaállított kosár már nem érhető el.",
137
+ shop: "Vásárlás folytatása",
138
+ }
139
+ }