@revenexx/cover 0.7.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 (175) hide show
  1. package/app/api/account.ts +4 -0
  2. package/app/api/forms.ts +1 -0
  3. package/app/app.config.ts +17 -12
  4. package/app/assets/css/cover.css +9 -0
  5. package/app/components/RevenexxForm.vue +84 -12
  6. package/app/components/account/AccountShell.vue +18 -0
  7. package/app/components/account/AccountSidebar.vue +2 -5
  8. package/app/components/account/approvals/AccountPendingApprovals.vue +178 -0
  9. package/app/components/account/dashboard/AccountDashboardKpis.vue +74 -34
  10. package/app/components/account/dashboard/AccountDashboardQuickActions.vue +24 -6
  11. package/app/components/account/orderlists/AccountOrderListDetail.vue +47 -4
  12. package/app/components/account/orders/AccountOrderDetail.vue +186 -1
  13. package/app/components/account/organization/AccountOrganization.vue +3 -1
  14. package/app/components/account/payments/AccountPayments.vue +129 -0
  15. package/app/components/account/quotes/AccountQuoteDetail.vue +48 -16
  16. package/app/components/account/team/AccountTeam.vue +32 -7
  17. package/app/components/auth/AuthForgotPasswordPanel.vue +9 -4
  18. package/app/components/auth/AuthLoginPanel.vue +136 -18
  19. package/app/components/auth/AuthMagicLinkPanel.vue +70 -0
  20. package/app/components/cart/actions/CartSaveToListModal.vue +5 -0
  21. package/app/components/cart/item/CartItem.vue +17 -75
  22. package/app/components/cart/position/CartPosition.vue +17 -30
  23. package/app/components/cart/quote/CartQuoteRequestModal.vue +9 -1
  24. package/app/components/cart/view/CartSummaryPanel.vue +54 -0
  25. package/app/components/category/view/GridView.vue +10 -1
  26. package/app/components/category/view/ListView.vue +10 -1
  27. package/app/components/checkout/confirmation/CheckoutConfirmationActions.vue +2 -0
  28. package/app/components/checkout/onepage/CheckoutAddressSection.vue +4 -4
  29. package/app/components/checkout/onepage/CheckoutDeliverySection.vue +31 -3
  30. package/app/components/checkout/onepage/CheckoutGate.vue +10 -7
  31. package/app/components/checkout/onepage/CheckoutOnePageView.vue +1 -1
  32. package/app/components/checkout/onepage/CheckoutPaymentSection.vue +10 -0
  33. package/app/components/checkout/onepage/CheckoutSummarySection.vue +7 -1
  34. package/app/components/form/FormPage.vue +40 -0
  35. package/app/components/layout/Region.vue +13 -0
  36. package/app/components/layout/footer/Footer.vue +8 -0
  37. package/app/components/layout/header/AppBar.vue +11 -4
  38. package/app/components/layout/header/MainNav.vue +26 -4
  39. package/app/components/layout/header/MobileMenu.vue +12 -0
  40. package/app/components/listing/ListingResults.vue +3 -1
  41. package/app/components/product/card/Compact.vue +10 -1
  42. package/app/components/product/detail/ProductDetailAddToCart.vue +51 -18
  43. package/app/components/product/detail/ProductDetailIdentity.vue +1 -1
  44. package/app/components/product/detail/ProductDetailPriceRequest.vue +39 -0
  45. package/app/components/product/detail/ProductDetailSaveToList.vue +10 -0
  46. package/app/components/product/detail/ProductDetailView.vue +57 -0
  47. package/app/composables/useAccountDashboard.ts +0 -10
  48. package/app/composables/useAccountHold.ts +45 -0
  49. package/app/composables/useAccountNavigation.ts +35 -0
  50. package/app/composables/useAccountPayments.ts +21 -0
  51. package/app/composables/useAccountQuotes.ts +15 -2
  52. package/app/composables/useAuthStore.ts +84 -2
  53. package/app/composables/useAuthoredForms.ts +26 -0
  54. package/app/composables/useAvailableOffers.ts +42 -0
  55. package/app/composables/useCategoryListing.ts +6 -0
  56. package/app/composables/useCheckoutOnePage.ts +21 -2
  57. package/app/composables/useGuestOrdering.ts +28 -0
  58. package/app/composables/useMasterDataEditable.ts +45 -7
  59. package/app/composables/useOrderListRules.ts +21 -1
  60. package/app/composables/usePendingApprovals.ts +37 -0
  61. package/app/composables/useProductCard.ts +29 -2
  62. package/app/composables/useProductListing.ts +79 -0
  63. package/app/composables/useQuantityStepper.ts +90 -0
  64. package/app/composables/useQuickActions.ts +35 -0
  65. package/app/composables/useRoleGrants.ts +32 -0
  66. package/app/composables/useSearchListing.ts +4 -0
  67. package/app/composables/useThemeEvents.ts +144 -0
  68. package/app/config/accountDashboard.ts +26 -0
  69. package/app/config/icons.ts +2 -0
  70. package/app/config/navigation.ts +2 -2
  71. package/app/config/quickActions.ts +40 -5
  72. package/app/formkit.config.ts +14 -0
  73. package/app/interfaces/account/approvals.ts +37 -0
  74. package/app/interfaces/account/dashboard.ts +2 -0
  75. package/app/interfaces/account/order-list.ts +29 -0
  76. package/app/interfaces/account/order-lists.ts +9 -0
  77. package/app/interfaces/account/payments.ts +48 -0
  78. package/app/interfaces/auth.ts +24 -2
  79. package/app/interfaces/b2b.ts +8 -8
  80. package/app/interfaces/offers.ts +35 -0
  81. package/app/interfaces/quantity-stepper.ts +17 -0
  82. package/app/interfaces/shopSettings.ts +77 -0
  83. package/app/layouts/default.vue +19 -10
  84. package/app/layouts/focus.vue +28 -7
  85. package/app/middleware/checkout-guard.ts +7 -1
  86. package/app/pages/punchout/transfer.vue +22 -0
  87. package/app/plugins/account-hold.client.ts +20 -0
  88. package/app/plugins/shop-settings.ts +27 -12
  89. package/app/plugins/theme-events.client.ts +132 -0
  90. package/app/shared/themeEvents.ts +445 -0
  91. package/i18n/locales/de/account.json +87 -0
  92. package/i18n/locales/de/auth.json +30 -0
  93. package/i18n/locales/de/cart.json +9 -1
  94. package/i18n/locales/de/checkout.json +4 -2
  95. package/i18n/locales/de/common.json +4 -0
  96. package/i18n/locales/de/cover.json +44 -0
  97. package/i18n/locales/de/editor.json +47 -1
  98. package/i18n/locales/de/forms.json +27 -0
  99. package/i18n/locales/en/account.json +87 -0
  100. package/i18n/locales/en/auth.json +30 -0
  101. package/i18n/locales/en/cart.json +9 -1
  102. package/i18n/locales/en/checkout.json +4 -2
  103. package/i18n/locales/en/common.json +4 -0
  104. package/i18n/locales/en/cover.json +44 -0
  105. package/i18n/locales/en/editor.json +47 -1
  106. package/i18n/locales/en/forms.json +27 -0
  107. package/nuxt.config.ts +15 -1
  108. package/package.json +6 -2
  109. package/server/api/account/address/[id].delete.ts +1 -1
  110. package/server/api/account/address/[id].put.ts +1 -1
  111. package/server/api/account/address/index.post.ts +1 -1
  112. package/server/api/account/order-lists/[id].get.ts +37 -3
  113. package/server/api/account/orders/[id]/cancel.post.ts +54 -0
  114. package/server/api/account/orders/[id]/messages.get.ts +63 -0
  115. package/server/api/account/orders/[id]/messages.post.ts +44 -0
  116. package/server/api/account/orders/[id]/return.post.ts +1 -0
  117. package/server/api/account/orders/[id].get.ts +1 -1
  118. package/server/api/account/organization.put.ts +1 -1
  119. package/server/api/account/payments.get.ts +54 -0
  120. package/server/api/account/pending-approvals/[id]/approve.post.ts +10 -0
  121. package/server/api/account/pending-approvals/[id]/decline.post.ts +10 -0
  122. package/server/api/account/pending-approvals/index.get.ts +26 -0
  123. package/server/api/account/profile.get.ts +3 -1
  124. package/server/api/account/profile.put.ts +1 -1
  125. package/server/api/account/quotes/[id]/decline.post.ts +35 -6
  126. package/server/api/account/team/[id].put.ts +1 -1
  127. package/server/api/account/team.post.ts +1 -1
  128. package/server/api/auth/login.post.ts +6 -0
  129. package/server/api/auth/magic-link.post.ts +32 -0
  130. package/server/api/auth/magic-link.put.ts +35 -0
  131. package/server/api/auth/otp.post.ts +33 -0
  132. package/server/api/auth/otp.put.ts +33 -0
  133. package/server/api/carts/[id]/activate.post.ts +1 -0
  134. package/server/api/carts/[id]/index.delete.ts +1 -0
  135. package/server/api/carts/[id]/index.put.ts +1 -0
  136. package/server/api/carts/[id]/items.post.ts +1 -0
  137. package/server/api/checkout/profile.get.ts +6 -3
  138. package/server/api/forms/[slug]/submit.post.ts +27 -16
  139. package/server/api/forms/[slug].get.ts +9 -1
  140. package/server/api/forms/index.get.ts +23 -0
  141. package/server/api/orders/index.post.ts +41 -0
  142. package/server/api/promotions/available.post.ts +37 -0
  143. package/server/api/quick-actions.get.ts +6 -38
  144. package/server/config/account/organization.json +0 -4
  145. package/server/config/shop/app-settings.json +4 -0
  146. package/server/data/forms/authored.json +337 -0
  147. package/server/interfaces/forms.ts +51 -0
  148. package/server/middleware/buyer-principal.ts +18 -0
  149. package/server/routes/punchout/start.get.ts +2 -2
  150. package/server/services/ApiAddressBookService.ts +43 -1
  151. package/server/services/ApiAuthService.ts +101 -10
  152. package/server/services/ApiCartService.ts +3 -10
  153. package/server/services/ApiFormsService.ts +56 -0
  154. package/server/services/ApiOrganizationService.ts +7 -2
  155. package/server/services/ApiTeamService.ts +93 -21
  156. package/server/services/MockB2BContextService.ts +1 -5
  157. package/server/services/MockFormsService.ts +63 -0
  158. package/server/utils/accountPayments.ts +45 -0
  159. package/server/utils/appSettings.ts +69 -4
  160. package/server/utils/buyerIdentity.ts +168 -0
  161. package/server/utils/cartOwnership.ts +27 -0
  162. package/server/utils/forms.ts +62 -14
  163. package/server/utils/formsService.ts +29 -0
  164. package/server/utils/liveOrderLists.ts +50 -23
  165. package/server/utils/liveOrders.ts +65 -24
  166. package/server/utils/livePrices.ts +7 -15
  167. package/server/utils/masterData.ts +60 -11
  168. package/server/utils/passwordlessSignIn.ts +82 -0
  169. package/server/utils/pendingApprovals.ts +175 -0
  170. package/server/utils/procurementCheckout.ts +2 -0
  171. package/server/utils/promotionsService.ts +90 -0
  172. package/server/utils/quickActionCatalogue.ts +53 -0
  173. package/server/utils/quotesService.ts +15 -0
  174. package/server/utils/revenexxSdk.ts +116 -2
  175. package/server/utils/shopSettings.ts +35 -4
@@ -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.
@@ -28,6 +29,8 @@ export interface LiveOrder {
28
29
  status: "pending" | "placed" | "in_fulfillment" | "completed" | "cancelled";
29
30
  payment_status: string;
30
31
  fulfillment_status: string;
32
+ /** A hold set by the merchant — whether it blocks a cancellation is theirs. */
33
+ on_hold?: boolean | null;
31
34
  currency: string;
32
35
  subtotal: number;
33
36
  shipping_total: number;
@@ -36,6 +39,8 @@ export interface LiveOrder {
36
39
  billing_address: Record<string, unknown> | null;
37
40
  shipping_address: Record<string, unknown> | null;
38
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;
39
44
  placed_at: string | null;
40
45
  created_at: string;
41
46
  acknowledged_at: string | null;
@@ -52,26 +57,25 @@ export interface LiveOrderReturn {
52
57
  positions?: Array<{ order_item_id?: string; name?: string | null; quantity: number }>;
53
58
  }
54
59
 
55
- /** 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
+ */
56
67
  export function sessionOrderRefs(event: H3Event): { contact_id?: string; organization_id?: string } {
57
- const raw = getCookie(event, SESSION_COOKIE_NAME);
58
- if (!raw) {
59
- return {};
60
- }
61
- try {
62
- const parsed = JSON.parse(raw) as StoredSession;
63
- return {
64
- ...(parsed.contactId ? { contact_id: parsed.contactId } : {}),
65
- ...(parsed.organizationId ? { organization_id: parsed.organizationId } : {}),
66
- };
67
- }
68
- catch {
69
- return {};
70
- }
68
+ const buyer = verifiedBuyer(event);
69
+ return {
70
+ ...(buyer?.contactId ? { contact_id: buyer.contactId } : {}),
71
+ ...(buyer?.organizationId ? { organization_id: buyer.organizationId } : {}),
72
+ };
71
73
  }
72
74
 
73
75
  function mapStatus(order: LiveOrder): AccountOrderStatus {
74
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";
75
79
  if (order.status === "completed") return "shipped";
76
80
  return "processing";
77
81
  }
@@ -173,21 +177,57 @@ export function mapLiveOrderToAccount(order: LiveOrder): AccountOrder {
173
177
  ? { tracking: { carrier: lastTracked.carrier ?? "", trackingNumber: lastTracked.tracking_code ?? "" } }
174
178
  : {}),
175
179
  progress,
180
+ // Whether the buyer may still call it off. The orders app refuses a
181
+ // cancellation once anything has shipped, so the shop asks the same
182
+ // question rather than offering a button that answers with an error.
183
+ cancellable: canBeCancelled(order),
176
184
  };
177
185
  }
178
186
 
187
+ /**
188
+ * Whether this order can still be called off.
189
+ *
190
+ * Shipped is the one that settles it: the app books cancelled quantities and
191
+ * refuses once a position has gone out, because the goods are with a carrier and
192
+ * cancelling them is a return. A held order is left out too — whether a hold
193
+ * blocks cancelling is the merchant's setting, and the shop cannot see which way
194
+ * they set it from here, so it does not offer what the app may refuse.
195
+ */
196
+ export function canBeCancelled(order: LiveOrder): boolean {
197
+ if (order.status === "cancelled" || order.status === "completed") {
198
+ return false;
199
+ }
200
+ if (order.on_hold === true) {
201
+ return false;
202
+ }
203
+ const shipped = (order.shipments ?? []).length > 0;
204
+ return !shipped;
205
+ }
206
+
179
207
  /** Fetch one live order by its display number (the account history id). */
180
- 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
+ }
181
218
  const sdk = useRevenexxSdk();
182
219
  // Typed list filter — orders.list now declares its query parameters
183
220
  // (@revenexx/sdk >= 0.0.10). The list response stays untyped (unnamed page
184
221
  // schema), so cast to the known shape.
185
- 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[] };
186
223
  const row = items[0];
187
224
  if (!row) {
188
225
  return null;
189
226
  }
190
- 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;
191
231
  }
192
232
 
193
233
  /**
@@ -198,20 +238,21 @@ export async function getLiveOrderByNumber(number: string): Promise<LiveOrder |
198
238
  */
199
239
  export async function requestOrderReturn(
200
240
  orderNumber: string,
241
+ contactId: string | undefined,
201
242
  positions: { orderItemId: string; quantity: number }[],
202
243
  reason?: string,
203
244
  ): Promise<AccountOrder | null> {
204
245
  const sdk = useRevenexxSdk();
205
- const { items } = await sdk.orders.ordersList({ number: orderNumber, limit: 1 }) as unknown as { items: LiveOrder[] };
206
- const row = items[0];
207
- if (!row) {
246
+ // The buyer's own order only — see getLiveOrderByNumber.
247
+ const order = await getLiveOrderByNumber(orderNumber, contactId);
248
+ if (!order) {
208
249
  return null;
209
250
  }
210
251
  await sdk.orders.ordersReturn({
211
- id: row.id,
252
+ id: order.id,
212
253
  positions: positions.map(p => ({ order_item_id: p.orderItemId, quantity: p.quantity })),
213
254
  ...(reason ? { reason } : {}),
214
255
  } as unknown as Parameters<typeof sdk.orders.ordersReturn>[0]);
215
- 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;
216
257
  return mapLiveOrderToAccount(refreshed);
217
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). */
@@ -1,23 +1,72 @@
1
+ import type { H3Event } from "h3";
2
+
1
3
  /**
2
- * Which parts of a customer's master data the storefront may change.
4
+ * Which parts of a customer's master data a buyer may change here.
5
+ *
6
+ * The customers app decides (`self_service_master_data`), because it owns the
7
+ * records. Where an ERP is the source — and for many tenants it is — a buyer who
8
+ * edits their address in the shop creates a second truth the next import
9
+ * overwrites: silently, and after they have already trusted it.
3
10
  *
4
- * Read from `account.<area>.editable` in the app config (default: editable).
5
- * A merchant whose ERP owns the data turns it off; every BFF route that
6
- * writes that data calls {@link assertMasterDataEditable} first, so the
7
- * guard does not depend on the UI having hidden the last button.
11
+ * The shop used to answer this with four flags of its own. That was a guess in
12
+ * both directions: it hid a form while the platform went on accepting the write
13
+ * from anything else that asked, and it could be set to allow what the platform
14
+ * refused. Now the platform refuses it (403) and this is the matching UX —
15
+ * asked before the write so a buyer is told rather than shown a wall.
16
+ *
17
+ * `team` follows the company and not the addresses: a merchant who keeps the
18
+ * company record keeps its people too, which is exactly the ERP-driven tenant
19
+ * this setting exists for. Adding a delivery point is the one thing such a
20
+ * buyer still knows first, which is why `addresses_only` exists at all.
8
21
  */
9
22
  export type MasterDataArea = "addresses" | "profile" | "organization" | "team";
10
23
 
11
- export function isMasterDataEditable(area: MasterDataArea): boolean {
12
- const account = (useAppConfig() as { account?: Partial<Record<MasterDataArea, { editable?: boolean }>> }).account;
13
- return account?.[area]?.editable !== false;
24
+ export async function isMasterDataEditable(event: H3Event | undefined, area: MasterDataArea): Promise<boolean> {
25
+ const { account } = await getShopSettings(event);
26
+ switch (account.selfService) {
27
+ case "none":
28
+ return false;
29
+ case "addresses_only":
30
+ return area === "addresses";
31
+ default:
32
+ return true;
33
+ }
14
34
  }
15
35
 
16
- export function assertMasterDataEditable(area: MasterDataArea): void {
17
- if (!isMasterDataEditable(area)) {
36
+ /**
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
+ */
55
+ export async function assertMasterDataEditable(event: H3Event, area: MasterDataArea): Promise<void> {
56
+ if (!await isMasterDataEditable(event, area)) {
57
+ throw createError({
58
+ statusCode: 403,
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)) {
18
66
  throw createError({
19
67
  statusCode: 403,
20
- message: `This storefront does not change ${area}: they are maintained by the merchant.`,
68
+ message: `Your role does not allow changing this: ${area}.`,
69
+ data: { type: "permission_missing", permission },
21
70
  });
22
71
  }
23
72
  }
@@ -0,0 +1,82 @@
1
+ import type { H3Event } from "h3";
2
+ import type { AuthRole, StoredSession } from "../../app/interfaces/auth";
3
+ import type { AuthLoginResult } from "../interfaces/auth";
4
+ import type { CustomersPermissionAnswer } from "./buyerIdentity";
5
+ import { grantsFrom } from "./buyerIdentity";
6
+
7
+ /**
8
+ * Signing in without a password: a mailed link, or a mailed code.
9
+ *
10
+ * Both are two calls — ask for the secret, then hand it back — and both end in
11
+ * the same session as a password sign-in, which is why the cookie is written
12
+ * here rather than twice. The customers app serves both and shapes which are
13
+ * offered (`login_magic_link`, `login_email_otp`); the shop only ever offers what
14
+ * the merchant switched on, because the app refuses the rest.
15
+ *
16
+ * One property of the mailed link is worth stating: an address nobody holds gets
17
+ * an account rather than an error, so it is a registration path as much as a
18
+ * sign-in one. The shop must not therefore tell a visitor whether an address is
19
+ * known — that would turn the form into a way of asking.
20
+ */
21
+
22
+ interface ApiSession {
23
+ $id: string;
24
+ expire: string;
25
+ userId: string;
26
+ }
27
+
28
+ interface ApiContact {
29
+ id: string;
30
+ email: string;
31
+ first_name?: string | null;
32
+ last_name?: string | null;
33
+ role?: string | null;
34
+ organization_id?: string | null;
35
+ active?: boolean | null;
36
+ }
37
+
38
+ const KNOWN_ROLES = new Set<AuthRole>(["buyer", "approver", "admin", "requester"]);
39
+
40
+ const roleOf = (role?: string | null): AuthRole | undefined =>
41
+ role && KNOWN_ROLES.has(role as AuthRole) ? (role as AuthRole) : undefined;
42
+
43
+ const nameOf = (contact: ApiContact | null, fallback: string): string =>
44
+ [contact?.first_name, contact?.last_name].filter(Boolean).join(" ") || contact?.email || fallback;
45
+
46
+ /** Turn a confirmed secret into the same session a password sign-in produces. */
47
+ export function completeSignIn(
48
+ event: H3Event,
49
+ session: ApiSession,
50
+ contact: ApiContact | null,
51
+ fallbackEmail: string,
52
+ permissions?: CustomersPermissionAnswer | null,
53
+ ): AuthLoginResult {
54
+ const stored: StoredSession = {
55
+ id: session.$id,
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).
59
+ userId: session.userId,
60
+ };
61
+ setCookie(event, SESSION_COOKIE_NAME, JSON.stringify(stored), sessionCookieOptions(session.expire));
62
+
63
+ return {
64
+ user: {
65
+ $id: session.userId,
66
+ name: nameOf(contact, fallbackEmail),
67
+ email: contact?.email ?? fallbackEmail,
68
+ role: roleOf(contact?.role),
69
+ ...(contact?.id ? { contactId: contact.id } : {}),
70
+ ...(contact?.organization_id ? { organizationId: contact.organization_id } : {}),
71
+ ...grantsFrom(permissions, contact),
72
+ },
73
+ session: { id: session.$id, expire: session.expire },
74
+ ...(contact?.id ? { contactId: contact.id } : {}),
75
+ };
76
+ }
77
+
78
+ export type PasswordlessConfirm = {
79
+ session: ApiSession;
80
+ contact: ApiContact | null;
81
+ permissions?: CustomersPermissionAnswer | null;
82
+ };
@@ -0,0 +1,175 @@
1
+ import type { H3Event } from "h3";
2
+ import type { PendingApproval } from "../../app/interfaces/account/approvals";
3
+
4
+ /**
5
+ * The approvals waiting on one person.
6
+ *
7
+ * Asked two ways because the procurement app records an approver two ways: by the
8
+ * contact themselves, and by the role they hold. A queue that asked only the first
9
+ * would be empty for every organisation that approves by role, which is most of
10
+ * them.
11
+ *
12
+ * Each layer is enriched with the request behind it, because an approver deciding
13
+ * on "layer 2 of 3" and nothing else is being asked to sign for a number they
14
+ * cannot see.
15
+ */
16
+ interface LivePendingApproval {
17
+ id: string;
18
+ purchase_request_id?: string | null;
19
+ cost_center_code?: string | null;
20
+ sequence?: number | null;
21
+ status?: string | null;
22
+ created_at?: string | null;
23
+ }
24
+
25
+ interface LivePurchaseRequest {
26
+ id: string;
27
+ number?: string | null;
28
+ total?: number | string | null;
29
+ currency?: string | null;
30
+ requested_by?: string | null;
31
+ contact_id?: string | null;
32
+ organization_id?: string | null;
33
+ }
34
+
35
+ export async function listPendingApprovals(
36
+ event: H3Event,
37
+ actor: { contactId?: string; role?: string; organizationId?: string },
38
+ ): Promise<PendingApproval[]> {
39
+ const sdk = useRevenexxSdk();
40
+
41
+ const queries: Array<{ byRole: boolean; query: Record<string, string | number> }> = [];
42
+ if (actor.contactId) {
43
+ queries.push({ byRole: false, query: { approver_contact_id: actor.contactId, status: "pending", limit: 100 } });
44
+ }
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 } });
51
+ }
52
+ if (queries.length === 0) {
53
+ return [];
54
+ }
55
+
56
+ const rows = new Map<string, LivePendingApproval>();
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) {
60
+ try {
61
+ const answer = await sdk.call<{ items?: LivePendingApproval[]; pending_approvals?: LivePendingApproval[] }>(
62
+ "GET",
63
+ "/v1/procurement/pending-approvals",
64
+ { query: { ...query, order: "created_at.asc" } },
65
+ );
66
+ for (const row of answer.items ?? answer.pending_approvals ?? []) {
67
+ // A layer can match both ways; it is one thing waiting, not two.
68
+ rows.set(row.id, row);
69
+ if (!byRole) {
70
+ named.add(row.id);
71
+ }
72
+ }
73
+ }
74
+ catch (err) {
75
+ getLogService().error("Pending approvals unavailable", apiErrorContext(err));
76
+ }
77
+ }
78
+
79
+ // The request behind each layer, read once per request rather than per layer.
80
+ const requestIds = [...new Set([...rows.values()].map(r => r.purchase_request_id).filter(Boolean))] as string[];
81
+ const requests = new Map<string, LivePurchaseRequest>();
82
+ for (const id of requestIds) {
83
+ try {
84
+ const request = await sdk.call<LivePurchaseRequest>("GET", `/v1/procurement/purchase-requests/${id}`);
85
+ requests.set(id, request);
86
+ }
87
+ catch (err) {
88
+ // A layer whose request cannot be read is still shown: the approver needs
89
+ // to know it is waiting, even where the figure is missing.
90
+ getLogService().error(`Purchase request ${id} unavailable`, apiErrorContext(err));
91
+ }
92
+ }
93
+
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) => {
106
+ const request = row.purchase_request_id ? requests.get(row.purchase_request_id) : undefined;
107
+ const total = request?.total == null ? null : Number(request.total);
108
+ return {
109
+ id: row.id,
110
+ requestId: row.purchase_request_id ?? "",
111
+ requestNumber: request?.number ?? null,
112
+ requestedBy: request?.requested_by ?? request?.contact_id ?? null,
113
+ // Zero is not a figure here: the app leaves the total unset on the
114
+ // records this tenant keeps (RX-795), and a confident 0,00 € beside a
115
+ // signature is worse than an honest blank.
116
+ total: total && total > 0 ? total : null,
117
+ currency: request?.currency ?? null,
118
+ costCentreCode: row.cost_center_code ?? null,
119
+ layer: Number(row.sequence ?? 1),
120
+ at: row.created_at ?? "",
121
+ };
122
+ });
123
+ }
124
+
125
+ /**
126
+ * Pass one approver's decision to the app.
127
+ *
128
+ * Both directions in one place because they differ in exactly one word and in
129
+ * nothing else that matters: the same guard, the same refusals, the same reason.
130
+ * A decline ends the request; an approval unlocks the next layer.
131
+ */
132
+ export async function decidePendingApproval(
133
+ event: H3Event,
134
+ decision: "approve" | "decline",
135
+ ): Promise<{ ok: true }> {
136
+ const id = getRouterParam(event, "id") ?? "";
137
+ const body = await readBody<{ reason?: string }>(event).catch(() => ({} as { reason?: string }));
138
+
139
+ const user = await getAuthService(event).me(event);
140
+ if (!user) {
141
+ throw createError({ statusCode: 401, message: "Unauthorized" });
142
+ }
143
+ if (!isProcurementLive(event)) {
144
+ throw createError({ statusCode: 501, message: "This storefront does not decide approvals on demo data" });
145
+ }
146
+
147
+ // Only what is actually waiting on this person. The app knows who may decide,
148
+ // and asking it first means a link somebody was sent cannot be used by
149
+ // somebody else — the alternative is trusting the id in the address.
150
+ const mine = await listPendingApprovals(event, {
151
+ ...(user.contactId ? { contactId: user.contactId } : {}),
152
+ ...(user.role ? { role: user.role } : {}),
153
+ ...(user.organizationId ? { organizationId: user.organizationId } : {}),
154
+ });
155
+ if (!mine.some(approval => approval.id === id)) {
156
+ throw createError({ statusCode: 404, message: "No such approval is waiting on you" });
157
+ }
158
+
159
+ const reason = body?.reason?.trim();
160
+ try {
161
+ await useRevenexxSdk().call("POST", `/v1/procurement/pending-approvals/${id}/${decision}`, {
162
+ body: reason ? { reason } : {},
163
+ });
164
+ return { ok: true };
165
+ }
166
+ catch (err) {
167
+ // 409 is the layer having been decided since the page was drawn — by a
168
+ // deputy, or by this approver in another tab. The buyer's to read.
169
+ if (err instanceof RevenexxException && [400, 409, 422].includes(err.code)) {
170
+ throw createError({ statusCode: 422, message: err.message });
171
+ }
172
+ getLogService().error(`Deciding approval ${id} failed`, apiErrorContext(err));
173
+ throw createError({ statusCode: 502, message: "Procurement service unavailable" });
174
+ }
175
+ }
@@ -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. */
@@ -1,5 +1,6 @@
1
1
  import { PromotionsRedemptionsReleaseReason } from "@revenexx/sdk";
2
2
  import type { H3Event } from "h3";
3
+ import type { AvailableOffer } from "../../app/interfaces/offers";
3
4
 
4
5
  /**
5
6
  * The promotions domain has no service class — the cart endpoint branches on
@@ -275,3 +276,92 @@ export async function releaseRedemption(
275
276
  getLogService().error("Promotion release failed — the hold will expire", apiErrorContext(err));
276
277
  }
277
278
  }
279
+
280
+ /* ------------------------------------------------------------------ */
281
+ /* What a buyer could still get */
282
+ /* ------------------------------------------------------------------ */
283
+
284
+ /** The promotions app's own shape for an offer this buyer has not earned yet. */
285
+ export interface LiveAvailablePromotion {
286
+ promotion_id: string;
287
+ code?: string | null;
288
+ name?: string | null;
289
+ needs_code?: boolean;
290
+ already_met?: boolean;
291
+ distance?: { subject?: string; missing?: number; required?: number } | null;
292
+ }
293
+
294
+ /**
295
+ * The offers this buyer could still reach, with how far away each one is.
296
+ *
297
+ * Read-only and cheap: it writes nothing and holds nothing, so a storefront may
298
+ * ask it on every cart change the way it asks for the cart's own total.
299
+ *
300
+ * Fails soft to an empty list. An offer nobody can see costs a shop a larger
301
+ * order; an error page costs it the order.
302
+ */
303
+ export async function liveAvailableOffers(
304
+ event: H3Event,
305
+ input: {
306
+ currency: string;
307
+ subtotal: number;
308
+ itemCount?: number;
309
+ contactId?: string;
310
+ organizationId?: string;
311
+ },
312
+ ): Promise<{ offers: AvailableOffer[]; total: number }> {
313
+ try {
314
+ const answer = await useRevenexxSdk().call<{
315
+ promotions?: LiveAvailablePromotion[];
316
+ total?: number;
317
+ }>("POST", "/v1/promotions/available", {
318
+ body: {
319
+ currency: input.currency,
320
+ subtotal: input.subtotal,
321
+ ...(typeof input.itemCount === "number" ? { item_count: input.itemCount } : {}),
322
+ ...(input.contactId ? { contact_id: input.contactId } : {}),
323
+ ...(input.organizationId ? { organization_id: input.organizationId } : {}),
324
+ },
325
+ });
326
+ const offers = (answer.promotions ?? [])
327
+ .map(mapOffer)
328
+ .filter((offer): offer is AvailableOffer => offer !== null);
329
+ return { offers, total: Number(answer.total ?? offers.length) };
330
+ }
331
+ catch (err) {
332
+ getLogService().error("Available offers unavailable", apiErrorContext(err));
333
+ return { offers: [], total: 0 };
334
+ }
335
+ }
336
+
337
+ /**
338
+ * One offer in the shop's words.
339
+ *
340
+ * An offer with no name is dropped rather than shown as a blank row: the name is
341
+ * the whole of what a buyer reads, and the merchant is the one who writes it.
342
+ */
343
+ export function mapOffer(promotion: LiveAvailablePromotion): AvailableOffer | null {
344
+ const name = promotion.name?.trim();
345
+ if (!promotion.promotion_id || !name) {
346
+ return null;
347
+ }
348
+ const reached = promotion.already_met === true;
349
+ const distance = promotion.distance;
350
+ // Only a distance the buyer can act on. The app leaves it null where the
351
+ // unmet condition is not a number, and "somewhere between here and there"
352
+ // is not a thing to put in front of somebody.
353
+ const missing = !reached && distance && typeof distance.missing === "number" && distance.missing > 0
354
+ ? {
355
+ kind: distance.subject === "item_count" ? "quantity" as const : "value" as const,
356
+ amount: distance.missing,
357
+ required: Number(distance.required ?? 0),
358
+ }
359
+ : undefined;
360
+ return {
361
+ id: promotion.promotion_id,
362
+ name,
363
+ reached,
364
+ needsCode: promotion.needs_code === true,
365
+ ...(missing ? { missing } : {}),
366
+ };
367
+ }