import { describe, expect, it, vi } from "vitest"; import { createAnalyticsEvent, createAnalyticsPageView, defaultAnalyticsPeriod, findAnalyticsPortalForTenant, findFeatureFlagByName, getAnalyticsEventFilterOptions, getAnalyticsEventList, getAnalyticsOverview, getAnalyticsPageViewFilterOptions, getAnalyticsPageViewList, getAnalyticsSettings, getAnalyticsVisitorList, getOrCreateAnalyticsSettings, deleteAllAnalyticsData, removeAnalyticsIgnoredPage, sanitizeAnalyticsReferrer, sanitizeAnalyticsUrl, updateAnalyticsSettingsPreferences, getOrCreateAnalyticsUniqueVisitor, isAnalyticsPeriod, updateAnalyticsUniqueVisitorSource, type AnalyticsClient, type AnalyticsUniqueVisitor, } from "./analytics.server.js"; function createAnalyticsClient(): AnalyticsClient { return { analyticsSettings: { findFirst: vi.fn().mockResolvedValue({ id: "settings_1", public: false, ignorePages: "/health", onlyPages: "" }), create: vi.fn().mockResolvedValue({ id: "settings_1", public: false, ignorePages: "/analytics,/admin/analytics", onlyPages: "" }), update: vi.fn().mockResolvedValue({ id: "settings_1", public: true, ignorePages: "/health,/docs", onlyPages: "" }), }, analyticsUniqueVisitor: { count: vi.fn().mockResolvedValue(4), findFirst: vi.fn().mockResolvedValue(null), findUnique: vi.fn().mockResolvedValue(null), create: vi.fn().mockResolvedValue(createVisitor()), update: vi.fn().mockResolvedValue(createVisitor()), findMany: vi.fn().mockResolvedValue([{ id: "visitor_1" }]), deleteMany: vi.fn().mockResolvedValue({ count: 1 }), groupBy: vi.fn().mockImplementation(({ by }) => { const field = by[0]; if (field === "createdAt") { return Promise.resolve([ { createdAt: new Date("2024-06-15T01:00:00.000Z"), _count: 1 }, { createdAt: new Date("2024-06-15T18:30:00.000Z"), _count: 2 }, { createdAt: new Date("2024-06-16T01:00:00.000Z"), _count: 3 }, ]); } return Promise.resolve([ { [field]: "low", _count: 1 }, { [field]: "high", _count: 7 }, { [field]: null, _count: 3 }, ]); }), }, analyticsEvent: { count: vi.fn().mockResolvedValue(8), groupBy: vi.fn().mockImplementation(({ by }) => Promise.resolve([{ [by[0]]: `${by[0]}_1` }])), findMany: vi.fn().mockResolvedValue([{ id: "event_1" }]), create: vi.fn().mockResolvedValue({ id: "event_1" }), deleteMany: vi.fn().mockResolvedValue({ count: 1 }), }, analyticsPageView: { count: vi.fn().mockResolvedValue(12), findMany: vi.fn().mockResolvedValue([{ id: "page_view_1" }]), groupBy: vi.fn().mockImplementation(({ by }) => { const field = by[0]; if (field === "uniqueVisitorId") { return Promise.resolve([ { uniqueVisitorId: "visitor_1", _count: 3 }, { uniqueVisitorId: "visitor_2", _count: 1 }, ]); } if (field === "createdAt") { return Promise.resolve([ { createdAt: new Date("2024-06-15T05:00:00.000Z"), _count: 4 }, { createdAt: new Date("2024-06-15T23:30:00.000Z"), _count: 5 }, { createdAt: new Date("2024-06-16T05:00:00.000Z"), _count: 6 }, ]); } if (field === "url") { return Promise.resolve(Array.from({ length: 12 }, (_, index) => ({ [field]: `/url-${index}`, _count: 12 - index }))); } return Promise.resolve([ { [field]: "low", _count: 2 }, { [field]: "high", _count: 9 }, ]); }), create: vi.fn().mockResolvedValue({ id: "page_view_1" }), deleteMany: vi.fn().mockResolvedValue({ count: 1 }), }, user: { findMany: vi.fn().mockResolvedValue([ { id: "user_1", email: "ada@example.com", firstName: "Ada", lastName: "Lovelace" }, { id: "user_2", email: "grace@example.com", firstName: null, lastName: null }, ]), }, featureFlag: { findFirst: vi.fn().mockResolvedValue({ id: "flag_1" }), findMany: vi.fn().mockResolvedValue([{ id: "flag_1", name: "New home" }]), }, portal: { findFirst: vi.fn().mockResolvedValue({ id: "portal_1", tenantId: "tenant_1" }), findMany: vi.fn().mockResolvedValue([{ id: "portal_1", title: "Docs portal" }]), }, }; } function createVisitor(overrides: Partial = {}): AnalyticsUniqueVisitor { return { id: "visitor_1", cookie: "cookie_1", source: "google", medium: "cpc", campaign: "spring", content: "hero", term: "analytics", country: "DE", city: "Berlin", userId: "user_1", portalUserId: "portal_user_1", ...overrides, }; } describe("analytics period helpers", () => { it("exposes a default period and rejects invalid periods", () => { expect(defaultAnalyticsPeriod).toBe("last-30-days"); expect(isAnalyticsPeriod("last-hour")).toBe(true); expect(isAnalyticsPeriod("last-7-days")).toBe(true); expect(isAnalyticsPeriod("not-a-period")).toBe(false); }); }); describe("analytics redaction helpers", () => { it("strips sensitive query data from stored analytics URLs and referrers", () => { expect(sanitizeAnalyticsUrl("/reset?token=secret&utm_source=newsletter&email=ada@example.com")).toBe("/reset?utm_source=newsletter"); expect(sanitizeAnalyticsUrl("https://example.com/callback?code=secret&ref=docs#ignored")).toBe("https://example.com/callback?ref=docs"); expect(sanitizeAnalyticsReferrer("https://referrer.example.com/path?token=secret")).toBe("https://referrer.example.com"); }); }); describe("analytics overview aggregation", () => { it("passes portal and last-7-days createdAt filters to count and groupBy calls", async () => { const client = createAnalyticsClient(); const now = new Date("2024-06-20T12:00:00.000Z"); await getAnalyticsOverview({ period: "last-7-days", portalId: "portal_1", now }, client); expect(client.analyticsUniqueVisitor.count).toHaveBeenCalledWith({ where: { portalId: "portal_1", createdAt: { gte: new Date("2024-06-13T12:00:00.000Z") } }, }); expect(client.analyticsPageView.count).toHaveBeenCalledWith({ where: { portalId: "portal_1", createdAt: { gte: new Date("2024-06-13T12:00:00.000Z") } }, }); expect(client.analyticsEvent.count).toHaveBeenCalledWith({ where: { portalId: "portal_1", createdAt: { gte: new Date("2024-06-13T12:00:00.000Z") } }, }); expect(client.analyticsUniqueVisitor.groupBy).toHaveBeenCalledWith( expect.objectContaining({ by: ["source"], where: { portalId: "portal_1", createdAt: { gte: new Date("2024-06-13T12:00:00.000Z") } }, }) ); }); it("uses a last-hour window for totals and a one-minute window for live visitors", async () => { const client = createAnalyticsClient(); const now = new Date("2024-06-20T12:30:00.000Z"); await getAnalyticsOverview({ period: "last-hour", portalId: null, now }, client); expect(client.analyticsPageView.count).toHaveBeenCalledWith({ where: { portalId: null, createdAt: { gte: new Date("2024-06-20T11:30:00.000Z") } }, }); expect(client.analyticsPageView.groupBy).toHaveBeenCalledWith( expect.objectContaining({ by: ["uniqueVisitorId"], where: { portalId: null, createdAt: { gte: new Date("2024-06-20T12:29:00.000Z") } }, }) ); }); it("anchors all-time ranges to the first tracked visitor for totals and charts", async () => { const client = createAnalyticsClient(); vi.mocked(client.analyticsUniqueVisitor.findFirst).mockResolvedValue({ createdAt: new Date("2024-01-02T03:04:05.000Z") }); await getAnalyticsOverview({ period: "all-time", portalId: "portal_2", now: new Date("2024-06-20T12:00:00.000Z") }, client); expect(client.analyticsUniqueVisitor.findFirst).toHaveBeenCalledWith({ where: { portalId: "portal_2" }, orderBy: { createdAt: "asc" } }); expect(client.analyticsUniqueVisitor.count).toHaveBeenCalledWith({ where: { portalId: "portal_2", createdAt: { gte: new Date("2024-01-02T03:04:05.000Z") } }, }); expect(client.analyticsPageView.groupBy).toHaveBeenCalledWith( expect.objectContaining({ by: ["createdAt"], where: { portalId: "portal_2", createdAt: { gte: new Date("2024-01-02T03:04:05.000Z") } }, }) ); }); it("sorts top counts, caps URLs, counts live visitor groups, skips users by default, and aggregates chart labels", async () => { const client = createAnalyticsClient(); const overview = await getAnalyticsOverview({ period: "last-7-days", portalId: "portal_1", now: new Date("2024-06-20T12:00:00.000Z") }, client); expect(overview).toMatchObject({ uniqueVisitors: 4, pageViews: 12, events: 8, liveVisitors: 2 }); expect(overview.top.sources).toEqual([ { name: "high", count: 7 }, { name: null, count: 3 }, { name: "low", count: 1 }, ]); expect(overview.top.urls).toHaveLength(10); expect(overview.top.urls[0]).toEqual({ name: "/url-0", count: 12 }); expect(overview.top.user).toEqual([]); expect(client.user.findMany).not.toHaveBeenCalled(); expect(client.analyticsUniqueVisitor.groupBy).not.toHaveBeenCalledWith(expect.objectContaining({ by: ["userId"] })); expect(overview.charts.pageViewsAndUniqueVisitors).toEqual([ { date: "Jun 15", "Page views": 9, "Unique visitors": 3 }, { date: "Jun 16", "Page views": 6, "Unique visitors": 3 }, ]); }); it("formats chart bucket labels with the requested locale without changing counts", async () => { const client = createAnalyticsClient(); const overview = await getAnalyticsOverview( { period: "last-7-days", portalId: "portal_1", locale: "de", now: new Date("2024-06-20T12:00:00.000Z") }, client ); expect(overview.charts.pageViewsAndUniqueVisitors).toEqual([ { date: "15. Juni", "Page views": 9, "Unique visitors": 3 }, { date: "16. Juni", "Page views": 6, "Unique visitors": 3 }, ]); }); it("looks up top user display names only when requested without selecting password fields", async () => { const client = createAnalyticsClient(); vi.mocked(client.analyticsUniqueVisitor.groupBy).mockImplementation(({ by }) => { const field = by[0]; if (field === "userId") { return Promise.resolve([ { userId: "user_1", _count: 5 }, { userId: "user_2", _count: 3 }, { userId: null, _count: 1 }, ]); } if (field === "createdAt") { return Promise.resolve([{ createdAt: new Date("2024-06-16T01:00:00.000Z"), _count: 3 }]); } return Promise.resolve([{ [field]: "high", _count: 7 }]); }); const overview = await getAnalyticsOverview( { period: "last-7-days", portalId: "portal_1", withUsers: true, now: new Date("2024-06-20T12:00:00.000Z") }, client ); expect(client.analyticsUniqueVisitor.groupBy).toHaveBeenCalledWith({ by: ["userId"], _count: true, where: { portalId: "portal_1", createdAt: { gte: new Date("2024-06-13T12:00:00.000Z") } }, }); expect(client.user.findMany).toHaveBeenCalledWith({ select: { id: true, email: true, firstName: true, lastName: true }, where: { id: { in: ["user_1", "user_2"] } }, }); expect(overview.top.user).toEqual([ { name: "Ada Lovelace", count: 5 }, { name: "grace@example.com", count: 3 }, { name: null, count: 1 }, ]); }); }); describe("analytics list read models", () => { it("binds portal analytics reads to an exact tenant and portal pair", async () => { const client = createAnalyticsClient(); await expect(findAnalyticsPortalForTenant({ portalId: "portal_1", tenantId: "tenant_1" }, client)).resolves.toEqual({ id: "portal_1", tenantId: "tenant_1", }); expect(client.portal.findFirst).toHaveBeenCalledWith({ where: { id: "portal_1", tenantId: "tenant_1" }, select: { id: true, tenantId: true }, }); }); it("reads visitor pages with pagination, count filters, and relation counts", async () => { const client = createAnalyticsClient(); const where = { source: "google" }; await expect(getAnalyticsVisitorList({ take: 25, skip: 50, where }, client)).resolves.toEqual({ items: [{ id: "visitor_1" }], totalItems: 4 }); expect(client.analyticsUniqueVisitor.findMany).toHaveBeenCalledWith({ take: 25, skip: 50, where, include: { _count: { select: { pageViews: true, events: true, }, }, }, orderBy: { createdAt: "desc" }, }); expect(client.analyticsUniqueVisitor.count).toHaveBeenCalledWith({ where }); }); it("reads event pages with pass-through filters and unique visitor include", async () => { const client = createAnalyticsClient(); const where = { action: "click", category: { not: null } }; await expect(getAnalyticsEventList({ take: 10, skip: 20, where }, client)).resolves.toEqual({ items: [{ id: "event_1" }], totalItems: 8 }); expect(client.analyticsEvent.findMany).toHaveBeenCalledWith({ take: 10, skip: 20, include: { uniqueVisitor: true }, orderBy: { createdAt: "desc" }, where, }); expect(client.analyticsEvent.count).toHaveBeenCalledWith({ where }); }); it("reads page-view pages with visitor user email and portal title only", async () => { const client = createAnalyticsClient(); const where = { uniqueVisitor: { userId: "user_1" } }; await expect(getAnalyticsPageViewList({ take: 15, skip: 30, where }, client)).resolves.toEqual({ items: [{ id: "page_view_1" }], totalItems: 12 }); expect(client.analyticsPageView.findMany).toHaveBeenCalledWith({ take: 15, skip: 30, include: { uniqueVisitor: { include: { user: { select: { email: true }, }, }, }, portal: { select: { id: true, title: true } }, }, orderBy: { createdAt: "desc" }, where, }); expect(client.analyticsPageView.count).toHaveBeenCalledWith({ where }); }); it("provides event action/category/label/value and feature flag filter option shapes", async () => { const client = createAnalyticsClient(); await expect(getAnalyticsEventFilterOptions(client)).resolves.toEqual({ actions: [{ value: "action_1", name: "action_1" }], categories: [{ value: "category_1", name: "category_1" }], labels: [{ value: "label_1", name: "label_1" }], values: [{ value: "value_1", name: "value_1" }], featureFlags: [{ value: "flag_1", name: "New home" }], }); expect(client.analyticsEvent.groupBy).toHaveBeenCalledWith({ by: ["action"] }); expect(client.analyticsEvent.groupBy).toHaveBeenCalledWith({ where: { category: { not: null } }, by: ["category"] }); expect(client.analyticsEvent.groupBy).toHaveBeenCalledWith({ where: { label: { not: null } }, by: ["label"] }); expect(client.analyticsEvent.groupBy).toHaveBeenCalledWith({ where: { value: { not: null } }, by: ["value"] }); expect(client.featureFlag.findMany).toHaveBeenCalledWith({ select: { id: true, name: true }, where: { enabled: undefined } }); }); it("provides page-view route, portal, and display-only user option shapes", async () => { const client = createAnalyticsClient(); vi.mocked(client.analyticsUniqueVisitor.groupBy).mockResolvedValue([{ userId: "user_1" }, { userId: null }]); await expect(getAnalyticsPageViewFilterOptions({ includePortals: true }, client)).resolves.toEqual({ routes: [ { value: "low", name: "low" }, { value: "high", name: "high" }, ], users: [ { value: "user_1", name: "ada@example.com" }, { value: "user_2", name: "grace@example.com" }, ], portals: [{ value: "portal_1", name: "Docs portal" }], }); expect(client.analyticsPageView.groupBy).toHaveBeenCalledWith({ by: ["route"] }); expect(client.analyticsUniqueVisitor.groupBy).toHaveBeenCalledWith({ by: ["userId"] }); expect(client.user.findMany).toHaveBeenCalledWith({ select: { id: true, email: true }, where: { id: { in: ["user_1", ""] } }, }); expect(client.portal.findMany).toHaveBeenCalledWith({ select: { id: true, title: true } }); }); }); describe("analytics write helpers", () => { it("creates and updates unique visitors through the injected analytics client", async () => { const client = createAnalyticsClient(); vi.mocked(client.analyticsUniqueVisitor.findUnique).mockResolvedValue(null); await getOrCreateAnalyticsUniqueVisitor( { cookie: "cookie_2", fromUrl: "/from", fromRoute: "/route", analytics: { userAgent: { type: "desktop", os: { family: "macOS", version: "14" }, browser: { name: "Chrome", version: "120" } }, referrer: { http: "https://example.com/path?token=secret", via: "web", source: "newsletter", utm_medium: "email", utm_campaign: "launch", utm_content: "button", utm_term: "hivegrid", }, region: { country: "US", city: "Austin" }, userId: "user_2", portalId: "portal_1", portalUserId: "portal_user_2", }, }, client ); expect(client.analyticsUniqueVisitor.create).toHaveBeenCalledWith({ data: { cookie: "cookie_2", httpReferrer: "https://example.com", via: "web", browser: "Chrome", browserVersion: "120", os: "macOS", osVersion: "14", device: "desktop", source: "newsletter", medium: "email", campaign: "launch", content: "button", term: "hivegrid", country: "US", city: "Austin", fromUrl: "/from", fromRoute: "/route", userId: "user_2", portalId: "portal_1", portalUserId: "portal_user_2", }, }); await updateAnalyticsUniqueVisitorSource(createVisitor({ source: "old", medium: "old" }), { referrer: { source: "new", utm_medium: "organic" } }, client); expect(client.analyticsUniqueVisitor.update).toHaveBeenCalledWith({ where: { id: "visitor_1" }, data: { source: "new", medium: "organic" }, }); }); it("does not update a visitor when no tracked fields changed", async () => { const client = createAnalyticsClient(); await updateAnalyticsUniqueVisitorSource( createVisitor(), { referrer: { source: "google", utm_medium: "cpc", utm_campaign: "spring" }, region: { country: "DE", city: "Berlin" }, userId: "user_1", portalUserId: "portal_user_1", }, client ); expect(client.analyticsUniqueVisitor.update).not.toHaveBeenCalled(); }); it("creates page views, events, reads settings, and looks up feature flags", async () => { const client = createAnalyticsClient(); await createAnalyticsPageView( { uniqueVisitorId: "visitor_1", url: "/docs?token=secret&utm_source=newsletter", route: "/docs", portalId: "portal_1", portalUserId: "portal_user_1" }, client ); await createAnalyticsEvent( { uniqueVisitorId: "visitor_1", action: "click", category: "cta", url: "/event?email=ada@example.com", portalId: "portal_1", featureFlagId: "flag_1" }, client ); await expect(getAnalyticsSettings(client)).resolves.toEqual({ id: "settings_1", public: false, ignorePages: "/health", onlyPages: "" }); await expect(findFeatureFlagByName("new-home", client)).resolves.toEqual({ id: "flag_1" }); expect(client.analyticsPageView.create).toHaveBeenCalledWith({ data: { uniqueVisitorId: "visitor_1", url: "/docs?utm_source=newsletter", route: "/docs", portalId: "portal_1", portalUserId: "portal_user_1" }, }); expect(client.analyticsEvent.create).toHaveBeenCalledWith({ data: { uniqueVisitorId: "visitor_1", action: "click", category: "cta", url: "/event", portalId: "portal_1", featureFlagId: "flag_1" }, }); expect(client.analyticsSettings.findFirst).toHaveBeenCalledWith({ select: { public: true, ignorePages: true } }); expect(client.featureFlag.findFirst).toHaveBeenCalledWith({ where: { name: "new-home" }, select: { id: true } }); }); it("gets or creates analytics settings with the package-owned defaults", async () => { const client = createAnalyticsClient(); vi.mocked(client.analyticsSettings.findFirst).mockResolvedValueOnce(null); await expect(getOrCreateAnalyticsSettings(client)).resolves.toEqual({ id: "settings_1", public: false, ignorePages: "/analytics,/admin/analytics", onlyPages: "", }); expect(client.analyticsSettings.findFirst).toHaveBeenCalledWith({}); expect(client.analyticsSettings.create).toHaveBeenCalledWith({ data: { public: false, ignorePages: "/analytics", onlyPages: "" } }); }); it("updates analytics public and ignored-page preferences without duplicating existing pages", async () => { const client = createAnalyticsClient(); await updateAnalyticsSettingsPreferences({ public: true, ignorePage: "/docs" }, client); expect(client.analyticsSettings.update).toHaveBeenCalledWith({ where: { id: "settings_1" }, data: { public: true, ignorePages: "/health,/docs" }, }); await updateAnalyticsSettingsPreferences({ public: false, ignorePage: "/health" }, client); expect(client.analyticsSettings.update).toHaveBeenLastCalledWith({ where: { id: "settings_1" }, data: { public: false, ignorePages: "/health" }, }); }); it("removes ignored pages while leaving non-existing removals as a safe no-op list update", async () => { const client = createAnalyticsClient(); await removeAnalyticsIgnoredPage("/missing", client); expect(client.analyticsSettings.update).toHaveBeenCalledWith({ where: { id: "settings_1" }, data: { ignorePages: "/health" }, }); vi.mocked(client.analyticsSettings.findFirst).mockResolvedValueOnce({ id: "settings_1", public: false, ignorePages: "/health,/docs", onlyPages: "" }); await removeAnalyticsIgnoredPage("/health", client); expect(client.analyticsSettings.update).toHaveBeenLastCalledWith({ where: { id: "settings_1" }, data: { ignorePages: "/docs" }, }); }); it("deletes analytics data through relation-safe package-owned delete calls", async () => { const client = createAnalyticsClient(); await deleteAllAnalyticsData(client); expect(client.analyticsEvent.deleteMany).toHaveBeenCalledWith({}); expect(client.analyticsPageView.deleteMany).toHaveBeenCalledWith({}); expect(client.analyticsUniqueVisitor.deleteMany).toHaveBeenCalledWith({}); expect(vi.mocked(client.analyticsEvent.deleteMany).mock.invocationCallOrder[0]).toBeLessThan( vi.mocked(client.analyticsPageView.deleteMany).mock.invocationCallOrder[0] ); expect(vi.mocked(client.analyticsPageView.deleteMany).mock.invocationCallOrder[0]).toBeLessThan( vi.mocked(client.analyticsUniqueVisitor.deleteMany).mock.invocationCallOrder[0] ); }); });