@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,5 +1,7 @@
1
1
  import { useDebounceFn } from "@vueuse/core";
2
2
 
3
+ import { categoryListId } from "../shared/themeEvents";
4
+
3
5
  export interface CategoryListingOptions {
4
6
  /** Resolved category slug the listing is pinned to. */
5
7
  readonly categorySlug: () => string;
@@ -58,6 +60,10 @@ export const useCategoryListing = (options: CategoryListingOptions) => {
58
60
  facetFields: () => (subcategorySlug.value
59
61
  ? ["manufacturer", "available"]
60
62
  : ["subcategory", "manufacturer", "available"]),
63
+ // Every shown page of the category is a product list view.
64
+ listEvent: () => (categorySlug.value
65
+ ? { event: "view_item_list", listId: categoryListId(categorySlug.value, subcategorySlug.value) }
66
+ : null),
61
67
  });
62
68
 
63
69
  const title = computed(() =>
@@ -1,5 +1,7 @@
1
1
  import { checkoutApi } from "../api/checkout";
2
+ import type { CartCalculation } from "../interfaces/cart-calculation";
2
3
  import type { CheckoutOnePageForm, CheckoutProfile } from "../interfaces/checkout";
4
+ import { browserSession, purchaseFromCart, stashPurchase } from "../shared/themeEvents";
3
5
 
4
6
  /**
5
7
  * Who is checking out:
@@ -56,6 +58,9 @@ export function useCheckoutOnePage() {
56
58
  const cart = useCartStore();
57
59
  const { settings } = useB2BContext();
58
60
  const psp = usePspCheckout();
61
+ // The server-calculated totals the summary shows (shared state) — read when
62
+ // an order is placed, so the confirmation can report what was bought.
63
+ const calculation = useState<CartCalculation | null>("cart-calculation", () => null);
59
64
  const { data: profile, refresh: refreshProfile } = useCheckoutProfileSource();
60
65
  const profileLoading = computed(() => profile.value === null);
61
66
 
@@ -293,7 +298,7 @@ export function useCheckoutOnePage() {
293
298
  // (approval limits, quantity rules) against the same data.
294
299
  items: cart.items,
295
300
  ...(isGuest.value ? { contactEmail: guestContact.value.email } : {}),
296
- ...(f.deliveryMethod ? { deliveryMethod: f.deliveryMethod } : {}),
301
+ ...(form.value.deliveryMethod ? { deliveryMethod: f.deliveryMethod } : {}),
297
302
  ...(f.requestedDate ? { requestedDate: f.requestedDate } : {}),
298
303
  ...(f.deliveryNote ? { deliveryNote: f.deliveryNote } : {}),
299
304
  ...(f.partialDelivery ? { partialDelivery: true } : {}),
@@ -301,7 +306,7 @@ export function useCheckoutOnePage() {
301
306
  ...(f.quoteNumber ? { quoteNumber: f.quoteNumber } : {}),
302
307
  ...(f.noOrderConfirmation ? { noOrderConfirmation: true } : {}),
303
308
  ...(f.orderNote ? { orderNote: f.orderNote } : {}),
304
- ...(f.promoCode ? { promoCode: f.promoCode } : {}),
309
+ ...(form.value.promoCode ? { promoCode: f.promoCode } : {}),
305
310
  };
306
311
  }
307
312
 
@@ -336,6 +341,20 @@ export function useCheckoutOnePage() {
336
341
  }
337
342
  }
338
343
 
344
+ // The order as it is placed, kept for the confirmation page's
345
+ // `purchase` event — the cart is cleared below, and a PSP redirect
346
+ // leaves this page altogether. Lines and money only, never who.
347
+ if (import.meta.client) {
348
+ stashPurchase(
349
+ browserSession(),
350
+ purchaseFromCart(cart.items, calculation.value?.totals, { subtotal: cart.subtotal, tax: cart.tax }, {
351
+ ...(form.value.paymentMethod ? { payment_type: String(form.value.paymentMethod).slice(0, 64) } : {}),
352
+ ...(form.value.deliveryMethod ? { shipping_tier: String(form.value.deliveryMethod).slice(0, 64) } : {}),
353
+ ...(form.value.promoCode ? { coupon: String(form.value.promoCode).slice(0, 64) } : {}),
354
+ }),
355
+ );
356
+ }
357
+
339
358
  const order = await $fetch(checkoutApi.orders(), {
340
359
  method: "POST",
341
360
  body: payload,
@@ -1,5 +1,16 @@
1
1
  import type { ComputedRef } from "vue";
2
2
 
3
+ /**
4
+ * The permission the buyer's role must grant for each area — the same map the
5
+ * BFF refuses the write by. The profile is the buyer's own and needs none.
6
+ */
7
+ const AREA_PERMISSION: Record<"addresses" | "profile" | "organization" | "team", string | null> = {
8
+ addresses: "addresses.manage",
9
+ profile: null,
10
+ organization: "organization.manage",
11
+ team: "contacts.manage",
12
+ };
13
+
3
14
  /**
4
15
  * Whether this buyer may change this part of their own master data.
5
16
  *
@@ -10,10 +21,22 @@ import type { ComputedRef } from "vue";
10
21
  *
11
22
  * `team` follows the company rather than the addresses: a merchant who keeps the
12
23
  * company record keeps its people too.
24
+ *
25
+ * Two halves: what the merchant left in buyers' hands, and what this buyer's
26
+ * own role grants (RAD-155) — managing the people takes `contacts.manage`.
13
27
  */
14
28
  export function useMasterDataEditable(area: "addresses" | "profile" | "organization" | "team"): ComputedRef<boolean> {
15
29
  const { account } = useShopSettings();
30
+ const auth = useAuthStore();
16
31
  return computed(() => {
32
+ // The role half: a buyer whose role does not grant the change is not
33
+ // offered it. Only where the platform stated the grants — the demo
34
+ // personas carry none, and the setting alone decides for them.
35
+ const permission = AREA_PERMISSION[area];
36
+ const granted = auth.user?.permissions;
37
+ if (permission && Array.isArray(granted) && !granted.includes(permission)) {
38
+ return false;
39
+ }
17
40
  switch (account.value?.selfService) {
18
41
  case "none":
19
42
  return false;
@@ -1,8 +1,35 @@
1
1
  import type { ProductList } from "../interfaces/product-list";
2
+ import { listingProductToItem } from "../shared/themeEvents";
2
3
 
3
- export function useProductCard(getProduct: () => ProductList) {
4
+ /** Where a card is shown, for the `select_item` it reports when opened. */
5
+ export interface ProductCardListContext {
6
+ listId?: string;
7
+ /** 1-based position in that list. */
8
+ position?: number;
9
+ }
10
+
11
+ export function useProductCard(
12
+ getProduct: () => ProductList,
13
+ getList?: () => ProductCardListContext | undefined,
14
+ ) {
4
15
  const url = computed(() => useProductUrl(getProduct()).value);
5
16
  const { getImage } = useProductImage();
17
+ const { useOffer } = useOffers();
18
+ const { offer } = useOffer(() => getProduct().id);
19
+ const events = useThemeEvents();
20
+
21
+ /** Report that the buyer opened this product from the list it was shown in. */
22
+ function select(): void {
23
+ const list = getList?.();
24
+ const item = listingProductToItem(getProduct(), {
25
+ position: list?.position,
26
+ listId: list?.listId,
27
+ prices: offer.value?.prices,
28
+ });
29
+ events.emit("select_item", {
30
+ ecommerce: { items: [item], ...(list?.listId ? { list_id: list.listId } : {}) },
31
+ });
32
+ }
6
33
 
7
- return { url, getImage };
34
+ return { url, getImage, select };
8
35
  }
@@ -1,6 +1,7 @@
1
1
  import { searchApi } from "../api/search";
2
2
  import type { ProductList } from "../interfaces/product-list";
3
3
  import type { PriceRange, SearchFacet } from "../interfaces/search-facets";
4
+ import { listingProductToItem } from "../shared/themeEvents";
4
5
 
5
6
  export interface ProductListingOptions {
6
7
  /** Unique fetch key per listing surface (e.g. "search", "category"). */
@@ -16,8 +17,22 @@ export interface ProductListingOptions {
16
17
  facetFields?: MaybeRefOrGetter<string[]>;
17
18
  /** Run the first request even with an empty query (category pages). */
18
19
  allowEmptyQuery?: boolean;
20
+ /**
21
+ * How a shown page of results is reported to the theme event contract:
22
+ * a category listing is a `view_item_list`, the search page a `search`.
23
+ * Omitted or null → nothing is reported (e.g. the editor's sample listing).
24
+ */
25
+ listEvent?: () => ListingEvent | null;
19
26
  }
20
27
 
28
+ /** What a listing reports itself as (theme-events/1). */
29
+ export type ListingEvent =
30
+ | { event: "view_item_list"; listId: string }
31
+ | { event: "search"; listId: string; term: string };
32
+
33
+ /** How long a reported listing waits for its prices before it goes out without them. */
34
+ const LIST_EVENT_OFFER_WAIT_MS = 4000;
35
+
21
36
  const DEFAULT_FACETS = ["category", "subcategory", "manufacturer", "available"];
22
37
 
23
38
  /** Every sort the layer knows, and the i18n key that names it. */
@@ -200,6 +215,68 @@ export function useProductListing(options: ProductListingOptions) {
200
215
  }
201
216
  }, { immediate: true });
202
217
 
218
+ /* ---- theme events --------------------------------------------- */
219
+ // Reported once per shown page of results, after the offers for it have
220
+ // settled — a list view without prices tells a tag little. Client-only:
221
+ // `useThemeEvents()` is a no-op on the server and in the editor.
222
+ if (import.meta.client && options.listEvent) {
223
+ const themeEvents = useThemeEvents();
224
+ const offerCache = useState<Record<string, { prices: { [key: string]: number }[] }>>("offers:cache", () => ({}));
225
+ const offerAttempted = useState<Record<string, boolean>>("offers:attempted", () => ({}));
226
+ const offersSettled = (ids: string[]): Promise<void> => new Promise((resolve) => {
227
+ const settled = () => ids.every(id => id in offerCache.value || offerAttempted.value[id]);
228
+ if (settled()) {
229
+ resolve();
230
+ return;
231
+ }
232
+ const timer = setTimeout(() => {
233
+ stop();
234
+ resolve();
235
+ }, LIST_EVENT_OFFER_WAIT_MS);
236
+ const stop = watch([offerCache, offerAttempted], () => {
237
+ if (settled()) {
238
+ clearTimeout(timer);
239
+ stop();
240
+ resolve();
241
+ }
242
+ });
243
+ });
244
+
245
+ let lastReported = "";
246
+ watch(data, (loaded) => {
247
+ const spec = options.listEvent?.();
248
+ if (!loaded || !spec || !themeEvents.active()) {
249
+ return;
250
+ }
251
+ if (spec.event === "search" && (!spec.term.trim() || spec.term.trim() === "*")) {
252
+ return;
253
+ }
254
+ const list = loaded.products ?? [];
255
+ const key = JSON.stringify([spec, loaded.page, list.map(p => p.id)]);
256
+ if (key === lastReported || (spec.event === "view_item_list" && !list.length)) {
257
+ return;
258
+ }
259
+ lastReported = key;
260
+ const offset = (Math.max(1, loaded.page || 1) - 1) * (loaded.perPage || (productsPerPage as number));
261
+ void offersSettled(list.map(p => p.id)).then(() => {
262
+ const items = list.map((product, index) => listingProductToItem(product, {
263
+ position: offset + index + 1,
264
+ listId: spec.listId,
265
+ prices: offerCache.value[product.id]?.prices,
266
+ }));
267
+ if (spec.event === "search") {
268
+ themeEvents.emit("search", {
269
+ search: { search_term: spec.term.trim().slice(0, 256), results_count: loaded.found ?? list.length },
270
+ ...(items.length ? { ecommerce: { list_id: spec.listId, items } } : {}),
271
+ });
272
+ }
273
+ else {
274
+ themeEvents.emit("view_item_list", { ecommerce: { list_id: spec.listId, items } });
275
+ }
276
+ });
277
+ }, { immediate: true });
278
+ }
279
+
203
280
  const found = computed(() => data.value?.found ?? 0);
204
281
  const totalPages = computed(() => Math.ceil(found.value / (productsPerPage as number)));
205
282
  const isEmpty = computed(() => data.value !== null && data.value !== undefined && products.value.length === 0);
@@ -254,6 +331,8 @@ export function useProductListing(options: ProductListingOptions) {
254
331
  products, facets, found, totalPages, isEmpty,
255
332
  chips, activeFilterCount, removeChip, clearFilters,
256
333
  perPage: productsPerPage as number,
334
+ /** The list id cards report a selection from, when the listing reports at all. */
335
+ listId: () => options.listEvent?.()?.listId,
257
336
  };
258
337
  }
259
338
 
@@ -0,0 +1,90 @@
1
+ import { CART_MAX_QUANTITY } from "../interfaces/cart-item";
2
+ import type { QuantityStepperNotice, QuantityStepperOptions } from "../interfaces/quantity-stepper";
3
+
4
+ /** How long a refused or corrected entry keeps its notice on screen. */
5
+ const NOTICE_DURATION_MS = 2000;
6
+ /** Longest number the field accepts — CART_MAX_QUANTITY has six digits. */
7
+ const MAX_INPUT_DIGITS = 6;
8
+
9
+ /**
10
+ * The −/+ stepper with a typed field, as the cart page, the mini-cart and the
11
+ * product buy box all use it — one set of rules so the three cannot drift:
12
+ *
13
+ * - typing only edits the field; Enter or leaving it commits
14
+ * - an empty, zero or unparsable entry reverts to the committed quantity
15
+ * - anything above the ceiling — typed or stepped — lands on the ceiling
16
+ *
17
+ * Each correction raises a short-lived `notice`; a surface that has room for
18
+ * the explanation shows it, one that does not just ignores it.
19
+ */
20
+ export function useQuantityStepper(options: QuantityStepperOptions) {
21
+ const min = options.min ?? 1;
22
+
23
+ const inputValue = ref(String(options.quantity()));
24
+ const notice = ref<QuantityStepperNotice | null>(null);
25
+ let noticeTimer: ReturnType<typeof setTimeout> | null = null;
26
+
27
+ const ceiling = computed(() => options.max() ?? CART_MAX_QUANTITY);
28
+ const canDecrease = computed(() => options.quantity() > min);
29
+
30
+ watch(options.quantity, (value) => {
31
+ inputValue.value = String(value);
32
+ });
33
+
34
+ function clearNoticeTimer(): void {
35
+ if (noticeTimer !== null) {
36
+ clearTimeout(noticeTimer);
37
+ noticeTimer = null;
38
+ }
39
+ }
40
+
41
+ function raiseNotice(kind: QuantityStepperNotice): void {
42
+ notice.value = kind;
43
+ clearNoticeTimer();
44
+ noticeTimer = setTimeout(() => {
45
+ notice.value = null;
46
+ noticeTimer = null;
47
+ }, NOTICE_DURATION_MS);
48
+ }
49
+
50
+ function applyQuantity(next: number): void {
51
+ let target = Math.max(next, min);
52
+ if (target > ceiling.value) {
53
+ target = ceiling.value;
54
+ raiseNotice("max");
55
+ }
56
+ if (target !== options.quantity()) {
57
+ options.apply(target);
58
+ }
59
+ // The field shows the committed value even when nothing changed (a
60
+ // typed 12 clamped back onto a quantity that already sat at the ceiling).
61
+ inputValue.value = String(target);
62
+ }
63
+
64
+ function decrease(): void {
65
+ applyQuantity(options.quantity() - 1);
66
+ }
67
+
68
+ function increase(): void {
69
+ applyQuantity(options.quantity() + 1);
70
+ }
71
+
72
+ function onInput(event: Event): void {
73
+ const input = event.target as HTMLInputElement;
74
+ inputValue.value = input.value.replace(/[^0-9]/g, "").slice(0, MAX_INPUT_DIGITS);
75
+ }
76
+
77
+ function commit(): void {
78
+ const parsed = Number.parseInt(inputValue.value, 10);
79
+ if (!Number.isFinite(parsed) || parsed < 1) {
80
+ raiseNotice("invalid");
81
+ inputValue.value = String(options.quantity());
82
+ return;
83
+ }
84
+ applyQuantity(parsed);
85
+ }
86
+
87
+ onScopeDispose(clearNoticeTimer);
88
+
89
+ return { inputValue, notice, canDecrease, decrease, increase, onInput, commit };
90
+ }
@@ -0,0 +1,35 @@
1
+ import type { ComputedRef } from "vue";
2
+
3
+ import type { QuickAction } from "../config/quickActions";
4
+
5
+ import { allowedQuickActionIds, resolveQuickActions } from "../config/quickActions";
6
+
7
+ export interface UseQuickActionsReturn {
8
+ /** Catalogue ids the account navigation in effect permits, in catalogue order. */
9
+ readonly allowedIds: ComputedRef<string[]>;
10
+ /** Resolves an authored selection, in its own order, minus what the nav does not permit. */
11
+ readonly resolveAllowed: (ids: readonly string[]) => QuickAction[];
12
+ }
13
+
14
+ /**
15
+ * Quick actions as the current tenant may show them. The picker overlay gets
16
+ * the same limit server-side (the theme's catalogue endpoint), and this is the
17
+ * render-time half: a selection authored before the tenant dropped a nav link
18
+ * — or authored against a wider nav — loses the tiles the nav no longer backs.
19
+ *
20
+ * Only a tenant-authored nav limits the set: the layer's static tree (and a
21
+ * theme's app.config override) is the full B2B account, where every catalogue
22
+ * entry is a real page.
23
+ */
24
+ export function useQuickActions(): UseQuickActionsReturn {
25
+ const { navigation, isTenantAuthored } = useAccountNavigation();
26
+
27
+ const allowedIds = computed(() => allowedQuickActionIds(isTenantAuthored.value ? navigation.value : null));
28
+
29
+ function resolveAllowed(ids: readonly string[]): QuickAction[] {
30
+ const permitted = new Set(allowedIds.value);
31
+ return resolveQuickActions(ids).filter(action => permitted.has(action.id));
32
+ }
33
+
34
+ return { allowedIds, resolveAllowed };
35
+ }
@@ -0,0 +1,32 @@
1
+ import type { ComputedRef } from "vue";
2
+
3
+ import type { AuthRole } from "../interfaces/auth";
4
+
5
+ /** Least → most privileged — the order the BFF ranks roles by. */
6
+ const ROLE_RANK: Record<AuthRole, number> = { requester: 0, buyer: 1, approver: 2, admin: 3 };
7
+
8
+ /**
9
+ * What the signed-in buyer's own role lets them do, as the platform stated it
10
+ * (RAD-155). The BFF refuses the write regardless; this only keeps the page from
11
+ * offering what it would refuse.
12
+ *
13
+ * Where the platform stated no grants — the demo personas — nothing is locked
14
+ * by role, which is how the shop behaved before anybody asked.
15
+ */
16
+ export function useRoleGrants(): {
17
+ lockedByRole: (permission: string) => ComputedRef<boolean>;
18
+ mayGrant: (role: AuthRole) => boolean;
19
+ isSelf: (contactId: string) => boolean;
20
+ outranks: (role: AuthRole) => boolean;
21
+ } {
22
+ const auth = useAuthStore();
23
+ const stated = (): boolean => Array.isArray(auth.user?.permissions);
24
+ const ownRank = (): number => (auth.user?.role ? ROLE_RANK[auth.user.role] ?? -1 : -1);
25
+
26
+ return {
27
+ lockedByRole: permission => computed(() => stated() && !auth.user!.permissions!.includes(permission)),
28
+ mayGrant: role => !stated() || ROLE_RANK[role] <= ownRank(),
29
+ isSelf: contactId => !!auth.user?.contactId && auth.user.contactId === contactId,
30
+ outranks: role => stated() && ROLE_RANK[role] > ownRank(),
31
+ };
32
+ }
@@ -57,6 +57,10 @@ export const useSearchListing = (options: SearchListingOptions) => {
57
57
  key: "search",
58
58
  query: () => query.value,
59
59
  facetFields: ["category", "subcategory", "manufacturer", "available"],
60
+ // A search is reported as `search` (term + hit count), not as a list
61
+ // view: etracker reads both as `viewProductList` and would count twice.
62
+ // The match-all `*` is the catalogue, not a search, and is skipped.
63
+ listEvent: () => ({ event: "search", listId: "search", term: query.value }),
60
64
  });
61
65
 
62
66
  // `?q=*` is the match-all link (Typesense's native catch-all query): the
@@ -0,0 +1,144 @@
1
+ import { createThemeEvents } from "@revenexx/tag-manager-nuxt/events";
2
+ import type {
3
+ ThemeEventContext,
4
+ ThemeEventData,
5
+ ThemeEventEnvelope,
6
+ ThemeEventName,
7
+ ThemeEvents,
8
+ } from "@revenexx/tag-manager-nuxt/events";
9
+
10
+ import type { ShopMarket } from "../interfaces/market";
11
+ import { isEditorContext, pageTypeOf } from "../shared/themeEvents";
12
+
13
+ /**
14
+ * The storefront's voice in the event contract (`theme-events/1`).
15
+ *
16
+ * The theme says WHAT happened — `add_to_cart`, `purchase`, `request_quote` —
17
+ * once, and whoever listens (the Tag Manager module today, a theme extension
18
+ * through the DOM event, the Analytics Studio later) says it to each vendor in
19
+ * its own words. The emitter is the framework-free one from
20
+ * `@revenexx/tag-manager-nuxt/events`: importing it loads no module, so cover
21
+ * emits whether a theme installs the Tag Manager or not.
22
+ *
23
+ * Transport: `nuxtApp.callHook('revenexx:event', envelope)` and
24
+ * `window.dispatchEvent(new CustomEvent('revenexx:event', …))`.
25
+ *
26
+ * Nothing is emitted on the server, in the editor or in a preview — the editor
27
+ * seeds sample carts and renders sample products, and none of that is a buyer.
28
+ * Consent is NOT decided here: an event is a fact about the page, and each tag
29
+ * that hears it is gated by the consent provider on its own.
30
+ */
31
+
32
+ export interface UseThemeEvents {
33
+ /**
34
+ * Emit one event. Returns the envelope that went out, or null where nothing
35
+ * was emitted (server, editor/preview, an invalid envelope in dev, a repeated
36
+ * purchase).
37
+ */
38
+ emit<E extends ThemeEventName>(event: E, data?: ThemeEventData): ThemeEventEnvelope<E> | null;
39
+ /** Whether events are emitted on this page at all (client, not editor/preview). */
40
+ active(): boolean;
41
+ }
42
+
43
+ const NOOP: UseThemeEvents = { emit: () => null, active: () => false };
44
+
45
+ const MARKET_RE = /^[a-z0-9][\w-]*$/;
46
+ const CURRENCY_RE = /^[A-Z]{3}$/;
47
+ const LOCALE_RE = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/;
48
+
49
+ interface ThemeEventsHost {
50
+ _rvxThemeEvents?: UseThemeEvents;
51
+ }
52
+
53
+ /**
54
+ * Build the per-app emitter. Must run inside a Nuxt context (a plugin or a
55
+ * component's setup) — every ref it reads later is captured here.
56
+ */
57
+ function createForApp(): UseThemeEvents {
58
+ const nuxtApp = useNuxtApp();
59
+ const router = useRouter();
60
+ const config = useRuntimeConfig().public as { locale?: string; currency?: string };
61
+ const marketCookie = useCookie<string>("cover-market", { default: () => "", watch: true });
62
+ const currencyCookie = useCookie<string>("cover-currency", { default: () => "", watch: true });
63
+ const { data: markets } = useNuxtData<ShopMarket[]>("shop-markets");
64
+ const auth = useAuthStore();
65
+
66
+ const i18n = nuxtApp.$i18n as unknown as {
67
+ locale: { value: string };
68
+ locales: { value: ({ code: string; language?: string } | string)[] };
69
+ } | undefined;
70
+
71
+ const localeCodes = (): string[] =>
72
+ (i18n?.locales.value ?? []).map(l => (typeof l === "string" ? l : l.code));
73
+
74
+ const activeMarket = (): ShopMarket | null => {
75
+ const list = markets.value ?? [];
76
+ return list.find(m => m.code === marketCookie.value)
77
+ ?? list.find(m => m.isDefault)
78
+ ?? list[0]
79
+ ?? null;
80
+ };
81
+
82
+ const marketCode = (): string => {
83
+ const code = String(marketCookie.value || activeMarket()?.code || "default").toLowerCase();
84
+ return MARKET_RE.test(code) ? code : "default";
85
+ };
86
+
87
+ const localeTag = (): string => {
88
+ const code = i18n?.locale.value ?? "";
89
+ const entry = (i18n?.locales.value ?? []).find(l => (typeof l === "string" ? l : l.code) === code);
90
+ const language = typeof entry === "object" ? entry.language : undefined;
91
+ const candidate = language || code || config.locale || "de";
92
+ // The contract wants a lower-case language subtag (`de-DE`, `en`).
93
+ const [lang, ...rest] = candidate.split("-");
94
+ const tag = [lang!.toLowerCase(), ...rest].join("-");
95
+ return LOCALE_RE.test(tag) ? tag : "de";
96
+ };
97
+
98
+ const currencyCode = (): string => {
99
+ const code = String(currencyCookie.value || activeMarket()?.currency || config.currency || "EUR").toUpperCase();
100
+ return CURRENCY_RE.test(code) ? code : "EUR";
101
+ };
102
+
103
+ const context = (): ThemeEventContext => {
104
+ const route = router.currentRoute.value;
105
+ return {
106
+ market: marketCode(),
107
+ locale: localeTag(),
108
+ currency: currencyCode(),
109
+ page: { path: route.path || "/", type: pageTypeOf(route.path || "/", localeCodes()) },
110
+ // Exactly the two booleans the contract allows — never who.
111
+ customer: { authenticated: auth.isLoggedIn, b2b: Boolean(auth.user?.organizationId) },
112
+ };
113
+ };
114
+
115
+ const events: ThemeEvents = createThemeEvents({
116
+ context,
117
+ callHook: (name, envelope) => nuxtApp.callHook(name as never, envelope as never),
118
+ validate: import.meta.dev,
119
+ });
120
+
121
+ const active = (): boolean => {
122
+ const route = router.currentRoute.value;
123
+ return !isEditorContext({
124
+ path: route.path || "/",
125
+ host: window.location.host,
126
+ query: route.query,
127
+ localeCodes: localeCodes(),
128
+ });
129
+ };
130
+
131
+ return {
132
+ active,
133
+ emit: (event, data) => (active() ? events.emit(event, data) : null),
134
+ };
135
+ }
136
+
137
+ export function useThemeEvents(): UseThemeEvents {
138
+ if (import.meta.server) {
139
+ return NOOP;
140
+ }
141
+ const host = useNuxtApp() as unknown as ThemeEventsHost;
142
+ host._rvxThemeEvents ??= createForApp();
143
+ return host._rvxThemeEvents;
144
+ }
@@ -0,0 +1,26 @@
1
+ import type { AccountDashboardKpiId } from "../interfaces/account/dashboard";
2
+
3
+ /** Every dashboard KPI, in the order the band renders them. */
4
+ export const ACCOUNT_DASHBOARD_KPI_IDS: readonly AccountDashboardKpiId[] = [
5
+ "openOrders",
6
+ "awaitingApproval",
7
+ "spend30",
8
+ "budgetUsed",
9
+ ];
10
+
11
+ function isAccountDashboardKpiId(id: string): id is AccountDashboardKpiId {
12
+ return (ACCOUNT_DASHBOARD_KPI_IDS as readonly string[]).includes(id);
13
+ }
14
+
15
+ /**
16
+ * Narrows a requested KPI selection (a block option, a tenant setting) to the
17
+ * KPIs that exist, in canonical order and without duplicates. A selection that
18
+ * leaves nothing valid — empty, or only unknown ids — resolves to the full set:
19
+ * the band always shows at least one KPI, and an editor who unchecks every box
20
+ * gets the default rather than an empty frame.
21
+ */
22
+ export function resolveAccountDashboardKpis(ids: readonly string[]): AccountDashboardKpiId[] {
23
+ const requested = new Set(ids.filter(isAccountDashboardKpiId));
24
+ const resolved = ACCOUNT_DASHBOARD_KPI_IDS.filter(id => requested.has(id));
25
+ return resolved.length > 0 ? resolved : [...ACCOUNT_DASHBOARD_KPI_IDS];
26
+ }
@@ -1,4 +1,4 @@
1
- import type { AccountNavLink } from "./navigation";
1
+ import type { AccountNavGroup, AccountNavLink } from "./navigation";
2
2
 
3
3
  import { accountNavigation } from "./navigation";
4
4
 
@@ -28,9 +28,9 @@ export interface QuickAction {
28
28
  }
29
29
 
30
30
  /**
31
- * Render AND editor order in one list: the blokkli checkboxes control sorts any
32
- * selection back into the declared option order, so there is no authorable
33
- * ordering — this array is the only place tile order is decided. It opens with
31
+ * Catalogue order: what the picker overlay lists, and the order of a resolved
32
+ * allowed set. Tile order on the page is the editor's own — the picker stores
33
+ * its selection in authored order (see `resolveQuickActions`). It opens with
34
34
  * the four shortcuts the live shop shows by default.
35
35
  */
36
36
  const QUICK_ACTION_ORDER: readonly string[] = [
@@ -60,6 +60,18 @@ export const DEFAULT_QUICK_ACTION_IDS: readonly string[] = [
60
60
  "cart",
61
61
  ];
62
62
 
63
+ /**
64
+ * The account dashboard's quick-access widget default — what an instance
65
+ * without an authored selection shows, in this order.
66
+ */
67
+ export const DASHBOARD_QUICK_ACTION_IDS: readonly string[] = [
68
+ "direct-order",
69
+ "orders",
70
+ "order-lists",
71
+ "requisitions",
72
+ "cost-centers",
73
+ ];
74
+
63
75
  /**
64
76
  * Shortcuts with no `accountNavigation` counterpart. The direct-order tile is
65
77
  * labelled "Schnellerfassung" rather than the page's own "Direktbestellung":
@@ -87,7 +99,7 @@ const ICON_OVERRIDES: Record<string, string> = {
87
99
  };
88
100
 
89
101
  /** `/account` → `dashboard`, `/account/cost-centers` → `cost-centers`. */
90
- function actionIdForPath(path: string): string {
102
+ export function actionIdForPath(path: string): string {
91
103
  if (path === "/account") {
92
104
  return "dashboard";
93
105
  }
@@ -136,3 +148,26 @@ export const QUICK_ACTION_IDS: readonly string[] = quickActions.map(action => ac
136
148
  export function resolveQuickActions(ids: readonly string[]): QuickAction[] {
137
149
  return ids.flatMap(id => quickActions.find(action => action.id === id) ?? []);
138
150
  }
151
+
152
+ /**
153
+ * The ids a given account navigation permits, in catalogue order. A shortcut
154
+ * is only offered — in the picker and on the page — when the sidebar links its
155
+ * target, so a tile never points where the tenant's nav does not: a tenant
156
+ * whose nav has no Kostenstellen gets no Kostenstellen tile.
157
+ *
158
+ * The two standalone shortcuts are exempt: they are never nav links by design,
159
+ * so the nav cannot vouch for them and does not need to. `null` stands for
160
+ * "no tenant nav" (the layer's static tree) and permits the whole catalogue.
161
+ */
162
+ export function allowedQuickActionIds(nav: readonly AccountNavGroup[] | null): string[] {
163
+ if (nav === null) {
164
+ return [...QUICK_ACTION_IDS];
165
+ }
166
+ const permitted = new Set(Object.keys(STANDALONE_ACTIONS));
167
+ for (const group of nav) {
168
+ for (const link of group.links) {
169
+ permitted.add(actionIdForPath(link.to));
170
+ }
171
+ }
172
+ return QUICK_ACTION_IDS.filter(id => permitted.has(id));
173
+ }