@revenexx/cover 0.23.0 → 0.24.2

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 (36) hide show
  1. package/app/components/account/orders/AccountOrderPay.vue +5 -1
  2. package/app/components/auth/AuthRegisterPanel.vue +10 -1
  3. package/app/components/checkout/onepage/CheckoutAddressSection.vue +2 -2
  4. package/app/components/checkout/onepage/CheckoutGuestDetailsSection.vue +6 -0
  5. package/app/components/checkout/onepage/CheckoutNotesSection.vue +2 -0
  6. package/app/components/checkout/onepage/CheckoutPaymentSection.vue +2 -0
  7. package/app/components/ui/forms/FormKitDatePicker.vue +1 -1
  8. package/app/composables/useAuthStore.ts +4 -0
  9. package/app/composables/useCheckoutOnePage.ts +7 -0
  10. package/app/shared/signInLink.ts +86 -0
  11. package/i18n/locales/de/account.json +2 -1
  12. package/i18n/locales/de/auth.json +2 -0
  13. package/i18n/locales/de/checkout.json +1 -0
  14. package/i18n/locales/en/account.json +2 -1
  15. package/i18n/locales/en/auth.json +2 -0
  16. package/i18n/locales/en/checkout.json +1 -0
  17. package/nuxt.config.ts +13 -0
  18. package/package.json +23 -21
  19. package/server/api/account/orders/[id]/pay.post.ts +7 -0
  20. package/server/api/auth/register.post.ts +15 -41
  21. package/server/api/campaigns/touches.post.ts +1 -1
  22. package/server/api/orders/index.post.ts +7 -0
  23. package/server/api/payment/methods.post.ts +11 -4
  24. package/server/middleware/market-scope.ts +24 -0
  25. package/server/services/ApiAuthService.ts +14 -3
  26. package/server/utils/appSettings.ts +1 -1
  27. package/server/utils/buyerIdentity.ts +28 -1
  28. package/server/utils/country.ts +71 -12
  29. package/server/utils/eligiblePaymentMethods.ts +37 -0
  30. package/server/utils/locale.ts +2 -2
  31. package/server/utils/market.ts +131 -7
  32. package/server/utils/orderAttribution.ts +1 -17
  33. package/server/utils/orderPayment.ts +26 -1
  34. package/server/utils/registration.ts +149 -0
  35. package/server/utils/revenexxSdk.ts +33 -6
  36. package/server/utils/sdkClientAdding.ts +25 -0
@@ -38,6 +38,8 @@ interface ApiMeAnswer {
38
38
 
39
39
  /** The verified identity of one request, resolved at most once per request. */
40
40
  const ME_KEY = "coverApiAuthMe";
41
+ /** The platform session the cookie named, once it was well-formed enough to ask about. */
42
+ const VERIFIED_SESSION_KEY = "coverApiAuthSession";
41
43
 
42
44
  /**
43
45
  * A short cross-request memory of verified answers, keyed by tenant + user +
@@ -145,15 +147,22 @@ export class ApiAuthService implements IAuthService {
145
147
  if (pending) {
146
148
  return pending;
147
149
  }
148
- const resolving = this.resolve(event).then((user) => {
149
- rememberVerifiedBuyer(event, user);
150
+ const resolving = this.resolve(event).then(({ user, sessionId }) => {
151
+ rememberVerifiedBuyer(event, user, sessionId);
150
152
  return user;
151
153
  });
152
154
  context[ME_KEY] = resolving;
153
155
  return resolving;
154
156
  }
155
157
 
156
- private async resolve(event: H3Event): Promise<AuthUser | null> {
158
+ /** The verified user, and the session it was verified for. */
159
+ private async resolve(event: H3Event): Promise<{ user: AuthUser | null; sessionId?: string }> {
160
+ const user = await this.verify(event);
161
+ const sessionId = user ? (event.context as Record<string, unknown>)[VERIFIED_SESSION_KEY] : undefined;
162
+ return { user, ...(typeof sessionId === "string" ? { sessionId } : {}) };
163
+ }
164
+
165
+ private async verify(event: H3Event): Promise<AuthUser | null> {
157
166
  const raw = getCookie(event, SESSION_COOKIE_NAME);
158
167
  if (!raw) {
159
168
  return null;
@@ -177,6 +186,8 @@ export class ApiAuthService implements IAuthService {
177
186
  return null;
178
187
  }
179
188
 
189
+ // The session every answer below is verified for, whichever path gives it.
190
+ (event.context as Record<string, unknown>)[VERIFIED_SESSION_KEY] = parsed.id;
180
191
  const cacheKey = `${revenexxTenantKey()}\u0000${parsed.userId}\u0000${parsed.id}`;
181
192
  const remembered = verified.get(cacheKey);
182
193
  if (remembered && remembered.until > Date.now()) {
@@ -130,7 +130,7 @@ export async function readAppSettings(event: H3Event | undefined, app: string):
130
130
  return { ...await readDemoAppSettings(app), ...override };
131
131
  }
132
132
 
133
- const market = event ? resolveSelectedMarket(event) : undefined;
133
+ const market = event ? requestMarket(event) : undefined;
134
134
  // Partitioned by tenant: a theme serving several must never answer one
135
135
  // tenant's page with another's settings (see revenexxTenantKey()).
136
136
  const key = `${revenexxTenantKey()}|${app}|${market ?? "-"}`;
@@ -30,6 +30,7 @@ import type { AuthRole, AuthUser } from "../../app/interfaces/auth";
30
30
 
31
31
  const BUYER_KEY = "coverVerifiedBuyer";
32
32
  const PRINCIPAL_KEY = "revenexxPrincipal";
33
+ const SESSION_KEY = "revenexxBuyerSession";
33
34
 
34
35
  type BuyerContext = Record<string, unknown>;
35
36
 
@@ -42,8 +43,12 @@ function contextOf(event: H3Event | undefined): BuyerContext | null {
42
43
  * Record what the identity service answered for this request. Only a verified
43
44
  * answer comes through here; null records "signed out" so a second read in the
44
45
  * same request does not ask again.
46
+ *
47
+ * `sessionId` is the platform session the answer was verified for: the
48
+ * identity service confirmed it is that user's live one, so it may ride beside
49
+ * the principal (buyerSession).
45
50
  */
46
- export function rememberVerifiedBuyer(event: H3Event, user: AuthUser | null): void {
51
+ export function rememberVerifiedBuyer(event: H3Event, user: AuthUser | null, sessionId?: string): void {
47
52
  const context = contextOf(event);
48
53
  if (!context) {
49
54
  return;
@@ -55,6 +60,12 @@ export function rememberVerifiedBuyer(event: H3Event, user: AuthUser | null): vo
55
60
  else {
56
61
  delete context[PRINCIPAL_KEY];
57
62
  }
63
+ if (user?.contactId && sessionId) {
64
+ context[SESSION_KEY] = sessionId;
65
+ }
66
+ else {
67
+ delete context[SESSION_KEY];
68
+ }
58
69
  }
59
70
 
60
71
  /** Forget it again — after a sign-out within the same request. */
@@ -63,6 +74,7 @@ export function forgetVerifiedBuyer(event: H3Event): void {
63
74
  if (context) {
64
75
  delete context[BUYER_KEY];
65
76
  delete context[PRINCIPAL_KEY];
77
+ delete context[SESSION_KEY];
66
78
  }
67
79
  }
68
80
 
@@ -88,6 +100,21 @@ export function buyerPrincipal(event: H3Event | undefined): string {
88
100
  return typeof value === "string" ? value : "";
89
101
  }
90
102
 
103
+ /**
104
+ * The value for `X-Revenexx-Session`: the platform session the verified buyer
105
+ * holds, or "" when there is none (RAD-472).
106
+ *
107
+ * The gateway hands it to the customers app beside the principal, and only
108
+ * then learns whether a sales rep opened that session for the buyer — which it
109
+ * forwards to every app as the acting rep. Without it a handed-over session
110
+ * looks like the buyer's own. It can only ever add the rep: who the buyer is
111
+ * still comes from the principal.
112
+ */
113
+ export function buyerSession(event: H3Event | undefined): string {
114
+ const value = contextOf(event)?.[SESSION_KEY];
115
+ return typeof value === "string" ? value : "";
116
+ }
117
+
91
118
  /**
92
119
  * The contact the request acts for, or undefined. A body that names a contact
93
120
  * to an app enforcing the principal (payments 1.0) has to name exactly this
@@ -1,17 +1,76 @@
1
1
  // Customer addresses may carry the country as a display name ("Deutschland",
2
- // "Austria") — the payments app's eligibility check expects ISO 3166-1
3
- // alpha-2 codes. Two-letter values pass through unchanged.
2
+ // "Austria") — the payments app's eligibility check and the customers app's
3
+ // address type expect ISO 3166-1 alpha-2 codes. Two-letter values pass through
4
+ // unchanged.
5
+ //
6
+ // Every value of the shop's country select (app/config/countries.ts, German
7
+ // names) is listed, plus the English names of the common ones. A static table
8
+ // on purpose: Intl.DisplayNames reverse-lookups depend on the ICU data the
9
+ // runtime ships, and answer withdrawn codes (DD for "Deutschland", CS for
10
+ // "Serbien") first.
4
11
  const COUNTRY_NAME_TO_ISO: Record<string, string> = {
5
- deutschland: "DE", germany: "DE",
6
- österreich: "AT", austria: "AT",
7
- schweiz: "CH", switzerland: "CH",
8
- niederlande: "NL", netherlands: "NL",
9
- frankreich: "FR", france: "FR",
10
- italien: "IT", italy: "IT",
11
- spanien: "ES", spain: "ES",
12
- belgien: "BE", belgium: "BE",
13
- polen: "PL", poland: "PL",
14
- tschechien: "CZ", "czech republic": "CZ", czechia: "CZ",
12
+ "deutschland": "DE", "germany": "DE",
13
+ "österreich": "AT", "austria": "AT",
14
+ "schweiz": "CH", "switzerland": "CH",
15
+ "liechtenstein": "LI",
16
+ "luxemburg": "LU", "luxembourg": "LU",
17
+ "albanien": "AL", "albania": "AL",
18
+ "andorra": "AD",
19
+ "belgien": "BE", "belgium": "BE",
20
+ "bosnien und herzegowina": "BA", "bosnia and herzegovina": "BA",
21
+ "bulgarien": "BG", "bulgaria": "BG",
22
+ "dänemark": "DK", "denmark": "DK",
23
+ "estland": "EE", "estonia": "EE",
24
+ "finnland": "FI", "finland": "FI",
25
+ "frankreich": "FR", "france": "FR",
26
+ "griechenland": "GR", "greece": "GR",
27
+ "irland": "IE", "ireland": "IE",
28
+ "island": "IS", "iceland": "IS",
29
+ "italien": "IT", "italy": "IT",
30
+ "kosovo": "XK",
31
+ "kroatien": "HR", "croatia": "HR",
32
+ "lettland": "LV", "latvia": "LV",
33
+ "litauen": "LT", "lithuania": "LT",
34
+ "malta": "MT",
35
+ "moldau": "MD", "moldova": "MD",
36
+ "monaco": "MC",
37
+ "montenegro": "ME",
38
+ "niederlande": "NL", "netherlands": "NL",
39
+ "nordmazedonien": "MK", "north macedonia": "MK",
40
+ "norwegen": "NO", "norway": "NO",
41
+ "polen": "PL", "poland": "PL",
42
+ "portugal": "PT",
43
+ "rumänien": "RO", "romania": "RO",
44
+ "san marino": "SM",
45
+ "schweden": "SE", "sweden": "SE",
46
+ "serbien": "RS", "serbia": "RS",
47
+ "slowakei": "SK", "slovakia": "SK",
48
+ "slowenien": "SI", "slovenia": "SI",
49
+ "spanien": "ES", "spain": "ES",
50
+ "tschechien": "CZ", "czech republic": "CZ", "czechia": "CZ",
51
+ "türkei": "TR", "turkey": "TR", "türkiye": "TR",
52
+ "ukraine": "UA",
53
+ "ungarn": "HU", "hungary": "HU",
54
+ "vatikanstadt": "VA", "vatican city": "VA",
55
+ "vereinigtes königreich": "GB", "united kingdom": "GB",
56
+ "weißrussland": "BY", "belarus": "BY",
57
+ "zypern": "CY", "cyprus": "CY",
58
+ "australien": "AU", "australia": "AU",
59
+ "brasilien": "BR", "brazil": "BR",
60
+ "china": "CN",
61
+ "indien": "IN", "india": "IN",
62
+ "japan": "JP",
63
+ "kanada": "CA", "canada": "CA",
64
+ "mexiko": "MX", "mexico": "MX",
65
+ "neuseeland": "NZ", "new zealand": "NZ",
66
+ "russland": "RU", "russia": "RU",
67
+ "saudi-arabien": "SA", "saudi arabia": "SA",
68
+ "singapur": "SG", "singapore": "SG",
69
+ "südafrika": "ZA", "south africa": "ZA",
70
+ "südkorea": "KR", "south korea": "KR",
71
+ "taiwan": "TW",
72
+ "vereinigte arabische emirate": "AE", "united arab emirates": "AE",
73
+ "vereinigte staaten": "US", "united states": "US",
15
74
  };
16
75
 
17
76
  export function toIsoCountry(value: unknown): string {
@@ -0,0 +1,37 @@
1
+ import { PaymentsMethods } from "@revenexx/sdk";
2
+
3
+ import type { ApiEligibleMethod } from "./paymentOptions";
4
+ import { clientAdding } from "./sdkClientAdding";
5
+
6
+ export interface EligibilityQuestion {
7
+ amount: number;
8
+ country: string;
9
+ currency: string;
10
+ /**
11
+ * The signed-in buyer's organization, as the identity service verified it
12
+ * for this request — never a value the browser sent. Absent for a guest and
13
+ * for a contact without a company.
14
+ */
15
+ organizationId?: string;
16
+ }
17
+
18
+ /**
19
+ * `POST /v1/payments/methods/eligible` — "what can THIS buyer pay with?".
20
+ *
21
+ * A merchant may limit an organization to some methods (payments, RAD-512);
22
+ * the payments app honours that list only when it is told whose checkout this
23
+ * is, so a signed-in buyer's organization travels as `organization_id`
24
+ * (RAD-513). The typed SDK asks with amount, country and currency only and
25
+ * drops any other key, so the organization is added on the wire, through the
26
+ * same generated method. Guests send none and see every method, as before.
27
+ */
28
+ export async function eligiblePaymentMethods(question: EligibilityQuestion): Promise<ApiEligibleMethod[]> {
29
+ const extra = question.organizationId ? { organization_id: question.organizationId } : {};
30
+ const methods = new PaymentsMethods(clientAdding(useRevenexxSdk().client, extra) as never);
31
+ const { methods: eligible } = await methods.paymentsMethodsEligible({
32
+ amount: question.amount,
33
+ country: question.country,
34
+ currency: question.currency,
35
+ }) as unknown as { methods: ApiEligibleMethod[] };
36
+ return eligible;
37
+ }
@@ -62,7 +62,7 @@ export async function resolveMarketLocale(event: H3Event): Promise<string> {
62
62
  let locales: { code: string; language?: string; isDefault?: boolean; status?: string }[] = [];
63
63
  try {
64
64
  const markets = await getMarketService(event).listMarkets();
65
- const selected = resolveSelectedMarket(event);
65
+ const selected = requestMarket(event);
66
66
  const market = markets.find(m => m.code === selected) ?? markets.find(m => m.isDefault) ?? markets[0];
67
67
  locales = market?.locales ?? [];
68
68
  }
@@ -94,7 +94,7 @@ export async function resolveStoreLocale(event: H3Event): Promise<string> {
94
94
  const language = resolveLocale(event);
95
95
  try {
96
96
  const markets = await getMarketService(event).listMarkets();
97
- const selected = resolveSelectedMarket(event);
97
+ const selected = requestMarket(event);
98
98
  const market = markets.find(m => m.code === selected) ?? markets.find(m => m.isDefault) ?? markets[0];
99
99
  const locales = market?.locales ?? [];
100
100
  if (!locales.length) {
@@ -1,15 +1,20 @@
1
1
  import type { H3Event } from "h3";
2
2
 
3
+ import type { ShopMarket } from "../../app/interfaces/market";
4
+
3
5
  /** Cookie the storefront's locale selector persists the chosen market in. */
4
6
  export const MARKET_COOKIE_NAME = "cover-market";
5
7
 
8
+ /** Where the request's market is remembered once it is resolved (resolveRequestMarket). */
9
+ const REQUEST_MARKET_KEY = "coverRequestMarket";
10
+
11
+ const MARKET_CODE = /^[a-z][a-z0-9_]{0,62}$/;
12
+
6
13
  /**
7
- * The buyer's active market for server-side scoping. Read from the cookie the
8
- * locale selector sets — the BFF forwards it as X-Revenexx-Market
9
- * (client.setMarket), so the gateway's Entity Scoping Engine filters
10
- * market-scoped data to that market plus global (unassigned) rows. Undefined →
11
- * no header → the API returns only global rows, so the shop works before any
12
- * market is chosen. Market slugs are lowercase (e.g. "de").
14
+ * The market the buyer CHOSE, from the cookie the locale selector sets — or
15
+ * undefined when they chose none. Only the choice: which market a request is
16
+ * made in is requestMarket(), which falls back to the shop's own market when
17
+ * nothing was chosen. Market slugs are lowercase (e.g. "de").
13
18
  */
14
19
  export function resolveSelectedMarket(event: H3Event): string | undefined {
15
20
  const raw = getCookie(event, MARKET_COOKIE_NAME);
@@ -17,5 +22,124 @@ export function resolveSelectedMarket(event: H3Event): string | undefined {
17
22
  return undefined;
18
23
  }
19
24
  const code = raw.trim().toLowerCase();
20
- return /^[a-z][a-z0-9_]{0,62}$/.test(code) ? code : undefined;
25
+ return MARKET_CODE.test(code) ? code : undefined;
26
+ }
27
+
28
+ /**
29
+ * Which market a request is made in (RAD-479), among the tenant's active
30
+ * markets: the chosen one when it is one of them, else the shop's own market.
31
+ *
32
+ * The shop's own market is the domain's (RAD-471): a domain in Experience
33
+ * Studio names the market it serves, or none, which means it serves every
34
+ * market and opens in the tenant's default one, else the first. A domain bound
35
+ * to a market the tenant does not run is read as one that names none. Pure,
36
+ * for the tests.
37
+ */
38
+ export function pickRequestMarket(
39
+ markets: readonly ShopMarket[],
40
+ chosen: string | undefined,
41
+ domainMarket?: string | null,
42
+ ): string | undefined {
43
+ if (chosen && markets.some(m => m.code === chosen)) {
44
+ return chosen;
45
+ }
46
+ if (domainMarket && markets.some(m => m.code === domainMarket)) {
47
+ return domainMarket;
48
+ }
49
+ return (markets.find(m => m.isDefault) ?? markets[0])?.code;
50
+ }
51
+
52
+ /** One shop domain as `GET /v1/settings/storefronts` answers it. */
53
+ interface StorefrontRow {
54
+ readonly host?: string;
55
+ readonly market?: string | null;
56
+ }
57
+
58
+ const STOREFRONTS_TTL_MS = 5 * 60 * 1000;
59
+
60
+ // Partitioned by tenant (see revenexxTenantKey()): host → bound market, or
61
+ // null where the domain serves every market. A failed read is remembered as an
62
+ // empty map for the same time, so a gateway without the route costs one call
63
+ // per tenant and TTL, not one per request.
64
+ const storefrontMarkets = new Map<string, { markets: Map<string, string | null>; loadedAt: number }>();
65
+
66
+ /** Test seam: forget every remembered storefront list. */
67
+ export function clearStorefrontMarkets(): void {
68
+ storefrontMarkets.clear();
69
+ }
70
+
71
+ /**
72
+ * The market the domain this request was made to is bound to, from the
73
+ * tenant's storefronts in Experience Studio (RAD-471): its code, or null when
74
+ * the domain serves every market, is not a storefront the platform knows, or
75
+ * the list cannot be read. Host from `Host`, as seoRequestHost reads it.
76
+ */
77
+ export async function domainMarket(event: H3Event): Promise<string | null> {
78
+ let tenant: string;
79
+ try {
80
+ tenant = revenexxTenantKey();
81
+ }
82
+ catch {
83
+ return null;
84
+ }
85
+ let entry = storefrontMarkets.get(tenant);
86
+ if (!entry || Date.now() - entry.loadedAt >= STOREFRONTS_TTL_MS) {
87
+ const markets = new Map<string, string | null>();
88
+ try {
89
+ const answer = await useTenantSdk().call<{ storefronts?: StorefrontRow[] }>("GET", "/v1/settings/storefronts");
90
+ for (const row of answer?.storefronts ?? []) {
91
+ const host = typeof row.host === "string" ? row.host.toLowerCase() : "";
92
+ if (host) {
93
+ markets.set(host, typeof row.market === "string" && MARKET_CODE.test(row.market) ? row.market : null);
94
+ }
95
+ }
96
+ }
97
+ catch {
98
+ // Not readable: no domain names a market, as before the list existed.
99
+ }
100
+ entry = { markets, loadedAt: Date.now() };
101
+ storefrontMarkets.set(tenant, entry);
102
+ }
103
+ return entry.markets.get(seoRequestHost(event)) ?? null;
104
+ }
105
+
106
+ /**
107
+ * Resolve the request's market once, before any handler calls an app, and
108
+ * remember it on the event (server/middleware/market-scope.ts).
109
+ *
110
+ * Every call then carries `X-Revenexx-Market`, which is what Baseline assigns a
111
+ * new row of a market-scoped table to: a cart created without the header was
112
+ * nobody's market. When the markets cannot be read, the request keeps the
113
+ * buyer's choice and nothing else — the same as before markets were read here.
114
+ */
115
+ export async function resolveRequestMarket(event: H3Event): Promise<string | undefined> {
116
+ const context = event.context as Record<string, unknown>;
117
+ if (REQUEST_MARKET_KEY in context) {
118
+ return context[REQUEST_MARKET_KEY] as string | undefined;
119
+ }
120
+ const chosen = resolveSelectedMarket(event);
121
+ let market = chosen;
122
+ try {
123
+ const [markets, bound] = await Promise.all([getMarketService(event).listMarkets(), domainMarket(event)]);
124
+ market = pickRequestMarket(markets, chosen, bound) ?? chosen;
125
+ }
126
+ catch {
127
+ // The markets app could not be asked: the choice, if any, stands.
128
+ }
129
+ context[REQUEST_MARKET_KEY] = market;
130
+ return market;
131
+ }
132
+
133
+ /**
134
+ * The market this request is made in: what resolveRequestMarket() decided, or
135
+ * the buyer's choice while nothing decided yet (startup code, the markets read
136
+ * itself). Synchronous, for the SDK client. Undefined → no header → the gateway
137
+ * answers global rows only.
138
+ */
139
+ export function requestMarket(event: H3Event): string | undefined {
140
+ const context = (event as { context?: Record<string, unknown> }).context;
141
+ if (context && REQUEST_MARKET_KEY in context) {
142
+ return context[REQUEST_MARKET_KEY] as string | undefined;
143
+ }
144
+ return resolveSelectedMarket(event);
21
145
  }
@@ -1,7 +1,7 @@
1
1
  import { Orders, RevenexxException } from "@revenexx/sdk";
2
2
 
3
3
  import type { Attribution } from "../../app/shared/campaignAttribution";
4
- import type { RevenexxSdk } from "./revenexxSdk";
4
+ import { clientAdding } from "./sdkClientAdding";
5
5
 
6
6
  /**
7
7
  * `POST /v1/orders/place` with the visit's attribution (RAD-293). The orders
@@ -31,22 +31,6 @@ export function isAttributionRefusal(err: unknown): boolean {
31
31
  return /attribution/i.test(String(err.message ?? ""));
32
32
  }
33
33
 
34
- type SdkClient = RevenexxSdk["client"];
35
-
36
- /** The SDK client, adding `extra` to the body of the request it sends. */
37
- function clientAdding(client: SdkClient, extra: Record<string, unknown>): SdkClient {
38
- return new Proxy(client, {
39
- get(target, prop, receiver) {
40
- if (prop === "call") {
41
- return (method: string, url: URL, headers: Record<string, string>, payload?: Record<string, unknown>) =>
42
- target.call(method, url, headers, { ...(payload ?? {}), ...extra } as never);
43
- }
44
- const value = Reflect.get(target, prop, receiver);
45
- return typeof value === "function" ? value.bind(target) : value;
46
- },
47
- });
48
- }
49
-
50
34
  /**
51
35
  * Keys of a placement the typed SDK does not map and silently drops, sent on
52
36
  * the wire as they are given. `discounts` is what the promotions app decided
@@ -1,4 +1,4 @@
1
- import { OrderPaymentStatus } from "@revenexx/sdk";
1
+ import { OrderPaymentStatus, RevenexxException } from "@revenexx/sdk";
2
2
  import type { H3Event } from "h3";
3
3
 
4
4
  import { canBePaid, type LiveOrder } from "./liveOrders";
@@ -13,6 +13,31 @@ import { canBePaid, type LiveOrder } from "./liveOrders";
13
13
  * currency, buyer and open total.
14
14
  */
15
15
 
16
+ /**
17
+ * The type a payment carries when the payments app refused its method for the
18
+ * buyer's organization (RAD-510): the merchant limited the company to other
19
+ * methods. The checkout no longer offers such a method (RAD-513), so this is
20
+ * the answer to a stale page or a hand-made request — and it is the buyer's to
21
+ * read, not an outage.
22
+ */
23
+ export const METHOD_NOT_ALLOWED_FOR_ORGANIZATION = "method_not_allowed_for_organization";
24
+
25
+ /** Whether the payments app refused the payment's method for the buyer's organization. */
26
+ export function isMethodRefusedForOrganization(err: unknown): boolean {
27
+ return err instanceof RevenexxException
28
+ && err.code === 403
29
+ && apiErrorCode(err) === METHOD_NOT_ALLOWED_FOR_ORGANIZATION;
30
+ }
31
+
32
+ /** The answer this BFF gives for it: a 403 the checkout shows in the buyer's language. */
33
+ export function methodRefusedForOrganizationError(): Error {
34
+ return createError({
35
+ statusCode: 403,
36
+ message: "This payment method is not available for your company.",
37
+ data: { type: METHOD_NOT_ALLOWED_FOR_ORGANIZATION },
38
+ });
39
+ }
40
+
16
41
  /** Whether the checkout takes the payment now, or leaves it to the order. */
17
42
  export function checkoutTakesPayment(livePayments: boolean, awaitingApproval: boolean): boolean {
18
43
  return livePayments && !awaitingApproval;
@@ -0,0 +1,149 @@
1
+ import { Customers, RevenexxException } from "@revenexx/sdk";
2
+
3
+ import { toIsoCountry } from "./country";
4
+ import { clientAdding } from "./sdkClientAdding";
5
+
6
+ /** The company profile the registration form sends beside the credentials. */
7
+ export interface RegistrationProfilePayload {
8
+ mode: "new" | "existing";
9
+ company: string;
10
+ vatId?: string;
11
+ customerNumber?: string;
12
+ address?: {
13
+ street: string;
14
+ streetNumber: string;
15
+ zip: string;
16
+ city: string;
17
+ country: string;
18
+ };
19
+ salutation?: string;
20
+ jobTitle?: string;
21
+ phone?: string;
22
+ }
23
+
24
+ export interface CustomerRegistration {
25
+ email: string;
26
+ password: string;
27
+ /** The buyer's full name as the form joined it ("Erika Mustermann"). */
28
+ name?: string;
29
+ profile?: RegistrationProfilePayload;
30
+ /** BCP 47 tag of the store locale the buyer registered in. */
31
+ locale: string;
32
+ }
33
+
34
+ function text(value: unknown): string {
35
+ return typeof value === "string" ? value.trim() : "";
36
+ }
37
+
38
+ /** First name / last name from the one name field: the last word is the family name. */
39
+ export function splitFullName(name: string | undefined): { fullName: string; firstName: string; lastName: string } {
40
+ const fullName = (name ?? "").trim();
41
+ const splitAt = fullName.lastIndexOf(" ");
42
+ return {
43
+ fullName,
44
+ firstName: splitAt > 0 ? fullName.slice(0, splitAt) : fullName,
45
+ lastName: splitAt > 0 ? fullName.slice(splitAt + 1) : "",
46
+ };
47
+ }
48
+
49
+ /**
50
+ * The keys of `POST /v1/customers/auth/register` (customers, RAD-506) that the
51
+ * typed `customersAuthRegister` does not know and would drop: the contact's
52
+ * salutation, job title and phone, the customer number a buyer says they
53
+ * already have, and the billing address. Empty values are left out — the
54
+ * customers app reads an empty string as a malformed value, not as "none".
55
+ *
56
+ * `customer_number` only travels for an existing customer: it is their claim
57
+ * to be one, and a new customer has none to claim. `billing_address` joins
58
+ * street and house number into one line and names the country by its ISO
59
+ * code, which is what the customers app's address type stores.
60
+ */
61
+ export function registrationExtras(profile: RegistrationProfilePayload | undefined, fullName: string): Record<string, unknown> {
62
+ if (!profile) {
63
+ return {};
64
+ }
65
+ const extra: Record<string, unknown> = {};
66
+ const salutation = text(profile.salutation);
67
+ const jobTitle = text(profile.jobTitle);
68
+ const phone = text(profile.phone);
69
+ const customerNumber = text(profile.customerNumber);
70
+ if (salutation) {
71
+ extra.salutation = salutation;
72
+ }
73
+ if (jobTitle) {
74
+ extra.job_title = jobTitle;
75
+ }
76
+ if (phone) {
77
+ extra.phone = phone;
78
+ }
79
+ if (profile.mode === "existing" && customerNumber) {
80
+ extra.customer_number = customerNumber;
81
+ }
82
+
83
+ const address = profile.address;
84
+ const street = [text(address?.street), text(address?.streetNumber)].filter(Boolean).join(" ");
85
+ if (address && street) {
86
+ const company = text(profile.company);
87
+ extra.billing_address = {
88
+ street,
89
+ postal_code: text(address.zip),
90
+ city: text(address.city),
91
+ country_code: toIsoCountry(address.country),
92
+ ...(company ? { company } : {}),
93
+ ...(fullName ? { recipient: fullName } : {}),
94
+ };
95
+ }
96
+ return extra;
97
+ }
98
+
99
+ /**
100
+ * Register a buyer with the customers app — the system of record — with
101
+ * everything the form asked for. A company registration founds the
102
+ * organization (and its platform team) in the same call; the contact mirrors
103
+ * to a platform user behind the scenes.
104
+ *
105
+ * The keys the typed SDK knows go through its own mapping; the rest are added
106
+ * on the wire (clientAdding), so nothing the buyer typed is dropped.
107
+ */
108
+ export async function registerCustomer<T = unknown>(input: CustomerRegistration): Promise<T> {
109
+ const { fullName, firstName, lastName } = splitFullName(input.name);
110
+ const profile = input.profile;
111
+ const company = text(profile?.company);
112
+ const vatId = text(profile?.vatId);
113
+ const customers = new Customers(clientAdding(useRevenexxSdk().client, registrationExtras(profile, fullName)) as never);
114
+
115
+ return await customers.customersAuthRegister({
116
+ email: input.email,
117
+ password: input.password,
118
+ ...(firstName ? { firstName } : {}),
119
+ ...(lastName ? { lastName } : {}),
120
+ ...(company ? { organizationName: company } : {}),
121
+ ...(vatId ? { vatId } : {}),
122
+ locale: input.locale,
123
+ }) as unknown as T;
124
+ }
125
+
126
+ /**
127
+ * A 400 the customers app raised over one of the form's fields, as the type
128
+ * the registration form shows at that field — or null when the refusal is
129
+ * about something else.
130
+ *
131
+ * A VAT id the tenant requires, or whose shape or VIES entry it checks, is
132
+ * refused as `'vat_id' …`; an address its type does not allow as
133
+ * `address_invalid` (customers >= RAD-506 validates `billing_address` with the
134
+ * same rules as an address of the address book).
135
+ */
136
+ export function registrationFieldErrorType(err: unknown): "vat_id_invalid" | "address_invalid" | null {
137
+ if (!(err instanceof RevenexxException) || err.code !== 400) {
138
+ return null;
139
+ }
140
+ const code = apiErrorCode(err);
141
+ const message = String(err.message ?? "");
142
+ if (/vat/i.test(code) || /\bvat_id\b/.test(message)) {
143
+ return "vat_id_invalid";
144
+ }
145
+ if (/address/i.test(code) || /\bbilling_address\b/.test(message)) {
146
+ return "address_invalid";
147
+ }
148
+ return null;
149
+ }