Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
7 changes: 1 addition & 6 deletions src/api/metric-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,9 @@ export const METRIC_REGISTRY = {
V2_MEMBER_VALUES_DELIVERY: "00000000-0000-0000-0001-000000000040",
V2_MEMBER_VALUES_COLLAB: "00000000-0000-0000-0001-000000000041",
V2_MEMBER_VALUES_GIT: "00000000-0000-0000-0001-000000000042",
V2_MEMBER_VALUES_AI: "00000000-0000-0000-0001-000000000049",
V2_IC_AI_TOOL_SUMMARY: "00000000-0000-0000-0001-000000000050",
V2_IC_AI_TOOL_TREND: "00000000-0000-0000-0001-000000000051",
V2_IC_AI_PEER_COUNTERS: "00000000-0000-0000-0001-000000000052",
// Per-person collaboration Messaging peer counters (#1527): long rows
// (person_id, metric_key, value + per-org_unit bands) for messages_sent /
// channel_posts. Mirrors V2_IC_AI_PEER_COUNTERS.
// channel_posts.
V2_IC_COLLAB_PEER_COUNTERS: "00000000-0000-0000-0001-000000000053",

// Per-person PRs merged for a roster (period-bounded, from the weekly git
Expand All @@ -54,7 +50,6 @@ export const METRIC_REGISTRY = {
V2_DEPT_DIST_COLLAB: "00000000-0000-0000-0001-000000000045",
V2_DEPT_DIST_GIT: "00000000-0000-0000-0001-000000000046",
V2_DEPT_DIST_KPIS: "00000000-0000-0000-0001-000000000047",
V2_DEPT_DIST_AI: "00000000-0000-0000-0001-000000000048",
} as const satisfies Record<string, string>;

export type MetricRegistryKey = keyof typeof METRIC_REGISTRY;
Expand Down
71 changes: 71 additions & 0 deletions src/api/metric-results-client.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { beforeEach, describe, expect, it, vi } from "vitest";

import { AnalyticsApiError } from "@/api/analytics-client";
import {
queryMetricResults,
type MetricResultsRequest,
} from "@/api/metric-results-client";
import { fetchWithAuth } from "@/api/fetch-with-auth";
import { METRIC_RESULTS_RESPONSE_FIXTURE } from "@/mocks/metric-results-fixtures";

vi.mock("@/api/fetch-with-auth", () => ({ fetchWithAuth: vi.fn() }));

const mockFetch = vi.mocked(fetchWithAuth);

const REQUEST: MetricResultsRequest = {
entity: { type: "person", ids: ["alice@example.com"] },
period: { from: "2026-06-01", to: "2026-06-30" },
metrics: [{ metric_key: "ai.accepted_lines", views: [{ view: "period" }] }],
};

function response(init: {
ok: boolean;
status?: number;
json: () => Promise<unknown>;
}): Response {
return {
ok: init.ok,
status: init.status ?? (init.ok ? 200 : 500),
json: init.json,
} as Response;
}

describe("queryMetricResults", () => {
beforeEach(() => mockFetch.mockReset());

it("returns the parsed response on success", async () => {
mockFetch.mockResolvedValue(
response({ ok: true, json: async () => METRIC_RESULTS_RESPONSE_FIXTURE }),
);
await expect(queryMetricResults(REQUEST)).resolves.toEqual(
METRIC_RESULTS_RESPONSE_FIXTURE,
);
});

it("throws AnalyticsApiError with status + body on a non-ok response", async () => {
mockFetch.mockResolvedValue(
response({ ok: false, status: 400, json: async () => ({ error: "bad" }) }),
);
await expect(queryMetricResults(REQUEST)).rejects.toMatchObject({
status: 400,
body: { error: "bad" },
});
await expect(queryMetricResults(REQUEST)).rejects.toBeInstanceOf(
AnalyticsApiError,
);
});

it("throws AnalyticsApiError('invalid_json') when an ok body fails to parse", async () => {
mockFetch.mockResolvedValue(
response({
ok: true,
json: async () => {
throw new Error("not json");
},
}),
);
await expect(queryMetricResults(REQUEST)).rejects.toMatchObject({
body: { error: "invalid_json" },
});
});
});
139 changes: 139 additions & 0 deletions src/api/metric-results-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { fetchWithAuth } from "@/api/fetch-with-auth";
import { AnalyticsApiError } from "@/api/analytics-client";

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

export type MetricFormat = "integer" | "decimal" | "currency" | "percent";
export type MetricDirection =
| "higher_is_better"
| "lower_is_better"
| "neutral";
export type MetricResultViewKind =
| "period"
| "timeseries"
| "peer"
| "breakdown";
export type MetricBucket = "day" | "week" | "month";
export type MetricComputation = "sum" | "ratio";
export type MetricEntityType = "person";

export interface MetricResultsRequest {
entity: { type: MetricEntityType; ids: string[] };
period: { from: string; to: string };
metrics: MetricRequest[];
}

export interface MetricRequest {
metric_key: string;
views: MetricViewRequest[];
}

export type MetricViewRequest =
| { view: "period" }
| { view: "peer"; cohort_key?: string }
| {
view: "timeseries";
bucket?: MetricBucket;
dimensions?: string[];
}
| {
view: "breakdown";
dimensions: string[];
};

export interface MetricDimension {
key: string;
value: string;
label?: string;
}

export type MetricResult = SumMetricResult | RatioMetricResult;

interface MetricResultBase {
metric_key: string;
label: string;
description?: string;
explanation?: string;
unit: string | null;
format: MetricFormat;
direction: MetricDirection;
views: MetricResultView[];
}

export interface SumMetricResult extends MetricResultBase {
computation: "sum";
}

export interface RatioMetricResult extends MetricResultBase {
computation: "ratio";
scale: number;
}

export type MetricResultView =
| PeriodView
| TimeseriesView
| PeerView
| BreakdownView;

export interface PeriodView {
view: "period";
values: Array<{ entity_id: string; value: number | null }>;
}

export interface TimeseriesView {
view: "timeseries";
bucket: MetricBucket;
series: Array<{
entity_id: string;
dimensions: MetricDimension[];
points: Array<{ bucket_start: string; value: number | null }>;
}>;
}

export interface PeerView {
view: "peer";
values: Array<{
entity_id: string;
target_value: number | null;
p25: number | null;
median: number | null;
p75: number | null;
min: number | null;
max: number | null;
n: number;
}>;
}

export interface BreakdownView {
view: "breakdown";
dimensions: string[];
values: Array<{
entity_id: string;
dimensions: MetricDimension[];
value: number | null;
}>;
}

export interface MetricResultsResponse {
metrics: MetricResult[];
}

export async function queryMetricResults(
body: MetricResultsRequest,
): Promise<MetricResultsResponse> {
const res = await fetchWithAuth(`${BASE}/metric-results`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) {
const errorBody = await res.json().catch(() => null);
throw new AnalyticsApiError(res.status, errorBody);
}
try {
return (await res.json()) as MetricResultsResponse;
} catch {
throw new AnalyticsApiError(res.status, { error: "invalid_json" });
}
}
Comment on lines +122 to +139

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Add tests to satisfy the coverage gate.

The coverage pipeline reports 0% diff coverage on this function (lines 4, 125, 130-132, 134-135, 137), which will fail the CI gate (min 80%). Add unit tests covering the success path, the !res.ok branch, and the invalid-JSON branch.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/api/metric-results-client.ts` around lines 122 - 139, The
queryMetricResults function in metric-results-client needs unit tests to raise
diff coverage and satisfy the gate. Add tests that exercise the happy path where
fetchWithAuth returns an ok response and parsed MetricResultsResponse is
returned, the !res.ok branch where res.json() provides an error body and
AnalyticsApiError is thrown with the status/body, and the invalid JSON branch
where res.json() rejects on an ok response and AnalyticsApiError is thrown with
invalid_json.

Source: Pipeline failures

105 changes: 105 additions & 0 deletions src/components/widgets/metric-views/collection-drilldown.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";

import { CollectionDrilldown } from "@/components/widgets/metric-views/collection-drilldown";
import type { MetricGroup } from "@/lib/insight/groups";
import { normalizeMetricResults } from "@/lib/metrics/collection";
import type { MetricCollectionResult } from "@/queries/metric-results";
import {
RATIO_METRIC_FIXTURE,
SUM_METRIC_FIXTURE,
} from "@/mocks/metric-results-fixtures";

vi.mock("@/hooks/use-settings", () => ({
useSettings: () => ({ focusMode: "all", showExplanations: true }),
}));

const DEF: MetricGroup = {
kind: "metrics",
id: "ai_adoption",
title: "AI adoption",
collection: {
metrics: [
{
key: "ai.accepted_lines",
views: [
{ view: "period" },
{ view: "peer" },
{ view: "timeseries", bucket: "auto", dimensions: ["tool"] },
{ view: "breakdown", dimensions: ["tool"] },
],
},
{
key: "ai.tool_acceptance_rate",
views: [{ view: "period" }, { view: "peer" }],
},
],
},
card: { preview: ["ai.accepted_lines"] },
drilldown: [
{ chart: "bars", view: "breakdown", metrics: ["ai.accepted_lines"] },
{
chart: "stacked-bar",
view: "timeseries",
metrics: ["ai.accepted_lines"],
},
],
};

function result(
overrides: Partial<MetricCollectionResult> = {},
): MetricCollectionResult {
return {
byKey: normalizeMetricResults([SUM_METRIC_FIXTURE, RATIO_METRIC_FIXTURE]),
previousByKey: null,
isPending: false,
isFetching: false,
isError: false,
refetch: vi.fn(),
...overrides,
};
}

describe("CollectionDrilldown", () => {
it("renders the def's blocks and the peer story from wire data", () => {
render(
<CollectionDrilldown
def={DEF}
data={result()}
entityId="alice@example.com"
/>,
);
// Breakdown block: composition by tool with response-provided labels.
expect(screen.getByText("Period total by tool")).toBeInTheDocument();
expect(screen.getAllByText("Claude Code").length).toBeGreaterThan(0);
// Timeseries block.
expect(screen.getByText("Accepted lines over time")).toBeInTheDocument();
// Peer story: both fixture metrics are in-pack (no outlier hero), so the
// story falls back to the flat grid with one card per metric.
expect(screen.getByText("Tool acceptance rate")).toBeInTheDocument();
expect(screen.getByText("77%")).toBeInTheDocument();
});

it("shows the error state with retry when the collection failed", () => {
const refetch = vi.fn();
render(
<CollectionDrilldown
def={DEF}
data={result({ isError: true, refetch })}
entityId="alice@example.com"
/>,
);
expect(screen.getByText("Unable to load metrics")).toBeInTheDocument();
});

it("shows a spinner while pending", () => {
const { container } = render(
<CollectionDrilldown
def={DEF}
data={result({ isPending: true })}
entityId="alice@example.com"
/>,
);
expect(container.querySelector("svg")).toBeInTheDocument();
});
});
Loading