@revenexx/cover 0.18.0 → 0.20.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 (52) hide show
  1. package/app/api/marketing.ts +24 -0
  2. package/app/app.config.ts +22 -0
  3. package/app/components/account/loyalty/AccountLoyalty.vue +205 -0
  4. package/app/components/cart/view/CartSummaryPanel.vue +4 -0
  5. package/app/components/checkout/onepage/CheckoutSummarySection.vue +4 -0
  6. package/app/components/loyalty/hint/LoyaltyPerkHint.vue +28 -0
  7. package/app/components/newsletter/confirm/NewsletterConfirmation.vue +54 -0
  8. package/app/components/newsletter/preferences/NewsletterPreferenceCentre.vue +183 -0
  9. package/app/components/newsletter/state/NewsletterLinkRefusal.vue +45 -0
  10. package/app/components/product/detail/ProductDetailImageGallery.vue +39 -13
  11. package/app/components/product/detail/ProductDetailView.vue +3 -1
  12. package/app/components/review/form/ReviewForm.vue +211 -0
  13. package/app/composables/useCampaignAttribution.ts +120 -0
  14. package/app/composables/useCheckoutOnePage.ts +9 -0
  15. package/app/composables/useLoyaltyAccount.ts +79 -0
  16. package/app/composables/useMarketingConsent.ts +49 -0
  17. package/app/composables/useProduct.ts +6 -1
  18. package/app/config/navigation.ts +1 -1
  19. package/app/config/quickActions.ts +1 -0
  20. package/app/interfaces/product-detail.ts +11 -0
  21. package/app/pages/account/points.vue +26 -0
  22. package/app/pages/newsletter/confirm/[token].vue +23 -0
  23. package/app/pages/newsletter/preferences/[token].vue +24 -0
  24. package/app/pages/review/[token].vue +23 -0
  25. package/app/plugins/campaign-attribution.client.ts +47 -0
  26. package/app/shared/campaignAttribution.ts +281 -0
  27. package/app/shared/personalisation.ts +107 -0
  28. package/i18n/locales/de/account.json +3 -2
  29. package/i18n/locales/de/marketing.json +71 -0
  30. package/i18n/locales/en/account.json +3 -2
  31. package/i18n/locales/en/marketing.json +71 -0
  32. package/package.json +1 -1
  33. package/server/api/campaigns/touches.post.ts +42 -0
  34. package/server/api/cart/attribution.put.ts +31 -0
  35. package/server/api/loyalty/account.get.ts +27 -0
  36. package/server/api/newsletter/confirm/[token].post.ts +21 -0
  37. package/server/api/newsletter/preferences/[token].get.ts +14 -0
  38. package/server/api/newsletter/preferences/[token].post.ts +36 -0
  39. package/server/api/orders/index.post.ts +10 -1
  40. package/server/api/reviews/requests/[token].get.ts +14 -0
  41. package/server/api/reviews/submit/[token].post.ts +31 -0
  42. package/server/interfaces/cart.ts +6 -0
  43. package/server/interfaces/marketing.ts +150 -0
  44. package/server/services/ApiCartService.ts +16 -0
  45. package/server/services/ApiMarketingService.ts +292 -0
  46. package/server/services/ApiProductService.ts +20 -1
  47. package/server/services/LocalFileProductService.ts +9 -1
  48. package/server/services/MockMarketingService.ts +178 -0
  49. package/server/utils/liveCatalog.ts +178 -2
  50. package/server/utils/marketingService.ts +63 -0
  51. package/server/utils/orderAttribution.ts +65 -0
  52. package/server/utils/personalisationViewer.ts +28 -0
@@ -134,6 +134,108 @@ export function liveImageSrc(raw: string): string {
134
134
  return `${CDN_PREFIX}${tenant && key.startsWith(`${tenant}/`) ? key.slice(tenant.length + 1) : key}`;
135
135
  }
136
136
 
137
+ /** A product asset row (products app): the catalogue's record of one file. */
138
+ interface LiveProductAssetRow {
139
+ code: string;
140
+ source?: string | null;
141
+ storage_asset_id?: string | null;
142
+ }
143
+
144
+ /** The storage service's view of an uploaded file. */
145
+ interface LiveStorageAsset {
146
+ kind?: string | null;
147
+ model_url?: string | null;
148
+ preview_url?: string | null;
149
+ }
150
+
151
+ /**
152
+ * A storage delivery URL as a key for the `/cdn/` path: the URL's own host is
153
+ * the storage service's (unreachable from the shop's domain), the path is
154
+ * `<tenant>/<folder>/<file>`, and the query (`?d=model`, `?d=preview`) selects
155
+ * the rendition, so it is kept. The path stays percent-encoded: decoded, a
156
+ * `#` or `?` in a file name would end the URL early.
157
+ */
158
+ function storageUrlToCdnSrc(url: string): string {
159
+ const parsed = new URL(url);
160
+ return `${liveImageSrc(parsed.pathname.replace(/^\/+/, ""))}${parsed.search}`;
161
+ }
162
+
163
+ type LiveProductModel = { url: string; poster: string | null };
164
+
165
+ const MODEL_TTL_MS = 5 * 60 * 1000;
166
+ const modelCache = new Map<string, { model: LiveProductModel | null; loadedAt: number }>();
167
+
168
+ /**
169
+ * One media code's 3D model, or `null`: not a product asset, not in storage,
170
+ * or not a model. `undefined` when the lookup failed — a deleted file must not
171
+ * cost the product's other media, and a failure must not be cached as "none".
172
+ */
173
+ async function liveAssetModel(code: string): Promise<LiveProductModel | null | undefined> {
174
+ const sdk = useRevenexxSdk();
175
+ try {
176
+ const assets = await sdk.call<{ items?: LiveProductAssetRow[] }>(
177
+ "GET", "/v1/products/assets", { query: { code, limit: 1 } },
178
+ );
179
+ const asset = assets.items?.[0];
180
+ if (!asset?.storage_asset_id) {
181
+ return null;
182
+ }
183
+ const file = await sdk.call<LiveStorageAsset | { data?: LiveStorageAsset }>(
184
+ "GET", `/v1/storage/assets/${encodeURIComponent(asset.storage_asset_id)}`,
185
+ );
186
+ const stored: LiveStorageAsset = "data" in file && file.data ? file.data : file as LiveStorageAsset;
187
+ if (stored.kind !== "model3d" || !stored.model_url) {
188
+ return null;
189
+ }
190
+ return {
191
+ url: storageUrlToCdnSrc(stored.model_url),
192
+ poster: stored.preview_url ? storageUrlToCdnSrc(stored.preview_url) : null,
193
+ };
194
+ }
195
+ catch (err) {
196
+ getLogService().warn("Live 3D lookup failed for one asset", { code, ...toErrorContext(err) });
197
+ return undefined;
198
+ }
199
+ }
200
+
201
+ /**
202
+ * The product's 3D model, from its own media: the codes in its
203
+ * `asset_collection` attributes name product assets, a product asset names
204
+ * its file in storage, and storage renders a CAD file (STEP) as a glTF mesh
205
+ * plus a preview still. The first file storage reports as `model3d` wins, in
206
+ * the order the attributes are declared. `null` when there is none.
207
+ *
208
+ * Runs on every product page, so the codes are looked up side by side, not
209
+ * one after another, and the answer (a missing model too) is kept for a few
210
+ * minutes per tenant and set of codes.
211
+ */
212
+ export async function resolveLiveProductModel(
213
+ attrs: Record<string, unknown>,
214
+ ): Promise<LiveProductModel | null> {
215
+ const meta = await loadLiveAttributeMeta();
216
+ const codes = Object.entries(attrs)
217
+ .filter(([key, value]) => meta[key]?.type === "asset_collection" && Array.isArray(value))
218
+ .sort(([a], [b]) => (meta[a]?.position ?? 999) - (meta[b]?.position ?? 999))
219
+ .flatMap(([, value]) => (value as unknown[]).filter((code): code is string => typeof code === "string" && code !== ""));
220
+ if (!codes.length) {
221
+ return null;
222
+ }
223
+
224
+ const key = `${revenexxTenantKey()}:${codes.join("|")}`;
225
+ const cached = modelCache.get(key);
226
+ if (cached && Date.now() - cached.loadedAt < MODEL_TTL_MS) {
227
+ return cached.model;
228
+ }
229
+ const found = await Promise.all(codes.map(code => liveAssetModel(code)));
230
+ const model = found.find(candidate => candidate !== null && candidate !== undefined) ?? null;
231
+ // A model found is kept; "none" only when every lookup answered, so a
232
+ // passing outage does not hide the 3D view for the whole TTL.
233
+ if (model || !found.includes(undefined)) {
234
+ modelCache.set(key, { model, loadedAt: Date.now() });
235
+ }
236
+ return model;
237
+ }
238
+
137
239
  /** Fallback attribute code holding a manufacturer's logo on the product doc. */
138
240
  const DEFAULT_LOGO_ATTRIBUTE = "manufacturer_logo";
139
241
 
@@ -874,12 +976,68 @@ export function renderLiveAttributeValue(
874
976
  value: unknown,
875
977
  locale: Locale,
876
978
  ): string {
979
+ if (isMeasureValue(value)) {
980
+ return renderMeasureValue(value, meta?.unit);
981
+ }
982
+ // Any other object (no amount to read) has no text of its own; empty drops
983
+ // the row instead of printing "[object Object]" or throwing.
984
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
985
+ return "";
986
+ }
877
987
  const raw = String(value);
878
988
  const option = meta?.options?.[raw];
879
989
  const label = option ? pickLiveLabel(option, locale, raw) : raw;
880
990
  return meta?.unit && !raw.includes(meta.unit) ? `${label} ${meta.unit}` : label;
881
991
  }
882
992
 
993
+ /**
994
+ * A metric attribute as the products app stores it: `{ amount, unit }`, the
995
+ * unit a code such as `MILLIMETER`. Cockpit edits and shows it in this shape;
996
+ * `String()` on it throws for the prototype-less objects the API client
997
+ * parses ("Cannot convert object to primitive value"), and took the whole
998
+ * product page down with it.
999
+ */
1000
+ function isMeasureValue(value: unknown): value is { amount: unknown; unit?: unknown; currency?: unknown } {
1001
+ return value !== null && typeof value === "object" && !Array.isArray(value) && "amount" in value;
1002
+ }
1003
+
1004
+ /** Symbols for the common unit codes; any other code is shown as it is. */
1005
+ const UNIT_SYMBOLS: Record<string, string> = {
1006
+ AMPERE_HOUR: "Ah",
1007
+ CENTIMETER: "cm",
1008
+ DECIBEL: "dB",
1009
+ DEGREE: "°",
1010
+ GRAM: "g",
1011
+ GRAM_PER_SQUARE_METER: "g/m²",
1012
+ KELVIN: "K",
1013
+ KILOGRAM: "kg",
1014
+ LITER: "l",
1015
+ LUMEN: "lm",
1016
+ METER: "m",
1017
+ MICROLITER: "µl",
1018
+ MILLILITER: "ml",
1019
+ MILLIMETER: "mm",
1020
+ REVOLUTIONS_PER_MINUTE: "rpm",
1021
+ VOLT: "V",
1022
+ WATT: "W",
1023
+ };
1024
+
1025
+ function renderMeasureValue(value: { amount: unknown; unit?: unknown; currency?: unknown }, fallbackUnit?: string): string {
1026
+ const amount = value.amount === null || value.amount === undefined ? "" : String(value.amount);
1027
+ if (!amount) {
1028
+ return "";
1029
+ }
1030
+ // A price-shaped value carries its currency where a metric carries its unit.
1031
+ const own = typeof value.unit === "string" && value.unit
1032
+ ? value.unit
1033
+ : typeof value.currency === "string" && value.currency ? value.currency : "";
1034
+ const unit = own || fallbackUnit;
1035
+ if (!unit) {
1036
+ return amount;
1037
+ }
1038
+ return `${amount} ${UNIT_SYMBOLS[unit] ?? unit}`;
1039
+ }
1040
+
883
1041
  /**
884
1042
  * Build the product detail specification rows from the doc's `attrs`:
885
1043
  * localized label, option/unit-aware value, internal keys hidden. Degrades to
@@ -980,6 +1138,8 @@ async function buildSpecRows(
980
1138
  const rank = m?.groupCode && SPEC_GROUP_RANK[m.groupCode] !== undefined ? SPEC_GROUP_RANK[m.groupCode] : 5;
981
1139
  return { label: pickLiveLabel(m?.labels, locale, prettifyAttrKey(key)), value: display, sort: rank * 1000 + (m?.position ?? 999) };
982
1140
  })
1141
+ // A value with nothing to read (an object without an amount) is no row.
1142
+ .filter(row => row.value !== "")
983
1143
  .sort((a, b) => a.sort - b.sort || a.label.localeCompare(b.label));
984
1144
 
985
1145
  return rows.map((r, i) => ({ id: i + 1, name: r.label, value: r.value }));
@@ -1066,6 +1226,22 @@ function livePimName(product: LivePimProduct, locale: Locale): string {
1066
1226
  return pickLiveLabel(names, locale, product.sku);
1067
1227
  }
1068
1228
 
1229
+ /**
1230
+ * An attribute value as a comparable string, for telling siblings apart. A
1231
+ * metric compares by what it reads ("40 W"); `String()` would make every
1232
+ * metric "[object Object]", or throw on the prototype-less objects the API
1233
+ * client parses.
1234
+ */
1235
+ function attributeValueKey(value: unknown): string {
1236
+ if (value === null || value === undefined) {
1237
+ return "";
1238
+ }
1239
+ if (isMeasureValue(value)) {
1240
+ return renderMeasureValue(value);
1241
+ }
1242
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
1243
+ }
1244
+
1069
1245
  /**
1070
1246
  * Which attributes actually distinguish these siblings.
1071
1247
  *
@@ -1091,7 +1267,7 @@ function deriveVariantAxisCodes(
1091
1267
  }
1092
1268
 
1093
1269
  const distinctCount = (code: string): number =>
1094
- new Set(commons.map(common => String(common[code] ?? ""))).size;
1270
+ new Set(commons.map(common => attributeValueKey(common[code]))).size;
1095
1271
 
1096
1272
  const candidates = [...codes]
1097
1273
  .filter((code) => {
@@ -1115,7 +1291,7 @@ function deriveVariantAxisCodes(
1115
1291
  }
1116
1292
  chosen.push(candidate.code);
1117
1293
  const tuples = new Set(
1118
- commons.map(common => chosen.map(code => String(common[code] ?? "")).join("")),
1294
+ commons.map(common => chosen.map(code => attributeValueKey(common[code])).join("")),
1119
1295
  );
1120
1296
  // Every sibling now has its own combination — further attributes would
1121
1297
  // add columns without adding information.
@@ -0,0 +1,63 @@
1
+ import type { H3Event } from "h3";
2
+
3
+ import type { Evidence, IMarketingService } from "../interfaces/marketing";
4
+ import { MarketingTokenError } from "../interfaces/marketing";
5
+ import { ApiMarketingService } from "../services/ApiMarketingService";
6
+ import { MockMarketingService } from "../services/MockMarketingService";
7
+
8
+ /**
9
+ * Registry of the marketing apps' source (RAD-293):
10
+ * - "mock" — demo answers for every marketing page
11
+ * - "api" — marketing-consents, reviews, loyalty, audiences and campaigns
12
+ * through the public revenexx API
13
+ */
14
+ const serviceRegistry: Record<string, IMarketingService> = {
15
+ mock: new MockMarketingService(),
16
+ api: new ApiMarketingService(),
17
+ };
18
+
19
+ export function resolveMarketingServiceKey(event?: H3Event): string {
20
+ return resolveServiceKey(event, {
21
+ domain: "marketingService",
22
+ mockKey: "mock",
23
+ liveKey: "api",
24
+ });
25
+ }
26
+
27
+ export function getMarketingService(event?: H3Event): IMarketingService {
28
+ return serviceRegistry[resolveMarketingServiceKey(event)] ?? serviceRegistry["mock"]!;
29
+ }
30
+
31
+ /**
32
+ * What a consent record keeps as evidence of who confirmed: the address the
33
+ * request came from and the browser it named. The double opt-in is proven by
34
+ * exactly this; marketing-consents deletes the address after its retention.
35
+ */
36
+ export function consentEvidence(event: H3Event, pageUrl?: string | null): Evidence {
37
+ return {
38
+ ip: getRequestIP(event, { xForwardedFor: true }) ?? null,
39
+ user_agent: getHeader(event, "user-agent")?.slice(0, 512) ?? null,
40
+ ...(pageUrl !== undefined ? { page_url: pageUrl } : {}),
41
+ };
42
+ }
43
+
44
+ /** A token as a route received it, or a 404 before anything is asked. */
45
+ export function routeToken(event: H3Event): string {
46
+ const token = getRouterParam(event, "token");
47
+ if (!token || token.length > 256) {
48
+ throw createError({ statusCode: 404, data: { refusal: "unknown" }, message: "Link unknown" });
49
+ }
50
+ return token;
51
+ }
52
+
53
+ /** A refused token as the page reads it: 404 unknown, 410 expired. */
54
+ export function rethrowTokenRefusal(err: unknown): never {
55
+ if (err instanceof MarketingTokenError) {
56
+ throw createError({
57
+ statusCode: err.refusal === "expired" ? 410 : 404,
58
+ data: { refusal: err.refusal },
59
+ message: err.message,
60
+ });
61
+ }
62
+ throw err;
63
+ }
@@ -0,0 +1,65 @@
1
+ import { Orders, RevenexxException } from "@revenexx/sdk";
2
+
3
+ import type { Attribution } from "../../app/shared/campaignAttribution";
4
+ import type { RevenexxSdk } from "./revenexxSdk";
5
+
6
+ /**
7
+ * `POST /v1/orders/place` with the visit's attribution (RAD-293). The orders
8
+ * app takes it from the placement body and never reads the cart for it
9
+ * (orders 3.8.0, RAD-287), so it has to travel with the order.
10
+ *
11
+ * The typed SDK builds the request body from the parameters it knows, and
12
+ * `attribution` is not one of them yet. Rather than rebuild that body by
13
+ * hand — the line, address and payment mapping is the SDK's, and two copies
14
+ * of it would drift — the call is made through the same generated method on
15
+ * a client that adds the one key on its way out.
16
+ *
17
+ * An orders app that refuses the field (one older than 3.8.0, or a value it
18
+ * reads as malformed) answers 400 before anything is placed; the order is
19
+ * then placed again without it. A buyer's order never fails over where they
20
+ * came from.
21
+ */
22
+ const ATTRIBUTION_REFUSALS = new Set(["unknown_attribution_field", "invalid_attribution", "attribution_frozen"]);
23
+
24
+ export function isAttributionRefusal(err: unknown): boolean {
25
+ if (!(err instanceof RevenexxException) || err.code !== 400) {
26
+ return false;
27
+ }
28
+ if (ATTRIBUTION_REFUSALS.has(apiErrorCode(err))) {
29
+ return true;
30
+ }
31
+ return /attribution/i.test(String(err.message ?? ""));
32
+ }
33
+
34
+ type SdkClient = RevenexxSdk["client"];
35
+
36
+ /** The SDK client, adding `extra` to the body of the request it sends. */
37
+ function clientAdding(client: SdkClient, extra: Record<string, unknown>): SdkClient {
38
+ return new Proxy(client, {
39
+ get(target, prop, receiver) {
40
+ if (prop === "call") {
41
+ return (method: string, url: URL, headers: Record<string, string>, payload?: Record<string, unknown>) =>
42
+ target.call(method, url, headers, { ...(payload ?? {}), ...extra } as never);
43
+ }
44
+ const value = Reflect.get(target, prop, receiver);
45
+ return typeof value === "function" ? value.bind(target) : value;
46
+ },
47
+ });
48
+ }
49
+
50
+ export async function placeOrderWithAttribution<T>(submission: unknown, attribution: Attribution | null): Promise<T> {
51
+ const sdk = useRevenexxSdk();
52
+ if (!attribution) {
53
+ return await sdk.orders.ordersPlace(submission as never) as unknown as T;
54
+ }
55
+ try {
56
+ return await new Orders(clientAdding(sdk.client, { attribution }) as never).ordersPlace(submission as never) as unknown as T;
57
+ }
58
+ catch (err) {
59
+ if (!isAttributionRefusal(err)) {
60
+ throw err;
61
+ }
62
+ getLogService().warn("order attribution refused, placed without it", apiErrorContext(err));
63
+ return await sdk.orders.ordersPlace(submission as never) as unknown as T;
64
+ }
65
+ }
@@ -0,0 +1,28 @@
1
+ import type { H3Event } from "h3";
2
+
3
+ import { codeList, type Viewer } from "../../app/shared/personalisation";
4
+
5
+ /**
6
+ * Who is looking at a page, for onsite personalisation (RAD-293): the
7
+ * purposes the visitor allowed in the cookie choice (the browser sends them
8
+ * as `consents=`), and — only if those include the personalisation purpose —
9
+ * the audiences of the signed-in contact, asked of the audiences app here.
10
+ *
11
+ * The audiences are never taken from the browser: what a contact is shown
12
+ * would otherwise be whatever the address bar claimed. Without consent, or
13
+ * signed out, the viewer is anonymous and sees what everybody sees.
14
+ */
15
+ export async function resolvePersonalisationViewer(event: H3Event, consentsParam: unknown): Promise<Viewer> {
16
+ const consents = codeList(consentsParam);
17
+ const config = useAppConfig() as { marketing?: { purposes?: { personalisation?: string } } };
18
+ const purpose = config.marketing?.purposes?.personalisation ?? "marketing";
19
+ if (!consents.includes(purpose)) {
20
+ return { audiences: [], consents };
21
+ }
22
+ const contactId = sessionOrderRefs(event).contact_id;
23
+ if (!contactId) {
24
+ return { audiences: [], consents };
25
+ }
26
+ const audiences = codeList(await getMarketingService(event).audienceCodes(event, contactId));
27
+ return { audiences, consents };
28
+ }