@revenexx/cover 0.10.1 → 0.12.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 (115) 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/carts/AccountCartsTable.vue +4 -2
  6. package/app/components/account/dashboard/AccountDashboardKpis.vue +74 -34
  7. package/app/components/account/dashboard/AccountDashboardQuickActions.vue +24 -6
  8. package/app/components/account/organization/AccountOrganization.vue +3 -1
  9. package/app/components/account/team/AccountTeam.vue +32 -7
  10. package/app/components/auth/AuthForgotPasswordPanel.vue +9 -4
  11. package/app/components/auth/AuthLoginPanel.vue +75 -18
  12. package/app/components/auth/AuthRegisterPanel.vue +1 -1
  13. package/app/components/cart/actions/CartSaveToListModal.vue +5 -0
  14. package/app/components/cart/item/CartItem.vue +17 -75
  15. package/app/components/cart/position/CartPosition.vue +17 -30
  16. package/app/components/cart/quote/CartQuoteRequestModal.vue +9 -1
  17. package/app/components/cart/switcher/CartSwitcher.vue +5 -2
  18. package/app/components/category/view/GridView.vue +10 -1
  19. package/app/components/category/view/ListView.vue +10 -1
  20. package/app/components/checkout/confirmation/CheckoutConfirmationActions.vue +2 -0
  21. package/app/components/checkout/onepage/CheckoutAddressSection.vue +4 -4
  22. package/app/components/checkout/onepage/CheckoutDeliverySection.vue +18 -2
  23. package/app/components/checkout/onepage/CheckoutGate.vue +2 -0
  24. package/app/components/checkout/onepage/CheckoutOnePageView.vue +1 -1
  25. package/app/components/checkout/onepage/CheckoutPaymentSection.vue +10 -0
  26. package/app/components/checkout/onepage/CheckoutSummarySection.vue +7 -1
  27. package/app/components/layout/Region.vue +13 -0
  28. package/app/components/layout/footer/Footer.vue +8 -0
  29. package/app/components/layout/header/AppBar.vue +4 -3
  30. package/app/components/layout/header/MainNav.vue +3 -3
  31. package/app/components/listing/ListingResults.vue +3 -1
  32. package/app/components/product/card/Compact.vue +10 -1
  33. package/app/components/product/detail/ProductDetailAddToCart.vue +51 -18
  34. package/app/components/product/detail/ProductDetailIdentity.vue +1 -1
  35. package/app/components/product/detail/ProductDetailPriceRequest.vue +1 -1
  36. package/app/components/product/detail/ProductDetailSaveToList.vue +10 -0
  37. package/app/composables/useAccountDashboard.ts +0 -10
  38. package/app/composables/useAccountNavigation.ts +35 -0
  39. package/app/composables/useAuthStore.ts +6 -2
  40. package/app/composables/useCategoryListing.ts +6 -0
  41. package/app/composables/useCheckoutOnePage.ts +21 -2
  42. package/app/composables/useMasterDataEditable.ts +23 -0
  43. package/app/composables/useProductCard.ts +29 -2
  44. package/app/composables/useProductListing.ts +79 -0
  45. package/app/composables/useQuantityStepper.ts +90 -0
  46. package/app/composables/useQuickActions.ts +35 -0
  47. package/app/composables/useRoleGrants.ts +32 -0
  48. package/app/composables/useSearchListing.ts +4 -0
  49. package/app/composables/useThemeEvents.ts +144 -0
  50. package/app/config/accountDashboard.ts +26 -0
  51. package/app/config/quickActions.ts +40 -5
  52. package/app/interfaces/account/dashboard.ts +2 -0
  53. package/app/interfaces/auth.ts +25 -4
  54. package/app/interfaces/quantity-stepper.ts +17 -0
  55. package/app/interfaces/shopSettings.ts +84 -0
  56. package/app/layouts/default.vue +19 -10
  57. package/app/layouts/focus.vue +28 -7
  58. package/app/middleware/checkout-guard.ts +7 -1
  59. package/app/pages/punchout/transfer.vue +22 -0
  60. package/app/plugins/theme-events.client.ts +132 -0
  61. package/app/shared/themeEvents.ts +445 -0
  62. package/i18n/locales/de/account.json +7 -0
  63. package/i18n/locales/de/auth.json +42 -2
  64. package/i18n/locales/de/cart.json +4 -2
  65. package/i18n/locales/de/checkout.json +2 -1
  66. package/i18n/locales/de/common.json +2 -0
  67. package/i18n/locales/de/cover.json +44 -0
  68. package/i18n/locales/de/editor.json +47 -1
  69. package/i18n/locales/en/account.json +7 -0
  70. package/i18n/locales/en/auth.json +42 -2
  71. package/i18n/locales/en/cart.json +4 -2
  72. package/i18n/locales/en/checkout.json +2 -1
  73. package/i18n/locales/en/common.json +2 -0
  74. package/i18n/locales/en/cover.json +44 -0
  75. package/i18n/locales/en/editor.json +47 -1
  76. package/nuxt.config.ts +15 -1
  77. package/package.json +5 -2
  78. package/server/api/account/orders/[id]/cancel.post.ts +1 -1
  79. package/server/api/account/orders/[id]/messages.get.ts +1 -1
  80. package/server/api/account/orders/[id]/messages.post.ts +1 -1
  81. package/server/api/account/orders/[id]/return.post.ts +1 -0
  82. package/server/api/account/orders/[id].get.ts +1 -1
  83. package/server/api/account/pending-approvals/index.get.ts +1 -0
  84. package/server/api/account/profile.get.ts +3 -1
  85. package/server/api/auth/login.post.ts +22 -3
  86. package/server/api/auth/magic-link.put.ts +6 -1
  87. package/server/api/auth/otp.put.ts +6 -1
  88. package/server/api/carts/[id]/activate.post.ts +8 -0
  89. package/server/api/carts/[id]/index.delete.ts +3 -0
  90. package/server/api/carts/[id]/index.put.ts +1 -0
  91. package/server/api/carts/[id]/items.post.ts +1 -0
  92. package/server/api/carts/index.post.ts +4 -0
  93. package/server/api/orders/index.post.ts +33 -0
  94. package/server/api/quick-actions.get.ts +6 -38
  95. package/server/interfaces/auth.ts +10 -1
  96. package/server/middleware/buyer-principal.ts +18 -0
  97. package/server/routes/punchout/start.get.ts +6 -15
  98. package/server/services/ApiAddressBookService.ts +43 -1
  99. package/server/services/ApiAuthService.ts +119 -22
  100. package/server/services/ApiCartService.ts +67 -32
  101. package/server/services/ApiOrganizationService.ts +7 -2
  102. package/server/services/ApiTeamService.ts +93 -21
  103. package/server/services/MockAuthService.ts +21 -2
  104. package/server/utils/buyerIdentity.ts +168 -0
  105. package/server/utils/cartOwnership.ts +67 -0
  106. package/server/utils/liveOrderLists.ts +50 -23
  107. package/server/utils/liveOrders.ts +39 -24
  108. package/server/utils/livePrices.ts +7 -15
  109. package/server/utils/masterData.ts +29 -0
  110. package/server/utils/passwordlessSignIn.ts +13 -4
  111. package/server/utils/pendingApprovals.ts +29 -7
  112. package/server/utils/procurementCheckout.ts +2 -0
  113. package/server/utils/quickActionCatalogue.ts +53 -0
  114. package/server/utils/revenexxSdk.ts +116 -2
  115. package/server/utils/shopSettings.ts +5 -0
@@ -450,6 +450,27 @@ export default defineEventHandler(async (event) => {
450
450
  }
451
451
 
452
452
  const placed = outcome.order;
453
+
454
+ // An attributed buyer (RAD-155) whose role only REQUESTS orders,
455
+ // or whose order is above the merchant's approval threshold, gets
456
+ // a pending order back rather than a placed one. Nothing is bought
457
+ // yet: no payment is taken and no promotion is spent until
458
+ // somebody approves it — the same answer a procurement request
459
+ // gets above.
460
+ if (placed.status === "pending") {
461
+ if (reserved === "held" && cartId) {
462
+ await releaseRedemption(event, { cartId, reason: PromotionsRedemptionsReleaseReason.CartReleased });
463
+ }
464
+ return {
465
+ orderId: placed.number,
466
+ status: "approval-pending",
467
+ createdAt: new Date().toISOString(),
468
+ payment,
469
+ approvalRequired: true,
470
+ approvers: [],
471
+ };
472
+ }
473
+
453
474
  orderId = placed.number;
454
475
  liveOrderUuid = placed.id;
455
476
  liveOrderTotal = typeof placed.grand_total === "number" ? placed.grand_total : null;
@@ -479,6 +500,18 @@ export default defineEventHandler(async (event) => {
479
500
  if (err instanceof RevenexxException && (err.code === 400 || err.code === 422)) {
480
501
  throw createError({ status: 422, message: err.message });
481
502
  }
503
+ // The buyer's role neither places nor requests orders (a viewer,
504
+ // a blocked contact, a role the merchant narrowed). The gateway or
505
+ // the orders app says so with a 403 once the call is attributed
506
+ // (RAD-155) — that is the buyer's answer, not an outage.
507
+ if (err instanceof RevenexxException && err.code === 403) {
508
+ throw createError({
509
+ status: 403,
510
+ statusMessage: "Your account may not place orders",
511
+ message: "Your account may not place orders.",
512
+ data: { type: "permission_missing", permission: "orders.create" },
513
+ });
514
+ }
482
515
  getLogService().error("Order placement failed", apiErrorContext(err));
483
516
  throw createError({ status: 502, message: "Order service unavailable" });
484
517
  }
@@ -1,43 +1,11 @@
1
- import { quickActions } from "../../app/config/quickActions";
2
-
3
1
  /**
4
- * The shortcut catalogue behind the `quick_actions` block, with its i18n keys
5
- * already resolved.
6
- *
7
- * This exists for the blökkli picker overlay: that component is compiled
8
- * through the editor's own runtime pipeline, so it has neither Nuxt's `$fetch`
9
- * nor `useI18n()` and cannot translate a key itself. The block on the page does
10
- * NOT call this — it holds the same registry and resolves the keys through
11
- * `useI18n()` with no round-trip.
2
+ * The full shortcut catalogue behind the `quick_actions` block, with its i18n
3
+ * keys already resolved — see `loadQuickActionCatalogue`. Themes that know a
4
+ * tenant's account navigation serve a narrowed catalogue of their own (the
5
+ * Blokkli theme: /api/blokkli/quick-actions); this one is the unfiltered layer
6
+ * default.
12
7
  *
13
8
  * Static config, not a BFF domain: no service interface, no app.config registry
14
9
  * key, nothing to switch between mock and live.
15
10
  */
16
-
17
- /**
18
- * `serverT` scopes a key to one locale FILE, but the registry's keys span two
19
- * (`header.cart` lives in common.json, the rest in account.json). A miss
20
- * returns the key unchanged, which is the signal to try the next namespace.
21
- */
22
- const NAMESPACES = ["account", "common"];
23
-
24
- function translate(key: string, locale: string): string {
25
- for (const namespace of NAMESPACES) {
26
- const value = serverT(key, locale, namespace);
27
- if (value !== key) {
28
- return value;
29
- }
30
- }
31
- return key;
32
- }
33
-
34
- export default defineEventHandler(async (event) => {
35
- const locale = resolveLocale(event);
36
- await preloadLocaleNamespaces(locale, NAMESPACES);
37
-
38
- return quickActions.map(action => ({
39
- id: action.id,
40
- label: translate(action.labelKey, locale),
41
- description: translate(action.descriptionKey, locale),
42
- }));
43
- });
11
+ export default defineEventHandler(event => loadQuickActionCatalogue(event));
@@ -6,6 +6,10 @@ export interface AuthPersona {
6
6
  readonly id: string;
7
7
  readonly name: string;
8
8
  readonly email: string;
9
+ /** Demo only: lets the persona sign in by username where the shop takes one. */
10
+ readonly username?: string;
11
+ /** Demo only: the persona's company customer number, likewise. */
12
+ readonly customerNumber?: string;
9
13
  readonly role: AuthRole;
10
14
  readonly description: string;
11
15
  }
@@ -26,7 +30,12 @@ export interface AuthLoginResult {
26
30
  * auth flow (store, guards, middleware) is identical.
27
31
  */
28
32
  export interface IAuthService {
29
- login(event: H3Event, email: string, password: string): Promise<AuthLoginResult>;
33
+ /**
34
+ * `identifier` is an address, a username or a customer number — whichever
35
+ * the shop accepts (customers.login_identifier_*). A kind it does not
36
+ * accept is refused with `identifier_not_offered`.
37
+ */
38
+ login(event: H3Event, identifier: string, password: string): Promise<AuthLoginResult>;
30
39
  me(event: H3Event): Promise<AuthUser | null>;
31
40
  logout(event: H3Event): Promise<void>;
32
41
  }
@@ -0,0 +1,18 @@
1
+ import { getCookie } from "h3";
2
+
3
+ /**
4
+ * Resolve the signed-in buyer before any BFF handler runs (RAD-155).
5
+ *
6
+ * Every live service reads the buyer's contact and organization synchronously
7
+ * (sessionOrderRefs), and every SDK call puts the contact on the wire as its
8
+ * principal — both from what the identity service verified for THIS request,
9
+ * never from the cookie. Doing it here, once, is what makes both true for
10
+ * every route instead of only for the routes that remembered to ask.
11
+ * Which paths: needsVerifiedBuyer.
12
+ */
13
+ export default defineEventHandler(async (event) => {
14
+ if (!needsVerifiedBuyer(event.path) || !getCookie(event, SESSION_COOKIE_NAME)) {
15
+ return;
16
+ }
17
+ await getAuthService(event).me(event);
18
+ });
@@ -108,9 +108,9 @@ export default defineEventHandler(async (event) => {
108
108
  const stored: StoredSession = {
109
109
  id: session.$id,
110
110
  expire: session.expire,
111
+ // The contact and organization are not written: the browser can rewrite
112
+ // this cookie, so they are re-resolved per request (RAD-155).
111
113
  userId: session.userId,
112
- ...(signedIn.contact?.id ? { contactId: signedIn.contact.id } : {}),
113
- ...(signedIn.contact?.organization_id ? { organizationId: signedIn.contact.organization_id } : {}),
114
114
  };
115
115
  setCookie(event, SESSION_COOKIE_NAME, JSON.stringify(stored), sessionCookieOptions(session.expire));
116
116
 
@@ -127,19 +127,10 @@ export default defineEventHandler(async (event) => {
127
127
  };
128
128
  setPunchoutVisit(event, visit);
129
129
 
130
- // A visit the external system opened WITH a cart names it, and a `WKS`
131
- // import always creates a new one — so the buyer is put on that cart
132
- // rather than on whatever the shop would otherwise call "the" cart.
133
- if (visit.cartId) {
134
- try {
135
- await getCartManager(event)?.activateCart(event, visit.cartId);
136
- }
137
- catch (err) {
138
- // The cart exists and the visit names it; failing to make it the
139
- // active one is worth a line in the log, not a refused visit.
140
- getLogService().error("Punchout cart activation failed", toErrorContext(err));
141
- }
142
- }
130
+ // There is deliberately no "make the visit's cart the current one" here:
131
+ // the cart service addresses `visit.cartId` directly for the whole visit.
132
+ // Activating it would flip the contact's `is_current` — which every other
133
+ // visit and the contact's ordinary sessions resolve "the" cart by (RAD-109).
143
134
 
144
135
  // The locale prefix is applied last, because the decision above is about
145
136
  // WHERE the buyer goes and this is about how this storefront spells it.
@@ -57,7 +57,8 @@ function toAccountAddress(row: ApiAddressRow, companyFallback = ""): AccountAddr
57
57
  /**
58
58
  * Live address book: the signed-in buyer's addresses in the customers app —
59
59
  * their own AND their company's, because in B2B the delivery addresses belong
60
- * to the company. Both references come from the session cookie; guests have no
60
+ * to the company. Both references are the ones the identity service verified
61
+ * for this request (RAD-155), never ids the browser supplied; guests have no
61
62
  * address book. The customers schema requires ISO 3166-1 alpha-2 countries.
62
63
  */
63
64
  export class ApiAddressBookService implements IAddressBookService {
@@ -86,6 +87,33 @@ export class ApiAddressBookService implements IAddressBookService {
86
87
  }
87
88
  }
88
89
 
90
+ /**
91
+ * Refuse a change to an address that is neither the buyer's own nor their
92
+ * company's. The id comes from the URL, so without this any buyer could
93
+ * rewrite or delete any address they could name (RAD-155). Somebody else's
94
+ * address is answered exactly like one that does not exist.
95
+ */
96
+ private async requireOwnAddress(event: H3Event, id: string): Promise<void> {
97
+ const { contact_id, organization_id } = this.contactRef(event);
98
+ let row: ApiAddressRow | null = null;
99
+ try {
100
+ row = await useRevenexxSdk().customersOrganizations.customersAddressesGet({ id }) as unknown as ApiAddressRow;
101
+ }
102
+ catch (err) {
103
+ if (!(err instanceof RevenexxException && (err.code === 404 || err.code === 403))) {
104
+ getLogService().error("API request failed: addresses/get", apiErrorContext(err));
105
+ throw createError({ statusCode: 502, statusMessage: "Address service unavailable" });
106
+ }
107
+ }
108
+ const own = !!row && (
109
+ (!!contact_id && row.contact_id === contact_id)
110
+ || (!!organization_id && row.organization_id === organization_id)
111
+ );
112
+ if (!own) {
113
+ throw createError({ statusCode: 404, statusMessage: "Address not found" });
114
+ }
115
+ }
116
+
89
117
  private requireContact(event: H3Event): string {
90
118
  const { contact_id } = this.contactRef(event);
91
119
  if (!contact_id) {
@@ -166,6 +194,10 @@ export class ApiAddressBookService implements IAddressBookService {
166
194
  return toAccountAddress(row);
167
195
  }
168
196
  catch (err) {
197
+ const refused = selfServiceRefusal(err);
198
+ if (refused) {
199
+ throw refused;
200
+ }
169
201
  if (err instanceof RevenexxException && (err.code === 400 || err.code === 422)) {
170
202
  throw createError({ statusCode: 422, message: err.message });
171
203
  }
@@ -176,6 +208,7 @@ export class ApiAddressBookService implements IAddressBookService {
176
208
 
177
209
  async update(event: H3Event, id: string, input: AccountAddressFormState): Promise<AccountAddress> {
178
210
  this.requireContact(event);
211
+ await this.requireOwnAddress(event, id);
179
212
  try {
180
213
  const row = await useRevenexxSdk().customersOrganizations.customersAddressesUpdate({
181
214
  id,
@@ -191,6 +224,10 @@ export class ApiAddressBookService implements IAddressBookService {
191
224
  return toAccountAddress(row);
192
225
  }
193
226
  catch (err) {
227
+ const refused = selfServiceRefusal(err);
228
+ if (refused) {
229
+ throw refused;
230
+ }
194
231
  if (err instanceof RevenexxException && (err.code === 400 || err.code === 422)) {
195
232
  throw createError({ statusCode: 422, message: err.message });
196
233
  }
@@ -201,10 +238,15 @@ export class ApiAddressBookService implements IAddressBookService {
201
238
 
202
239
  async remove(event: H3Event, id: string): Promise<AccountAddress[]> {
203
240
  this.requireContact(event);
241
+ await this.requireOwnAddress(event, id);
204
242
  try {
205
243
  await useRevenexxSdk().customersOrganizations.customersAddressesDelete({ id });
206
244
  }
207
245
  catch (err) {
246
+ const refused = selfServiceRefusal(err);
247
+ if (refused) {
248
+ throw refused;
249
+ }
208
250
  getLogService().error("API request failed: addresses/delete", apiErrorContext(err));
209
251
  throw createError({ statusCode: 502, statusMessage: "Address service unavailable" });
210
252
  }
@@ -1,7 +1,10 @@
1
1
  import type { H3Event } from "h3";
2
2
 
3
3
  import type { AuthRole, AuthUser, StoredSession } from "../../app/interfaces/auth";
4
+ import { loginIdentifierKind } from "../../app/interfaces/shopSettings";
4
5
  import type { AuthLoginResult, IAuthService } from "../interfaces/auth";
6
+ import type { CustomersPermissionAnswer } from "../utils/buyerIdentity";
7
+ import { forgetVerifiedBuyer, grantsFrom, rememberVerifiedBuyer } from "../utils/buyerIdentity";
5
8
 
6
9
  /** Session payload of the customers app's auth passthrough. */
7
10
  interface ApiSession {
@@ -20,19 +23,62 @@ interface ApiContact {
20
23
  role?: string | null;
21
24
  organization_id?: string | null;
22
25
  /**
23
- * False for a contact that is blocked, pending or rejected. The customers app
24
- * answers it on every read and shapes the permission set to match; the shop
25
- * carries it through so a surface can say why rather than showing a wall.
26
+ * Legacy: a contact row carries `status`, not `active` — the may-act flag is
27
+ * on the permission answer beside it (see grantsFrom). Read as a fallback.
26
28
  */
27
29
  active?: boolean | null;
28
30
  }
29
31
 
32
+ /** What auth/me answers. */
33
+ interface ApiMeAnswer {
34
+ user: { $id: string; name?: string; email: string };
35
+ contact: ApiContact | null;
36
+ permissions?: CustomersPermissionAnswer | null;
37
+ }
38
+
39
+ /** The verified identity of one request, resolved at most once per request. */
40
+ const ME_KEY = "coverApiAuthMe";
41
+
42
+ /**
43
+ * A short cross-request memory of verified answers, keyed by tenant + user +
44
+ * session. A signed-in page fans out into a handful of BFF calls, and each of
45
+ * them now needs the verified buyer; without this every one of them would
46
+ * ask auth/me again within the same second. Only answers the identity service
47
+ * GAVE are kept, so a key a browser forges finds nothing it did not already
48
+ * prove — and a block or a revoked session is seen within the TTL.
49
+ */
50
+ const VERIFIED_TTL_MS = 10_000;
51
+ const VERIFIED_MAX = 1000;
52
+ const verified = new Map<string, { user: AuthUser; until: number }>();
53
+
54
+ function rememberAcrossRequests(key: string, user: AuthUser): void {
55
+ if (verified.size >= VERIFIED_MAX) {
56
+ const oldest = verified.keys().next().value;
57
+ if (oldest !== undefined) {
58
+ verified.delete(oldest);
59
+ }
60
+ }
61
+ verified.set(key, { user, until: Date.now() + VERIFIED_TTL_MS });
62
+ }
63
+
64
+ /** Test seam: forget every remembered answer. */
65
+ export function clearVerifiedSessions(): void {
66
+ verified.clear();
67
+ }
68
+
30
69
  const KNOWN_ROLES = new Set<AuthRole>(["buyer", "approver", "admin", "requester"]);
31
70
 
32
71
  function toAuthRole(role?: string | null): AuthRole | undefined {
33
72
  return role && KNOWN_ROLES.has(role as AuthRole) ? (role as AuthRole) : undefined;
34
73
  }
35
74
 
75
+ /** What the customers app's login takes, for every version that serves it. */
76
+ export function loginBody(identifier: string, password: string): Record<string, string> {
77
+ return loginIdentifierKind(identifier) === "email"
78
+ ? { identifier, email: identifier, password }
79
+ : { identifier, password };
80
+ }
81
+
36
82
  function contactName(contact: ApiContact | null, fallback: string): string {
37
83
  const name = [contact?.first_name, contact?.last_name].filter(Boolean).join(" ").trim();
38
84
  return name || fallback;
@@ -40,7 +86,7 @@ function contactName(contact: ApiContact | null, fallback: string): string {
40
86
 
41
87
  /**
42
88
  * Live authentication via the public revenexx API (customers app):
43
- * customersAuthLogin → platform session (incl. secret) + contact
89
+ * auth/login (raw call) → platform session (incl. secret) + contact
44
90
  * auth/me (raw call) → platform user + contact
45
91
  * customersAuthLogout → revokes the platform session
46
92
  *
@@ -49,34 +95,65 @@ function contactName(contact: ApiContact | null, fallback: string): string {
49
95
  * session secret stays server-side only — the BFF never forwards it.
50
96
  */
51
97
  export class ApiAuthService implements IAuthService {
52
- async login(event: H3Event, email: string, password: string): Promise<AuthLoginResult> {
53
- const { session, contact } = await useRevenexxSdk().customers.customersAuthLogin({ email, password }) as unknown as {
98
+ async login(event: H3Event, identifier: string, password: string): Promise<AuthLoginResult> {
99
+ // Raw call: the generated customersAuthLogin() of @revenexx/sdk 0.2.0
100
+ // only knows `email` and refuses to send without it. customers 1.1.2
101
+ // declares `identifier` and keeps `email` as an alias, so `identifier`
102
+ // always goes — and `email` beside it only when the value IS an address,
103
+ // which is all a customers app older than the identifier can sign in
104
+ // with. A username or customer number is never passed off as an address.
105
+ const { session, contact, permissions } = await useRevenexxSdk().call<{
54
106
  session: ApiSession;
55
107
  contact: ApiContact | null;
56
- };
108
+ permissions?: CustomersPermissionAnswer | null;
109
+ }>("POST", "/v1/customers/auth/login", { body: loginBody(identifier, password) });
57
110
 
111
+ // The cookie points at the platform session and nothing else: the
112
+ // contact and organization are re-resolved per request (RAD-155).
58
113
  const storedSession: StoredSession = {
59
114
  id: session.$id,
60
115
  expire: session.expire,
61
116
  userId: session.userId,
62
- ...(contact?.id ? { contactId: contact.id } : {}),
63
- ...(contact?.organization_id ? { organizationId: contact.organization_id } : {}),
64
117
  };
65
118
  setCookie(event, SESSION_COOKIE_NAME, JSON.stringify(storedSession), sessionCookieOptions(session.expire));
66
119
 
67
120
  return {
68
121
  user: {
69
122
  $id: session.userId,
70
- name: contactName(contact, email),
71
- email: contact?.email ?? email,
123
+ name: contactName(contact, identifier),
124
+ // Never the identifier itself unless it is an address: a username
125
+ // or customer number in the email slot would be mailed to.
126
+ email: contact?.email ?? (loginIdentifierKind(identifier) === "email" ? identifier : ""),
72
127
  role: toAuthRole(contact?.role),
128
+ ...(contact?.id ? { contactId: contact.id } : {}),
129
+ ...(contact?.organization_id ? { organizationId: contact.organization_id } : {}),
130
+ ...grantsFrom(permissions, contact),
73
131
  },
74
132
  session: { id: session.$id, expire: session.expire },
75
133
  ...(contact?.id ? { contactId: contact.id } : {}),
76
134
  };
77
135
  }
78
136
 
137
+ /**
138
+ * The verified buyer of this request. Resolved at most once per request and
139
+ * remembered on the event (rememberVerifiedBuyer), which is also what puts
140
+ * the contact on every later SDK call as its principal.
141
+ */
79
142
  async me(event: H3Event): Promise<AuthUser | null> {
143
+ const context = event.context as Record<string, unknown>;
144
+ const pending = context[ME_KEY] as Promise<AuthUser | null> | undefined;
145
+ if (pending) {
146
+ return pending;
147
+ }
148
+ const resolving = this.resolve(event).then((user) => {
149
+ rememberVerifiedBuyer(event, user);
150
+ return user;
151
+ });
152
+ context[ME_KEY] = resolving;
153
+ return resolving;
154
+ }
155
+
156
+ private async resolve(event: H3Event): Promise<AuthUser | null> {
80
157
  const raw = getCookie(event, SESSION_COOKIE_NAME);
81
158
  if (!raw) {
82
159
  return null;
@@ -92,11 +169,21 @@ export class ApiAuthService implements IAuthService {
92
169
  return null;
93
170
  }
94
171
 
95
- if (!parsed.userId) {
172
+ // Both halves are required: auth/me is asked whether THIS session is
173
+ // that user's live one, which is what makes the answer proof rather
174
+ // than an echo of whatever user id the browser wrote.
175
+ if (!parsed || typeof parsed.userId !== "string" || !parsed.userId || typeof parsed.id !== "string" || !parsed.id) {
96
176
  deleteCookie(event, SESSION_COOKIE_NAME, sessionCookieOptions());
97
177
  return null;
98
178
  }
99
179
 
180
+ const cacheKey = `${revenexxTenantKey()}\u0000${parsed.userId}\u0000${parsed.id}`;
181
+ const remembered = verified.get(cacheKey);
182
+ if (remembered && remembered.until > Date.now()) {
183
+ return remembered.user;
184
+ }
185
+ verified.delete(cacheKey);
186
+
100
187
  // Validate the session against the customers app, retrying transient
101
188
  // failures. A 401 is the only proof the session is gone (revoked/expired)
102
189
  // → clear the cookie + log out. Anything else (5xx "capability dispatch
@@ -113,27 +200,34 @@ export class ApiAuthService implements IAuthService {
113
200
  // alive — a logged-out/revoked session answers 401 here. Raw call:
114
201
  // the AuthMeRequest contract does not declare session_id yet, so
115
202
  // the generated customersAuthMe() would drop the session check.
116
- const { user, contact } = await useRevenexxSdk().call<{
117
- user: { $id: string; name?: string; email: string };
118
- contact: ApiContact | null;
119
- }>("POST", "/v1/customers/auth/me", { body: { user_id: parsed.userId, session_id: parsed.id } });
203
+ const { user, contact, permissions } = await useRevenexxSdk().call<ApiMeAnswer>(
204
+ "POST",
205
+ "/v1/customers/auth/me",
206
+ { body: { user_id: parsed.userId, session_id: parsed.id } },
207
+ );
120
208
 
121
- return {
209
+ const resolved: AuthUser = {
122
210
  $id: user.$id,
123
211
  name: contactName(contact, user.name ?? user.email),
124
212
  email: user.email,
125
213
  role: toAuthRole(contact?.role),
126
214
  ...(contact?.id ? { contactId: contact.id } : {}),
127
215
  ...(contact?.organization_id ? { organizationId: contact.organization_id } : {}),
128
- // Only when the app actually said: undefined means nobody asked,
129
- // and reading that as blocked would lock out every session whose
130
- // cookie predates this.
131
- ...(typeof contact?.active === "boolean" ? { active: contact.active } : {}),
216
+ // `active` only when the app actually said: undefined means
217
+ // nobody asked, and reading that as blocked would lock out
218
+ // every session whose cookie predates this.
219
+ ...grantsFrom(permissions, contact),
132
220
  };
221
+ rememberAcrossRequests(cacheKey, resolved);
222
+ return resolved;
133
223
  }
134
224
  catch (err) {
135
225
  lastErr = err;
136
- if (isApiUserError(err) && err.code === 401) {
226
+ // 401: the session is gone. A blocked contact or organization
227
+ // refused outright (customers >= 1.1.0) is signed out as well.
228
+ // Any other 403 is this shop's credentials, not the buyer's
229
+ // session, and must not sign everybody out.
230
+ if (err instanceof RevenexxException && (err.code === 401 || signInRefusalType(err) !== null)) {
137
231
  deleteCookie(event, SESSION_COOKIE_NAME, sessionCookieOptions());
138
232
  return null;
139
233
  }
@@ -152,6 +246,7 @@ export class ApiAuthService implements IAuthService {
152
246
  try {
153
247
  const parsed = JSON.parse(raw) as StoredSession;
154
248
  if (parsed.userId && parsed.id) {
249
+ verified.delete(`${revenexxTenantKey()}\u0000${parsed.userId}\u0000${parsed.id}`);
155
250
  await useRevenexxSdk().customers.customersAuthLogout({
156
251
  userId: parsed.userId,
157
252
  sessionId: parsed.id,
@@ -164,5 +259,7 @@ export class ApiAuthService implements IAuthService {
164
259
  }
165
260
  }
166
261
  deleteCookie(event, SESSION_COOKIE_NAME, sessionCookieOptions());
262
+ forgetVerifiedBuyer(event);
263
+ delete (event.context as Record<string, unknown>)[ME_KEY];
167
264
  }
168
265
  }
@@ -3,7 +3,6 @@ import type { Models } from "@revenexx/sdk";
3
3
  import type { H3Event } from "h3";
4
4
 
5
5
  import type { CartItem } from "../../app/interfaces/cart-item";
6
- import type { StoredSession } from "../../app/interfaces/auth";
7
6
  import type { CartSummaryRow, ICartManager, ICartService } from "../interfaces/cart";
8
7
 
9
8
  /** Cart row of the carts app. */
@@ -47,18 +46,28 @@ const DEFAULT_CART_NAME = "Mein Warenkorb";
47
46
 
48
47
  /** The request's cart owner: the logged-in contact, else the guest session. */
49
48
  function resolveOwner(event: H3Event): CartOwner {
50
- let contactId: string | null = null;
51
- const raw = getCookie(event, SESSION_COOKIE_NAME);
52
- if (raw) {
53
- try {
54
- const parsed = JSON.parse(raw) as StoredSession;
55
- contactId = parsed.contactId ?? null;
56
- }
57
- catch { /* guest */ }
58
- }
49
+ // The VERIFIED contact (RAD-155) — a contact id read from the cookie would
50
+ // open any buyer's cart to whoever wrote it there.
51
+ const contactId = sessionOrderRefs(event).contact_id ?? null;
59
52
  return { contactId, sessionKey: getOrCreateCartSessionId(event) };
60
53
  }
61
54
 
55
+ /**
56
+ * The cart a punchout visit works in, or null outside one.
57
+ *
58
+ * `is_current` is one cart per contact, and several ERP users on one punchout
59
+ * account can resolve to the same contact — so a visit that went through "the"
60
+ * current cart would share it with every other visit of that contact, and hand
61
+ * back only its own (stale) cart. A visit therefore addresses the cart its
62
+ * claim named and never touches `is_current`, which also leaves an ordinary
63
+ * session of that contact exactly as it was (RAD-109). A handed-back visit is
64
+ * over: the buyer is signed out, and whatever they do next is not the visit's.
65
+ */
66
+ function visitCartId(event: H3Event): string | null {
67
+ const visit = readPunchoutVisit(event);
68
+ return visit && !visit.handedBack ? visit.cartId : null;
69
+ }
70
+
62
71
  /** Storefront CartItem → carts-app line. The snapshot is the loose product copy. */
63
72
  function toApiLine(item: CartItem, position: number): Record<string, unknown> {
64
73
  return {
@@ -166,24 +175,32 @@ export class ApiCartService implements ICartService, ICartManager {
166
175
  }) as unknown as ApiCart;
167
176
  }
168
177
 
178
+ private async listItems(cartId: string): Promise<CartItem[]> {
179
+ const { items } = await useRevenexxSdk().cartsItems.cartsItemsList({ cartId }) as unknown as { items: ApiCartLine[] };
180
+ return items.map(toCartItem);
181
+ }
182
+
183
+ /** The request's active cart id: the visit's cart, else the owner's current one. */
184
+ private async activeCartId(event: H3Event): Promise<string | null> {
185
+ const visitCart = visitCartId(event);
186
+ if (visitCart) {
187
+ return visitCart;
188
+ }
189
+ const carts = await this.listActive(resolveOwner(event));
190
+ return (carts.find(c => c.is_current) ?? carts[0])?.id ?? null;
191
+ }
192
+
169
193
  // ---- ICartService (the active cart) --------------------------------
170
194
 
171
195
  async getItems(event: H3Event): Promise<CartItem[]> {
172
- const owner = resolveOwner(event);
173
- const carts = await this.listActive(owner);
174
- const current = carts.find(c => c.is_current) ?? carts[0];
175
- if (!current) {
176
- return [];
177
- }
178
- const { items } = await useRevenexxSdk().cartsItems.cartsItemsList({ cartId: current.id }) as unknown as { items: ApiCartLine[] };
179
- return items.map(toCartItem);
196
+ const cartId = await this.activeCartId(event);
197
+ return cartId ? await this.listItems(cartId) : [];
180
198
  }
181
199
 
182
200
  async saveItems(event: H3Event, items: CartItem[]): Promise<void> {
183
- const owner = resolveOwner(event);
184
- const cart = await this.ensureActiveCart(owner);
201
+ const cartId = visitCartId(event) ?? (await this.ensureActiveCart(resolveOwner(event))).id;
185
202
  await useRevenexxSdk().cartsItems.cartsItemsReplace({
186
- cartId: cart.id,
203
+ cartId,
187
204
  items: items.map((item, index) => toApiLine(item, index)) as unknown as Models.CartItemCreateRequest[],
188
205
  });
189
206
  }
@@ -195,8 +212,15 @@ export class ApiCartService implements ICartService, ICartManager {
195
212
  // ---- ICartManager (multi-cart) --------------------------------------
196
213
 
197
214
  async listCarts(event: H3Event): Promise<{ carts: CartSummaryRow[]; activeCartId: string | null }> {
198
- const owner = resolveOwner(event);
199
- const carts = await this.listActive(owner);
215
+ // A visit's cart is owned by the punchout session, not by the contact,
216
+ // so the contact's list would not even contain it — and the hand-back
217
+ // sends that cart and no other. The visit sees exactly its own cart.
218
+ const visitCart = visitCartId(event);
219
+ if (visitCart) {
220
+ const cart = await useRevenexxSdk().call<ApiCart>("GET", `/v1/carts/${encodeURIComponent(visitCart)}`);
221
+ return { carts: [{ ...toSummary(cart), active: true }], activeCartId: visitCart };
222
+ }
223
+ const carts = await this.listActive(resolveOwner(event));
200
224
  const active = carts.find(c => c.is_current) ?? carts[0] ?? null;
201
225
  return {
202
226
  carts: carts.map(c => ({ ...toSummary(c), active: c.id === active?.id })),
@@ -205,6 +229,11 @@ export class ApiCartService implements ICartService, ICartManager {
205
229
  }
206
230
 
207
231
  async createCart(event: H3Event, name: string, activate: boolean): Promise<CartSummaryRow> {
232
+ if (visitCartId(event)) {
233
+ // A visit works in the one cart its hand-back sends; a second cart
234
+ // would be one the procurement system never receives.
235
+ throw createError({ statusCode: 409, data: { type: "punchout_cart_fixed" } });
236
+ }
208
237
  const owner = resolveOwner(event);
209
238
  const cart = await useRevenexxSdk().carts.cartsCreate({
210
239
  name: name.trim() || DEFAULT_CART_NAME,
@@ -223,9 +252,17 @@ export class ApiCartService implements ICartService, ICartManager {
223
252
  }
224
253
 
225
254
  async activateCart(event: H3Event, id: string): Promise<CartItem[]> {
226
- await useRevenexxSdk().carts.cartsActivate({ id });
227
- const { items } = await useRevenexxSdk().cartsItems.cartsItemsList({ cartId: id }) as unknown as { items: ApiCartLine[] };
228
- return items.map(toCartItem);
255
+ const visitCart = visitCartId(event);
256
+ if (visitCart && id !== visitCart) {
257
+ // The hand-back sends the visit's cart and no other, so switching
258
+ // away from it would leave the buyer filling a cart that never
259
+ // reaches their procurement system.
260
+ throw createError({ statusCode: 409, data: { type: "punchout_cart_fixed" } });
261
+ }
262
+ if (!visitCart) {
263
+ await useRevenexxSdk().carts.cartsActivate({ id });
264
+ }
265
+ return await this.listItems(id);
229
266
  }
230
267
 
231
268
  async addItemToCart(event: H3Event, id: string, item: CartItem): Promise<void> {
@@ -246,14 +283,12 @@ export class ApiCartService implements ICartService, ICartManager {
246
283
  }
247
284
 
248
285
  async orderActiveCart(event: H3Event, orderRef: string): Promise<string | null> {
249
- const owner = resolveOwner(event);
250
- const carts = await this.listActive(owner);
251
- const current = carts.find(c => c.is_current) ?? carts[0];
252
- if (!current) {
286
+ const cartId = await this.activeCartId(event);
287
+ if (!cartId) {
253
288
  return null;
254
289
  }
255
- await useRevenexxSdk().carts.cartsOrder({ id: current.id, orderRef });
256
- return current.id;
290
+ await useRevenexxSdk().carts.cartsOrder({ id: cartId, orderRef });
291
+ return cartId;
257
292
  }
258
293
 
259
294
  async claimSession(event: H3Event, contactId: string): Promise<void> {