@revenexx/cover 0.6.0 → 0.7.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 (55) hide show
  1. package/app/app.config.ts +12 -0
  2. package/app/components/account/address/AccountAddressView.vue +12 -1
  3. package/app/components/account/orderlists/AccountOrderListDetail.vue +16 -2
  4. package/app/components/account/orderlists/AccountOrderListsTable.vue +9 -1
  5. package/app/components/account/quotes/AccountQuoteDetail.vue +77 -3
  6. package/app/components/auth/AuthLoginPanel.vue +31 -0
  7. package/app/components/auth/AuthRegisterPanel.vue +71 -3
  8. package/app/components/cart/drawer/CartDrawer.vue +2 -1
  9. package/app/components/cart/item/CartItem.vue +4 -1
  10. package/app/components/cart/position/CartPosition.vue +7 -2
  11. package/app/components/cart/quote/CartQuoteRequestModal.vue +9 -0
  12. package/app/components/cart/view/CartSummaryPanel.vue +42 -5
  13. package/app/components/category/info/CategoryPrice.vue +4 -2
  14. package/app/components/layout/header/TopBar.vue +13 -4
  15. package/app/components/product/card/Compact.vue +4 -2
  16. package/app/components/product/detail/ProductDetailAddToCart.vue +8 -3
  17. package/app/composables/useCartLimits.ts +54 -0
  18. package/app/composables/useCartStore.ts +39 -6
  19. package/app/composables/useCartSummaryFormatting.ts +21 -3
  20. package/app/composables/useDeliveryPromise.ts +112 -0
  21. package/app/composables/useOrderListRules.ts +72 -0
  22. package/app/composables/useProduct.ts +5 -2
  23. package/app/composables/useRegistrationConfig.ts +27 -6
  24. package/app/composables/useShopSettings.ts +66 -0
  25. package/app/config/navigation.ts +16 -2
  26. package/app/interfaces/account/quotes.ts +20 -0
  27. package/app/interfaces/cart-calculation.ts +9 -1
  28. package/app/interfaces/shopSettings.ts +246 -0
  29. package/app/plugins/shop-settings.ts +52 -0
  30. package/i18n/locales/de/account.json +6 -0
  31. package/i18n/locales/de/auth.json +12 -0
  32. package/i18n/locales/de/cart.json +12 -3
  33. package/i18n/locales/de/common.json +3 -2
  34. package/i18n/locales/en/account.json +6 -0
  35. package/i18n/locales/en/auth.json +12 -0
  36. package/i18n/locales/en/cart.json +12 -3
  37. package/i18n/locales/en/common.json +3 -2
  38. package/nuxt.config.ts +0 -1
  39. package/package.json +1 -1
  40. package/server/api/account/quotes/[id]/decline.post.ts +1 -1
  41. package/server/api/account/quotes/[id]/order.post.ts +25 -5
  42. package/server/api/account/quotes/[id].get.ts +1 -1
  43. package/server/api/account/quotes.get.ts +10 -3
  44. package/server/api/auth/registration-config.get.ts +19 -33
  45. package/server/api/cart/calculate.post.ts +35 -18
  46. package/server/api/orders/index.post.ts +30 -0
  47. package/server/api/shop/settings.get.ts +14 -0
  48. package/server/config/shop/app-settings.json +54 -0
  49. package/server/interfaces/cartCalculation.ts +22 -0
  50. package/server/services/MockB2BContextService.ts +43 -1
  51. package/server/services/MockCartCalculationService.ts +117 -11
  52. package/server/utils/appSettings.ts +242 -0
  53. package/server/utils/livePrices.ts +24 -2
  54. package/server/utils/quotesService.ts +109 -16
  55. package/server/utils/shopSettings.ts +130 -0
@@ -7,5 +7,5 @@ export default defineEventHandler(async (event): Promise<AccountQuote> => {
7
7
  if (!actor.user) {
8
8
  throw createError({ statusCode: 401, message: "Unauthorized" });
9
9
  }
10
- return mapQuote(await loadOwnQuote(event, id, actor));
10
+ return mapQuote(await loadOwnQuote(event, id, actor), await quoteTerms(event));
11
11
  });
@@ -1,18 +1,23 @@
1
1
  import type { AccountQuoteListResponse } from "../../../app/interfaces/account/quotes";
2
2
 
3
- /** The buyer's quotes, newest first — their organisation's, as the quotes app accepts by organisation. */
3
+ /**
4
+ * The buyer's quotes, newest first — their own or their organisation's, as the
5
+ * quotes app's acceptance scope decides. Read once for the whole list, so every
6
+ * row on the page is judged by the same terms.
7
+ */
4
8
  export default defineEventHandler(async (event): Promise<AccountQuoteListResponse> => {
5
9
  const actor = await quoteActor(event);
6
10
  if (!actor.user) {
7
11
  throw createError({ statusCode: 401, message: "Unauthorized" });
8
12
  }
13
+ const terms = await quoteTerms(event);
9
14
 
10
15
  if (resolveQuotesServiceKey(event) === "api") {
11
16
  try {
12
17
  const rows = await liveQuoteList(actor.organizationId, actor.contactId);
13
18
  // Belt and braces: the app filtered by organisation, and nothing
14
19
  // that is not the buyer's may reach the page even if it did not.
15
- const quotes = rows.filter(row => ownsQuote(row, actor)).map(mapQuote);
20
+ const quotes = rows.filter(row => ownsQuote(row, actor, terms)).map(row => mapQuote(row, terms));
16
21
  return { quotes, total: quotes.length };
17
22
  }
18
23
  catch (err) {
@@ -21,6 +26,8 @@ export default defineEventHandler(async (event): Promise<AccountQuoteListRespons
21
26
  }
22
27
  }
23
28
 
24
- const quotes = (await readMockQuotes()).filter(row => ownsQuote(row, actor) || (!row.organization_id && !row.contact_id)).map(mapQuote);
29
+ const quotes = (await readMockQuotes())
30
+ .filter(row => ownsQuote(row, actor, terms) || (!row.organization_id && !row.contact_id))
31
+ .map(row => mapQuote(row, terms));
25
32
  return { quotes, total: quotes.length };
26
33
  });
@@ -1,41 +1,27 @@
1
1
  /**
2
2
  * Registration availability for the storefront.
3
3
  *
4
- * The customers app exposes self-registration as tenant settings
5
- * (b2b/b2c toggles, VAT requirement). The gateway resolves them at
6
- * /v1/settings/apps/customers; we read them here so the register form can hide
7
- * or disable itself when the tenant has switched registration off. The
8
- * customers app ENFORCES the same flags (403 on a disabled path) — this is the
9
- * matching UX so users never hit a wall after filling the form.
4
+ * The customers app exposes self-registration as tenant settings — the two
5
+ * toggles, the VAT requirement, how far a VAT id is checked, and whether a new
6
+ * account is signed in at once or waits for somebody to say yes. The gateway
7
+ * resolves them; the shop reads them so the register form can hide or disable
8
+ * itself, ask for what is required, and tell an applicant what happens next.
10
9
  *
11
- * Fails open: a settings read error never locks the form. Mock mode (the demo
12
- * shop) reports everything enabled.
10
+ * The customers app ENFORCES the same flags (403 on a disabled path), so this is
11
+ * the matching UX: nobody should fill a form to be turned away by it.
12
+ *
13
+ * Fails open, in the reader: a settings read error leaves every app's declared
14
+ * default standing, which is a working registration.
13
15
  */
14
- interface RegistrationConfig {
15
- b2b: boolean;
16
- b2c: boolean;
17
- vatRequired: boolean;
18
- }
19
-
20
- const DEFAULTS: RegistrationConfig = { b2b: true, b2c: true, vatRequired: false };
16
+ import type { RegistrationConfig } from "../../../app/composables/useRegistrationConfig";
21
17
 
22
18
  export default defineEventHandler(async (event): Promise<RegistrationConfig> => {
23
- if (resolveAuthServiceKey(event) === "mock") {
24
- return DEFAULTS;
25
- }
26
- try {
27
- const res = await useRevenexxSdk().settings.settingsGetAppSettings({ app: "customers" }) as {
28
- settings?: Record<string, unknown>;
29
- };
30
- const s = res.settings ?? {};
31
- return {
32
- b2b: s.b2b_registration_enabled !== false,
33
- b2c: s.b2c_registration_enabled !== false,
34
- vatRequired: s.organization_vat_id_required === true,
35
- };
36
- }
37
- catch (err) {
38
- getLogService().error("API request failed: registration-config", apiErrorContext(err));
39
- return DEFAULTS;
40
- }
19
+ const { registration } = await getShopSettings(event);
20
+ return {
21
+ b2b: registration.b2b,
22
+ b2c: registration.b2c,
23
+ vatRequired: registration.vatRequired,
24
+ mode: registration.mode,
25
+ vatValidation: registration.vatValidation,
26
+ };
41
27
  });
@@ -5,12 +5,19 @@ import type { CartCalculationRequest } from "../../../app/interfaces/cart-calcul
5
5
  import type { CartCalculationOverrides } from "../../interfaces/cartCalculation";
6
6
 
7
7
  /**
8
- * Resolve the pricing inputs the BFF must not invent itself — per-item tax
9
- * rates (prices app) and the shipping fee + its tax rate (shipping app) — so
10
- * the cart/checkout summary matches the totals the orders app will store.
11
- * Best-effort: any failure leaves the demo profile to fill in (mock fees).
8
+ * Resolve everything about this cart the BFF must not invent itself: the
9
+ * per-item tax rates and prices (prices app), the discounts (promotions), the
10
+ * shipping fee and its tax rate (shipping app) and the terms on which delivery
11
+ * is free (also shipping) — so the cart and checkout summary match the totals
12
+ * the orders app will store, and the promises around them match what the
13
+ * merchant configured.
14
+ *
15
+ * Best-effort throughout: a failure leaves the demo profile to fill in rather
16
+ * than taking the cart down. The delivery terms are the exception in one
17
+ * direction only — a threshold nobody set comes back as null, and the summary
18
+ * then states no free-delivery promise at all.
12
19
  */
13
- async function resolveLiveOverrides(
20
+ async function resolveOverrides(
14
21
  event: H3Event,
15
22
  body: CartCalculationRequest,
16
23
  subtotal: number,
@@ -98,6 +105,23 @@ async function resolveLiveOverrides(
98
105
  };
99
106
  }
100
107
 
108
+ // What makes delivery free is the shipping app's to state, and the shop's
109
+ // only to repeat — including where the fee itself still comes from the demo
110
+ // profile, because the nudge in the summary is a promise about this
111
+ // merchant's terms either way. Mock mode answers from the bundled demo
112
+ // tenant, so this is read on every cart and not only on a live one.
113
+ const terms = await getShopSettings(event);
114
+ overrides.freeShipping = {
115
+ threshold: terms.shipping.freeThreshold,
116
+ compares: terms.shipping.freeCompares,
117
+ };
118
+ // Whether a position nobody can order is a problem at all, and what kind:
119
+ // the inventories app answers the first, the orders app the second.
120
+ overrides.positions = {
121
+ backorders: terms.inventory.backorders,
122
+ onUnorderable: terms.orders.onUnorderablePosition,
123
+ };
124
+
101
125
  if (resolveShippingServiceKey(event) === "api") {
102
126
  const method = body.deliveryMethod ?? "standard";
103
127
  try {
@@ -140,21 +164,14 @@ export default defineEventHandler(async (event) => {
140
164
  const context = await getB2BContextService(event).getContext(user?.$id ?? null, user?.role ?? null);
141
165
  const service = getCartCalculationService();
142
166
 
143
- // First pass establishes the subtotal the shipping app prices against;
144
- // a second pass folds the live fee + tax rates into the totals. Mock
145
- // mode skips the round-trips entirely.
167
+ // Two passes: the first establishes the subtotal the shipping app prices
168
+ // against, the second folds the resolved figures into the totals. Both
169
+ // run on every cart now — the delivery terms the summary states are read
170
+ // from the apps whether the rest of the shop is live or not, so there is
171
+ // no longer a cart for which the first pass is the whole answer.
146
172
  const base = await service.calculate(body, context, locale);
147
- if (resolvePriceServiceKey(event) !== "api"
148
- && resolveShippingServiceKey(event) !== "api"
149
- && resolvePromotionsServiceKey(event) !== "api") {
150
- return base;
151
- }
152
173
  const subtotal = base.totals.find(row => row.key === "subtotal")?.amount ?? 0;
153
- const overrides = await resolveLiveOverrides(event, body, subtotal, base.currency);
154
- if (!overrides.shipping && !overrides.itemTaxRates && !overrides.itemUnitPrices
155
- && !overrides.currency && !overrides.promotion) {
156
- return base;
157
- }
174
+ const overrides = await resolveOverrides(event, body, subtotal, base.currency);
158
175
  return await service.calculate(body, context, locale, overrides);
159
176
  }
160
177
  catch (err) {
@@ -159,6 +159,9 @@ export default defineEventHandler(async (event) => {
159
159
  const user = await getAuthService(event).me(event);
160
160
  const context = await getB2BContextService(event).getContext(user?.$id ?? null, user?.role ?? null);
161
161
  const locale = resolveLocale(event);
162
+ // The same terms the cart was calculated under, or the order would be
163
+ // judged by different rules than the summary the buyer agreed to.
164
+ const terms = await getShopSettings(event);
162
165
  const calculation = await getCartCalculationService().calculate(
163
166
  {
164
167
  items: body.items as never,
@@ -166,7 +169,25 @@ export default defineEventHandler(async (event) => {
166
169
  },
167
170
  context,
168
171
  locale,
172
+ {
173
+ positions: {
174
+ backorders: terms.inventory.backorders,
175
+ onUnorderable: terms.orders.onUnorderablePosition,
176
+ },
177
+ },
169
178
  );
179
+
180
+ // A cart the calculation says cannot be ordered is not ordered. The cart
181
+ // page says so and hides the button, but the button is not the rule: a
182
+ // stale tab, a second window or a direct call would otherwise place an
183
+ // order the shop had already told the buyer it could not place.
184
+ if (!calculation.orderable) {
185
+ const blocking = calculation.messages.find(m => m.severity === "error");
186
+ throw createError({
187
+ status: 422,
188
+ message: `Cart cannot be ordered${blocking ? `: ${blocking.code}` : ""}`,
189
+ });
190
+ }
170
191
  const blockingApprovals = calculation.approvalLimits.filter(
171
192
  l => l.status === "exceeded" && l.approval.required,
172
193
  );
@@ -369,6 +390,15 @@ export default defineEventHandler(async (event) => {
369
390
  quantity: calculation.lines[index]?.adjustedQuantity ?? Number(item.quantity),
370
391
  unit_price: itemPrice.get(String(item.id)) ?? itemPrice.get(String(item.sku ?? "")) ?? calculation.lines[index]?.unitPrice ?? Number(item.price ?? 0),
371
392
  tax_rate: itemRate.get(String(item.id)) ?? itemRate.get(String(item.sku ?? "")) ?? 0,
393
+ // Whether this position can be ordered at all. The orders app
394
+ // holds the merchant's policy for one that cannot — order it,
395
+ // leave it out, or refuse the lot — and cannot see stock
396
+ // itself, so the answer has to travel with the position.
397
+ // Only sent when it is false: a flag on every line would be
398
+ // noise on the ninety-nine that are fine.
399
+ ...(calculation.lines[index]?.hints.some(h => h.type === "not-orderable")
400
+ ? { orderable: false }
401
+ : {}),
372
402
  product: {
373
403
  ...(item.image ? { image: String(item.image) } : {}),
374
404
  ...(item.categorySlug ? { categorySlug: String(item.categorySlug) } : {}),
@@ -0,0 +1,14 @@
1
+ /**
2
+ * What the shop was configured to do, for the surfaces that render it.
3
+ *
4
+ * One read for the whole storefront: the header's delivery promise, the
5
+ * quantity field's ceiling, which sign-in methods the login page offers, what
6
+ * a quote page lets a buyer do. Every value comes from the app that owns it
7
+ * (see server/utils/shopSettings.ts) and none is decided here.
8
+ *
9
+ * Public on purpose. These are the shop's own terms — a buyer reads every one
10
+ * of them off the page anyway — so nothing here depends on who is asking.
11
+ */
12
+ export default defineEventHandler(async (event) => {
13
+ return await getShopSettings(event);
14
+ });
@@ -0,0 +1,54 @@
1
+ {
2
+ "_comment": [
3
+ "What the DEMO tenant has configured in the platform apps.",
4
+ "",
5
+ "Mock mode has no gateway to ask, so this file plays the part of the stored",
6
+ "tenant settings: the same key names the apps declare, read through the same",
7
+ "reader (server/utils/appSettings.ts). A key left out here is not configured,",
8
+ "and the app's own declared default then applies — exactly as it would for a",
9
+ "live tenant who never touched it.",
10
+ "",
11
+ "So this is the showcase's own terms of sale, and nothing else in the shop",
12
+ "may hold a second copy of them. The header's delivery promise and the",
13
+ "cart's free-delivery nudge are both built from the shipping block below."
14
+ ],
15
+ "shipping": {
16
+ "free_shipping_threshold": 100,
17
+ "free_above_compares": "net",
18
+ "cutoff_time": "14:00",
19
+ "handling_days": 1,
20
+ "weight_unit": "kg"
21
+ },
22
+ "carts": {
23
+ "multi_cart_enabled": true,
24
+ "max_quantity_per_line": 9999
25
+ },
26
+ "prices": {
27
+ "tax_inclusive_default": "net",
28
+ "anonymous_resolve_allowed": true
29
+ },
30
+ "quotes": {
31
+ "partial_acceptance_enabled": true,
32
+ "acceptance_scope": "organization",
33
+ "default_validity_days": 30,
34
+ "expiry_warning_days": 3
35
+ },
36
+ "orderlists": {
37
+ "shared_lists_editable": true,
38
+ "on_missing_article": "skip",
39
+ "cart_merge_mode": "append"
40
+ },
41
+ "promotions": {
42
+ "max_codes_per_cart": 1,
43
+ "code_case_sensitive": false
44
+ },
45
+ "inventories": {
46
+ "backorder_policy": "deny"
47
+ },
48
+ "customers": {
49
+ "b2b_registration_enabled": true,
50
+ "b2c_registration_enabled": true,
51
+ "registration_mode": "open",
52
+ "login_password": true
53
+ }
54
+ }
@@ -12,6 +12,28 @@ export interface CartCalculationOverrides {
12
12
  currency?: string;
13
13
  /** Live shipping fee + its tax rate for the chosen method. */
14
14
  shipping?: { price: number; taxRate: number };
15
+ /**
16
+ * What makes delivery free, as the shipping app has it.
17
+ *
18
+ * `threshold: null` is an answer and not a missing one: this merchant has
19
+ * not promised free delivery, so the summary must not nudge a buyer towards
20
+ * a figure nobody set. `compares` says whether the threshold is met on the
21
+ * goods' net or gross value — the shipping app sends it with every rate for
22
+ * exactly this reason, so a buyer and the app never read one cart two ways.
23
+ */
24
+ freeShipping?: { threshold: number | null; compares: "net" | "gross" };
25
+ /**
26
+ * What to do about a position nobody can order.
27
+ *
28
+ * Two apps answer between them: the inventories app says whether stock that
29
+ * is not there may be ordered anyway (`backorders`), and the orders app says
30
+ * what a placement does with such a position (`onUnorderable`). The cart
31
+ * needs both — whether a line is a problem, and what kind.
32
+ */
33
+ positions?: {
34
+ backorders: "deny" | "allow" | "allow_per_sku";
35
+ onUnorderable: "place" | "drop" | "refuse";
36
+ };
15
37
  /** Per-item tax rate (percent) keyed by product id or sku, from prices.resolve. */
16
38
  itemTaxRates?: Record<string, number>;
17
39
  /**
@@ -2,6 +2,8 @@ import type { H3Event } from "h3";
2
2
  import type { B2BContext, B2BRole, ApprovalLimit, ApprovalWorkflow, CostCenter, OrganizationSettings, Requisition } from "../../app/interfaces/b2b";
3
3
  import type { AuthRole } from "../../app/interfaces/auth";
4
4
 
5
+ import { resolvePriceBasis } from "../../app/interfaces/shopSettings";
6
+
5
7
  import type { IB2BContextService, IRequisitionService } from "../interfaces/b2bContext";
6
8
 
7
9
  interface OrganizationConfig {
@@ -47,7 +49,7 @@ export class B2BContextService implements IB2BContextService {
47
49
 
48
50
  async getContext(userId: string | null, fallbackRole?: B2BRole | null): Promise<B2BContext> {
49
51
  const org = await readCoverConfigJson<OrganizationConfig>("account/organization.json");
50
- const settings = this.mergeSettings(org.settings);
52
+ const settings = await this.applyAppSettings(this.mergeSettings(org.settings));
51
53
 
52
54
  if (!userId) {
53
55
  return {
@@ -130,6 +132,46 @@ export class B2BContextService implements IB2BContextService {
130
132
  };
131
133
  }
132
134
 
135
+ /**
136
+ * Fold in what the apps decided, over what the organisation and the
137
+ * storefront configured.
138
+ *
139
+ * Three of these settings existed in two places. Whether a buyer may keep
140
+ * several carts is the carts app's `multi_cart_enabled`; whether prices read
141
+ * net or gross is the prices app's basis and the market's override; whether
142
+ * spending is approved before it happens is the procurement app's gate and
143
+ * the orders app's value threshold. The shop's own flags said the same things
144
+ * in its own words, and the two could disagree — a buyer offered a second
145
+ * cart the carts app then refused with a 409, a summary quoting net while the
146
+ * order was booked gross.
147
+ *
148
+ * The apps win, because they are the ones that act. What stays the shop's is
149
+ * everything no app answers: cost centres, workflows, the minimum order
150
+ * value, guest ordering, the mandatory order number.
151
+ */
152
+ private async applyAppSettings(base: OrganizationSettings): Promise<OrganizationSettings> {
153
+ const shop = await getShopSettings(this.event);
154
+ if (shop.source !== "apps") {
155
+ // The bundled demo tenant: the organisation's own settings and the dev
156
+ // panel are the showcase's story, and nothing overrides them.
157
+ return base;
158
+ }
159
+ return {
160
+ ...base,
161
+ // Approved before it happens, if either app says so: procurement's gate
162
+ // routes the cart through its rules, and the orders app's threshold
163
+ // turns a large order into a request on its own.
164
+ approvals: {
165
+ enabled: shop.procurement.gate !== "none" || shop.orders.approvalAboveValue > 0,
166
+ },
167
+ cart: {
168
+ ...base.cart,
169
+ multipleCarts: shop.cart.multipleCarts,
170
+ priceDisplay: resolvePriceBasis(shop.prices),
171
+ },
172
+ };
173
+ }
174
+
133
175
  private mergeSettings(base: OrganizationSettings): OrganizationSettings {
134
176
  const o = this.settingsOverride;
135
177
  if (!o) {
@@ -36,9 +36,11 @@ const SURCHARGE_PER_UNIT = 2.5;
36
36
  const DISCOUNT_THRESHOLD = 1000;
37
37
  const DISCOUNT_RATE = 0.03;
38
38
 
39
- // Free shipping from FREE_SHIPPING_THRESHOLD net (the topbar promise);
40
- // below it standard delivery costs a flat fee. Express always costs.
41
- const FREE_SHIPPING_THRESHOLD = 100;
39
+ // The demo profile's own delivery terms. A tenant's real ones come from the
40
+ // shipping app and arrive as overrides.freeShipping — this figure applies only
41
+ // where no app has been asked, which is the showcase running on bundled data.
42
+ // Below the threshold standard delivery costs a flat fee; express always costs.
43
+ const DEMO_FREE_SHIPPING_THRESHOLD = 100;
42
44
  const STANDARD_SHIPPING_FEE = 6.9;
43
45
  const EXPRESS_SHIPPING_FEE = 9.9;
44
46
 
@@ -60,6 +62,43 @@ const normalizeRate = (rate: number | undefined): number => {
60
62
  return Math.round(percent * 100) / 100;
61
63
  };
62
64
 
65
+ /**
66
+ * The goods' value with tax, for a shipping app that compares its free-delivery
67
+ * threshold gross.
68
+ *
69
+ * The goods only: delivery is not part of what earns free delivery, or the
70
+ * threshold would move with the fee it decides. Discounts come off first —
71
+ * "order value" is what the buyer is being charged for the articles, and a
72
+ * threshold measured before a discount would promise free delivery on a cart
73
+ * that no longer reaches it.
74
+ */
75
+ const grossGoodsValue = (
76
+ lines: CalculatedCartLine[],
77
+ items: CartItem[],
78
+ overrides: CartCalculationOverrides | undefined,
79
+ discount: number,
80
+ subtotal: number,
81
+ ): number => {
82
+ const discountFactor = subtotal > 0 ? 1 - discount / subtotal : 1;
83
+ let gross = 0;
84
+ for (let i = 0; i < lines.length; i++) {
85
+ const line = lines[i]!;
86
+ const item = items[i]!;
87
+ if (line.priceLabel) {
88
+ continue;
89
+ }
90
+ const qty = line.adjustedQuantity ?? line.quantity;
91
+ const surcharge = line.surcharges.reduce((s, c) => s + c.amountPerUnit * qty, 0);
92
+ const discounted = overrides?.promotion
93
+ ? line.lineTotal - (overrides.promotion.lineDiscounts[i + 1] ?? 0)
94
+ : line.lineTotal * discountFactor;
95
+ const liveRate = overrides?.itemTaxRates?.[item.id] ?? overrides?.itemTaxRates?.[item.sku ?? ""];
96
+ const rate = normalizeRate(liveRate ?? item.taxRate);
97
+ gross += (discounted + surcharge) * (1 + rate / 100);
98
+ }
99
+ return r2(gross);
100
+ };
101
+
63
102
  const tieredUnitPrice = (item: CartItem, quantity: number): number => {
64
103
  if (!item.priceTiers?.length) {
65
104
  return item.price;
@@ -139,6 +178,27 @@ export class MockCartCalculationService implements ICartCalculationService {
139
178
  ? { state: "partial" as const, availableQuantity: stock, deliveryDays: 7 }
140
179
  : { state: "in-stock" as const, availableQuantity: stock, deliveryDays: 2 };
141
180
 
181
+ // A position nobody can order: the stock is not there and the
182
+ // inventories app forbids backorders. Where it allows them, a line
183
+ // out of stock is a delivery date and not a problem — which is why
184
+ // the verdict is the app's and not this service's.
185
+ //
186
+ // `allow_per_sku` means per-article flags that reach no cart today, so
187
+ // it is read as "allow": telling a buyer they cannot order something
188
+ // they can is the worse of the two mistakes. Recorded as a gap.
189
+ const backordersDenied = overrides?.positions?.backorders === "deny";
190
+ if (backordersDenied && availability.state !== "in-stock") {
191
+ // WHICH message depends on what the orders app will do with it —
192
+ // left out, refused, or ordered anyway. "Out of stock" alone tells
193
+ // the buyer nothing about what to do next.
194
+ const policy = overrides?.positions?.onUnorderable ?? "place";
195
+ hints.push({
196
+ type: "not-orderable",
197
+ messageKey: `calc.hints.notOrderable.${policy}`,
198
+ params: { available: availability.availableQuantity },
199
+ });
200
+ }
201
+
142
202
  if ((skuCounts.get(item.sku ?? "") ?? 0) > 1) {
143
203
  hints.push({ type: "duplicate", messageKey: "calc.hints.duplicate" });
144
204
  }
@@ -207,6 +267,21 @@ export class MockCartCalculationService implements ICartCalculationService {
207
267
  });
208
268
  }
209
269
 
270
+ // What makes delivery free is the shipping app's answer where one was
271
+ // read, and the demo profile's only where none was. A threshold of null
272
+ // means this merchant has not promised free delivery at all, and the
273
+ // summary then says nothing about one rather than naming a figure the
274
+ // shipping app would never charge by.
275
+ const freeShippingThreshold = overrides?.freeShipping
276
+ ? overrides.freeShipping.threshold
277
+ : DEMO_FREE_SHIPPING_THRESHOLD;
278
+ // Net or gross, as the shipping app compares it. The figure is the
279
+ // goods' value: shipping is not part of what earns free shipping.
280
+ const goodsValue = overrides?.freeShipping?.compares === "gross"
281
+ ? grossGoodsValue(lines, request.items, overrides, discount, subtotal)
282
+ : r2(subtotal - discount);
283
+ const freeShippingReached = freeShippingThreshold !== null && goodsValue >= freeShippingThreshold;
284
+
210
285
  // Live mode: the shipping fee comes from the shipping app (resolved in
211
286
  // the cart endpoint), so the summary matches the order. Mock mode keeps
212
287
  // the demo profile's flat/free logic.
@@ -214,7 +289,7 @@ export class MockCartCalculationService implements ICartCalculationService {
214
289
  ? r2(overrides.shipping.price)
215
290
  : (request.deliveryMethod ?? "standard") === "express"
216
291
  ? EXPRESS_SHIPPING_FEE
217
- : subtotal >= FREE_SHIPPING_THRESHOLD ? 0 : STANDARD_SHIPPING_FEE;
292
+ : freeShippingReached ? 0 : STANDARD_SHIPPING_FEE;
218
293
  totals.push({ key: "shipping", label: t("calc.totals.shipping"), amount: shipping, alwaysVisible: true });
219
294
 
220
295
  // Taxable base per rate: line totals + line surcharges, discount applied
@@ -278,6 +353,32 @@ export class MockCartCalculationService implements ICartCalculationService {
278
353
  const messages: CartMessage[] = [];
279
354
  let orderable = true;
280
355
 
356
+ // A cart the orders app would refuse is a cart that cannot be ordered, and
357
+ // the buyer has to be told BEFORE the checkout rather than by a 400 at the
358
+ // end of it. Where the policy leaves the position out instead, the cart is
359
+ // orderable and the warning says what will be missing from the delivery.
360
+ const unorderableLines = lines.filter(l => l.hints.some(h => h.type === "not-orderable"));
361
+ if (unorderableLines.length > 0) {
362
+ const policy = overrides?.positions?.onUnorderable ?? "place";
363
+ if (policy === "refuse") {
364
+ orderable = false;
365
+ messages.push({
366
+ severity: "error",
367
+ code: "positions-not-orderable",
368
+ messageKey: "calc.messages.positionsNotOrderable",
369
+ params: { count: unorderableLines.length },
370
+ });
371
+ }
372
+ else if (policy === "drop") {
373
+ messages.push({
374
+ severity: "warning",
375
+ code: "positions-will-be-dropped",
376
+ messageKey: "calc.messages.positionsWillBeDropped",
377
+ params: { count: unorderableLines.length },
378
+ });
379
+ }
380
+ }
381
+
281
382
  if (settings.costCenters.enabled && settings.costCenters.required && role) {
282
383
  const missing = lines.some(l => l.hints.some(h => h.type === "missing-cost-center"));
283
384
  if (context.costCenters.length === 0) {
@@ -305,13 +406,18 @@ export class MockCartCalculationService implements ICartCalculationService {
305
406
 
306
407
  /* ---- spend incentives (revenue nudges for the summary) ---------- */
307
408
  const incentives = [
308
- {
309
- key: "free-shipping" as const,
310
- label: t("calc.incentives.freeShipping"),
311
- threshold: FREE_SHIPPING_THRESHOLD,
312
- missing: r2(Math.max(0, FREE_SHIPPING_THRESHOLD - subtotal)),
313
- reached: subtotal >= FREE_SHIPPING_THRESHOLD,
314
- },
409
+ // Only where free delivery is actually promised. A nudge towards a
410
+ // threshold the merchant never set would be the shop inventing a
411
+ // term of sale.
412
+ ...(freeShippingThreshold !== null
413
+ ? [{
414
+ key: "free-shipping" as const,
415
+ label: t("calc.incentives.freeShipping"),
416
+ threshold: freeShippingThreshold,
417
+ missing: r2(Math.max(0, freeShippingThreshold - goodsValue)),
418
+ reached: freeShippingReached,
419
+ }]
420
+ : []),
315
421
  {
316
422
  key: "volume-discount" as const,
317
423
  label: t("calc.incentives.volumeDiscount", { percent: DISCOUNT_RATE * 100 }),