@hszrdm/create-commerce 1.10.1 → 1.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +70 -46
  2. package/package.json +1 -1
  3. package/src/cli.mjs +23 -4
  4. package/src/upgrade.mjs +248 -22
  5. package/templates/backend/.env.example +8 -0
  6. package/templates/backend/package.json +1 -1
  7. package/templates/backend/scripts/commerce-instance-status.mjs +135 -0
  8. package/templates/backend/scripts/commerce-ops.mjs +58 -2
  9. package/templates/backend/scripts/core-restore.mjs +40 -5
  10. package/templates/backend/scripts/lib/core-backup-common.mjs +91 -11
  11. package/templates/backend/scripts/production-assets/backup.sh +6 -51
  12. package/templates/backend/scripts/production-assets/deploy.sh +10 -62
  13. package/templates/backend/scripts/production-assets/install.sh +23 -195
  14. package/templates/backend/scripts/production-assets/restore.sh +17 -66
  15. package/templates/storefront/package.json +5 -1
  16. package/templates/storefront/src/app/checkout/success/page.tsx +2 -0
  17. package/templates/storefront/src/app/globals.css +32 -0
  18. package/templates/storefront/src/app/layout.tsx +7 -1
  19. package/templates/storefront/src/app/legal/page.tsx +3 -3
  20. package/templates/storefront/src/components/analytics.tsx +10 -8
  21. package/templates/storefront/src/components/checkout-flow.tsx +539 -75
  22. package/templates/storefront/src/components/fogyasztobarat-embed.tsx +6 -2
  23. package/templates/storefront/src/components/google-analytics-purchase.tsx +33 -0
  24. package/templates/storefront/src/components/stripe-payment.tsx +186 -62
  25. package/templates/storefront/src/lib/core/checkout-addresses.ts +166 -0
  26. package/templates/storefront/src/lib/core/checkout.ts +12 -0
  27. package/templates/storefront/src/lib/core/commerce.ts +12 -2
  28. package/templates/storefront/src/lib/core/company-tax.ts +132 -0
  29. package/templates/storefront/src/lib/core/ga4-bootstrap.ts +35 -0
  30. package/templates/storefront/src/lib/core/legal.ts +1 -0
  31. package/templates/storefront/src/lib/core/public-error.ts +1 -0
  32. package/templates/storefront/src/lib/core/stripe-checkout-phase.ts +23 -0
  33. package/templates/storefront/src/lib/core/tracking.ts +11 -2
  34. package/templates/storefront/tests/checkout-addresses.test.mjs +148 -0
  35. package/templates/storefront/tests/company-tax.test.mjs +68 -0
  36. package/templates/storefront/tests/ga4-bootstrap.test.mjs +74 -0
  37. package/templates/storefront/tests/stripe-checkout-phase.test.mjs +92 -0
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Pure HU/EU VAT ID syntax rules. This validates format, not whether an ID
3
+ * actually exists, belongs to a merchant, or is active in VIES / NAV.
4
+ *
5
+ * Shared contract: keep this file in sync with the storefront starter copy.
6
+ */
7
+ export class CompanyTaxValidationError extends Error {
8
+ readonly field: "company" | "billing_tax_number" | "billing_eu_tax_number" | "billing_tax_details"
9
+
10
+ constructor(message: string, field: "company" | "billing_tax_number" | "billing_eu_tax_number" | "billing_tax_details") {
11
+ super(message)
12
+ this.name = "CompanyTaxValidationError"
13
+ this.field = field
14
+ }
15
+ }
16
+
17
+ const EU_VAT_PATTERNS: Record<string, RegExp> = {
18
+ AT: /^U\d{8}$/,
19
+ BE: /^\d{10}$/,
20
+ BG: /^\d{9,10}$/,
21
+ CY: /^\d{8}[A-Z]$/,
22
+ CZ: /^\d{8,10}$/,
23
+ DE: /^\d{9}$/,
24
+ DK: /^\d{8}$/,
25
+ EE: /^\d{9}$/,
26
+ EL: /^\d{9}$/,
27
+ ES: /^[A-Z0-9]\d{7}[A-Z0-9]$/,
28
+ FI: /^\d{8}$/,
29
+ FR: /^[A-HJ-NP-Z0-9]{2}\d{9}$/,
30
+ HR: /^\d{11}$/,
31
+ HU: /^\d{8}$/,
32
+ IE: /^[0-9A-Z+*]{8,9}$/,
33
+ IT: /^\d{11}$/,
34
+ LT: /^(?:\d{9}|\d{12})$/,
35
+ LU: /^\d{8}$/,
36
+ LV: /^\d{11}$/,
37
+ MT: /^\d{8}$/,
38
+ NL: /^\d{9}B\d{2}$/,
39
+ PL: /^\d{10}$/,
40
+ PT: /^\d{9}$/,
41
+ RO: /^\d{2,10}$/,
42
+ SE: /^\d{12}$/,
43
+ SI: /^\d{8}$/,
44
+ SK: /^\d{10}$/,
45
+ // Northern Ireland EU VAT reporting, where relevant.
46
+ XI: /^(?:\d{9}|\d{12}|GD\d{3}|HA\d{3})$/,
47
+ }
48
+
49
+ export type CompanyTaxDetails = {
50
+ isCompany: boolean
51
+ company: string
52
+ billingTaxNumber: string
53
+ billingEuTaxNumber: string
54
+ }
55
+
56
+ export function normalizeHungarianTaxNumber(input: unknown) {
57
+ if (typeof input !== "string") throw new CompanyTaxValidationError(
58
+ "A magyar adószám érvénytelen.", "billing_tax_number",
59
+ )
60
+ const value = input.trim().replace(/[\s.]/g, "")
61
+ if (!value) return ""
62
+ // Accept both 12345678-2-42 and the unseparated 12345678242 form.
63
+ const valid = /^\d{8}-[1-5]-\d{2}$/.test(value) ||
64
+ /^\d{8}[1-5]\d{2}$/.test(value)
65
+ const digits = value.replace(/-/g, "")
66
+ if (!valid) {
67
+ throw new CompanyTaxValidationError(
68
+ "A magyar adószám formátuma: 12345678-2-42 (8+1+2 számjegy).",
69
+ "billing_tax_number",
70
+ )
71
+ }
72
+ return `${digits.slice(0, 8)}-${digits[8]}-${digits.slice(9)}`
73
+ }
74
+
75
+ export function normalizeEuTaxNumber(input: unknown) {
76
+ if (typeof input !== "string") throw new CompanyTaxValidationError(
77
+ "Az EU-s közösségi adószám érvénytelen.", "billing_eu_tax_number",
78
+ )
79
+ const value = input.toUpperCase().trim().replace(/[\s.-]/g, "")
80
+ if (!value) return ""
81
+ const country = value.slice(0, 2)
82
+ const number = value.slice(2)
83
+ const pattern = EU_VAT_PATTERNS[country]
84
+ if (!pattern || !pattern.test(number)) {
85
+ throw new CompanyTaxValidationError(
86
+ "Érvénytelen EU-s közösségi adószám. Országkóddal add meg (pl. HU12345678 vagy DE123456789).",
87
+ "billing_eu_tax_number",
88
+ )
89
+ }
90
+ return value
91
+ }
92
+
93
+ export function validateCompanyTaxDetails(input: {
94
+ isCompany: unknown
95
+ company: unknown
96
+ billingTaxNumber: unknown
97
+ billingEuTaxNumber: unknown
98
+ }): CompanyTaxDetails {
99
+ if (typeof input.isCompany !== "boolean" || typeof input.company !== "string") {
100
+ throw new CompanyTaxValidationError(
101
+ "Érvénytelen céges számlázási adat.", "billing_tax_details",
102
+ )
103
+ }
104
+ const company = input.company.trim()
105
+ if (company.length > 150) throw new CompanyTaxValidationError(
106
+ "A cégnév túl hosszú.", "company",
107
+ )
108
+ const billingTaxNumber = normalizeHungarianTaxNumber(input.billingTaxNumber)
109
+ const billingEuTaxNumber = normalizeEuTaxNumber(input.billingEuTaxNumber)
110
+
111
+ if (!input.isCompany) {
112
+ if (billingTaxNumber || billingEuTaxNumber) throw new CompanyTaxValidationError(
113
+ "Magánszemély számlázásnál töröld a céges adószámokat.", "billing_tax_details",
114
+ )
115
+ return { isCompany: false, company: "", billingTaxNumber: "", billingEuTaxNumber: "" }
116
+ }
117
+ if (!company) throw new CompanyTaxValidationError(
118
+ "Céges számlázásnál a cégnév megadása kötelező.", "company",
119
+ )
120
+ if (!billingTaxNumber && !billingEuTaxNumber) throw new CompanyTaxValidationError(
121
+ "Céges számlázásnál legalább a magyar vagy az EU-s adószám kötelező.",
122
+ "billing_tax_details",
123
+ )
124
+ if (billingTaxNumber && billingEuTaxNumber.startsWith("HU") &&
125
+ billingTaxNumber.slice(0, 8) !== billingEuTaxNumber.slice(2)) {
126
+ throw new CompanyTaxValidationError(
127
+ "A HU közösségi adószám első nyolc számjegyének egyeznie kell a magyar adószámmal.",
128
+ "billing_eu_tax_number",
129
+ )
130
+ }
131
+ return { isCompany: true, company, billingTaxNumber, billingEuTaxNumber }
132
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Initialize the direct GA4 destination once per browser page, before any
3
+ * ecommerce events. next/script may still be loading at this point: gtag
4
+ * commands are queued in dataLayer and replayed in order when gtag.js arrives.
5
+ *
6
+ * Do not call this for GTM mode: GTM is the single tag loader in that mode.
7
+ */
8
+ const configuredIds = new Set<string>()
9
+
10
+ export function ensureDirectGa4Initialized(
11
+ measurementId: string | null,
12
+ analyticsConsentGranted: boolean,
13
+ ): boolean {
14
+ if (typeof window === "undefined" || !analyticsConsentGranted) return false
15
+ const id = measurementId?.trim() || ""
16
+ if (!/^G-[A-Z0-9]+$/.test(id)) return false
17
+
18
+ const target = window as typeof window & {
19
+ dataLayer?: unknown[]
20
+ gtag?: (...args: unknown[]) => void
21
+ }
22
+ target.dataLayer = target.dataLayer || []
23
+ target.gtag = target.gtag || function gtag(...args: unknown[]) {
24
+ target.dataLayer!.push(args)
25
+ }
26
+
27
+ if (!configuredIds.has(id)) {
28
+ // The initial config emits the first page_view. Later SPA route views are
29
+ // captured by GA4 Enhanced Measurement's history-change setting.
30
+ target.gtag("js", new Date())
31
+ target.gtag("config", id)
32
+ configuredIds.add(id)
33
+ }
34
+ return true
35
+ }
@@ -7,6 +7,7 @@ export type LegalEmbedConfig = {
7
7
  scriptUrl?: string
8
8
  dataId?: string
9
9
  dataType?: string
10
+ placement?: "global" | "legal"
10
11
  }
11
12
 
12
13
  export async function listLegalDocuments(config: CoreConfig) {
@@ -40,6 +40,7 @@ const publicCodes = new Set([
40
40
  "MPL_VALIDATION",
41
41
  "PACKETA_VALIDATION",
42
42
  "DPD_VALIDATION",
43
+ "BILLING_TAX_INVALID",
43
44
  ])
44
45
 
45
46
  const unsafe = /(?:Error:|\b(?:TypeError|ReferenceError|SyntaxError|ECONN|ETIMEDOUT|SQL|SELECT|INSERT|UPDATE|DELETE FROM|Prisma|Postgres|database|password|secret|token|api[_ -]?key|node_modules|stack trace|PaymentIntent|Bearer|sk_live_|sk_test_)\b|\/var\/|\/home\/|\/private\/|https?:\/\/[^\s]*@)/i
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Stripe checkout presentation is separate from the asynchronous Medusa
3
+ * payment-session initialization. Missing client_secret while a session is
4
+ * being created is NOT a configuration error.
5
+ */
6
+ export type StripeCheckoutPhase = "hidden" | "preparing" | "ready" | "error"
7
+
8
+ export function stripeCheckoutPhase(input: {
9
+ sessionProviderId: string
10
+ selectedProviderId: string
11
+ busy: string | null
12
+ clientSecret: string | null
13
+ publishableKey: string | null | undefined
14
+ initializationError?: string | null
15
+ }): StripeCheckoutPhase {
16
+ const selected = input.selectedProviderId || input.sessionProviderId
17
+ if (!selected.toLowerCase().includes("stripe")) return "hidden"
18
+ if (input.busy === "payment" && input.selectedProviderId.toLowerCase().includes("stripe")) {
19
+ return "preparing"
20
+ }
21
+ if (input.initializationError || !input.clientSecret || !input.publishableKey) return "error"
22
+ return "ready"
23
+ }
@@ -1,4 +1,5 @@
1
1
  import { readConsentPreferences } from "./consent"
2
+ import { ensureDirectGa4Initialized } from "./ga4-bootstrap"
2
3
  import type { CoreConfig } from "./types"
3
4
 
4
5
  export type EcommerceItem = {
@@ -127,8 +128,16 @@ export function trackEcommerce(
127
128
  target.dataLayer.push({ ecommerce: null })
128
129
  target.dataLayer.push({ event, ecommerce })
129
130
  googleSent = true
130
- } else if (typeof target.gtag === "function") {
131
- target.gtag("event", event, ecommerce)
131
+ } else if (
132
+ mode === "ga4" &&
133
+ ensureDirectGa4Initialized(analytics.google_analytics.measurement_id, true) &&
134
+ typeof target.gtag === "function"
135
+ ) {
136
+ // Explicitly target GA4. The same gtag.js loader may also serve Google Ads.
137
+ target.gtag("event", event, {
138
+ ...ecommerce,
139
+ send_to: analytics.google_analytics.measurement_id,
140
+ })
132
141
  googleSent = true
133
142
  }
134
143
 
@@ -0,0 +1,148 @@
1
+ import test from "node:test"
2
+ import assert from "node:assert/strict"
3
+ import {
4
+ CART_CHECKOUT_ADDRESS,
5
+ NEW_CHECKOUT_ADDRESS,
6
+ checkoutAddressFromRecord,
7
+ checkoutAddressLabel,
8
+ checkoutAddressPayload,
9
+ checkoutAddressesMatch,
10
+ emptyCheckoutAddress,
11
+ initialCheckoutAddresses,
12
+ } from "../src/lib/core/checkout-addresses.ts"
13
+
14
+ const shipping = {
15
+ id: "cadr_shipping", address_name: "Otthon", is_default_shipping: true,
16
+ first_name: "Kata", last_name: "Teszt", phone: "06301234567",
17
+ country_code: "hu", postal_code: "8000", city: "Székesfehérvár",
18
+ address_1: "Fő utca 1", address_2: "",
19
+ }
20
+ const billing = {
21
+ id: "cadr_billing", address_name: "Céges számlázás", is_default_billing: true,
22
+ first_name: "Kata", last_name: "Teszt", company: "Teszt Kft.",
23
+ country_code: "hu", postal_code: "1117", city: "Budapest",
24
+ address_1: "Duna utca 10",
25
+ }
26
+ const savedAddresses = [shipping, billing]
27
+ const base = { country: "HU", customer: { email: "kata@example.com" }, savedAddresses }
28
+
29
+ test("logged-in customer gets default shipping and distinct default billing automatically", () => {
30
+ const initial = initialCheckoutAddresses({ ...base, cart: {} })
31
+ assert.equal(initial.shippingSelection, "cadr_shipping")
32
+ assert.equal(initial.billingSelection, "cadr_billing")
33
+ assert.equal(initial.shipping.email, "kata@example.com")
34
+ assert.equal(initial.shipping.city, "Székesfehérvár")
35
+ assert.equal(initial.shipping.country_code, "HU")
36
+ assert.equal(initial.billing.company, "Teszt Kft.")
37
+ assert.equal(initial.billing.address_1, "Duna utca 10")
38
+ assert.equal(initial.billingSameAsShipping, false)
39
+ assert.equal(initial.addressOnCart, false)
40
+ assert.match(checkoutAddressLabel(billing), /Céges számlázás/)
41
+ })
42
+
43
+ test("explicit customer default-address IDs take precedence over stale address flags", () => {
44
+ const initial = initialCheckoutAddresses({
45
+ cart: {},
46
+ country: "HU",
47
+ customer: {
48
+ email: "kata@example.com",
49
+ default_shipping_address_id: "cadr_billing",
50
+ default_billing_address_id: "cadr_shipping",
51
+ },
52
+ savedAddresses,
53
+ })
54
+ assert.equal(initial.shippingSelection, "cadr_billing")
55
+ assert.equal(initial.billingSelection, "cadr_shipping")
56
+ assert.equal(initial.shipping.address_1, "Duna utca 10")
57
+ assert.equal(initial.billing.address_1, "Fő utca 1")
58
+ })
59
+
60
+ test("one default saved address can be used as both shipping and billing", () => {
61
+ const initial = initialCheckoutAddresses({
62
+ cart: {}, country: "HU", customer: { email: "kata@example.com" },
63
+ savedAddresses: [{ ...shipping, is_default_billing: true }],
64
+ })
65
+ assert.equal(initial.billingSameAsShipping, true)
66
+ assert.equal(initial.shippingSelection, "cadr_shipping")
67
+ assert.equal(initial.billingSelection, "cadr_shipping")
68
+ })
69
+
70
+ test("existing cart-specific addresses win over address book defaults", () => {
71
+ const previousShipping = { ...shipping, id: undefined, address_1: "Korábbi utca 2" }
72
+ const previousBilling = { ...billing, id: undefined, address_1: "Másik utca 3" }
73
+ const initial = initialCheckoutAddresses({
74
+ ...base,
75
+ cart: { email: "checkout@example.com", shipping_address: previousShipping, billing_address: previousBilling },
76
+ })
77
+ assert.equal(initial.shipping.address_1, "Korábbi utca 2")
78
+ assert.equal(initial.billing.address_1, "Másik utca 3")
79
+ assert.equal(initial.shippingSelection, CART_CHECKOUT_ADDRESS)
80
+ assert.equal(initial.billingSelection, CART_CHECKOUT_ADDRESS)
81
+ assert.equal(initial.shipping.email, "checkout@example.com")
82
+ assert.equal(initial.billingSameAsShipping, false)
83
+ assert.equal(initial.addressOnCart, true)
84
+ })
85
+
86
+ test("saved address matching a previous cart stays selectable without losing cart content", () => {
87
+ const initial = initialCheckoutAddresses({
88
+ ...base, cart: { email: "kata@example.com", shipping_address: shipping, billing_address: shipping },
89
+ })
90
+ assert.equal(initial.shippingSelection, "cadr_shipping")
91
+ assert.equal(initial.billingSelection, "cadr_shipping")
92
+ assert.equal(initial.billingSameAsShipping, true)
93
+ assert.equal(initial.addressOnCart, true)
94
+ })
95
+
96
+ test("cart with both addresses but no email still needs an explicit checkout save", () => {
97
+ const initial = initialCheckoutAddresses({
98
+ ...base, cart: { shipping_address: shipping, billing_address: billing },
99
+ })
100
+ assert.equal(initial.shipping.email, "kata@example.com")
101
+ assert.equal(initial.addressOnCart, false)
102
+ })
103
+
104
+ test("guests and customers without addresses get editable empty checkout forms", () => {
105
+ const initial = initialCheckoutAddresses({ country: "HU", cart: {}, savedAddresses: [] })
106
+ assert.equal(initial.shippingSelection, NEW_CHECKOUT_ADDRESS)
107
+ assert.equal(initial.billingSelection, NEW_CHECKOUT_ADDRESS)
108
+ assert.equal(initial.shipping.email, "")
109
+ assert.equal(initial.billingSameAsShipping, true)
110
+ assert.equal(initial.addressOnCart, false)
111
+ assert.deepEqual(initial.shipping, emptyCheckoutAddress("HU"))
112
+ })
113
+
114
+ test("checkout edits only a copy; customer-saved records are not changed", () => {
115
+ const initial = initialCheckoutAddresses({ ...base, cart: {} })
116
+ initial.shipping.address_1 = "Egyszeri cím 25"
117
+ initial.billing.company = "Egyszeri számlázás"
118
+
119
+ const cartPayload = {
120
+ email: initial.shipping.email,
121
+ shipping_address: checkoutAddressPayload(initial.shipping),
122
+ billing_address: checkoutAddressPayload(initial.billing),
123
+ }
124
+ assert.equal(cartPayload.shipping_address.address_1, "Egyszeri cím 25")
125
+ assert.equal(cartPayload.billing_address.company, "Egyszeri számlázás")
126
+ assert.equal(cartPayload.shipping_address.country_code, "hu")
127
+ assert.equal(shipping.address_1, "Fő utca 1")
128
+ assert.equal(billing.company, "Teszt Kft.")
129
+ assert.notStrictEqual(initial.shipping, initial.billing)
130
+ })
131
+
132
+ test("copy-based address normalization does not reuse the original object", () => {
133
+ const copy = checkoutAddressFromRecord(shipping, "HU", "kata@example.com")
134
+ assert.equal(copy.email, "kata@example.com")
135
+ assert.equal(copy.country_code, "HU")
136
+ assert.ok(checkoutAddressesMatch(copy, { ...copy }))
137
+ assert.equal(checkoutAddressesMatch(copy, { ...copy, address_1: "Más" }), false)
138
+ assert.equal(checkoutAddressPayload({ ...copy, address_2: "" }).address_2, undefined)
139
+ })
140
+
141
+ test("partial cart with shipping but no billing must still be explicitly saved", () => {
142
+ const initial = initialCheckoutAddresses({
143
+ ...base, cart: { shipping_address: shipping },
144
+ })
145
+ assert.equal(initial.shippingSelection, "cadr_shipping")
146
+ assert.equal(initial.billingSelection, "cadr_billing")
147
+ assert.equal(initial.addressOnCart, false)
148
+ })
@@ -0,0 +1,68 @@
1
+ import test from "node:test"
2
+ import assert from "node:assert/strict"
3
+ import {
4
+ normalizeHungarianTaxNumber,
5
+ normalizeEuTaxNumber,
6
+ validateCompanyTaxDetails,
7
+ CompanyTaxValidationError,
8
+ } from "../src/lib/core/company-tax.ts"
9
+
10
+ test("private buyers do not need a tax number", () => {
11
+ assert.deepEqual(validateCompanyTaxDetails({
12
+ isCompany: false, company: "", billingTaxNumber: "", billingEuTaxNumber: "",
13
+ }), { isCompany: false, company: "", billingTaxNumber: "", billingEuTaxNumber: "" })
14
+ })
15
+
16
+ test("company can provide only a HU tax number", () => {
17
+ assert.equal(validateCompanyTaxDetails({
18
+ isCompany: true, company: "Minta Kft.",
19
+ billingTaxNumber: "12345678-2-42", billingEuTaxNumber: "",
20
+ }).billingTaxNumber, "12345678-2-42")
21
+ })
22
+
23
+ test("company can provide only an EU VAT number", () => {
24
+ assert.equal(validateCompanyTaxDetails({
25
+ isCompany: true, company: "Minta GmbH",
26
+ billingTaxNumber: "", billingEuTaxNumber: "de 123-456-789",
27
+ }).billingEuTaxNumber, "DE123456789")
28
+ })
29
+
30
+ test("both numbers are accepted and normalized, without overwriting each other", () => {
31
+ assert.deepEqual(validateCompanyTaxDetails({
32
+ isCompany: true, company: "Minta Kft.",
33
+ billingTaxNumber: "12345678242", billingEuTaxNumber: "HU12345678",
34
+ }), {
35
+ isCompany: true, company: "Minta Kft.",
36
+ billingTaxNumber: "12345678-2-42", billingEuTaxNumber: "HU12345678",
37
+ })
38
+ })
39
+
40
+ test("missing company name or both tax numbers is rejected for business billing", () => {
41
+ for (const pair of [["", "HU12345678"], ["12345678-2-42", ""]]) {
42
+ assert.throws(() => validateCompanyTaxDetails({
43
+ isCompany: true, company: "", billingTaxNumber: pair[0], billingEuTaxNumber: pair[1],
44
+ }), CompanyTaxValidationError)
45
+ }
46
+ assert.throws(() => validateCompanyTaxDetails({
47
+ isCompany: true, company: "Minta Kft.", billingTaxNumber: "", billingEuTaxNumber: "",
48
+ }), /legalább/)
49
+ })
50
+
51
+ test("bad syntax and conflicting Hungarian numbers are rejected", () => {
52
+ for (const bad of ["12345678", "12345678-9-42", "1234-56782-42"]) {
53
+ assert.throws(() => normalizeHungarianTaxNumber(bad), CompanyTaxValidationError)
54
+ }
55
+ for (const bad of ["DE123", "US123456789", "HU123456789"]) {
56
+ assert.throws(() => normalizeEuTaxNumber(bad), CompanyTaxValidationError)
57
+ }
58
+ assert.throws(() => validateCompanyTaxDetails({
59
+ isCompany: true, company: "Minta Kft.",
60
+ billingTaxNumber: "12345678-2-42", billingEuTaxNumber: "HU87654321",
61
+ }), /egyeznie kell/)
62
+ })
63
+
64
+ test("private billing is not accidentally contaminated by stale company tax input", () => {
65
+ assert.throws(() => validateCompanyTaxDetails({
66
+ isCompany: false, company: "", billingTaxNumber: "", billingEuTaxNumber: "DE123456789",
67
+ }), CompanyTaxValidationError)
68
+ })
@@ -0,0 +1,74 @@
1
+ import assert from "node:assert/strict"
2
+ import { readFileSync } from "node:fs"
3
+ import { afterEach, test } from "node:test"
4
+ import { ensureDirectGa4Initialized } from "../src/lib/core/ga4-bootstrap.ts"
5
+
6
+ const previousWindow = globalThis.window
7
+
8
+ afterEach(() => {
9
+ if (previousWindow === undefined) delete globalThis.window
10
+ else globalThis.window = previousWindow
11
+ })
12
+
13
+ test("without analytics consent the GA4 tag is not configured", () => {
14
+ const commands = []
15
+ globalThis.window = { gtag: (...args) => commands.push(args) }
16
+ assert.equal(ensureDirectGa4Initialized("G-NOCONSENT01", false), false)
17
+ assert.deepEqual(commands, [])
18
+ })
19
+
20
+ test("invalid or absent measurement IDs do not initialize Google tracking", () => {
21
+ const commands = []
22
+ globalThis.window = { gtag: (...args) => commands.push(args) }
23
+ assert.equal(ensureDirectGa4Initialized(null, true), false)
24
+ assert.equal(ensureDirectGa4Initialized("AW-12345", true), false)
25
+ assert.deepEqual(commands, [])
26
+ })
27
+
28
+ test("initial GA4 config is queued exactly once per measurement ID", () => {
29
+ const commands = []
30
+ globalThis.window = { gtag: (...args) => commands.push(args) }
31
+ assert.equal(ensureDirectGa4Initialized("G-ONCE0001", true), true)
32
+ assert.equal(ensureDirectGa4Initialized("G-ONCE0001", true), true)
33
+ assert.deepEqual(commands.map(args => args[0]), ["js", "config"])
34
+ assert.equal(commands[1][1], "G-ONCE0001")
35
+ })
36
+
37
+ test("GA4 config precedes ecommerce commands even while external script is still loading", () => {
38
+ globalThis.window = { dataLayer: [] }
39
+ assert.equal(ensureDirectGa4Initialized("G-QUEUE0001", true), true)
40
+ globalThis.window.gtag("event", "purchase", { transaction_id: "order_123", send_to: "G-QUEUE0001" })
41
+ assert.deepEqual(globalThis.window.dataLayer.map(args => args[0]), ["js", "config", "event"])
42
+ assert.equal(globalThis.window.dataLayer[2][1], "purchase")
43
+ assert.equal(globalThis.window.dataLayer[2][2].send_to, "G-QUEUE0001")
44
+ })
45
+
46
+ test("multiple GA4 destinations each receive their own config", () => {
47
+ const commands = []
48
+ globalThis.window = { gtag: (...args) => commands.push(args) }
49
+ ensureDirectGa4Initialized("G-STORE001", true)
50
+ ensureDirectGa4Initialized("G-STORE002", true)
51
+ assert.deepEqual(commands.filter(args => args[0] === "config").map(args => args[1]), ["G-STORE001", "G-STORE002"])
52
+ })
53
+
54
+ test("payment success replays the purchase for GA4 and consent changes without changing Medusa checkout", () => {
55
+ const success = readFileSync(new URL("../src/app/checkout/success/page.tsx", import.meta.url), "utf8")
56
+ const component = readFileSync(new URL("../src/components/google-analytics-purchase.tsx", import.meta.url), "utf8")
57
+ const checkout = readFileSync(new URL("../src/lib/core/checkout.ts", import.meta.url), "utf8")
58
+ const tracking = readFileSync(new URL("../src/lib/core/tracking.ts", import.meta.url), "utf8")
59
+
60
+ assert.match(success, /<GoogleAnalyticsPurchase analytics=\{config\.analytics\} order=\{order\}/)
61
+ assert.match(component, /trackPurchase\(analytics, order\)/)
62
+ assert.match(component, /window\.addEventListener\(COOKIE_CONSENT_EVENT, send\)/)
63
+ assert.match(checkout, /trackPurchase\(config\.analytics, result\.order\)/)
64
+ assert.match(tracking, /core:analytics:event:\$\{event\}:\$\{options\.dedupeKey\}/)
65
+ assert.match(tracking, /send_to: analytics\.google_analytics\.measurement_id/)
66
+ })
67
+
68
+ test("direct GA4 loader shares initialization and GTM remains the single container loader", () => {
69
+ const gate = readFileSync(new URL("../src/components/analytics.tsx", import.meta.url), "utf8")
70
+ assert.match(gate, /ensureDirectGa4Initialized\(ga4Id, true\)/)
71
+ assert.match(gate, /mode === "gtm"/)
72
+ assert.match(gate, /mode === "ga4"/)
73
+ assert.doesNotMatch(gate, /core-ga4-config/)
74
+ })
@@ -0,0 +1,92 @@
1
+ import test from "node:test"
2
+ import assert from "node:assert/strict"
3
+ import { stripeCheckoutPhase } from "../src/lib/core/stripe-checkout-phase.ts"
4
+ import { paymentClientSecret } from "../src/lib/core/commerce.ts"
5
+
6
+ const stripe = "pp_stripe_stripe"
7
+ const input = {
8
+ sessionProviderId: "",
9
+ selectedProviderId: stripe,
10
+ busy: null,
11
+ clientSecret: "pi_test_secret_123",
12
+ publishableKey: "pk_test_123",
13
+ initializationError: null,
14
+ }
15
+
16
+ test("selecting Stripe before Medusa returns client_secret shows preparing, not missing-secret error", () => {
17
+ assert.equal(stripeCheckoutPhase({
18
+ ...input,
19
+ busy: "payment",
20
+ clientSecret: null,
21
+ }), "preparing")
22
+ })
23
+
24
+ test("Stripe is ready only after session resolves with matching client_secret and key", () => {
25
+ assert.equal(stripeCheckoutPhase(input), "ready")
26
+ assert.equal(stripeCheckoutPhase({ ...input, clientSecret: null }), "error")
27
+ assert.equal(stripeCheckoutPhase({ ...input, publishableKey: "" }), "error")
28
+ })
29
+
30
+ test("a real initialization error remains visible after the request completes", () => {
31
+ assert.equal(stripeCheckoutPhase({
32
+ ...input,
33
+ initializationError: "Payment initialization failed",
34
+ }), "error")
35
+ assert.equal(stripeCheckoutPhase({
36
+ ...input,
37
+ busy: "payment",
38
+ initializationError: "previous transient error",
39
+ }), "preparing")
40
+ })
41
+
42
+ test("non-Stripe providers do not get Stripe warnings or spinner", () => {
43
+ assert.equal(stripeCheckoutPhase({
44
+ ...input,
45
+ selectedProviderId: "pp_system_default",
46
+ clientSecret: null,
47
+ busy: "payment",
48
+ }), "hidden")
49
+ assert.equal(stripeCheckoutPhase({
50
+ ...input, selectedProviderId: "", sessionProviderId: "pp_simplepay_simplepay",
51
+ }), "hidden")
52
+ })
53
+
54
+ test("explicit Stripe choice wins over a previous payment-session provider", () => {
55
+ assert.equal(stripeCheckoutPhase({
56
+ ...input,
57
+ sessionProviderId: "pp_system_default",
58
+ busy: "payment",
59
+ clientSecret: null,
60
+ }), "preparing")
61
+ })
62
+
63
+ test("returning to an existing Stripe session can render or retry without a new selection", () => {
64
+ assert.equal(stripeCheckoutPhase({
65
+ ...input, selectedProviderId: "", sessionProviderId: stripe,
66
+ }), "ready")
67
+ assert.equal(stripeCheckoutPhase({
68
+ ...input, selectedProviderId: "", sessionProviderId: stripe, clientSecret: null,
69
+ }), "error")
70
+ })
71
+
72
+ test("client_secret resolves from requested Stripe session, never stale session[0]", () => {
73
+ const cart = {
74
+ payment_collection: {
75
+ payment_sessions: [
76
+ { provider_id: "pp_system_default", data: { client_secret: "wrong_method" } },
77
+ { provider_id: stripe, data: { client_secret: "pi_123_secret_safe" } },
78
+ ],
79
+ },
80
+ }
81
+ assert.equal(paymentClientSecret(cart, stripe), "pi_123_secret_safe")
82
+ assert.equal(paymentClientSecret(cart, "pp_stripe_missing"), null)
83
+ assert.equal(paymentClientSecret(cart, "pp_system_default"), "wrong_method")
84
+ assert.equal(paymentClientSecret(cart), "wrong_method") // legacy single-session API unchanged
85
+ })
86
+
87
+ test("missing Stripe session cannot accidentally reuse a SimplePay session", () => {
88
+ const cart = {
89
+ payment_collection: { payment_sessions: [{ provider_id: "pp_simplepay_simplepay", data: { client_secret: "wrong" } }] },
90
+ }
91
+ assert.equal(paymentClientSecret(cart, stripe), null)
92
+ })