feat(analytics): instrument privacy-minimized catalog navigation
This commit is contained in:
1 parent
c62d9836e9
commit
13dc74807a
8 files changed
+145
-32
No files matched your search
@@ -1,10 +1,12 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import { analyticsAllowed, catalogRoute, trackCatalogClick } from '../lib/catalogAnalytics';
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
globalPrivacyControl?: boolean;
|
||||
dataLayer?: any[];
|
||||
clarity?: any;
|
||||
gtag?: (...args: any[]) => void;
|
||||
@@ -20,42 +22,36 @@ interface AnalyticsDeferredProps {
|
||||
export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsDeferredProps) {
|
||||
const pathname = usePathname();
|
||||
const loadedRef = useRef(false);
|
||||
const initialPathRef = useRef<string | null>(null);
|
||||
const lastPathRef = useRef<string | null>(null);
|
||||
const pathnameRef = useRef(pathname);
|
||||
useEffect(() => { pathnameRef.current = pathname; }, [pathname]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!initialPathRef.current && pathname) {
|
||||
initialPathRef.current = pathname;
|
||||
}
|
||||
}, [pathname]);
|
||||
const emit = useCallback((event: string, params: Record<string, string>) => {
|
||||
if (!analyticsAllowed(navigator, window)) return;
|
||||
if (gaId && window.gtag) window.gtag('event', event, params);
|
||||
else if (gtmId && window.dataLayer) window.dataLayer.push({ event, ...params });
|
||||
}, [gaId, gtmId]);
|
||||
|
||||
const recordView = useCallback((path: string) => {
|
||||
if (lastPathRef.current === path) return;
|
||||
lastPathRef.current = path;
|
||||
const route = catalogRoute(path);
|
||||
emit('page_view', { page_path: route, page_location: window.location.origin + route, page_referrer: '' });
|
||||
if (route === '/shop/[slug]') emit('catalog_product_view', { content_type: 'product' });
|
||||
if (route === '/blog/[slug]' || route === '/wiki/[slug]') emit('catalog_content_view', { content_type: route.startsWith('/blog') ? 'article' : 'wiki' });
|
||||
}, [emit]);
|
||||
|
||||
// Track client-side page views on Next.js route transitions
|
||||
useEffect(() => {
|
||||
if (!pathname || !loadedRef.current) return;
|
||||
if (pathname === initialPathRef.current) return;
|
||||
|
||||
// 1. Google Analytics 4 page_view event on client navigation
|
||||
if (gaId && typeof window !== 'undefined' && typeof window.gtag === 'function') {
|
||||
window.gtag('event', 'page_view', {
|
||||
page_path: pathname,
|
||||
page_location: window.location.href,
|
||||
page_title: typeof document !== 'undefined' ? document.title : '',
|
||||
});
|
||||
}
|
||||
|
||||
// 2. Google Tag Manager page_view event on client navigation
|
||||
if (gtmId && typeof window !== 'undefined' && Array.isArray(window.dataLayer)) {
|
||||
window.dataLayer.push({
|
||||
event: 'page_view',
|
||||
page_path: pathname,
|
||||
});
|
||||
}
|
||||
}, [pathname, gaId, gtmId]);
|
||||
recordView(pathname);
|
||||
}, [pathname, recordView]);
|
||||
|
||||
useEffect(() => {
|
||||
let loaded = false;
|
||||
|
||||
const loadAnalytics = () => {
|
||||
if (loaded) return;
|
||||
if (loaded || !analyticsAllowed(navigator, window)) return;
|
||||
loaded = true;
|
||||
loadedRef.current = true;
|
||||
|
||||
@@ -85,7 +81,7 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
|
||||
}
|
||||
window.gtag = gtag;
|
||||
gtag('js', new Date());
|
||||
gtag('config', gaId, { page_path: window.location.pathname });
|
||||
gtag('config', gaId, { send_page_view: false, page_title: '', page_location: window.location.origin + catalogRoute(pathnameRef.current || '/'), page_referrer: '' });
|
||||
|
||||
// Only append gtag.js script if not already added
|
||||
if (!document.querySelector(`script[src*="${gaId}"]`)) {
|
||||
@@ -112,8 +108,16 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
|
||||
else l.head.appendChild(t);
|
||||
})(window, document, 'clarity', 'script', clarityId);
|
||||
}
|
||||
if (pathnameRef.current) recordView(pathnameRef.current);
|
||||
};
|
||||
|
||||
const onClick = (event: MouseEvent) => {
|
||||
if (!loadedRef.current || !analyticsAllowed(navigator, window)) return;
|
||||
const anchor = event.target instanceof Element ? event.target.closest('a') : null;
|
||||
if (anchor instanceof HTMLAnchorElement) trackCatalogClick(event, anchor, pathnameRef.current || '/', emit);
|
||||
};
|
||||
document.addEventListener('click', onClick);
|
||||
|
||||
// Listen to first user interaction
|
||||
window.addEventListener('scroll', loadAnalytics, { passive: true, once: true });
|
||||
window.addEventListener('touchstart', loadAnalytics, { passive: true, once: true });
|
||||
@@ -133,6 +137,8 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
|
||||
return () => {
|
||||
loaded = true;
|
||||
loadedRef.current = false;
|
||||
lastPathRef.current = null;
|
||||
document.removeEventListener('click', onClick);
|
||||
clearTimeout(timer);
|
||||
if (idleId !== undefined) window.cancelIdleCallback(idleId);
|
||||
window.removeEventListener('scroll', loadAnalytics);
|
||||
@@ -140,7 +146,7 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
|
||||
window.removeEventListener('mousemove', loadAnalytics);
|
||||
window.removeEventListener('keydown', loadAnalytics);
|
||||
};
|
||||
}, [gtmId, gaId, clarityId]);
|
||||
}, [gtmId, gaId, clarityId, emit, recordView]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -54,14 +54,19 @@ it('tracks client-side route changes when pathname changes',()=>{
|
||||
mockPathname = '/blog/test-article';
|
||||
rerender(<AnalyticsDeferred gaId="G-test" gtmId="GTM-test"/>);
|
||||
|
||||
const gtmPageView = window.dataLayer?.find(entry => entry.event === 'page_view' && entry.page_path === '/blog/test-article');
|
||||
expect(gtmPageView).toBeDefined();
|
||||
const gtmPageView = window.dataLayer?.find(entry => entry.event === 'page_view');
|
||||
expect(gtmPageView).toBeUndefined(); // direct GA is the single first-party owner
|
||||
mockPathname = '/';
|
||||
rerender(<AnalyticsDeferred gaId="G-test" gtmId="GTM-test"/>);
|
||||
const views = window.dataLayer?.filter(entry => entry[0] === 'event' && entry[1] === 'page_view');
|
||||
expect(views?.map(entry => entry[2].page_path)).toEqual(['/','/blog/[slug]','/']);
|
||||
expect(views?.every(entry => !('page_title' in entry[2]) && !entry[2].page_location.includes('?'))).toBe(true);
|
||||
|
||||
const gaPageView = window.dataLayer?.find(entry => {
|
||||
return Object.prototype.toString.call(entry) === '[object Arguments]' && entry[0] === 'event' && entry[1] === 'page_view';
|
||||
});
|
||||
expect(gaPageView).toBeDefined();
|
||||
expect(gaPageView[2].page_path).toBe('/blog/test-article');
|
||||
expect(gaPageView[2].page_path).toBe('/');
|
||||
});
|
||||
|
||||
it.each(['scroll','touchstart','mousemove','keydown'])('loads on %s',event=>{
|
||||
@@ -115,6 +120,32 @@ it('cancels idle work on unmount',()=>{
|
||||
expect(cancelIdleCallback).toHaveBeenCalledWith(9);
|
||||
});
|
||||
|
||||
it('honors opt-out before loading and after initialization',()=>{
|
||||
window.globalPrivacyControl=true;
|
||||
const v=render(<AnalyticsDeferred gaId="G-test"/>);
|
||||
fireEvent.scroll(window);
|
||||
expect(document.scripts).toHaveLength(0);
|
||||
delete window.globalPrivacyControl;
|
||||
fireEvent.keyDown(window);
|
||||
const count=window.dataLayer?.length;
|
||||
window.globalPrivacyControl=true;
|
||||
mockPathname='/shop/joint';v.rerender(<AnalyticsDeferred gaId="G-test"/>);
|
||||
expect(window.dataLayer).toHaveLength(count!);
|
||||
delete window.globalPrivacyControl;
|
||||
});
|
||||
|
||||
it('tracks catalog views and actual enabled contact anchors without commerce events',()=>{
|
||||
mockPathname='/shop/joint';
|
||||
const v=render(<AnalyticsDeferred gaId="G-test"/>);
|
||||
fireEvent.scroll(window);
|
||||
const a=document.createElement('a');a.href='tel:private';document.body.append(a);
|
||||
fireEvent.click(a);a.remove();
|
||||
expect(window.dataLayer?.filter(e=>e[0]==='event').map(e=>e[1])).toEqual(['page_view','catalog_product_view','contact_intent']);
|
||||
expect(window.dataLayer?.some(e=>e[0]==='config' && e[2].send_page_view===false)).toBe(true);
|
||||
mockPathname='/shop/joint';v.rerender(<AnalyticsDeferred gaId="G-test"/>);
|
||||
expect(window.dataLayer?.filter(e=>e[1]==='catalog_product_view')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('unmount removes event and timeout callbacks',()=>{
|
||||
const v=render(<AnalyticsDeferred gtmId="GTM-test"/>);
|
||||
v.unmount();
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import {describe,it,expect,vi} from 'vitest';
|
||||
import {catalogRoute, analyticsAllowed, trackCatalogClick} from '../catalogAnalytics';
|
||||
describe('catalog analytics privacy and intent',()=>{
|
||||
it('uses bounded public route templates without identifiers or private URLs',()=>{
|
||||
expect(catalogRoute('/shop/joint')).toBe('/shop/[slug]');
|
||||
expect(catalogRoute('/blog/article')).toBe('/blog/[slug]');
|
||||
expect(catalogRoute('/dashboard/orders/secret')).toBe('/other');
|
||||
});
|
||||
it('respects browser privacy signals',()=>{expect(analyticsAllowed({doNotTrack:'1'},{})).toBe(false);expect(analyticsAllowed({}, {globalPrivacyControl:true})).toBe(false);});
|
||||
it('records article to product intent without href, title, query or contact data',()=>{
|
||||
const emit=vi.fn(); const a=document.createElement('a');a.href='/shop/joint?email=private#phone';a.textContent='private';
|
||||
trackCatalogClick(new MouseEvent('click'),a,'/blog/article',emit);
|
||||
expect(emit).toHaveBeenCalledExactlyOnceWith('internal_navigation',{source_route:'/blog/[slug]',target_route:'/shop/[slug]'});
|
||||
});
|
||||
it('records actual contact anchors but never contact value or external navigation',()=>{
|
||||
const emit=vi.fn();const a=document.createElement('a');a.href='tel:private';trackCatalogClick(new MouseEvent('click'),a,'/shop/joint',emit);
|
||||
expect(emit).toHaveBeenCalledExactlyOnceWith('contact_intent',{source_route:'/shop/[slug]',contact_type:'phone'});
|
||||
emit.mockClear();a.href='https://external.test';trackCatalogClick(new MouseEvent('click'),a,'/blog/a',emit);expect(emit).not.toHaveBeenCalled();
|
||||
});
|
||||
it('ignores cancelled, modified, and non-primary clicks',()=>{const emit=vi.fn();const a=document.createElement('a');a.href='/shop/a';for(const event of [new MouseEvent('click',{ctrlKey:true}),new MouseEvent('click',{button:1})]) trackCatalogClick(event,a,'/blog/a',emit);const event=new MouseEvent('click',{cancelable:true});event.preventDefault();trackCatalogClick(event,a,'/blog/a',emit);expect(emit).not.toHaveBeenCalled();});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
// Only bounded route classes leave the browser; never arbitrary paths or contact values.
|
||||
export function catalogRoute(path: string): string {
|
||||
if (/^\/(shop|blog|wiki)\/[^/]+\/?$/.test(path)) return `/${path.split('/')[1]}/[slug]`;
|
||||
return ['/', '/shop', '/blog', '/wiki', '/catalog', '/about', '/contact', '/videos'].includes(path) ? path : '/other';
|
||||
}
|
||||
|
||||
export function analyticsAllowed(nav: { doNotTrack?: string | null; globalPrivacyControl?: boolean }, browser: { globalPrivacyControl?: boolean }): boolean {
|
||||
return nav.doNotTrack !== '1' && !nav.globalPrivacyControl && !browser.globalPrivacyControl;
|
||||
}
|
||||
|
||||
export type CatalogEmitter = (event: string, params: Record<string, string>) => void;
|
||||
|
||||
export function trackCatalogClick(event: MouseEvent, anchor: HTMLAnchorElement, source: string, emit: CatalogEmitter): void {
|
||||
if (event.defaultPrevented || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey || anchor.hasAttribute('download')) return;
|
||||
const url = new URL(anchor.href, window.location.origin);
|
||||
const source_route = catalogRoute(source);
|
||||
if (url.protocol === 'tel:' || url.protocol === 'mailto:') {
|
||||
emit('contact_intent', { source_route, contact_type: url.protocol === 'tel:' ? 'phone' : 'email' });
|
||||
return;
|
||||
}
|
||||
if (url.origin !== window.location.origin || !['http:', 'https:'].includes(url.protocol)) return;
|
||||
const target_route = catalogRoute(url.pathname);
|
||||
if (target_route === '/other' || url.pathname === source) return;
|
||||
if (!['/blog/[slug]', '/wiki/[slug]', '/shop/[slug]'].includes(source_route) && target_route !== '/contact') return;
|
||||
emit(target_route === '/contact' ? 'contact_intent' : 'internal_navigation', target_route === '/contact'
|
||||
? { source_route, contact_type: 'contact_page' } : { source_route, target_route });
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
# Plan
|
||||
Change only AnalyticsDeferred and a first-party catalog analytics helper/tests. Direct GA owns first-party events when configured; otherwise GTM dataLayer. Disable GA automatic initial pageview and explicitly emit current route on deferred initialization. Classify route templates instead of exporting arbitrary slugs. Delegate click listener records real anchors only, ignores prevented/non-primary clicks and external destinations except bounded contact schemes. No checkout/payment code edits. Stage acceptance requires immutable SHA, browser/network/DebugView and ingestion receipts; this task does not push/deploy.
|
||||
|
||||
Baseline 312fcc2acc8f07dcf20d3d6ee0165ba8e619122e on develop; concurrent backend/worker/.specify/evidence and graph cache changes excluded. Graph hash 6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af (SHA binding unverified, navigation only); graph nodes AnalyticsDeferred/layout and useCatalogMode/ProductPage verified directly against source. specify 1.2.3 check passes.
|
||||
@@ -0,0 +1,2 @@
|
||||
# Catalog analytics
|
||||
Online sales are intentionally closed pending importer approval. Absence of purchases is not a tracking failure. Preserve all catalog/checkout flags; no commerce instrumentation or runtime changes. Emit one sanitized pageview per committed pathname including return to initial path, catalog product/article views, bounded internal navigation and actual clicked contact CTA intent. No customer data, search/query/hash, contact values or page titles. Respect configured analytics enablement and browser DNT/GPC. No new requests in tests. Organic acquisition and engagement remain vendor reporting, not invented client events.
|
||||
@@ -0,0 +1,4 @@
|
||||
# Tasks
|
||||
1. RED route return, single-owner, privacy, catalog navigation/contact/opt-out tests.
|
||||
2. Implement helper and integration without changing catalog availability.
|
||||
3. GREEN targeted tests, catalog guard regressions, typecheck/lint/build; document gaps separately from runtime proof.
|
||||
@@ -0,0 +1,18 @@
|
||||
# Local verification and release boundary
|
||||
|
||||
## Outcome
|
||||
Catalog mode remains untouched. Online sales are intentionally closed pending importer approval; historical absence of ecommerce rows is not evidence of broken tracking or no demand. No add/remove cart, checkout, purchase, subscription, money/currency conversion or backend changes made. This supersedes the initial commerce implementation request.
|
||||
|
||||
First-party events: explicit `page_view`, `catalog_product_view`, `catalog_content_view`, `internal_navigation`, `contact_intent`. Route classes only: no raw slugs, titles, search terms, query/hash, customer identity or contact destination. Views measure committed routes, not server-confirmed product availability or paid conversions. Article-to-product clicks carry source/target route classes, not content-level attribution. Contact intent only follows an actual anchor click (tel/mailto/internal contact page), not an inferred lead, submitted form or active subscription. Modified/cancelled/non-primary clicks excluded. Direct GA owns these events when configured; otherwise GTM dataLayer. Existing deferred initialization preserved. Returning to initial pathname emits again; same-path query/hash changes intentionally do not. DNT and GPC prevent initialization and first-party emissions; existing configured enablement remains controlled by layout/SEO settings. No consent CMP/storage policy was found or introduced.
|
||||
|
||||
## TDD and checks
|
||||
- RED: targeted run before implementation: route single-owner assertion failed (old duplicate GTM pageview) and helper suite failed unresolved new module; 12 existing tests passed. Tests existed before implementation.
|
||||
- GREEN: targeted analytics plus ProductPage/CheckoutPage catalog guard regressions: 4 files, 38 tests passed.
|
||||
- Full storefront suite: 99 files, 509 tests passed, exit 0. Log `/opt/data/cache/scratch/catalog-analytics-full-tests.log` (local non-versioned evidence).
|
||||
- `npm run typecheck`: exit 0.
|
||||
- Targeted ESLint: exit 0; 9 pre-existing-style `any` warnings in vendor shim, no Hook dependency warnings.
|
||||
- `npm run build`: exit 0; all 29 static pages generated. Build reports unavailable local backend reads at 127.0.0.1:4001/4400 and workspace-lockfile warning. Therefore not proof of integrated API content or Stage acceptance.
|
||||
- Tests only inspect DOM/shim payloads in jsdom, no new third-party network requests. Existing catalog restrictions verified in ProductPage/CheckoutPage tests; availability code not edited.
|
||||
|
||||
## Not yet proven / Stage prerequisites
|
||||
No push, deployment, runtime configuration, analytics provisioning, live writes or vendor event delivery performed. Release must pin the explicit commit containing these files, never build a moving shared HEAD. Browser/network + DebugView receipts and later GA4 report ingestion needed before calling telemetry live. GTM container and GA4 enhanced-measurement history settings were not inspected; third-party duplicate tags/automatic history events and vendor-collected URL/referrer defaults need a separate configuration/privacy audit. This patch's single-owner guarantee is only for first-party emitted events, not arbitrary GTM tags. Deferred short visits/clicks before initialization remain undercounted. Route-template minimization intentionally prevents per-article/product identification; approved public content IDs and registration of bounded custom dimensions are a follow-up contract if needed. Organic acquisition and engagement remain GA4/GSC reporting, not synthesized events. Clarity project installation exists but export token still needs secure user provisioning; no token changes in this scope. Commerce stays out of scope until business authorization and verified paid-order/money contracts exist.
|
||||
Reference in new issue
Block a user