Fas 1a: analytics tracker, ingestion endpoint, admin dashboards

This commit is contained in:
Sven (AAMOS AI)
2026-08-05 22:15:37 +07:00
parent d627014425
commit 1250640b1d
16 changed files with 4544 additions and 6450 deletions
+17
View File
@@ -0,0 +1,17 @@
{
"name": "@app/analytics",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "Product analytics tracker (spec §8.2) React Native batch sender + typed builders.",
"exports": {
".": "./src/index.ts"
},
"scripts": {
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"@app/shared-types": "workspace:*"
}
}
+90
View File
@@ -0,0 +1,90 @@
/**
* Typed event builders for the product analytics taxonomy.
* Each builder returns a plain AnalyticsEvent ready for batching.
*/
import type { ProductAnalyticsEventName } from "@app/shared-types";
import type { AnalyticsEvent } from "./types.js";
function builder(name: ProductAnalyticsEventName) {
return (props?: {
occurredAt?: string;
anonymousId?: string;
sessionId?: string;
householdId?: string;
appVersion?: string;
platform?: "ios" | "android" | "web";
locale?: string;
experimentVariant?: string;
properties?: Record<string, unknown>;
}): AnalyticsEvent => ({ name, ...props });
}
// Acquisition & onboarding
export const appInstalled = builder("app_installed");
export const appFirstOpen = builder("app_first_open");
export const onboardingStarted = builder("onboarding_started");
export const onboardingStepCompleted = builder("onboarding_step_completed");
export const onboardingSkipped = builder("onboarding_skipped");
export const accountCreated = builder("account_created");
export const householdCreated = builder("household_created");
export const householdJoined = builder("household_joined");
export const allergySetupCompleted = builder("allergy_setup_completed");
export const cameraPermissionResult = builder("camera_permission_result");
export const notificationPermissionResult = builder("notification_permission_result");
// Inventory
export const scanStarted = builder("scan_started");
export const scanUploaded = builder("scan_uploaded");
export const scanProcessingCompleted = builder("scan_processing_completed");
export const scanProcessingFailed = builder("scan_processing_failed");
export const scanReviewOpened = builder("scan_review_opened");
export const scanItemConfirmed = builder("scan_item_confirmed");
export const scanItemCorrected = builder("scan_item_corrected");
export const scanItemRemoved = builder("scan_item_removed");
export const scanCompleted = builder("scan_completed");
export const inventoryItemAdded = builder("inventory_item_added");
export const inventoryItemConsumed = builder("inventory_item_consumed");
export const inventoryItemDiscarded = builder("inventory_item_discarded");
export const inventoryReconciliationStarted = builder("inventory_reconciliation_started");
export const inventoryReconciliationCompleted = builder("inventory_reconciliation_completed");
export const inventoryConflictCreated = builder("inventory_conflict_created");
export const inventoryConflictResolved = builder("inventory_conflict_resolved");
// Recipes & cooking
export const recommendationsViewed = builder("recommendations_viewed");
export const recommendationOpened = builder("recommendation_opened");
export const recipeSaved = builder("recipe_saved");
export const cookingSessionStarted = builder("cooking_session_started");
export const cookingSessionCompleted = builder("cooking_session_completed");
export const cookingSessionCancelled = builder("cooking_session_cancelled");
export const leftoversCreated = builder("leftovers_created");
export const substitutionConfirmed = builder("substitution_confirmed");
// Shopping
export const shoppingItemAdded = builder("shopping_item_added");
export const shoppingItemChecked = builder("shopping_item_checked");
export const shoppingListShared = builder("shopping_list_shared");
export const receiptScanned = builder("receipt_scanned");
export const purchaseImported = builder("purchase_imported");
// Household
export const householdInviteSent = builder("household_invite_sent");
export const householdInviteAccepted = builder("household_invite_accepted");
export const secondMemberFirstAction = builder("second_member_first_action");
// Subscription
export const paywallViewed = builder("paywall_viewed");
export const trialStarted = builder("trial_started");
export const trialCancelled = builder("trial_cancelled");
export const subscriptionStarted = builder("subscription_started");
export const subscriptionRenewed = builder("subscription_renewed");
export const subscriptionGracePeriod = builder("subscription_grace_period");
export const subscriptionCancelled = builder("subscription_cancelled");
export const subscriptionExpired = builder("subscription_expired");
export const entitlementRestored = builder("entitlement_restored");
// Feedback
export const feedbackSubmitted = builder("feedback_submitted");
export const incorrectInventoryReported = builder("incorrect_inventory_reported");
export const badRecommendationReported = builder("bad_recommendation_reported");
export const supportContactStarted = builder("support_contact_started");
+3
View File
@@ -0,0 +1,3 @@
export * from "./types.js";
export * from "./builders.js";
export * from "./tracker.js";
+111
View File
@@ -0,0 +1,111 @@
/**
* React Native analytics tracker: small in-memory queue + periodic flush.
* No PII is stored locally beyond anonymous/session ids.
*/
import type { AnalyticsBatchResult, AnalyticsEvent, TrackerConfig } from "./types.js";
export type SendBatch = (events: AnalyticsEvent[]) => Promise<AnalyticsBatchResult>;
export interface Tracker {
track: (event: AnalyticsEvent) => void;
flush: () => Promise<AnalyticsBatchResult>;
setSessionId: (sessionId: string) => void;
setAuthToken: (token: string | undefined) => void;
setAnonymousId: (anonymousId: string) => void;
destroy: () => void;
}
/**
* Create a tracker that batches events in memory and flushes periodically.
* In a React Native app the storage adapter (AsyncStorage) should persist
* anonymousId; this tracker intentionally keeps no durable local state.
*/
export function createTracker(config: TrackerConfig, send: SendBatch): Tracker {
const maxBatchSize = config.maxBatchSize ?? 20;
const flushIntervalMs = config.flushIntervalMs ?? 10_000;
let queue: AnalyticsEvent[] = [];
let sessionId = config.sessionId ?? "";
let authToken = config.authToken ?? "";
let anonymousId = config.anonymousId ?? "";
function enrich(event: AnalyticsEvent): AnalyticsEvent {
return {
...event,
anonymousId: event.anonymousId ?? anonymousId,
sessionId: event.sessionId ?? sessionId,
appVersion: event.appVersion ?? config.appVersion,
platform: event.platform ?? config.platform,
locale: event.locale ?? config.locale,
occurredAt: event.occurredAt ?? new Date().toISOString(),
};
}
async function flush(): Promise<AnalyticsBatchResult> {
if (queue.length === 0) return { accepted: 0 };
const batch = queue.slice(0, maxBatchSize);
queue = queue.slice(maxBatchSize);
try {
const result = await send(batch);
if (result.rejected && result.rejected > 0) {
// Put rejected events back at the front of the queue only if the
// server asked us to retry (e.g. rate limit). For validation errors
// we drop them to avoid an infinite retry loop.
const retryable = batch.filter((_, i) =>
result.errors?.some((e) => e.index === i && e.message.toLowerCase().includes("rate limit")),
);
queue = [...retryable, ...queue];
}
return result;
} catch (err) {
// Network failure: keep events for next flush.
queue = [...batch, ...queue];
return { accepted: 0, rejected: batch.length, errors: [{ index: 0, message: String(err) }] };
}
}
const timer = flushIntervalMs > 0 ? setInterval(() => void flush(), flushIntervalMs) : null;
return {
track(event: AnalyticsEvent) {
queue.push(enrich(event));
if (queue.length >= maxBatchSize) {
void flush();
}
},
flush,
setSessionId(next) {
sessionId = next;
},
setAuthToken(next) {
authToken = next ?? "";
},
setAnonymousId(next) {
anonymousId = next;
},
destroy() {
if (timer) clearInterval(timer);
},
};
}
/**
* Default HTTP sender for the batch endpoint.
* This function has no React Native dependencies and can be used anywhere.
*/
export function createHttpSend(config: { apiBaseUrl: string; authToken?: string }): SendBatch {
return async (events) => {
const res = await fetch(`${config.apiBaseUrl.replace(/\/$/, "")}/v1/analytics/events`, {
method: "POST",
headers: {
"Content-Type": "application/json",
...(config.authToken ? { Authorization: `Bearer ${config.authToken}` } : {}),
},
body: JSON.stringify({ events }),
});
if (!res.ok) {
const text = await res.text().catch(() => "unknown error");
throw new Error(`Analytics API ${res.status}: ${text}`);
}
return (await res.json().catch(() => ({ accepted: events.length }))) as AnalyticsBatchResult;
};
}
+50
View File
@@ -0,0 +1,50 @@
/**
* Product analytics tracker types (spec §8.2).
* Events are plain JSON objects validated against the shared taxonomy.
*/
import type { ProductAnalyticsEventName } from "@app/shared-types";
export interface AnalyticsEvent {
name: ProductAnalyticsEventName;
/** ISO 8601 timestamp. Defaults to now if omitted. */
occurredAt?: string;
/** UUID or device-stable pseudonymous id. */
anonymousId?: string;
/** Session id, rotated periodically. */
sessionId?: string;
/** Active household when event was produced. */
householdId?: string;
appVersion?: string;
platform?: "ios" | "android" | "web";
locale?: string;
experimentVariant?: string;
/** Structured, safe properties only (no PII, no free text). */
properties?: Record<string, unknown>;
}
export interface AnalyticsBatchPayload {
events: AnalyticsEvent[];
}
export interface AnalyticsBatchResult {
accepted: number;
rejected?: number;
errors?: Array<{ index: number; message: string }>;
}
export interface TrackerConfig {
apiBaseUrl: string;
/** Auth token; events sent before login are anonymous. */
authToken?: string;
/** Anonymous id persisted for this install. */
anonymousId: string;
/** Current session id. */
sessionId?: string;
appVersion: string;
platform: "ios" | "android" | "web";
locale: string;
/** Max events per batch. */
maxBatchSize?: number;
/** Flush interval in ms. */
flushIntervalMs?: number;
}
+115
View File
@@ -0,0 +1,115 @@
/**
* Unit tests for the analytics tracker.
*/
import { describe, expect, it, vi } from "vitest";
import { createTracker, appFirstOpen, scanStarted } from "@app/analytics";
import type { AnalyticsBatchResult, AnalyticsEvent, SendBatch } from "@app/analytics";
describe("createTracker", () => {
it("enriches events with default context and flushes immediately when batch is full", async () => {
const sent: AnalyticsEvent[][] = [];
const send: SendBatch = vi.fn(async (events) => {
sent.push(events);
return { accepted: events.length } satisfies AnalyticsBatchResult;
});
const tracker = createTracker(
{
apiBaseUrl: "http://localhost:4000",
anonymousId: "anon-1",
sessionId: "session-1",
appVersion: "1.0.0",
platform: "ios",
locale: "sv-SE",
maxBatchSize: 2,
flushIntervalMs: 0,
},
send,
);
tracker.track(appFirstOpen());
tracker.track(scanStarted({ properties: { source: "camera" } }));
await tracker.flush();
expect(sent).toHaveLength(1);
const firstBatch = sent[0]!;
expect(firstBatch).toHaveLength(2);
expect(firstBatch[0]).toBeDefined();
expect(firstBatch[0]!.name).toBe("app_first_open");
expect(firstBatch[0]!.anonymousId).toBe("anon-1");
expect(firstBatch[0]!.sessionId).toBe("session-1");
expect(firstBatch[0]!.appVersion).toBe("1.0.0");
expect(firstBatch[0]!.platform).toBe("ios");
expect(firstBatch[0]!.locale).toBe("sv-SE");
expect(firstBatch[0]!.occurredAt).toBeDefined();
expect(firstBatch[1]).toBeDefined();
expect(firstBatch[1]!.name).toBe("scan_started");
expect(firstBatch[1]!.properties).toEqual({ source: "camera" });
tracker.destroy();
});
it("requeues events when send fails", async () => {
let calls = 0;
const send: SendBatch = vi.fn(async () => {
calls++;
if (calls === 1) throw new Error("network");
return { accepted: 1 };
});
const tracker = createTracker(
{
apiBaseUrl: "http://localhost:4000",
anonymousId: "anon-2",
appVersion: "1.0.0",
platform: "android",
locale: "en-US",
maxBatchSize: 1,
flushIntervalMs: 0,
},
send,
);
tracker.track(appFirstOpen());
const first = await tracker.flush();
expect(first.accepted).toBe(0);
const second = await tracker.flush();
expect(second.accepted).toBe(1);
expect(send).toHaveBeenCalledTimes(2);
tracker.destroy();
});
it("drops validation-rejected events instead of retrying forever", async () => {
const send: SendBatch = vi.fn(async () => ({
accepted: 0,
rejected: 1,
errors: [{ index: 0, message: "validation error, do not retry" }],
}));
const tracker = createTracker(
{
apiBaseUrl: "http://localhost:4000",
anonymousId: "anon-3",
appVersion: "1.0.0",
platform: "web",
locale: "sv-SE",
maxBatchSize: 100,
flushIntervalMs: 0,
},
send,
);
tracker.track(appFirstOpen());
const result = await tracker.flush();
expect(result.rejected).toBe(1);
// Queue should be empty; second flush returns zero.
const second = await tracker.flush();
expect(second.accepted).toBe(0);
expect(send).toHaveBeenCalledTimes(1);
tracker.destroy();
});
});
+9
View File
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": ".",
"lib": ["ES2023", "DOM"]
},
"include": ["src/**/*", "test/**/*"]
}