@revenexx/cover 0.2.36 → 0.2.38
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.
- package/app/components/cart/view/CartSummaryPanel.vue +79 -17
- package/app/components/cart/view/CartView.vue +24 -2
- package/app/components/punchout/action/PunchoutTransferAction.vue +69 -0
- package/app/composables/useCartCalculation.ts +1 -0
- package/app/composables/useCartStore.ts +62 -1
- package/app/composables/usePunchoutVisit.ts +55 -0
- package/app/interfaces/cart-calculation.ts +6 -0
- package/app/interfaces/punchout.ts +79 -0
- package/app/layouts/default.vue +7 -0
- package/app/pages/punchout/transfer.vue +158 -0
- package/i18n/locales/de/cart.json +5 -2
- package/i18n/locales/de/punchout.json +45 -0
- package/i18n/locales/en/cart.json +5 -2
- package/i18n/locales/en/punchout.json +45 -0
- package/nuxt.config.ts +28 -0
- package/package.json +2 -1
- package/server/api/cart/calculate.post.ts +47 -3
- package/server/api/orders/index.post.ts +101 -0
- package/server/api/punchout/return.post.ts +66 -0
- package/server/api/punchout/session.get.ts +15 -0
- package/server/interfaces/cartCalculation.ts +16 -0
- package/server/interfaces/punchout.ts +57 -0
- package/server/routes/punchout/start.get.ts +261 -0
- package/server/services/MockCartCalculationService.ts +19 -5
- package/server/utils/promotionsService.ts +275 -0
- package/server/utils/punchoutLanding.ts +159 -0
- package/server/utils/punchoutVisit.ts +134 -0
- package/server/utils/revenexxSdk.ts +34 -1
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { PunchoutIntent, PunchoutProtocol } from "../../app/interfaces/punchout";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* What `POST /punchout/sessions/{psid}/claim` answers.
|
|
5
|
+
*
|
|
6
|
+
* The secret is an ordinary magic-link secret, minted by the customers app's
|
|
7
|
+
* trusted hand-off and answered here instead of mailed. It is single-use and
|
|
8
|
+
* short-lived: it is redeemed server-side, in the same request, and it must
|
|
9
|
+
* never reach a redirect URL, a browser history or a `Referer`.
|
|
10
|
+
*/
|
|
11
|
+
export interface PunchoutClaim {
|
|
12
|
+
readonly psid: string;
|
|
13
|
+
readonly protocol: PunchoutProtocol;
|
|
14
|
+
readonly channel_code: string;
|
|
15
|
+
readonly account_code: string | null;
|
|
16
|
+
readonly entry_action: string | null;
|
|
17
|
+
readonly entry_intent: PunchoutIntent | null;
|
|
18
|
+
readonly cart_id: string | null;
|
|
19
|
+
readonly expires_at: string;
|
|
20
|
+
readonly contact_id: string | null;
|
|
21
|
+
readonly organization_id: string | null;
|
|
22
|
+
readonly claimed_at: string | null;
|
|
23
|
+
/** The platform user the secret signs in — passed back with the secret. */
|
|
24
|
+
readonly user_id: string | null;
|
|
25
|
+
readonly secret: string;
|
|
26
|
+
readonly expire: string | null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The visit as the storefront keeps it, in an HTTP-only cookie.
|
|
31
|
+
*
|
|
32
|
+
* The handle is in here and nowhere else on this side: it travelled through
|
|
33
|
+
* the external system in the clear, so it is worth nothing to an attacker who
|
|
34
|
+
* already read it — but it is also the only thing that names the visit to the
|
|
35
|
+
* punchout app, and a value the browser could rewrite would let a buyer hand
|
|
36
|
+
* back somebody else's cart.
|
|
37
|
+
*/
|
|
38
|
+
export interface PunchoutVisit {
|
|
39
|
+
readonly psid: string;
|
|
40
|
+
readonly protocol: PunchoutProtocol;
|
|
41
|
+
readonly channelCode: string;
|
|
42
|
+
readonly accountCode: string | null;
|
|
43
|
+
readonly entryAction: string | null;
|
|
44
|
+
readonly cartId: string | null;
|
|
45
|
+
readonly expiresAt: string;
|
|
46
|
+
/** cXML `inspect`: the buyer may look at this cart and not change it. */
|
|
47
|
+
readonly readOnly: boolean;
|
|
48
|
+
/** Set once the cart has been handed back; a repeat ask replays the payload. */
|
|
49
|
+
readonly handedBack: boolean;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Where a claimed visit lands the buyer, before it is turned into a path. */
|
|
53
|
+
export type PunchoutLandingTarget =
|
|
54
|
+
| { readonly kind: "shop" }
|
|
55
|
+
| { readonly kind: "article"; readonly supplierPartId: string }
|
|
56
|
+
| { readonly kind: "search"; readonly term: string }
|
|
57
|
+
| { readonly kind: "cart" };
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import type { H3Event } from "h3";
|
|
2
|
+
import { defineEventHandler, getQuery, sendRedirect, setResponseHeader, setResponseStatus } from "h3";
|
|
3
|
+
|
|
4
|
+
import type { StoredSession } from "../../../app/interfaces/auth";
|
|
5
|
+
import type { PunchoutClaim, PunchoutVisit } from "../../interfaces/punchout";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* `/punchout/start?pSid=…` — where the entry redirect lands the buyer.
|
|
9
|
+
*
|
|
10
|
+
* The redirect an ERP followed carries the session handle and NOTHING else: an
|
|
11
|
+
* ERP redirect is written into ERP logs, browser history and the referrer of
|
|
12
|
+
* the next request, so a sign-in secret there is a credential published three
|
|
13
|
+
* times over (buyer-identity AC-6). This route therefore does the whole
|
|
14
|
+
* sign-in on the back channel, server-side, in one request:
|
|
15
|
+
*
|
|
16
|
+
* 1. claim the handle POST /punchout/sessions/{psid}/claim
|
|
17
|
+
* 2. redeem the secret PUT /customers/auth/magic-link
|
|
18
|
+
* 3. remember the visit the HTTP-only punchout cookie
|
|
19
|
+
* 4. land the buyer where the entry call pointed
|
|
20
|
+
*
|
|
21
|
+
* The secret never reaches the browser, a redirect URL or a log line. The
|
|
22
|
+
* claim is answered once — a handle that was already claimed, expired, revoked
|
|
23
|
+
* or never minted gets the same refusal, deliberately, because the handle
|
|
24
|
+
* travelled through an external system in the clear.
|
|
25
|
+
*
|
|
26
|
+
* A refusal is a plain page saying so, never a half-open shop and never a
|
|
27
|
+
* redirect to a login form: the buyer cannot sign in here, they have to go
|
|
28
|
+
* back to their procurement system and start again (session-lifecycle AC-11).
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
/** What `PUT /customers/auth/magic-link` answers — the same as a password login. */
|
|
32
|
+
interface MagicLinkSession {
|
|
33
|
+
readonly session: { readonly $id: string; readonly userId: string; readonly expire: string };
|
|
34
|
+
readonly contact: { readonly id?: string; readonly organization_id?: string | null } | null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** One row of the shop's own search, as much as resolving an article needs. */
|
|
38
|
+
interface SearchAnswer {
|
|
39
|
+
readonly products?: readonly {
|
|
40
|
+
readonly id?: string;
|
|
41
|
+
readonly name?: string;
|
|
42
|
+
readonly sku?: string;
|
|
43
|
+
readonly categorySlug?: string | null;
|
|
44
|
+
readonly subcategorySlug?: string | null;
|
|
45
|
+
}[];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export default defineEventHandler(async (event) => {
|
|
49
|
+
const query = getQuery(event);
|
|
50
|
+
// The parameter is the account's own start page URL plus whatever casing
|
|
51
|
+
// the punchout app appends. Read both rather than make an operator's
|
|
52
|
+
// configuration depend on one.
|
|
53
|
+
const psid = String(query.pSid ?? query.psid ?? "").trim();
|
|
54
|
+
if (!psid) {
|
|
55
|
+
return refuse(event, "missing");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
let claim: PunchoutClaim;
|
|
59
|
+
try {
|
|
60
|
+
claim = await useRevenexxSdk().call<PunchoutClaim>(
|
|
61
|
+
"POST",
|
|
62
|
+
`/v1/punchout/sessions/${encodeURIComponent(psid)}/claim`,
|
|
63
|
+
{ body: {} },
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
catch (err) {
|
|
67
|
+
// 409 is the app's one answer for every unusable handle. Everything
|
|
68
|
+
// else is this shop or the platform failing, and says so — but neither
|
|
69
|
+
// opens a shop.
|
|
70
|
+
const status = err instanceof RevenexxException ? err.code : 0;
|
|
71
|
+
if (status !== 409) {
|
|
72
|
+
getLogService().error("Punchout claim failed", apiErrorContext(err));
|
|
73
|
+
}
|
|
74
|
+
return refuse(event, status === 409 ? "unusable" : "unavailable");
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (!claim.secret || !claim.user_id) {
|
|
78
|
+
getLogService().error("Punchout claim answered no sign-in secret", { psid: "(withheld)" });
|
|
79
|
+
return refuse(event, "unavailable");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Redeem the hand-off exactly as a mailed magic link is redeemed. Nothing
|
|
83
|
+
// about this call is punchout-specific, which is the point: a shop must not
|
|
84
|
+
// have to branch on how somebody signed in.
|
|
85
|
+
let signedIn: MagicLinkSession;
|
|
86
|
+
try {
|
|
87
|
+
signedIn = await useRevenexxSdk().call<MagicLinkSession>("PUT", "/v1/customers/auth/magic-link", {
|
|
88
|
+
body: { user_id: claim.user_id, secret: claim.secret },
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
catch (err) {
|
|
92
|
+
// The two configuration faults RAD-46 owns look exactly like this from
|
|
93
|
+
// here: REVENEXX_HANDOFF_KEY unset makes the hand-off 503, and a tenant
|
|
94
|
+
// with `login_magic_link` off makes the redeem 403 `method_not_offered`.
|
|
95
|
+
// Both are "the claim answered, the buyer is not signed in" — so they
|
|
96
|
+
// are logged as themselves and the buyer is told the shop could not
|
|
97
|
+
// sign them in, rather than dropped into it as a guest.
|
|
98
|
+
getLogService().error("Punchout sign-in failed", apiErrorContext(err));
|
|
99
|
+
return refuse(event, "unavailable");
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const session = signedIn.session;
|
|
103
|
+
if (!session?.$id || !session.userId) {
|
|
104
|
+
getLogService().error("Punchout sign-in answered no session", {});
|
|
105
|
+
return refuse(event, "unavailable");
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const stored: StoredSession = {
|
|
109
|
+
id: session.$id,
|
|
110
|
+
expire: session.expire,
|
|
111
|
+
userId: session.userId,
|
|
112
|
+
...(signedIn.contact?.id ? { contactId: signedIn.contact.id } : {}),
|
|
113
|
+
...(signedIn.contact?.organization_id ? { organizationId: signedIn.contact.organization_id } : {}),
|
|
114
|
+
};
|
|
115
|
+
setCookie(event, SESSION_COOKIE_NAME, JSON.stringify(stored), sessionCookieOptions(session.expire));
|
|
116
|
+
|
|
117
|
+
const visit: PunchoutVisit = {
|
|
118
|
+
psid: claim.psid,
|
|
119
|
+
protocol: claim.protocol,
|
|
120
|
+
channelCode: claim.channel_code,
|
|
121
|
+
accountCode: claim.account_code ?? null,
|
|
122
|
+
entryAction: claim.entry_action ?? null,
|
|
123
|
+
cartId: claim.cart_id ?? null,
|
|
124
|
+
expiresAt: claim.expires_at,
|
|
125
|
+
readOnly: claim.entry_intent?.read_only === true,
|
|
126
|
+
handedBack: false,
|
|
127
|
+
};
|
|
128
|
+
setPunchoutVisit(event, visit);
|
|
129
|
+
|
|
130
|
+
// A visit the external system opened WITH a cart names it, and a `WKS`
|
|
131
|
+
// import always creates a new one — so the buyer is put on that cart
|
|
132
|
+
// rather than on whatever the shop would otherwise call "the" cart.
|
|
133
|
+
if (visit.cartId) {
|
|
134
|
+
try {
|
|
135
|
+
await getCartManager(event)?.activateCart(event, visit.cartId);
|
|
136
|
+
}
|
|
137
|
+
catch (err) {
|
|
138
|
+
// The cart exists and the visit names it; failing to make it the
|
|
139
|
+
// active one is worth a line in the log, not a refused visit.
|
|
140
|
+
getLogService().error("Punchout cart activation failed", toErrorContext(err));
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// The locale prefix is applied last, because the decision above is about
|
|
145
|
+
// WHERE the buyer goes and this is about how this storefront spells it.
|
|
146
|
+
const punchoutConfig = (useRuntimeConfig(event).punchout ?? {}) as { localeStrategy?: string; defaultLocale?: string };
|
|
147
|
+
const path = punchoutLocalePath(
|
|
148
|
+
await landingPath(claim),
|
|
149
|
+
resolveLocale(event),
|
|
150
|
+
String(punchoutConfig.localeStrategy ?? "no_prefix"),
|
|
151
|
+
String(punchoutConfig.defaultLocale ?? ""),
|
|
152
|
+
);
|
|
153
|
+
|
|
154
|
+
return await sendRedirect(event, path, 302);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Where this visit lands, as a path on this shop.
|
|
159
|
+
*
|
|
160
|
+
* The decision is `punchoutLandingTarget()` and is protocol-free; only an
|
|
161
|
+
* article needs the catalogue, because an external system names an article
|
|
162
|
+
* NUMBER and the shop's product pages are addressed by id and slug.
|
|
163
|
+
*/
|
|
164
|
+
async function landingPath(claim: PunchoutClaim): Promise<string> {
|
|
165
|
+
const target = punchoutLandingTarget(claim.entry_action, claim.entry_intent, claim.cart_id);
|
|
166
|
+
const direct = punchoutLandingPath(target);
|
|
167
|
+
if (direct) {
|
|
168
|
+
return direct;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// `article` — resolve the number through the shop's own search.
|
|
172
|
+
const supplierPartId = target.kind === "article" ? target.supplierPartId : "";
|
|
173
|
+
try {
|
|
174
|
+
const found = await $fetch<SearchAnswer>("/api/typesense/search", {
|
|
175
|
+
method: "POST",
|
|
176
|
+
body: { q: supplierPartId, page: 1, perPage: 5 },
|
|
177
|
+
});
|
|
178
|
+
return punchoutArticlePath(found?.products ?? [], supplierPartId);
|
|
179
|
+
}
|
|
180
|
+
catch (err) {
|
|
181
|
+
// No search backend, or one that failed: the buyer still gets what the
|
|
182
|
+
// call asked for as a query rather than a page that lost it.
|
|
183
|
+
getLogService().error("Punchout article lookup failed", toErrorContext(err));
|
|
184
|
+
return punchoutArticlePath([], supplierPartId);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Why a visit could not be opened — one page per cause, in plain words. */
|
|
189
|
+
type RefusalCause = "missing" | "unusable" | "unavailable";
|
|
190
|
+
|
|
191
|
+
const REFUSALS: Record<RefusalCause, { readonly status: number; readonly title: string; readonly body: string }> = {
|
|
192
|
+
missing: {
|
|
193
|
+
status: 400,
|
|
194
|
+
title: "No punchout session",
|
|
195
|
+
body: "This address was opened without a punchout session. Start the catalogue again from your procurement system.",
|
|
196
|
+
},
|
|
197
|
+
unusable: {
|
|
198
|
+
status: 410,
|
|
199
|
+
title: "This punchout session cannot be opened",
|
|
200
|
+
body: "It has already been used, it has run out, or it was ended. Start the catalogue again from your procurement system — a new session will be opened for you.",
|
|
201
|
+
},
|
|
202
|
+
unavailable: {
|
|
203
|
+
status: 503,
|
|
204
|
+
title: "This shop could not sign you in",
|
|
205
|
+
body: "The punchout session was accepted, but signing you in failed. Please try again in a moment, or tell your supplier's support that punchout sign-in is failing.",
|
|
206
|
+
},
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* A refusal page, written out here.
|
|
211
|
+
*
|
|
212
|
+
* Plain HTML from the server rather than a rendered shop page, for the same
|
|
213
|
+
* reason the pass-through beside it is plain: the buyer has no session, no
|
|
214
|
+
* shop has been opened for them, and a themed page would need one. A redirect
|
|
215
|
+
* to a login form would be worse still — there is no password they could use.
|
|
216
|
+
*/
|
|
217
|
+
function refuse(event: H3Event, cause: RefusalCause): string {
|
|
218
|
+
const refusal = REFUSALS[cause];
|
|
219
|
+
|
|
220
|
+
// Nothing half-open: a stale visit cookie from an earlier entry is dropped
|
|
221
|
+
// here, so the shop never goes on offering a transfer for a visit the app
|
|
222
|
+
// has already refused. The auth session is deliberately left alone — this
|
|
223
|
+
// route never signs anybody in before the last step that can fail, and a
|
|
224
|
+
// mistyped address must not log out whoever is browsing.
|
|
225
|
+
clearPunchoutVisit(event);
|
|
226
|
+
|
|
227
|
+
setResponseStatus(event, refusal.status);
|
|
228
|
+
setResponseHeader(event, "content-type", "text/html; charset=utf-8");
|
|
229
|
+
setResponseHeader(event, "cache-control", "no-store");
|
|
230
|
+
setResponseHeader(event, "x-robots-tag", "noindex");
|
|
231
|
+
return `<!doctype html>
|
|
232
|
+
<html lang="en">
|
|
233
|
+
<head>
|
|
234
|
+
<meta charset="utf-8">
|
|
235
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
236
|
+
<meta name="robots" content="noindex">
|
|
237
|
+
<title>${escapeHtml(refusal.title)}</title>
|
|
238
|
+
<style>
|
|
239
|
+
body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 2rem;
|
|
240
|
+
font: 16px/1.6 system-ui, -apple-system, "Segoe UI", sans-serif; color: #1f2430; background: #f6f7f9; }
|
|
241
|
+
main { max-width: 34rem; text-align: center; }
|
|
242
|
+
h1 { font-size: 1.375rem; margin: 0 0 0.75rem; }
|
|
243
|
+
p { margin: 0; color: #55606f; }
|
|
244
|
+
</style>
|
|
245
|
+
</head>
|
|
246
|
+
<body>
|
|
247
|
+
<main>
|
|
248
|
+
<h1>${escapeHtml(refusal.title)}</h1>
|
|
249
|
+
<p>${escapeHtml(refusal.body)}</p>
|
|
250
|
+
</main>
|
|
251
|
+
</body>
|
|
252
|
+
</html>`;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function escapeHtml(value: string): string {
|
|
256
|
+
return value
|
|
257
|
+
.replace(/&/g, "&")
|
|
258
|
+
.replace(/</g, "<")
|
|
259
|
+
.replace(/>/g, ">")
|
|
260
|
+
.replace(/"/g, """);
|
|
261
|
+
}
|
|
@@ -191,13 +191,18 @@ export class MockCartCalculationService implements ICartCalculationService {
|
|
|
191
191
|
});
|
|
192
192
|
}
|
|
193
193
|
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
194
|
+
// Live mode: what the promotions app decided, ATTRIBUTED PER LINE. Mock
|
|
195
|
+
// mode keeps the demo profile's flat volume discount, so the showcase
|
|
196
|
+
// works without a tenant behind it.
|
|
197
|
+
const discount = overrides?.promotion
|
|
198
|
+
? r2(overrides.promotion.discountTotal)
|
|
199
|
+
: (subtotal >= DISCOUNT_THRESHOLD ? r2(subtotal * DISCOUNT_RATE) : 0);
|
|
197
200
|
if (discount > 0) {
|
|
198
201
|
totals.push({
|
|
199
202
|
key: "discount",
|
|
200
|
-
label:
|
|
203
|
+
label: overrides?.promotion
|
|
204
|
+
? (overrides.promotion.label ?? t("calc.totals.discountGeneric"))
|
|
205
|
+
: t("calc.totals.discount", { percent: DISCOUNT_RATE * 100 }),
|
|
201
206
|
amount: -discount,
|
|
202
207
|
});
|
|
203
208
|
}
|
|
@@ -214,6 +219,12 @@ export class MockCartCalculationService implements ICartCalculationService {
|
|
|
214
219
|
|
|
215
220
|
// Taxable base per rate: line totals + line surcharges, discount applied
|
|
216
221
|
// proportionally; document-level charges taxed at the default rate.
|
|
222
|
+
// A flat factor is right for the demo discount, which is a share of the
|
|
223
|
+
// whole cart. It is WRONG for a real promotion: the engine attributes an
|
|
224
|
+
// amount to each line, and the order applies those same amounts — so a
|
|
225
|
+
// factor applied here would spread the money differently and the summary
|
|
226
|
+
// would disagree with the order by a cent on almost every mixed cart.
|
|
227
|
+
// When the engine has spoken, its per-line figures are used verbatim.
|
|
217
228
|
const discountFactor = subtotal > 0 ? 1 - discount / subtotal : 1;
|
|
218
229
|
const basePerRate = new Map<number, number>();
|
|
219
230
|
for (let i = 0; i < lines.length; i++) {
|
|
@@ -227,7 +238,10 @@ export class MockCartCalculationService implements ICartCalculationService {
|
|
|
227
238
|
const liveRate = overrides?.itemTaxRates?.[item.id] ?? overrides?.itemTaxRates?.[item.sku ?? ""];
|
|
228
239
|
const rate = normalizeRate(liveRate ?? item.taxRate);
|
|
229
240
|
const lineSurcharge = line.surcharges.reduce((s, c) => s + c.amountPerUnit * effectiveQty(line), 0);
|
|
230
|
-
const
|
|
241
|
+
const discounted = overrides?.promotion
|
|
242
|
+
? line.lineTotal - (overrides.promotion.lineDiscounts[i + 1] ?? 0)
|
|
243
|
+
: line.lineTotal * discountFactor;
|
|
244
|
+
const base = discounted + lineSurcharge;
|
|
231
245
|
basePerRate.set(rate, (basePerRate.get(rate) ?? 0) + base);
|
|
232
246
|
}
|
|
233
247
|
// The min-order charge is a BFF construct taxed at the default rate;
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import type { H3Event } from "h3";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The promotions domain has no service class — the cart endpoint branches on
|
|
5
|
+
* the resolved registry key ("mock" = the demo profile's own flat discount,
|
|
6
|
+
* "api" = the promotions app via the public revenexx API).
|
|
7
|
+
*
|
|
8
|
+
* Mock mode is untouched by any of this: the demo cart keeps its hard-coded
|
|
9
|
+
* volume discount, so the showcase keeps working without a tenant behind it.
|
|
10
|
+
*/
|
|
11
|
+
export function resolvePromotionsServiceKey(event?: H3Event): string {
|
|
12
|
+
return resolveServiceKey(event, {
|
|
13
|
+
domain: "promotionsService",
|
|
14
|
+
mockKey: "mock",
|
|
15
|
+
liveKey: "api",
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** One line as the promotions app wants to see it: priced, and numbered. */
|
|
20
|
+
interface PricedLine {
|
|
21
|
+
position: number;
|
|
22
|
+
sku?: string;
|
|
23
|
+
product_id?: string;
|
|
24
|
+
name?: string;
|
|
25
|
+
quantity: number;
|
|
26
|
+
unit_price: number;
|
|
27
|
+
tax_rate?: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** What `POST /promotions/evaluate` answers, in the part the storefront uses. */
|
|
31
|
+
export interface PromotionEvaluation {
|
|
32
|
+
/** The discount per line, keyed by the 1-based position the line was sent under. */
|
|
33
|
+
lineDiscounts: Record<number, number>;
|
|
34
|
+
/** Every discount together — what the summary shows on its own row. */
|
|
35
|
+
discountTotal: number;
|
|
36
|
+
/** The promotions that applied, for the row label and the order that follows. */
|
|
37
|
+
applied: Array<{
|
|
38
|
+
promotion_id: string;
|
|
39
|
+
promotion_name: string;
|
|
40
|
+
/** The voucher behind it, when a code produced it. The redemption ledger
|
|
41
|
+
* counts a voucher's uses by this, so a hold without it never moves
|
|
42
|
+
* `usage_count` and the code stays usable for ever. */
|
|
43
|
+
voucher_id?: string | null;
|
|
44
|
+
voucher_code?: string | null;
|
|
45
|
+
value_type?: string | null;
|
|
46
|
+
percent?: number | null;
|
|
47
|
+
line_position?: number | null;
|
|
48
|
+
amount: number;
|
|
49
|
+
}>;
|
|
50
|
+
/** Codes the engine refused, so the cart can say WHICH code did not work. */
|
|
51
|
+
rejectedCodes: string[];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Ask the promotions app what this cart is worth.
|
|
56
|
+
*
|
|
57
|
+
* The call writes nothing, which is what makes it safe on every keystroke, and
|
|
58
|
+
* it prices nothing — a line with no resolved unit price is refused rather than
|
|
59
|
+
* guessed at, so this runs AFTER the prices app has answered.
|
|
60
|
+
*
|
|
61
|
+
* Attribution is the point. The engine answers a discount PER LINE, and those
|
|
62
|
+
* are the figures carried through to the order — the BFF never re-derives a
|
|
63
|
+
* split of its own, because a split computed twice is a split that disagrees by
|
|
64
|
+
* a cent, and a cent that appears in the summary and not in the order is the
|
|
65
|
+
* defect this whole wiring exists to avoid.
|
|
66
|
+
*
|
|
67
|
+
* Failure is silent by design: an unreachable promotions app leaves the cart
|
|
68
|
+
* priced and orderable, without a discount. A storefront that refuses to show a
|
|
69
|
+
* cart because a promotion could not be evaluated is worse than one that shows
|
|
70
|
+
* the undiscounted price.
|
|
71
|
+
*/
|
|
72
|
+
export async function evaluatePromotions(
|
|
73
|
+
event: H3Event,
|
|
74
|
+
input: { lines: PricedLine[]; currency?: string; codes?: string[]; contactId?: string | null; organizationId?: string | null },
|
|
75
|
+
): Promise<PromotionEvaluation | null> {
|
|
76
|
+
if (resolvePromotionsServiceKey(event) !== "api" || !input.lines.length) {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
// The escape hatch, not a typed method: the SDK vendored here predates
|
|
81
|
+
// the promotions app and carries no namespace for it. Same transport,
|
|
82
|
+
// same auth, same error type — it moves to a typed call when the SDK
|
|
83
|
+
// next carries one.
|
|
84
|
+
const answer = await useRevenexxSdk().call<{
|
|
85
|
+
lines?: Array<{ position?: number; discount?: number }>;
|
|
86
|
+
totals?: { discount_total?: number };
|
|
87
|
+
applied?: Array<Record<string, unknown>>;
|
|
88
|
+
rejected_codes?: string[];
|
|
89
|
+
}>("POST", "/v1/promotions/evaluate", {
|
|
90
|
+
body: {
|
|
91
|
+
currency: input.currency,
|
|
92
|
+
lines: input.lines,
|
|
93
|
+
...(input.codes?.length ? { codes: input.codes } : {}),
|
|
94
|
+
...(input.contactId ? { contact_id: input.contactId } : {}),
|
|
95
|
+
...(input.organizationId ? { organization_id: input.organizationId } : {}),
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
const lineDiscounts: Record<number, number> = {};
|
|
100
|
+
for (const line of answer.lines ?? []) {
|
|
101
|
+
const discount = Number(line.discount ?? 0);
|
|
102
|
+
if (line.position !== undefined && discount > 0) {
|
|
103
|
+
lineDiscounts[Number(line.position)] = discount;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
lineDiscounts,
|
|
108
|
+
discountTotal: Number(answer.totals?.discount_total ?? 0),
|
|
109
|
+
applied: (answer.applied ?? []).map(a => ({
|
|
110
|
+
promotion_id: String(a.promotion_id ?? a.id ?? ""),
|
|
111
|
+
promotion_name: String(a.name ?? a.promotion_name ?? "Promotion"),
|
|
112
|
+
voucher_id: (a.voucher_id ?? null) as string | null,
|
|
113
|
+
voucher_code: (a.voucher_code ?? a.code ?? null) as string | null,
|
|
114
|
+
value_type: (a.value_type ?? null) as string | null,
|
|
115
|
+
percent: a.percent != null ? Number(a.percent) : null,
|
|
116
|
+
line_position: a.line_position != null ? Number(a.line_position) : null,
|
|
117
|
+
amount: Number(a.amount ?? 0),
|
|
118
|
+
})),
|
|
119
|
+
rejectedCodes: answer.rejected_codes ?? [],
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
catch (err) {
|
|
123
|
+
getLogService().error("Promotion evaluation failed", apiErrorContext(err));
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Hold what this cart is about to spend, then keep it or hand it back.
|
|
130
|
+
*
|
|
131
|
+
* Evaluating is free and writes nothing; RESERVING is the moment a voucher's
|
|
132
|
+
* remaining uses are taken out of circulation, so it happens on SUBMIT and not
|
|
133
|
+
* a moment earlier. A buyer who opens a checkout and wanders off must not hold
|
|
134
|
+
* the last use of a code against everyone else.
|
|
135
|
+
*
|
|
136
|
+
* Three outcomes and all three are written:
|
|
137
|
+
*
|
|
138
|
+
* reserve → commit the order exists, the redemption is spent
|
|
139
|
+
* reserve → release the order did not happen, the uses go back
|
|
140
|
+
* reserve → expire nothing was said; the hold lapses on its own, which is
|
|
141
|
+
* why the reservation carries an expiry and why a missed
|
|
142
|
+
* release is untidy rather than lost
|
|
143
|
+
*
|
|
144
|
+
* Every one of them is best-effort and none of them fails the order. A
|
|
145
|
+
* promotion that cannot be reserved leaves the order placed without it — which
|
|
146
|
+
* is a discount the buyer did not get, and a conversation. A promotion that
|
|
147
|
+
* cannot be COMMITTED leaves a hold that expires by itself. Neither is worth
|
|
148
|
+
* refusing a sale that the buyer has already paid for.
|
|
149
|
+
*/
|
|
150
|
+
/**
|
|
151
|
+
* Why a hold did not happen, because the three cases are not one.
|
|
152
|
+
*
|
|
153
|
+
* `refused` is the promotions app answering no — the code is spent, the budget
|
|
154
|
+
* is gone — and the discount goes with it. `unavailable` is nobody answering,
|
|
155
|
+
* which is not the buyer's fault and does not cost them their discount.
|
|
156
|
+
* `not_applicable` is there being nothing to hold in the first place.
|
|
157
|
+
*/
|
|
158
|
+
export type ReservationOutcome = "held" | "refused" | "unavailable" | "not_applicable";
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* What reserve and commit hold: the engine's own attribution, promotion by
|
|
162
|
+
* promotion. `/promotions/reserve` holds exactly what it is handed under
|
|
163
|
+
* `promotions` and RELEASES everything else on the cart, so calling it without
|
|
164
|
+
* that list holds nothing and quietly drops any hold that was already there.
|
|
165
|
+
*/
|
|
166
|
+
function heldPromotions(applied: PromotionEvaluation["applied"]) {
|
|
167
|
+
return applied
|
|
168
|
+
.filter(a => a.promotion_id)
|
|
169
|
+
.map(a => ({
|
|
170
|
+
promotion_id: a.promotion_id,
|
|
171
|
+
...(a.voucher_id ? { voucher_id: a.voucher_id } : {}),
|
|
172
|
+
amount: a.amount,
|
|
173
|
+
}));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export async function reserveRedemption(
|
|
177
|
+
event: H3Event,
|
|
178
|
+
input: {
|
|
179
|
+
cartId: string;
|
|
180
|
+
promotions: PromotionEvaluation["applied"];
|
|
181
|
+
currency?: string;
|
|
182
|
+
contactId?: string | null;
|
|
183
|
+
organizationId?: string | null;
|
|
184
|
+
},
|
|
185
|
+
): Promise<ReservationOutcome> {
|
|
186
|
+
if (resolvePromotionsServiceKey(event) !== "api") {
|
|
187
|
+
return "not_applicable";
|
|
188
|
+
}
|
|
189
|
+
const promotions = heldPromotions(input.promotions);
|
|
190
|
+
if (!promotions.length) {
|
|
191
|
+
return "not_applicable";
|
|
192
|
+
}
|
|
193
|
+
try {
|
|
194
|
+
await useRevenexxSdk().call("POST", "/v1/promotions/reserve", {
|
|
195
|
+
body: {
|
|
196
|
+
cart_id: input.cartId,
|
|
197
|
+
promotions,
|
|
198
|
+
...(input.currency ? { currency: input.currency } : {}),
|
|
199
|
+
...(input.contactId ? { contact_id: input.contactId } : {}),
|
|
200
|
+
...(input.organizationId ? { organization_id: input.organizationId } : {}),
|
|
201
|
+
},
|
|
202
|
+
});
|
|
203
|
+
return "held";
|
|
204
|
+
}
|
|
205
|
+
catch (err) {
|
|
206
|
+
// A refusal is an ANSWER: the promotions app looked and said no, so the
|
|
207
|
+
// discount it was refusing may not be charged for. Anything else means
|
|
208
|
+
// nobody answered — a sale is not failed over an unreachable service,
|
|
209
|
+
// and the hold is picked up by reconciliation.
|
|
210
|
+
// 409 and 422 only. `isApiUserError` is wider on purpose elsewhere, but
|
|
211
|
+
// here it would read a 401 or a 429 — our own auth or our own rate limit
|
|
212
|
+
// — as the buyer's code being spent, and take their discount away for an
|
|
213
|
+
// infrastructure fault they had no part in.
|
|
214
|
+
if (err instanceof RevenexxException && (err.code === 409 || err.code === 422)) {
|
|
215
|
+
getLogService().error("Promotion reservation refused", apiErrorContext(err));
|
|
216
|
+
return "refused";
|
|
217
|
+
}
|
|
218
|
+
getLogService().error("Promotion reservation failed", apiErrorContext(err));
|
|
219
|
+
return "unavailable";
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export async function commitRedemption(
|
|
224
|
+
event: H3Event,
|
|
225
|
+
input: {
|
|
226
|
+
orderId: string;
|
|
227
|
+
promotions: PromotionEvaluation["applied"];
|
|
228
|
+
cartId?: string | null;
|
|
229
|
+
currency?: string;
|
|
230
|
+
contactId?: string | null;
|
|
231
|
+
organizationId?: string | null;
|
|
232
|
+
},
|
|
233
|
+
): Promise<void> {
|
|
234
|
+
if (resolvePromotionsServiceKey(event) !== "api") {
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
try {
|
|
238
|
+
await useRevenexxSdk().call("POST", "/v1/promotions/commit", {
|
|
239
|
+
body: {
|
|
240
|
+
order_id: input.orderId,
|
|
241
|
+
// Commit promotes the cart's held rows; the list is what it falls
|
|
242
|
+
// back to when a hold has expired or was never taken, and it is
|
|
243
|
+
// what moves a promotion's budget and a voucher's usage_count.
|
|
244
|
+
promotions: heldPromotions(input.promotions),
|
|
245
|
+
...(input.cartId ? { cart_id: input.cartId } : {}),
|
|
246
|
+
...(input.currency ? { currency: input.currency } : {}),
|
|
247
|
+
...(input.contactId ? { contact_id: input.contactId } : {}),
|
|
248
|
+
...(input.organizationId ? { organization_id: input.organizationId } : {}),
|
|
249
|
+
},
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
catch (err) {
|
|
253
|
+
// The order exists and the buyer has been charged. A hold that was not
|
|
254
|
+
// committed expires on its own, so this is a reconciliation job, not a
|
|
255
|
+
// reason to fail a completed sale.
|
|
256
|
+
getLogService().error("Promotion commit failed — the hold will expire", apiErrorContext(err));
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export async function releaseRedemption(
|
|
261
|
+
event: H3Event,
|
|
262
|
+
input: { cartId: string; reason: string },
|
|
263
|
+
): Promise<void> {
|
|
264
|
+
if (resolvePromotionsServiceKey(event) !== "api") {
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
try {
|
|
268
|
+
await useRevenexxSdk().call("POST", "/v1/promotions/release", {
|
|
269
|
+
body: { cart_id: input.cartId, reason: input.reason },
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
catch (err) {
|
|
273
|
+
getLogService().error("Promotion release failed — the hold will expire", apiErrorContext(err));
|
|
274
|
+
}
|
|
275
|
+
}
|