@revenexx/cover 0.2.36 → 0.2.38

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.
@@ -0,0 +1,159 @@
1
+ import type { PunchoutIntent } from "../../app/interfaces/punchout";
2
+ import type { PunchoutLandingTarget } from "../interfaces/punchout";
3
+
4
+ /**
5
+ * Where a punchout buyer lands, and why it is decided here.
6
+ *
7
+ * An entry call is rarely "come in and shop". A cXML setup request can name
8
+ * one article or reopen a requisition; an IDS call can be `ADL` (one article,
9
+ * by `ghnummer`), `AS` (a search for `searchterm`) or `WKS` (a cart the trade
10
+ * software sent in). The punchout app records what was asked for as
11
+ * `entry_action` plus `entry_intent`, in its own vocabulary rather than any
12
+ * protocol's — so this is the one place the shop reads it, and nothing here
13
+ * knows what OCI, cXML or IDS are.
14
+ *
15
+ * Two of the promises this keeps are the ones the specs leave to the shop:
16
+ * cxml-entry AC-9 and ids-actions AC-11 — "the buyer arrives where the call
17
+ * pointed", which is the half a buyer actually experiences.
18
+ */
19
+
20
+ /**
21
+ * What the visit asked for.
22
+ *
23
+ * `entry_action` is the primary reading; `entry_intent.kind` is the fallback,
24
+ * because the two are written together and an adapter that filled only the
25
+ * intent (as the IDS inbound cart does, once the cart has been imported) must
26
+ * still land the buyer correctly.
27
+ *
28
+ * An action this shop does not recognise lands on the shop rather than
29
+ * nowhere: the alternative is a buyer who got through the door and met a 404.
30
+ */
31
+ export function punchoutLandingTarget(
32
+ entryAction: string | null | undefined,
33
+ intent: PunchoutIntent | null | undefined,
34
+ cartId: string | null | undefined,
35
+ ): PunchoutLandingTarget {
36
+ const kind = String(intent?.kind ?? "").trim();
37
+ const action = String(entryAction ?? "").trim();
38
+
39
+ // A cart the external system sent in, or a requisition it reopened. It is
40
+ // always a NEW cart — a `WKS` import creates one every time — so the buyer
41
+ // is pointed at THAT cart and never at "the" cart.
42
+ if (cartId && (kind === "inbound_cart" || action === "inbound_cart" || action === "reopen" || action === "inspect")) {
43
+ return { kind: "cart" };
44
+ }
45
+
46
+ const supplierPartId = String(intent?.supplier_part_id ?? "").trim();
47
+ if (supplierPartId && (kind === "article" || action === "article")) {
48
+ return { kind: "article", supplierPartId };
49
+ }
50
+
51
+ const term = String(intent?.term ?? "").trim();
52
+ if (term && (kind === "search" || action === "search")) {
53
+ return { kind: "search", term };
54
+ }
55
+
56
+ return { kind: "shop" };
57
+ }
58
+
59
+ /**
60
+ * The path for a target that needs no lookup.
61
+ *
62
+ * An article does: the external system names an article NUMBER and the shop's
63
+ * product pages are addressed by id and slug, so resolving one is a catalogue
64
+ * question — `punchoutArticlePath()` below.
65
+ */
66
+ export function punchoutLandingPath(target: PunchoutLandingTarget): string | null {
67
+ switch (target.kind) {
68
+ case "shop":
69
+ return "/";
70
+ case "cart":
71
+ return "/cart";
72
+ case "search":
73
+ return `/search?q=${encodeURIComponent(target.term)}`;
74
+ case "article":
75
+ return null;
76
+ }
77
+ }
78
+
79
+ /** One row of the search answer, as much of it as resolving an article needs. */
80
+ interface SearchHit {
81
+ readonly id?: string;
82
+ readonly name?: string;
83
+ readonly sku?: string;
84
+ readonly categorySlug?: string | null;
85
+ readonly subcategorySlug?: string | null;
86
+ }
87
+
88
+ /**
89
+ * The product page of one article number, or the search for it.
90
+ *
91
+ * The catalogue is addressed by `{id}-{name}` slugs under the article's
92
+ * category, and an external system knows neither — it knows the number it
93
+ * sells under. So the number is resolved through the shop's own search, which
94
+ * queries `name,sku`, and only an EXACT sku match counts: "lands on the
95
+ * article named by ghnummer" is a promise about one article, and a fuzzy match
96
+ * would quietly land the buyer on a different one.
97
+ *
98
+ * Anything else — several matches, none, or a search backend that is not there
99
+ * — lands on the search results for that number. That is honest (the buyer
100
+ * sees what the shop found for it) where a 404 or the home page would silently
101
+ * lose what the call asked for.
102
+ *
103
+ * The slug is built here rather than taken from `categoryProductPath()`: that
104
+ * helper sits in a composables file that pulls the Vue runtime in with it, and
105
+ * a server route must not. The two have to stay in step — a product URL the
106
+ * shop cannot route is a landing that 404s — which is what
107
+ * `test/unit/punchout-landing.test.ts` asserts against the same fixtures the
108
+ * app-side helper is asserted against.
109
+ */
110
+ export function punchoutArticlePath(hits: readonly SearchHit[], supplierPartId: string): string {
111
+ const wanted = supplierPartId.trim().toLowerCase();
112
+ const exact = hits.filter(hit => String(hit.sku ?? "").trim().toLowerCase() === wanted);
113
+
114
+ const only = exact.length === 1 ? exact[0] : undefined;
115
+ if (only?.id && only.name) {
116
+ const segments = [only.categorySlug, only.subcategorySlug]
117
+ .filter((segment): segment is string => Boolean(segment) && segment !== "undefined");
118
+ const prefix = segments.length > 0 ? segments.join("/") : "_";
119
+ const slug = `${only.id}-${only.name.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "")}`;
120
+ return `/category/${prefix}/product/${slug}`;
121
+ }
122
+
123
+ return `/search?q=${encodeURIComponent(supplierPartId)}`;
124
+ }
125
+
126
+ /**
127
+ * The same path, addressed the way this storefront addresses pages.
128
+ *
129
+ * A punchout buyer is redirected by a SERVER route, which cannot ask the Vue
130
+ * router what a page's URL is. So the locale prefix is applied here, from the
131
+ * app's own i18n strategy (published into runtime config by the cover layer's
132
+ * `modules:done` hook, because @nuxtjs/i18n v10 does not publish it itself).
133
+ *
134
+ * This is not cosmetic. Under `prefix` — the demo shop — an unprefixed `/cart`
135
+ * is a 404, so a buyer would be signed in and dropped on an error page; under
136
+ * `prefix_except_default` the default locale's pages are only reachable
137
+ * WITHOUT one, so a prefix would 404 just as hard. Both storefronts in this
138
+ * repo exist, and they answer differently.
139
+ */
140
+ export function punchoutLocalePath(
141
+ path: string,
142
+ locale: string,
143
+ strategy: string,
144
+ defaultLocale: string,
145
+ ): string {
146
+ if (!locale || strategy === "no_prefix") {
147
+ return path;
148
+ }
149
+ if (strategy === "prefix_except_default" && locale === defaultLocale) {
150
+ return path;
151
+ }
152
+ if (strategy !== "prefix" && strategy !== "prefix_and_default" && strategy !== "prefix_except_default") {
153
+ // An unknown strategy is a future one: leaving the path alone is what a
154
+ // storefront with no prefixes wants, and the worst case is one redirect
155
+ // the framework fixes up rather than a path invented out of nothing.
156
+ return path;
157
+ }
158
+ return `/${locale}${path === "/" ? "" : path}`;
159
+ }
@@ -0,0 +1,134 @@
1
+ import type { CookieSerializeOptions } from "cookie-es";
2
+ import type { H3Event } from "h3";
3
+ import { deleteCookie, getCookie, setCookie } from "h3";
4
+
5
+ import type { PunchoutVisitView } from "../../app/interfaces/punchout";
6
+ import type { PunchoutVisit } from "../interfaces/punchout";
7
+
8
+ /**
9
+ * The storefront's own record of one punchout visit.
10
+ *
11
+ * It sits beside the auth session rather than inside it, because the two end
12
+ * at different moments: the buyer is signed in the instant the hand-off secret
13
+ * is redeemed, and stays signed in for the platform session's own lifetime,
14
+ * while the VISIT ends when the cart is handed back, when it expires, or when
15
+ * somebody revokes it. Folding one into the other would mean a hand-back could
16
+ * not sign the buyer out without also forgetting which visit had just ended.
17
+ *
18
+ * HTTP-only, so the handle cannot be rewritten in the browser. The handle is
19
+ * not a credential — it identifies a visit and nothing more, which is why the
20
+ * sign-in secret goes over a back channel instead — but a value the browser
21
+ * could edit would let a buyer hand back somebody else's cart.
22
+ */
23
+
24
+ export const PUNCHOUT_COOKIE_NAME = "cover-punchout";
25
+
26
+ function visitCookieOptions(expiresAt?: string): CookieSerializeOptions {
27
+ return {
28
+ httpOnly: true,
29
+ secure: !import.meta.dev,
30
+ // `lax` and not `strict`: the buyer arrives here by a cross-site
31
+ // redirect from their procurement system, and a strict cookie set on
32
+ // that navigation would not be sent back on the page that follows it.
33
+ sameSite: "lax",
34
+ path: "/",
35
+ ...(expiresAt ? { expires: new Date(expiresAt) } : {}),
36
+ };
37
+ }
38
+
39
+ /** Remember one claimed visit for the rest of the buyer's stay. */
40
+ export function setPunchoutVisit(event: H3Event, visit: PunchoutVisit): void {
41
+ setCookie(event, PUNCHOUT_COOKIE_NAME, JSON.stringify(visit), visitCookieOptions(visit.expiresAt));
42
+ }
43
+
44
+ /**
45
+ * The visit this request belongs to, or null — reading only.
46
+ *
47
+ * A visit past its expiry is read as no visit at all: the punchout app settles
48
+ * an expired session the next time anything reads it, and the shop must not go
49
+ * on offering a transfer action for a visit that can no longer be handed back.
50
+ *
51
+ * Kept free of side effects because it is called from the SDK factory, on every
52
+ * gateway call: a read that also wrote a `Set-Cookie` would try to touch the
53
+ * response from paths that have already answered.
54
+ */
55
+ export function readPunchoutVisit(event: H3Event, now: Date = new Date()): PunchoutVisit | null {
56
+ const raw = getCookie(event, PUNCHOUT_COOKIE_NAME);
57
+ if (!raw) {
58
+ return null;
59
+ }
60
+
61
+ let visit: PunchoutVisit;
62
+ try {
63
+ visit = JSON.parse(raw) as PunchoutVisit;
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+
69
+ if (!visit?.psid || !visit.protocol) {
70
+ return null;
71
+ }
72
+ if (visit.expiresAt && new Date(visit.expiresAt).getTime() <= now.getTime()) {
73
+ return null;
74
+ }
75
+ return visit;
76
+ }
77
+
78
+ /**
79
+ * The same, and it tidies up after itself: a cookie that is there but no longer
80
+ * usable is dropped, so the browser stops sending a visit that ended. For the
81
+ * routes that answer a request of their own — everything but the SDK factory.
82
+ */
83
+ export function getPunchoutVisit(event: H3Event, now: Date = new Date()): PunchoutVisit | null {
84
+ const visit = readPunchoutVisit(event, now);
85
+ if (!visit && getCookie(event, PUNCHOUT_COOKIE_NAME)) {
86
+ clearPunchoutVisit(event);
87
+ }
88
+ return visit;
89
+ }
90
+
91
+ /** Update the stored visit in place — used to mark it handed back. */
92
+ export function updatePunchoutVisit(event: H3Event, patch: Partial<PunchoutVisit>): PunchoutVisit | null {
93
+ const visit = getPunchoutVisit(event);
94
+ if (!visit) {
95
+ return null;
96
+ }
97
+ const updated = { ...visit, ...patch };
98
+ setPunchoutVisit(event, updated);
99
+ return updated;
100
+ }
101
+
102
+ export function clearPunchoutVisit(event: H3Event): void {
103
+ deleteCookie(event, PUNCHOUT_COOKIE_NAME, visitCookieOptions());
104
+ }
105
+
106
+ /**
107
+ * What the browser is told about the visit: enough to show the right action in
108
+ * the right words, and nothing that names the visit to the punchout app. The
109
+ * handle stays server-side — the transfer action goes through the BFF.
110
+ */
111
+ export function punchoutVisitView(visit: PunchoutVisit | null): PunchoutVisitView {
112
+ if (!visit) {
113
+ return {
114
+ active: false,
115
+ protocol: null,
116
+ channelCode: null,
117
+ entryAction: null,
118
+ readOnly: false,
119
+ cartId: null,
120
+ expiresAt: null,
121
+ handedBack: false,
122
+ };
123
+ }
124
+ return {
125
+ active: true,
126
+ protocol: visit.protocol,
127
+ channelCode: visit.channelCode,
128
+ entryAction: visit.entryAction,
129
+ readOnly: visit.readOnly === true,
130
+ cartId: visit.cartId,
131
+ expiresAt: visit.expiresAt,
132
+ handedBack: visit.handedBack === true,
133
+ };
134
+ }
@@ -128,6 +128,31 @@ function activeMarket(): string {
128
128
  }
129
129
  }
130
130
 
131
+ /**
132
+ * The channel the current request shops, when it belongs to a punchout visit.
133
+ * "" otherwise — an ordinary shop visit carries no channel and the gateway
134
+ * answers whatever the tenant's default is.
135
+ *
136
+ * A punchout buyer's channel is not a preference, it is the account's: it
137
+ * decides which assortment and which price list they see, and it has to ride
138
+ * on EVERY call for the rest of the visit (RAD-44). Without it a punchout
139
+ * buyer silently gets the public shop's catalogue — silently, because nothing
140
+ * about the answer says which channel produced it.
141
+ *
142
+ * Per-request and never part of a cache key, for the same reason the market is
143
+ * not: the value comes from a cookie, and a client-keyed cache is a cache a
144
+ * caller can fill.
145
+ */
146
+ function activeChannel(): string {
147
+ try {
148
+ return readPunchoutVisit(useEvent())?.channelCode ?? "";
149
+ }
150
+ catch {
151
+ // No async context (e.g. startup code) — no channel scoping.
152
+ return "";
153
+ }
154
+ }
155
+
131
156
  /**
132
157
  * The tenant slug the current request's SDK calls are scoped to — the cache
133
158
  * key for any server-side cache of gateway data (markets, categories, …).
@@ -144,8 +169,9 @@ export function revenexxTenantKey(): string {
144
169
  export function useRevenexxSdk(): RevenexxSdk {
145
170
  const { tenant, apiKey, jwt, source } = resolveRevenexxCredentials();
146
171
  const market = activeMarket();
172
+ const channel = activeChannel();
147
173
 
148
- const isCacheable = source !== "brokered" && !market;
174
+ const isCacheable = source !== "brokered" && !market && !channel;
149
175
  if (isCacheable) {
150
176
  const cached = clients.get(tenant);
151
177
  if (cached) {
@@ -175,6 +201,13 @@ export function useRevenexxSdk(): RevenexxSdk {
175
201
  if (market) {
176
202
  client.setMarket(market);
177
203
  }
204
+ // Active channel (punchout) → X-Revenexx-Channel. The SDK has no setter for
205
+ // it — channels are a scope dimension the generated services do not declare
206
+ // a parameter for — so it goes on the client's own header map, which is
207
+ // what setMarket() writes to as well.
208
+ if (channel) {
209
+ client.headers["X-Revenexx-Channel"] = channel;
210
+ }
178
211
  // Auth: the brokered context wins — it is a Zitadel JWT the gateway
179
212
  // verifies against the same JWKS as any interactive caller, so one theme
180
213
  // build serves any tenant without per-site credentials. The explicit