@revenexx/cover 0.2.35 → 0.2.37

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.
@@ -0,0 +1,158 @@
1
+ <script setup lang="ts">
2
+ import type { PunchoutReturnPayload } from "../../interfaces/punchout";
3
+
4
+ /**
5
+ * The interstitial — the buyer is leaving.
6
+ *
7
+ * A punchout cart goes back to the procurement system as a form submitted by
8
+ * the BUYER's browser, inside the buyer's own ERP session. This app cannot
9
+ * post it: a request from a server carries none of that session, and the
10
+ * protocols that expect a browser form post would reject it even if it did. So
11
+ * this page asks the BFF for the payload, builds exactly the form it describes,
12
+ * and submits it.
13
+ *
14
+ * Three things decide what that form looks like, and all three come from the
15
+ * payload rather than from any knowledge of the protocols here:
16
+ *
17
+ * - `encoding` — url-encoded for OCI and cXML, `multipart/form-data` for IDS,
18
+ * whose standard rules a query string out because a cart does not fit in one;
19
+ * - how many fields there are — cXML and IDS carry the whole document in ONE
20
+ * field, OCI carries many (`NEW_ITEM-DESCRIPTION[1]` and its siblings);
21
+ * - whether `target_url` is null — which is what a SECURED OCI visit looks
22
+ * like: the procurement system fetches the cart on its own back channel, and
23
+ * the browser must post nothing at all.
24
+ *
25
+ * `replayed: true` means this visit had already been handed back and the same
26
+ * payload is being answered again. It is submitted like any other — a buyer who
27
+ * pressed back, or a browser that double-submitted, must get the form and not
28
+ * an error page.
29
+ */
30
+ const { t } = useI18n();
31
+ const { icon } = useIcons();
32
+ const { to } = useAppUrl();
33
+ const { protocol } = usePunchoutVisit();
34
+
35
+ definePageMeta({
36
+ // The buyer is on their way out; this page is not part of the shop's
37
+ // navigation and must never be indexed or restored from a cache.
38
+ layout: "default",
39
+ });
40
+
41
+ useHead({
42
+ meta: [{ name: "robots", content: "noindex" }],
43
+ });
44
+
45
+ const form = useTemplateRef<HTMLFormElement>("handBackForm");
46
+ const payload = ref<PunchoutReturnPayload | null>(null);
47
+ const failed = ref<"closed" | "unavailable" | null>(null);
48
+
49
+ /** Everything to submit: the mapped fields, exactly as they must be named. */
50
+ const fields = computed(() => Object.entries(payload.value?.fields ?? {}));
51
+
52
+ /**
53
+ * A secured OCI visit hands nothing over through the browser — the ERP fetches
54
+ * the finished cart itself. There is no form, and inventing one would post a
55
+ * cart to an address the payload deliberately did not name.
56
+ */
57
+ const isBackChannel = computed(() => payload.value !== null && !payload.value.target_url);
58
+
59
+ onMounted(async () => {
60
+ try {
61
+ payload.value = await $fetch<PunchoutReturnPayload>("/api/punchout/return", { method: "POST" });
62
+ }
63
+ catch (err) {
64
+ const type = (err as { data?: { data?: { type?: string } } })?.data?.data?.type;
65
+ failed.value = type === "punchout_session_closed" || type === "punchout_no_session" ? "closed" : "unavailable";
66
+ return;
67
+ }
68
+
69
+ if (isBackChannel.value) {
70
+ return;
71
+ }
72
+
73
+ // One tick so the form is in the DOM, and a beat so the buyer sees where
74
+ // they are going rather than a flash of a page they cannot read.
75
+ await nextTick();
76
+ window.setTimeout(() => form.value?.submit(), 400);
77
+ });
78
+ </script>
79
+
80
+ <template>
81
+ <UContainer class="py-16">
82
+ <div class="mx-auto max-w-lg text-center space-y-4">
83
+ <template v-if="failed">
84
+ <UIcon
85
+ :name="icon('warning')"
86
+ class="size-10 mx-auto text-warning"
87
+ />
88
+ <h1 class="text-xl font-semibold text-highlighted">
89
+ {{ t(`punchout.transfer.failed.${failed}.title`) }}
90
+ </h1>
91
+ <p class="text-sm text-muted">
92
+ {{ t(`punchout.transfer.failed.${failed}.body`) }}
93
+ </p>
94
+ <UButton
95
+ color="neutral"
96
+ variant="subtle"
97
+ :to="to('/cart')"
98
+ :label="t('punchout.transfer.failed.backToCart')"
99
+ />
100
+ </template>
101
+
102
+ <template v-else-if="isBackChannel">
103
+ <UIcon
104
+ :name="icon('success')"
105
+ class="size-10 mx-auto text-success"
106
+ />
107
+ <h1 class="text-xl font-semibold text-highlighted">
108
+ {{ t('punchout.transfer.backChannel.title') }}
109
+ </h1>
110
+ <p class="text-sm text-muted">
111
+ {{ t('punchout.transfer.backChannel.body') }}
112
+ </p>
113
+ </template>
114
+
115
+ <template v-else>
116
+ <UIcon
117
+ :name="icon('upload')"
118
+ class="size-10 mx-auto text-primary animate-pulse"
119
+ />
120
+ <h1 class="text-xl font-semibold text-highlighted">
121
+ {{ t('punchout.transfer.leaving.title') }}
122
+ </h1>
123
+ <p class="text-sm text-muted">
124
+ {{ t(`punchout.transfer.leaving.body.${protocol ?? 'oci'}`) }}
125
+ </p>
126
+
127
+ <!--
128
+ Built from the payload and nothing else. `enctype` is the
129
+ payload's encoding, the action its target, and every field is
130
+ written out with the name it must carry — a browser that has
131
+ JavaScript switched off still gets a button it can press.
132
+ -->
133
+ <form
134
+ v-if="payload"
135
+ ref="handBackForm"
136
+ :action="payload.target_url ?? undefined"
137
+ :method="payload.method || 'POST'"
138
+ :enctype="payload.encoding || 'application/x-www-form-urlencoded'"
139
+ accept-charset="UTF-8"
140
+ >
141
+ <input
142
+ v-for="[name, value] in fields"
143
+ :key="name"
144
+ type="hidden"
145
+ :name="name"
146
+ :value="value"
147
+ >
148
+ <UButton
149
+ type="submit"
150
+ color="primary"
151
+ variant="subtle"
152
+ :label="t('punchout.transfer.leaving.submit')"
153
+ />
154
+ </form>
155
+ </template>
156
+ </div>
157
+ </UContainer>
158
+ </template>
@@ -79,7 +79,9 @@
79
79
  "notOrderable": "Der Warenkorb ist derzeit nicht bestellbar — bitte beheben Sie die genannten Hinweise."
80
80
  },
81
81
  "summary": {
82
- "minOrderHint": "Mindestbestellwert {threshold} — die Differenz wird als Zuschlag berechnet."
82
+ "minOrderHint": "Mindestbestellwert {threshold} — die Differenz wird als Zuschlag berechnet.",
83
+ "voucherPlaceholder": "Aktionscode",
84
+ "voucherApply": "Einlösen"
83
85
  },
84
86
  "workflow": {
85
87
  "pickTitle": "Workflow auswählen",
@@ -224,7 +226,8 @@
224
226
  "shipping": "Versandkosten",
225
227
  "tax": "MwSt. {percent} %",
226
228
  "rounding": "Rundungsdifferenz",
227
- "total": "Total"
229
+ "total": "Total",
230
+ "discountGeneric": "Rabatt"
228
231
  },
229
232
  "recyclingFee": "Recyclinggebühr",
230
233
  "priceLabels": {
@@ -0,0 +1,45 @@
1
+ {
2
+ "punchout": {
3
+ "transfer": {
4
+ "action": {
5
+ "oci": "Warenkorb übernehmen",
6
+ "cxml": "Anforderung zurückgeben",
7
+ "ids": "Warenkorb an Ihre Software senden"
8
+ },
9
+ "hint": {
10
+ "oci": "Der Warenkorb wird an Ihr Beschaffungssystem übergeben. Bestellt wird dort.",
11
+ "cxml": "Die Positionen gehen als Anforderung an Ihr Beschaffungssystem zurück. Bestellt wird dort.",
12
+ "ids": "Der Warenkorb geht an Ihre Handwerkersoftware zurück. Bestellt wird dort."
13
+ },
14
+ "emptyCart": "Ihr Warenkorb ist leer — es gibt nichts zu übergeben.",
15
+ "leaving": {
16
+ "title": "Sie verlassen den Shop",
17
+ "body": {
18
+ "oci": "Ihr Warenkorb wird an Ihr Beschaffungssystem übergeben. Bitte warten Sie einen Moment.",
19
+ "cxml": "Ihre Anforderung wird an Ihr Beschaffungssystem zurückgegeben. Bitte warten Sie einen Moment.",
20
+ "ids": "Ihr Warenkorb wird an Ihre Handwerkersoftware gesendet. Bitte warten Sie einen Moment."
21
+ },
22
+ "submit": "Jetzt übergeben"
23
+ },
24
+ "backChannel": {
25
+ "title": "Warenkorb bereitgestellt",
26
+ "body": "Ihr Beschaffungssystem holt den Warenkorb selbst ab. Sie können dieses Fenster schließen und dort weiterarbeiten."
27
+ },
28
+ "failed": {
29
+ "closed": {
30
+ "title": "Diese Punchout-Sitzung ist beendet",
31
+ "body": "Sie ist abgelaufen oder wurde beendet. Starten Sie den Katalog erneut aus Ihrem Beschaffungssystem."
32
+ },
33
+ "unavailable": {
34
+ "title": "Die Übergabe hat nicht geklappt",
35
+ "body": "Der Warenkorb konnte gerade nicht übergeben werden. Bitte versuchen Sie es in einem Moment noch einmal."
36
+ },
37
+ "backToCart": "Zurück zum Warenkorb"
38
+ }
39
+ },
40
+ "readOnly": {
41
+ "hint": "Diese Anforderung wurde nur zur Ansicht geöffnet und kann hier nicht geändert werden.",
42
+ "badge": "Nur zur Ansicht"
43
+ }
44
+ }
45
+ }
@@ -79,7 +79,9 @@
79
79
  "notOrderable": "The cart cannot be ordered right now — please resolve the notices above."
80
80
  },
81
81
  "summary": {
82
- "minOrderHint": "Minimum order value {threshold} — the difference is charged as a surcharge."
82
+ "minOrderHint": "Minimum order value {threshold} — the difference is charged as a surcharge.",
83
+ "voucherPlaceholder": "Promotion code",
84
+ "voucherApply": "Apply"
83
85
  },
84
86
  "workflow": {
85
87
  "pickTitle": "Select workflow",
@@ -224,7 +226,8 @@
224
226
  "shipping": "Shipping costs",
225
227
  "tax": "VAT {percent} %",
226
228
  "rounding": "Rounding difference",
227
- "total": "Total"
229
+ "total": "Total",
230
+ "discountGeneric": "Discount"
228
231
  },
229
232
  "recyclingFee": "Recycling fee",
230
233
  "priceLabels": {
@@ -0,0 +1,45 @@
1
+ {
2
+ "punchout": {
3
+ "transfer": {
4
+ "action": {
5
+ "oci": "Transfer cart",
6
+ "cxml": "Return requisition",
7
+ "ids": "Send cart to your software"
8
+ },
9
+ "hint": {
10
+ "oci": "The cart is handed over to your procurement system. You order there.",
11
+ "cxml": "The lines go back to your procurement system as a requisition. You order there.",
12
+ "ids": "The cart goes back to your trade software. You order there."
13
+ },
14
+ "emptyCart": "Your cart is empty — there is nothing to hand over.",
15
+ "leaving": {
16
+ "title": "You are leaving the shop",
17
+ "body": {
18
+ "oci": "Your cart is being handed over to your procurement system. One moment, please.",
19
+ "cxml": "Your requisition is being returned to your procurement system. One moment, please.",
20
+ "ids": "Your cart is being sent to your trade software. One moment, please."
21
+ },
22
+ "submit": "Hand over now"
23
+ },
24
+ "backChannel": {
25
+ "title": "Cart ready",
26
+ "body": "Your procurement system collects the cart itself. You can close this window and carry on there."
27
+ },
28
+ "failed": {
29
+ "closed": {
30
+ "title": "This punchout session has ended",
31
+ "body": "It ran out or it was ended. Start the catalogue again from your procurement system."
32
+ },
33
+ "unavailable": {
34
+ "title": "The hand-over did not work",
35
+ "body": "The cart could not be handed over just now. Please try again in a moment."
36
+ },
37
+ "backToCart": "Back to the cart"
38
+ }
39
+ },
40
+ "readOnly": {
41
+ "hint": "This requisition was opened for viewing only and cannot be changed here.",
42
+ "badge": "View only"
43
+ }
44
+ }
45
+ }
package/nuxt.config.ts CHANGED
@@ -3,6 +3,7 @@ import { createRequire } from "node:module";
3
3
  import { dirname, resolve } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
 
6
+ import { useNuxt } from "@nuxt/kit";
6
7
  import { defineNuxtConfig } from "nuxt/config";
7
8
 
8
9
  const currentDir = dirname(fileURLToPath(import.meta.url));
@@ -147,4 +148,31 @@ export default defineNuxtConfig({
147
148
  { code: "en", language: "en-US", files: layerLocaleFiles("en") },
148
149
  ],
149
150
  },
151
+
152
+ hooks: {
153
+ /**
154
+ * Hand the consuming app's i18n routing strategy to the server.
155
+ *
156
+ * `/punchout/start` is a Nitro route: it signs the buyer in and then
157
+ * has to REDIRECT them to a shop path — the cart, an article, a search.
158
+ * Which path that is depends on how the app prefixes locales, and the
159
+ * two storefronts here answer differently (`prefix` in the demo shop,
160
+ * `prefix_except_default` in the themes). A server route cannot ask the
161
+ * Vue router, and `@nuxtjs/i18n` v10 does not publish the strategy in
162
+ * runtime config, so it is copied here, once, at build time.
163
+ *
164
+ * Getting it wrong is not cosmetic: under `prefix`, an unprefixed
165
+ * `/cart` is a 404, so a punchout buyer would be signed in and dropped
166
+ * on an error page.
167
+ */
168
+ "modules:done": () => {
169
+ const nuxt = useNuxt();
170
+ const i18n = (nuxt.options as { i18n?: { strategy?: string; defaultLocale?: string } }).i18n;
171
+ nuxt.options.runtimeConfig.punchout = {
172
+ ...(nuxt.options.runtimeConfig.punchout as Record<string, unknown> | undefined),
173
+ localeStrategy: i18n?.strategy ?? "no_prefix",
174
+ defaultLocale: i18n?.defaultLocale ?? "",
175
+ };
176
+ },
177
+ },
150
178
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@revenexx/cover",
3
- "version": "0.2.35",
3
+ "version": "0.2.37",
4
4
  "description": "Cover \u2014 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",
@@ -52,6 +52,7 @@
52
52
  "vue-i18n": "^11.0.0 || ^10.0.0"
53
53
  },
54
54
  "devDependencies": {
55
+ "@nuxt/kit": "^4.4.8",
55
56
  "nuxt": "^4.4.2"
56
57
  },
57
58
  "publishConfig": {
@@ -57,6 +57,42 @@ async function resolveLiveOverrides(
57
57
  }
58
58
  }
59
59
 
60
+ // Promotions run AFTER prices: the engine reduces prices and refuses a line
61
+ // that has none, so it needs the resolved ones. It writes nothing, which is
62
+ // why the storefront may call it on every keystroke.
63
+ const promo = await evaluatePromotions(event, {
64
+ currency,
65
+ codes: body.voucherCodes,
66
+ lines: body.items.map((it, index) => ({
67
+ // 1-based, the same numbering the order sends when it asks the very
68
+ // same engine about the very same cart. The engine echoes whatever
69
+ // it is given, so either base would balance on its own — but one
70
+ // cart evaluated under two numberings is a trap waiting for the
71
+ // first rule that reads a position.
72
+ position: index + 1,
73
+ sku: it.sku ? String(it.sku) : undefined,
74
+ product_id: String(it.id),
75
+ name: it.name ? String(it.name) : undefined,
76
+ quantity: Number(it.quantity) || 1,
77
+ unit_price: Number(
78
+ overrides.itemUnitPrices?.[String(it.id)]
79
+ ?? overrides.itemUnitPrices?.[String(it.sku ?? "")]
80
+ ?? it.price
81
+ ?? 0,
82
+ ),
83
+ tax_rate: Number(overrides.itemTaxRates?.[String(it.id)] ?? overrides.itemTaxRates?.[String(it.sku ?? "")] ?? it.taxRate ?? 0),
84
+ })),
85
+ });
86
+ if (promo && promo.discountTotal > 0) {
87
+ overrides.promotion = {
88
+ lineDiscounts: promo.lineDiscounts,
89
+ discountTotal: promo.discountTotal,
90
+ // One promotion names the row; several make it a plain "discount",
91
+ // because a row listing three names is a row nobody reads.
92
+ label: promo.applied.length === 1 ? promo.applied[0]!.promotion_name : undefined,
93
+ };
94
+ }
95
+
60
96
  if (resolveShippingServiceKey(event) === "api") {
61
97
  const method = body.deliveryMethod ?? "standard";
62
98
  try {
@@ -103,12 +139,15 @@ export default defineEventHandler(async (event) => {
103
139
  // a second pass folds the live fee + tax rates into the totals. Mock
104
140
  // mode skips the round-trips entirely.
105
141
  const base = await service.calculate(body, context, locale);
106
- if (resolvePriceServiceKey(event) !== "api" && resolveShippingServiceKey(event) !== "api") {
142
+ if (resolvePriceServiceKey(event) !== "api"
143
+ && resolveShippingServiceKey(event) !== "api"
144
+ && resolvePromotionsServiceKey(event) !== "api") {
107
145
  return base;
108
146
  }
109
147
  const subtotal = base.totals.find(row => row.key === "subtotal")?.amount ?? 0;
110
148
  const overrides = await resolveLiveOverrides(event, body, subtotal);
111
- if (!overrides.shipping && !overrides.itemTaxRates && !overrides.itemUnitPrices && !overrides.currency) {
149
+ if (!overrides.shipping && !overrides.itemTaxRates && !overrides.itemUnitPrices
150
+ && !overrides.currency && !overrides.promotion) {
112
151
  return base;
113
152
  }
114
153
  return await service.calculate(body, context, locale, overrides);
@@ -32,6 +32,8 @@ interface OrderPayload {
32
32
  partialDelivery?: boolean;
33
33
  orderNote?: string;
34
34
  promoCode?: string;
35
+ /** The codes the buyer entered on the cart, carried to the engine at submit. */
36
+ voucherCodes?: string[];
35
37
  /** PSP single-use token from the checkout's client-side tokenizer (e.g. Stripe pm_…). */
36
38
  paymentInstrument?: { token?: string };
37
39
  /** Where the PSP returns the buyer after a redirect/3DS step-up. */
@@ -211,6 +213,10 @@ export default defineEventHandler(async (event) => {
211
213
  // The placed order's grand_total (orders app = source of truth) drives
212
214
  // the payment amount, so payment and order can never diverge.
213
215
  let liveOrderTotal: number | null = null;
216
+ // Hoisted out of the placement block on purpose: the catch has to be
217
+ // able to hand back what the try held.
218
+ let cartId: string | null = null;
219
+ let reserved: ReservationOutcome = "not_applicable";
214
220
  if (liveOrders) {
215
221
  const address = body.address as Record<string, unknown>;
216
222
  const billing = address?.billingAddressSameAsShipping === false
@@ -259,9 +265,83 @@ export default defineEventHandler(async (event) => {
259
265
  getLogService().error("Item price/tax resolution failed", apiErrorContext(rateErr));
260
266
  }
261
267
 
268
+ // What the promotions app decided, evaluated once more against the
269
+ // prices that were just resolved — not the figures the cart was
270
+ // last shown with. Minutes can pass in a checkout, and a
271
+ // promotion that has meanwhile expired or run out of budget must
272
+ // not still be honoured because the summary said so.
273
+ //
274
+ // The engine's ATTRIBUTED amounts are carried over unchanged: the
275
+ // orders app applies these very numbers, so what was shown and
276
+ // what is stored agree to the cent. The BFF computes no discount
277
+ // of its own and sends no total — orders is the source of truth
278
+ // for both.
279
+ const promo = await evaluatePromotions(event, {
280
+ currency: selectedCurrency ?? calculation.currency,
281
+ codes: body.voucherCodes,
282
+ ...(contactId ? { contactId } : {}),
283
+ ...(organizationId ? { organizationId } : {}),
284
+ lines: orderItems.map((it, index) => ({
285
+ position: index + 1,
286
+ sku: it.sku ? String(it.sku) : undefined,
287
+ product_id: String(it.id),
288
+ name: String(it.name ?? it.sku ?? it.id),
289
+ quantity: calculation.lines[index]?.adjustedQuantity ?? Number(it.quantity),
290
+ unit_price: itemPrice.get(String(it.id)) ?? itemPrice.get(String(it.sku ?? "")) ?? calculation.lines[index]?.unitPrice ?? Number(it.price ?? 0),
291
+ tax_rate: itemRate.get(String(it.id)) ?? itemRate.get(String(it.sku ?? "")) ?? 0,
292
+ })),
293
+ });
294
+ let discounts = (promo?.applied ?? []).map(a => ({
295
+ promotion_id: a.promotion_id,
296
+ promotion_name: a.promotion_name,
297
+ ...(a.voucher_code ? { voucher_code: a.voucher_code } : {}),
298
+ ...(a.value_type ? { value_type: a.value_type } : {}),
299
+ ...(a.percent != null ? { percent: a.percent } : {}),
300
+ ...(a.line_position != null
301
+ ? { placement: "line" as const, line_position: a.line_position }
302
+ : { placement: "head" as const }),
303
+ amount: a.amount,
304
+ }));
305
+
306
+ // The cart this order came out of. The promotions app keys its
307
+ // redemption ledger on it, so without it a reservation has
308
+ // nothing to hang on — the BFF has been posting items directly
309
+ // and never naming the cart, even in live mode where the cart is
310
+ // a real record in the carts app.
311
+ try {
312
+ cartId = (await getCartManager(event)?.listCarts(event))?.activeCartId ?? null;
313
+ }
314
+ catch (cartErr) {
315
+ getLogService().error("Active cart lookup failed", apiErrorContext(cartErr));
316
+ }
317
+
318
+ // Held on SUBMIT, not on entering the checkout: a buyer who opens
319
+ // one and wanders off must not hold the last use of a code
320
+ // against everyone else.
321
+ reserved = cartId
322
+ ? await reserveRedemption(event, {
323
+ cartId,
324
+ promotions: promo?.applied ?? [],
325
+ currency: selectedCurrency ?? calculation.currency,
326
+ ...(contactId ? { contactId } : {}),
327
+ ...(organizationId ? { organizationId } : {}),
328
+ })
329
+ : "not_applicable";
330
+
331
+ // A refusal is the promotions app saying these uses are not
332
+ // there to be had. The order is still placed — the goods are
333
+ // wanted — but it is placed at the undiscounted price, because
334
+ // charging a discount nobody may spend is the one outcome that
335
+ // cannot be reconciled afterwards.
336
+ if (reserved === "refused") {
337
+ discounts = [];
338
+ }
339
+
262
340
  const placed = await useRevenexxSdk().orders.ordersPlace({
263
341
  ...(contactId ? { contactId } : {}),
264
342
  ...(organizationId ? { organizationId } : {}),
343
+ ...(cartId ? { cartId } : {}),
344
+ ...(discounts.length ? { discounts } : {}),
265
345
  currency: selectedCurrency ?? calculation.currency,
266
346
  ...(body.orderNumber ? { customerOrderNumber: body.orderNumber } : {}),
267
347
  buyer: user ? { name: user.name, email: user.email } : { email: body.contactEmail ?? null },
@@ -299,8 +379,29 @@ export default defineEventHandler(async (event) => {
299
379
  orderId = placed.number;
300
380
  liveOrderUuid = placed.id;
301
381
  liveOrderTotal = typeof placed.grand_total === "number" ? placed.grand_total : null;
382
+
383
+ // The order exists, so the hold becomes a spend. Best-effort: a
384
+ // commit that fails leaves a hold that expires on its own, which
385
+ // is a reconciliation job and not a reason to fail a sale the
386
+ // buyer has already been charged for.
387
+ if (reserved === "held") {
388
+ await commitRedemption(event, {
389
+ orderId: placed.id,
390
+ promotions: promo?.applied ?? [],
391
+ cartId,
392
+ currency: selectedCurrency ?? calculation.currency,
393
+ ...(contactId ? { contactId } : {}),
394
+ ...(organizationId ? { organizationId } : {}),
395
+ });
396
+ }
302
397
  }
303
398
  catch (err) {
399
+ // The order did not happen, so the uses go back rather than
400
+ // waiting out the expiry — the next buyer should find the code
401
+ // usable, not blocked by an attempt that failed.
402
+ if (reserved === "held" && cartId) {
403
+ await releaseRedemption(event, { cartId, reason: "order placement failed" });
404
+ }
304
405
  if (err instanceof RevenexxException && (err.code === 400 || err.code === 422)) {
305
406
  throw createError({ status: 422, message: err.message });
306
407
  }
@@ -0,0 +1,66 @@
1
+ import { createError, defineEventHandler } from "h3";
2
+
3
+ import type { PunchoutReturnPayload } from "../../../app/interfaces/punchout";
4
+
5
+ /**
6
+ * Hand the cart back — the end of a punchout visit.
7
+ *
8
+ * This app answers the payload; it never posts it. The cart has to arrive
9
+ * inside the BUYER's own ERP session, and a request from a server carries none
10
+ * of it — the procurement systems that expect a browser form post would reject
11
+ * it even if it did. So the answer here is what the interstitial turns into a
12
+ * form and submits from the buyer's browser, and this route makes exactly one
13
+ * call: `POST /punchout/sessions/{psid}/return`.
14
+ *
15
+ * Two things happen on this side beyond forwarding it:
16
+ *
17
+ * - **the visit is marked handed back**, but the cookie is kept, so a browser
18
+ * that comes back to a page it already submitted asks again and gets the
19
+ * same payload with `replayed: true` rather than an error page;
20
+ * - **the buyer is signed out**. A punchout visit ends when the cart goes;
21
+ * leaving a live shop session behind on a machine the ERP handed over is
22
+ * the thing this must not do. The punchout app closes the visit as
23
+ * transferred at the same moment, so nothing here has to close it too.
24
+ */
25
+ export default defineEventHandler(async (event): Promise<PunchoutReturnPayload> => {
26
+ const visit = getPunchoutVisit(event);
27
+ if (!visit) {
28
+ // Not inside a visit: there is no cart to hand anywhere, and the action
29
+ // that called this should not have been on the page at all.
30
+ throw createError({ statusCode: 409, data: { type: "punchout_no_session" } });
31
+ }
32
+
33
+ let payload: PunchoutReturnPayload;
34
+ try {
35
+ payload = await useRevenexxSdk().call<PunchoutReturnPayload>(
36
+ "POST",
37
+ `/v1/punchout/sessions/${encodeURIComponent(visit.psid)}/return`,
38
+ { body: {} },
39
+ );
40
+ }
41
+ catch (err) {
42
+ // 409 is the app's one answer for a visit that expired, was revoked or
43
+ // never existed — the same answer for all three, deliberately. The
44
+ // visit is dropped here so the shop stops offering an action that
45
+ // cannot work.
46
+ if (err instanceof RevenexxException && err.code === 409) {
47
+ clearPunchoutVisit(event);
48
+ throw createError({ statusCode: 409, data: { type: "punchout_session_closed" } });
49
+ }
50
+ getLogService().error("Punchout hand-back failed", apiErrorContext(err));
51
+ throw createError({ statusCode: 503, data: { type: "service_unavailable" } });
52
+ }
53
+
54
+ updatePunchoutVisit(event, { handedBack: true });
55
+
56
+ // Sign out only once the payload is in hand: a logout that ran first would
57
+ // be a visit closed with the cart still here.
58
+ try {
59
+ await getAuthService(event).logout(event);
60
+ }
61
+ catch (err) {
62
+ getLogService().error("Punchout sign-out after hand-back failed", toErrorContext(err));
63
+ }
64
+
65
+ return payload;
66
+ });
@@ -0,0 +1,15 @@
1
+ import { defineEventHandler } from "h3";
2
+
3
+ /**
4
+ * What the shop knows about the visit the browser is in.
5
+ *
6
+ * The transfer action is visible ONLY inside a punchout session and its
7
+ * wording follows the session's protocol, so the storefront has to be able to
8
+ * ask. It gets the context and never the handle: the handle stays in the
9
+ * HTTP-only cookie, and every call that needs it goes through the BFF.
10
+ *
11
+ * Answers the empty view rather than a 404 outside a visit — "am I in a
12
+ * punchout session" is a question every shop page asks, and its ordinary
13
+ * answer is no.
14
+ */
15
+ export default defineEventHandler(event => punchoutVisitView(getPunchoutVisit(event)));