@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.
@@ -30,6 +30,25 @@ function isMissingSortFieldError(err: unknown): boolean {
30
30
  return /Could not find a field named .* in the schema for sorting/i.test(msg);
31
31
  }
32
32
 
33
+ /**
34
+ * Typesense's answer when a `filter_by` names a field the collection does not
35
+ * declare: `Could not find a filter field named \`x\` in the schema.`
36
+ *
37
+ * The same shape as the facet and sort checks below it, and the same reason —
38
+ * the SDK surfaces no typed error — but a filter is the one of the three that
39
+ * is not a nicety. `enabled:=true` is pinned on every live query, so a
40
+ * collection that has the field stored but not indexed answered nothing at
41
+ * all: every listing and every search on the storefront read "0 results" with
42
+ * a failure banner, in every language, while the catalogue was intact.
43
+ */
44
+ function missingFilterField(err: unknown): string | null {
45
+ if (!err) return null;
46
+ const msg = err instanceof Error ? err.message : String(err);
47
+ return /Could not find a filter field named/i.test(msg)
48
+ ? (msg.match(/filter field named `([^`]+)`/i)?.[1] ?? "")
49
+ : null;
50
+ }
51
+
33
52
  /**
34
53
  * The live category codes behind the storefront's subcategory filter values.
35
54
  *
@@ -207,10 +226,17 @@ export default defineEventHandler(async (event) => {
207
226
  ? SORT_MAP[sort]
208
227
  : undefined;
209
228
 
229
+ // Filter clauses the collection turned out not to carry, dropped for
230
+ // the retry. Read after the search so the mapper can enforce by hand
231
+ // what the index could not enforce for us.
232
+ const droppedFilterFields = new Set<string>();
233
+
210
234
  const runSearch = async (facetBy: string, sortBy?: string) => searchLiveProducts({
211
235
  q,
212
236
  queryBy: "name,sku,description,manufacturer",
213
- filterBy: liveFilterParts.join(" && "),
237
+ filterBy: liveFilterParts
238
+ .filter(part => ![...droppedFilterFields].some(f => part.startsWith(`${f}:`)))
239
+ .join(" && "),
214
240
  facetBy,
215
241
  // Typesense answers with 10 values per facet when this is unset,
216
242
  // which silently truncates the rail AND undercounts the subcategory
@@ -222,22 +248,45 @@ export default defineEventHandler(async (event) => {
222
248
  perPage,
223
249
  });
224
250
 
225
- // Two independent degradations, each retried once: a dynamic facet the
226
- // tenant's schema no longer has, and a sort field it never had.
251
+ // Three independent degradations, each retried once: a dynamic facet
252
+ // the tenant's schema no longer has, a sort field it never had, and a
253
+ // filter field it does not declare.
254
+ //
255
+ // The filter one is the newcomer and the one that hurt: a pinned
256
+ // clause naming an undeclared field fails the whole query, so the
257
+ // storefront showed nothing at all rather than showing too much. It is
258
+ // retried without that clause — and what the clause promised is then
259
+ // enforced on the documents instead, below, so dropping it narrows
260
+ // what the page can say about totals but never widens what it shows.
227
261
  const searchWithFallbacks = async (sortBy?: string) => {
228
- try {
229
- return await runSearch(liveFacetBy, sortBy);
230
- }
231
- catch (err) {
232
- if (dynamicFacets.length > 0 && isMissingFacetFieldError(err)) {
233
- getLogService().warn(
234
- "search: dynamic facet missing in Typesense, retrying with spine facets only",
235
- toErrorContext(err),
236
- );
237
- return await runSearch(spineFacetBy, sortBy);
262
+ for (let attempt = 0; attempt < 4; attempt++) {
263
+ try {
264
+ return await runSearch(liveFacetBy, sortBy);
265
+ }
266
+ catch (err) {
267
+ const missing = missingFilterField(err);
268
+ if (missing && !droppedFilterFields.has(missing)) {
269
+ getLogService().warn(
270
+ `search: the collection does not declare the filter field \`${missing}\`, retrying without that clause`,
271
+ toErrorContext(err),
272
+ );
273
+ droppedFilterFields.add(missing);
274
+
275
+ continue;
276
+ }
277
+ if (dynamicFacets.length > 0 && isMissingFacetFieldError(err)) {
278
+ getLogService().warn(
279
+ "search: dynamic facet missing in Typesense, retrying with spine facets only",
280
+ toErrorContext(err),
281
+ );
282
+ return await runSearch(spineFacetBy, sortBy);
283
+ }
284
+ throw err;
238
285
  }
239
- throw err;
240
286
  }
287
+ // Every clause the collection rejected has been dropped once; a
288
+ // failure now is a real one.
289
+ return await runSearch(liveFacetBy, sortBy);
241
290
  };
242
291
 
243
292
  try {
@@ -258,9 +307,26 @@ export default defineEventHandler(async (event) => {
258
307
  }
259
308
  }
260
309
 
310
+ // A clause the collection could not carry is enforced here instead.
311
+ // `enabled` is the one that matters: Typesense STORES a field it
312
+ // does not index and hands it back on every hit, so the value is
313
+ // there to be read even when it could not be filtered on. Dropping
314
+ // the clause therefore costs an accurate `found` and accurate facet
315
+ // counts — never a product on the page that should not be there.
316
+ const hits = droppedFilterFields.has("enabled")
317
+ ? (results.hits ?? []).filter(hit => hit.document?.enabled !== false)
318
+ : (results.hits ?? []);
319
+ const withheld = (results.hits ?? []).length - hits.length;
320
+ if (withheld > 0) {
321
+ getLogService().warn(
322
+ `search: withheld ${withheld} disabled product(s) the index could not filter out`,
323
+ { collection: PRODUCTS_COLLECTION },
324
+ );
325
+ }
326
+
261
327
  // Catalog shell only — offers (price + availability) hydrate
262
328
  // separately via POST /api/offers, never blocking search.
263
- const products: ProductList[] = (results.hits ?? []).map(hit => mapLiveDocToProduct(hit.document));
329
+ const products: ProductList[] = hits.map(hit => mapLiveDocToProduct(hit.document));
264
330
  const facets: SearchFacet[] = (results.facet_counts ?? []).map(fc => ({
265
331
  fieldName: fc.field_name,
266
332
  counts: (fc.counts ?? []).map(c => ({ value: c.value, count: c.count })),
@@ -292,7 +358,12 @@ export default defineEventHandler(async (event) => {
292
358
  return {
293
359
  products,
294
360
  facets,
295
- found: results.found,
361
+ // Reduced by what was withheld above, so the count and the rows
362
+ // agree on the page the visitor is looking at. It stays an
363
+ // estimate across the whole result set — only this page's hits
364
+ // were ever read — which is the honest cost of a filter the
365
+ // index could not apply.
366
+ found: Math.max(0, (results.found ?? 0) - withheld),
296
367
  page: results.page ?? page,
297
368
  perPage,
298
369
  };
@@ -20,6 +20,22 @@ export interface CartCalculationOverrides {
20
20
  * client-supplied price — the dumb BFF reads prices from the prices app.
21
21
  */
22
22
  itemUnitPrices?: Record<string, number>;
23
+ /**
24
+ * What the promotions app decided this cart is worth, ATTRIBUTED PER LINE.
25
+ *
26
+ * Per line and not as one figure on purpose. The order applies the same
27
+ * attributed amounts, so the summary and the stored order agree to the
28
+ * cent; a total handed over and split again here would be split by a
29
+ * different rule and disagree by one.
30
+ */
31
+ promotion?: {
32
+ /** Discount on each line, keyed by its 1-based position in the request. */
33
+ lineDiscounts: Record<number, number>;
34
+ /** The sum, for the summary's own row. */
35
+ discountTotal: number;
36
+ /** What to call the row — the promotion's name when exactly one applied. */
37
+ label?: string;
38
+ };
23
39
  }
24
40
 
25
41
  /**
@@ -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, "&amp;")
258
+ .replace(/</g, "&lt;")
259
+ .replace(/>/g, "&gt;")
260
+ .replace(/"/g, "&quot;");
261
+ }
@@ -191,13 +191,18 @@ export class MockCartCalculationService implements ICartCalculationService {
191
191
  });
192
192
  }
193
193
 
194
- const discount = subtotal >= DISCOUNT_THRESHOLD
195
- ? r2(subtotal * DISCOUNT_RATE)
196
- : 0;
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: t("calc.totals.discount", { percent: DISCOUNT_RATE * 100 }),
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 base = (line.lineTotal * discountFactor) + lineSurcharge;
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;