@revenexx/cover 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/app/api/account.ts +4 -0
  2. package/app/assets/css/cover.css +9 -0
  3. package/app/components/RevenexxForm.vue +4 -0
  4. package/app/components/account/AccountSidebar.vue +2 -5
  5. package/app/components/account/dashboard/AccountDashboardKpis.vue +74 -34
  6. package/app/components/account/dashboard/AccountDashboardQuickActions.vue +24 -6
  7. package/app/components/account/organization/AccountOrganization.vue +3 -1
  8. package/app/components/account/team/AccountTeam.vue +32 -7
  9. package/app/components/auth/AuthForgotPasswordPanel.vue +9 -4
  10. package/app/components/auth/AuthLoginPanel.vue +5 -3
  11. package/app/components/cart/actions/CartSaveToListModal.vue +5 -0
  12. package/app/components/cart/item/CartItem.vue +17 -75
  13. package/app/components/cart/position/CartPosition.vue +17 -30
  14. package/app/components/cart/quote/CartQuoteRequestModal.vue +9 -1
  15. package/app/components/category/view/GridView.vue +10 -1
  16. package/app/components/category/view/ListView.vue +10 -1
  17. package/app/components/checkout/confirmation/CheckoutConfirmationActions.vue +2 -0
  18. package/app/components/checkout/onepage/CheckoutAddressSection.vue +4 -4
  19. package/app/components/checkout/onepage/CheckoutDeliverySection.vue +18 -2
  20. package/app/components/checkout/onepage/CheckoutGate.vue +2 -0
  21. package/app/components/checkout/onepage/CheckoutOnePageView.vue +1 -1
  22. package/app/components/checkout/onepage/CheckoutPaymentSection.vue +10 -0
  23. package/app/components/checkout/onepage/CheckoutSummarySection.vue +7 -1
  24. package/app/components/layout/Region.vue +13 -0
  25. package/app/components/layout/footer/Footer.vue +8 -0
  26. package/app/components/layout/header/AppBar.vue +4 -3
  27. package/app/components/layout/header/MainNav.vue +3 -3
  28. package/app/components/listing/ListingResults.vue +3 -1
  29. package/app/components/product/card/Compact.vue +10 -1
  30. package/app/components/product/detail/ProductDetailAddToCart.vue +51 -18
  31. package/app/components/product/detail/ProductDetailIdentity.vue +1 -1
  32. package/app/components/product/detail/ProductDetailPriceRequest.vue +1 -1
  33. package/app/components/product/detail/ProductDetailSaveToList.vue +10 -0
  34. package/app/composables/useAccountDashboard.ts +0 -10
  35. package/app/composables/useAccountNavigation.ts +35 -0
  36. package/app/composables/useAuthStore.ts +2 -0
  37. package/app/composables/useCategoryListing.ts +6 -0
  38. package/app/composables/useCheckoutOnePage.ts +21 -2
  39. package/app/composables/useMasterDataEditable.ts +23 -0
  40. package/app/composables/useProductCard.ts +29 -2
  41. package/app/composables/useProductListing.ts +79 -0
  42. package/app/composables/useQuantityStepper.ts +90 -0
  43. package/app/composables/useQuickActions.ts +35 -0
  44. package/app/composables/useRoleGrants.ts +32 -0
  45. package/app/composables/useSearchListing.ts +4 -0
  46. package/app/composables/useThemeEvents.ts +144 -0
  47. package/app/config/accountDashboard.ts +26 -0
  48. package/app/config/quickActions.ts +40 -5
  49. package/app/interfaces/account/dashboard.ts +2 -0
  50. package/app/interfaces/auth.ts +13 -2
  51. package/app/interfaces/quantity-stepper.ts +17 -0
  52. package/app/layouts/default.vue +19 -10
  53. package/app/layouts/focus.vue +28 -7
  54. package/app/middleware/checkout-guard.ts +7 -1
  55. package/app/pages/punchout/transfer.vue +22 -0
  56. package/app/plugins/theme-events.client.ts +132 -0
  57. package/app/shared/themeEvents.ts +445 -0
  58. package/i18n/locales/de/account.json +7 -0
  59. package/i18n/locales/de/auth.json +1 -0
  60. package/i18n/locales/de/cart.json +2 -1
  61. package/i18n/locales/de/checkout.json +2 -1
  62. package/i18n/locales/de/common.json +2 -0
  63. package/i18n/locales/de/cover.json +44 -0
  64. package/i18n/locales/de/editor.json +47 -1
  65. package/i18n/locales/en/account.json +7 -0
  66. package/i18n/locales/en/auth.json +1 -0
  67. package/i18n/locales/en/cart.json +2 -1
  68. package/i18n/locales/en/checkout.json +2 -1
  69. package/i18n/locales/en/common.json +2 -0
  70. package/i18n/locales/en/cover.json +44 -0
  71. package/i18n/locales/en/editor.json +47 -1
  72. package/nuxt.config.ts +15 -1
  73. package/package.json +5 -2
  74. package/server/api/account/orders/[id]/cancel.post.ts +1 -1
  75. package/server/api/account/orders/[id]/messages.get.ts +1 -1
  76. package/server/api/account/orders/[id]/messages.post.ts +1 -1
  77. package/server/api/account/orders/[id]/return.post.ts +1 -0
  78. package/server/api/account/orders/[id].get.ts +1 -1
  79. package/server/api/account/pending-approvals/index.get.ts +1 -0
  80. package/server/api/account/profile.get.ts +3 -1
  81. package/server/api/auth/login.post.ts +6 -0
  82. package/server/api/auth/magic-link.put.ts +6 -1
  83. package/server/api/auth/otp.put.ts +6 -1
  84. package/server/api/carts/[id]/activate.post.ts +1 -0
  85. package/server/api/carts/[id]/index.delete.ts +1 -0
  86. package/server/api/carts/[id]/index.put.ts +1 -0
  87. package/server/api/carts/[id]/items.post.ts +1 -0
  88. package/server/api/orders/index.post.ts +33 -0
  89. package/server/api/quick-actions.get.ts +6 -38
  90. package/server/middleware/buyer-principal.ts +18 -0
  91. package/server/routes/punchout/start.get.ts +2 -2
  92. package/server/services/ApiAddressBookService.ts +43 -1
  93. package/server/services/ApiAuthService.ts +98 -17
  94. package/server/services/ApiCartService.ts +3 -10
  95. package/server/services/ApiOrganizationService.ts +7 -2
  96. package/server/services/ApiTeamService.ts +93 -21
  97. package/server/utils/buyerIdentity.ts +168 -0
  98. package/server/utils/cartOwnership.ts +27 -0
  99. package/server/utils/liveOrderLists.ts +50 -23
  100. package/server/utils/liveOrders.ts +39 -24
  101. package/server/utils/livePrices.ts +7 -15
  102. package/server/utils/masterData.ts +29 -0
  103. package/server/utils/passwordlessSignIn.ts +13 -4
  104. package/server/utils/pendingApprovals.ts +29 -7
  105. package/server/utils/procurementCheckout.ts +2 -0
  106. package/server/utils/quickActionCatalogue.ts +53 -0
  107. package/server/utils/revenexxSdk.ts +116 -2
@@ -1,7 +1,9 @@
1
1
  import type { H3Event } from "h3";
2
+ import { RevenexxException } from "@revenexx/sdk";
2
3
  import type { Models } from "@revenexx/sdk";
3
4
 
4
5
  import type { OrderList, OrderListPosition } from "../../app/interfaces/account/order-lists";
6
+ import type { RevenexxSdk } from "./revenexxSdk";
5
7
 
6
8
  /**
7
9
  * Live order lists through the `orderlists` gateway app
@@ -16,6 +18,11 @@ import type { OrderList, OrderListPosition } from "../../app/interfaces/account/
16
18
  * returns the owner's own lists ∪ the organization's shared lists. We supply
17
19
  * both from the authenticated contact (auth/me). The cover OrderList keeps
18
20
  * `public` UI-side; it maps to the app's `shared`.
21
+ *
22
+ * Access: every call carries the contact as `X-Revenexx-Principal`
23
+ * (RAD-168). With it, orderlists (>= 1.0, RAD-134) answers 404 for another
24
+ * customer's private list — items included; without it the tenant key reads
25
+ * every list of the tenant. That 404 is passed on as cover's own.
19
26
  */
20
27
 
21
28
  interface AppItem {
@@ -56,6 +63,24 @@ async function actor(event: H3Event): Promise<{ contactId: string; name: string;
56
63
  return { contactId: user.contactId, name: user.name, organizationId: user.organizationId };
57
64
  }
58
65
 
66
+ /** The SDK acting as the signed-in contact. */
67
+ function sdkAs(me: { contactId: string }): RevenexxSdk {
68
+ return useRevenexxSdk({ principal: `contact:${me.contactId}` });
69
+ }
70
+
71
+ /** A list the principal may not see is one that does not exist. */
72
+ async function orNotFound<T>(run: () => Promise<T>): Promise<T> {
73
+ try {
74
+ return await run();
75
+ }
76
+ catch (err) {
77
+ if (err instanceof RevenexxException && err.code === 404) {
78
+ throw createError({ statusCode: 404, message: "List not found" });
79
+ }
80
+ throw err;
81
+ }
82
+ }
83
+
59
84
  function toCoverPosition(item: AppItem): OrderListPosition {
60
85
  return {
61
86
  // cover treats position.id as the PRODUCT id (membership flag on the
@@ -175,7 +200,7 @@ function toCoverList(row: AppList): OrderList {
175
200
  /** Own lists ∪ org-shared, each with its positions (bounded fan-out). */
176
201
  export async function listOrderLists(event: H3Event): Promise<OrderList[]> {
177
202
  const me = await actor(event);
178
- const sdk = useRevenexxSdk();
203
+ const sdk = sdkAs(me);
179
204
  // Typed list filter (orderlists.list declares owner_id/organization_id —
180
205
  // @revenexx/sdk >= 0.0.11). The fan-out to full lists is typed too.
181
206
  const { items } = await sdk.orderlists.orderlistsList({
@@ -187,8 +212,8 @@ export async function listOrderLists(event: H3Event): Promise<OrderList[]> {
187
212
  }
188
213
 
189
214
  export async function getOrderList(event: H3Event, id: string): Promise<OrderList> {
190
- await actor(event);
191
- const row = await useRevenexxSdk().orderlists.orderlistsGet({ id });
215
+ const me = await actor(event);
216
+ const row = await orNotFound(() => sdkAs(me).orderlists.orderlistsGet({ id }));
192
217
  return toCoverList(row as unknown as AppList);
193
218
  }
194
219
 
@@ -197,7 +222,7 @@ export async function createOrderList(
197
222
  body: { name: string; kind?: string; public?: boolean; positions?: OrderListPosition[] },
198
223
  ): Promise<OrderList> {
199
224
  const me = await actor(event);
200
- const row = await useRevenexxSdk().orderlists.orderlistsCreate({
225
+ const row = await sdkAs(me).orderlists.orderlistsCreate({
201
226
  name: body.name,
202
227
  ownerId: me.contactId,
203
228
  ownerName: me.name,
@@ -214,28 +239,30 @@ export async function updateOrderList(
214
239
  id: string,
215
240
  body: { name?: string; public?: boolean; positions?: OrderListPosition[]; appendPositions?: OrderListPosition[] },
216
241
  ): Promise<OrderList> {
217
- await actor(event);
218
- const sdk = useRevenexxSdk();
219
-
220
- if (typeof body.name === "string" && body.name.trim() || typeof body.public === "boolean") {
221
- await sdk.orderlists.orderlistsUpdate({
222
- id,
223
- ...(typeof body.name === "string" && body.name.trim() ? { name: body.name.trim() } : {}),
224
- ...(typeof body.public === "boolean" ? { shared: body.public } : {}),
225
- });
226
- }
242
+ const me = await actor(event);
243
+ const sdk = sdkAs(me);
227
244
 
228
- if (Array.isArray(body.positions)) {
229
- await sdk.orderlists.orderlistsItemsReplace({ listId: id, items: body.positions.map(toItemInput) });
230
- }
231
- for (const position of body.appendPositions ?? []) {
232
- await sdk.orderlists.orderlistsItemsCreate({ listId: id, ...toItemCreateParams(position) });
233
- }
245
+ return await orNotFound(async () => {
246
+ if (typeof body.name === "string" && body.name.trim() || typeof body.public === "boolean") {
247
+ await sdk.orderlists.orderlistsUpdate({
248
+ id,
249
+ ...(typeof body.name === "string" && body.name.trim() ? { name: body.name.trim() } : {}),
250
+ ...(typeof body.public === "boolean" ? { shared: body.public } : {}),
251
+ });
252
+ }
234
253
 
235
- return toCoverList(await sdk.orderlists.orderlistsGet({ id }) as unknown as AppList);
254
+ if (Array.isArray(body.positions)) {
255
+ await sdk.orderlists.orderlistsItemsReplace({ listId: id, items: body.positions.map(toItemInput) });
256
+ }
257
+ for (const position of body.appendPositions ?? []) {
258
+ await sdk.orderlists.orderlistsItemsCreate({ listId: id, ...toItemCreateParams(position) });
259
+ }
260
+
261
+ return toCoverList(await sdk.orderlists.orderlistsGet({ id }) as unknown as AppList);
262
+ });
236
263
  }
237
264
 
238
265
  export async function deleteOrderList(event: H3Event, id: string): Promise<void> {
239
- await actor(event);
240
- await useRevenexxSdk().orderlists.orderlistsDelete({ id });
266
+ const me = await actor(event);
267
+ await orNotFound(() => sdkAs(me).orderlists.orderlistsDelete({ id }));
241
268
  }
@@ -1,8 +1,9 @@
1
1
  import type { H3Event } from "h3";
2
2
 
3
- import type { StoredSession } from "../../app/interfaces/auth";
4
3
  import type { AccountOrder, AccountOrderPosition, AccountOrderReturn, AccountOrderStatus, AccountOrderPaymentStatus } from "../../app/interfaces/account/order-list";
5
4
 
5
+ import { verifiedBuyer } from "./buyerIdentity";
6
+
6
7
  /**
7
8
  * Live orders via the orders app — placing from the checkout snapshot and
8
9
  * mapping the order aggregate back into the account history contracts.
@@ -38,6 +39,8 @@ export interface LiveOrder {
38
39
  billing_address: Record<string, unknown> | null;
39
40
  shipping_address: Record<string, unknown> | null;
40
41
  payment: { method?: string } | null;
42
+ /** The contact the order was placed for — what "the buyer's own" is decided by. */
43
+ contact_id?: string | null;
41
44
  placed_at: string | null;
42
45
  created_at: string;
43
46
  acknowledged_at: string | null;
@@ -54,26 +57,25 @@ export interface LiveOrderReturn {
54
57
  positions?: Array<{ order_item_id?: string; name?: string | null; quantity: number }>;
55
58
  }
56
59
 
57
- /** The buyer's identity refs from the session cookie (guests place openly). */
60
+ /**
61
+ * The buyer's identity refs (guests place openly) — as the identity service
62
+ * verified them for this request, NOT as the session cookie states them: the
63
+ * cookie is browser-writable, and reading the ids from it let a buyer act for
64
+ * any organization they could name (RAD-155). Empty until the buyer has been
65
+ * resolved, which the buyer-principal middleware does for every BFF route.
66
+ */
58
67
  export function sessionOrderRefs(event: H3Event): { contact_id?: string; organization_id?: string } {
59
- const raw = getCookie(event, SESSION_COOKIE_NAME);
60
- if (!raw) {
61
- return {};
62
- }
63
- try {
64
- const parsed = JSON.parse(raw) as StoredSession;
65
- return {
66
- ...(parsed.contactId ? { contact_id: parsed.contactId } : {}),
67
- ...(parsed.organizationId ? { organization_id: parsed.organizationId } : {}),
68
- };
69
- }
70
- catch {
71
- return {};
72
- }
68
+ const buyer = verifiedBuyer(event);
69
+ return {
70
+ ...(buyer?.contactId ? { contact_id: buyer.contactId } : {}),
71
+ ...(buyer?.organizationId ? { organization_id: buyer.organizationId } : {}),
72
+ };
73
73
  }
74
74
 
75
75
  function mapStatus(order: LiveOrder): AccountOrderStatus {
76
76
  if (order.status === "cancelled") return "cancelled";
77
+ // Requested rather than placed: waiting for somebody who may approve it.
78
+ if (order.status === "pending") return "approval-pending";
77
79
  if (order.status === "completed") return "shipped";
78
80
  return "processing";
79
81
  }
@@ -203,17 +205,29 @@ export function canBeCancelled(order: LiveOrder): boolean {
203
205
  }
204
206
 
205
207
  /** Fetch one live order by its display number (the account history id). */
206
- export async function getLiveOrderByNumber(number: string): Promise<LiveOrder | null> {
208
+ export async function getLiveOrderByNumber(number: string, contactId: string | undefined): Promise<LiveOrder | null> {
209
+ // The buyer's own order, or none. The number comes from the URL and is
210
+ // sequential, and the orders app does not narrow a read to the acting
211
+ // contact, so without this every signed-in buyer could read, cancel,
212
+ // message and return any order of the tenant by counting (RAD-155). The
213
+ // history is filtered by contact the same way; somebody else's order
214
+ // answers exactly like one that does not exist.
215
+ if (!contactId) {
216
+ return null;
217
+ }
207
218
  const sdk = useRevenexxSdk();
208
219
  // Typed list filter — orders.list now declares its query parameters
209
220
  // (@revenexx/sdk >= 0.0.10). The list response stays untyped (unnamed page
210
221
  // schema), so cast to the known shape.
211
- const { items } = await sdk.orders.ordersList({ number, limit: 1 }) as unknown as { items: LiveOrder[] };
222
+ const { items } = await sdk.orders.ordersList({ number, contactId, limit: 1 }) as unknown as { items: LiveOrder[] };
212
223
  const row = items[0];
213
224
  if (!row) {
214
225
  return null;
215
226
  }
216
- return await sdk.orders.ordersGet({ id: row.id }) as unknown as LiveOrder;
227
+ const order = await sdk.orders.ordersGet({ id: row.id }) as unknown as LiveOrder;
228
+ // Checked again on the aggregate: a filter the app ignored must not hand
229
+ // out somebody else's order.
230
+ return order.contact_id === contactId ? order : null;
217
231
  }
218
232
 
219
233
  /**
@@ -224,20 +238,21 @@ export async function getLiveOrderByNumber(number: string): Promise<LiveOrder |
224
238
  */
225
239
  export async function requestOrderReturn(
226
240
  orderNumber: string,
241
+ contactId: string | undefined,
227
242
  positions: { orderItemId: string; quantity: number }[],
228
243
  reason?: string,
229
244
  ): Promise<AccountOrder | null> {
230
245
  const sdk = useRevenexxSdk();
231
- const { items } = await sdk.orders.ordersList({ number: orderNumber, limit: 1 }) as unknown as { items: LiveOrder[] };
232
- const row = items[0];
233
- if (!row) {
246
+ // The buyer's own order only — see getLiveOrderByNumber.
247
+ const order = await getLiveOrderByNumber(orderNumber, contactId);
248
+ if (!order) {
234
249
  return null;
235
250
  }
236
251
  await sdk.orders.ordersReturn({
237
- id: row.id,
252
+ id: order.id,
238
253
  positions: positions.map(p => ({ order_item_id: p.orderItemId, quantity: p.quantity })),
239
254
  ...(reason ? { reason } : {}),
240
255
  } as unknown as Parameters<typeof sdk.orders.ordersReturn>[0]);
241
- const refreshed = await sdk.orders.ordersGet({ id: row.id }) as unknown as LiveOrder;
256
+ const refreshed = await sdk.orders.ordersGet({ id: order.id }) as unknown as LiveOrder;
242
257
  return mapLiveOrderToAccount(refreshed);
243
258
  }
@@ -1,7 +1,6 @@
1
1
  import type { H3Event } from "h3";
2
2
  import type { Models } from "@revenexx/sdk";
3
3
 
4
- import type { StoredSession } from "../../app/interfaces/auth";
5
4
  import type { Offer, OfferRequestItem } from "../interfaces/offer";
6
5
 
7
6
  /**
@@ -29,20 +28,13 @@ interface ResolvedPrice {
29
28
  * see resolveLivePriceMap.
30
29
  */
31
30
  function priceContext(event: H3Event): { contactId?: string; organizationId?: string } {
32
- const raw = getCookie(event, SESSION_COOKIE_NAME);
33
- if (!raw) {
34
- return {};
35
- }
36
- try {
37
- const parsed = JSON.parse(raw) as StoredSession;
38
- return {
39
- ...(parsed.contactId ? { contactId: parsed.contactId } : {}),
40
- ...(parsed.organizationId ? { organizationId: parsed.organizationId } : {}),
41
- };
42
- }
43
- catch {
44
- return {};
45
- }
31
+ // Verified, not read from the cookie (RAD-155): a forged organization id
32
+ // would show another company's contract prices.
33
+ const { contact_id, organization_id } = sessionOrderRefs(event);
34
+ return {
35
+ ...(contact_id ? { contactId: contact_id } : {}),
36
+ ...(organization_id ? { organizationId: organization_id } : {}),
37
+ };
46
38
  }
47
39
 
48
40
  /** Resolve tier ladder → the storefront tier map (quantity → TOTAL cents). */
@@ -33,11 +33,40 @@ export async function isMasterDataEditable(event: H3Event | undefined, area: Mas
33
33
  }
34
34
  }
35
35
 
36
+ /**
37
+ * The permission a buyer's role must grant to change each area, in the
38
+ * customers app's vocabulary. The profile is the buyer's own and needs none.
39
+ */
40
+ export const MASTER_DATA_PERMISSION: Record<MasterDataArea, string | null> = {
41
+ addresses: "addresses.manage",
42
+ profile: null,
43
+ organization: "organization.manage",
44
+ team: "contacts.manage",
45
+ };
46
+
47
+ /**
48
+ * Refuse a write the merchant's setting OR the buyer's own role does not allow.
49
+ *
50
+ * The setting alone used to be the whole check, so any signed-in buyer could
51
+ * rename the company or invite people (RAD-155). The role half reads the
52
+ * permissions the identity service answered for this request; where it said
53
+ * none (the demo personas) only the setting applies.
54
+ */
36
55
  export async function assertMasterDataEditable(event: H3Event, area: MasterDataArea): Promise<void> {
37
56
  if (!await isMasterDataEditable(event, area)) {
38
57
  throw createError({
39
58
  statusCode: 403,
40
59
  message: `This data is maintained by the merchant and cannot be changed here: ${area}.`,
60
+ data: { type: "master_data_merchant_owned" },
61
+ });
62
+ }
63
+ const permission = MASTER_DATA_PERMISSION[area];
64
+ const buyer = verifiedBuyer(event);
65
+ if (permission && buyer && !buyerHolds(buyer, permission, true)) {
66
+ throw createError({
67
+ statusCode: 403,
68
+ message: `Your role does not allow changing this: ${area}.`,
69
+ data: { type: "permission_missing", permission },
41
70
  });
42
71
  }
43
72
  }
@@ -1,6 +1,8 @@
1
1
  import type { H3Event } from "h3";
2
2
  import type { AuthRole, StoredSession } from "../../app/interfaces/auth";
3
3
  import type { AuthLoginResult } from "../interfaces/auth";
4
+ import type { CustomersPermissionAnswer } from "./buyerIdentity";
5
+ import { grantsFrom } from "./buyerIdentity";
4
6
 
5
7
  /**
6
8
  * Signing in without a password: a mailed link, or a mailed code.
@@ -47,13 +49,14 @@ export function completeSignIn(
47
49
  session: ApiSession,
48
50
  contact: ApiContact | null,
49
51
  fallbackEmail: string,
52
+ permissions?: CustomersPermissionAnswer | null,
50
53
  ): AuthLoginResult {
51
54
  const stored: StoredSession = {
52
55
  id: session.$id,
53
56
  expire: session.expire,
57
+ // The contact and organization are not written: the browser can rewrite
58
+ // this cookie, so they are re-resolved per request (RAD-155).
54
59
  userId: session.userId,
55
- ...(contact?.id ? { contactId: contact.id } : {}),
56
- ...(contact?.organization_id ? { organizationId: contact.organization_id } : {}),
57
60
  };
58
61
  setCookie(event, SESSION_COOKIE_NAME, JSON.stringify(stored), sessionCookieOptions(session.expire));
59
62
 
@@ -63,11 +66,17 @@ export function completeSignIn(
63
66
  name: nameOf(contact, fallbackEmail),
64
67
  email: contact?.email ?? fallbackEmail,
65
68
  role: roleOf(contact?.role),
66
- ...(typeof contact?.active === "boolean" ? { active: contact.active } : {}),
69
+ ...(contact?.id ? { contactId: contact.id } : {}),
70
+ ...(contact?.organization_id ? { organizationId: contact.organization_id } : {}),
71
+ ...grantsFrom(permissions, contact),
67
72
  },
68
73
  session: { id: session.$id, expire: session.expire },
69
74
  ...(contact?.id ? { contactId: contact.id } : {}),
70
75
  };
71
76
  }
72
77
 
73
- export type PasswordlessConfirm = { session: ApiSession; contact: ApiContact | null };
78
+ export type PasswordlessConfirm = {
79
+ session: ApiSession;
80
+ contact: ApiContact | null;
81
+ permissions?: CustomersPermissionAnswer | null;
82
+ };
@@ -29,27 +29,34 @@ interface LivePurchaseRequest {
29
29
  currency?: string | null;
30
30
  requested_by?: string | null;
31
31
  contact_id?: string | null;
32
+ organization_id?: string | null;
32
33
  }
33
34
 
34
35
  export async function listPendingApprovals(
35
36
  event: H3Event,
36
- actor: { contactId?: string; role?: string },
37
+ actor: { contactId?: string; role?: string; organizationId?: string },
37
38
  ): Promise<PendingApproval[]> {
38
39
  const sdk = useRevenexxSdk();
39
40
 
40
- const queries: Array<Record<string, string | number>> = [];
41
+ const queries: Array<{ byRole: boolean; query: Record<string, string | number> }> = [];
41
42
  if (actor.contactId) {
42
- queries.push({ approver_contact_id: actor.contactId, status: "pending", limit: 100 });
43
+ queries.push({ byRole: false, query: { approver_contact_id: actor.contactId, status: "pending", limit: 100 } });
43
44
  }
44
- if (actor.role) {
45
- queries.push({ approver_role: actor.role, status: "pending", limit: 100 });
45
+ // A layer recorded by ROLE names no organization, and the procurement app
46
+ // does not narrow it to the asker's: an approver of one company would see,
47
+ // and could decide, every other company's requests. Only asked for a buyer
48
+ // whose company is known; each row is then held to it below.
49
+ if (actor.role && actor.organizationId) {
50
+ queries.push({ byRole: true, query: { approver_role: actor.role, status: "pending", limit: 100 } });
46
51
  }
47
52
  if (queries.length === 0) {
48
53
  return [];
49
54
  }
50
55
 
51
56
  const rows = new Map<string, LivePendingApproval>();
52
- for (const query of queries) {
57
+ // Layers that are this person's by name rather than only by role.
58
+ const named = new Set<string>();
59
+ for (const { byRole, query } of queries) {
53
60
  try {
54
61
  const answer = await sdk.call<{ items?: LivePendingApproval[]; pending_approvals?: LivePendingApproval[] }>(
55
62
  "GET",
@@ -59,6 +66,9 @@ export async function listPendingApprovals(
59
66
  for (const row of answer.items ?? answer.pending_approvals ?? []) {
60
67
  // A layer can match both ways; it is one thing waiting, not two.
61
68
  rows.set(row.id, row);
69
+ if (!byRole) {
70
+ named.add(row.id);
71
+ }
62
72
  }
63
73
  }
64
74
  catch (err) {
@@ -81,7 +91,18 @@ export async function listPendingApprovals(
81
91
  }
82
92
  }
83
93
 
84
- return [...rows.values()].map((row) => {
94
+ // A role-matched layer counts only when its request is the approver's own
95
+ // company's; one whose request cannot be read is not shown, because its
96
+ // company cannot be proven.
97
+ const ownCompany = (row: LivePendingApproval): boolean => {
98
+ if (named.has(row.id)) {
99
+ return true;
100
+ }
101
+ const request = row.purchase_request_id ? requests.get(row.purchase_request_id) : undefined;
102
+ return !!request?.organization_id && request.organization_id === actor.organizationId;
103
+ };
104
+
105
+ return [...rows.values()].filter(ownCompany).map((row) => {
85
106
  const request = row.purchase_request_id ? requests.get(row.purchase_request_id) : undefined;
86
107
  const total = request?.total == null ? null : Number(request.total);
87
108
  return {
@@ -129,6 +150,7 @@ export async function decidePendingApproval(
129
150
  const mine = await listPendingApprovals(event, {
130
151
  ...(user.contactId ? { contactId: user.contactId } : {}),
131
152
  ...(user.role ? { role: user.role } : {}),
153
+ ...(user.organizationId ? { organizationId: user.organizationId } : {}),
132
154
  });
133
155
  if (!mine.some(approval => approval.id === id)) {
134
156
  throw createError({ statusCode: 404, message: "No such approval is waiting on you" });
@@ -27,6 +27,8 @@ export interface SubmittedOrder {
27
27
  id: string;
28
28
  number: string;
29
29
  grand_total?: number;
30
+ /** `pending` when the orders app took it for approval rather than placing it. */
31
+ status?: string;
30
32
  }
31
33
 
32
34
  /** A request waiting for a decision. */
@@ -0,0 +1,53 @@
1
+ import type { H3Event } from "h3";
2
+
3
+ import { quickActions } from "../../app/config/quickActions";
4
+
5
+ /**
6
+ * A catalogue row as the blökkli picker overlay consumes it: id plus the
7
+ * title and description already translated.
8
+ */
9
+ export interface QuickActionSummary {
10
+ readonly id: string;
11
+ readonly label: string;
12
+ readonly description: string;
13
+ }
14
+
15
+ /**
16
+ * `serverT` scopes a key to one locale FILE, but the registry's keys span two
17
+ * (`header.cart` lives in common.json, the rest in account.json). A miss
18
+ * returns the key unchanged, which is the signal to try the next namespace.
19
+ */
20
+ const NAMESPACES = ["account", "common"];
21
+
22
+ function translate(key: string, locale: string): string {
23
+ for (const namespace of NAMESPACES) {
24
+ const value = serverT(key, locale, namespace);
25
+ if (value !== key) {
26
+ return value;
27
+ }
28
+ }
29
+ return key;
30
+ }
31
+
32
+ /**
33
+ * The shortcut catalogue with its i18n keys resolved for the request's locale,
34
+ * optionally narrowed to `ids` (catalogue order is kept either way). Serves the
35
+ * picker overlay, which is compiled through the editor's own pipeline and has
36
+ * neither `$fetch` nor `useI18n()` to translate a key itself.
37
+ */
38
+ export async function loadQuickActionCatalogue(
39
+ event: H3Event,
40
+ ids?: readonly string[],
41
+ ): Promise<QuickActionSummary[]> {
42
+ const locale = resolveLocale(event);
43
+ await preloadLocaleNamespaces(locale, NAMESPACES);
44
+
45
+ const permitted = ids ? new Set(ids) : null;
46
+ return quickActions
47
+ .filter(action => permitted === null || permitted.has(action.id))
48
+ .map(action => ({
49
+ id: action.id,
50
+ label: translate(action.labelKey, locale),
51
+ description: translate(action.descriptionKey, locale),
52
+ }));
53
+ }
@@ -23,6 +23,10 @@ import {
23
23
  ShippingMethods,
24
24
  } from "@revenexx/sdk";
25
25
 
26
+ // Explicit rather than a Nitro auto-import, so the header logic is reachable
27
+ // from a unit test that imports this module.
28
+ import { buyerPrincipal } from "./buyerIdentity";
29
+
26
30
  /**
27
31
  * The generated revenexx web SDK, configured for the BFF. Every live
28
32
  * "api"-keyed implementation goes through these service instances.
@@ -43,6 +47,15 @@ import {
43
47
  // from the package themselves (Nitro auto-imports this util's exports).
44
48
  export { RevenexxException };
45
49
 
50
+ export interface RevenexxSdkOptions {
51
+ /**
52
+ * The acting party, sent as `X-Revenexx-Principal` (e.g. `contact:<id>`).
53
+ * Apps that enforce access per principal (orderlists >= 1.0, RAD-134)
54
+ * apply no rule without it — the tenant key alone sees every record.
55
+ */
56
+ readonly principal?: string;
57
+ }
58
+
46
59
  export interface RevenexxSdkCallOptions {
47
60
  readonly query?: Record<string, string | number | boolean | undefined>;
48
61
  readonly body?: unknown;
@@ -106,6 +119,79 @@ export function apiAuthErrorType(err: RevenexxException): string {
106
119
  }
107
120
  }
108
121
 
122
+ /**
123
+ * The machine code an app put on a refusal (`{ error, code }` — e.g.
124
+ * `not_self_service`, `field_merchant_owned`, `contact_blocked`), or "" when
125
+ * there is none. The SDK keeps the body only as text, so it is read back here.
126
+ */
127
+ export function apiErrorCode(err: unknown): string {
128
+ if (!(err instanceof RevenexxException)) {
129
+ return "";
130
+ }
131
+ try {
132
+ const body = JSON.parse(String(err.response ?? "")) as { code?: unknown } | null;
133
+ if (body && typeof body.code === "string") {
134
+ return body.code;
135
+ }
136
+ }
137
+ catch {
138
+ // Not JSON — fall back to the type the SDK read, if any.
139
+ }
140
+ return err.type || "";
141
+ }
142
+
143
+ /**
144
+ * A sign-in the identity service refused because the account may not act
145
+ * (customers >= 1.1.0): the auth-store type to show, or null when the
146
+ * refusal is something else. A blocked contact reads as the existing
147
+ * "account blocked" line; a blocked company has its own, because the buyer
148
+ * did nothing to their own account and asking support about it is the wrong
149
+ * desk — their company's contact person is the right one.
150
+ */
151
+ export function signInRefusalType(err: unknown): string | null {
152
+ if (!(err instanceof RevenexxException) || err.code !== 403) {
153
+ return null;
154
+ }
155
+ switch (apiErrorCode(err)) {
156
+ case "contact_blocked": return "user_blocked";
157
+ case "organization_blocked": return "organization_blocked";
158
+ default: return null;
159
+ }
160
+ }
161
+
162
+ /**
163
+ * A buyer-attributed write the customers app refused (>= 1.1.0), as the error
164
+ * this BFF answers — or null when the failure is something else.
165
+ *
166
+ * A record outside the buyer's reach reads as not found, which is what the
167
+ * shop's own ownership checks answer too, so a probe learns nothing from the
168
+ * difference. The rest are 403s with a sentence a buyer can act on and the
169
+ * app's code beside it for the page to branch on.
170
+ */
171
+ export function selfServiceRefusal(err: unknown): Error | null {
172
+ if (!(err instanceof RevenexxException) || err.code !== 403) {
173
+ return null;
174
+ }
175
+ const code = apiErrorCode(err);
176
+ switch (code) {
177
+ case "not_own_record":
178
+ return createError({ statusCode: 404, statusMessage: "Not found" });
179
+ case "field_merchant_owned":
180
+ return createError({ statusCode: 403, message: "This is maintained by the merchant and cannot be changed here.", data: { type: code } });
181
+ case "not_self_service":
182
+ return createError({ statusCode: 403, message: "This change cannot be made in the shop.", data: { type: code } });
183
+ case "self_service_closed":
184
+ return createError({ statusCode: 403, message: "This is maintained by the merchant and cannot be changed here.", data: { type: "master_data_merchant_owned" } });
185
+ case "role_exceeds_own":
186
+ return createError({ statusCode: 403, message: "You cannot give anybody a role above your own.", data: { type: "role_above_own" } });
187
+ case "contact_blocked":
188
+ case "organization_blocked":
189
+ return createError({ statusCode: 403, message: "This account is on hold.", data: { type: code } });
190
+ default:
191
+ return null;
192
+ }
193
+ }
194
+
109
195
  /** Diagnostic fields for structured logs — never includes the API key. */
110
196
  export function apiErrorContext(err: unknown): Record<string, unknown> {
111
197
  if (err instanceof RevenexxException) {
@@ -182,12 +268,32 @@ export function revenexxTenantKey(): string {
182
268
  return resolveRevenexxCredentials().tenant;
183
269
  }
184
270
 
185
- export function useRevenexxSdk(): RevenexxSdk {
271
+ /**
272
+ * Who the current request acts for: `contact:<uuid>` for a signed-in buyer,
273
+ * "" otherwise. Read from what the identity service verified for this request
274
+ * (./buyerIdentity.ts) — never from the session cookie, which the browser can
275
+ * rewrite — so a request is attributed to exactly the contact whose live
276
+ * session it carries, or to nobody.
277
+ */
278
+ function activePrincipal(): string {
279
+ try {
280
+ return buyerPrincipal(useEvent());
281
+ }
282
+ catch {
283
+ // No async context — no buyer to act for.
284
+ return "";
285
+ }
286
+ }
287
+
288
+ export function useRevenexxSdk(options: RevenexxSdkOptions = {}): RevenexxSdk {
186
289
  const { tenant, apiKey, jwt, source } = resolveRevenexxCredentials();
187
290
  const market = activeMarket();
188
291
  const channel = activeChannel();
292
+ const principal = options.principal ?? activePrincipal();
189
293
 
190
- const isCacheable = source !== "brokered" && !market && !channel;
294
+ // A client carrying a principal is ONE buyer's: cached, it would hand that
295
+ // buyer's identity to whichever request came next.
296
+ const isCacheable = source !== "brokered" && !market && !channel && !principal;
191
297
  if (isCacheable) {
192
298
  const cached = clients.get(tenant);
193
299
  if (cached) {
@@ -224,6 +330,14 @@ export function useRevenexxSdk(): RevenexxSdk {
224
330
  if (channel) {
225
331
  client.headers["X-Revenexx-Channel"] = channel;
226
332
  }
333
+ // The signed-in buyer this call is made for (RAD-155). The gateway resolves
334
+ // it into the contact, organization and permissions every app sees, and the
335
+ // customers app holds such a request to its self-service allowlist. Without
336
+ // it the call is unattributed — operator-equivalent — so it goes on every
337
+ // call made for a buyer, and on none made for nobody.
338
+ if (principal) {
339
+ client.headers["X-Revenexx-Principal"] = principal;
340
+ }
227
341
  // Auth: the brokered context wins — it is a Zitadel JWT the gateway
228
342
  // verifies against the same JWKS as any interactive caller, so one theme
229
343
  // build serves any tenant without per-site credentials. The explicit