@revenexx/cover 0.3.2 → 0.5.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.
@@ -6,7 +6,13 @@
6
6
  *
7
7
  * Composed from per-section widget components so the same sections can be
8
8
  * rearranged as individual blocks in the page editor (see cover-theme).
9
+ *
10
+ * The two governance widgets follow the organisation's settings. They used to
11
+ * render for every shop, each with a "view all" link into a route only a shop
12
+ * with governance has — so a storefront without it put two dead links on the
13
+ * first page a buyer sees after signing in (RX-791's sibling).
9
14
  */
15
+ const { settings } = useB2BContext();
10
16
  </script>
11
17
 
12
18
  <template>
@@ -19,10 +25,10 @@
19
25
  <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 items-start">
20
26
  <div class="lg:col-span-2 space-y-6">
21
27
  <AccountDashboardRecentOrders />
22
- <AccountDashboardRequisitions />
28
+ <AccountDashboardRequisitions v-if="settings?.approvals?.enabled" />
23
29
  </div>
24
30
  <div class="space-y-6">
25
- <AccountDashboardBudgets />
31
+ <AccountDashboardBudgets v-if="settings?.costCenters?.enabled" />
26
32
  <AccountDashboardQuickActions />
27
33
  </div>
28
34
  </div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@revenexx/cover",
3
- "version": "0.3.2",
3
+ "version": "0.5.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);
@@ -0,0 +1,33 @@
1
+ import type { H3Event } from "h3";
2
+
3
+ import type { CostCenter } from "../../app/interfaces/b2b";
4
+
5
+ /**
6
+ * Where a buyer's cost centres come from.
7
+ *
8
+ * A cost centre is the account a line is booked against, and which ones a
9
+ * buyer may book to is a fact about the organisation, not about the shop. The
10
+ * demo implementation composes them from the bundled organisation and the
11
+ * records the account area created; the live one reads the cost-centers app.
12
+ *
13
+ * Kept apart from the rest of the B2B context on purpose: the context also
14
+ * carries approval limits and workflows, which no app answers yet. A single
15
+ * "live context" would have to invent those, and inventing is what the
16
+ * registry key exists to avoid — a domain goes live when its app does, and
17
+ * not before.
18
+ */
19
+ export interface ICostCenterService {
20
+ /**
21
+ * The cost centres this buyer may book to, in the order they should be
22
+ * offered. An empty list means the buyer books to none, which is a valid
23
+ * answer and not an error.
24
+ */
25
+ list(event: H3Event | undefined, buyer: CostCenterBuyer): Promise<CostCenter[]>;
26
+ }
27
+
28
+ /** Who is asking — the shop knows the buyer, the app knows their organisation. */
29
+ export interface CostCenterBuyer {
30
+ readonly userId: string | null;
31
+ readonly contactId?: string | null;
32
+ readonly organizationId?: string | null;
33
+ }
@@ -0,0 +1,54 @@
1
+ import type { CostCenter } from "../../app/interfaces/b2b";
2
+ import type { CostCenterBuyer, ICostCenterService } from "../interfaces/costCenters";
3
+
4
+ /** One cost centre as the cost-centers app answers it. */
5
+ interface ApiCostCenterRow {
6
+ id: string;
7
+ code: string;
8
+ name: string;
9
+ organization_id?: string | null;
10
+ active?: boolean;
11
+ }
12
+
13
+ /** How many a buyer's organisation can plausibly keep. */
14
+ const PAGE_LIMIT = 200;
15
+
16
+ /**
17
+ * The cost centres a buyer's organisation keeps, from the cost-centers app.
18
+ *
19
+ * Scoped by organisation, which is how the app itself answers: asked which
20
+ * centres are usable while naming an organisation, it offers that
21
+ * organisation's and no others. A buyer with no organisation gets none rather
22
+ * than the tenant's whole list — a cost centre is somebody's, and showing one
23
+ * company's booking accounts to another is the failure this scoping prevents.
24
+ */
25
+ export class ApiCostCenterService implements ICostCenterService {
26
+ async list(_event: unknown, buyer: CostCenterBuyer): Promise<CostCenter[]> {
27
+ if (!buyer.organizationId) {
28
+ return [];
29
+ }
30
+
31
+ try {
32
+ // The escape hatch, not a typed method: `cost_centers.cost_centers.list`
33
+ // declares limit/offset/order and a punchout account code, but not the
34
+ // organisation the record carries — the app filters on it, the contract
35
+ // does not declare it. It moves to the typed call when it does.
36
+ const { items } = await useRevenexxSdk().call<{ items: ApiCostCenterRow[] }>(
37
+ "GET",
38
+ "/v1/cost-centers/cost-centers",
39
+ { query: { organization_id: buyer.organizationId, limit: PAGE_LIMIT, order: "code.asc" } },
40
+ );
41
+
42
+ return (items ?? [])
43
+ .filter(row => row.active !== false)
44
+ .map(row => ({ id: row.id, code: row.code, label: row.name }));
45
+ }
46
+ catch (err) {
47
+ // A buyer who cannot be told their cost centres must not be told a
48
+ // wrong set either: an unreachable app answers none, and the surfaces
49
+ // that offer a choice fall back to offering none.
50
+ getLogService().error("API request failed: cost-centers/list", apiErrorContext(err));
51
+ return [];
52
+ }
53
+ }
54
+ }
@@ -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
+ }
@@ -1,3 +1,4 @@
1
+ import type { H3Event } from "h3";
1
2
  import type { B2BContext, B2BRole, ApprovalLimit, ApprovalWorkflow, CostCenter, OrganizationSettings, Requisition } from "../../app/interfaces/b2b";
2
3
  import type { AuthRole } from "../../app/interfaces/auth";
3
4
 
@@ -27,8 +28,22 @@ const GUEST_ROLE = null;
27
28
  * workflows. An override for the organization settings can be injected per
28
29
  * request (demo shop dev panel) via the constructor.
29
30
  */
30
- export class MockB2BContextService implements IB2BContextService {
31
- constructor(private readonly settingsOverride?: Partial<OrganizationSettings>) {}
31
+ /**
32
+ * The buyer's B2B context: their role, the organisation's settings, the cost
33
+ * centres they may book to, the approval limits that apply and the workflows
34
+ * they can be sent through.
35
+ *
36
+ * Only ONE of those has a live source today. Cost centres come from the
37
+ * `costCenterService` registry key, which is the cost-centers app when a
38
+ * storefront sets it; the rest is the demo organisation, because no app
39
+ * answers approval limits or workflows yet. That split is deliberate and
40
+ * visible here rather than hidden behind a class named for one of the two.
41
+ */
42
+ export class B2BContextService implements IB2BContextService {
43
+ constructor(
44
+ private readonly settingsOverride?: Partial<OrganizationSettings>,
45
+ private readonly event?: H3Event,
46
+ ) {}
32
47
 
33
48
  async getContext(userId: string | null, fallbackRole?: B2BRole | null): Promise<B2BContext> {
34
49
  const org = await readCoverConfigJson<OrganizationConfig>("account/organization.json");
@@ -57,13 +72,17 @@ export class MockB2BContextService implements IB2BContextService {
57
72
  ...overrides.workflows,
58
73
  ];
59
74
 
60
- // Account-created cost centers belong to the whole organization;
61
- // bundled ones follow the persona assignment. Patches overlay both.
75
+ // Whose cost centres these are is the cost-centre source's question, not
76
+ // this one's: the demo composes them from the bundled organisation, the
77
+ // live one reads the buyer's organisation out of the cost-centers app.
78
+ // A shop that does not book to cost centres asks neither.
79
+ const refs = this.event ? sessionOrderRefs(this.event) : undefined;
62
80
  const costCenters = settings.costCenters.enabled
63
- ? [
64
- ...org.costCenters.filter(cc => (persona?.costCenterIds ?? []).includes(cc.id)),
65
- ...overrides.costCenters,
66
- ].map(cc => ({ ...cc, ...overrides.costCenterPatches[cc.id] }))
81
+ ? await getCostCenterService(this.event).list(this.event, {
82
+ userId,
83
+ contactId: refs?.contact_id ?? null,
84
+ organizationId: refs?.organization_id ?? null,
85
+ })
67
86
  : [];
68
87
 
69
88
  // Approval limits only apply when actually ordering — requesters never
@@ -0,0 +1,40 @@
1
+ import type { CostCenter } from "../../app/interfaces/b2b";
2
+ import type { CostCenterBuyer, ICostCenterService } from "../interfaces/costCenters";
3
+
4
+ interface OrganizationConfig {
5
+ costCenters: CostCenter[];
6
+ }
7
+
8
+ interface PersonaConfig {
9
+ id: string;
10
+ costCenterIds?: string[];
11
+ }
12
+
13
+ /**
14
+ * The demo tenant's cost centres: the bundled organisation's, narrowed to the
15
+ * ones the signed-in persona is assigned, plus whatever the account area
16
+ * created, with patches overlaid.
17
+ *
18
+ * This is the composition the B2B context used to carry itself; it moved here
19
+ * when the domain got a registry key, so the demo and the live source answer
20
+ * the same question through the same seam.
21
+ */
22
+ export class MockCostCenterService implements ICostCenterService {
23
+ async list(_event: unknown, buyer: CostCenterBuyer): Promise<CostCenter[]> {
24
+ if (!buyer.userId) {
25
+ return [];
26
+ }
27
+
28
+ const org = await readCoverConfigJson<OrganizationConfig>("account/organization.json");
29
+ const personas = await readCoverConfigJson<PersonaConfig[]>("account/personas.json");
30
+ const persona = personas.find(p => p.id === buyer.userId);
31
+ const overrides = await readGovernanceOverrides();
32
+
33
+ // Account-created cost centres belong to the whole organisation;
34
+ // bundled ones follow the persona assignment. Patches overlay both.
35
+ return [
36
+ ...org.costCenters.filter(cc => (persona?.costCenterIds ?? []).includes(cc.id)),
37
+ ...overrides.costCenters,
38
+ ].map(cc => ({ ...cc, ...overrides.costCenterPatches[cc.id] }));
39
+ }
40
+ }
@@ -4,7 +4,8 @@ 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 { MockB2BContextService, MockRequisitionService } from "../services/MockB2BContextService";
7
+ import { ApiRequisitionService } from "../services/ApiRequisitionService";
8
+ import { B2BContextService, MockRequisitionService } from "../services/MockB2BContextService";
8
9
  import { MockCartCalculationService } from "../services/MockCartCalculationService";
9
10
 
10
11
  /**
@@ -51,13 +52,30 @@ export function resolveOrgSettingsOverride(event?: H3Event): Partial<Organizatio
51
52
  export function getB2BContextService(event?: H3Event): IB2BContextService {
52
53
  // Per-request instantiation: the service carries the request's settings
53
54
  // override; the underlying data reads are cached by Nitro's storage.
54
- return new MockB2BContextService(resolveOrgSettingsOverride(event));
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: "requisitionService",
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,28 @@
1
+ import type { H3Event } from "h3";
2
+
3
+ import type { ICostCenterService } from "../interfaces/costCenters";
4
+ import { ApiCostCenterService } from "../services/ApiCostCenterService";
5
+ import { MockCostCenterService } from "../services/MockCostCenterService";
6
+
7
+ /**
8
+ * Registry of cost-centre sources:
9
+ * - "mock" — the bundled demo organisation and what the account area created
10
+ * - "api" — the cost-centers app through the public revenexx API
11
+ *
12
+ * The rest of the B2B context — approval limits and workflows — stays on the
13
+ * demo data whichever key is set, because no app answers those yet. A domain
14
+ * goes live when its app does.
15
+ */
16
+ const serviceRegistry: Record<string, ICostCenterService> = {
17
+ mock: new MockCostCenterService(),
18
+ api: new ApiCostCenterService(),
19
+ };
20
+
21
+ export function getCostCenterService(event?: H3Event): ICostCenterService {
22
+ const key = resolveServiceKey(event, {
23
+ domain: "costCenterService",
24
+ mockKey: "mock",
25
+ liveKey: "api",
26
+ });
27
+ return serviceRegistry[key] ?? serviceRegistry["mock"]!;
28
+ }