@revenexx/cover 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/app/api/account.ts +1 -0
  2. package/app/components/RevenexxForm.vue +183 -19
  3. package/app/components/account/address/AccountAddressCard.vue +8 -2
  4. package/app/components/account/address/AccountAddressView.vue +5 -1
  5. package/app/components/account/carts/AccountCartsTable.vue +85 -3
  6. package/app/components/account/dashboard/AccountDashboardBudgets.vue +2 -1
  7. package/app/components/account/dashboard/AccountDashboardRecentOrders.vue +2 -1
  8. package/app/components/account/dashboard/AccountDashboardRequisitions.vue +2 -1
  9. package/app/components/account/directorder/AccountDirectOrder.vue +100 -12
  10. package/app/components/account/governance/AccountApprovalLimitsTable.vue +124 -8
  11. package/app/components/account/governance/AccountCostCenterDetail.vue +3 -2
  12. package/app/components/account/governance/AccountCostCentersTable.vue +133 -6
  13. package/app/components/account/governance/AccountRequisitionDetail.vue +2 -1
  14. package/app/components/account/governance/AccountRequisitionsTable.vue +102 -6
  15. package/app/components/account/governance/AccountWorkflowDetail.vue +3 -2
  16. package/app/components/account/governance/AccountWorkflowsTable.vue +76 -1
  17. package/app/components/account/governance/GovernanceApprovalLimitModal.vue +8 -0
  18. package/app/components/account/governance/GovernanceCostCenterModal.vue +7 -0
  19. package/app/components/account/governance/GovernanceWorkflowModal.vue +7 -0
  20. package/app/components/account/orderlists/AccountOrderListDetail.vue +14 -4
  21. package/app/components/account/orderlists/AccountOrderListsTable.vue +115 -7
  22. package/app/components/account/orders/AccountOrderDetail.vue +67 -3
  23. package/app/components/account/orders/AccountOrderPay.vue +211 -0
  24. package/app/components/account/orders/AccountOrdersTable.vue +119 -10
  25. package/app/components/account/organization/AccountOrganization.vue +6 -0
  26. package/app/components/account/profile/AccountPasswordForm.vue +2 -0
  27. package/app/components/account/profile/AccountProfileForm.vue +4 -0
  28. package/app/components/account/quotes/AccountQuoteDetail.vue +7 -10
  29. package/app/components/account/team/AccountTeam.vue +91 -0
  30. package/app/components/auth/AuthLoginTeaser.vue +1 -1
  31. package/app/components/auth/AuthRegisterPanel.vue +22 -3
  32. package/app/components/cart/manage/CartNameModal.vue +4 -0
  33. package/app/components/checkout/onepage/CheckoutAddressSection.vue +5 -1
  34. package/app/components/checkout/onepage/CheckoutGuestDetailsSection.vue +9 -1
  35. package/app/components/checkout/onepage/CheckoutSummarySection.vue +6 -1
  36. package/app/components/form/FormPage.vue +7 -4
  37. package/app/components/layout/footer/Footer.vue +15 -2
  38. package/app/components/ui/forms/PasswordInput.vue +2 -0
  39. package/app/components/ui/table/TableCardList.vue +69 -0
  40. package/app/components/ui/table/TableSortButton.vue +1 -1
  41. package/app/components/ui/table/TableToolbar.vue +2 -0
  42. package/app/components/withdrawal/WithdrawalDeclaration.vue +286 -0
  43. package/app/composables/useCheckoutOnePage.ts +22 -0
  44. package/app/composables/useMobileTableSort.ts +82 -0
  45. package/app/config/forms.ts +8 -0
  46. package/app/config/navigation.ts +8 -0
  47. package/app/formkit.config.ts +21 -0
  48. package/app/interfaces/account/order-list.ts +11 -0
  49. package/app/interfaces/account/quotes.ts +7 -3
  50. package/app/pages/punchout/transfer.vue +36 -1
  51. package/app/pages/widerruf.vue +33 -0
  52. package/app/shared/addressLines.ts +66 -0
  53. package/app/shared/checkoutAddressRefusal.ts +63 -0
  54. package/i18n/locales/de/account.json +13 -1
  55. package/i18n/locales/de/cart.json +1 -0
  56. package/i18n/locales/de/checkout.json +1 -1
  57. package/i18n/locales/de/common.json +7 -0
  58. package/i18n/locales/de/withdrawal.json +34 -0
  59. package/i18n/locales/en/account.json +13 -1
  60. package/i18n/locales/en/cart.json +1 -0
  61. package/i18n/locales/en/checkout.json +1 -1
  62. package/i18n/locales/en/common.json +7 -0
  63. package/i18n/locales/en/withdrawal.json +34 -0
  64. package/nuxt.config.ts +3 -0
  65. package/package.json +1 -1
  66. package/server/api/account/orders/[id]/pay.post.ts +100 -0
  67. package/server/api/account/orders/[id].get.ts +5 -1
  68. package/server/api/account/quotes/[id]/order.post.ts +22 -22
  69. package/server/api/forms/[slug].get.ts +1 -3
  70. package/server/api/orders/index.post.ts +33 -50
  71. package/server/api/punchout/return.post.ts +3 -1
  72. package/server/data/forms/authored.json +69 -8
  73. package/server/dev/errorHandler.ts +47 -0
  74. package/server/interfaces/punchout.ts +5 -0
  75. package/server/middleware/missing-media.ts +35 -0
  76. package/server/middleware/punchout-hand-back-csp.ts +17 -0
  77. package/server/plugins/vue-devtools-sink.ts +28 -0
  78. package/server/services/ApiCartService.ts +75 -6
  79. package/server/services/MockFormsService.ts +3 -1
  80. package/server/utils/addressRefusal.ts +63 -0
  81. package/server/utils/country.ts +23 -0
  82. package/server/utils/forms.ts +23 -1
  83. package/server/utils/liveOrders.ts +44 -2
  84. package/server/utils/orderPayment.ts +155 -0
  85. package/server/utils/punchoutFormAction.ts +44 -0
@@ -68,6 +68,29 @@ function visitCartId(event: H3Event): string | null {
68
68
  return visit && !visit.handedBack ? visit.cartId : null;
69
69
  }
70
70
 
71
+ /**
72
+ * The query a call on `cartId` has to carry: the visit's pSid as
73
+ * `?session_key=` when the cart is the open visit's own, else null.
74
+ *
75
+ * The visit's cart is owned by its pSid, not by the contact, and every call
76
+ * this BFF makes for a signed-in buyer carries their principal. From carts
77
+ * 3.0.0 on such a call reaches a cart no contact owns only with that cart's
78
+ * key, so every call on the visit's cart presents it (RAD-167). carts accepts
79
+ * it from 2.5.0 on (RAD-252). The typed SDK takes no such parameter yet, so
80
+ * these calls go through the transport's escape hatch.
81
+ */
82
+ function visitCartKey(event: H3Event, cartId: string): { session_key: string } | null {
83
+ const visit = readPunchoutVisit(event);
84
+ return visit && !visit.handedBack && visit.cartId === cartId && visit.psid
85
+ ? { session_key: visit.psid }
86
+ : null;
87
+ }
88
+
89
+ /** A cart's address in the gateway, with an optional sub-path. */
90
+ function cartPath(cartId: string, suffix = ""): string {
91
+ return `/v1/carts/${encodeURIComponent(cartId)}${suffix}`;
92
+ }
93
+
71
94
  /** Storefront CartItem → carts-app line. The snapshot is the loose product copy. */
72
95
  function toApiLine(item: CartItem, position: number): Record<string, unknown> {
73
96
  return {
@@ -175,8 +198,11 @@ export class ApiCartService implements ICartService, ICartManager {
175
198
  }) as unknown as ApiCart;
176
199
  }
177
200
 
178
- private async listItems(cartId: string): Promise<CartItem[]> {
179
- const { items } = await useRevenexxSdk().cartsItems.cartsItemsList({ cartId }) as unknown as { items: ApiCartLine[] };
201
+ private async listItems(event: H3Event, cartId: string): Promise<CartItem[]> {
202
+ const query = visitCartKey(event, cartId);
203
+ const { items } = (query
204
+ ? await useRevenexxSdk().call("GET", cartPath(cartId, "/items"), { query })
205
+ : await useRevenexxSdk().cartsItems.cartsItemsList({ cartId })) as unknown as { items: ApiCartLine[] };
180
206
  return items.map(toCartItem);
181
207
  }
182
208
 
@@ -194,14 +220,20 @@ export class ApiCartService implements ICartService, ICartManager {
194
220
 
195
221
  async getItems(event: H3Event): Promise<CartItem[]> {
196
222
  const cartId = await this.activeCartId(event);
197
- return cartId ? await this.listItems(cartId) : [];
223
+ return cartId ? await this.listItems(event, cartId) : [];
198
224
  }
199
225
 
200
226
  async saveItems(event: H3Event, items: CartItem[]): Promise<void> {
201
227
  const cartId = visitCartId(event) ?? (await this.ensureActiveCart(resolveOwner(event))).id;
228
+ const lines = items.map((item, index) => toApiLine(item, index));
229
+ const query = visitCartKey(event, cartId);
230
+ if (query) {
231
+ await useRevenexxSdk().call("PUT", cartPath(cartId, "/items"), { query, body: { items: lines } });
232
+ return;
233
+ }
202
234
  await useRevenexxSdk().cartsItems.cartsItemsReplace({
203
235
  cartId,
204
- items: items.map((item, index) => toApiLine(item, index)) as unknown as Models.CartItemCreateRequest[],
236
+ items: lines as unknown as Models.CartItemCreateRequest[],
205
237
  });
206
238
  }
207
239
 
@@ -217,7 +249,7 @@ export class ApiCartService implements ICartService, ICartManager {
217
249
  // sends that cart and no other. The visit sees exactly its own cart.
218
250
  const visitCart = visitCartId(event);
219
251
  if (visitCart) {
220
- const cart = await useRevenexxSdk().call<ApiCart>("GET", `/v1/carts/${encodeURIComponent(visitCart)}`);
252
+ const cart = await useRevenexxSdk().call<ApiCart>("GET", cartPath(visitCart), { query: visitCartKey(event, visitCart) ?? {} });
221
253
  return { carts: [{ ...toSummary(cart), active: true }], activeCartId: visitCart };
222
254
  }
223
255
  const carts = await this.listActive(resolveOwner(event));
@@ -244,10 +276,22 @@ export class ApiCartService implements ICartService, ICartManager {
244
276
  }
245
277
 
246
278
  async renameCart(event: H3Event, id: string, name: string): Promise<void> {
279
+ const query = visitCartKey(event, id);
280
+ if (query) {
281
+ await useRevenexxSdk().call("PUT", cartPath(id), { query, body: { name: name.trim() } });
282
+ return;
283
+ }
247
284
  await useRevenexxSdk().carts.cartsUpdate({ id, name: name.trim() });
248
285
  }
249
286
 
250
287
  async deleteCart(event: H3Event, id: string): Promise<void> {
288
+ // The visit's own cart never gets here (assertPunchoutCartKept), but a
289
+ // call on it would need its key all the same.
290
+ const query = visitCartKey(event, id);
291
+ if (query) {
292
+ await useRevenexxSdk().call("DELETE", cartPath(id), { query });
293
+ return;
294
+ }
251
295
  await useRevenexxSdk().carts.cartsDelete({ id });
252
296
  }
253
297
 
@@ -262,11 +306,31 @@ export class ApiCartService implements ICartService, ICartManager {
262
306
  if (!visitCart) {
263
307
  await useRevenexxSdk().carts.cartsActivate({ id });
264
308
  }
265
- return await this.listItems(id);
309
+ return await this.listItems(event, id);
266
310
  }
267
311
 
268
312
  async addItemToCart(event: H3Event, id: string, item: CartItem): Promise<void> {
269
313
  const line = toApiLine(item, 0);
314
+ const query = visitCartKey(event, id);
315
+ if (query) {
316
+ // The wire form of exactly what the typed call below sends.
317
+ await useRevenexxSdk().call("POST", cartPath(id, "/items"), {
318
+ query,
319
+ body: {
320
+ ...(line.product_id ? { product_id: String(line.product_id) } : {}),
321
+ ...(line.sku ? { sku: String(line.sku) } : {}),
322
+ name: String(line.name),
323
+ quantity: Number(line.quantity),
324
+ ...(line.unit ? { unit: String(line.unit) } : {}),
325
+ unit_price: Number(line.unit_price),
326
+ tax_rate: Number(line.tax_rate),
327
+ position: Number(line.position),
328
+ snapshot: line.snapshot,
329
+ metadata: line.metadata,
330
+ },
331
+ });
332
+ return;
333
+ }
270
334
  await useRevenexxSdk().cartsItems.cartsItemsCreate({
271
335
  cartId: id,
272
336
  ...(line.product_id ? { productId: String(line.product_id) } : {}),
@@ -287,6 +351,11 @@ export class ApiCartService implements ICartService, ICartManager {
287
351
  if (!cartId) {
288
352
  return null;
289
353
  }
354
+ const query = visitCartKey(event, cartId);
355
+ if (query) {
356
+ await useRevenexxSdk().call("POST", cartPath(cartId, "/order"), { query, body: { order_ref: orderRef } });
357
+ return cartId;
358
+ }
290
359
  await useRevenexxSdk().carts.cartsOrder({ id: cartId, orderRef });
291
360
  return cartId;
292
361
  }
@@ -5,7 +5,9 @@ import type { FormRow, FormSpamPolicy, FormSubmissionResult, FormSummary, IForms
5
5
  * can produce rather than to look tidy: a contact form (text, email, tel,
6
6
  * select, textarea, checkbox), a price request (the `rxKind: product` field a
7
7
  * product page pre-fills, plus a radio group), and a two-step return request
8
- * with a designed thank-you page.
8
+ * with a designed thank-you page. Beside them the `widerruf` form the
9
+ * withdrawal page (§ 356a BGB) submits to: not rendered from its definition,
10
+ * but its fields have to be declared or the submit route drops them.
9
11
  *
10
12
  * They are authored in German with an English overlay, which is the shape a
11
13
  * live form has: the app stores one base definition and per-locale field texts
@@ -0,0 +1,63 @@
1
+ import { RevenexxException } from "@revenexx/sdk";
2
+
3
+ /**
4
+ * An address the orders app refused (RAD-234, RAD-236).
5
+ *
6
+ * The orders app holds billing and shipping address to the platform's address
7
+ * type and the rules of its country, so a postal code the checkout's own check
8
+ * let through can come back as a 400 `invalid_address` with one sentence
9
+ * naming the field (`shipping_address.postal_code: 2045 is not a postal code in
10
+ * Germany, e.g. 10115.`). This reads that refusal back so the checkout can put
11
+ * the sentence on the field it names rather than in a generic error.
12
+ */
13
+ export interface AddressRefusal {
14
+ /** The field as the orders app named it, e.g. `shipping_address.postal_code`. */
15
+ field: string;
16
+ /** Which of the two addresses it is, or null when the app named neither. */
17
+ address: "billing" | "shipping" | null;
18
+ /** The key of the address type it faults (`postal_code`), or null for the whole address. */
19
+ key: string | null;
20
+ /** The sentence, without the field it names in front. */
21
+ message: string;
22
+ }
23
+
24
+ interface RefusalBody {
25
+ code?: unknown;
26
+ type?: unknown;
27
+ error?: unknown;
28
+ message?: unknown;
29
+ details?: {
30
+ field?: unknown;
31
+ errors?: Array<{ field?: unknown; message?: unknown }>;
32
+ } | null;
33
+ }
34
+
35
+ const str = (value: unknown): string => (typeof value === "string" ? value.trim() : "");
36
+
37
+ export function addressRefusalOf(err: unknown): AddressRefusal | null {
38
+ if (!(err instanceof RevenexxException) || err.code !== 400) {
39
+ return null;
40
+ }
41
+ let body: RefusalBody;
42
+ try {
43
+ body = JSON.parse(String(err.response ?? "")) as RefusalBody;
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ if (!body || typeof body !== "object" || (body.code ?? body.type) !== "invalid_address") {
49
+ return null;
50
+ }
51
+
52
+ const raw = str(body.error) || str(body.message) || err.message;
53
+ const field = str(body.details?.field) || raw.match(/^([\w.]+_address(?:\.[\w.]+)?):/)?.[1] || "";
54
+ const listed = body.details?.errors?.find(e => str(e.field) === field);
55
+ const message = str(listed?.message)
56
+ || (field && raw.startsWith(`${field}:`) ? raw.slice(field.length + 1).trim() : raw);
57
+
58
+ const [column, ...rest] = field.split(".");
59
+ const address = column === "billing_address" ? "billing" : column === "shipping_address" ? "shipping" : null;
60
+ const key = rest.length ? rest.join(".") : null;
61
+
62
+ return { field, address, key, message };
63
+ }
@@ -0,0 +1,23 @@
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.
4
+ 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",
15
+ };
16
+
17
+ export function toIsoCountry(value: unknown): string {
18
+ const raw = String(value ?? "").trim();
19
+ if (/^[A-Za-z]{2}$/.test(raw)) {
20
+ return raw.toUpperCase();
21
+ }
22
+ return COUNTRY_NAME_TO_ISO[raw.toLowerCase()] ?? raw;
23
+ }
@@ -1,6 +1,6 @@
1
1
  import type { H3Event } from "h3";
2
2
 
3
- import type { FormRow, FormSettings, FormSpamPolicy } from "../interfaces/forms";
3
+ import type { FormPublicSettings, FormRow, FormSettings, FormSpamPolicy } from "../interfaces/forms";
4
4
 
5
5
  /**
6
6
  * Run a form's post-submit actions once a submission is recorded. Best-effort
@@ -79,6 +79,28 @@ export function localizeDefinition(
79
79
  });
80
80
  }
81
81
 
82
+ /**
83
+ * The form's own words — submit label, success message — for the visitor.
84
+ *
85
+ * The Cockpit's overlay translates fields only, so these exist in the authored
86
+ * language alone. Shown to a visitor reading another language they would be the
87
+ * one sentence on the page in a language they did not choose; left out, the
88
+ * storefront says the same in its own translated words instead.
89
+ */
90
+ export function localizeSettings(
91
+ settings: FormSettings | null | undefined,
92
+ locale: string,
93
+ ): FormPublicSettings | null {
94
+ if (!settings) {
95
+ return null;
96
+ }
97
+ const base = settings.default_locale ?? "en";
98
+ if (locale && locale !== base) {
99
+ return {};
100
+ }
101
+ return { submit_label: settings.submit_label, success_message: settings.success_message };
102
+ }
103
+
82
104
  /**
83
105
  * The field names a definition declares. Only a named node collects a value —
84
106
  * the same rule the app counts its field ceiling by — so content nodes and step
@@ -1,8 +1,10 @@
1
1
  import type { H3Event } from "h3";
2
2
 
3
3
  import type { AccountOrder, AccountOrderPosition, AccountOrderReturn, AccountOrderStatus, AccountOrderPaymentStatus } from "../../app/interfaces/account/order-list";
4
+ import { addressLines } from "../../app/shared/addressLines";
4
5
 
5
6
  import { verifiedBuyer } from "./buyerIdentity";
7
+ import { toIsoCountry } from "./country";
6
8
 
7
9
  /**
8
10
  * Live orders via the orders app — placing from the checkout snapshot and
@@ -86,9 +88,13 @@ function mapPaymentStatus(status: string): AccountOrderPaymentStatus {
86
88
  return "open";
87
89
  }
88
90
 
91
+ /**
92
+ * One address as the account and the confirmation print it: the lines frozen on
93
+ * the order when there are some, else the address type's keys (RAD-236). The
94
+ * pages split this back on " · ".
95
+ */
89
96
  const addressLine = (a: Record<string, unknown> | null | undefined): string =>
90
- [a?.companyName, a?.street, `${a?.postalCode ?? ""} ${a?.city ?? ""}`.trim()]
91
- .filter(Boolean).join(" · ");
97
+ addressLines(a).join(" · ");
92
98
 
93
99
  /** Units already returned per order_item id, summed across all return records. */
94
100
  function returnedByOrderItem(returns: LiveOrderReturn[] | undefined): Record<string, number> {
@@ -181,9 +187,45 @@ export function mapLiveOrderToAccount(order: LiveOrder): AccountOrder {
181
187
  // cancellation once anything has shipped, so the shop asks the same
182
188
  // question rather than offering a button that answers with an error.
183
189
  cancellable: canBeCancelled(order),
190
+ ...(paymentCountry(order) ? { paymentCountry: paymentCountry(order) } : {}),
184
191
  };
185
192
  }
186
193
 
194
+ /**
195
+ * The country an order is paid from, as the payments app reads one: the billing
196
+ * address's, else the delivery address's, as an ISO code. One answer for both
197
+ * questions asked of it, which methods the order may be paid with and the
198
+ * payment itself, so the methods offered are the ones the payment is taken under.
199
+ */
200
+ export function paymentCountry(order: LiveOrder): string | undefined {
201
+ // `||`, not `??`: an address saved with an empty country names none. The
202
+ // address type's `country_code` first, the old flat key after (RAD-236).
203
+ const billing = order.billing_address;
204
+ const shipping = order.shipping_address;
205
+ return toIsoCountry(billing?.country_code || billing?.country || shipping?.country_code || shipping?.country) || undefined;
206
+ }
207
+
208
+ /**
209
+ * Whether the order itself stands open for a payment.
210
+ *
211
+ * An order that waited for approval was not paid at the checkout, so once it is
212
+ * placed it is open with nothing behind it (RAD-173) — as is one whose payment
213
+ * failed. One still waiting, or called off, owes nothing; one with a payment
214
+ * under way is the payments app's to settle; and one naming no method cannot be
215
+ * paid by the buyer at all. Whether a payment already sits on it is the second
216
+ * half of the question, which only the payments app can answer
217
+ * (`orderAwaitsPayment`).
218
+ */
219
+ export function canBePaid(order: LiveOrder): boolean {
220
+ if (order.status === "pending" || order.status === "cancelled") {
221
+ return false;
222
+ }
223
+ if (!order.payment?.method) {
224
+ return false;
225
+ }
226
+ return order.payment_status === "open" || order.payment_status === "failed";
227
+ }
228
+
187
229
  /**
188
230
  * Whether this order can still be called off.
189
231
  *
@@ -0,0 +1,155 @@
1
+ import { OrderPaymentStatus } from "@revenexx/sdk";
2
+ import type { H3Event } from "h3";
3
+
4
+ import { canBePaid, type LiveOrder } from "./liveOrders";
5
+
6
+ /**
7
+ * When a purchase is paid, and what its payment says about the order (RAD-173).
8
+ *
9
+ * A purchase that waits for somebody's approval is not paid at the checkout:
10
+ * there is no order yet, and the approval may never produce one. It is paid
11
+ * once the order exists — from the order's own page — and every payment for an
12
+ * order names it, so the payments app can hold the payment to the order's
13
+ * currency, buyer and open total.
14
+ */
15
+
16
+ /** Whether the checkout takes the payment now, or leaves it to the order. */
17
+ export function checkoutTakesPayment(livePayments: boolean, awaitingApproval: boolean): boolean {
18
+ return livePayments && !awaitingApproval;
19
+ }
20
+
21
+ export interface OrderPaymentInput {
22
+ method: string;
23
+ amount: number;
24
+ currency: string;
25
+ country: string;
26
+ /** The order's display number. */
27
+ orderRef: string;
28
+ /** The order's id, once the orders app placed it. */
29
+ orderId?: string | null;
30
+ contactId?: string;
31
+ idempotencyKey: string;
32
+ token?: string;
33
+ returnUrl?: string;
34
+ metadata?: Record<string, string>;
35
+ }
36
+
37
+ /** The body the payments app is asked to create a payment with. */
38
+ export function orderPaymentRequest(input: OrderPaymentInput): Record<string, unknown> {
39
+ return {
40
+ method_code: input.method,
41
+ amount: Math.max(0, Math.round(input.amount * 100) / 100),
42
+ currency: input.currency,
43
+ country: input.country,
44
+ order_ref: input.orderRef,
45
+ // The order itself, wherever there is one: payments then checks the
46
+ // payment against it and refuses one the order never owed.
47
+ ...(input.orderId ? { order_id: input.orderId } : {}),
48
+ // Whose payment this is: the account's payments page lists by it
49
+ // (RAD-171). The principal's contact, which payments holds the body to —
50
+ // a guest pays as nobody.
51
+ ...(input.contactId ? { contact_id: input.contactId } : {}),
52
+ idempotency_key: input.idempotencyKey,
53
+ ...(input.token ? { token: input.token } : {}),
54
+ ...(input.returnUrl ? { return_url: input.returnUrl } : {}),
55
+ metadata: input.metadata ?? {},
56
+ };
57
+ }
58
+
59
+ /**
60
+ * The order's payment dimension for what the payments app answered. Its
61
+ * terminal "paid" state is `captured` (PSP auto/manual capture);
62
+ * `succeeded`/`paid` are accepted as synonyms.
63
+ *
64
+ * A failed payment says so, and a cancelled one leaves the order open: neither
65
+ * holds any of the order's money, so the order is still owed and its page
66
+ * offers it for payment (RAD-173). Recorded as pending, a quote order whose
67
+ * payment failed would read as being paid and never be offered.
68
+ */
69
+ export function orderPaymentStatusFor(paymentStatus: string): OrderPaymentStatus {
70
+ if (["captured", "succeeded", "paid"].includes(paymentStatus)) {
71
+ return OrderPaymentStatus.Paid;
72
+ }
73
+ if (paymentStatus === "authorized") {
74
+ return OrderPaymentStatus.Authorized;
75
+ }
76
+ if (paymentStatus === "failed") {
77
+ return OrderPaymentStatus.Failed;
78
+ }
79
+ if (paymentStatus === "cancelled") {
80
+ return OrderPaymentStatus.Open;
81
+ }
82
+ return OrderPaymentStatus.Pending;
83
+ }
84
+
85
+ /**
86
+ * Payment states that hold part of an order's total — the payments app's own
87
+ * rule for what counts against an order. A failed, cancelled or refunded one
88
+ * leaves the order owed again.
89
+ */
90
+ const HOLDING_PAYMENT = new Set(["created", "requires_action", "authorized", "captured"]);
91
+
92
+ interface OrderPaymentRow {
93
+ status: string;
94
+ idempotency_key?: string | null;
95
+ }
96
+
97
+ /**
98
+ * Whether this order waits for the buyer to pay it (RAD-173).
99
+ *
100
+ * The order has to stand open for a payment (`canBePaid`), the storefront has
101
+ * to take live payments, and no payment may already sit on it. That last part
102
+ * is asked of the payments app by the order's number, not its id: payments made
103
+ * before they named the order carry only the number, and an order whose status
104
+ * sync failed back then would otherwise be charged a second time. It is read as
105
+ * the merchant's system, because a buyer's list shows only payments made out to
106
+ * them, and an older payment may be made out to nobody.
107
+ *
108
+ * One payment does not stand in the way: the one made under `idempotencyKey`.
109
+ * That is this same attempt asked again, after its answer was lost. Let through,
110
+ * the payments app replays it, which is how a buyer whose 3-D Secure step was
111
+ * lost on the way back still gets the redirect.
112
+ *
113
+ * Fails closed: a payments app that cannot say means no offer to pay.
114
+ */
115
+ export async function orderAwaitsPayment(event: H3Event, order: LiveOrder, idempotencyKey?: string): Promise<boolean> {
116
+ if (resolvePaymentServiceKey(event) !== "api" || !order.payment?.method) {
117
+ return false;
118
+ }
119
+ if (order.status === "pending" || order.status === "cancelled") {
120
+ return false;
121
+ }
122
+ try {
123
+ const answer = await useTenantSdk().call<{ payments?: OrderPaymentRow[]; items?: OrderPaymentRow[] }>(
124
+ "GET",
125
+ "/v1/payments",
126
+ { query: { order_ref: order.number, limit: 50 } },
127
+ );
128
+ const holding = (answer.payments ?? answer.items ?? []).filter(p => HOLDING_PAYMENT.has(p.status));
129
+ // This attempt's own payment: through, whatever the order says by now —
130
+ // the first call may already have recorded it as pending before its
131
+ // answer was lost.
132
+ if (idempotencyKey !== undefined && holding.some(p => p.idempotency_key === idempotencyKey)) {
133
+ return true;
134
+ }
135
+ return canBePaid(order) && holding.length === 0;
136
+ }
137
+ catch (err) {
138
+ getLogService().error(`Payments for order ${order.number} could not be read`, apiErrorContext(err));
139
+ return false;
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Record on the order what its payment came to — as the merchant's system,
145
+ * because the orders app refuses a payment status from a buyer (RAD-174).
146
+ * Best-effort: the payment stands either way, and a missed sync is logged.
147
+ */
148
+ export async function recordOrderPaymentStatus(orderUuid: string, paymentStatus: string): Promise<void> {
149
+ try {
150
+ await useTenantSdk().orders.ordersPaymentStatusUpdate({ id: orderUuid, status: orderPaymentStatusFor(paymentStatus) });
151
+ }
152
+ catch (err) {
153
+ getLogService().error("Order payment-status sync failed", apiErrorContext(err));
154
+ }
155
+ }
@@ -0,0 +1,44 @@
1
+ import type { PunchoutVisit } from "../interfaces/punchout";
2
+
3
+ /**
4
+ * Where the hand-back form may be submitted to (PE-994).
5
+ *
6
+ * The hand-back is a form the buyer's browser submits to the procurement
7
+ * system's return address — OCI `HOOK_URL`, cXML `BrowserFormPost`, IDS
8
+ * `hookurl`. A shop that answers `form-action 'self'` makes the browser refuse
9
+ * that submit, and the buyer is left on the interstitial with a button that
10
+ * does nothing. The address differs per ERP and per visit, so no static
11
+ * allowlist can cover it: the hand-back page names the one origin THIS visit
12
+ * goes back to, and every other page keeps `'self'`.
13
+ */
14
+
15
+ /** The hand-back page, under any locale prefix. */
16
+ const HAND_BACK_PATH = /(?:^|\/)punchout\/transfer\/?$/;
17
+
18
+ export function isHandBackPath(path: string): boolean {
19
+ return HAND_BACK_PATH.test(path.split("?")[0] ?? "");
20
+ }
21
+
22
+ /**
23
+ * The origin a hand-back payload posts to, or null when the browser posts
24
+ * nothing (a secured OCI visit answers no `target_url`) or the address is not
25
+ * an http(s) URL — anything else must not reach a CSP header.
26
+ */
27
+ export function handBackOrigin(targetUrl: string | null | undefined): string | null {
28
+ if (!targetUrl) {
29
+ return null;
30
+ }
31
+ try {
32
+ const url = new URL(targetUrl);
33
+ return url.protocol === "https:" || url.protocol === "http:" ? url.origin : null;
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ }
39
+
40
+ /** The `form-action` directive the hand-back page answers for this visit. */
41
+ export function handBackFormAction(visit: PunchoutVisit | null): string {
42
+ const origin = visit?.handBackOrigin;
43
+ return origin ? `form-action 'self' ${origin}` : "form-action 'self'";
44
+ }