@revenexx/cover 0.19.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 (45) 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/review/form/ReviewForm.vue +211 -0
  11. package/app/composables/useCampaignAttribution.ts +120 -0
  12. package/app/composables/useCheckoutOnePage.ts +9 -0
  13. package/app/composables/useLoyaltyAccount.ts +79 -0
  14. package/app/composables/useMarketingConsent.ts +49 -0
  15. package/app/config/navigation.ts +1 -1
  16. package/app/config/quickActions.ts +1 -0
  17. package/app/pages/account/points.vue +26 -0
  18. package/app/pages/newsletter/confirm/[token].vue +23 -0
  19. package/app/pages/newsletter/preferences/[token].vue +24 -0
  20. package/app/pages/review/[token].vue +23 -0
  21. package/app/plugins/campaign-attribution.client.ts +47 -0
  22. package/app/shared/campaignAttribution.ts +281 -0
  23. package/app/shared/personalisation.ts +107 -0
  24. package/i18n/locales/de/account.json +3 -2
  25. package/i18n/locales/de/marketing.json +71 -0
  26. package/i18n/locales/en/account.json +3 -2
  27. package/i18n/locales/en/marketing.json +71 -0
  28. package/package.json +1 -1
  29. package/server/api/campaigns/touches.post.ts +42 -0
  30. package/server/api/cart/attribution.put.ts +31 -0
  31. package/server/api/loyalty/account.get.ts +27 -0
  32. package/server/api/newsletter/confirm/[token].post.ts +21 -0
  33. package/server/api/newsletter/preferences/[token].get.ts +14 -0
  34. package/server/api/newsletter/preferences/[token].post.ts +36 -0
  35. package/server/api/orders/index.post.ts +10 -1
  36. package/server/api/reviews/requests/[token].get.ts +14 -0
  37. package/server/api/reviews/submit/[token].post.ts +31 -0
  38. package/server/interfaces/cart.ts +6 -0
  39. package/server/interfaces/marketing.ts +150 -0
  40. package/server/services/ApiCartService.ts +16 -0
  41. package/server/services/ApiMarketingService.ts +292 -0
  42. package/server/services/MockMarketingService.ts +178 -0
  43. package/server/utils/marketingService.ts +63 -0
  44. package/server/utils/orderAttribution.ts +65 -0
  45. package/server/utils/personalisationViewer.ts +28 -0
@@ -0,0 +1,178 @@
1
+ import type { H3Event } from "h3";
2
+
3
+ import type {
4
+ ConfirmResult,
5
+ IMarketingService,
6
+ LoyaltyAccount,
7
+ PreferenceChange,
8
+ PreferenceChoice,
9
+ PreferenceView,
10
+ ReviewInput,
11
+ ReviewRequestView,
12
+ ReviewSubmitResult,
13
+ } from "../interfaces/marketing";
14
+ import { MarketingTokenError } from "../interfaces/marketing";
15
+
16
+ /**
17
+ * Demo answers for the marketing pages (RAD-293), so a storefront without
18
+ * gateway credentials can show every page and a test has something to drive.
19
+ *
20
+ * A token containing `expired` answers as an expired link, one containing
21
+ * `unknown` as a link nobody issued; any other token is a valid one. The
22
+ * loyalty account is the eltric "Premium" agreement of the click dummy
23
+ * (designer draft 2026-10-14): last year 88.300 €, three stages at 100, 105
24
+ * and 110 % of it.
25
+ */
26
+
27
+ const PREFERENCE_TYPES = [
28
+ { code: "newsletter", label: { de: "Newsletter", en: "Newsletter" }, description: { de: "Neuheiten und Angebote, etwa zweimal im Monat.", en: "News and offers, about twice a month." } },
29
+ { code: "product-news", label: { de: "Produktinformationen", en: "Product information" }, description: { de: "Wenn ein Artikel aus Ihren Bestellungen ein Update bekommt.", en: "When an article you ordered gets an update." } },
30
+ ] as const;
31
+
32
+ const BASE = 88300;
33
+
34
+ function refuse(token: string): void {
35
+ if (token.includes("expired")) {
36
+ throw new MarketingTokenError("expired");
37
+ }
38
+ if (token.includes("unknown")) {
39
+ throw new MarketingTokenError("unknown");
40
+ }
41
+ }
42
+
43
+ function lang(locale: string): "de" | "en" {
44
+ return locale.startsWith("en") ? "en" : "de";
45
+ }
46
+
47
+ export class MockMarketingService implements IMarketingService {
48
+ /** Per token, which types are subscribed — survives a reload in one dev server. */
49
+ private readonly subscriptions = new Map<string, Set<string>>();
50
+ private readonly reviewed = new Map<string, Set<string>>();
51
+
52
+ async confirmSubscription(_event: H3Event, token: string): Promise<ConfirmResult> {
53
+ refuse(token);
54
+ return { alreadyConfirmed: token.includes("confirmed") };
55
+ }
56
+
57
+ private view(token: string, locale: string): PreferenceView {
58
+ const subscribed = this.subscriptions.get(token) ?? new Set(["newsletter"]);
59
+ this.subscriptions.set(token, subscribed);
60
+ return {
61
+ addressHint: "e•••@example.com",
62
+ types: PREFERENCE_TYPES.map(type => ({
63
+ code: type.code,
64
+ label: type.label[lang(locale)],
65
+ description: type.description[lang(locale)],
66
+ subscribed: subscribed.has(type.code),
67
+ state: subscribed.has(type.code) ? "confirmed" : null,
68
+ consentTextId: null,
69
+ consentText: lang(locale) === "en"
70
+ ? "I would like to receive this by email. I can withdraw at any time."
71
+ : "Ich möchte das per E-Mail erhalten. Ich kann jederzeit widerrufen.",
72
+ })),
73
+ };
74
+ }
75
+
76
+ async preferences(_event: H3Event, token: string, locale: string): Promise<PreferenceView> {
77
+ refuse(token);
78
+ return this.view(token, locale);
79
+ }
80
+
81
+ async savePreferences(
82
+ _event: H3Event,
83
+ token: string,
84
+ input: { choices?: PreferenceChoice[]; unsubscribeAll?: boolean; locale: string },
85
+ ): Promise<{ view: PreferenceView; changes: PreferenceChange[] }> {
86
+ refuse(token);
87
+ const subscribed = this.subscriptions.get(token) ?? new Set(["newsletter"]);
88
+ const changes: PreferenceChange[] = [];
89
+ if (input.unsubscribeAll) {
90
+ for (const code of subscribed) {
91
+ changes.push({ subscription_type: code, action: "withdrawn" });
92
+ }
93
+ subscribed.clear();
94
+ }
95
+ else {
96
+ for (const choice of input.choices ?? []) {
97
+ const had = subscribed.has(choice.subscription_type);
98
+ if (choice.subscribed && !had) {
99
+ // A new type with double opt-in waits for its confirmation mail.
100
+ changes.push({ subscription_type: choice.subscription_type, action: "requested" });
101
+ }
102
+ else if (!choice.subscribed && had) {
103
+ subscribed.delete(choice.subscription_type);
104
+ changes.push({ subscription_type: choice.subscription_type, action: "withdrawn" });
105
+ }
106
+ else {
107
+ changes.push({ subscription_type: choice.subscription_type, action: "unchanged" });
108
+ }
109
+ }
110
+ }
111
+ this.subscriptions.set(token, subscribed);
112
+ return { view: this.view(token, input.locale), changes };
113
+ }
114
+
115
+ async reviewRequest(_event: H3Event, token: string): Promise<ReviewRequestView> {
116
+ refuse(token);
117
+ const done = this.reviewed.get(token) ?? new Set<string>();
118
+ return {
119
+ orderNumber: "100234",
120
+ expiresAt: null,
121
+ products: [
122
+ { productId: "demo-drill", sku: "BM-4711", name: "Akku-Bohrschrauber 18 V", reviewed: done.has("demo-drill") },
123
+ { productId: "demo-bits", sku: "BT-0815", name: "Bit-Set 32-teilig", reviewed: done.has("demo-bits") },
124
+ ],
125
+ };
126
+ }
127
+
128
+ async submitReviews(_event: H3Event, token: string, reviews: ReviewInput[]): Promise<ReviewSubmitResult> {
129
+ refuse(token);
130
+ const done = this.reviewed.get(token) ?? new Set<string>();
131
+ const result: ReviewSubmitResult = { accepted: [], rejected: [] };
132
+ for (const review of reviews) {
133
+ if (done.has(review.product_id)) {
134
+ result.rejected.push({ productId: review.product_id, reason: "already_reviewed" });
135
+ continue;
136
+ }
137
+ done.add(review.product_id);
138
+ result.accepted.push(review.product_id);
139
+ }
140
+ this.reviewed.set(token, done);
141
+ return result;
142
+ }
143
+
144
+ async loyaltyAccount(): Promise<LoyaltyAccount | null> {
145
+ const perks = [{ de: "Premiumversand: frachtfrei ab 75 € statt 145 €", en: "Premium shipping: free from €75 instead of €145" }];
146
+ return {
147
+ memberships: [{
148
+ program: { code: "premium", labels: { de: "eltric Premium", en: "eltric Premium" }, kind: "turnover_bonus" },
149
+ tier: { code: "stufe-2", labels: { de: "Stufe 2", en: "Stage 2" }, perks },
150
+ pointsBalance: null,
151
+ agreementId: "demo-agreement",
152
+ }],
153
+ progress: {
154
+ period: new Date().getFullYear(),
155
+ currency: "EUR",
156
+ turnoverYtd: 93148,
157
+ projectedTurnover: 101420,
158
+ tiers: [
159
+ { code: "stufe-1", labels: { de: "Stufe 1", en: "Stage 1" }, threshold: BASE, bonusPercent: 1, reached: true, current: false },
160
+ { code: "stufe-2", labels: { de: "Stufe 2", en: "Stage 2" }, threshold: 92715, bonusPercent: 2, reached: true, current: true },
161
+ { code: "stufe-3", labels: { de: "Stufe 3", en: "Stage 3" }, threshold: 97130, bonusPercent: 3, reached: false, current: false },
162
+ ],
163
+ nextTier: { code: "stufe-3", labels: { de: "Stufe 3", en: "Stage 3" }, gap: 3982, bonusPercent: 3 },
164
+ bonusNow: 1862.96,
165
+ expectedBonus: 3042.6,
166
+ requiresNoOverdue: true,
167
+ },
168
+ };
169
+ }
170
+
171
+ async audienceCodes(): Promise<string[]> {
172
+ return [];
173
+ }
174
+
175
+ async recordTouches(): Promise<void> {
176
+ // The demo counts nothing: there is no campaign to count for.
177
+ }
178
+ }
@@ -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
+ }