@hszrdm/create-commerce 1.8.0 → 1.9.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hszrdm/create-commerce",
3
- "version": "1.8.0",
3
+ "version": "1.9.1",
4
4
  "description": "Create a complete HSZRDM Commerce webshop project.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
package/src/cli.mjs CHANGED
@@ -234,17 +234,60 @@ function configureProject(root, settings) {
234
234
  "core:init": "npm --workspace backend run core:init --",
235
235
  "storefront:key": "npm --workspace backend run storefront:key --",
236
236
  "bootstrap:assert": "npm --workspace backend run bootstrap:assert",
237
+ "install:dev": "node ./scripts/commerce-ops.mjs install dev",
238
+ "install:prod": "node ./scripts/commerce-ops.mjs install prod",
239
+ "deploy:dev": "node ./scripts/commerce-ops.mjs deploy dev",
240
+ "deploy:prod": "node ./scripts/commerce-ops.mjs deploy prod",
241
+ "backup:dev": "node ./scripts/commerce-ops.mjs backup dev",
242
+ "backup:prod": "node ./scripts/commerce-ops.mjs backup prod",
243
+ "restore:dev": "node ./scripts/commerce-ops.mjs restore dev",
244
+ "restore:prod": "node ./scripts/commerce-ops.mjs restore prod",
237
245
  "docker:up": "docker compose --env-file .env.docker up -d --wait",
238
246
  "docker:down": "docker compose --env-file .env.docker down"
239
247
  },
240
248
  }
241
249
  writeJson(join(root, "package.json"), rootPackage)
250
+ mkdirSync(join(root, "scripts"), { recursive: true })
251
+ cpSync(join(root, "backend", "scripts", "commerce-ops.mjs"),
252
+ join(root, "scripts", "commerce-ops.mjs"))
253
+ writeFileSync(join(root, "ecosystem.config.cjs"), `module.exports = {
254
+ apps: [
255
+ {
256
+ name: ${JSON.stringify(settings.slug + "-backend")},
257
+ cwd: __dirname,
258
+ script: "npm",
259
+ args: "--workspace backend run start:prod",
260
+ env_production: {
261
+ NODE_ENV: "production",
262
+ APP_ENV: "production",
263
+ PORT: ${JSON.stringify(new URL(settings.backendUrl).port || "9000")},
264
+ HOST: "127.0.0.1",
265
+ },
266
+ },
267
+ {
268
+ name: ${JSON.stringify(settings.slug + "-storefront")},
269
+ cwd: __dirname,
270
+ script: "npm",
271
+ args: "--workspace storefront run start",
272
+ env_production: {
273
+ NODE_ENV: "production",
274
+ APP_ENV: "production",
275
+ PORT: ${JSON.stringify(new URL(settings.storefrontUrl).port || "3000")},
276
+ HOSTNAME: "127.0.0.1",
277
+ },
278
+ },
279
+ ],
280
+ }
281
+ `)
282
+
242
283
  writeFileSync(join(root, ".nvmrc"), "22\n")
243
284
  writeFileSync(
244
285
  join(root, ".gitignore"),
245
286
  [
246
287
  "node_modules/",
247
288
  "backend/.env",
289
+ "backend/.env.production",
290
+ "storefront/.env.production",
248
291
  "backend/.medusa/",
249
292
  "backend/src/api",
250
293
  "backend/src/jobs",
@@ -278,7 +321,18 @@ function configureProject(root, settings) {
278
321
 
279
322
  writeFileSync(
280
323
  join(root, "README.md"),
281
- `# ${settings.storeName}\n\nGenerated by @hszrdm/create-commerce.\n\n## Development\n\n\`npm run docker:up\`\n\`npm run dev:backend\`\n\`npm run dev:storefront\`\n\nProject-specific backend code belongs in \`backend/src/project/\`. Shared commerce behavior comes from \`@hszrdm/core\`.\n`,
324
+ `# ${settings.storeName}\n\nGenerated by @hszrdm/create-commerce.\n\n## Development\n\n\`npm run docker:up\`\n\`npm run dev:backend\`\n\`npm run dev:storefront\`\n\n## Environment operations
325
+
326
+ Development uses \`backend/.env\` and a separate development PostgreSQL database:
327
+ \`npm run install:dev\`, \`npm run deploy:dev\`, \`npm run backup:dev\`.
328
+ Production requires an independently configured \`backend/.env.production\` and PM2:
329
+ \`npm run install:prod\`, \`npm run deploy:prod\`, \`npm run backup:prod\`.
330
+ Restore is dry-run by default: \`npm run restore:dev -- --from backups/dev/<bundle>\`
331
+ or \`npm run restore:prod -- --from backups/prod/<bundle>\`.
332
+ Only add \`--yes\` after checking the target database; a restore can delete existing data.
333
+ Do not point development and production at the same PostgreSQL database.
334
+
335
+ Project-specific backend code belongs in \`backend/src/project/\`. Shared commerce behavior comes from \`@hszrdm/core\`.\n`,
282
336
  )
283
337
  }
284
338
 
@@ -318,6 +372,9 @@ function configureBackend(root, settings) {
318
372
  AUTH_CORS: `${settings.storefrontUrl},${settings.backendUrl}`,
319
373
  INTEGRATION_SETTINGS_ENCRYPTION_KEY: settings.integrationEncryptionKey,
320
374
  SHIPPING_WEBHOOK_SECRET: settings.shippingWebhookSecret,
375
+ FOXPOST_PACKAGE_SIZE: "M",
376
+ SHIPPING_STATUS_SYNC_ENABLED: "true",
377
+ SHIPPING_STATUS_SYNC_BATCH_SIZE: "100",
321
378
  STORE_NAME: settings.storeName,
322
379
  STORE_SLUG: settings.slug,
323
380
  STORE_LOCALE: settings.locale,
@@ -238,22 +238,32 @@ BILLINGO_LANGUAGE=hu
238
238
  BILLINGO_ELECTRONIC=true
239
239
  BILLINGO_DUE_DAYS=0
240
240
  BILLINGO_UNIT=db
241
- BILLINGO_TIMEOUT_MS=15000
241
+ BILLINGO_TIMEOUT_MS=30000
242
242
  BILLINGO_AUTO_INVOICE=true
243
243
  BILLINGO_AUTO_SEND=true
244
244
  BILLINGO_AUTO_CANCEL_ON_ORDER_CANCELED=false
245
245
  BILLINGO_INVOICE_TRIGGER=payment_captured
246
246
 
247
247
  # -----------------------------------------------------------------------------
248
+ # Background carrier status sync: FOXPOST, GLS, Packeta, Csomagpiac every 30 minutes.
249
+ # MPL uses its hourly PULL job when MPL_TRACKING_ENABLED=true;
250
+ # DPD uses its dedicated Statusdata FTP job when DPD_STATUSDATA_ENABLED=true.
251
+ SHIPPING_STATUS_SYNC_ENABLED=true
252
+ SHIPPING_STATUS_SYNC_BATCH_SIZE=100
253
+
248
254
  # Shipping fallback/bootstrap settings
249
255
  # Prefer Admin -> Settings -> Integrációk.
250
256
  # -----------------------------------------------------------------------------
251
257
  FOXPOST_ENABLED=false
258
+ # FOXPOST_API_URL üresen: a sandbox kapcsoló alapján automatikus teszt/éles végpont.
259
+ # Egyedi környezetben itt felülírható.
252
260
  FOXPOST_API_URL=
253
261
  FOXPOST_API_USERNAME=
254
262
  FOXPOST_API_PASSWORD=
255
263
  FOXPOST_API_KEY=
256
264
  FOXPOST_SANDBOX=true
265
+ # Fixed FOXPOST parcel size sent during Create Fulfillment (XS/S/M/L/XL); default M.
266
+ FOXPOST_PACKAGE_SIZE=M
257
267
  FOXPOST_LOCKER_FEED_URL=https://cdn.foxpost.hu/foxplus.json
258
268
  FOXPOST_LOCKER_PRICE_HUF=1290
259
269
  FOXPOST_HOME_DELIVERY_PRICE_HUF=1990
@@ -15,19 +15,20 @@
15
15
  "core:backup": "node ./scripts/core-backup.mjs --project-dir .",
16
16
  "core:restore": "node ./scripts/core-restore.mjs --project-dir .",
17
17
  "storefront:key": "npm run prepare:project && medusa exec ./src/scripts/create-storefront-key.ts",
18
+ "runtime:verify": "npm run prepare:project && medusa exec ./src/scripts/verify-runtime-modules.ts",
18
19
  "bootstrap:assert": "npm run prepare:project && medusa exec ./src/scripts/verify-bootstrap.ts",
19
20
  "db:migrate": "npm run prepare:project && medusa db:migrate",
20
21
  "db:generate": "npm run prepare:project && medusa db:generate",
21
22
  "start:prod": "cd .medusa/server && medusa start"
22
23
  },
23
24
  "dependencies": {
24
- "@hszrdm/core": "1.8.0",
25
- "@medusajs/admin-sdk": "2.21.2",
26
- "@medusajs/cli": "2.21.2",
27
- "@medusajs/draft-order": "2.21.2",
28
- "@medusajs/framework": "2.21.2",
29
- "@medusajs/medusa": "2.21.2",
30
- "@medusajs/ui": "4.2.6",
25
+ "@hszrdm/core": "1.9.1",
26
+ "@medusajs/admin-sdk": "2.22.2",
27
+ "@medusajs/cli": "2.22.2",
28
+ "@medusajs/draft-order": "2.22.2",
29
+ "@medusajs/framework": "2.22.2",
30
+ "@medusajs/medusa": "2.22.2",
31
+ "@medusajs/ui": "4.2.9",
31
32
  "react": "^18.3.1",
32
33
  "react-dom": "^18.3.1",
33
34
  "react-router-dom": "7.18.2"
@@ -0,0 +1,116 @@
1
+ #!/usr/bin/env node
2
+ // Shared development/production operations for generated HSZRDM shops.
3
+ // Environment selection is explicit: never reuse a production database in dev.
4
+ import { existsSync, readFileSync } from "node:fs"
5
+ import { resolve, join } from "node:path"
6
+ import { spawnSync, spawn } from "node:child_process"
7
+
8
+ const [action, target, ...rest] = process.argv.slice(2)
9
+ if (!["install", "deploy", "backup", "restore"].includes(action) || !["dev", "prod"].includes(target)) {
10
+ console.error("Usage: node scripts/commerce-ops.mjs <install|deploy|backup|restore> <dev|prod> [--from ...] [--yes]")
11
+ process.exit(2)
12
+ }
13
+ const root = process.cwd()
14
+ const backendDir = existsSync(join(root, "backend")) ? join(root, "backend") : join(root, "apps/backend")
15
+ const envPath = join(backendDir, target === "prod" ? ".env.production" : ".env")
16
+ if (!existsSync(envPath)) throw new Error(`Missing ${envPath}. Configure it before ${target} operations.`)
17
+ const envFile = parseEnv(readFileSync(envPath, "utf8"))
18
+ const expectedApp = target === "prod" ? "production" : "development"
19
+ const expectedNode = target === "prod" ? "production" : "development"
20
+ if (envFile.APP_ENV && envFile.APP_ENV !== expectedApp) {
21
+ throw new Error(`Environment mismatch: expected APP_ENV=${expectedApp} in ${envPath}`)
22
+ }
23
+ if (envFile.NODE_ENV && envFile.NODE_ENV !== expectedNode) {
24
+ throw new Error(`Environment mismatch: expected NODE_ENV=${expectedNode} in ${envPath}`)
25
+ }
26
+ if (!envFile.DATABASE_URL) throw new Error(`DATABASE_URL is missing from ${envPath}`)
27
+ const dbName = databaseIdentity(envFile.DATABASE_URL)
28
+ const otherPath = join(backendDir, target === "prod" ? ".env" : ".env.production")
29
+ if (existsSync(otherPath)) {
30
+ const other = parseEnv(readFileSync(otherPath, "utf8"))
31
+ if (other.DATABASE_URL && databaseIdentity(other.DATABASE_URL) === dbName) {
32
+ throw new Error("Dev and prod may not share the same database connection.")
33
+ }
34
+ }
35
+ const env = { ...process.env, ...envFile, APP_ENV: expectedApp, NODE_ENV: expectedNode }
36
+ console.log(`HSZRDM ${action}:${target} | DB: ${new URL(envFile.DATABASE_URL).pathname.slice(1)}`)
37
+
38
+ function run(command, args) {
39
+ const result = spawnSync(command, args, { cwd: root, env, stdio: "inherit" })
40
+ if (result.error) throw result.error
41
+ if (result.status !== 0) process.exit(result.status || 1)
42
+ }
43
+ function npm(args) { run(process.platform === "win32" ? "npm.cmd" : "npm", args) }
44
+ function backupScript() {
45
+ const candidates = [join(root, "scripts/core-backup.mjs"), join(backendDir, "scripts/core-backup.mjs")]
46
+ const path = candidates.find(existsSync)
47
+ if (!path) throw new Error("Core backup script not installed.")
48
+ return path
49
+ }
50
+ function restoreScript() {
51
+ const candidates = [join(root, "scripts/core-restore.mjs"), join(backendDir, "scripts/core-restore.mjs")]
52
+ const path = candidates.find(existsSync)
53
+ if (!path) throw new Error("Core restore script not installed.")
54
+ return path
55
+ }
56
+ function backup() {
57
+ run(process.execPath, [backupScript(), "--project-dir", root,
58
+ "--database-url", envFile.DATABASE_URL, "--output", join(root, "backups", target)])
59
+ }
60
+ function parseEnv(src) {
61
+ const result = {}
62
+ for (const line of src.split(/\r?\n/)) {
63
+ const m = line.match(/^\s*([A-Z][A-Z0-9_]*)\s*=\s*(.*?)\s*$/)
64
+ if (!m) continue
65
+ const v = m[2]
66
+ result[m[1]] = (v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'")) ? v.slice(1, -1) : v
67
+ }
68
+ return result
69
+ }
70
+ function databaseIdentity(value) {
71
+ const u = new URL(value)
72
+ if (!["postgres:", "postgresql:"].includes(u.protocol)) throw new Error("DATABASE_URL must be PostgreSQL.")
73
+ return `${u.hostname.toLowerCase()}:${u.port || "5432"}/${decodeURIComponent(u.pathname)}`
74
+ }
75
+ function devServer() {
76
+ const children = []
77
+ const cmd = process.platform === "win32" ? "npm.cmd" : "npm"
78
+ for (const name of ["dev:backend", "dev:storefront"]) {
79
+ children.push(spawn(cmd, ["run", name], { cwd: root, env, stdio: "inherit" }))
80
+ }
81
+ function stop() { for (const child of children) child.kill("SIGTERM") }
82
+ process.on("SIGINT", stop)
83
+ process.on("SIGTERM", stop)
84
+ for (const child of children) child.on("exit", (code) => {
85
+ if (code && !process.exitCode) process.exitCode = code
86
+ stop()
87
+ })
88
+ }
89
+ if (action === "backup") backup()
90
+ if (action === "restore") {
91
+ if (!rest.includes("--from")) throw new Error("Restore requires --from <backup-directory>.")
92
+ const fromIndex = rest.indexOf("--from")
93
+ const from = rest[fromIndex + 1]
94
+ if (!from || from.startsWith("--")) throw new Error("Restore --from path missing.")
95
+ // Explicit --yes is still required by core-restore for destructive restore.
96
+ run(process.execPath, [restoreScript(), "--project-dir", root,
97
+ "--database-url", envFile.DATABASE_URL, "--from", resolve(from),
98
+ ...(rest.includes("--yes") ? ["--yes"] : []),
99
+ ...(rest.includes("--overwrite-files") ? ["--overwrite-files"] : [])])
100
+ }
101
+ if (action === "install") npm(["ci"])
102
+ if (action === "deploy") {
103
+ npm(["ci"])
104
+ backup()
105
+ npm(["run", "db:migrate"])
106
+ if (target === "dev") {
107
+ devServer()
108
+ } else {
109
+ npm(["run", "build"])
110
+ if (!existsSync(join(root, "ecosystem.config.cjs"))) {
111
+ throw new Error("Missing ecosystem.config.cjs: cannot safely reload production PM2.")
112
+ }
113
+ run("pm2", ["startOrReload", "ecosystem.config.cjs", "--env", "production", "--update-env"])
114
+ run("pm2", ["save"])
115
+ }
116
+ }
@@ -0,0 +1,55 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, readFileSync, writeFileSync, copyFileSync, chmodSync, statSync } from "node:fs"
3
+ import { resolve } from "node:path"
4
+ import { fileURLToPath } from "node:url"
5
+
6
+ /** Idempotent: only append keys missing from the actual env; never override secrets. */
7
+ export function syncMissingEnvKeys(examplePath, envPath) {
8
+ if (!existsSync(examplePath)) throw new Error("Missing .env.example: " + examplePath)
9
+ if (!existsSync(envPath)) throw new Error("Missing existing .env file: " + envPath)
10
+ const template = readFileSync(examplePath, "utf8")
11
+ const current = readFileSync(envPath, "utf8")
12
+ const extract = (source, name) => {
13
+ const values = new Map()
14
+ for (const raw of source.split(/\r?\n/)) {
15
+ const match = raw.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/)
16
+ if (!match) continue
17
+ if (values.has(match[1])) throw new Error("Duplicate " + name + " env key: " + match[1])
18
+ values.set(match[1], match[2])
19
+ }
20
+ return values
21
+ }
22
+ const exampleKeys = extract(template, "example")
23
+ const currentKeys = extract(current, "current")
24
+ const missing = [...exampleKeys.entries()].filter(([key]) => !currentKeys.has(key))
25
+ if (!missing.length) return { added: [], changed: false }
26
+ // Only the original .env is modified, never the canonical template.
27
+ // A backup is made before any modification. Do not log configuration values.
28
+ const backup = envPath + ".bak"
29
+ copyFileSync(envPath, backup)
30
+ chmodSync(backup, 0o600)
31
+ const additions = missing.map(([key, value]) => key + "=" + value).join("\n")
32
+ const updated = current + (current.endsWith("\n") ? "" : "\n") +
33
+ "\n# Missing keys automatically added from .env.example\n" + additions + "\n"
34
+ writeFileSync(envPath, updated, { mode: statSync(envPath).mode & 0o777 })
35
+ return { added: missing.map(([key]) => key), changed: true, backup }
36
+ }
37
+
38
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
39
+ const example = process.argv[2]
40
+ const env = process.argv[3]
41
+ if (!example || !env) {
42
+ console.error("Usage: node sync-env-example.mjs <example-file> <existing-env-file>")
43
+ process.exitCode = 64
44
+ } else {
45
+ try {
46
+ const result = syncMissingEnvKeys(example, env)
47
+ console.log(result.changed
48
+ ? "Environment synchronized: " + result.added.length + " missing keys added; backup created."
49
+ : "Environment already contains all example keys.")
50
+ } catch (error) {
51
+ console.error(error instanceof Error ? error.message : String(error))
52
+ process.exitCode = 1
53
+ }
54
+ }
55
+ }
@@ -2,6 +2,7 @@
2
2
 
3
3
  import { existsSync, readFileSync } from "node:fs"
4
4
  import { resolve } from "node:path"
5
+ import { syncMissingEnvKeys } from "./sync-env-example.mjs"
5
6
 
6
7
  const backendRoot = resolve(import.meta.dirname, "..")
7
8
  const examplePath = resolve(backendRoot, ".env.example")
@@ -15,16 +16,16 @@ if (!existsSync(envPath)) {
15
16
  throw new Error(`Hiányzik a backend .env: ${envPath}`)
16
17
  }
17
18
 
19
+ const syncResult = syncMissingEnvKeys(examplePath, envPath)
20
+ if (syncResult.changed) console.log(`Added ${syncResult.added.length} missing keys from .env.example; previous env backed up.`)
21
+
18
22
  const exampleKeys = envKeys(readFileSync(examplePath, "utf8"))
19
23
  const envKeysActual = envKeys(readFileSync(envPath, "utf8"))
20
24
 
21
25
  const missing = exampleKeys.filter((key) => !envKeysActual.includes(key))
22
- const extra = envKeysActual.filter((key) => !exampleKeys.includes(key))
23
-
24
- if (missing.length || extra.length) {
26
+ if (missing.length) {
25
27
  const details = [
26
28
  missing.length ? `Hiányzik a .env-ből: ${missing.join(", ")}` : "",
27
- extra.length ? `Nincs benne a .env.example-ban: ${extra.join(", ")}` : "",
28
29
  ].filter(Boolean)
29
30
 
30
31
  throw new Error(
@@ -32,7 +33,7 @@ if (missing.length || extra.length) {
32
33
  )
33
34
  }
34
35
 
35
- console.log(`✅ Env contract rendben: ${exampleKeys.length} kulcs 1:1 megegyezik.`)
36
+ console.log(`✅ Env contract rendben: ${exampleKeys.length} template kulcs elérhető; egyedi .env kulcsok megőrizve.`)
36
37
 
37
38
  function envKeys(source) {
38
39
  const keys = []
@@ -0,0 +1 @@
1
+ export { default } from "@hszrdm/core/scripts/verify-runtime-modules"
@@ -3,3 +3,9 @@
3
3
  MEDUSA_BACKEND_URL=http://localhost:9000
4
4
  NEXT_PUBLIC_MEDUSA_BACKEND_URL=http://localhost:9000
5
5
  NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=
6
+
7
+ # Public widget key from Packeta Client (never use Packeta API password here).
8
+ NEXT_PUBLIC_PACKETA_WIDGET_API_KEY=
9
+
10
+ # Browser-restricted Google Maps API key for the MPL PostaPont legacy map.
11
+ NEXT_PUBLIC_GOOGLE_MAPS_API_KEY=
@@ -0,0 +1,3 @@
1
+ MEDUSA_BACKEND_URL=http://localhost:9000
2
+ NEXT_PUBLIC_MEDUSA_BACKEND_URL=http://localhost:9000
3
+ NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=pk_ebe31eec729cb9d2f557923b99c76c765eece8378eec3bf566c6ef527fd8419d
@@ -6,7 +6,8 @@
6
6
  "dev": "next dev",
7
7
  "build": "next build",
8
8
  "start": "next start",
9
- "typecheck": "tsc --noEmit"
9
+ "typecheck": "tsc --noEmit",
10
+ "test:pickup": "node --experimental-strip-types --test tests/carrier-pickup-adapter.test.mjs"
10
11
  },
11
12
  "dependencies": {
12
13
  "@stripe/react-stripe-js": "7.0.0",
@@ -0,0 +1,93 @@
1
+ export type CarrierPickupKind = "foxpost" | "gls" | "packeta" | "dpd" | "mpl"
2
+
3
+ export type CarrierPickupPoint = {
4
+ id: string
5
+ name: string
6
+ postalCode: string
7
+ city: string
8
+ address: string
9
+ provider: CarrierPickupKind
10
+ type?: string
11
+ raw: Record<string, unknown>
12
+ }
13
+
14
+ function record(value: unknown): Record<string, unknown> {
15
+ return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {}
16
+ }
17
+
18
+ function str(...values: unknown[]) {
19
+ for (const value of values) {
20
+ if (typeof value === "string" && value.trim()) return value.trim()
21
+ if (typeof value === "number" && Number.isFinite(value)) return String(value)
22
+ }
23
+ return ""
24
+ }
25
+
26
+ function addressText(value: unknown) {
27
+ if (typeof value === "string") return value.trim()
28
+ const item = record(value)
29
+ return str(item.street, item.address, [item.streetName, item.houseNumber].filter(Boolean).join(" "))
30
+ }
31
+
32
+ /** Provider-specific widget results are adapted to the same checkout model. */
33
+ export function normalizeCarrierPickupPoint(provider: CarrierPickupKind, value: unknown): CarrierPickupPoint | null {
34
+ const raw = record(value)
35
+ const contact = record(raw.contact)
36
+ const location = record(raw.location)
37
+ const addr = record(raw.address)
38
+ const address = provider === "gls" ? str(contact.address, addressText(raw.address)) :
39
+ provider === "dpd" ? str(raw.street, raw.address, location.address, addr.street, addr.address, [raw.street, raw.houseNo].filter(Boolean).join(" ")) :
40
+ provider === "foxpost" ? str(raw.address, raw.street) :
41
+ str(raw.address, raw.street, location.address, addr.street)
42
+ const id = provider === "foxpost" ? str(raw.operator_id, raw.operatorId, raw.place_id, raw.placeId) :
43
+ provider === "dpd" ? str(raw.id, raw.pickupPointId, raw.pudoId, raw.pudo_id, raw.parcelShopId, location.id) :
44
+ str(raw.id, raw.addressId, raw.location_id, raw.code)
45
+ const name = str(raw.name, raw.label, raw.shop_name, raw.title, contact.name, location.name)
46
+ const postalCode = str(raw.zip, raw.postalCode, raw.postCode, raw.post_code, raw.zipCode, raw.postal_code, contact.postalCode, location.zip, addr.zip)
47
+ const city = str(raw.city, contact.city, raw.country, raw.town, location.city, addr.city)
48
+ if (!id || !name || !postalCode || !city || !address) return null
49
+ return { id, name, postalCode, city, address, provider, type: str(raw.variant, raw.type, raw.group), raw }
50
+ }
51
+
52
+ /** Map fields to the existing Medusa fulfillment providers; preserve native IDs. */
53
+ export function carrierPointToShippingData(point: CarrierPickupPoint): Record<string, unknown> {
54
+ const p = point.raw
55
+ switch (point.provider) {
56
+ case "foxpost":
57
+ return { foxpost: { locker: {
58
+ operatorId: str(p.operator_id, p.operatorId) || null,
59
+ placeId: str(p.place_id, p.placeId) || null,
60
+ name: point.name, postalCode: point.postalCode, city: point.city,
61
+ address: point.address, findMe: str(p.findme, p.findMe) || null,
62
+ }, packageSize: "M" } }
63
+ case "gls":
64
+ return { gls: { deliveryPoint: {
65
+ id: point.id, name: point.name, countryCode: str(record(p.contact).countryCode, p.countryCode, "HU"),
66
+ postalCode: point.postalCode, city: point.city, address: point.address,
67
+ type: point.type === "parcel-shop" || point.type === "parcel-locker" ? point.type : null,
68
+ } } }
69
+ case "packeta":
70
+ return { packeta: { pickupPoint: {
71
+ id: point.id, name: point.name,
72
+ ...(str(p.carrierId, p.carrier_id) ? { carrierId: str(p.carrierId, p.carrier_id) } : {}),
73
+ ...(str(p.carrierPickupPoint, p.carrier_pickup_point) ? { carrierPickupPoint: str(p.carrierPickupPoint, p.carrier_pickup_point) } : {}),
74
+ } } }
75
+ case "dpd":
76
+ return { dpd: { pickupPoint: {
77
+ id: point.id, name: point.name,
78
+ countryCode: str(p.countryCode, p.country_code, "HU"),
79
+ zipCode: point.postalCode, city: point.city,
80
+ street: str(p.street, point.address), houseNo: str(p.houseNo, p.house_no),
81
+ ...(Number.isInteger(Number(p.parcelShopId)) && Number(p.parcelShopId) > 0 ? { parcelShopId: Number(p.parcelShopId) } : {}),
82
+ } } }
83
+ case "mpl":
84
+ return { mpl: { pickupPoint: {
85
+ id: point.id, name: point.name,
86
+ postCode: point.postalCode, city: point.city, address: point.address,
87
+ deliveryMode: str(p.deliveryMode, p.delivery_mode) ||
88
+ (str(p.group).includes("csomagautomata") ? "CS" : "PM"),
89
+ servicePointType: str(p.group, p.servicePointType) || undefined,
90
+ } } }
91
+ }
92
+ }
93
+
@@ -0,0 +1,119 @@
1
+ "use client"
2
+
3
+ import { useEffect, useId, useRef, useState } from "react"
4
+ import { createPortal } from "react-dom"
5
+ import { CarrierPickupMap, type CarrierPickupKind, type CarrierPickupPoint } from "./carrier-pickup-map"
6
+
7
+ type Props = {
8
+ carrier: CarrierPickupKind
9
+ selected: CarrierPickupPoint | null
10
+ postalCode: string
11
+ locale: "hu" | "en"
12
+ onSelect: (point: CarrierPickupPoint) => void
13
+ onClose: () => void
14
+ }
15
+
16
+ const carrierLabels: Record<CarrierPickupKind, string> = {
17
+ foxpost: "FOXPOST",
18
+ gls: "GLS",
19
+ packeta: "Packeta",
20
+ dpd: "DPD",
21
+ mpl: "MPL / PostaPont",
22
+ }
23
+
24
+ export function CarrierPickupDialog({ carrier, selected, postalCode, locale, onSelect, onClose }: Props) {
25
+ const titleId = useId()
26
+ const closeRef = useRef<HTMLButtonElement>(null)
27
+ const previousFocus = useRef<HTMLElement | null>(null)
28
+ const [mounted, setMounted] = useState(false)
29
+
30
+ useEffect(() => {
31
+ previousFocus.current = document.activeElement instanceof HTMLElement
32
+ ? document.activeElement : null
33
+ const oldOverflow = document.body.style.overflow
34
+ document.body.style.overflow = "hidden"
35
+ setMounted(true)
36
+ return () => {
37
+ document.body.style.overflow = oldOverflow
38
+ previousFocus.current?.focus()
39
+ }
40
+ }, [])
41
+
42
+ useEffect(() => {
43
+ if (!mounted) return
44
+ closeRef.current?.focus()
45
+ const handleKeyDown = (event: KeyboardEvent) => {
46
+ if (event.key === "Escape") {
47
+ // The Packeta native picker may handle its own Escape key.
48
+ if (carrier !== "packeta") {
49
+ event.preventDefault()
50
+ onClose()
51
+ }
52
+ return
53
+ }
54
+ if (event.key !== "Tab" || carrier === "packeta") return
55
+ const dialog = document.getElementById(titleId)?.closest<HTMLElement>('[role="dialog"]')
56
+ if (!dialog) return
57
+ const focusable = Array.from(dialog.querySelectorAll<HTMLElement>(
58
+ 'button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), iframe, [tabindex]:not([tabindex="-1"])'
59
+ )).filter((element) => element.getClientRects().length > 0)
60
+ if (!focusable.length) return
61
+ const first = focusable[0]
62
+ const last = focusable[focusable.length - 1]
63
+ if (event.shiftKey && document.activeElement === first) {
64
+ event.preventDefault()
65
+ last.focus()
66
+ } else if (!event.shiftKey && document.activeElement === last) {
67
+ event.preventDefault()
68
+ first.focus()
69
+ }
70
+ }
71
+ document.addEventListener("keydown", handleKeyDown)
72
+ return () => document.removeEventListener("keydown", handleKeyDown)
73
+ }, [carrier, mounted, onClose, titleId])
74
+
75
+ const choose = (point: CarrierPickupPoint | null) => {
76
+ if (!point) return
77
+ onSelect(point)
78
+ onClose()
79
+ }
80
+
81
+ if (!mounted) return null
82
+
83
+ return createPortal(
84
+ <>
85
+ <style>{`
86
+ .hszrdm-pickup-overlay { position: fixed; inset: 0; z-index: 1000; display: flex; align-items: center; justify-content: center; padding: 16px; background: rgba(9, 15, 27, .76); backdrop-filter: blur(4px); box-sizing: border-box; }
87
+ .hszrdm-pickup-window { box-sizing: border-box; position: relative; display: flex; flex-direction: column; width: min(960px, 100%); max-height: calc(100dvh - 32px); margin: auto; padding: 0; border: 1px solid rgba(128, 128, 128, .3); border-radius: 16px; background: var(--surface, #fff); color: var(--text, #20242b); box-shadow: 0 28px 90px rgba(0, 0, 0, .35); overflow: hidden; }
88
+ .hszrdm-pickup-header { flex: none; display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 16px 20px; border-bottom: 1px solid rgba(128, 128, 128, .25); }
89
+ .hszrdm-pickup-body { flex: 1 1 auto; min-height: 0; overflow: auto; padding: 16px 20px 22px; }
90
+ .hszrdm-pickup-title { margin: 0; font-size: 1.15rem; font-weight: 700; }
91
+ .hszrdm-pickup-close { flex: none; cursor: pointer; border: 1px solid rgba(128, 128, 128, .45); border-radius: 9px; min-width: 40px; min-height: 40px; background: transparent; color: inherit; font-size: 24px; line-height: 1; }
92
+ @media (max-width: 640px) {
93
+ .hszrdm-pickup-overlay { padding: 0; }
94
+ .hszrdm-pickup-window { width: 100%; height: 100dvh; max-height: 100dvh; border: 0; border-radius: 0; }
95
+ .hszrdm-pickup-header { padding: 12px 16px; }
96
+ .hszrdm-pickup-body { padding: 12px; }
97
+ }
98
+ `}</style>
99
+ <div className="hszrdm-pickup-overlay"
100
+ onMouseDown={(event) => { if (event.target === event.currentTarget) onClose() }}>
101
+ <section className="hszrdm-pickup-window" role="dialog" aria-modal="true"
102
+ aria-labelledby={titleId}>
103
+ <div className="hszrdm-pickup-header">
104
+ <h2 id={titleId} className="hszrdm-pickup-title">
105
+ {carrierLabels[carrier]} – {locale === "en" ? "Choose a pickup point" : "Csomagpont kiválasztása"}
106
+ </h2>
107
+ <button ref={closeRef} type="button" className="hszrdm-pickup-close"
108
+ onClick={onClose} aria-label={locale === "en" ? "Close map" : "Térkép bezárása"}>×</button>
109
+ </div>
110
+ <div className="hszrdm-pickup-body">
111
+ <CarrierPickupMap carrier={carrier} locale={locale} postalCode={postalCode}
112
+ selected={selected} onSelect={choose} autoOpen />
113
+ </div>
114
+ </section>
115
+ </div>
116
+ </>,
117
+ document.body,
118
+ )
119
+ }
@@ -0,0 +1,200 @@
1
+ "use client"
2
+
3
+ import { useCallback, useEffect, useId, useRef, useState } from "react"
4
+
5
+ import { normalizeCarrierPickupPoint, type CarrierPickupKind, type CarrierPickupPoint } from "./carrier-pickup-adapter"
6
+ export { carrierPointToShippingData } from "./carrier-pickup-adapter"
7
+ export type { CarrierPickupKind, CarrierPickupPoint } from "./carrier-pickup-adapter"
8
+
9
+ type WidgetGlobals = Window & {
10
+ Packeta?: { Widget?: { pick: (key: string, callback: (point: unknown) => void, options: Record<string, unknown>) => void; close?: () => void } }
11
+ ppapi?: {
12
+ linkZipField: (id: string) => void
13
+ insertMap: (id: string) => void
14
+ onSelect?: (point: unknown) => void
15
+ showAllFilters?: boolean
16
+ }
17
+ jQuery?: unknown
18
+ }
19
+
20
+ const FOXPOST_ORIGIN = "https://cdn.foxpost.hu"
21
+ const DPD_ORIGIN = "https://api.dpd.cz"
22
+ const FOXPOST_WIDGET = "https://cdn.foxpost.hu/apt-finder/v1/app/"
23
+ const DPD_WIDGET = "https://api.dpd.cz/widget/latest/index.html?enabledCountries=HU&countries=HU&lang=hu&hideCloseButton=true"
24
+ const GLS_SCRIPT = "https://map.gls-hungary.com/widget/gls-dpm.js"
25
+ const PACKETA_SCRIPT = "https://widget.packeta.com/v6/www/js/library.js"
26
+ const POSTA_SCRIPT = "https://posta.hu/szolgaltatasok/postoffice/static/script/ppapi/postapont-api.js"
27
+ const POSTA_CSS = "https://posta.hu/szolgaltatasok/postoffice/static/css/ppapi/postapont-api.css"
28
+
29
+ function record(value: unknown): Record<string, unknown> {
30
+ return value !== null && typeof value === "object" && !Array.isArray(value)
31
+ ? (value as Record<string, unknown>)
32
+ : {}
33
+ }
34
+
35
+ function str(value: unknown): string {
36
+ return typeof value === "string" ? value.trim() : ""
37
+ }
38
+
39
+ function loadWidgetScript(url: string, module = false): Promise<void> {
40
+ if (typeof document === "undefined") return Promise.reject(new Error("Nincs böngészőkörnyezet."))
41
+ const existing = document.querySelector<HTMLScriptElement>(`script[data-hszrdm-widget="${url}"]`)
42
+ if (existing?.dataset.loaded === "true") return Promise.resolve()
43
+ return new Promise((resolve, reject) => {
44
+ const script = existing ?? document.createElement("script")
45
+ const timeout = window.setTimeout(() => reject(new Error("A térképes választó betöltése időtúllépés miatt megszakadt.")), 15000)
46
+ const success = () => { window.clearTimeout(timeout); script.dataset.loaded = "true"; resolve() }
47
+ const failure = () => { window.clearTimeout(timeout); script.remove(); reject(new Error("A futárszolgálat térképe nem tölthető be.")) }
48
+ script.addEventListener("load", success, { once: true })
49
+ script.addEventListener("error", failure, { once: true })
50
+ if (!existing) {
51
+ script.src = url
52
+ script.async = true
53
+ if (module) script.type = "module"
54
+ script.dataset.hszrdmWidget = url
55
+ document.head.appendChild(script)
56
+ }
57
+ })
58
+ }
59
+
60
+ export function CarrierPickupMap({
61
+ carrier, onSelect, selected, locale = "hu", postalCode = "", autoOpen = false,
62
+ }: {
63
+ carrier: CarrierPickupKind
64
+ onSelect: (point: CarrierPickupPoint | null) => void
65
+ selected: CarrierPickupPoint | null
66
+ locale?: "hu" | "en"
67
+ postalCode?: string
68
+ autoOpen?: boolean
69
+ }) {
70
+ const rawId = useId().replace(/[^a-zA-Z0-9_-]/g, "")
71
+ const containerId = `hszrdm-pickup-${rawId}`
72
+ const zipId = `hszrdm-postcode-${rawId}`
73
+ const frame = useRef<HTMLIFrameElement>(null)
74
+ const map = useRef<HTMLDivElement>(null)
75
+ const onSelectRef = useRef(onSelect)
76
+ const [error, setError] = useState("")
77
+ const [ready, setReady] = useState(false)
78
+ onSelectRef.current = onSelect
79
+
80
+ useEffect(() => {
81
+ let alive = true
82
+ const report = (err: unknown) => { if (alive) setError(err instanceof Error ? err.message : "A térkép nem elérhető.") }
83
+ const accept = (value: unknown) => {
84
+ if (!alive) return
85
+ const point = normalizeCarrierPickupPoint(carrier, value)
86
+ if (!point) { report(new Error("A kiválasztott pont azonosítója vagy neve hiányzik. Válassz másik pontot.")); return }
87
+ setError("")
88
+ onSelectRef.current(point)
89
+ }
90
+ const message = (event: MessageEvent) => {
91
+ if (event.source !== frame.current?.contentWindow) return
92
+ if (carrier === "foxpost" && event.origin === FOXPOST_ORIGIN) {
93
+ try { accept(typeof event.data === "string" ? JSON.parse(event.data) : event.data) } catch { report(new Error("Érvénytelen FOXPOST pontadat.")) }
94
+ }
95
+ if (carrier === "dpd" && event.origin === DPD_ORIGIN) {
96
+ const widget = record(record(event.data).dpdWidget)
97
+ if (str(widget.message) === "widgetClose") return
98
+ if (Object.keys(widget).length) {
99
+ const nested = record(widget.pickupPoint ?? widget.pickupPointData ?? widget.pickupPointResult)
100
+ accept(Object.keys(nested).length ? { ...widget, ...nested } : widget)
101
+ }
102
+ }
103
+ }
104
+ window.addEventListener("message", message)
105
+ const globals = window as WidgetGlobals
106
+ let glsElement: HTMLElement | null = null
107
+ let glsChange: EventListener | null = null
108
+ const initialize = async () => {
109
+ if (carrier === "foxpost" || carrier === "dpd") { setReady(true); return }
110
+ if (carrier === "gls") {
111
+ await loadWidgetScript(GLS_SCRIPT, true)
112
+ if (!alive || !map.current) return
113
+ glsElement = document.createElement("gls-dpm")
114
+ glsElement.setAttribute("country", "hu")
115
+ glsElement.setAttribute("language", locale)
116
+ glsElement.style.cssText = "display:block;width:100%;height:100%"
117
+ glsChange = ((event: Event) => accept((event as CustomEvent).detail)) as EventListener
118
+ glsElement.addEventListener("change", glsChange)
119
+ map.current.replaceChildren(glsElement)
120
+ setReady(true)
121
+ return
122
+ }
123
+ if (carrier === "packeta") {
124
+ if (!process.env.NEXT_PUBLIC_PACKETA_WIDGET_API_KEY?.trim()) {
125
+ throw new Error("Hiányzik a NEXT_PUBLIC_PACKETA_WIDGET_API_KEY. A Packeta térképhez nyilvános widget-kulcs szükséges.")
126
+ }
127
+ await loadWidgetScript(PACKETA_SCRIPT)
128
+ if (!alive) return
129
+ if (!globals.Packeta?.Widget?.pick) throw new Error("A Packeta widget nem indult el.")
130
+ setReady(true)
131
+ return
132
+ }
133
+ if (carrier === "mpl") {
134
+ const mapsKey = process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY?.trim()
135
+ if (!mapsKey) throw new Error("A PostaPont térképhez NEXT_PUBLIC_GOOGLE_MAPS_API_KEY szükséges.")
136
+ await loadWidgetScript("https://code.jquery.com/jquery-3.7.1.min.js")
137
+ await loadWidgetScript(`https://maps.googleapis.com/maps/api/js?key=${encodeURIComponent(mapsKey)}&language=hu&region=HU`)
138
+ await loadWidgetScript(POSTA_SCRIPT)
139
+ if (!alive) return
140
+ if (!globals.ppapi) throw new Error("A PostaPont térkép szolgáltatás nem inicializálható.")
141
+ if (!document.querySelector(`link[data-hszrdm-posta-css]`)) {
142
+ const link = document.createElement("link")
143
+ link.rel = "stylesheet"; link.href = POSTA_CSS; link.dataset.hszrdmPostaCss = "true"
144
+ document.head.appendChild(link)
145
+ }
146
+ globals.ppapi.linkZipField(zipId)
147
+ globals.ppapi.onSelect = accept
148
+ globals.ppapi.insertMap(containerId)
149
+ setReady(true)
150
+ }
151
+ }
152
+ void initialize().catch(report)
153
+ return () => {
154
+ alive = false
155
+ window.removeEventListener("message", message)
156
+ if (glsElement && glsChange) glsElement.removeEventListener("change", glsChange)
157
+ if (carrier === "packeta") globals.Packeta?.Widget?.close?.()
158
+ if (carrier === "mpl" && globals.ppapi) globals.ppapi.onSelect = undefined
159
+ }
160
+ }, [carrier, containerId, locale, zipId])
161
+
162
+ const openPacketa = useCallback(() => {
163
+ const key = process.env.NEXT_PUBLIC_PACKETA_WIDGET_API_KEY?.trim()
164
+ if (!key) { setError("Nincs Packeta widget-kulcs."); return }
165
+ const widget = (window as WidgetGlobals).Packeta?.Widget
166
+ if (!widget?.pick) { setError("A Packeta térkép még nem töltődött be."); return }
167
+ widget.pick(key, (value) => { if (value) {
168
+ const point = normalizeCarrierPickupPoint("packeta", value)
169
+ if (point) { setError(""); onSelectRef.current(point) }
170
+ else setError("A Packeta nem adott vissza érvényes pontazonosítót.")
171
+ } }, { country: "hu", language: locale })
172
+ }, [locale])
173
+
174
+ useEffect(() => {
175
+ if (autoOpen && ready && carrier === "packeta") openPacketa()
176
+ }, [autoOpen, carrier, ready, openPacketa])
177
+
178
+ return <div className="stack-sm" aria-label="Hivatalos futárszolgálati csomagpontválasztó">
179
+ {error ? <p className="notice warning" role="alert">{error}</p> : null}
180
+ {carrier === "foxpost" ? <iframe ref={frame} title="FOXPOST hivatalos csomagponttérkép"
181
+ src={FOXPOST_WIDGET} loading="lazy" allow="geolocation"
182
+ onError={() => setError("A FOXPOST térkép nem tölthető be. Ellenőrizd a böngésző hálózati és tartalomvédelmi beállításait.")}
183
+ style={{ width: "100%", height: 530, border: 0 }} /> : null}
184
+ {carrier === "dpd" ? <iframe ref={frame} title="DPD hivatalos Pickup térkép"
185
+ src={DPD_WIDGET} loading="lazy" allow="geolocation"
186
+ onError={() => setError("A DPD térkép nem tölthető be. Ellenőrizd a böngésző hálózati és tartalomvédelmi beállításait.")}
187
+ style={{ width: "100%", height: 530, border: 0 }} /> : null}
188
+ {carrier === "gls" ? <div ref={map} style={{ height: 530, minHeight: 400 }} /> : null}
189
+ {carrier === "packeta" ? <button type="button" className="button secondary" disabled={!ready}
190
+ onClick={openPacketa}>{locale === "en" ? "Open Packeta pickup map" : "Packeta térkép megnyitása"}</button> : null}
191
+ {carrier === "mpl" ? <div>
192
+ <input id={zipId} type="hidden" value={postalCode} readOnly />
193
+ <div id={containerId} style={{ minHeight: 530, maxWidth: "100%" }} />
194
+ </div> : null}
195
+ {selected?.provider === carrier ? <p className="notice" role="status">
196
+ {locale === "en" ? "Selected point" : "Kiválasztott átvételi pont"}: <strong>{selected.name}</strong>
197
+ {" – "}{[selected.postalCode, selected.city, selected.address].filter(Boolean).join(" ")}
198
+ </p> : null}
199
+ </div>
200
+ }
@@ -4,6 +4,9 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"
4
4
  import { usePathname, useRouter, useSearchParams } from "next/navigation"
5
5
  import { useCart } from "./cart-provider"
6
6
  import { StripePayment } from "./stripe-payment"
7
+ import { carrierPointToShippingData, type CarrierPickupPoint } from "./carrier-pickup-map"
8
+ import { CarrierPickupDialog } from "./carrier-pickup-dialog"
9
+ import { normalizeCarrierPickupPoint } from "./carrier-pickup-adapter"
7
10
  import { checkoutApi } from "@/lib/core/checkout"
8
11
  import {
9
12
  activePaymentSession,
@@ -73,11 +76,8 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
73
76
  const [address, setAddress] = useState<AddressState>(() => emptyAddress(config.store.default_country))
74
77
  const [shippingOptions, setShippingOptions] = useState<JsonRecord[]>([])
75
78
  const [selectedShipping, setSelectedShipping] = useState<JsonRecord | null>(null)
76
- const [pickupPoints, setPickupPoints] = useState<JsonRecord[]>([])
77
- const [selectedPickupKey, setSelectedPickupKey] = useState("")
78
- const [pickupSearch, setPickupSearch] = useState("")
79
- const [packetaPointId, setPacketaPointId] = useState("")
80
- const [packetaPointName, setPacketaPointName] = useState("")
79
+ const [selectedPickupPoint, setSelectedPickupPoint] = useState<CarrierPickupPoint | null>(null)
80
+ const [pickupDialogOpen, setPickupDialogOpen] = useState(false)
81
81
  const [providers, setProviders] = useState<JsonRecord[]>([])
82
82
  const [selectedProvider, setSelectedProvider] = useState("")
83
83
  const [preparedCart, setPreparedCart] = useState<JsonRecord | null>(null)
@@ -278,49 +278,41 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
278
278
  }
279
279
  }
280
280
 
281
- const selectShippingOption = async (option: JsonRecord) => {
281
+ const selectShippingOption = (option: JsonRecord) => {
282
282
  setSelectedShipping(option)
283
- setSelectedPickupKey("")
284
- setPickupPoints([])
285
- setPickupSearch("")
286
- const kind = pickupKind(option)
287
- if (!kind || kind === "packeta") return
288
- setBusy("pickup")
283
+ setSelectedPickupPoint(null)
284
+ setPickupDialogOpen(false)
289
285
  setError(null)
290
- try {
291
- if (kind === "foxpost") setPickupPoints((await api.foxpostLockers()).lockers)
292
- if (kind === "gls") setPickupPoints((await api.glsDeliveryPoints()).deliveryPoints)
293
- if (kind === "dpd") {
294
- setPickupPoints(
295
- (
296
- await api.dpdPickupPoints({
297
- country: address.country_code,
298
- postalCode: address.postal_code,
299
- city: address.city,
300
- limit: "100",
301
- })
302
- ).pickupPoints,
303
- )
304
- }
305
- if (kind === "mpl") {
306
- setPickupPoints(
307
- (
308
- await api.mplDeliveryPlaces({
309
- postCode: address.postal_code,
310
- city: address.city,
311
- })
312
- ).deliveryPlaces,
313
- )
286
+ }
287
+
288
+ /** Reconcile vendor widget selection with Core's current catalog where available. */
289
+ const verifyCarrierPickupPoint = async (kind: PickupKind, picked: CarrierPickupPoint | null) => {
290
+ if (!kind || !picked || kind !== picked.provider) return picked
291
+ let candidates: JsonRecord[] | null = null
292
+ if (kind === "foxpost") candidates = (await api.foxpostLockers()).lockers
293
+ if (kind === "gls") candidates = (await api.glsDeliveryPoints()).deliveryPoints
294
+ if (kind === "mpl") {
295
+ candidates = (await api.mplDeliveryPlaces({ postCode: picked.postalCode })).deliveryPlaces
296
+ }
297
+ if (!candidates) return picked
298
+ const match = candidates.find((item) => {
299
+ const candidate = normalizeCarrierPickupPoint(kind, item)
300
+ if (!candidate) return false
301
+ if (candidate.id === picked.id) return true
302
+ if (kind === "foxpost") {
303
+ const identifiers = [stringValue(item.operatorId), stringValue(item.placeId)].filter(Boolean)
304
+ return identifiers.includes(picked.id) || identifiers.includes(stringValue(picked.raw.place_id))
314
305
  }
315
- } catch (cause) {
316
- setError(
317
- cause instanceof Error
318
- ? cause.message
319
- : localized(locale, "A csomagpontok nem tölthetők be.", "Pickup points could not be loaded."),
320
- )
321
- } finally {
322
- setBusy(null)
306
+ return false
307
+ })
308
+ if (!match) {
309
+ throw new Error(localized(locale,
310
+ "A kiválasztott átvételi pont már nem érhető el ennél a futárszolgálatnál. Válassz másikat.",
311
+ "This pickup point is no longer available for this carrier. Please choose another."))
323
312
  }
313
+ const confirmed = normalizeCarrierPickupPoint(kind, match)
314
+ if (!confirmed) throw new Error(localized(locale, "Hiányos átvételipont-adatok.", "Invalid pickup point details."))
315
+ return confirmed
324
316
  }
325
317
 
326
318
  const saveShipping = async () => {
@@ -329,11 +321,11 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
329
321
  }
330
322
  const optionId = stringValue(selectedShipping.id)
331
323
  const kind = pickupKind(selectedShipping)
332
- const selectedPoint = pickupPoints.find((point) => pickupKey(point) === selectedPickupKey) || null
333
- const data = shippingData(kind, selectedPoint, packetaPointId, packetaPointName, locale)
334
324
  setBusy("shipping")
335
325
  setError(null)
336
326
  try {
327
+ const verifiedPoint = await verifyCarrierPickupPoint(kind, selectedPickupPoint)
328
+ const data = shippingData(kind, verifiedPoint, locale)
337
329
  const result = await api.addShippingMethod(cartId, optionId, data)
338
330
  await refresh(cartId)
339
331
  await loadProviders(result.cart)
@@ -396,11 +388,6 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
396
388
  }
397
389
 
398
390
  const pickup = selectedShipping ? pickupKind(selectedShipping) : null
399
- const filteredPoints = pickupSearch.trim()
400
- ? pickupPoints
401
- .filter((point) => pointLabel(point).toLowerCase().includes(pickupSearch.trim().toLowerCase()))
402
- .slice(0, 200)
403
- : pickupPoints.slice(0, 200)
404
391
  const effectiveCart = preparedCart || cart
405
392
  const session = activePaymentSession(effectiveCart)
406
393
  const activeProviderId = providerId(session) || selectedProvider
@@ -454,29 +441,43 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
454
441
  </div>
455
442
  )}
456
443
 
457
- {pickup && pickup !== "packeta" ? (
444
+ {pickup ? (
458
445
  <div className="stack-sm">
459
- <Field label={copy.pickupSearch} value={pickupSearch} onChange={setPickupSearch} />
460
- <label>
461
- {copy.pickupPoint}
462
- <select value={selectedPickupKey} onChange={(event) => setSelectedPickupKey(event.target.value)} disabled={busy === "pickup"}>
463
- <option value="">{copy.choosePickupPoint}</option>
464
- {filteredPoints.map((point) => (
465
- <option key={pickupKey(point)} value={pickupKey(point)}>{pointLabel(point)}</option>
466
- ))}
467
- </select>
468
- </label>
469
- {pickupPoints.length > 200 ? <p className="muted small">{copy.filterPickupHint}</p> : null}
446
+ {selectedPickupPoint?.provider === pickup ? (
447
+ <p className="notice" role="status">
448
+ <strong>{locale === "en" ? "Selected pickup point" : "Kiválasztott csomagpont"}: {selectedPickupPoint.name}</strong>
449
+ {" – "}{[selectedPickupPoint.postalCode, selectedPickupPoint.city, selectedPickupPoint.address].filter(Boolean).join(" ")}
450
+ </p>
451
+ ) : (
452
+ <p className="muted">
453
+ {locale === "en"
454
+ ? "Choose a pickup point on the carrier's map to continue."
455
+ : "A folytatáshoz válassz csomagpontot a futárszolgálat térképén."}
456
+ </p>
457
+ )}
458
+ <button
459
+ className="button secondary"
460
+ type="button"
461
+ disabled={busy === "shipping" || mutating}
462
+ onClick={() => setPickupDialogOpen(true)}
463
+ >
464
+ {selectedPickupPoint?.provider === pickup
465
+ ? (locale === "en" ? "Change pickup point on map" : "Csomagpont módosítása a térképen")
466
+ : (locale === "en" ? "Choose pickup point on map" : "Csomagpont kiválasztása a térképen")}
467
+ </button>
470
468
  </div>
471
469
  ) : null}
472
470
 
473
- {pickup === "packeta" ? (
474
- <div className="notice warning stack-sm">
475
- <strong>{copy.packetaPoint}</strong>
476
- <span>{copy.packetaHint}</span>
477
- <Field label="Packeta point ID" value={packetaPointId} onChange={setPacketaPointId} />
478
- <Field label={copy.pointName} value={packetaPointName} onChange={setPacketaPointName} />
479
- </div>
471
+ {pickup && pickupDialogOpen ? (
472
+ <CarrierPickupDialog
473
+ key={pickup}
474
+ carrier={pickup}
475
+ selected={selectedPickupPoint}
476
+ postalCode={address.postal_code}
477
+ locale={locale}
478
+ onSelect={setSelectedPickupPoint}
479
+ onClose={() => setPickupDialogOpen(false)}
480
+ />
480
481
  ) : null}
481
482
 
482
483
  {selectedShipping ? (
@@ -485,8 +486,7 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
485
486
  type="button"
486
487
  disabled={
487
488
  busy === "shipping" ||
488
- (Boolean(pickup) && pickup !== "packeta" && !selectedPickupKey) ||
489
- (pickup === "packeta" && !packetaPointId.trim())
489
+ (Boolean(pickup) && selectedPickupPoint?.provider !== pickup)
490
490
  }
491
491
  onClick={() => void saveShipping()}
492
492
  >
@@ -735,50 +735,10 @@ function pickupKind(option: JsonRecord): PickupKind {
735
735
  return null
736
736
  }
737
737
 
738
- function pickupKey(point: JsonRecord) {
739
- return stringValue(
740
- point.id ||
741
- point.operatorId ||
742
- point.placeId ||
743
- point.code ||
744
- point.shop_id ||
745
- point.location_id ||
746
- point.name,
747
- )
748
- }
749
-
750
- function pointLabel(point: JsonRecord) {
751
- const name = stringValue(point.name || point.label || point.title || point.shop_name || point.type)
752
- const postal = stringValue(point.postalCode || point.postal_code || point.zipCode || point.zip_code || point.zip)
753
- const city = stringValue(point.city || point.town)
754
- const address = stringValue(point.address || point.address_1 || point.street || point.fullAddress)
755
- return [name, [postal, city].filter(Boolean).join(" "), address].filter(Boolean).join(" – ") || pickupKey(point)
756
- }
757
-
758
- function shippingData(
759
- kind: PickupKind,
760
- point: JsonRecord | null,
761
- packetaId: string,
762
- packetaName: string,
763
- locale: StorefrontLocale,
764
- ): Record<string, unknown> | undefined {
738
+ function shippingData(kind: PickupKind, point: CarrierPickupPoint | null, locale: StorefrontLocale): Record<string, unknown> | undefined {
765
739
  if (!kind) return undefined
766
- if (kind === "packeta") {
767
- if (!packetaId.trim()) {
768
- throw new Error(
769
- localized(locale, "A Packeta pont azonosítója kötelező.", "The Packeta pickup point ID is required."),
770
- )
771
- }
772
- return { packeta: { pickupPoint: { id: packetaId.trim(), name: packetaName.trim() || undefined } } }
773
- }
774
- if (!point) {
775
- throw new Error(localized(locale, "Válassz átvételi pontot.", "Choose a pickup point."))
776
- }
777
- if (kind === "foxpost") return { foxpost: { locker: point, packageSize: "M" } }
778
- if (kind === "gls") return { gls: { deliveryPoint: point } }
779
- if (kind === "dpd") return { dpd: { pickupPoint: point } }
780
- if (kind === "mpl") return { mpl: { pickupPoint: point } }
781
- return undefined
740
+ if (!point || point.provider !== kind) throw new Error(localized(locale, "Válassz átvételi pontot a futár térképén.", "Choose a pickup point on the carrier map."))
741
+ return carrierPointToShippingData(point)
782
742
  }
783
743
 
784
744
  function localized(locale: StorefrontLocale, hu: string, en: string) {
@@ -0,0 +1,69 @@
1
+ import assert from "node:assert/strict"
2
+ import test from "node:test"
3
+ import { normalizeCarrierPickupPoint, carrierPointToShippingData } from "../src/components/carrier-pickup-adapter.ts"
4
+
5
+ test("FOXPOST 2in1 point preserves operator and place ID", () => {
6
+ const point = normalizeCarrierPickupPoint("foxpost", {
7
+ place_id: 1250198, operator_id: "hu5516", name: "Gabi Cukrászat",
8
+ zip: "9081", city: "Győrújbarát", address: "9081 Győrújbarát, István utca 67.",
9
+ })
10
+ assert.ok(point)
11
+ const payload = carrierPointToShippingData(point)
12
+ assert.equal(payload.foxpost.locker.operatorId, "hu5516")
13
+ assert.equal(payload.foxpost.locker.placeId, "1250198")
14
+ assert.equal(payload.foxpost.locker.postalCode, "9081")
15
+ })
16
+
17
+ test("GLS map detail uses contact country/zip/city/address", () => {
18
+ const point = normalizeCarrierPickupPoint("gls", {
19
+ id: "1011-ALPHAZOOKF", name: "Alpha Zoo", contact: {
20
+ countryCode: "HU", postalCode: "1011", city: "Budapest", address: "Batthyány tér 5.",
21
+ },
22
+ })
23
+ assert.ok(point)
24
+ const payload = carrierPointToShippingData(point)
25
+ assert.equal(payload.gls.deliveryPoint.id, "1011-ALPHAZOOKF")
26
+ assert.equal(payload.gls.deliveryPoint.postalCode, "1011")
27
+ assert.equal(payload.gls.deliveryPoint.address, "Batthyány tér 5.")
28
+ })
29
+
30
+ test("Packeta widget keeps carrier pickup point metadata", () => {
31
+ const point = normalizeCarrierPickupPoint("packeta", {
32
+ id: 12345, name: "Z-BOX", zip: "8000", city: "Székesfehérvár",
33
+ street: "Kossuth utca 1.", carrierId: 10, carrierPickupPoint: "10-12345",
34
+ })
35
+ assert.ok(point)
36
+ const payload = carrierPointToShippingData(point)
37
+ assert.equal(payload.packeta.pickupPoint.id, "12345")
38
+ assert.equal(payload.packeta.pickupPoint.carrierId, "10")
39
+ })
40
+
41
+ test("DPD pickup ID survives provider payload conversion", () => {
42
+ const point = normalizeCarrierPickupPoint("dpd", {
43
+ id: "HU1234", name: "DPD Pickup", zipCode: "8000",
44
+ city: "Székesfehérvár", street: "Fő utca 1.", countryCode: "HU",
45
+ })
46
+ assert.ok(point)
47
+ const payload = carrierPointToShippingData(point)
48
+ assert.equal(payload.dpd.pickupPoint.id, "HU1234")
49
+ assert.equal(payload.dpd.pickupPoint.countryCode, "HU")
50
+ })
51
+
52
+ test("MPL PostaPont callback keeps official point ID and location", () => {
53
+ const point = normalizeCarrierPickupPoint("mpl", {
54
+ id: "PP123", name: "PostaPont", zip: "8000",
55
+ country: "Székesfehérvár", address: "Fő utca 1.", group: "10_posta",
56
+ deliveryMode: "PM",
57
+ })
58
+ assert.ok(point)
59
+ const payload = carrierPointToShippingData(point)
60
+ assert.equal(payload.mpl.pickupPoint.id, "PP123")
61
+ assert.equal(payload.mpl.pickupPoint.city, "Székesfehérvár")
62
+ assert.equal(payload.mpl.pickupPoint.deliveryMode, "PM")
63
+ })
64
+
65
+ test("invalid or incomplete widget selection is rejected", () => {
66
+ assert.equal(normalizeCarrierPickupPoint("foxpost", { name: "Incomplete", city: "Budapest" }), null)
67
+ assert.equal(normalizeCarrierPickupPoint("gls", { id: "X", name: "Incomplete" }), null)
68
+ assert.equal(normalizeCarrierPickupPoint("packeta", null), null)
69
+ })