feat(console): product analytics screens (events feed, first-event proof, people, setup, privacy) and one nav line (A1)
The console signs a 5-minute HS256 org token with WebCrypto (no new dependency) and reads the service; screens refresh every 10 seconds while live, show capMessage at the cap, export a person as JSON and request a deletion that stays visible until done. Copy passes the vendored denylist. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
dbef356e6e
commit
ea3199891b
@ -0,0 +1,47 @@
|
||||
"use client";
|
||||
// Frame of every product analytics screen: title, the four screens, the app
|
||||
// picker, and (on live screens) a quiet refresh every 10 seconds.
|
||||
import { useEffect, type ReactNode } from "react";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
|
||||
const SCREENS = [
|
||||
{ href: "/product-analytics", label: "Events" },
|
||||
{ href: "/product-analytics/persons", label: "People" },
|
||||
{ href: "/product-analytics/setup", label: "Setup" },
|
||||
{ href: "/product-analytics/privacy", label: "Privacy" },
|
||||
];
|
||||
|
||||
export const REFRESH_MS = 10_000;
|
||||
|
||||
export function Shell({ title, apps, app, live = false, children }: { title: string; apps: string[]; app: string | null; live?: boolean; children: ReactNode }) {
|
||||
const path = usePathname();
|
||||
const router = useRouter();
|
||||
useEffect(() => {
|
||||
if (!live) return;
|
||||
const t = setInterval(() => router.refresh(), REFRESH_MS);
|
||||
return () => clearInterval(t);
|
||||
}, [live, router]);
|
||||
const q = app ? `?app=${encodeURIComponent(app)}` : "";
|
||||
return (
|
||||
<>
|
||||
<h1>{title}</h1>
|
||||
<nav className="row" aria-label="Product analytics" style={{ marginBottom: 18 }}>
|
||||
{SCREENS.map((s) => (
|
||||
<a key={s.href} href={`${s.href}${q}`} aria-current={path === s.href ? "page" : undefined} className="muted">
|
||||
{s.label}
|
||||
</a>
|
||||
))}
|
||||
{apps.length > 1 ? (
|
||||
<span className="row" style={{ marginLeft: "auto" }}>
|
||||
{apps.map((name) => (
|
||||
<a key={name} href={`${path}?app=${encodeURIComponent(name)}`} aria-current={name === app ? "true" : undefined}>
|
||||
{name}
|
||||
</a>
|
||||
))}
|
||||
</span>
|
||||
) : null}
|
||||
</nav>
|
||||
{children}
|
||||
</>
|
||||
);
|
||||
}
|
||||
119
apps/console/app/(app)/product-analytics/_lib/http.ts
Normal file
119
apps/console/app/(app)/product-analytics/_lib/http.ts
Normal file
@ -0,0 +1,119 @@
|
||||
// Server-only client for the product analytics service. Every call carries
|
||||
// a fresh org token scoped to the org's own app ids.
|
||||
|
||||
import { signOrgToken, type Role } from "./token.ts";
|
||||
|
||||
export interface PaConfig {
|
||||
url: string;
|
||||
secret: string;
|
||||
}
|
||||
|
||||
/** Null when the service is not connected on this deployment (the page says so). */
|
||||
export function paConfig(env: Record<string, string | undefined> = process.env): PaConfig | null {
|
||||
const url = env.PRODUCT_ANALYTICS_URL?.trim();
|
||||
const secret = env.PRODUCT_ANALYTICS_CONSOLE_SECRET?.trim();
|
||||
if (!url || !secret || secret.length < 32) return null;
|
||||
return { url: url.replace(/\/$/, ""), secret };
|
||||
}
|
||||
|
||||
export interface Scope {
|
||||
org_id: string;
|
||||
app_ids: string[];
|
||||
role?: Role;
|
||||
}
|
||||
|
||||
export class PaError extends Error {
|
||||
status: number;
|
||||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
export async function paFetch<T>(cfg: PaConfig, scope: Scope, path: string, init: RequestInit = {}, fetchImpl: typeof fetch = fetch, now = new Date()): Promise<T> {
|
||||
const token = await signOrgToken(cfg.secret, { org_id: scope.org_id, app_ids: scope.app_ids, role: scope.role ?? "owner" }, now);
|
||||
const res = await fetchImpl(`${cfg.url}${path}`, {
|
||||
...init,
|
||||
headers: { authorization: `Bearer ${token}`, "content-type": "application/json", ...(init.headers ?? {}) },
|
||||
cache: "no-store",
|
||||
});
|
||||
const text = await res.text();
|
||||
let body: unknown = null;
|
||||
try {
|
||||
body = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
body = null;
|
||||
}
|
||||
if (!res.ok) {
|
||||
const msg = body && typeof body === "object" && "error" in body ? String((body as { error: unknown }).error) : "Product analytics could not be reached. Try again shortly.";
|
||||
throw new PaError(res.status, msg);
|
||||
}
|
||||
return body as T;
|
||||
}
|
||||
|
||||
/** Raw response (for downloads). */
|
||||
export async function paRaw(cfg: PaConfig, scope: Scope, path: string, fetchImpl: typeof fetch = fetch, now = new Date()): Promise<Response> {
|
||||
const token = await signOrgToken(cfg.secret, { org_id: scope.org_id, app_ids: scope.app_ids, role: scope.role ?? "owner" }, now);
|
||||
return fetchImpl(`${cfg.url}${path}`, { headers: { authorization: `Bearer ${token}` }, cache: "no-store" });
|
||||
}
|
||||
|
||||
export interface AppRef {
|
||||
id: string;
|
||||
name: string;
|
||||
site_key: string;
|
||||
}
|
||||
|
||||
/** The app named in `?app=` if it is the org's, else the org's first app. */
|
||||
export function pickApp(apps: AppRef[], name: string | undefined): AppRef | null {
|
||||
return apps.find((a) => a.name === name) ?? apps[0] ?? null;
|
||||
}
|
||||
|
||||
export interface Status {
|
||||
project: { id: string; name: string };
|
||||
paused: boolean;
|
||||
first_event: { uuid: string; event: string; at: string } | null;
|
||||
usage: { month: string; received: number; stored: number; capped: number; dropped: number };
|
||||
org_stored_this_month: number;
|
||||
events_limit: number;
|
||||
cap_message: string | null;
|
||||
retention_days: number;
|
||||
}
|
||||
|
||||
export interface FeedEvent {
|
||||
uuid: string;
|
||||
event: string;
|
||||
distinct_id: string;
|
||||
timestamp: string;
|
||||
url: string | null;
|
||||
screen: string | null;
|
||||
lib: string | null;
|
||||
}
|
||||
|
||||
export interface PersonRow {
|
||||
id: string;
|
||||
properties: Record<string, unknown>;
|
||||
is_identified: boolean;
|
||||
created_at: string;
|
||||
distinct_ids: string[] | null;
|
||||
}
|
||||
|
||||
export interface PrivacyJob {
|
||||
id: string;
|
||||
distinct_id: string;
|
||||
requested_at: string;
|
||||
due_at: string;
|
||||
status: "queued" | "running" | "done" | "failed";
|
||||
finished_at: string | null;
|
||||
result: Record<string, number> | null;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface Settings {
|
||||
require_consent: boolean;
|
||||
autocapture: boolean;
|
||||
capture_pageview: boolean;
|
||||
flags_client_key: string | null;
|
||||
retention_days: number | null;
|
||||
}
|
||||
|
||||
export const fmtTime = (iso: string | null | undefined) => (iso ? new Date(iso).toISOString().replace("T", " ").slice(0, 16) + " UTC" : "");
|
||||
19
apps/console/app/(app)/product-analytics/_lib/token.ts
Normal file
19
apps/console/app/(app)/product-analytics/_lib/token.ts
Normal file
@ -0,0 +1,19 @@
|
||||
// The console's 5-minute org token for the product analytics service:
|
||||
// HS256 JWT {org_id, app_ids, role, iat, exp} signed with
|
||||
// PRODUCT_ANALYTICS_CONSOLE_SECRET (the service verifies it with jose).
|
||||
// WebCrypto only, so it runs on Workers without a new dependency.
|
||||
|
||||
import { b64url, hmacSha256 } from "../../../../lib/crypto.ts";
|
||||
|
||||
export const TOKEN_TTL_SECONDS = 300;
|
||||
|
||||
export type Role = "owner" | "admin" | "member" | "viewer";
|
||||
|
||||
const enc = new TextEncoder();
|
||||
const part = (v: unknown) => b64url(enc.encode(JSON.stringify(v)));
|
||||
|
||||
export async function signOrgToken(secret: string, claims: { org_id: string; app_ids: string[]; role: Role }, now: Date): Promise<string> {
|
||||
const iat = Math.floor(now.getTime() / 1000);
|
||||
const head = `${part({ alg: "HS256", typ: "JWT" })}.${part({ org_id: claims.org_id, app_ids: claims.app_ids, role: claims.role, iat, exp: iat + TOKEN_TTL_SECONDS })}`;
|
||||
return `${head}.${b64url(await hmacSha256(enc.encode(secret), head))}`;
|
||||
}
|
||||
107
apps/console/app/(app)/product-analytics/page.tsx
Normal file
107
apps/console/app/(app)/product-analytics/page.tsx
Normal file
@ -0,0 +1,107 @@
|
||||
import { currentSession } from "../../../lib/current.ts";
|
||||
import { deps } from "../../../lib/deps.ts";
|
||||
import { Shell } from "./_components/Shell.tsx";
|
||||
import { fmtTime, paConfig, paFetch, PaError, pickApp, type FeedEvent, type Status } from "./_lib/http.ts";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Events screen: the first-event proof and the live feed of the latest
|
||||
// events for one app (refreshed every 10 seconds).
|
||||
export default async function ProductAnalyticsPage({ searchParams }: { searchParams: { app?: string } }) {
|
||||
const s = (await currentSession())!;
|
||||
const apps = await deps().repo.listApps(s.org);
|
||||
const app = pickApp(apps, searchParams.app);
|
||||
const names = apps.map((a) => a.name);
|
||||
const cfg = paConfig();
|
||||
if (!app) {
|
||||
return (
|
||||
<Shell title="Product analytics" apps={names} app={null}>
|
||||
<section className="card">
|
||||
<p className="muted">Add an app first. Its events appear here.</p>
|
||||
<a href="/apps">Add an app</a>
|
||||
</section>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
if (!cfg) {
|
||||
return (
|
||||
<Shell title="Product analytics" apps={names} app={app.name}>
|
||||
<section className="card">
|
||||
<p className="muted">Product analytics is arriving on this deployment. Page analytics under Insights keeps working meanwhile.</p>
|
||||
</section>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
const scope = { org_id: s.org, app_ids: apps.map((a) => a.id) };
|
||||
let status: Status | null = null;
|
||||
let feed: FeedEvent[] = [];
|
||||
let problem: string | null = null;
|
||||
try {
|
||||
[status, { events: feed }] = await Promise.all([
|
||||
paFetch<Status>(cfg, scope, `/v1/projects/${app.id}/status`),
|
||||
paFetch<{ events: FeedEvent[] }>(cfg, scope, `/v1/projects/${app.id}/events?limit=50`),
|
||||
]);
|
||||
} catch (e) {
|
||||
problem = e instanceof PaError ? e.message : "Product analytics could not be reached. Try again shortly.";
|
||||
}
|
||||
return (
|
||||
<Shell title="Product analytics" apps={names} app={app.name} live>
|
||||
{problem ? (
|
||||
<section className="card">
|
||||
<p>{problem}</p>
|
||||
</section>
|
||||
) : null}
|
||||
{status ? (
|
||||
<section className="card">
|
||||
<h2>First event</h2>
|
||||
{status.first_event ? (
|
||||
<p data-copy-source="product-analytics /v1/projects/{id}/status (live query)">
|
||||
Received {status.first_event.event} at {fmtTime(status.first_event.at)}.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<p>Waiting for the first event from {app.name}.</p>
|
||||
<a href={`/product-analytics/setup?app=${encodeURIComponent(app.name)}`}>Set up the app</a>
|
||||
</>
|
||||
)}
|
||||
{status.paused ? <p className="muted">This organization is paused, so new events are not stored.</p> : null}
|
||||
{status.cap_message ? <p data-copy-source="lib/caps.ts with the plan's events limit">{status.cap_message}</p> : null}
|
||||
<p className="muted" data-copy-source="product-analytics /v1/projects/{id}/status (live query)">
|
||||
This month: {status.usage.stored.toLocaleString("en-US")} stored, {status.usage.capped.toLocaleString("en-US")} counted over the limit.
|
||||
</p>
|
||||
</section>
|
||||
) : null}
|
||||
{status ? (
|
||||
<section className="card">
|
||||
<h2>Latest events</h2>
|
||||
{feed.length === 0 ? (
|
||||
<p className="muted">No events yet. They appear here within seconds of arriving.</p>
|
||||
) : (
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Time</th>
|
||||
<th>Event</th>
|
||||
<th>Person</th>
|
||||
<th>Where</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-copy-source="product-analytics /v1/projects/{id}/events (live query)">
|
||||
{feed.map((e) => (
|
||||
<tr key={e.uuid}>
|
||||
<td>{fmtTime(e.timestamp)}</td>
|
||||
<td>{e.event}</td>
|
||||
<td>
|
||||
<a href={`/product-analytics/persons/${encodeURIComponent(e.distinct_id)}?app=${encodeURIComponent(app.name)}`}>{e.distinct_id}</a>
|
||||
</td>
|
||||
<td>{e.screen ?? e.url ?? ""}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</section>
|
||||
) : null}
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
@ -0,0 +1,21 @@
|
||||
// Download one person's data as one JSON file (proxied from the service with
|
||||
// a fresh org token; the session decides the org).
|
||||
import { sessionFromRequest } from "../../../../../../lib/current.ts";
|
||||
import { deps } from "../../../../../../lib/deps.ts";
|
||||
import { paConfig, paRaw, pickApp } from "../../../_lib/http.ts";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(req: Request, { params }: { params: { distinct_id: string } }) {
|
||||
const s = await sessionFromRequest(req);
|
||||
if (!s) return new Response(JSON.stringify({ error: "Sign in again." }), { status: 401, headers: { "content-type": "application/json" } });
|
||||
const apps = await deps().repo.listApps(s.org);
|
||||
const app = pickApp(apps, new URL(req.url).searchParams.get("app") ?? undefined);
|
||||
const cfg = paConfig();
|
||||
if (!app || !cfg) return new Response(JSON.stringify({ error: "Product analytics is arriving on this deployment." }), { status: 503, headers: { "content-type": "application/json" } });
|
||||
const res = await paRaw(cfg, { org_id: s.org, app_ids: apps.map((a) => a.id) }, `/v1/projects/${app.id}/persons/${encodeURIComponent(decodeURIComponent(params.distinct_id))}/export`);
|
||||
return new Response(res.body, {
|
||||
status: res.status,
|
||||
headers: { "content-type": "application/json", "content-disposition": 'attachment; filename="person-export.json"', "cache-control": "no-store" },
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,104 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { currentSession } from "../../../../../lib/current.ts";
|
||||
import { deps } from "../../../../../lib/deps.ts";
|
||||
import { Shell } from "../../_components/Shell.tsx";
|
||||
import { fmtTime, paConfig, paFetch, PaError, pickApp, type PersonRow } from "../../_lib/http.ts";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
interface Detail {
|
||||
person: PersonRow;
|
||||
distinct_ids: string[];
|
||||
events: { uuid: string; event: string; timestamp: string; url: string | null }[];
|
||||
event_count: number;
|
||||
}
|
||||
|
||||
async function requestDeletion(form: FormData) {
|
||||
"use server";
|
||||
const s = await currentSession();
|
||||
if (!s) redirect("/");
|
||||
const apps = await deps().repo.listApps(s.org);
|
||||
const app = pickApp(apps, String(form.get("app") ?? ""));
|
||||
const cfg = paConfig();
|
||||
const id = String(form.get("distinct_id") ?? "");
|
||||
if (!app || !cfg || !id) redirect("/product-analytics/privacy");
|
||||
await paFetch(cfg, { org_id: s.org, app_ids: apps.map((a) => a.id) }, `/v1/projects/${app.id}/persons/${encodeURIComponent(id)}/delete`, { method: "POST" });
|
||||
redirect(`/product-analytics/privacy?app=${encodeURIComponent(app.name)}`);
|
||||
}
|
||||
|
||||
// One person: their ids, properties and latest events; export or delete.
|
||||
export default async function PersonPage({ params, searchParams }: { params: { distinct_id: string }; searchParams: { app?: string } }) {
|
||||
const s = (await currentSession())!;
|
||||
const apps = await deps().repo.listApps(s.org);
|
||||
const app = pickApp(apps, searchParams.app);
|
||||
const cfg = paConfig();
|
||||
const distinctId = decodeURIComponent(params.distinct_id);
|
||||
let detail: Detail | null = null;
|
||||
let problem: string | null = null;
|
||||
if (app && cfg) {
|
||||
try {
|
||||
detail = await paFetch<Detail>(cfg, { org_id: s.org, app_ids: apps.map((a) => a.id) }, `/v1/projects/${app.id}/persons/${encodeURIComponent(distinctId)}`);
|
||||
} catch (e) {
|
||||
problem = e instanceof PaError ? e.message : "Product analytics could not be reached. Try again shortly.";
|
||||
}
|
||||
}
|
||||
const q = app ? `?app=${encodeURIComponent(app.name)}` : "";
|
||||
return (
|
||||
<Shell title="Person" apps={apps.map((a) => a.name)} app={app?.name ?? null}>
|
||||
{problem ? (
|
||||
<section className="card">
|
||||
<p>{problem}</p>
|
||||
</section>
|
||||
) : null}
|
||||
{detail ? (
|
||||
<>
|
||||
<section className="card">
|
||||
<h2>{distinctId}</h2>
|
||||
<p className="muted" data-copy-source="product-analytics /v1/projects/{id}/persons/{distinct_id} (live query)">
|
||||
Also known as: {detail.distinct_ids.filter((d) => d !== distinctId).join(", ") || "no other ids"}. {detail.event_count.toLocaleString("en-US")} events.
|
||||
</p>
|
||||
<table>
|
||||
<tbody data-copy-source="product-analytics person properties (live query)">
|
||||
{Object.entries(detail.person.properties)
|
||||
.filter(([k]) => !k.startsWith("$initial_"))
|
||||
.slice(0, 40)
|
||||
.map(([k, v]) => (
|
||||
<tr key={k}>
|
||||
<td>{k}</td>
|
||||
<td>{typeof v === "string" ? v : JSON.stringify(v)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
<section className="card">
|
||||
<h2>Latest events</h2>
|
||||
<table>
|
||||
<tbody data-copy-source="product-analytics /v1/projects/{id}/persons/{distinct_id} (live query)">
|
||||
{detail.events.map((e) => (
|
||||
<tr key={e.uuid}>
|
||||
<td>{fmtTime(e.timestamp)}</td>
|
||||
<td>{e.event}</td>
|
||||
<td>{e.url ?? ""}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
<section className="card">
|
||||
<h2>Privacy</h2>
|
||||
<div className="row">
|
||||
<a href={`/product-analytics/persons/${encodeURIComponent(distinctId)}/export${q}`}>Download their data</a>
|
||||
<form action={requestDeletion}>
|
||||
<input type="hidden" name="app" value={app?.name ?? ""} />
|
||||
<input type="hidden" name="distinct_id" value={distinctId} />
|
||||
<button type="submit">Delete this person</button>
|
||||
</form>
|
||||
</div>
|
||||
<p className="muted">Deleting removes their events, ids and properties. The Privacy screen shows the request until it is done.</p>
|
||||
</section>
|
||||
</>
|
||||
) : null}
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
68
apps/console/app/(app)/product-analytics/persons/page.tsx
Normal file
68
apps/console/app/(app)/product-analytics/persons/page.tsx
Normal file
@ -0,0 +1,68 @@
|
||||
import { currentSession } from "../../../../lib/current.ts";
|
||||
import { deps } from "../../../../lib/deps.ts";
|
||||
import { Shell } from "../_components/Shell.tsx";
|
||||
import { fmtTime, paConfig, paFetch, PaError, pickApp, type PersonRow } from "../_lib/http.ts";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// People: find one person by id, email or name.
|
||||
export default async function PersonsPage({ searchParams }: { searchParams: { app?: string; q?: string } }) {
|
||||
const s = (await currentSession())!;
|
||||
const apps = await deps().repo.listApps(s.org);
|
||||
const app = pickApp(apps, searchParams.app);
|
||||
const cfg = paConfig();
|
||||
const q = (searchParams.q ?? "").slice(0, 200);
|
||||
let persons: PersonRow[] = [];
|
||||
let problem: string | null = null;
|
||||
if (app && cfg) {
|
||||
try {
|
||||
({ persons } = await paFetch<{ persons: PersonRow[] }>(cfg, { org_id: s.org, app_ids: apps.map((a) => a.id) }, `/v1/projects/${app.id}/persons?limit=50&search=${encodeURIComponent(q)}`));
|
||||
} catch (e) {
|
||||
problem = e instanceof PaError ? e.message : "Product analytics could not be reached. Try again shortly.";
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Shell title="People" apps={apps.map((a) => a.name)} app={app?.name ?? null}>
|
||||
<section className="card">
|
||||
<form method="get" className="row">
|
||||
{app ? <input type="hidden" name="app" value={app.name} /> : null}
|
||||
<input name="q" defaultValue={q} placeholder="Id, email or name" aria-label="Find a person" />
|
||||
<button type="submit">Find</button>
|
||||
</form>
|
||||
</section>
|
||||
<section className="card">
|
||||
{!app ? <p className="muted">Add an app first.</p> : null}
|
||||
{app && !cfg ? <p className="muted">Product analytics is arriving on this deployment.</p> : null}
|
||||
{problem ? <p>{problem}</p> : null}
|
||||
{app && cfg && !problem && persons.length === 0 ? <p className="muted">{q ? "Nobody matches that." : "No people yet. A person appears with their first event."}</p> : null}
|
||||
{persons.length ? (
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Person</th>
|
||||
<th>Email</th>
|
||||
<th>Signed in</th>
|
||||
<th>First seen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-copy-source="product-analytics /v1/projects/{id}/persons (live query)">
|
||||
{persons.map((p) => {
|
||||
const id = p.distinct_ids?.[0] ?? p.id;
|
||||
return (
|
||||
<tr key={p.id}>
|
||||
<td>
|
||||
<a href={`/product-analytics/persons/${encodeURIComponent(id)}?app=${encodeURIComponent(app!.name)}`}>{id}</a>
|
||||
</td>
|
||||
<td>{typeof p.properties.email === "string" ? p.properties.email : ""}</td>
|
||||
<td>{p.is_identified ? "Yes" : "No"}</td>
|
||||
<td>{fmtTime(p.created_at)}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
) : null}
|
||||
</section>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
78
apps/console/app/(app)/product-analytics/privacy/page.tsx
Normal file
78
apps/console/app/(app)/product-analytics/privacy/page.tsx
Normal file
@ -0,0 +1,78 @@
|
||||
import { currentSession } from "../../../../lib/current.ts";
|
||||
import { deps } from "../../../../lib/deps.ts";
|
||||
import { Shell } from "../_components/Shell.tsx";
|
||||
import { fmtTime, paConfig, paFetch, PaError, pickApp, type PrivacyJob, type Status } from "../_lib/http.ts";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const STATUS_WORDS: Record<PrivacyJob["status"], string> = {
|
||||
queued: "Waiting",
|
||||
running: "Deleting now",
|
||||
done: "Deleted",
|
||||
failed: "Could not finish; retry from the person's page",
|
||||
};
|
||||
|
||||
// Privacy: what is kept, for how long, and every deletion request.
|
||||
export default async function PrivacyPage({ searchParams }: { searchParams: { app?: string } }) {
|
||||
const s = (await currentSession())!;
|
||||
const apps = await deps().repo.listApps(s.org);
|
||||
const app = pickApp(apps, searchParams.app);
|
||||
const cfg = paConfig();
|
||||
let jobs: PrivacyJob[] = [];
|
||||
let status: Status | null = null;
|
||||
let problem: string | null = null;
|
||||
if (app && cfg) {
|
||||
const scope = { org_id: s.org, app_ids: apps.map((a) => a.id) };
|
||||
try {
|
||||
[{ jobs }, status] = await Promise.all([
|
||||
paFetch<{ jobs: PrivacyJob[] }>(cfg, scope, `/v1/projects/${app.id}/privacy/jobs`),
|
||||
paFetch<Status>(cfg, scope, `/v1/projects/${app.id}/status`),
|
||||
]);
|
||||
} catch (e) {
|
||||
problem = e instanceof PaError ? e.message : "Product analytics could not be reached. Try again shortly.";
|
||||
}
|
||||
}
|
||||
const pending = jobs.some((j) => j.status === "queued" || j.status === "running");
|
||||
return (
|
||||
<Shell title="Privacy" apps={apps.map((a) => a.name)} app={app?.name ?? null} live={pending}>
|
||||
<section className="card">
|
||||
<h2>What is kept</h2>
|
||||
<ul>
|
||||
<li>No IP address is stored or logged. The country comes from the network edge.</li>
|
||||
<li>Nothing is sent from a visitor's device before they agree, unless you turn that off in Setup.</li>
|
||||
{status ? <li data-copy-source="apps/product-analytics/src/plans.ts">Events are kept {status.retention_days} days, then removed.</li> : null}
|
||||
<li>A person can be deleted or exported from their page under People.</li>
|
||||
</ul>
|
||||
</section>
|
||||
<section className="card">
|
||||
<h2>Deletion requests</h2>
|
||||
{problem ? <p>{problem}</p> : null}
|
||||
{!problem && jobs.length === 0 ? <p className="muted">No requests yet.</p> : null}
|
||||
{jobs.length ? (
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Person</th>
|
||||
<th>Asked</th>
|
||||
<th>Due by</th>
|
||||
<th>Status</th>
|
||||
<th>Finished</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-copy-source="product-analytics /v1/projects/{id}/privacy/jobs (live query)">
|
||||
{jobs.map((j) => (
|
||||
<tr key={j.id}>
|
||||
<td>{j.distinct_id}</td>
|
||||
<td>{fmtTime(j.requested_at)}</td>
|
||||
<td>{fmtTime(j.due_at)}</td>
|
||||
<td>{STATUS_WORDS[j.status]}</td>
|
||||
<td>{j.finished_at ? `${fmtTime(j.finished_at)} (${j.result?.events ?? 0} events)` : ""}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
) : null}
|
||||
</section>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
122
apps/console/app/(app)/product-analytics/setup/page.tsx
Normal file
122
apps/console/app/(app)/product-analytics/setup/page.tsx
Normal file
@ -0,0 +1,122 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { currentSession } from "../../../../lib/current.ts";
|
||||
import { deps } from "../../../../lib/deps.ts";
|
||||
import { Shell } from "../_components/Shell.tsx";
|
||||
import { fmtTime, paConfig, paFetch, PaError, pickApp, type Settings, type Status } from "../_lib/http.ts";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const HOST_DEFAULT = "https://pa.railyard.ereboslab.com";
|
||||
|
||||
async function saveSettings(form: FormData) {
|
||||
"use server";
|
||||
const s = await currentSession();
|
||||
if (!s) redirect("/");
|
||||
const apps = await deps().repo.listApps(s.org);
|
||||
const app = pickApp(apps, String(form.get("app") ?? ""));
|
||||
const cfg = paConfig();
|
||||
if (!app || !cfg) redirect("/product-analytics/setup");
|
||||
const key = String(form.get("flags_client_key") ?? "").trim();
|
||||
await paFetch(cfg, { org_id: s.org, app_ids: apps.map((a) => a.id) }, `/v1/projects/${app.id}/settings`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({
|
||||
require_consent: form.get("require_consent") === "on",
|
||||
autocapture: form.get("autocapture") === "on",
|
||||
capture_pageview: form.get("capture_pageview") === "on",
|
||||
flags_client_key: key || null,
|
||||
}),
|
||||
});
|
||||
redirect(`/product-analytics/setup?app=${encodeURIComponent(app.name)}&saved=1`);
|
||||
}
|
||||
|
||||
// Setup: the two lines the app needs, then proof that its first event arrived.
|
||||
export default async function SetupPage({ searchParams }: { searchParams: { app?: string; saved?: string } }) {
|
||||
const s = (await currentSession())!;
|
||||
const apps = await deps().repo.listApps(s.org);
|
||||
const app = pickApp(apps, searchParams.app);
|
||||
const cfg = paConfig();
|
||||
const host = process.env.PRODUCT_ANALYTICS_PUBLIC_URL?.trim() || HOST_DEFAULT;
|
||||
let status: Status | null = null;
|
||||
let settings: Settings | null = null;
|
||||
let problem: string | null = null;
|
||||
if (app && cfg) {
|
||||
const scope = { org_id: s.org, app_ids: apps.map((a) => a.id) };
|
||||
try {
|
||||
[status, { settings }] = await Promise.all([
|
||||
paFetch<Status>(cfg, scope, `/v1/projects/${app.id}/status`),
|
||||
paFetch<{ settings: Settings }>(cfg, scope, `/v1/projects/${app.id}/settings`),
|
||||
]);
|
||||
} catch (e) {
|
||||
problem = e instanceof PaError ? e.message : "Product analytics could not be reached. Try again shortly.";
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Shell title="Set up product analytics" apps={apps.map((a) => a.name)} app={app?.name ?? null} live={!!status && !status.first_event}>
|
||||
{!app ? (
|
||||
<section className="card">
|
||||
<p className="muted">Add an app first.</p>
|
||||
<a href="/apps">Add an app</a>
|
||||
</section>
|
||||
) : (
|
||||
<>
|
||||
<section className="card">
|
||||
<h2>1. Add the package</h2>
|
||||
<pre>
|
||||
<code>npm install @railyard/analytics-js</code>
|
||||
</pre>
|
||||
<p className="muted">Scribase projects already have these lines after scribase add analytics.</p>
|
||||
<pre>
|
||||
<code data-copy-source="railyard.apps.site_key">{`NEXT_PUBLIC_ANALYTICS_SITE=${app.site_key}\nNEXT_PUBLIC_ANALYTICS_HOST=${host}`}</code>
|
||||
</pre>
|
||||
<p className="muted">Expo uses EXPO_PUBLIC_ and Vite uses VITE_ in front of the same names.</p>
|
||||
</section>
|
||||
<section className="card">
|
||||
<h2>2. Send the first event</h2>
|
||||
<pre>
|
||||
<code>{`import { createAnalytics } from "@railyard/analytics-js";\n\nconst analytics = createAnalytics();\nanalytics.setConsent("granted"); // from your consent banner\nanalytics.capture("signed_up");`}</code>
|
||||
</pre>
|
||||
{problem ? <p>{problem}</p> : null}
|
||||
{!cfg ? <p className="muted">Product analytics is arriving on this deployment.</p> : null}
|
||||
{status?.first_event ? (
|
||||
<p data-copy-source="product-analytics /v1/projects/{id}/status (live query)">
|
||||
Done: {status.first_event.event} arrived at {fmtTime(status.first_event.at)}.
|
||||
</p>
|
||||
) : status ? (
|
||||
<p className="muted">Waiting for the first event. This screen checks every 10 seconds.</p>
|
||||
) : null}
|
||||
</section>
|
||||
{settings ? (
|
||||
<section className="card">
|
||||
<h2>Settings</h2>
|
||||
{searchParams.saved ? <p className="muted">Saved.</p> : null}
|
||||
<form action={saveSettings}>
|
||||
<input type="hidden" name="app" value={app.name} />
|
||||
<p>
|
||||
<label>
|
||||
<input type="checkbox" name="require_consent" defaultChecked={settings.require_consent} /> Ask for consent before sending
|
||||
</label>
|
||||
</p>
|
||||
<p>
|
||||
<label>
|
||||
<input type="checkbox" name="autocapture" defaultChecked={settings.autocapture} /> Record clicks automatically
|
||||
</label>
|
||||
</p>
|
||||
<p>
|
||||
<label>
|
||||
<input type="checkbox" name="capture_pageview" defaultChecked={settings.capture_pageview} /> Record page views
|
||||
</label>
|
||||
</p>
|
||||
<p>
|
||||
<label>
|
||||
Flags key of this app's environment <input name="flags_client_key" defaultValue={settings.flags_client_key ?? ""} placeholder="ry_flags_..." />
|
||||
</label>
|
||||
</p>
|
||||
<button type="submit">Save</button>
|
||||
</form>
|
||||
</section>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
@ -5,6 +5,7 @@ import { SignOutIcon } from "./Icons.tsx";
|
||||
const LINKS = [
|
||||
{ href: "/apps", label: "Apps" },
|
||||
{ href: "/insights", label: "Insights" },
|
||||
{ href: "/product-analytics", label: "Product analytics" },
|
||||
{ href: "/usage", label: "Usage" },
|
||||
{ href: "/billing", label: "Billing" },
|
||||
];
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user