@revenexx/cover 0.7.1 → 0.10.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 (101) hide show
  1. package/app/api/forms.ts +1 -0
  2. package/app/app.config.ts +17 -12
  3. package/app/components/RevenexxForm.vue +80 -12
  4. package/app/components/account/AccountShell.vue +18 -0
  5. package/app/components/account/approvals/AccountPendingApprovals.vue +178 -0
  6. package/app/components/account/orderlists/AccountOrderListDetail.vue +47 -4
  7. package/app/components/account/orders/AccountOrderDetail.vue +186 -1
  8. package/app/components/account/payments/AccountPayments.vue +129 -0
  9. package/app/components/account/quotes/AccountQuoteDetail.vue +48 -16
  10. package/app/components/auth/AuthLoginPanel.vue +131 -15
  11. package/app/components/auth/AuthMagicLinkPanel.vue +70 -0
  12. package/app/components/cart/view/CartSummaryPanel.vue +54 -0
  13. package/app/components/checkout/onepage/CheckoutDeliverySection.vue +13 -1
  14. package/app/components/checkout/onepage/CheckoutGate.vue +8 -7
  15. package/app/components/form/FormPage.vue +40 -0
  16. package/app/components/layout/header/AppBar.vue +7 -1
  17. package/app/components/layout/header/MainNav.vue +23 -1
  18. package/app/components/layout/header/MobileMenu.vue +12 -0
  19. package/app/components/product/detail/ProductDetailPriceRequest.vue +39 -0
  20. package/app/components/product/detail/ProductDetailView.vue +57 -0
  21. package/app/composables/useAccountHold.ts +45 -0
  22. package/app/composables/useAccountPayments.ts +21 -0
  23. package/app/composables/useAccountQuotes.ts +15 -2
  24. package/app/composables/useAuthStore.ts +82 -2
  25. package/app/composables/useAuthoredForms.ts +26 -0
  26. package/app/composables/useAvailableOffers.ts +42 -0
  27. package/app/composables/useGuestOrdering.ts +28 -0
  28. package/app/composables/useMasterDataEditable.ts +22 -7
  29. package/app/composables/useOrderListRules.ts +21 -1
  30. package/app/composables/usePendingApprovals.ts +37 -0
  31. package/app/config/icons.ts +2 -0
  32. package/app/config/navigation.ts +2 -2
  33. package/app/formkit.config.ts +14 -0
  34. package/app/interfaces/account/approvals.ts +37 -0
  35. package/app/interfaces/account/order-list.ts +29 -0
  36. package/app/interfaces/account/order-lists.ts +9 -0
  37. package/app/interfaces/account/payments.ts +48 -0
  38. package/app/interfaces/auth.ts +11 -0
  39. package/app/interfaces/b2b.ts +8 -8
  40. package/app/interfaces/offers.ts +35 -0
  41. package/app/interfaces/shopSettings.ts +77 -0
  42. package/app/plugins/account-hold.client.ts +20 -0
  43. package/app/plugins/shop-settings.ts +27 -12
  44. package/i18n/locales/de/account.json +80 -0
  45. package/i18n/locales/de/auth.json +29 -0
  46. package/i18n/locales/de/cart.json +7 -0
  47. package/i18n/locales/de/checkout.json +2 -1
  48. package/i18n/locales/de/common.json +2 -0
  49. package/i18n/locales/de/forms.json +27 -0
  50. package/i18n/locales/en/account.json +80 -0
  51. package/i18n/locales/en/auth.json +29 -0
  52. package/i18n/locales/en/cart.json +7 -0
  53. package/i18n/locales/en/checkout.json +2 -1
  54. package/i18n/locales/en/common.json +2 -0
  55. package/i18n/locales/en/forms.json +27 -0
  56. package/package.json +2 -1
  57. package/server/api/account/address/[id].delete.ts +1 -1
  58. package/server/api/account/address/[id].put.ts +1 -1
  59. package/server/api/account/address/index.post.ts +1 -1
  60. package/server/api/account/order-lists/[id].get.ts +37 -3
  61. package/server/api/account/orders/[id]/cancel.post.ts +54 -0
  62. package/server/api/account/orders/[id]/messages.get.ts +63 -0
  63. package/server/api/account/orders/[id]/messages.post.ts +44 -0
  64. package/server/api/account/organization.put.ts +1 -1
  65. package/server/api/account/payments.get.ts +54 -0
  66. package/server/api/account/pending-approvals/[id]/approve.post.ts +10 -0
  67. package/server/api/account/pending-approvals/[id]/decline.post.ts +10 -0
  68. package/server/api/account/pending-approvals/index.get.ts +25 -0
  69. package/server/api/account/profile.put.ts +1 -1
  70. package/server/api/account/quotes/[id]/decline.post.ts +35 -6
  71. package/server/api/account/team/[id].put.ts +1 -1
  72. package/server/api/account/team.post.ts +1 -1
  73. package/server/api/auth/magic-link.post.ts +32 -0
  74. package/server/api/auth/magic-link.put.ts +30 -0
  75. package/server/api/auth/otp.post.ts +33 -0
  76. package/server/api/auth/otp.put.ts +28 -0
  77. package/server/api/checkout/profile.get.ts +6 -3
  78. package/server/api/forms/[slug]/submit.post.ts +27 -16
  79. package/server/api/forms/[slug].get.ts +9 -1
  80. package/server/api/forms/index.get.ts +23 -0
  81. package/server/api/orders/index.post.ts +8 -0
  82. package/server/api/promotions/available.post.ts +37 -0
  83. package/server/config/account/organization.json +0 -4
  84. package/server/config/shop/app-settings.json +4 -0
  85. package/server/data/forms/authored.json +337 -0
  86. package/server/interfaces/forms.ts +51 -0
  87. package/server/services/ApiAuthService.ts +10 -0
  88. package/server/services/ApiFormsService.ts +56 -0
  89. package/server/services/MockB2BContextService.ts +1 -5
  90. package/server/services/MockFormsService.ts +63 -0
  91. package/server/utils/accountPayments.ts +45 -0
  92. package/server/utils/appSettings.ts +69 -4
  93. package/server/utils/forms.ts +62 -14
  94. package/server/utils/formsService.ts +29 -0
  95. package/server/utils/liveOrders.ts +26 -0
  96. package/server/utils/masterData.ts +31 -11
  97. package/server/utils/passwordlessSignIn.ts +73 -0
  98. package/server/utils/pendingApprovals.ts +153 -0
  99. package/server/utils/promotionsService.ts +90 -0
  100. package/server/utils/quotesService.ts +15 -0
  101. package/server/utils/shopSettings.ts +35 -4
@@ -30,6 +30,54 @@ export function isAppSettingsLive(event?: H3Event): boolean {
30
30
 
31
31
  export type AppSettings = Record<string, unknown>;
32
32
 
33
+ /**
34
+ * Cookie the demo shop's dev panel writes to try a setting without a Console
35
+ * round-trip: `{ "<app>": { "<key>": value } }`.
36
+ *
37
+ * It is a SIMULATION and says so — a request carrying it reports its settings as
38
+ * the demo's, whatever they were read from, so nothing can mistake a tried value
39
+ * for a configured one. Without that, the panel would be a fourth place a term of
40
+ * sale is decided, which is the thing this whole reader exists to remove.
41
+ */
42
+ export const APP_SETTINGS_OVERRIDE_COOKIE = "cover-app-settings";
43
+
44
+ function readOverride(event: H3Event | undefined, app: string): AppSettings | null {
45
+ if (!event) {
46
+ return null;
47
+ }
48
+ const raw = getCookie(event, APP_SETTINGS_OVERRIDE_COOKIE);
49
+ if (!raw) {
50
+ return null;
51
+ }
52
+ try {
53
+ const parsed = JSON.parse(raw) as Record<string, AppSettings>;
54
+ const section = parsed?.[app];
55
+ return section && typeof section === "object" ? section : null;
56
+ }
57
+ catch {
58
+ // A malformed cookie is a dev-panel bug, not a reason to stop serving.
59
+ return null;
60
+ }
61
+ }
62
+
63
+ /** Whether this request is carrying any tried-out setting at all. */
64
+ export function hasAppSettingsOverride(event?: H3Event): boolean {
65
+ if (!event) {
66
+ return false;
67
+ }
68
+ const raw = getCookie(event, APP_SETTINGS_OVERRIDE_COOKIE);
69
+ if (!raw) {
70
+ return false;
71
+ }
72
+ try {
73
+ const parsed = JSON.parse(raw) as Record<string, unknown>;
74
+ return Boolean(parsed && typeof parsed === "object" && Object.keys(parsed).length > 0);
75
+ }
76
+ catch {
77
+ return false;
78
+ }
79
+ }
80
+
33
81
  /**
34
82
  * How long a resolved app's settings are reused across requests.
35
83
  *
@@ -77,8 +125,9 @@ function requestCache(event?: H3Event): Map<string, AppSettings> | undefined {
77
125
  * and a live tenant then differ in their settings, never in their behaviour.
78
126
  */
79
127
  export async function readAppSettings(event: H3Event | undefined, app: string): Promise<AppSettings> {
128
+ const override = readOverride(event, app);
80
129
  if (!isAppSettingsLive(event)) {
81
- return await readDemoAppSettings(app);
130
+ return { ...await readDemoAppSettings(app), ...override };
82
131
  }
83
132
 
84
133
  const market = event ? resolveSelectedMarket(event) : undefined;
@@ -86,16 +135,22 @@ export async function readAppSettings(event: H3Event | undefined, app: string):
86
135
  // tenant's page with another's settings (see revenexxTenantKey()).
87
136
  const key = `${revenexxTenantKey()}|${app}|${market ?? "-"}`;
88
137
 
138
+ // The override is applied at every exit below rather than folded into the
139
+ // cache: what is cached is what the TENANT configured, and a value somebody is
140
+ // trying in one browser must never be served to another.
141
+ const withOverride = (settings: AppSettings): AppSettings =>
142
+ override ? { ...settings, ...override } : settings;
143
+
89
144
  const perRequest = requestCache(event);
90
145
  const memo = perRequest?.get(key);
91
146
  if (memo) {
92
- return memo;
147
+ return withOverride(memo);
93
148
  }
94
149
 
95
150
  const cached = cache.get(key);
96
151
  if (cached && cached.expires > Date.now()) {
97
152
  perRequest?.set(key, cached.settings);
98
- return cached.settings;
153
+ return withOverride(cached.settings);
99
154
  }
100
155
 
101
156
  let pending = inFlight.get(key);
@@ -111,7 +166,7 @@ export async function readAppSettings(event: H3Event | undefined, app: string):
111
166
 
112
167
  const settings = await pending;
113
168
  perRequest?.set(key, settings);
114
- return settings;
169
+ return withOverride(settings);
115
170
  }
116
171
 
117
172
  async function fetchAppSettings(app: string, market: string | undefined): Promise<AppSettings> {
@@ -202,6 +257,16 @@ export function stringSetting(settings: AppSettings, key: string, fallback: stri
202
257
  return typeof raw === "string" && raw.trim() !== "" ? raw.trim() : fallback;
203
258
  }
204
259
 
260
+ /**
261
+ * A string setting the app leaves empty by default — "" and absent both mean
262
+ * unset, and null says so in one shape rather than making every reader compare
263
+ * against the empty string.
264
+ */
265
+ export function optionalStringSetting(settings: AppSettings, key: string): string | null {
266
+ const raw = settings[key];
267
+ return typeof raw === "string" && raw.trim() !== "" ? raw.trim() : null;
268
+ }
269
+
205
270
  /** A comma-separated list, the shape the settings schema uses for those. */
206
271
  export function listSetting(settings: AppSettings, key: string, fallback: readonly string[]): string[] {
207
272
  const raw = settings[key];
@@ -1,4 +1,6 @@
1
- import type { FormRow, FormSettings } from "../interfaces/forms";
1
+ import type { H3Event } from "h3";
2
+
3
+ import type { FormRow, FormSettings, FormSpamPolicy } from "../interfaces/forms";
2
4
 
3
5
  /**
4
6
  * Run a form's post-submit actions once a submission is recorded. Best-effort
@@ -78,19 +80,65 @@ export function localizeDefinition(
78
80
  }
79
81
 
80
82
  /**
81
- * Resolve a single LIVE form by slug from the gateway (`GET /v1/forms`). Only
82
- * published (status: live) forms are visible to the storefront — drafts and
83
- * archived forms return null so a page block renders nothing. Slug is unique
84
- * per tenant, so at most one row matches.
83
+ * The field names a definition declares. Only a named node collects a value —
84
+ * the same rule the app counts its field ceiling by — so content nodes and step
85
+ * markers contribute nothing.
86
+ */
87
+ export function namedFields(definition: Record<string, unknown>[]): Set<string> {
88
+ const names = new Set<string>();
89
+ for (const node of definition) {
90
+ if (node && typeof node === "object" && typeof node.name === "string" && node.name !== "") {
91
+ names.add(node.name);
92
+ }
93
+ }
94
+ return names;
95
+ }
96
+
97
+ /**
98
+ * What of a submission reaches the tenant's inbox.
99
+ *
100
+ * A submission is stored as sent — that is the decision: the app itself stores
101
+ * whatever arrives, and a shop that refused a missing field would be stricter
102
+ * than the record it writes into. What the shop DOES do is drop what the form
103
+ * never asked for, because the only caller that can send an undeclared key is
104
+ * one that did not use the form, and a key nobody authored is a column nobody
105
+ * will ever read.
85
106
  *
86
- * Uses the SDK escape hatch: the cover @revenexx/sdk has no generated Forms
87
- * service yet (the app shipped after this SDK build). `?slug=&status=` are
88
- * exact-column filters mountCrud honors and the gateway passes through.
107
+ * The decoy field survives on purpose: the app needs it to judge the submission
108
+ * and strips it before storing.
89
109
  */
90
- export async function resolveLiveForm(slug: string): Promise<FormRow | null> {
91
- const sdk = useRevenexxSdk();
92
- const res = await sdk.call<{ items?: FormRow[] }>("GET", "/v1/forms", {
93
- query: { slug, status: "live", limit: 1 },
94
- });
95
- return res.items?.[0] ?? null;
110
+ export function sanitizeSubmission(
111
+ definition: Record<string, unknown>[],
112
+ data: Record<string, unknown>,
113
+ honeypotField: string | null,
114
+ ): Record<string, unknown> {
115
+ const allowed = namedFields(definition);
116
+ const out: Record<string, unknown> = {};
117
+ for (const [key, value] of Object.entries(data)) {
118
+ if (allowed.has(key) || (honeypotField !== null && key === honeypotField)) {
119
+ out[key] = value;
120
+ }
121
+ }
122
+ return out;
123
+ }
124
+
125
+ /**
126
+ * Whether a submission filled the decoy in.
127
+ *
128
+ * A human never sees the field and therefore never fills it; a bot fills
129
+ * everything. Whitespace does not count — a field a browser autofilled with a
130
+ * space is not a bot, and treating it as one would silently drop a real enquiry.
131
+ */
132
+ export function decoyFilled(data: Record<string, unknown>, honeypotField: string | null): boolean {
133
+ if (!honeypotField) {
134
+ return false;
135
+ }
136
+ const value = data[honeypotField];
137
+ return value !== undefined && value !== null && String(value).trim() !== "";
138
+ }
139
+
140
+ /** The two forms settings the storefront owes the app, from the one reader. */
141
+ export async function resolveFormSpamPolicy(event: H3Event): Promise<FormSpamPolicy> {
142
+ const { forms } = await getShopSettings(event);
143
+ return { honeypotField: forms.honeypotField, spamHandling: forms.spamHandling };
96
144
  }
@@ -0,0 +1,29 @@
1
+ import type { H3Event } from "h3";
2
+
3
+ import type { IFormsService } from "../interfaces/forms";
4
+ import { ApiFormsService } from "../services/ApiFormsService";
5
+ import { MockFormsService } from "../services/MockFormsService";
6
+
7
+ /**
8
+ * Registry of authored-form sources:
9
+ * - "mock" — the three bundled demo forms
10
+ * - "api" — the forms app through the public revenexx API
11
+ *
12
+ * This domain used to have no key at all: the BFF called the gateway
13
+ * unconditionally, so the one page that renders a form needed live credentials
14
+ * and a tenant that had published under that slug. A storefront with no
15
+ * credentials had a contact page that showed nothing and said nothing.
16
+ */
17
+ const serviceRegistry: Record<string, IFormsService> = {
18
+ mock: new MockFormsService(),
19
+ api: new ApiFormsService(),
20
+ };
21
+
22
+ export function getFormsService(event?: H3Event): IFormsService {
23
+ const key = resolveServiceKey(event, {
24
+ domain: "formsService",
25
+ mockKey: "mock",
26
+ liveKey: "api",
27
+ });
28
+ return serviceRegistry[key] ?? serviceRegistry["mock"]!;
29
+ }
@@ -28,6 +28,8 @@ export interface LiveOrder {
28
28
  status: "pending" | "placed" | "in_fulfillment" | "completed" | "cancelled";
29
29
  payment_status: string;
30
30
  fulfillment_status: string;
31
+ /** A hold set by the merchant — whether it blocks a cancellation is theirs. */
32
+ on_hold?: boolean | null;
31
33
  currency: string;
32
34
  subtotal: number;
33
35
  shipping_total: number;
@@ -173,9 +175,33 @@ export function mapLiveOrderToAccount(order: LiveOrder): AccountOrder {
173
175
  ? { tracking: { carrier: lastTracked.carrier ?? "", trackingNumber: lastTracked.tracking_code ?? "" } }
174
176
  : {}),
175
177
  progress,
178
+ // Whether the buyer may still call it off. The orders app refuses a
179
+ // cancellation once anything has shipped, so the shop asks the same
180
+ // question rather than offering a button that answers with an error.
181
+ cancellable: canBeCancelled(order),
176
182
  };
177
183
  }
178
184
 
185
+ /**
186
+ * Whether this order can still be called off.
187
+ *
188
+ * Shipped is the one that settles it: the app books cancelled quantities and
189
+ * refuses once a position has gone out, because the goods are with a carrier and
190
+ * cancelling them is a return. A held order is left out too — whether a hold
191
+ * blocks cancelling is the merchant's setting, and the shop cannot see which way
192
+ * they set it from here, so it does not offer what the app may refuse.
193
+ */
194
+ export function canBeCancelled(order: LiveOrder): boolean {
195
+ if (order.status === "cancelled" || order.status === "completed") {
196
+ return false;
197
+ }
198
+ if (order.on_hold === true) {
199
+ return false;
200
+ }
201
+ const shipped = (order.shipments ?? []).length > 0;
202
+ return !shipped;
203
+ }
204
+
179
205
  /** Fetch one live order by its display number (the account history id). */
180
206
  export async function getLiveOrderByNumber(number: string): Promise<LiveOrder | null> {
181
207
  const sdk = useRevenexxSdk();
@@ -1,23 +1,43 @@
1
+ import type { H3Event } from "h3";
2
+
1
3
  /**
2
- * Which parts of a customer's master data the storefront may change.
4
+ * Which parts of a customer's master data a buyer may change here.
5
+ *
6
+ * The customers app decides (`self_service_master_data`), because it owns the
7
+ * records. Where an ERP is the source — and for many tenants it is — a buyer who
8
+ * edits their address in the shop creates a second truth the next import
9
+ * overwrites: silently, and after they have already trusted it.
3
10
  *
4
- * Read from `account.<area>.editable` in the app config (default: editable).
5
- * A merchant whose ERP owns the data turns it off; every BFF route that
6
- * writes that data calls {@link assertMasterDataEditable} first, so the
7
- * guard does not depend on the UI having hidden the last button.
11
+ * The shop used to answer this with four flags of its own. That was a guess in
12
+ * both directions: it hid a form while the platform went on accepting the write
13
+ * from anything else that asked, and it could be set to allow what the platform
14
+ * refused. Now the platform refuses it (403) and this is the matching UX —
15
+ * asked before the write so a buyer is told rather than shown a wall.
16
+ *
17
+ * `team` follows the company and not the addresses: a merchant who keeps the
18
+ * company record keeps its people too, which is exactly the ERP-driven tenant
19
+ * this setting exists for. Adding a delivery point is the one thing such a
20
+ * buyer still knows first, which is why `addresses_only` exists at all.
8
21
  */
9
22
  export type MasterDataArea = "addresses" | "profile" | "organization" | "team";
10
23
 
11
- export function isMasterDataEditable(area: MasterDataArea): boolean {
12
- const account = (useAppConfig() as { account?: Partial<Record<MasterDataArea, { editable?: boolean }>> }).account;
13
- return account?.[area]?.editable !== false;
24
+ export async function isMasterDataEditable(event: H3Event | undefined, area: MasterDataArea): Promise<boolean> {
25
+ const { account } = await getShopSettings(event);
26
+ switch (account.selfService) {
27
+ case "none":
28
+ return false;
29
+ case "addresses_only":
30
+ return area === "addresses";
31
+ default:
32
+ return true;
33
+ }
14
34
  }
15
35
 
16
- export function assertMasterDataEditable(area: MasterDataArea): void {
17
- if (!isMasterDataEditable(area)) {
36
+ export async function assertMasterDataEditable(event: H3Event, area: MasterDataArea): Promise<void> {
37
+ if (!await isMasterDataEditable(event, area)) {
18
38
  throw createError({
19
39
  statusCode: 403,
20
- message: `This storefront does not change ${area}: they are maintained by the merchant.`,
40
+ message: `This data is maintained by the merchant and cannot be changed here: ${area}.`,
21
41
  });
22
42
  }
23
43
  }
@@ -0,0 +1,73 @@
1
+ import type { H3Event } from "h3";
2
+ import type { AuthRole, StoredSession } from "../../app/interfaces/auth";
3
+ import type { AuthLoginResult } from "../interfaces/auth";
4
+
5
+ /**
6
+ * Signing in without a password: a mailed link, or a mailed code.
7
+ *
8
+ * Both are two calls — ask for the secret, then hand it back — and both end in
9
+ * the same session as a password sign-in, which is why the cookie is written
10
+ * here rather than twice. The customers app serves both and shapes which are
11
+ * offered (`login_magic_link`, `login_email_otp`); the shop only ever offers what
12
+ * the merchant switched on, because the app refuses the rest.
13
+ *
14
+ * One property of the mailed link is worth stating: an address nobody holds gets
15
+ * an account rather than an error, so it is a registration path as much as a
16
+ * sign-in one. The shop must not therefore tell a visitor whether an address is
17
+ * known — that would turn the form into a way of asking.
18
+ */
19
+
20
+ interface ApiSession {
21
+ $id: string;
22
+ expire: string;
23
+ userId: string;
24
+ }
25
+
26
+ interface ApiContact {
27
+ id: string;
28
+ email: string;
29
+ first_name?: string | null;
30
+ last_name?: string | null;
31
+ role?: string | null;
32
+ organization_id?: string | null;
33
+ active?: boolean | null;
34
+ }
35
+
36
+ const KNOWN_ROLES = new Set<AuthRole>(["buyer", "approver", "admin", "requester"]);
37
+
38
+ const roleOf = (role?: string | null): AuthRole | undefined =>
39
+ role && KNOWN_ROLES.has(role as AuthRole) ? (role as AuthRole) : undefined;
40
+
41
+ const nameOf = (contact: ApiContact | null, fallback: string): string =>
42
+ [contact?.first_name, contact?.last_name].filter(Boolean).join(" ") || contact?.email || fallback;
43
+
44
+ /** Turn a confirmed secret into the same session a password sign-in produces. */
45
+ export function completeSignIn(
46
+ event: H3Event,
47
+ session: ApiSession,
48
+ contact: ApiContact | null,
49
+ fallbackEmail: string,
50
+ ): AuthLoginResult {
51
+ const stored: StoredSession = {
52
+ id: session.$id,
53
+ expire: session.expire,
54
+ userId: session.userId,
55
+ ...(contact?.id ? { contactId: contact.id } : {}),
56
+ ...(contact?.organization_id ? { organizationId: contact.organization_id } : {}),
57
+ };
58
+ setCookie(event, SESSION_COOKIE_NAME, JSON.stringify(stored), sessionCookieOptions(session.expire));
59
+
60
+ return {
61
+ user: {
62
+ $id: session.userId,
63
+ name: nameOf(contact, fallbackEmail),
64
+ email: contact?.email ?? fallbackEmail,
65
+ role: roleOf(contact?.role),
66
+ ...(typeof contact?.active === "boolean" ? { active: contact.active } : {}),
67
+ },
68
+ session: { id: session.$id, expire: session.expire },
69
+ ...(contact?.id ? { contactId: contact.id } : {}),
70
+ };
71
+ }
72
+
73
+ export type PasswordlessConfirm = { session: ApiSession; contact: ApiContact | null };
@@ -0,0 +1,153 @@
1
+ import type { H3Event } from "h3";
2
+ import type { PendingApproval } from "../../app/interfaces/account/approvals";
3
+
4
+ /**
5
+ * The approvals waiting on one person.
6
+ *
7
+ * Asked two ways because the procurement app records an approver two ways: by the
8
+ * contact themselves, and by the role they hold. A queue that asked only the first
9
+ * would be empty for every organisation that approves by role, which is most of
10
+ * them.
11
+ *
12
+ * Each layer is enriched with the request behind it, because an approver deciding
13
+ * on "layer 2 of 3" and nothing else is being asked to sign for a number they
14
+ * cannot see.
15
+ */
16
+ interface LivePendingApproval {
17
+ id: string;
18
+ purchase_request_id?: string | null;
19
+ cost_center_code?: string | null;
20
+ sequence?: number | null;
21
+ status?: string | null;
22
+ created_at?: string | null;
23
+ }
24
+
25
+ interface LivePurchaseRequest {
26
+ id: string;
27
+ number?: string | null;
28
+ total?: number | string | null;
29
+ currency?: string | null;
30
+ requested_by?: string | null;
31
+ contact_id?: string | null;
32
+ }
33
+
34
+ export async function listPendingApprovals(
35
+ event: H3Event,
36
+ actor: { contactId?: string; role?: string },
37
+ ): Promise<PendingApproval[]> {
38
+ const sdk = useRevenexxSdk();
39
+
40
+ const queries: Array<Record<string, string | number>> = [];
41
+ if (actor.contactId) {
42
+ queries.push({ approver_contact_id: actor.contactId, status: "pending", limit: 100 });
43
+ }
44
+ if (actor.role) {
45
+ queries.push({ approver_role: actor.role, status: "pending", limit: 100 });
46
+ }
47
+ if (queries.length === 0) {
48
+ return [];
49
+ }
50
+
51
+ const rows = new Map<string, LivePendingApproval>();
52
+ for (const query of queries) {
53
+ try {
54
+ const answer = await sdk.call<{ items?: LivePendingApproval[]; pending_approvals?: LivePendingApproval[] }>(
55
+ "GET",
56
+ "/v1/procurement/pending-approvals",
57
+ { query: { ...query, order: "created_at.asc" } },
58
+ );
59
+ for (const row of answer.items ?? answer.pending_approvals ?? []) {
60
+ // A layer can match both ways; it is one thing waiting, not two.
61
+ rows.set(row.id, row);
62
+ }
63
+ }
64
+ catch (err) {
65
+ getLogService().error("Pending approvals unavailable", apiErrorContext(err));
66
+ }
67
+ }
68
+
69
+ // The request behind each layer, read once per request rather than per layer.
70
+ const requestIds = [...new Set([...rows.values()].map(r => r.purchase_request_id).filter(Boolean))] as string[];
71
+ const requests = new Map<string, LivePurchaseRequest>();
72
+ for (const id of requestIds) {
73
+ try {
74
+ const request = await sdk.call<LivePurchaseRequest>("GET", `/v1/procurement/purchase-requests/${id}`);
75
+ requests.set(id, request);
76
+ }
77
+ catch (err) {
78
+ // A layer whose request cannot be read is still shown: the approver needs
79
+ // to know it is waiting, even where the figure is missing.
80
+ getLogService().error(`Purchase request ${id} unavailable`, apiErrorContext(err));
81
+ }
82
+ }
83
+
84
+ return [...rows.values()].map((row) => {
85
+ const request = row.purchase_request_id ? requests.get(row.purchase_request_id) : undefined;
86
+ const total = request?.total == null ? null : Number(request.total);
87
+ return {
88
+ id: row.id,
89
+ requestId: row.purchase_request_id ?? "",
90
+ requestNumber: request?.number ?? null,
91
+ requestedBy: request?.requested_by ?? request?.contact_id ?? null,
92
+ // Zero is not a figure here: the app leaves the total unset on the
93
+ // records this tenant keeps (RX-795), and a confident 0,00 € beside a
94
+ // signature is worse than an honest blank.
95
+ total: total && total > 0 ? total : null,
96
+ currency: request?.currency ?? null,
97
+ costCentreCode: row.cost_center_code ?? null,
98
+ layer: Number(row.sequence ?? 1),
99
+ at: row.created_at ?? "",
100
+ };
101
+ });
102
+ }
103
+
104
+ /**
105
+ * Pass one approver's decision to the app.
106
+ *
107
+ * Both directions in one place because they differ in exactly one word and in
108
+ * nothing else that matters: the same guard, the same refusals, the same reason.
109
+ * A decline ends the request; an approval unlocks the next layer.
110
+ */
111
+ export async function decidePendingApproval(
112
+ event: H3Event,
113
+ decision: "approve" | "decline",
114
+ ): Promise<{ ok: true }> {
115
+ const id = getRouterParam(event, "id") ?? "";
116
+ const body = await readBody<{ reason?: string }>(event).catch(() => ({} as { reason?: string }));
117
+
118
+ const user = await getAuthService(event).me(event);
119
+ if (!user) {
120
+ throw createError({ statusCode: 401, message: "Unauthorized" });
121
+ }
122
+ if (!isProcurementLive(event)) {
123
+ throw createError({ statusCode: 501, message: "This storefront does not decide approvals on demo data" });
124
+ }
125
+
126
+ // Only what is actually waiting on this person. The app knows who may decide,
127
+ // and asking it first means a link somebody was sent cannot be used by
128
+ // somebody else — the alternative is trusting the id in the address.
129
+ const mine = await listPendingApprovals(event, {
130
+ ...(user.contactId ? { contactId: user.contactId } : {}),
131
+ ...(user.role ? { role: user.role } : {}),
132
+ });
133
+ if (!mine.some(approval => approval.id === id)) {
134
+ throw createError({ statusCode: 404, message: "No such approval is waiting on you" });
135
+ }
136
+
137
+ const reason = body?.reason?.trim();
138
+ try {
139
+ await useRevenexxSdk().call("POST", `/v1/procurement/pending-approvals/${id}/${decision}`, {
140
+ body: reason ? { reason } : {},
141
+ });
142
+ return { ok: true };
143
+ }
144
+ catch (err) {
145
+ // 409 is the layer having been decided since the page was drawn — by a
146
+ // deputy, or by this approver in another tab. The buyer's to read.
147
+ if (err instanceof RevenexxException && [400, 409, 422].includes(err.code)) {
148
+ throw createError({ statusCode: 422, message: err.message });
149
+ }
150
+ getLogService().error(`Deciding approval ${id} failed`, apiErrorContext(err));
151
+ throw createError({ statusCode: 502, message: "Procurement service unavailable" });
152
+ }
153
+ }
@@ -1,5 +1,6 @@
1
1
  import { PromotionsRedemptionsReleaseReason } from "@revenexx/sdk";
2
2
  import type { H3Event } from "h3";
3
+ import type { AvailableOffer } from "../../app/interfaces/offers";
3
4
 
4
5
  /**
5
6
  * The promotions domain has no service class — the cart endpoint branches on
@@ -275,3 +276,92 @@ export async function releaseRedemption(
275
276
  getLogService().error("Promotion release failed — the hold will expire", apiErrorContext(err));
276
277
  }
277
278
  }
279
+
280
+ /* ------------------------------------------------------------------ */
281
+ /* What a buyer could still get */
282
+ /* ------------------------------------------------------------------ */
283
+
284
+ /** The promotions app's own shape for an offer this buyer has not earned yet. */
285
+ export interface LiveAvailablePromotion {
286
+ promotion_id: string;
287
+ code?: string | null;
288
+ name?: string | null;
289
+ needs_code?: boolean;
290
+ already_met?: boolean;
291
+ distance?: { subject?: string; missing?: number; required?: number } | null;
292
+ }
293
+
294
+ /**
295
+ * The offers this buyer could still reach, with how far away each one is.
296
+ *
297
+ * Read-only and cheap: it writes nothing and holds nothing, so a storefront may
298
+ * ask it on every cart change the way it asks for the cart's own total.
299
+ *
300
+ * Fails soft to an empty list. An offer nobody can see costs a shop a larger
301
+ * order; an error page costs it the order.
302
+ */
303
+ export async function liveAvailableOffers(
304
+ event: H3Event,
305
+ input: {
306
+ currency: string;
307
+ subtotal: number;
308
+ itemCount?: number;
309
+ contactId?: string;
310
+ organizationId?: string;
311
+ },
312
+ ): Promise<{ offers: AvailableOffer[]; total: number }> {
313
+ try {
314
+ const answer = await useRevenexxSdk().call<{
315
+ promotions?: LiveAvailablePromotion[];
316
+ total?: number;
317
+ }>("POST", "/v1/promotions/available", {
318
+ body: {
319
+ currency: input.currency,
320
+ subtotal: input.subtotal,
321
+ ...(typeof input.itemCount === "number" ? { item_count: input.itemCount } : {}),
322
+ ...(input.contactId ? { contact_id: input.contactId } : {}),
323
+ ...(input.organizationId ? { organization_id: input.organizationId } : {}),
324
+ },
325
+ });
326
+ const offers = (answer.promotions ?? [])
327
+ .map(mapOffer)
328
+ .filter((offer): offer is AvailableOffer => offer !== null);
329
+ return { offers, total: Number(answer.total ?? offers.length) };
330
+ }
331
+ catch (err) {
332
+ getLogService().error("Available offers unavailable", apiErrorContext(err));
333
+ return { offers: [], total: 0 };
334
+ }
335
+ }
336
+
337
+ /**
338
+ * One offer in the shop's words.
339
+ *
340
+ * An offer with no name is dropped rather than shown as a blank row: the name is
341
+ * the whole of what a buyer reads, and the merchant is the one who writes it.
342
+ */
343
+ export function mapOffer(promotion: LiveAvailablePromotion): AvailableOffer | null {
344
+ const name = promotion.name?.trim();
345
+ if (!promotion.promotion_id || !name) {
346
+ return null;
347
+ }
348
+ const reached = promotion.already_met === true;
349
+ const distance = promotion.distance;
350
+ // Only a distance the buyer can act on. The app leaves it null where the
351
+ // unmet condition is not a number, and "somewhere between here and there"
352
+ // is not a thing to put in front of somebody.
353
+ const missing = !reached && distance && typeof distance.missing === "number" && distance.missing > 0
354
+ ? {
355
+ kind: distance.subject === "item_count" ? "quantity" as const : "value" as const,
356
+ amount: distance.missing,
357
+ required: Number(distance.required ?? 0),
358
+ }
359
+ : undefined;
360
+ return {
361
+ id: promotion.promotion_id,
362
+ name,
363
+ reached,
364
+ needsCode: promotion.needs_code === true,
365
+ ...(missing ? { missing } : {}),
366
+ };
367
+ }
@@ -337,6 +337,21 @@ export async function liveQuoteDecline(id: string, reason?: string): Promise<voi
337
337
  await useRevenexxSdk().quotesAcceptance.quotesAcceptanceDecline({ id, ...(reason ? { reason } : {}) });
338
338
  }
339
339
 
340
+ /**
341
+ * Say no to SOME positions and leave the rest open.
342
+ *
343
+ * The same call that accepts positions carries a decision per line, so refusing a
344
+ * few is not a second mechanism — it is the other value of the same field. The
345
+ * whole-quote refusal above stays for what it is: a no to the offer as a whole,
346
+ * which also closes everything still open.
347
+ */
348
+ export async function liveQuoteDeclineLines(id: string, lineIds: string[]): Promise<void> {
349
+ await useRevenexxSdk().quotesAcceptance.quotesAcceptanceAccept({
350
+ id,
351
+ items: lineIds.map(lineId => ({ id: lineId, decision: AcceptLineDecision.Declined })),
352
+ });
353
+ }
354
+
340
355
  /**
341
356
  * The quote this buyer asked about, or a 404 — another organisation's quote
342
357
  * does not exist for them, and saying "not yours" would confirm it does.