@revenexx/cover 0.24.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.
@@ -136,9 +136,13 @@ async function pay(): Promise<void> {
136
136
  if (statusCode === 402 || statusCode === 422) {
137
137
  attempt.value = crypto.randomUUID();
138
138
  }
139
+ const failure = err as { data?: { message?: string; data?: { type?: string } } };
139
140
  toast.add({
140
141
  title: t("orders.pay.failed"),
141
- description: (err as { data?: { message?: string } })?.data?.message ?? (err instanceof Error ? err.message : undefined),
142
+ // A method the merchant does not allow the buyer's company (RAD-513).
143
+ description: failure?.data?.data?.type === "method_not_allowed_for_organization"
144
+ ? t("orders.pay.methodNotAllowedForOrganization")
145
+ : failure?.data?.message ?? (err instanceof Error ? err.message : undefined),
142
146
  color: "error",
143
147
  icon: icon("error"),
144
148
  });
@@ -1,4 +1,6 @@
1
1
  <script setup lang="ts">
2
+ import { setErrors } from "@formkit/core";
3
+
2
4
  import { COUNTRIES } from "../../config/countries";
3
5
  import { REQUIRED_MARK, REQUIRED_MARK_LEADING } from "../../config/forms";
4
6
  import type { RegisterFormState, RegistrationMode, RegistrationProfile } from "../../interfaces/auth";
@@ -36,6 +38,8 @@ const vatRequired = computed(() => registration.value?.vatRequired === true);
36
38
  const needsApproval = computed(() => registration.value?.mode === "approval_required");
37
39
  const applied = ref(false);
38
40
 
41
+ const FORM_ID = "cover-register";
42
+
39
43
  /**
40
44
  * How far the customers app checks a VAT id.
41
45
  *
@@ -147,7 +151,11 @@ async function onSubmit(): Promise<void> {
147
151
  emit("success");
148
152
  }
149
153
  catch {
150
- // error is set on the store and rendered by UAlert
154
+ // error is set on the store and rendered by UAlert. A VAT id the
155
+ // customers app refused is also marked at its field.
156
+ if (error.value === "auth.register.errors.vatIdInvalid") {
157
+ setErrors(FORM_ID, [], { vatId: t(error.value) });
158
+ }
151
159
  }
152
160
  }
153
161
  </script>
@@ -223,6 +231,7 @@ async function onSubmit(): Promise<void> {
223
231
 
224
232
  <FormKit
225
233
  v-if="registrationEnabled && !applied"
234
+ :id="FORM_ID"
226
235
  type="form"
227
236
  :actions="false"
228
237
  @submit="onSubmit"
@@ -23,6 +23,10 @@ function mapAuthError(err: unknown, context: "login" | "recovery" | "register" =
23
23
  return "auth.register.errors.emailExists";
24
24
  case "registration_disabled":
25
25
  return "auth.register.errors.registrationDisabled";
26
+ case "vat_id_invalid":
27
+ return "auth.register.errors.vatIdInvalid";
28
+ case "address_invalid":
29
+ return "auth.register.errors.addressInvalid";
26
30
  case "service_unavailable":
27
31
  return "auth.errors.serviceUnavailable";
28
32
  case "general_rate_limit_exceeded":
@@ -474,6 +474,13 @@ export function useCheckoutOnePage() {
474
474
  submitError.value = refusal.message;
475
475
  return null;
476
476
  }
477
+ // A method the merchant does not allow the buyer's company (RAD-513).
478
+ // The checkout no longer offers one, so this is a page that was open
479
+ // before the merchant changed the list: say so in the buyer's words.
480
+ if ((err as { data?: { data?: { type?: string } } })?.data?.data?.type === "method_not_allowed_for_organization") {
481
+ submitError.value = t("onepage.payment.methodNotAllowedForOrganization");
482
+ return null;
483
+ }
477
484
  submitError.value = err instanceof Error
478
485
  ? err.message
479
486
  : t("onepage.errors.submitError");
@@ -174,7 +174,8 @@
174
174
  "failed": "Die Zahlung ist nicht durchgegangen",
175
175
  "due": "Diese Bestellung wartet auf Ihre Zahlung",
176
176
  "unavailable": "Diese Zahlungsart ist für diese Bestellung gerade nicht verfügbar. Bitte kontaktieren Sie uns.",
177
- "settled": "Diese Bestellung wartet nicht mehr auf eine Zahlung."
177
+ "settled": "Diese Bestellung wartet nicht mehr auf eine Zahlung.",
178
+ "methodNotAllowedForOrganization": "Diese Zahlart steht für Ihr Unternehmen nicht zur Verfügung."
178
179
  },
179
180
  "messages": {
180
181
  "title": "Nachrichten zu dieser Bestellung",
@@ -29,6 +29,8 @@
29
29
  "emailFormat": "Bitte geben Sie eine gültige E-Mail-Adresse ein",
30
30
  "passwordsMismatch": "Passwörter stimmen nicht überein",
31
31
  "registrationDisabled": "Die Registrierung ist derzeit geschlossen. Bitte kontaktieren Sie uns, um ein Konto einzurichten.",
32
+ "vatIdInvalid": "Die USt-IdNr. wurde nicht angenommen. Bitte prüfen Sie die Nummer.",
33
+ "addressInvalid": "Die Rechnungsadresse wurde nicht angenommen. Bitte prüfen Sie Straße, PLZ, Ort und Land.",
32
34
  "emailExists": "Für diese E-Mail-Adresse besteht bereits ein Konto. Bitte melden Sie sich an oder setzen Sie Ihr Passwort zurück.",
33
35
  "network": "Server nicht erreichbar. Bitte prüfen Sie Ihre Verbindung und versuchen Sie es erneut.",
34
36
  "unknown": "Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut."
@@ -163,6 +163,7 @@
163
163
  "cardDetails": "Kartendaten",
164
164
  "cardOnProviderPage": "Sie geben Ihre Kartendaten nach dem Absenden auf der Zahlungsseite des Anbieters ein.",
165
165
  "cardFieldUnavailable": "Das Kartenfeld ist gerade nicht verfügbar. Bitte versuchen Sie es erneut oder wählen Sie eine andere Zahlungsart.",
166
+ "methodNotAllowedForOrganization": "Diese Zahlart steht für Ihr Unternehmen nicht zur Verfügung.",
166
167
  "change": "Ändern",
167
168
  "noMethod": "Keine Zahlungsmethode ausgewählt",
168
169
  "confirm": "Bestätigen",
@@ -174,7 +174,8 @@
174
174
  "failed": "The payment did not go through",
175
175
  "due": "This order is waiting for your payment",
176
176
  "unavailable": "This payment method cannot be used for this order right now. Please contact us.",
177
- "settled": "This order is no longer waiting for a payment."
177
+ "settled": "This order is no longer waiting for a payment.",
178
+ "methodNotAllowedForOrganization": "This payment method is not available for your company."
178
179
  },
179
180
  "messages": {
180
181
  "title": "Messages about this order",
@@ -29,6 +29,8 @@
29
29
  "emailFormat": "Please enter a valid email address",
30
30
  "passwordsMismatch": "Passwords do not match",
31
31
  "registrationDisabled": "Registration is currently closed. Please contact us to set up an account.",
32
+ "vatIdInvalid": "The VAT ID was not accepted. Please check the number.",
33
+ "addressInvalid": "The billing address was not accepted. Please check street, postcode, city and country.",
32
34
  "emailExists": "An account with this email address already exists. Please sign in, or reset your password.",
33
35
  "network": "Server unreachable. Please check your connection and try again.",
34
36
  "unknown": "Something went wrong. Please try again."
@@ -163,6 +163,7 @@
163
163
  "cardDetails": "Card details",
164
164
  "cardOnProviderPage": "After you place the order, you enter your card details on the payment provider's page.",
165
165
  "cardFieldUnavailable": "The card field is not available right now. Please try again or choose another payment method.",
166
+ "methodNotAllowedForOrganization": "This payment method is not available for your company.",
166
167
  "change": "Change",
167
168
  "noMethod": "No payment method selected",
168
169
  "confirm": "Confirm",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@revenexx/cover",
3
- "version": "0.24.0",
3
+ "version": "0.24.2",
4
4
  "description": "Cover — revenexx design system for Nuxt. Distributed as a Nuxt layer: generic UI components, theming tokens and stores shared by the demo shop, custom storefronts and the Blokkli theme.",
5
5
  "type": "module",
6
6
  "main": "./nuxt.config.ts",
@@ -1,4 +1,6 @@
1
1
  import {
2
+ isMethodRefusedForOrganization,
3
+ methodRefusedForOrganizationError,
2
4
  orderAwaitsPayment,
3
5
  orderPaymentRequest,
4
6
  paymentCustomerOf,
@@ -94,6 +96,11 @@ export default defineEventHandler(async (event) => {
94
96
  });
95
97
  }
96
98
  catch (err) {
99
+ // The merchant limited the buyer's company to other methods.
100
+ if (isMethodRefusedForOrganization(err)) {
101
+ getLogService().warn(`Payment method for order ${number} refused for the organization`, apiErrorContext(err));
102
+ throw methodRefusedForOrganizationError();
103
+ }
97
104
  // 409 is payments saying the order does not owe this — already paid, or
98
105
  // in another currency; 400/422 a method or instrument it refused. All of
99
106
  // them are the buyer's to read.
@@ -1,19 +1,4 @@
1
- interface RegistrationProfilePayload {
2
- mode: "new" | "existing";
3
- company: string;
4
- vatId?: string;
5
- customerNumber?: string;
6
- address?: {
7
- street: string;
8
- streetNumber: string;
9
- zip: string;
10
- city: string;
11
- country: string;
12
- };
13
- salutation?: string;
14
- jobTitle?: string;
15
- phone?: string;
16
- }
1
+ import type { RegistrationProfilePayload } from "../../utils/registration";
17
2
 
18
3
  interface RegisterPayload {
19
4
  email: string;
@@ -63,35 +48,17 @@ export default defineEventHandler(async (event) => {
63
48
  return user;
64
49
  }
65
50
 
66
- // Public-API mode: the customers app is the system of record. A company
67
- // registration creates the organization (and its platform team) in the
68
- // same call; the contact mirrors to a platform user behind the scenes.
69
- // Public-API mode: the customers app is the system of record. A company
70
- // registration creates the organization (and its platform team) in the
71
- // same call; the contact mirrors to a platform user behind the scenes.
72
- const fullName = (name ?? "").trim();
73
- const splitAt = fullName.lastIndexOf(" ");
74
- const firstName = splitAt > 0 ? fullName.slice(0, splitAt) : fullName;
75
- const lastName = splitAt > 0 ? fullName.slice(splitAt + 1) : "";
76
-
51
+ // Public-API mode: the customers app is the system of record and gets the
52
+ // whole form — company, VAT id, customer number, contact details and the
53
+ // billing address (RAD-507). The JSON request store above is mock-only:
54
+ // in a live shop nobody reads it, and a redeploy loses it.
77
55
  try {
78
- const { contact, user_id: userId } = await useRevenexxSdk().customers.customersAuthRegister({
79
- email,
80
- password,
81
- ...(firstName ? { firstName } : {}),
82
- ...(lastName ? { lastName } : {}),
83
- ...(profile?.company ? { organizationName: profile.company } : {}),
84
- locale: await resolveStoreLocale(event),
85
- }) as unknown as {
56
+ const { contact, user_id: userId } = await registerCustomer<{
86
57
  contact: { id: string; email: string };
87
58
  user_id: string;
88
- };
59
+ }>({ email, password, name, profile, locale: await resolveStoreLocale(event) });
89
60
 
90
- const user = { $id: userId, name: fullName || email, email: contact.email };
91
- if (profile?.company) {
92
- await persistRegistrationRequest(user, profile);
93
- }
94
- return user;
61
+ return { $id: userId, name: splitFullName(name).fullName || email, email: contact.email };
95
62
  }
96
63
  catch (err) {
97
64
  // The tenant turned self-registration off — a deliberate 403 the
@@ -100,6 +67,13 @@ export default defineEventHandler(async (event) => {
100
67
  if (err instanceof RevenexxException && err.code === 403) {
101
68
  throw createError({ statusCode: 403, data: { type: "registration_disabled" } });
102
69
  }
70
+ // A field of the form the customers app refused — the VAT id, the
71
+ // billing address. The form shows it at that field instead of a
72
+ // generic failure.
73
+ const fieldError = registrationFieldErrorType(err);
74
+ if (fieldError) {
75
+ throw createError({ statusCode: 400, data: { type: fieldError } });
76
+ }
103
77
  if (isApiUserError(err)) {
104
78
  throw createError({ statusCode: err.code, data: { type: apiAuthErrorType(err) } });
105
79
  }
@@ -7,6 +7,8 @@ import { orderLinePrices, type PriceResolveAnswer } from "../../utils/orderLineP
7
7
  import { toIsoCountry } from "../../utils/country";
8
8
  import {
9
9
  checkoutTakesPayment,
10
+ isMethodRefusedForOrganization,
11
+ methodRefusedForOrganizationError,
10
12
  orderPaymentRequest,
11
13
  paymentCustomerOf,
12
14
  recordOrderPaymentStatus,
@@ -662,6 +664,11 @@ export default defineEventHandler(async (event) => {
662
664
  if (isError(err)) {
663
665
  throw err;
664
666
  }
667
+ // The merchant limited the buyer's company to other methods.
668
+ if (isMethodRefusedForOrganization(err)) {
669
+ getLogService().warn("Payment method refused for the organization", apiErrorContext(err));
670
+ throw methodRefusedForOrganizationError();
671
+ }
665
672
  // 409 is payments refusing a payment its order does not owe.
666
673
  if (err instanceof RevenexxException && [400, 409, 422].includes(err.code)) {
667
674
  getLogService().error("Payment rejected", apiErrorContext(err));
@@ -1,12 +1,14 @@
1
1
  import type { PaymentOption } from "../../../app/interfaces/payment";
2
+ import { eligiblePaymentMethods } from "../../utils/eligiblePaymentMethods";
2
3
  import type { Locale } from "../../utils/locale";
3
- import { type ApiEligibleMethod, paymentOptionOf } from "../../utils/paymentOptions";
4
+ import { paymentOptionOf } from "../../utils/paymentOptions";
4
5
 
5
6
  /**
6
7
  * The checkout's payment question — "what can THIS buyer pay with?".
7
8
  * Live mode resolves against the payments app (restrictions + fees are
8
9
  * evaluated server-side there); mock mode answers the demo profile's
9
- * static methods. Body: { amount, country, currency? }.
10
+ * static methods. Body: { amount, country, currency? }; the buyer's
11
+ * organization is added from the verified session, never from the body.
10
12
  */
11
13
  export default defineEventHandler(async (event) => {
12
14
  const { amount = 0, country = "", currency = "EUR" } = await readBody<{
@@ -25,11 +27,16 @@ export default defineEventHandler(async (event) => {
25
27
 
26
28
  const locale: Locale = resolveLocale(event);
27
29
  try {
28
- const { methods } = await useRevenexxSdk().paymentsMethods.paymentsMethodsEligible({
30
+ // The buyer's company, when they are signed in for one: a merchant may
31
+ // limit it to some methods, and the payments app filters by it
32
+ // (RAD-513). Verified for this request, never taken from the body.
33
+ const { organization_id: organizationId } = sessionOrderRefs(event);
34
+ const methods = await eligiblePaymentMethods({
29
35
  amount,
30
36
  country,
31
37
  currency,
32
- }) as unknown as { methods: ApiEligibleMethod[] };
38
+ ...(organizationId ? { organizationId } : {}),
39
+ });
33
40
 
34
41
  const options: PaymentOption[] = methods.map(m => paymentOptionOf(m, locale));
35
42
 
@@ -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
+ }
@@ -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
+ }
@@ -0,0 +1,25 @@
1
+ import type { RevenexxSdk } from "./revenexxSdk";
2
+
3
+ type SdkClient = RevenexxSdk["client"];
4
+
5
+ /**
6
+ * The SDK client, adding `extra` to the body of every request it sends.
7
+ *
8
+ * The typed SDK builds a request body from the parameters it knows and drops
9
+ * the rest without a word. Where an app takes a key the SDK has not caught up
10
+ * with, the call is still made through the generated method — its own mapping
11
+ * of the known keys stays the one source — on a client that adds the unknown
12
+ * keys on the way out. Used as `new Orders(clientAdding(sdk.client, extra))`.
13
+ */
14
+ export function clientAdding(client: SdkClient, extra: Record<string, unknown>): SdkClient {
15
+ return new Proxy(client, {
16
+ get(target, prop, receiver) {
17
+ if (prop === "call") {
18
+ return (method: string, url: URL, headers: Record<string, string>, payload?: Record<string, unknown>) =>
19
+ target.call(method, url, headers, { ...(payload ?? {}), ...extra } as never);
20
+ }
21
+ const value = Reflect.get(target, prop, receiver);
22
+ return typeof value === "function" ? value.bind(target) : value;
23
+ },
24
+ });
25
+ }