@revenexx/cover 0.4.0 → 0.6.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@revenexx/cover",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Cover \u2014 revenexx design system for Nuxt. Distributed as a Nuxt layer: generic UI components, theming tokens and stores shared by the demo shop, custom storefronts and the Blokkli theme.",
5
5
  "type": "module",
6
6
  "main": "./nuxt.config.ts",
@@ -6,7 +6,7 @@ export default defineEventHandler(async (event) => {
6
6
  }
7
7
 
8
8
  const id = getRouterParam(event, "id") ?? "";
9
- const visible = await getRequisitionService().list(user.$id);
9
+ const visible = await getRequisitionService(event).list(user.$id);
10
10
  const requisition = visible.find(r => r.id === id);
11
11
  if (!requisition) {
12
12
  throw createError({ statusCode: 404, message: "Requisition not found" });
@@ -11,7 +11,7 @@ export default defineEventHandler(async (event) => {
11
11
  const { status } = getQuery(event);
12
12
 
13
13
  try {
14
- const service = getRequisitionService();
14
+ const service = getRequisitionService(event);
15
15
  return status === "open"
16
16
  ? await service.listOpen(user.$id)
17
17
  : await service.list(user.$id);
@@ -171,6 +171,12 @@ export default defineEventHandler(async (event) => {
171
171
  l => l.status === "exceeded" && l.approval.required,
172
172
  );
173
173
 
174
+ // An organisation that approves its spending, in a storefront whose
175
+ // procurement app is live: then the app decides what this cart becomes,
176
+ // and the demo limits above decide nothing (the context carries none —
177
+ // see the B2B context service).
178
+ const throughProcurement = context.settings.approvals.enabled && isProcurementLive(event);
179
+
174
180
  // Live shipping: the chosen method must be a real rate for this
175
181
  // buyer context; its price replaces the demo calculation's shipping
176
182
  // line in the order totals and the amount the payment is created over.
@@ -337,7 +343,7 @@ export default defineEventHandler(async (event) => {
337
343
  discounts = [];
338
344
  }
339
345
 
340
- const placed = await useRevenexxSdk().orders.ordersPlace({
346
+ const submission = {
341
347
  ...(contactId ? { contactId } : {}),
342
348
  ...(organizationId ? { organizationId } : {}),
343
349
  ...(cartId ? { cartId } : {}),
@@ -375,7 +381,37 @@ export default defineEventHandler(async (event) => {
375
381
  ...(body.partialDelivery !== undefined ? { partial_delivery: body.partialDelivery } : {}),
376
382
  ...(body.requestedDate ? { requested_date: body.requestedDate } : {}),
377
383
  },
378
- }) as unknown as { id: string; number: string; grand_total?: number };
384
+ };
385
+
386
+ // Where spending is approved before it happens, the procurement
387
+ // app is what a checkout hands the cart to: it decides between
388
+ // an order and a request waiting for a decision. Everywhere else
389
+ // the orders app places the order directly, as it always has.
390
+ const outcome = throughProcurement
391
+ ? await submitThroughProcurement(submission as never)
392
+ : {
393
+ kind: "order" as const,
394
+ order: await useRevenexxSdk().orders.ordersPlace(submission as never) as unknown as SubmittedOrder,
395
+ };
396
+
397
+ if (outcome.kind === "request") {
398
+ // Nothing was bought, so nothing is charged and no promotion
399
+ // is spent: the hold goes back and waits for the order the
400
+ // approval may yet produce.
401
+ if (reserved === "held" && cartId) {
402
+ await releaseRedemption(event, { cartId, reason: PromotionsRedemptionsReleaseReason.CartReleased });
403
+ }
404
+ return {
405
+ orderId: outcome.request.number,
406
+ status: "approval-pending",
407
+ createdAt: new Date().toISOString(),
408
+ payment,
409
+ approvalRequired: true,
410
+ approvers: [],
411
+ };
412
+ }
413
+
414
+ const placed = outcome.order;
379
415
  orderId = placed.number;
380
416
  liveOrderUuid = placed.id;
381
417
  liveOrderTotal = typeof placed.grand_total === "number" ? placed.grand_total : null;
@@ -0,0 +1,217 @@
1
+ import type { Requisition, RequisitionItemSnapshot, RequisitionStatus, WorkflowHistoryEntry } from "../../app/interfaces/b2b";
2
+ import type { IRequisitionService } from "../interfaces/b2bContext";
3
+
4
+ /** A purchase request as the procurement app answers it. */
5
+ interface ApiPurchaseRequest {
6
+ id: string;
7
+ number: string;
8
+ status: string;
9
+ total?: number | string | null;
10
+ currency?: string | null;
11
+ contact_id?: string | null;
12
+ organization_id?: string | null;
13
+ created_at: string;
14
+ order_id?: string | null;
15
+ cart_id?: string | null;
16
+ requested_by_name?: string | null;
17
+ }
18
+
19
+ interface ApiPurchaseRequestItem {
20
+ id: string;
21
+ purchase_request_id: string;
22
+ position?: number | null;
23
+ sku?: string | null;
24
+ name?: string | null;
25
+ quantity?: number | string | null;
26
+ unit?: string | null;
27
+ unit_price?: number | string | null;
28
+ tax_rate?: number | string | null;
29
+ cost_center_id?: string | null;
30
+ }
31
+
32
+ interface ApiPurchaseRequestEvent {
33
+ id: string;
34
+ purchase_request_id: string;
35
+ name: string;
36
+ created_at: string;
37
+ payload?: Record<string, unknown> | null;
38
+ }
39
+
40
+ const PAGE_LIMIT = 100;
41
+ const ITEM_LIMIT = 200;
42
+
43
+ const num = (value: unknown): number => {
44
+ const n = Number(value ?? 0);
45
+ return Number.isFinite(n) ? n : 0;
46
+ };
47
+
48
+ /**
49
+ * What the procurement app calls a purchase request is what the account area
50
+ * calls a requisition: a cart somebody asked for rather than ordered. The two
51
+ * words name one thing, and this is the only place they meet.
52
+ *
53
+ * Statuses map onto the account's own set; anything the app grows later that
54
+ * this does not know lands on "pending", because a request whose state cannot
55
+ * be read is still open business and must not disappear from a buyer's list.
56
+ */
57
+ const STATUS: Record<string, RequisitionStatus> = {
58
+ // The account knows three states where the app knows five. An approved
59
+ // request is still open business — it has not become an order yet — and a
60
+ // declined one is as closed as a cancelled one from the buyer's side.
61
+ pending: "open",
62
+ approved: "open",
63
+ declined: "cancelled",
64
+ rejected: "cancelled",
65
+ cancelled: "cancelled",
66
+ ordered: "ordered",
67
+ };
68
+
69
+ /**
70
+ * What the app announces, in the account's own words. A name this does not
71
+ * carry is not shown: the trail records decisions, and money moving is not one.
72
+ */
73
+ const TRAIL: Record<string, WorkflowHistoryEntry["action"]> = {
74
+ "purchase_request.requested": "submitted",
75
+ "purchase_request.approved": "approved",
76
+ "purchase_request.cancelled": "cancelled",
77
+ "purchase_request.ordered": "ordered",
78
+ };
79
+
80
+ export class ApiRequisitionService implements IRequisitionService {
81
+ async list(userId: string): Promise<Requisition[]> {
82
+ const rows = await this.fetchRequests();
83
+ return Promise.all(rows.map(row => this.toRequisition(row, userId)));
84
+ }
85
+
86
+ /**
87
+ * Whose requisitions these are.
88
+ *
89
+ * The app's list declares no filter for the buyer, so the narrowing happens
90
+ * here — and it is a refusal rather than a convenience: a request belongs to
91
+ * the organisation that made it, and a list that answered every request the
92
+ * tenant holds would show one company what another asked for, line by line
93
+ * and priced. A request naming no organisation is shown to nobody, because
94
+ * "belongs to nobody" cannot be read as "belongs to whoever is asking".
95
+ */
96
+ private ownedBy(rows: ApiPurchaseRequest[], organizationId: string | null): ApiPurchaseRequest[] {
97
+ if (!organizationId) {
98
+ return [];
99
+ }
100
+ return rows.filter(row => row.organization_id === organizationId);
101
+ }
102
+
103
+ /**
104
+ * The ones a buyer can still act on. "Open" is the account's word for a
105
+ * request that has neither become an order nor been turned down.
106
+ */
107
+ async listOpen(userId: string): Promise<Requisition[]> {
108
+ const all = await this.list(userId);
109
+ return all.filter(r => r.status === "open");
110
+ }
111
+
112
+ private async fetchRequests(): Promise<ApiPurchaseRequest[]> {
113
+ const refs = sessionOrderRefs(useEvent());
114
+ try {
115
+ // The escape hatch: `procurement.purchase_requests.list` declares
116
+ // limit/offset/order and nothing about whose requests these are, so
117
+ // the organisation is asked for as a column filter and the answer is
118
+ // narrowed again below — belt and braces, because the filter is not
119
+ // in the contract and could stop being honoured without anything
120
+ // going red.
121
+ const { items } = await useRevenexxSdk().call<{ items: ApiPurchaseRequest[] }>(
122
+ "GET",
123
+ "/v1/procurement/purchase-requests",
124
+ {
125
+ query: {
126
+ limit: PAGE_LIMIT,
127
+ order: "created_at.desc",
128
+ ...(refs.organization_id ? { organization_id: refs.organization_id } : {}),
129
+ },
130
+ },
131
+ );
132
+ return this.ownedBy(items ?? [], refs.organization_id ?? null);
133
+ }
134
+ catch (err) {
135
+ getLogService().error("API request failed: procurement/purchase-requests", apiErrorContext(err));
136
+ return [];
137
+ }
138
+ }
139
+
140
+ private async toRequisition(row: ApiPurchaseRequest, userId: string): Promise<Requisition> {
141
+ const [items, history] = await Promise.all([this.fetchItems(row.id), this.fetchHistory(row.id)]);
142
+
143
+ return {
144
+ id: row.id,
145
+ // The app owns approval rules rather than workflows, so a request
146
+ // carries the number it is known by instead of a workflow's name.
147
+ workflowId: "",
148
+ workflowName: row.number,
149
+ requestedBy: { id: row.contact_id ?? userId, name: row.requested_by_name ?? "" },
150
+ requestedAt: row.created_at,
151
+ status: STATUS[row.status] ?? "open",
152
+ totalValue: num(row.total),
153
+ items,
154
+ history,
155
+ };
156
+ }
157
+
158
+ private async fetchItems(requestId: string): Promise<RequisitionItemSnapshot[]> {
159
+ try {
160
+ const { items } = await useRevenexxSdk().call<{ items: ApiPurchaseRequestItem[] }>(
161
+ "GET",
162
+ "/v1/procurement/purchase-request-items",
163
+ { query: { purchase_request_id: requestId, limit: ITEM_LIMIT, order: "position.asc" } },
164
+ );
165
+ return (items ?? []).map(item => ({
166
+ id: item.id,
167
+ sku: item.sku ?? "",
168
+ name: item.name ?? "",
169
+ quantity: num(item.quantity),
170
+ unit: item.unit ?? undefined,
171
+ price: num(item.unit_price),
172
+ taxRate: num(item.tax_rate),
173
+ costCenterId: item.cost_center_id ?? undefined,
174
+ }));
175
+ }
176
+ catch (err) {
177
+ getLogService().error("API request failed: procurement/purchase-request-items", apiErrorContext(err));
178
+ return [];
179
+ }
180
+ }
181
+
182
+ /**
183
+ * The trail, oldest first — the account renders it as the story of the
184
+ * request, and a story told backwards reads as a list of unrelated events.
185
+ *
186
+ * The app announces more than the trail shows: a budget confirmed or
187
+ * withdrawn is money moving, not a step somebody took, and the account's
188
+ * trail is a record of decisions. Those are left out rather than bent into
189
+ * an action nobody performed.
190
+ */
191
+ private async fetchHistory(requestId: string): Promise<WorkflowHistoryEntry[]> {
192
+ try {
193
+ const { items } = await useRevenexxSdk().call<{ items: ApiPurchaseRequestEvent[] }>(
194
+ "GET",
195
+ "/v1/procurement/purchase-request-events",
196
+ { query: { purchase_request_id: requestId, limit: ITEM_LIMIT, order: "created_at.asc" } },
197
+ );
198
+ return (items ?? []).flatMap((event, index) => {
199
+ const action = TRAIL[event.name];
200
+ if (!action) {
201
+ return [];
202
+ }
203
+ return [{
204
+ id: event.id,
205
+ stepSequence: index + 1,
206
+ action,
207
+ actorName: String(event.payload?.["actor_name"] ?? ""),
208
+ actionDate: event.created_at,
209
+ }];
210
+ });
211
+ }
212
+ catch (err) {
213
+ getLogService().error("API request failed: procurement/purchase-request-events", apiErrorContext(err));
214
+ return [];
215
+ }
216
+ }
217
+ }
@@ -88,7 +88,15 @@ export class B2BContextService implements IB2BContextService {
88
88
  // Approval limits only apply when actually ordering — requesters never
89
89
  // order directly, so their context carries none (limits are not
90
90
  // checked for requisitions).
91
- const limitsApply = settings.approvals.enabled && role !== "requester";
91
+ //
92
+ // And where the procurement app is live it is the one that decides,
93
+ // at submission, against rules the merchant configured. The demo
94
+ // limits then carry none of that and must not pre-judge a cart in the
95
+ // shop: a buyer warned by one set of rules and stopped by another is
96
+ // worse off than one who is only ever told the truth once.
97
+ const limitsApply = settings.approvals.enabled
98
+ && role !== "requester"
99
+ && !isProcurementLive(this.event);
92
100
 
93
101
  const costCenterLimits = limitsApply
94
102
  ? costCenters.flatMap(cc => (cc.limit ? [cc.limit] : []))
@@ -4,6 +4,7 @@ import type { OrganizationSettings } from "../../app/interfaces/b2b";
4
4
 
5
5
  import type { IB2BContextService, IRequisitionService } from "../interfaces/b2bContext";
6
6
  import type { ICartCalculationService } from "../interfaces/cartCalculation";
7
+ import { ApiRequisitionService } from "../services/ApiRequisitionService";
7
8
  import { B2BContextService, MockRequisitionService } from "../services/MockB2BContextService";
8
9
  import { MockCartCalculationService } from "../services/MockCartCalculationService";
9
10
 
@@ -54,10 +55,27 @@ export function getB2BContextService(event?: H3Event): IB2BContextService {
54
55
  return new B2BContextService(resolveOrgSettingsOverride(event), event);
55
56
  }
56
57
 
57
- const requisitionService: IRequisitionService = new MockRequisitionService();
58
+ /**
59
+ * Registry of requisition sources:
60
+ * - "mock" — the bundled demo requests
61
+ * - "api" — purchase requests from the procurement app
62
+ *
63
+ * What the procurement app calls a purchase request is what the account area
64
+ * calls a requisition. The two words name one thing; the live service is the
65
+ * only place they meet.
66
+ */
67
+ const requisitionRegistry: Record<string, IRequisitionService> = {
68
+ mock: new MockRequisitionService(),
69
+ api: new ApiRequisitionService(),
70
+ };
58
71
 
59
- export function getRequisitionService(): IRequisitionService {
60
- return requisitionService;
72
+ export function getRequisitionService(event?: H3Event): IRequisitionService {
73
+ const key = resolveServiceKey(event, {
74
+ domain: "procurementService",
75
+ mockKey: "mock",
76
+ liveKey: "api",
77
+ });
78
+ return requisitionRegistry[key] ?? requisitionRegistry["mock"]!;
61
79
  }
62
80
 
63
81
  const cartCalculationService: ICartCalculationService = new MockCartCalculationService();
@@ -0,0 +1,98 @@
1
+ import type { H3Event } from "h3";
2
+
3
+ /**
4
+ * Submitting a cart where spending is approved before it happens.
5
+ *
6
+ * For such an organisation the procurement app — not the orders app — is what
7
+ * a checkout hands the cart to. It decides between the two things a submitted
8
+ * cart can become: an order, when nothing it checks objects, or a request
9
+ * waiting for somebody to say yes. The shop cannot make that call itself; it
10
+ * does not hold the rules, and guessing would mean charging for a purchase
11
+ * nobody approved.
12
+ *
13
+ * So the shop asks once and reads the answer. An order comes back the way the
14
+ * orders app would have answered it, which is what lets the rest of the
15
+ * checkout — the payment, the confirmation — carry on unchanged.
16
+ */
17
+ export function isProcurementLive(event?: H3Event): boolean {
18
+ return resolveServiceKey(event, {
19
+ domain: "procurementService",
20
+ mockKey: "mock",
21
+ liveKey: "api",
22
+ }) === "api";
23
+ }
24
+
25
+ /** An order, exactly as the orders app answers one. */
26
+ export interface SubmittedOrder {
27
+ id: string;
28
+ number: string;
29
+ grand_total?: number;
30
+ }
31
+
32
+ /** A request waiting for a decision. */
33
+ export interface SubmittedRequest {
34
+ id: string;
35
+ number: string;
36
+ status?: string;
37
+ }
38
+
39
+ export type SubmitOutcome =
40
+ | { readonly kind: "order"; readonly order: SubmittedOrder }
41
+ | { readonly kind: "request"; readonly request: SubmittedRequest };
42
+
43
+ /** What the orders app is asked for, in the words procurement asks for it. */
44
+ interface OrderLikePayload {
45
+ contactId?: string;
46
+ organizationId?: string;
47
+ cartId?: string;
48
+ currency: string;
49
+ customerOrderNumber?: string;
50
+ buyer?: unknown;
51
+ billingAddress?: unknown;
52
+ shippingAddress?: unknown;
53
+ payment?: { method: string };
54
+ shipping?: { method: string; price: number; tax_rate: number };
55
+ items: Array<Record<string, unknown>>;
56
+ userData?: Record<string, unknown>;
57
+ }
58
+
59
+ /**
60
+ * Hand the cart to procurement and say which of the two it became.
61
+ *
62
+ * The line shape is the app's own: what the orders app takes as an item, this
63
+ * one takes with the same field names, so nothing is translated twice.
64
+ */
65
+ export async function submitThroughProcurement(payload: OrderLikePayload): Promise<SubmitOutcome> {
66
+ const answer = await useRevenexxSdk().call<{
67
+ outcome?: string;
68
+ order?: SubmittedOrder;
69
+ purchase_request?: SubmittedRequest;
70
+ }>("POST", "/v1/procurement/submit", {
71
+ body: {
72
+ ...(payload.cartId ? { cart_id: payload.cartId } : {}),
73
+ ...(payload.contactId ? { contact_id: payload.contactId } : {}),
74
+ ...(payload.organizationId ? { organization_id: payload.organizationId } : {}),
75
+ currency: payload.currency,
76
+ ...(payload.customerOrderNumber ? { customer_order_number: payload.customerOrderNumber } : {}),
77
+ ...(payload.buyer ? { buyer: payload.buyer } : {}),
78
+ ...(payload.billingAddress ? { billing_address: payload.billingAddress } : {}),
79
+ ...(payload.shippingAddress ? { shipping_address: payload.shippingAddress } : {}),
80
+ ...(payload.payment ? { payment: payload.payment } : {}),
81
+ ...(payload.shipping ? { shipping: payload.shipping } : {}),
82
+ ...(payload.userData ? { user_data: payload.userData } : {}),
83
+ items: payload.items,
84
+ },
85
+ });
86
+
87
+ if (answer.outcome === "approval" && answer.purchase_request) {
88
+ return { kind: "request", request: answer.purchase_request };
89
+ }
90
+ if (answer.order) {
91
+ return { kind: "order", order: answer.order };
92
+ }
93
+
94
+ // Neither of the two: the app answered something this shop cannot act on,
95
+ // and acting on a guess would mean either charging for nothing or losing a
96
+ // purchase the buyer believes they made.
97
+ throw new Error(`procurement/submit answered no order and no request (outcome: ${answer.outcome ?? "none"})`);
98
+ }