Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 33 additions & 27 deletions eslint.config.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
import js from "@eslint/js";
import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint";
import { defineConfig, globalIgnores } from "eslint/config";

export default defineConfig([
globalIgnores([
'dist',
'coverage',
'.old',
'.v2-extras',
'public',
'src/routeTree.gen.ts',
"dist",
"coverage",
".old",
".v2-extras",
"public",
"src/routeTree.gen.ts",
]),
{
files: ['**/*.{ts,tsx}'],
files: ["**/*.{ts,tsx}"],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
Expand All @@ -29,13 +29,13 @@ export default defineConfig([
rules: {
// Underscore prefix is the project convention for intentionally
// unused parameters / catch bindings / destructured holes.
'@typescript-eslint/no-unused-vars': [
'error',
"@typescript-eslint/no-unused-vars": [
"error",
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
destructuredArrayIgnorePattern: '^_',
argsIgnorePattern: "^_",
varsIgnorePattern: "^_",
caughtErrorsIgnorePattern: "^_",
destructuredArrayIgnorePattern: "^_",
},
],
// TanStack Router file-routes export `Route = createFileRoute(...)({…})`
Expand All @@ -44,13 +44,13 @@ export default defineConfig([
// warning about the colocated component. `allowExportNames` is NOT used
// here because it short-circuits before the HOC check and would leave
// the route's local component flagged.
'react-refresh/only-export-components': [
'error',
"react-refresh/only-export-components": [
"error",
{
allowConstantExport: true,
// shadcn theme-provider co-exports the `useTheme` hook with the
// provider component — explicit allow keeps the pattern intact.
allowExportNames: ['useTheme'],
allowExportNames: ["useTheme"],
},
],
},
Expand All @@ -60,9 +60,9 @@ export default defineConfig([
// and helper hooks next to the component. Fast-Refresh restrictions
// don't apply to these — they're auto-regenerated by `shadcn add`,
// not hand-edited during HMR sessions.
files: ['src/components/ui/**/*.{ts,tsx}'],
files: ["src/components/ui/**/*.{ts,tsx}"],
rules: {
'react-refresh/only-export-components': 'off',
"react-refresh/only-export-components": "off",
},
},
{
Expand All @@ -73,9 +73,15 @@ export default defineConfig([
// maintainer warns it can degrade HMR over time. Disable the rule for
// the routes directory instead; route files are small and visually
// distinct, so the Fast-Refresh signal isn't pulling weight here.
files: ['src/routes/**/*.{ts,tsx}'],
files: ["src/routes/**/*.{ts,tsx}"],
rules: {
'react-refresh/only-export-components': 'off',
"react-refresh/only-export-components": "off",
},
},
])
{
files: ["src/components/metric-evidence-table.tsx"],
rules: {
"react-hooks/incompatible-library": "off",
},
},
]);
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"@tailwindcss/vite": "4.2.4",
"@tanstack/react-query": "5.100.9",
"@tanstack/react-router": "1.169.2",
"@tanstack/react-virtual": "3.13.12",
"class-variance-authority": "0.7.1",
"clsx": "2.1.1",
"date-fns": "4.1.0",
Expand Down
20 changes: 20 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions src/api/metric-definitions-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import { AnalyticsApiError } from "@/api/analytics-client";
import { fetchWithAuth } from "@/api/fetch-with-auth";
import type {
MetricDrilldownCapability,
MetricDirection,
MetricFormat,
} from "@/api/metric-results-client";
Expand All @@ -36,6 +37,7 @@ export interface MetricDefinition {
schema_error_code: MetricSchemaErrorCode | null;
/** ISO date of the newest observation ever seen; null = no data yet. */
last_observed_date: string | null;
drilldown?: MetricDrilldownCapability;
}

export type MetricSchemaErrorCode =
Expand Down
110 changes: 110 additions & 0 deletions src/api/metric-drilldown-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { AnalyticsApiError } from "@/api/analytics-client";
import { fetchWithAuth } from "@/api/fetch-with-auth";
import type {
MetricCanonicalSelection,
MetricDimensionFilter,
} from "@/api/metric-results-client";
import { downloadBlob } from "@/lib/download";

const BASE =
(import.meta.env.VITE_API_BASE as string | undefined) ?? "/api/analytics/v1";

export interface MetricEvidenceSelection {
metric_key: string;
entity: { type: "person"; id: string };
period: { from: string; to: string };
filters: MetricDimensionFilter[];
display_dimensions: string[];
}

export interface MetricEvidenceColumn {
key: string;
label: string;
type: "string" | "number" | "date";
}

export interface MetricEvidenceRow {
values: Record<string, unknown>;
}

export interface MetricDrilldownResponse {
selection: MetricEvidenceSelection;
columns: MetricEvidenceColumn[];
rows: MetricEvidenceRow[];
next_cursor: string | null;
}

export interface MetricDrilldownRequest extends MetricEvidenceSelection {
cursor?: string;
limit: number;
}

async function errorFor(res: Response): Promise<AnalyticsApiError> {
const body = await res.json().catch(() => null);
return new AnalyticsApiError(res.status, body);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

function exportFilename(disposition: string | null, fallback: string): string {
const encoded = disposition?.match(/filename\*=UTF-8''([^;]+)/i)?.[1];
if (encoded) {
try {
return decodeURIComponent(encoded);
} catch {
return disposition?.match(/filename="?([^";]+)"?/i)?.[1] ?? fallback;
}
}
return disposition?.match(/filename="?([^";]+)"?/i)?.[1] ?? fallback;
}

export async function queryMetricDrilldown(
request: MetricDrilldownRequest,
signal?: AbortSignal
): Promise<MetricDrilldownResponse> {
const res = await fetchWithAuth(`${BASE}/metric-drilldown`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
signal,
});
if (!res.ok) throw await errorFor(res);
return (await res.json()) as MetricDrilldownResponse;
}

export async function downloadMetricDrilldown(
selection: MetricEvidenceSelection,
format: "csv" | "xlsx",
signal?: AbortSignal
): Promise<void> {
const res = await fetchWithAuth(`${BASE}/metric-drilldown/export`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...selection, format }),
signal,
});
if (!res.ok) throw await errorFor(res);
const blob = await res.blob();
downloadBlob(
blob,
exportFilename(
res.headers.get("content-disposition"),
`${selection.metric_key}.${format}`
)
);
}

export function evidenceSelection(
canonical: MetricCanonicalSelection | undefined,
entityId: string,
period?: { from: string; to: string },
filters?: MetricDimensionFilter[],
displayDimensions: string[] = []
): MetricEvidenceSelection | null {
if (!canonical) return null;
return {
metric_key: canonical.metric_key,
entity: { type: "person", id: entityId },
period: period ?? canonical.period,
filters: filters ?? canonical.filters,
display_dimensions: [...new Set(displayDimensions)].sort(),
};
}
13 changes: 13 additions & 0 deletions src/api/metric-results-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,17 @@ export interface MetricDimensionFilter {
values: string[];
}

export interface MetricDrilldownCapability {
granularity: Array<"event" | "source_summary" | "derived_population">;
}

export interface MetricCanonicalSelection {
metric_key: string;
entity: { type: MetricEntityType; ids: string[] };
period: { from: string; to: string };
filters: MetricDimensionFilter[];
}

export interface MetricGroupLimit {
count: number;
rank_by_metric?: string;
Expand Down Expand Up @@ -80,6 +91,8 @@ interface MetricResultBase {
format: MetricFormat;
direction: MetricDirection;
views: MetricResultView[];
drilldown?: MetricDrilldownCapability;
selection?: MetricCanonicalSelection;
}

export interface SumMetricResult extends MetricResultBase {
Expand Down
13 changes: 13 additions & 0 deletions src/auth/session-scope.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import type { Session } from "@/auth/types";

export function sessionAuthorizationScope(
session: Session | null
): string | null {
if (!session) return null;
return JSON.stringify({
tenantId: session.tenantId,
personId: session.personId,
impersonatorEmail: session.impersonatorEmail,
roles: [...session.roles].sort(),
});
}
42 changes: 42 additions & 0 deletions src/components/metric-evidence-context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { createContext, useContext } from "react";

import type { MetricEvidenceSelection } from "@/api/metric-drilldown-client";

export interface EvidenceDialogTarget {
selection: MetricEvidenceSelection;
label: string;
}

export interface EvidenceDialogState {
targets: readonly [EvidenceDialogTarget, ...EvidenceDialogTarget[]];
activeMetricKey: string;
title?: string;
}

export interface EvidenceDialogContextValue {
openEvidence: (selection: MetricEvidenceSelection, label: string) => void;
openEvidenceTargets: (
targets: readonly EvidenceDialogTarget[],
title?: string
) => void;
}

export const EvidenceDialogContext = createContext<
EvidenceDialogContextValue | undefined
>(undefined);

export function useMetricEvidence(): EvidenceDialogContextValue {
const context = useContext(EvidenceDialogContext);
if (!context) {
throw new Error(
"useMetricEvidence must be used within MetricEvidenceDialogProvider"
);
}
return context;
}

export function useMetricEvidenceOptional():
| EvidenceDialogContextValue
| undefined {
return useContext(EvidenceDialogContext);
}
Loading
Loading