@revenexx/cover 0.6.0 → 0.7.1

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
@@ -0,0 +1,242 @@
1
+ import type { H3Event } from "h3";
2
+
3
+ /**
4
+ * What a platform app was configured to do.
5
+ *
6
+ * Every app declares its own tenant settings — the carts app decides whether a
7
+ * buyer may hold two carts, the shipping app what free delivery costs, the
8
+ * quotes app who may accept one. The gateway resolves them per app at
9
+ * /v1/settings/apps/{app}, already merged: the declared defaults with whatever
10
+ * the operator stored for the tenant or the market on top.
11
+ *
12
+ * So the shop reads them rather than deciding for itself. A storefront that
13
+ * kept its own copy of such a value would be a second answer to a question
14
+ * that already has one, and the buyer would eventually be shown the wrong one
15
+ * — a threshold promised in the header that the shipping app never charges by.
16
+ *
17
+ * Reading fails open. Settings say how the shop should behave, not whether it
18
+ * may run at all, so an unreachable gateway leaves the caller's own fallback
19
+ * standing instead of taking the page down.
20
+ */
21
+
22
+ /** The registry key for reading settings — a domain like any other. */
23
+ export function isAppSettingsLive(event?: H3Event): boolean {
24
+ return resolveServiceKey(event, {
25
+ domain: "settingsService",
26
+ mockKey: "mock",
27
+ liveKey: "api",
28
+ }) === "api";
29
+ }
30
+
31
+ export type AppSettings = Record<string, unknown>;
32
+
33
+ /**
34
+ * How long a resolved app's settings are reused across requests.
35
+ *
36
+ * An operator changes these by hand, in a console, a handful of times a year;
37
+ * a storefront reads them on every rendered page. Without a window here, one
38
+ * page view is a dozen gateway calls for values that did not move. Half a
39
+ * minute is short enough that an operator watching their own change appear
40
+ * does not think it was lost.
41
+ */
42
+ const CACHE_TTL_MS = 30_000;
43
+
44
+ interface CacheEntry {
45
+ readonly settings: AppSettings;
46
+ readonly expires: number;
47
+ }
48
+
49
+ const cache = new Map<string, CacheEntry>();
50
+ /** In-flight reads, so a burst of SSR consumers makes one call and not ten. */
51
+ const inFlight = new Map<string, Promise<AppSettings>>();
52
+
53
+ /** Per-request memo, so the cache TTL can never split one page's answers. */
54
+ const REQUEST_CACHE = "coverAppSettings";
55
+
56
+ function requestCache(event?: H3Event): Map<string, AppSettings> | undefined {
57
+ if (!event) {
58
+ return undefined;
59
+ }
60
+ const ctx = event.context as Record<string, unknown>;
61
+ const existing = ctx[REQUEST_CACHE];
62
+ if (existing instanceof Map) {
63
+ return existing as Map<string, AppSettings>;
64
+ }
65
+ const fresh = new Map<string, AppSettings>();
66
+ ctx[REQUEST_CACHE] = fresh;
67
+ return fresh;
68
+ }
69
+
70
+ /**
71
+ * One app's effective settings for this request's tenant and market.
72
+ *
73
+ * Mock mode reads the demo tenant's own stored values instead
74
+ * (server/config/shop/app-settings.json) — the same key names, through the same
75
+ * reader. Either way what comes back is what somebody CONFIGURED, and a key
76
+ * nobody set is absent in both, so the app's declared default applies. The demo
77
+ * and a live tenant then differ in their settings, never in their behaviour.
78
+ */
79
+ export async function readAppSettings(event: H3Event | undefined, app: string): Promise<AppSettings> {
80
+ if (!isAppSettingsLive(event)) {
81
+ return await readDemoAppSettings(app);
82
+ }
83
+
84
+ const market = event ? resolveSelectedMarket(event) : undefined;
85
+ // Partitioned by tenant: a theme serving several must never answer one
86
+ // tenant's page with another's settings (see revenexxTenantKey()).
87
+ const key = `${revenexxTenantKey()}|${app}|${market ?? "-"}`;
88
+
89
+ const perRequest = requestCache(event);
90
+ const memo = perRequest?.get(key);
91
+ if (memo) {
92
+ return memo;
93
+ }
94
+
95
+ const cached = cache.get(key);
96
+ if (cached && cached.expires > Date.now()) {
97
+ perRequest?.set(key, cached.settings);
98
+ return cached.settings;
99
+ }
100
+
101
+ let pending = inFlight.get(key);
102
+ if (!pending) {
103
+ pending = fetchAppSettings(app, market)
104
+ .then((settings) => {
105
+ cache.set(key, { settings, expires: Date.now() + CACHE_TTL_MS });
106
+ return settings;
107
+ })
108
+ .finally(() => inFlight.delete(key));
109
+ inFlight.set(key, pending);
110
+ }
111
+
112
+ const settings = await pending;
113
+ perRequest?.set(key, settings);
114
+ return settings;
115
+ }
116
+
117
+ async function fetchAppSettings(app: string, market: string | undefined): Promise<AppSettings> {
118
+ try {
119
+ const res = await useRevenexxSdk().settings.settingsGetAppSettings({
120
+ app,
121
+ ...(market ? { market } : {}),
122
+ }) as { settings?: AppSettings };
123
+ return res.settings ?? {};
124
+ }
125
+ catch (err) {
126
+ // Fails open: the caller's declared default stands, and the page renders.
127
+ getLogService().error(`App settings unavailable: ${app}`, apiErrorContext(err));
128
+ return {};
129
+ }
130
+ }
131
+
132
+ /** Several apps at once — one round of calls rather than one after another. */
133
+ export async function readAppSettingsMany<K extends string>(
134
+ event: H3Event | undefined,
135
+ apps: readonly K[],
136
+ ): Promise<Record<K, AppSettings>> {
137
+ const results = await Promise.all(apps.map(app => readAppSettings(event, app)));
138
+ return Object.fromEntries(apps.map((app, i) => [app, results[i]])) as Record<K, AppSettings>;
139
+ }
140
+
141
+ /* ------------------------------------------------------------------ */
142
+ /* Reading one value */
143
+ /* ------------------------------------------------------------------ */
144
+
145
+ /**
146
+ * The readers below all take the app's own declared default as the fallback,
147
+ * so a setting the operator never touched reads the same here as it behaves
148
+ * in the app. Where an app declares NO default — the shipping app's free
149
+ * delivery threshold is the one that matters most — the fallback is null and
150
+ * the shop says nothing rather than naming a figure nobody stands behind.
151
+ */
152
+
153
+ export function boolSetting(settings: AppSettings, key: string, fallback: boolean): boolean {
154
+ const raw = settings[key];
155
+ return typeof raw === "boolean" ? raw : fallback;
156
+ }
157
+
158
+ export function numberSetting(settings: AppSettings, key: string, fallback: number): number {
159
+ const raw = settings[key];
160
+ if (typeof raw === "number" && Number.isFinite(raw)) {
161
+ return raw;
162
+ }
163
+ // The gateway may carry a number as a string; a numeric string is the value.
164
+ if (typeof raw === "string" && raw.trim() !== "" && Number.isFinite(Number(raw))) {
165
+ return Number(raw);
166
+ }
167
+ return fallback;
168
+ }
169
+
170
+ /** A number the app leaves unset — absent means unset, not zero. */
171
+ export function optionalNumberSetting(settings: AppSettings, key: string): number | null {
172
+ const raw = settings[key];
173
+ if (typeof raw === "number" && Number.isFinite(raw)) {
174
+ return raw;
175
+ }
176
+ if (typeof raw === "string" && raw.trim() !== "" && Number.isFinite(Number(raw))) {
177
+ return Number(raw);
178
+ }
179
+ return null;
180
+ }
181
+
182
+ /** A boolean the app leaves unset — the market decides, or nobody has. */
183
+ export function optionalBoolSetting(settings: AppSettings, key: string): boolean | null {
184
+ const raw = settings[key];
185
+ return typeof raw === "boolean" ? raw : null;
186
+ }
187
+
188
+ export function enumSetting<T extends string>(
189
+ settings: AppSettings,
190
+ key: string,
191
+ allowed: readonly T[],
192
+ fallback: T,
193
+ ): T {
194
+ const raw = settings[key];
195
+ return typeof raw === "string" && (allowed as readonly string[]).includes(raw)
196
+ ? raw as T
197
+ : fallback;
198
+ }
199
+
200
+ export function stringSetting(settings: AppSettings, key: string, fallback: string): string {
201
+ const raw = settings[key];
202
+ return typeof raw === "string" && raw.trim() !== "" ? raw.trim() : fallback;
203
+ }
204
+
205
+ /** A comma-separated list, the shape the settings schema uses for those. */
206
+ export function listSetting(settings: AppSettings, key: string, fallback: readonly string[]): string[] {
207
+ const raw = settings[key];
208
+ if (Array.isArray(raw)) {
209
+ return raw.filter((v): v is string => typeof v === "string");
210
+ }
211
+ if (typeof raw === "string" && raw.trim() !== "") {
212
+ return raw.split(",").map(s => s.trim()).filter(Boolean);
213
+ }
214
+ return [...fallback];
215
+ }
216
+
217
+ /* ------------------------------------------------------------------ */
218
+ /* The demo tenant */
219
+ /* ------------------------------------------------------------------ */
220
+
221
+ let demoSettings: Promise<Record<string, AppSettings>> | null = null;
222
+
223
+ /**
224
+ * The demo tenant's stored settings, one section per app.
225
+ *
226
+ * Bundled rather than invented in code, for the same reason the demo
227
+ * organisation and personas are: a showcase is a tenant like any other, and its
228
+ * terms of sale belong in its data. Read once — the asset cannot change while
229
+ * the server runs.
230
+ */
231
+ async function readDemoAppSettings(app: string): Promise<AppSettings> {
232
+ demoSettings ??= readCoverConfigJson<Record<string, AppSettings>>("shop/app-settings.json")
233
+ .catch((err) => {
234
+ // A missing or broken bundle leaves every app's own default standing,
235
+ // which is a working shop, so it must not take the page down.
236
+ getLogService().error("Demo app settings unavailable", toErrorContext(err));
237
+ return {};
238
+ });
239
+ const all = await demoSettings;
240
+ const section = all[app];
241
+ return section && typeof section === "object" ? section : {};
242
+ }
@@ -21,7 +21,13 @@ interface ResolvedPrice {
21
21
  tiers: Array<{ quantity_min: number; unit_price: number }>;
22
22
  }
23
23
 
24
- /** The buyer's price scope from the session (guests resolve openly). */
24
+ /**
25
+ * The buyer's price scope from the session.
26
+ *
27
+ * A guest carries none, and whether they may see prices at all is the prices
28
+ * app's answer (`anonymous_resolve_allowed`), read before the call is made —
29
+ * see resolveLivePriceMap.
30
+ */
25
31
  function priceContext(event: H3Event): { contactId?: string; organizationId?: string } {
26
32
  const raw = getCookie(event, SESSION_COOKIE_NAME);
27
33
  if (!raw) {
@@ -66,10 +72,26 @@ export async function resolveLivePriceMap(
66
72
  if (items.length === 0) {
67
73
  return out;
68
74
  }
75
+ // A merchant who does not quote prices to strangers. The prices app refuses
76
+ // such a resolve, so the shop does not make it: every item comes back without
77
+ // a price, which is the same "price on request" the UI already renders for an
78
+ // article the merchant quotes individually. Asking anyway would turn a
79
+ // deliberate policy into an error page.
80
+ const context = priceContext(event);
81
+ if (!context.contactId && !context.organizationId) {
82
+ const { prices: priceTerms } = await getShopSettings(event);
83
+ if (!priceTerms.anonymousAllowed) {
84
+ for (const item of items) {
85
+ out.set(item.id, []);
86
+ }
87
+ return out;
88
+ }
89
+ }
90
+
69
91
  const currency = resolveSelectedCurrency(event);
70
92
  const { prices } = await useRevenexxSdk().prices.pricesResolve({
71
93
  items: items.map(i => ({ product_id: i.id, sku: i.sku, quantity: 1 })) as Models.PriceResolveItem[],
72
- ...priceContext(event),
94
+ ...context,
73
95
  ...(currency ? { currency } : {}),
74
96
  }) as unknown as { prices: ResolvedPrice[] };
75
97
 
@@ -1,4 +1,4 @@
1
- import { Audience } from "@revenexx/sdk";
1
+ import { AcceptLineDecision, Audience } from "@revenexx/sdk";
2
2
  import type { Models } from "@revenexx/sdk";
3
3
  import type { H3Event } from "h3";
4
4
 
@@ -109,12 +109,59 @@ export async function quoteActor(event: H3Event): Promise<{
109
109
  }
110
110
 
111
111
  /**
112
- * Whether the quote belongs to this buyer. The organisation decides, because
113
- * the quotes app accepts by organisation unless the merchant says otherwise:
114
- * a colleague's request is theirs to order too.
112
+ * The terms a quote is read under — the quotes app's, never this shop's.
113
+ *
114
+ * Who may act on a quote, how long past its date it still counts, when the
115
+ * buyer is warned, and whether a basket may be taken apart: four decisions the
116
+ * app declares as settings, and four the shop used to make for itself. Passed
117
+ * in rather than read here so one request reads them once.
118
+ */
119
+ export interface QuoteTerms {
120
+ acceptanceScope: "requester" | "organization";
121
+ expiryGraceHours: number;
122
+ expiryWarningDays: number;
123
+ partialAcceptance: boolean;
124
+ }
125
+
126
+ /**
127
+ * The terms this request's tenant configured in the quotes app.
128
+ *
129
+ * Read per request and handed down, so one page reads them once and every quote
130
+ * on it is judged by the same four answers.
131
+ */
132
+ export async function quoteTerms(event?: H3Event): Promise<QuoteTerms> {
133
+ const { quotes } = await getShopSettings(event);
134
+ return {
135
+ acceptanceScope: quotes.acceptanceScope,
136
+ expiryGraceHours: quotes.expiryGraceHours,
137
+ expiryWarningDays: quotes.expiryWarningDays,
138
+ partialAcceptance: quotes.partialAcceptance,
139
+ };
140
+ }
141
+
142
+ /** What the app's declared defaults amount to, for a caller that has none. */
143
+ const DEFAULT_TERMS: QuoteTerms = {
144
+ acceptanceScope: "organization",
145
+ expiryGraceHours: 0,
146
+ expiryWarningDays: 3,
147
+ partialAcceptance: true,
148
+ };
149
+
150
+ /**
151
+ * Whether the quote belongs to this buyer.
152
+ *
153
+ * The quotes app decides the reach: `organization` means a colleague's request
154
+ * is the buyer's to order too — the person who asked may be on holiday when the
155
+ * answer arrives — and `requester` means it is not. Reading it the wrong way is
156
+ * a mistake in both directions: too narrow and the answer reaches nobody, too
157
+ * wide and a buyer acts on a colleague's negotiation.
115
158
  */
116
- export function ownsQuote(quote: LiveQuote, actor: { contactId?: string; organizationId?: string }): boolean {
117
- if (quote.organization_id && actor.organizationId) {
159
+ export function ownsQuote(
160
+ quote: LiveQuote,
161
+ actor: { contactId?: string; organizationId?: string },
162
+ terms: QuoteTerms = DEFAULT_TERMS,
163
+ ): boolean {
164
+ if (terms.acceptanceScope === "organization" && quote.organization_id && actor.organizationId) {
118
165
  return quote.organization_id === actor.organizationId;
119
166
  }
120
167
  if (quote.contact_id && actor.contactId) {
@@ -123,15 +170,36 @@ export function ownsQuote(quote: LiveQuote, actor: { contactId?: string; organiz
123
170
  return false;
124
171
  }
125
172
 
126
- function isExpired(quote: LiveQuote): boolean {
173
+ /**
174
+ * Past its date, and past the grace the merchant allows on top.
175
+ *
176
+ * The grace exists because a quote that lapses at midnight is a quote a buyer
177
+ * loses to a weekend. The app grants the hours; the shop only counts them.
178
+ */
179
+ function isExpired(quote: LiveQuote, terms: QuoteTerms): boolean {
127
180
  if (quote.status === "expired") {
128
181
  return true;
129
182
  }
130
- return Boolean(quote.valid_until) && new Date(String(quote.valid_until)).getTime() < Date.now();
183
+ if (!quote.valid_until) {
184
+ return false;
185
+ }
186
+ const deadline = new Date(String(quote.valid_until)).getTime()
187
+ + terms.expiryGraceHours * 60 * 60 * 1000;
188
+ return deadline < Date.now();
189
+ }
190
+
191
+ /** Inside the window the app says to warn in — and not already past it. */
192
+ function expiresSoon(quote: LiveQuote, terms: QuoteTerms, expired: boolean): boolean {
193
+ if (expired || !quote.valid_until || terms.expiryWarningDays <= 0) {
194
+ return false;
195
+ }
196
+ const warnFrom = new Date(String(quote.valid_until)).getTime()
197
+ - terms.expiryWarningDays * 24 * 60 * 60 * 1000;
198
+ return warnFrom <= Date.now();
131
199
  }
132
200
 
133
- /** The quotes app's record, in the account's words. */
134
- export function mapQuote(quote: LiveQuote): AccountQuote {
201
+ /** The quotes app's record, in the account's words and under its terms. */
202
+ export function mapQuote(quote: LiveQuote, terms: QuoteTerms = DEFAULT_TERMS): AccountQuote {
135
203
  const lines: AccountQuoteLine[] = (quote.items ?? []).map(item => ({
136
204
  id: item.id,
137
205
  productId: item.product_id ?? null,
@@ -147,7 +215,7 @@ export function mapQuote(quote: LiveQuote): AccountQuote {
147
215
  decision: item.decision ?? "open",
148
216
  orderId: item.order_id ?? null,
149
217
  }));
150
- const expired = isExpired(quote);
218
+ const expired = isExpired(quote, terms);
151
219
  // A list row carries no positions; there "open" is what the status says.
152
220
  const open = quote.items ? lines.some(line => line.decision === "open") : quote.status !== "accepted";
153
221
  const priced = quote.status === "quoted" || quote.status === "partially_accepted";
@@ -181,6 +249,8 @@ export function mapQuote(quote: LiveQuote): AccountQuote {
181
249
  // merchant's desk — there is nothing to decline until there is a price.
182
250
  canDecline: priced && open && !expired,
183
251
  expired,
252
+ expiresSoon: expiresSoon(quote, terms, expired),
253
+ partialAcceptance: terms.partialAcceptance,
184
254
  };
185
255
  }
186
256
 
@@ -232,12 +302,35 @@ export async function liveQuoteRequest(body: LiveQuoteRequestInput): Promise<Liv
232
302
  return await useRevenexxSdk().quotes.quotesQuotesRequest(body) as LiveQuote;
233
303
  }
234
304
 
235
- export async function liveQuoteAccept(id: string): Promise<LiveQuote & { order_draft: LiveOrderDraft }> {
236
- return await useRevenexxSdk().quotesAcceptance.quotesAcceptanceAccept({ id }) as LiveQuote & { order_draft: LiveOrderDraft };
305
+ /**
306
+ * Take the offer, or the part of it the buyer picked.
307
+ *
308
+ * With no positions the app takes everything still open. With positions it
309
+ * decides exactly those and leaves the quote open for the rest — and it refuses
310
+ * the call outright where the merchant does not allow a basket to be taken
311
+ * apart, which is why the shop asks the setting before offering the choice.
312
+ */
313
+ export async function liveQuoteAccept(
314
+ id: string,
315
+ lineIds?: string[],
316
+ ): Promise<LiveQuote & { order_draft: LiveOrderDraft }> {
317
+ return await useRevenexxSdk().quotesAcceptance.quotesAcceptanceAccept({
318
+ id,
319
+ ...(lineIds?.length
320
+ ? { items: lineIds.map(id => ({ id, decision: AcceptLineDecision.Accepted })) }
321
+ : {}),
322
+ }) as LiveQuote & { order_draft: LiveOrderDraft };
237
323
  }
238
324
 
239
- export async function liveQuoteOrdered(id: string, orderId: string): Promise<void> {
240
- await useRevenexxSdk().quotesAcceptance.quotesAcceptanceOrdered({ id, orderId });
325
+ export async function liveQuoteOrdered(id: string, orderId: string, itemIds?: string[]): Promise<void> {
326
+ // Which positions went onto this order. Left out, the app writes back every
327
+ // accepted position not yet on one — right for a whole acceptance, wrong for
328
+ // a partial one, where a later order would find nothing left to claim.
329
+ await useRevenexxSdk().quotesAcceptance.quotesAcceptanceOrdered({
330
+ id,
331
+ orderId,
332
+ ...(itemIds?.length ? { itemIds } : {}),
333
+ });
241
334
  }
242
335
 
243
336
  export async function liveQuoteDecline(id: string, reason?: string): Promise<void> {
@@ -272,7 +365,7 @@ export async function loadOwnQuote(
272
365
  return quote;
273
366
  }
274
367
  }
275
- if (!quote || !ownsQuote(quote, actor)) {
368
+ if (!quote || !ownsQuote(quote, actor, await quoteTerms(event))) {
276
369
  throw createError({ statusCode: 404, message: "Quote not found" });
277
370
  }
278
371
  return quote;
@@ -0,0 +1,130 @@
1
+ import type { H3Event } from "h3";
2
+ import type { ShopSettings } from "../../app/interfaces/shopSettings";
3
+
4
+ /**
5
+ * The shop's configured behaviour, assembled from the apps that own it.
6
+ *
7
+ * Eleven apps are asked in one round — carts, orders, shipping, prices, markets,
8
+ * promotions, quotes, orderlists, customers, inventories and procurement — and
9
+ * their answers are folded into the one shape the storefront reads
10
+ * (app/interfaces/shopSettings.ts).
11
+ *
12
+ * Every fallback below is the app's OWN declared default, copied from its
13
+ * settings.json. That is deliberate: it means the demo tenant and a live tenant
14
+ * that never touched a setting behave identically, and it means the value in
15
+ * this file can be checked against the app that owns it. Where an app declares
16
+ * no default the fallback is null, and the surface says nothing rather than
17
+ * inventing a figure.
18
+ *
19
+ * Only settings a code path READS are here. A field nothing acts on is the same
20
+ * lie as a setting nothing enforces, one layer further out — so a key that
21
+ * looks useful but reaches no surface stays in the apps until a surface needs
22
+ * it, and the specs record what is still unanswered.
23
+ *
24
+ * Keep this file boring. It maps keys to fields and nothing else; anything that
25
+ * decides something belongs where the deciding is done.
26
+ */
27
+ export async function getShopSettings(event?: H3Event): Promise<ShopSettings> {
28
+ const live = isAppSettingsLive(event);
29
+ const s = await readAppSettingsMany(event, [
30
+ "carts",
31
+ "orders",
32
+ "shipping",
33
+ "prices",
34
+ "markets",
35
+ "promotions",
36
+ "quotes",
37
+ "orderlists",
38
+ "customers",
39
+ "inventories",
40
+ "procurement",
41
+ ] as const);
42
+
43
+ return {
44
+ cart: {
45
+ multipleCarts: boolSetting(s.carts, "multi_cart_enabled", true),
46
+ maxLines: numberSetting(s.carts, "max_items_per_cart", 0),
47
+ maxQuantityPerLine: numberSetting(s.carts, "max_quantity_per_line", 0),
48
+ },
49
+ orders: {
50
+ approvalAboveValue: numberSetting(s.orders, "require_approval_above_value", 0),
51
+ maxPositions: numberSetting(s.orders, "max_items_per_order", 500),
52
+ onUnorderablePosition: enumSetting(
53
+ s.orders,
54
+ "on_unorderable_position",
55
+ ["place", "drop", "refuse"] as const,
56
+ "place",
57
+ ),
58
+ },
59
+ shipping: {
60
+ // No default in the app, and none invented here.
61
+ freeThreshold: optionalNumberSetting(s.shipping, "free_shipping_threshold"),
62
+ freeCompares: enumSetting(s.shipping, "free_above_compares", ["net", "gross"] as const, "gross"),
63
+ cutoffTime: stringSetting(s.shipping, "cutoff_time", "14:00"),
64
+ handlingDays: numberSetting(s.shipping, "handling_days", 1),
65
+ },
66
+ prices: {
67
+ stored: enumSetting(s.prices, "tax_inclusive_default", ["net", "gross"] as const, "net"),
68
+ marketIncludesTax: optionalBoolSetting(s.markets, "prices_include_tax"),
69
+ anonymousAllowed: boolSetting(s.prices, "anonymous_resolve_allowed", true),
70
+ precision: numberSetting(s.prices, "price_precision", 2),
71
+ },
72
+ promotions: {
73
+ maxCodesPerCart: numberSetting(s.promotions, "max_codes_per_cart", 1),
74
+ codeCaseSensitive: boolSetting(s.promotions, "code_case_sensitive", false),
75
+ anonymousAllowed: boolSetting(s.promotions, "anonymous_promotions_allowed", true),
76
+ },
77
+ quotes: {
78
+ partialAcceptance: boolSetting(s.quotes, "partial_acceptance_enabled", true),
79
+ acceptanceScope: enumSetting(s.quotes, "acceptance_scope", ["requester", "organization"] as const, "organization"),
80
+ defaultValidityDays: numberSetting(s.quotes, "default_validity_days", 30),
81
+ expiryGraceHours: numberSetting(s.quotes, "expiry_grace_hours", 0),
82
+ expiryWarningDays: numberSetting(s.quotes, "expiry_warning_days", 3),
83
+ },
84
+ orderLists: {
85
+ maxItems: numberSetting(s.orderlists, "max_items_per_list", 200),
86
+ maxLists: numberSetting(s.orderlists, "max_lists_per_owner", 100),
87
+ sharedEditable: boolSetting(s.orderlists, "shared_lists_editable", false),
88
+ cartMergeMode: enumSetting(s.orderlists, "cart_merge_mode", ["append", "replace"] as const, "append"),
89
+ defaultKind: nullableEnum(s.orderlists, "default_kind", ["shopping", "label"] as const),
90
+ },
91
+ registration: {
92
+ b2b: boolSetting(s.customers, "b2b_registration_enabled", true),
93
+ b2c: boolSetting(s.customers, "b2c_registration_enabled", true),
94
+ vatRequired: boolSetting(s.customers, "organization_vat_id_required", false),
95
+ mode: enumSetting(s.customers, "registration_mode", ["open", "approval_required"] as const, "open"),
96
+ vatValidation: enumSetting(s.customers, "vat_id_validation", ["off", "format", "vies"] as const, "off"),
97
+ },
98
+ signIn: {
99
+ password: boolSetting(s.customers, "login_password", true),
100
+ magicLink: boolSetting(s.customers, "login_magic_link", false),
101
+ emailOtp: boolSetting(s.customers, "login_email_otp", false),
102
+ emailVerification: enumSetting(
103
+ s.customers,
104
+ "email_verification",
105
+ ["off", "on_registration", "required_for_login"] as const,
106
+ "off",
107
+ ),
108
+ },
109
+ account: {
110
+ singleDefaultAddressPerType: boolSetting(s.customers, "single_default_address_per_type", true),
111
+ },
112
+ inventory: {
113
+ backorders: enumSetting(s.inventories, "backorder_policy", ["deny", "allow", "allow_per_sku"] as const, "deny"),
114
+ },
115
+ procurement: {
116
+ gate: enumSetting(s.procurement, "approval_gate", ["none", "booking_account"] as const, "none"),
117
+ },
118
+ source: live ? "apps" : "demo",
119
+ };
120
+ }
121
+
122
+ /** An enum the app leaves unset — absent means unset, not the first value. */
123
+ function nullableEnum<T extends string>(
124
+ settings: Record<string, unknown>,
125
+ key: string,
126
+ allowed: readonly T[],
127
+ ): T | null {
128
+ const raw = settings[key];
129
+ return typeof raw === "string" && (allowed as readonly string[]).includes(raw) ? raw as T : null;
130
+ }