Loads Brevo's web tracker for a signed-in customer who has consented, reports route changes as page views, and tracks the three events the issue asked for: added_to_cart, favorited, and checkout_completed. The four design questions were settled on the issue in August and this implements those answers. The consent gate is the part worth reading. The decision recorded on the issue was "gate it behind consent", but the sentence customers actually agreed to named only email: "I want to receive occasional emails about new one-of-a-kind items". Gating a tracker on `marketing_consent` while that was the stored wording would have treated "email me about new items" as authorisation to send someone's browsing to a third party, which it does not say — and this project stores the wording verbatim against each customer precisely so that a record says what the customer saw. So the sentence is widened here, and the tracker is gated on `analytics_consent`, a field the server computes by comparing the wording stored against a customer with the current constant. Changing the sentence therefore does not retroactively widen anybody's consent: everyone who agreed to the old text keeps their email consent and is not tracked until they re-consent through the account page. A boolean alone could not tell those two populations apart, which is the whole reason the text is stored per customer. `analyticsConsent` is exported and has its own unit test, because "agreeing to the old wording does not authorise tracking" is the rule that silently tracks people if it regresses — their flag really is true. QA stays out of the live Brevo account by construction rather than by remembering. The key is per-environment, the tracker never loads without one, and `docker-compose.qa.yml` sets an empty literal with no stack variable behind it, so nothing can inherit a value from the host or be pasted in from production's stack. Same reasoning as QA_DB_PASSWORD and the QA_SMTP_ names beside it. Events are reported from the API layer rather than the UI call sites, so no caller can add to the cart or favorite an item without it being counted, and each fires only after the response was accepted — a refused add is not reported as one. The two checkout completions each name their processor, because a demo purchase charges nothing and counting it as a sale would overstate revenue. The privacy policy gains an analytics section in this change rather than a follow-up, since the published policy previously described none of this and would otherwise have lagged the code. It is deliberate about the limits: withdrawing consent stops further reporting, but anything already sent stays with Brevo, and a script already injected cannot be un-injected — `stopBrevoTracking` stops calls, it does not unload sa.js. That is said in the code too, because "tracking stops" reads as a stronger promise than any web tracker can make. Verified: backend tsc clean, both lint suites 0 errors with no new warnings, 474 unit tests passing across 33 suites, and the frontend production build green including the compose-environment guard. Not verified: integration and e2e, which need a database and a Node this machine does not have active, and no real Brevo key was exercised — the tracker has never been observed reporting to an actual account. Closes #56 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
121 lines
4.2 KiB
TypeScript
121 lines
4.2 KiB
TypeScript
// Reported here rather than at the UI call sites so that no caller can add an
|
|
// item or complete a checkout without it being counted (#56). Every one of
|
|
// these calls is a no-op unless a consenting customer is signed in and the
|
|
// environment has a key, so importing this into the API layer does not make the
|
|
// cart depend on analytics being configured.
|
|
import { brevoTrack } from '../brevo';
|
|
|
|
export interface CartItem {
|
|
item_id: number;
|
|
name: string;
|
|
price_cents: number;
|
|
status: string;
|
|
added_at: string;
|
|
expires_at: string;
|
|
images: { id: number; image_path: string }[];
|
|
}
|
|
|
|
export interface ShippingAddress {
|
|
id: number;
|
|
full_name: string;
|
|
address_line1: string;
|
|
address_line2: string | null;
|
|
city: string;
|
|
state: string;
|
|
postal_code: string;
|
|
country: string;
|
|
is_default: boolean;
|
|
usps_validated: boolean;
|
|
}
|
|
|
|
async function handle<T>(res: Response): Promise<T> {
|
|
if (!res.ok) {
|
|
const data = await res.json().catch(() => ({}));
|
|
throw new Error(data.error || 'Request failed');
|
|
}
|
|
return res.json();
|
|
}
|
|
|
|
export function fetchCart(): Promise<{ items: CartItem[] }> {
|
|
return fetch('/api/cart').then(res => handle(res));
|
|
}
|
|
|
|
export function addToCart(itemId: number): Promise<{ itemId: number; expiresAt: string }> {
|
|
// After handle(), which throws on a non-OK response — so a refused add (the
|
|
// item was already reserved by someone else) is not reported as one.
|
|
return fetch(`/api/cart/items/${itemId}`, { method: 'POST' })
|
|
.then(res => handle<{ itemId: number; expiresAt: string }>(res))
|
|
.then(result => {
|
|
brevoTrack('added_to_cart', { itemId });
|
|
return result;
|
|
});
|
|
}
|
|
|
|
export function removeFromCart(itemId: number): Promise<void> {
|
|
return fetch(`/api/cart/items/${itemId}`, { method: 'DELETE' }).then(() => undefined);
|
|
}
|
|
|
|
export function fetchAddresses(): Promise<ShippingAddress[]> {
|
|
return fetch('/api/customers/me/addresses').then(res => handle(res));
|
|
}
|
|
|
|
export interface AddressInput {
|
|
fullName: string;
|
|
addressLine1: string;
|
|
addressLine2?: string;
|
|
city: string;
|
|
state: string;
|
|
postalCode: string;
|
|
country?: string;
|
|
isDefault?: boolean;
|
|
}
|
|
|
|
export function createAddress(input: AddressInput): Promise<{ address: ShippingAddress; uspsCheck: { validated: boolean; deliverable: boolean | null; reason?: string }; uspsConfigured: boolean }> {
|
|
return fetch('/api/customers/me/addresses', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(input)
|
|
}).then(res => handle(res));
|
|
}
|
|
|
|
export function deleteAddress(id: number): Promise<void> {
|
|
return fetch(`/api/customers/me/addresses/${id}`, { method: 'DELETE' }).then(() => undefined);
|
|
}
|
|
|
|
export function setDefaultAddress(id: number): Promise<ShippingAddress> {
|
|
return fetch(`/api/customers/me/addresses/${id}/set-default`, { method: 'POST' }).then(res => handle(res));
|
|
}
|
|
|
|
export function createCartPaypalOrder(shippingAddressId: number): Promise<{ orderID: string }> {
|
|
return fetch('/api/checkout/cart/paypal/create', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ shippingAddressId })
|
|
}).then(res => handle(res));
|
|
}
|
|
|
|
// The two checkout completions are separate functions rather than one, so both
|
|
// report the event and both say which they were. Without the processor these
|
|
// would be indistinguishable in Brevo, and a demo purchase charges nothing —
|
|
// counting it as a sale would overstate revenue. QA cannot reach here anyway
|
|
// (no key), but DEMO_MODE is not exclusive to QA, so the distinction is real.
|
|
export function captureCartPaypalOrder(orderID: string): Promise<void> {
|
|
return fetch('/api/checkout/cart/paypal/capture', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ orderID })
|
|
})
|
|
.then(res => handle<void>(res))
|
|
.then(() => { brevoTrack('checkout_completed', { processor: 'paypal' }); });
|
|
}
|
|
|
|
export function demoCartPurchase(shippingAddressId: number): Promise<void> {
|
|
return fetch('/api/checkout/cart/demo/purchase', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ shippingAddressId })
|
|
})
|
|
.then(res => handle<void>(res))
|
|
.then(() => { brevoTrack('checkout_completed', { processor: 'demo' }); });
|
|
}
|