Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(dashboard): add pivot table widget type (#7546)

Thorsten Spiekerb445471f9847
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index f2e93d6859..74ac09cb1f 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -111,7 +111,8 @@ export const DashboardWidgetChartType = {
VERTICAL_BAR: "VERTICAL_BAR",
PIE: "PIE",
NUMBER: "NUMBER",
- HISTOGRAM: "HISTOGRAM"
+ HISTOGRAM: "HISTOGRAM",
+ PIVOT_TABLE: "PIVOT_TABLE"
} as const;
export type DashboardWidgetChartType = (typeof DashboardWidgetChartType)[keyof typeof DashboardWidgetChartType];
export type Account = {
diff --git a/packages/shared/prisma/migrations/20250625_add_pivot_table_charttype/migration.sql b/packages/shared/prisma/migrations/20250625_add_pivot_table_charttype/migration.sql
new file mode 100644
index 0000000000..6ff023adfe
--- /dev/null
+++ b/packages/shared/prisma/migrations/20250625_add_pivot_table_charttype/migration.sql
@@ -0,0 +1,9 @@
+-- Database migration to add PIVOT_TABLE chart type to DashboardWidgetChartType enum
+-- This enables the creation of pivot table widgets in the dashboard system
+--
+-- This migration adds support for tabular data visualization with configurable
+-- row dimensions and metrics, extending the existing widget types (line charts,
+-- bar charts, pie charts, etc.) to include pivot table functionality.
+
+-- AlterEnum
+ALTER TYPE "DashboardWidgetChartType" ADD VALUE 'PIVOT_TABLE';
\ No newline at end of file
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 84d0fc5ad1..5e12d8f17c 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -1157,6 +1157,7 @@ enum DashboardWidgetChartType {
PIE
NUMBER
HISTOGRAM
+ PIVOT_TABLE
}
model DashboardWidget {
diff --git a/packages/shared/src/server/services/DashboardService/types.ts b/packages/shared/src/server/services/DashboardService/types.ts
index b1c8e0008e..140d2d372b 100644
--- a/packages/shared/src/server/services/DashboardService/types.ts
+++ b/packages/shared/src/server/services/DashboardService/types.ts
@@ -33,6 +33,10 @@ export const HistogramChartConfig = BaseTotalValueChartConfig.extend({
bins: z.number().int().min(1).max(100).optional().default(10),
});
+export const PivotTableChartConfig = BaseTotalValueChartConfig.extend({
+ type: z.literal("PIVOT_TABLE"),
+});
+
// Define dimension schema
export const DimensionSchema = z.object({
field: z.string(),
@@ -53,6 +57,7 @@ export const ChartConfigSchema = z.discriminatedUnion("type", [
PieChartConfig,
BigNumberChartConfig,
HistogramChartConfig,
+ PivotTableChartConfig,
]);
export const DashboardDefinitionWidgetWidgetSchema = z.object({
diff --git a/web/src/__tests__/dashboard-router-pivot-table.servertest.ts b/web/src/__tests__/dashboard-router-pivot-table.servertest.ts
new file mode 100644
index 0000000000..000b7c47af
--- /dev/null
+++ b/web/src/__tests__/dashboard-router-pivot-table.servertest.ts
@@ -0,0 +1,679 @@
+/**
+ * @fileoverview Integration tests for Pivot Table widget functionality in dashboard router
+ *
+ * This test suite validates the complete data pipeline for pivot table widgets:
+ * - Query generation and execution through executeQuery function
+ * - SQL generation by QueryBuilder for various pivot table configurations
+ * - Data transformation from raw query results to pivot table structure
+ * - Integration with ClickHouse database and error handling
+ *
+ * Test Coverage:
+ * - Zero dimension pivot tables (grand total only)
+ * - Single dimension pivot tables with subtotals
+ * - Two dimension pivot tables with nested structure
+ * - Row limiting functionality
+ * - Error handling for malformed queries
+ * - Integration with existing dashboard query infrastructure
+ */
+
+import { randomUUID } from "crypto";
+import {
+ createTrace,
+ createTracesCh,
+ createObservation,
+ createObservationsCh,
+} from "@langfuse/shared/src/server";
+import { type QueryType } from "@/src/features/query/types";
+import { executeQuery } from "@/src/features/dashboard/server/dashboard-router";
+import {
+ transformToPivotTable,
+ type DatabaseRow,
+} from "@/src/features/widgets/utils/pivot-table-utils";
+import { QueryBuilder } from "@/src/features/query/server/queryBuilder";
+
+describe("Dashboard Router - Pivot Table Integration", () => {
+ // Single project ID for all tests
+ const projectId = randomUUID();
+
+ // Time references for test data
+ const now = new Date();
+ const oneHourAgo = new Date(now.getTime() - 3600000);
+ const twoHoursAgo = new Date(now.getTime() - 7200000);
+ const threeDaysAgo = new Date(now.getTime() - 3 * 24 * 3600000);
+
+ // Time ranges for queries - ISO format for query builder
+ const defaultFromTime = threeDaysAgo.toISOString();
+ const defaultToTime = new Date(now.getTime() + 3600000).toISOString(); // 1 hour in future
+
+ // Test data statistics for verification
+ const testDataStats = {
+ totalTraces: 0,
+ environmentCounts: {} as Record<string, number>,
+ modelCounts: {} as Record<string, number>,
+ totalObservations: 0,
+ };
+
+ beforeAll(async () => {
+ // Create diverse test data for pivot table testing
+ const traces = [
+ // Production environment traces
+ ...Array(6)
+ .fill(0)
+ .map((_, i) =>
+ createTrace({
+ project_id: projectId,
+ name: "chat-completion",
+ environment: "production",
+ timestamp: now.getTime() - i * 10000,
+ user_id: `user-prod-${i}`,
+ }),
+ ),
+
+ // Development environment traces
+ ...Array(4)
+ .fill(0)
+ .map((_, i) =>
+ createTrace({
+ project_id: projectId,
+ name: "embeddings",
+ environment: "development",
+ timestamp: oneHourAgo.getTime() - i * 15000,
+ user_id: `user-dev-${i}`,
+ }),
+ ),
+
+ // Staging environment traces
+ ...Array(3)
+ .fill(0)
+ .map((_, i) =>
+ createTrace({
+ project_id: projectId,
+ name: "summarize",
+ environment: "staging",
+ timestamp: twoHoursAgo.getTime() - i * 20000,
+ user_id: `user-staging-${i}`,
+ }),
+ ),
+ ];
+
+ // Insert traces into ClickHouse
+ await createTracesCh(traces);
+
+ // Create observations with different models for each trace
+ const observations = [];
+
+ // Production observations - GPT models
+ for (let i = 0; i < 6; i++) {
+ const traceId = traces[i].id;
+ observations.push(
+ createObservation({
+ project_id: projectId,
+ trace_id: traceId,
+ name: "gpt-generation",
+ type: "generation",
+ environment: "production",
+ start_time: now.getTime() - i * 10000,
+ completion_start_time: now.getTime() - i * 10000 + 500,
+ end_time: now.getTime() - i * 10000 + 2000,
+ provided_model_name: i < 3 ? "gpt-4-turbo" : "gpt-3.5-turbo",
+ }),
+ );
+ }
+
+ // Development observations - Claude models
+ for (let i = 0; i < 4; i++) {
+ const traceId = traces[6 + i].id;
+ observations.push(
+ createObservation({
+ project_id: projectId,
+ trace_id: traceId,
+ name: "claude-generation",
+ type: "generation",
+ environment: "development",
+ start_time: oneHourAgo.getTime() - i * 15000,
+ completion_start_time: oneHourAgo.getTime() - i * 15000 + 800,
+ end_time: oneHourAgo.getTime() - i * 15000 + 3000,
+ provided_model_name: i < 2 ? "claude-3-opus" : "claude-3-sonnet",
+ }),
+ );
+ }
+
+ // Staging observations - Mixed models
+ for (let i = 0; i < 3; i++) {
+ const traceId = traces[10 + i].id;
+ observations.push(
+ createObservation({
+ project_id: projectId,
+ trace_id: traceId,
+ name: "mixed-generation",
+ type: "generation",
+ environment: "staging",
+ start_time: twoHoursAgo.getTime() - i * 20000,
+ completion_start_time: twoHoursAgo.getTime() - i * 20000 + 600,
+ end_time: twoHoursAgo.getTime() - i * 20000 + 2500,
+ provided_model_name: "gpt-4-turbo",
+ }),
+ );
+ }
+
+ // Insert observations into ClickHouse
+ await createObservationsCh(observations);
+
+ // Calculate test data statistics for verification
+ testDataStats.totalTraces = traces.length;
+ testDataStats.totalObservations = observations.length;
+
+ // Count by environment
+ traces.forEach((trace) => {
+ testDataStats.environmentCounts[trace.environment] =
+ (testDataStats.environmentCounts[trace.environment] || 0) + 1;
+ });
+
+ // Count by model
+ observations.forEach((obs) => {
+ if (obs.provided_model_name) {
+ testDataStats.modelCounts[obs.provided_model_name] =
+ (testDataStats.modelCounts[obs.provided_model_name] || 0) + 1;
+ }
+ });
+ });
+
+ describe("executeQuery function with pivot table configurations", () => {
+ it("should execute zero-dimension pivot table query (grand total only)", async () => {
+ const query: QueryType = {
+ view: "traces",
+ dimensions: [],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [],
+ timeDimension: {
+ granularity: "day",
+ },
+ fromTimestamp: defaultFromTime,
+ toTimestamp: defaultToTime,
+ orderBy: null,
+ chartConfig: {
+ type: "PIVOT_TABLE",
+ row_limit: 20,
+ },
+ };
+
+ const result = await executeQuery(projectId, query);
+
+ // Verify basic query execution
+ expect(result).toBeDefined();
+ expect(Array.isArray(result)).toBe(true);
+
+ // Results should be grouped by time dimension when timeDimension is present
+ expect(result.length).toBeGreaterThan(0);
+
+ // Each row should have time_dimension and aggregated count
+ result.forEach((row) => {
+ expect(row).toHaveProperty("time_dimension");
+ expect(row).toHaveProperty("count_count");
+ expect(typeof row.count_count).toBe("string"); // ClickHouse returns numbers as strings
+ });
+
+ // Sum all counts to verify total
+ const totalCount = result.reduce(
+ (sum, row) => sum + parseInt(row.count_count as string),
+ 0,
+ );
+ expect(totalCount).toBe(testDataStats.totalTraces);
+ });
+
+ it("should execute single-dimension pivot table query with environment grouping", async () => {
+ const query: QueryType = {
+ view: "traces",
+ dimensions: [{ field: "environment" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [],
+ timeDimension: {
+ granularity: "day",
+ },
+ fromTimestamp: defaultFromTime,
+ toTimestamp: defaultToTime,
+ orderBy: [{ field: "environment", direction: "asc" }],
+ chartConfig: {
+ type: "PIVOT_TABLE",
+ row_limit: 20,
+ },
+ };
+
+ const result = await executeQuery(projectId, query);
+
+ // Verify query execution
+ expect(result).toBeDefined();
+ expect(Array.isArray(result)).toBe(true);
+
+ // Should have one row per environment per time dimension
+ expect(result.length).toBeGreaterThan(0);
+
+ // Verify structure of results
+ result.forEach((row) => {
+ expect(row).toHaveProperty("environment");
+ expect(row).toHaveProperty("time_dimension");
+ expect(row).toHaveProperty("count_count");
+ expect(typeof row.environment).toBe("string");
+ expect(typeof row.count_count).toBe("string"); // ClickHouse returns numbers as strings
+ });
+
+ // Verify data accuracy by checking environment counts
+ const environmentTotals = result.reduce(
+ (acc, row) => {
+ const env = row.environment as string;
+ acc[env] =
+ ((acc[env] as number) || 0) + parseInt(row.count_count as string);
+ return acc;
+ },
+ {} as Record<string, number>,
+ );
+
+ expect(environmentTotals["production"]).toBe(
+ testDataStats.environmentCounts["production"],
+ );
+ expect(environmentTotals["development"]).toBe(
+ testDataStats.environmentCounts["development"],
+ );
+ expect(environmentTotals["staging"]).toBe(
+ testDataStats.environmentCounts["staging"],
+ );
+ });
+
+ it("should execute two-dimension pivot table query with environment and model grouping", async () => {
+ const query: QueryType = {
+ view: "observations",
+ dimensions: [{ field: "environment" }, { field: "providedModelName" }],
+ metrics: [
+ { measure: "count", aggregation: "count" },
+ { measure: "totalTokens", aggregation: "sum" },
+ ],
+ filters: [],
+ timeDimension: {
+ granularity: "day",
+ },
+ fromTimestamp: defaultFromTime,
+ toTimestamp: defaultToTime,
+ orderBy: [
+ { field: "environment", direction: "asc" },
+ { field: "providedModelName", direction: "asc" },
+ ],
+ chartConfig: {
+ type: "PIVOT_TABLE",
+ row_limit: 20,
+ },
+ };
+
+ const result = await executeQuery(projectId, query);
+
+ // Verify query execution
+ expect(result).toBeDefined();
+ expect(Array.isArray(result)).toBe(true);
+ expect(result.length).toBeGreaterThan(0);
+
+ // Should have combinations of environment and model
+ result.forEach((row) => {
+ expect(row).toHaveProperty("environment");
+ expect(row).toHaveProperty("providedModelName");
+ expect(row).toHaveProperty("time_dimension");
+ expect(row).toHaveProperty("count_count");
+ expect(row).toHaveProperty("sum_totalTokens");
+
+ expect(typeof row.environment).toBe("string");
+ expect(typeof row.providedModelName).toBe("string");
+ expect(typeof row.count_count).toBe("string");
+ expect(typeof row.sum_totalTokens).toBe("string");
+ });
+
+ // Verify total observation count matches test data
+ const totalObservations = result.reduce(
+ (sum, row) => sum + parseInt(row.count_count as string),
+ 0,
+ );
+ expect(totalObservations).toBe(testDataStats.totalObservations);
+ });
+
+ it("should handle empty results gracefully", async () => {
+ const futureTime = new Date(now.getTime() + 86400000).toISOString(); // 1 day in future
+ const farFutureTime = new Date(now.getTime() + 172800000).toISOString(); // 2 days in future
+
+ const query: QueryType = {
+ view: "traces",
+ dimensions: [{ field: "environment" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [],
+ timeDimension: {
+ granularity: "day",
+ },
+ fromTimestamp: futureTime,
+ toTimestamp: farFutureTime,
+ orderBy: null,
+ chartConfig: {
+ type: "PIVOT_TABLE",
+ row_limit: 20,
+ },
+ };
+
+ const result = await executeQuery(projectId, query);
+
+ // Should handle empty results without errors
+ expect(result).toBeDefined();
+ expect(Array.isArray(result)).toBe(true);
+ // Time dimension queries can return rows with 0 counts for time filling
+ expect(result.length).toBeGreaterThanOrEqual(0);
+ });
+ });
+
+ describe("Query Builder integration with pivot table configurations", () => {
+ it("should generate correct SQL for zero-dimension pivot table", () => {
+ const query: QueryType = {
+ view: "traces",
+ dimensions: [],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [],
+ timeDimension: {
+ granularity: "day",
+ },
+ fromTimestamp: defaultFromTime,
+ toTimestamp: defaultToTime,
+ orderBy: null,
+ chartConfig: {
+ type: "PIVOT_TABLE",
+ row_limit: 20,
+ },
+ };
+
+ const queryBuilder = new QueryBuilder(query.chartConfig);
+ const { query: sql, parameters } = queryBuilder.build(query, projectId);
+
+ // Verify SQL generation
+ expect(sql).toBeDefined();
+ expect(typeof sql).toBe("string");
+ expect(parameters).toBeDefined();
+ expect(typeof parameters).toBe("object");
+
+ // SQL should contain GROUP BY for time dimension when timeDimension is present
+ expect(sql.toLowerCase()).toContain("group by");
+
+ // Should contain aggregation
+ expect(sql.toLowerCase()).toContain("count(");
+ });
+
+ it("should generate correct SQL for single-dimension pivot table", () => {
+ const query: QueryType = {
+ view: "traces",
+ dimensions: [{ field: "environment" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [],
+ timeDimension: {
+ granularity: "day",
+ },
+ fromTimestamp: defaultFromTime,
+ toTimestamp: defaultToTime,
+ orderBy: [{ field: "environment", direction: "asc" }],
+ chartConfig: {
+ type: "PIVOT_TABLE",
+ row_limit: 20,
+ },
+ };
+
+ const queryBuilder = new QueryBuilder(query.chartConfig);
+ const { query: sql, parameters } = queryBuilder.build(query, projectId);
+
+ // Verify SQL generation
+ expect(sql).toBeDefined();
+ expect(typeof sql).toBe("string");
+ expect(parameters).toBeDefined();
+
+ // SQL should contain GROUP BY for dimension
+ expect(sql.toLowerCase()).toContain("group by");
+ expect(sql.toLowerCase()).toContain("environment");
+
+ // Should contain ORDER BY
+ expect(sql.toLowerCase()).toContain("order by");
+ });
+
+ it("should generate correct SQL for two-dimension pivot table", () => {
+ const query: QueryType = {
+ view: "observations",
+ dimensions: [{ field: "environment" }, { field: "providedModelName" }],
+ metrics: [
+ { measure: "count", aggregation: "count" },
+ { measure: "totalTokens", aggregation: "sum" },
+ ],
+ filters: [],
+ timeDimension: {
+ granularity: "day",
+ },
+ fromTimestamp: defaultFromTime,
+ toTimestamp: defaultToTime,
+ orderBy: [
+ { field: "environment", direction: "asc" },
+ { field: "providedModelName", direction: "asc" },
+ ],
+ chartConfig: {
+ type: "PIVOT_TABLE",
+ row_limit: 20,
+ },
+ };
+
+ const queryBuilder = new QueryBuilder(query.chartConfig);
+ const { query: sql, parameters } = queryBuilder.build(query, projectId);
+
+ // Verify SQL generation
+ expect(sql).toBeDefined();
+ expect(typeof sql).toBe("string");
+ expect(parameters).toBeDefined();
+
+ // SQL should contain GROUP BY for both dimensions
+ expect(sql.toLowerCase()).toContain("group by");
+ expect(sql.toLowerCase()).toContain("environment");
+ expect(sql.toLowerCase()).toContain("providedmodelname");
+
+ // Should contain multiple aggregations
+ expect(sql.toLowerCase()).toContain("count(");
+ expect(sql.toLowerCase()).toContain("sum(");
+
+ // Should contain ORDER BY for both dimensions
+ expect(sql.toLowerCase()).toContain("order by");
+ });
+ });
+
+ describe("End-to-end pivot table data transformation", () => {
+ it("should transform query results to pivot table structure for zero dimensions", async () => {
+ const query: QueryType = {
+ view: "traces",
+ dimensions: [],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [],
+ timeDimension: null, // No time dimension for simpler test
+ fromTimestamp: defaultFromTime,
+ toTimestamp: defaultToTime,
+ orderBy: null,
+ chartConfig: {
+ type: "PIVOT_TABLE",
+ row_limit: 20,
+ },
+ };
+
+ // Execute query to get raw data
+ const rawData = await executeQuery(projectId, query);
+
+ // Transform to pivot table structure
+ const pivotTableData = transformToPivotTable(rawData as DatabaseRow[], {
+ dimensions: [],
+ metrics: ["count_count"],
+ rowLimit: 20,
+ });
+
+ // Verify transformation
+ expect(pivotTableData).toBeDefined();
+ expect(Array.isArray(pivotTableData)).toBe(true);
+ expect(pivotTableData.length).toBe(1); // Should have only grand total
+
+ const totalRow = pivotTableData[0];
+ expect(totalRow.type).toBe("total");
+ expect(totalRow.level).toBe(0);
+ expect(totalRow.label).toBe("Total");
+ expect(totalRow.isTotal).toBe(true);
+ expect(totalRow.values).toHaveProperty("count_count");
+ });
+
+ it("should transform query results to pivot table structure for single dimension", async () => {
+ const query: QueryType = {
+ view: "traces",
+ dimensions: [{ field: "environment" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [],
+ timeDimension: null, // No time dimension for simpler test
+ fromTimestamp: defaultFromTime,
+ toTimestamp: defaultToTime,
+ orderBy: [{ field: "environment", direction: "asc" }],
+ chartConfig: {
+ type: "PIVOT_TABLE",
+ row_limit: 20,
+ },
+ };
+
+ // Execute query to get raw data
+ const rawData = await executeQuery(projectId, query);
+
+ // Transform to pivot table structure
+ const pivotTableData = transformToPivotTable(rawData as DatabaseRow[], {
+ dimensions: ["environment"],
+ metrics: ["count_count"],
+ rowLimit: 20,
+ });
+
+ // Verify transformation
+ expect(pivotTableData).toBeDefined();
+ expect(Array.isArray(pivotTableData)).toBe(true);
+ expect(pivotTableData.length).toBeGreaterThan(1); // Should have data rows + total
+
+ // Should have data rows for each environment
+ const dataRows = pivotTableData.filter((row) => row.type === "data");
+ const totalRow = pivotTableData.find((row) => row.type === "total");
+
+ expect(dataRows.length).toBeGreaterThan(0);
+ expect(totalRow).toBeDefined();
+ expect(totalRow!.isTotal).toBe(true);
+
+ // Verify data row structure
+ dataRows.forEach((row) => {
+ expect(row.type).toBe("data");
+ expect(row.level).toBe(0);
+ expect(row.values).toHaveProperty("count_count");
+ expect(typeof row.values.count_count).toBe("number");
+ });
+ });
+
+ it("should transform query results to pivot table structure for two dimensions", async () => {
+ const query: QueryType = {
+ view: "observations",
+ dimensions: [{ field: "environment" }, { field: "providedModelName" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [],
+ timeDimension: null, // No time dimension for simpler test
+ fromTimestamp: defaultFromTime,
+ toTimestamp: defaultToTime,
+ orderBy: [
+ { field: "environment", direction: "asc" },
+ { field: "providedModelName", direction: "asc" },
+ ],
+ chartConfig: {
+ type: "PIVOT_TABLE",
+ row_limit: 20,
+ },
+ };
+
+ // Execute query to get raw data
+ const rawData = await executeQuery(projectId, query);
+
+ // Transform to pivot table structure
+ const pivotTableData = transformToPivotTable(rawData as DatabaseRow[], {
+ dimensions: ["environment", "providedModelName"],
+ metrics: ["count_count"],
+ rowLimit: 20,
+ });
+
+ // Verify transformation
+ expect(pivotTableData).toBeDefined();
+ expect(Array.isArray(pivotTableData)).toBe(true);
+ expect(pivotTableData.length).toBeGreaterThan(1);
+
+ // Should have nested structure with data rows, subtotals, and grand total
+ const dataRows = pivotTableData.filter((row) => row.type === "data");
+ const subtotalRows = pivotTableData.filter(
+ (row) => row.type === "subtotal",
+ );
+ const totalRow = pivotTableData.find((row) => row.type === "total");
+
+ expect(dataRows.length).toBeGreaterThan(0);
+ expect(totalRow).toBeDefined();
+
+ // Verify indentation levels
+ dataRows.forEach((row) => {
+ expect(row.level).toBe(1); // Second level for two dimensions
+ expect(row.values).toHaveProperty("count_count");
+ });
+
+ if (subtotalRows.length > 0) {
+ subtotalRows.forEach((row) => {
+ expect(row.level).toBe(0); // First level subtotals
+ expect(row.isSubtotal).toBe(true);
+ });
+ }
+
+ expect(totalRow!.level).toBe(0);
+ expect(totalRow!.isTotal).toBe(true);
+ });
+ });
+
+ describe("Error handling and edge cases", () => {
+ it("should handle empty results gracefully in transformation", async () => {
+ // Transform empty data to pivot table structure
+ const pivotTableData = transformToPivotTable([], {
+ dimensions: ["environment"],
+ metrics: ["count_count"],
+ rowLimit: 20,
+ });
+
+ // Should handle empty data gracefully
+ expect(pivotTableData).toBeDefined();
+ expect(Array.isArray(pivotTableData)).toBe(true);
+
+ // Should still have total row with zero values
+ expect(pivotTableData.length).toBe(1);
+ const totalRow = pivotTableData[0];
+ expect(totalRow.type).toBe("total");
+ expect(totalRow.values.count_count).toBe(0);
+ });
+
+ it("should handle missing project data gracefully", async () => {
+ const nonExistentProjectId = randomUUID();
+
+ const query: QueryType = {
+ view: "traces",
+ dimensions: [],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [],
+ timeDimension: {
+ granularity: "day",
+ },
+ fromTimestamp: defaultFromTime,
+ toTimestamp: defaultToTime,
+ orderBy: null,
+ chartConfig: {
+ type: "PIVOT_TABLE",
+ row_limit: 20,
+ },
+ };
+
+ const result = await executeQuery(nonExistentProjectId, query);
+
+ // Should return results even for non-existent project (time fill creates rows)
+ expect(result).toBeDefined();
+ expect(Array.isArray(result)).toBe(true);
+ expect(result.length).toBeGreaterThanOrEqual(0);
+ });
+ });
+});
diff --git a/web/src/__tests__/pivot-table-utils.servertest.ts b/web/src/__tests__/pivot-table-utils.servertest.ts
new file mode 100644
index 0000000000..8c3aa5c249
--- /dev/null
+++ b/web/src/__tests__/pivot-table-utils.servertest.ts
@@ -0,0 +1,1017 @@
+/**
+ * @fileoverview Unit tests for pivot table data transformation utilities
+ *
+ * This test suite comprehensively tests the pivot table utility functions,
+ * covering various dimension scenarios, edge cases, and configuration validation.
+ *
+ * Test Coverage:
+ * - transformToPivotTable function with 0-N dimensions
+ * - Configuration validation and error handling
+ * - Helper functions for row generation and calculation
+ * - MAX_DIMENSIONS constraint validation
+ * - Edge cases with empty data, null values, and malformed input
+ */
+
+import {
+ transformToPivotTable,
+ validatePivotTableConfig,
+ generateRowId,
+ createEmptyMetricValues,
+ extractDimensionValues,
+ extractMetricValues,
+ isDataRow,
+ isSubtotalRow,
+ isTotalRow,
+ groupDataByDimension,
+ calculateSubtotals,
+ calculateGrandTotals,
+ createSubtotalRow,
+ createGrandTotalRow,
+ type PivotTableConfig,
+ type DatabaseRow,
+ type PivotTableRow,
+} from "@/src/features/widgets/utils/pivot-table-utils";
+
+describe("pivot-table-utils", () => {
+ const MAX_PIVOT_TABLE_DIMENSIONS = 2;
+ // Sample test data
+ const sampleData: DatabaseRow[] = [
+ { model: "gpt-4", user: "alice", count: 10, avg_cost: 0.5 },
+ { model: "gpt-4", user: "bob", count: 15, avg_cost: 0.6 },
+ { model: "gpt-3.5", user: "alice", count: 20, avg_cost: 0.2 },
+ { model: "gpt-3.5", user: "bob", count: 25, avg_cost: 0.4 },
+ { model: "claude", user: "alice", count: 5, avg_cost: 0.8 },
+ ];
+
+ const sampleMetrics = ["count", "avg_cost"];
+
+ describe("validatePivotTableConfig", () => {
+ it("should pass validation for valid configurations", () => {
+ const validConfig: PivotTableConfig = {
+ dimensions: ["model"],
+ metrics: ["count"],
+ rowLimit: 20,
+ };
+
+ expect(() => validatePivotTableConfig(validConfig)).not.toThrow();
+ });
+
+ it("should pass validation for valid dimension counts", () => {
+ const configWithNoDimensions: PivotTableConfig = {
+ dimensions: [],
+ metrics: ["count"],
+ };
+ const configWithOneDimension: PivotTableConfig = {
+ dimensions: ["dim1"],
+ metrics: ["count"],
+ };
+ const configWithTwoDimensions: PivotTableConfig = {
+ dimensions: ["dim1", "dim2"],
+ metrics: ["count"],
+ };
+
+ expect(() =>
+ validatePivotTableConfig(configWithNoDimensions),
+ ).not.toThrow();
+ expect(() =>
+ validatePivotTableConfig(configWithOneDimension),
+ ).not.toThrow();
+ expect(() =>
+ validatePivotTableConfig(configWithTwoDimensions),
+ ).not.toThrow();
+ });
+
+ it("should throw error for empty metrics", () => {
+ const invalidConfig: PivotTableConfig = {
+ dimensions: ["model"],
+ metrics: [],
+ };
+
+ expect(() => validatePivotTableConfig(invalidConfig)).toThrow(
+ "At least one metric is required for pivot table",
+ );
+ });
+
+ it("should throw error for invalid row limit", () => {
+ const invalidConfig: PivotTableConfig = {
+ dimensions: ["model"],
+ metrics: ["count"],
+ rowLimit: 0,
+ };
+
+ expect(() => validatePivotTableConfig(invalidConfig)).toThrow(
+ "Row limit must be a positive number",
+ );
+ });
+
+ it("should throw error when dimension count exceeds maximum", () => {
+ const tooManyDimensions = Array.from(
+ { length: MAX_PIVOT_TABLE_DIMENSIONS + 1 },
+ (_, i) => `dim${i + 1}`,
+ );
+
+ const invalidConfig: PivotTableConfig = {
+ dimensions: tooManyDimensions,
+ metrics: ["count"],
+ };
+
+ expect(() => validatePivotTableConfig(invalidConfig)).toThrow(
+ `Cannot create pivot table with ${MAX_PIVOT_TABLE_DIMENSIONS + 1} dimensions. ` +
+ `Maximum supported dimensions: ${MAX_PIVOT_TABLE_DIMENSIONS}`,
+ );
+ });
+ });
+
+ describe("generateRowId", () => {
+ it("should generate consistent IDs for same inputs", () => {
+ const dimensionValues = { model: "gpt-4", user: "alice" };
+ const id1 = generateRowId(dimensionValues, "data", 0);
+ const id2 = generateRowId(dimensionValues, "data", 0);
+
+ expect(id1).toBe(id2);
+ expect(id1).toContain("data-0");
+ });
+
+ it("should generate different IDs for different inputs", () => {
+ const dimensionValues1 = { model: "gpt-4" };
+ const dimensionValues2 = { model: "gpt-3.5" };
+
+ const id1 = generateRowId(dimensionValues1, "data", 0);
+ const id2 = generateRowId(dimensionValues2, "data", 0);
+
+ expect(id1).not.toBe(id2);
+ });
+
+ it("should include type and level in ID", () => {
+ const dimensionValues = { model: "gpt-4" };
+
+ const dataId = generateRowId(dimensionValues, "data", 0);
+ const subtotalId = generateRowId(dimensionValues, "subtotal", 1);
+ const totalId = generateRowId(dimensionValues, "total", 0);
+
+ expect(dataId).toContain("data-0");
+ expect(subtotalId).toContain("subtotal-1");
+ expect(totalId).toContain("total-0");
+ });
+ });
+
+ describe("createEmptyMetricValues", () => {
+ it("should create object with all metrics set to 0", () => {
+ const metrics = ["count", "avg_cost", "total_tokens"];
+ const result = createEmptyMetricValues(metrics);
+
+ expect(result).toEqual({
+ count: 0,
+ avg_cost: 0,
+ total_tokens: 0,
+ });
+ });
+
+ it("should handle empty metrics array", () => {
+ const result = createEmptyMetricValues([]);
+ expect(result).toEqual({});
+ });
+ });
+
+ describe("extractDimensionValues", () => {
+ it("should extract specified dimension values from row", () => {
+ const row: DatabaseRow = {
+ model: "gpt-4",
+ user: "alice",
+ count: 10,
+ avg_cost: 0.5,
+ };
+
+ const result = extractDimensionValues(row, ["model", "user"]);
+
+ expect(result).toEqual({
+ model: "gpt-4",
+ user: "alice",
+ });
+ });
+
+ it("should handle missing dimension values", () => {
+ const row: DatabaseRow = {
+ model: "gpt-4",
+ count: 10,
+ };
+
+ const result = extractDimensionValues(row, ["model", "missing"]);
+
+ expect(result).toEqual({
+ model: "gpt-4",
+ missing: "",
+ });
+ });
+
+ it("should return empty object for empty dimensions", () => {
+ const row: DatabaseRow = { model: "gpt-4", count: 10 };
+ const result = extractDimensionValues(row, []);
+
+ expect(result).toEqual({});
+ });
+ });
+
+ describe("extractMetricValues", () => {
+ it("should extract specified metric values from row", () => {
+ const row: DatabaseRow = {
+ model: "gpt-4",
+ count: 10,
+ avg_cost: 0.5,
+ total_tokens: 1000,
+ };
+
+ const result = extractMetricValues(row, ["count", "avg_cost"]);
+
+ expect(result).toEqual({
+ count: 10,
+ avg_cost: 0.5,
+ });
+ });
+
+ it("should handle missing metric values", () => {
+ const row: DatabaseRow = {
+ model: "gpt-4",
+ count: 10,
+ };
+
+ const result = extractMetricValues(row, ["count", "missing"]);
+
+ expect(result).toEqual({
+ count: 10,
+ missing: 0,
+ });
+ });
+
+ it("should handle non-numeric values", () => {
+ const row: DatabaseRow = {
+ model: "gpt-4",
+ count: "invalid",
+ avg_cost: null,
+ };
+
+ const result = extractMetricValues(row, ["count", "avg_cost"]);
+
+ expect(result).toEqual({
+ count: 0,
+ avg_cost: 0,
+ });
+ });
+ });
+
+ describe("row type helpers", () => {
+ const dataRow: PivotTableRow = {
+ id: "test-data",
+ type: "data",
+ level: 0,
+ label: "Test",
+ values: { count: 10 },
+ };
+
+ const subtotalRow: PivotTableRow = {
+ id: "test-subtotal",
+ type: "subtotal",
+ level: 0,
+ label: "Subtotal",
+ values: { count: 20 },
+ isSubtotal: true,
+ };
+
+ const totalRow: PivotTableRow = {
+ id: "test-total",
+ type: "total",
+ level: 0,
+ label: "Total",
+ values: { count: 30 },
+ isTotal: true,
+ };
+
+ describe("isDataRow", () => {
+ it("should correctly identify data rows", () => {
+ expect(isDataRow(dataRow)).toBe(true);
+ expect(isDataRow(subtotalRow)).toBe(false);
+ expect(isDataRow(totalRow)).toBe(false);
+ });
+ });
+
+ describe("isSubtotalRow", () => {
+ it("should correctly identify subtotal rows", () => {
+ expect(isSubtotalRow(dataRow)).toBe(false);
+ expect(isSubtotalRow(subtotalRow)).toBe(true);
+ expect(isSubtotalRow(totalRow)).toBe(false);
+ });
+ });
+
+ describe("isTotalRow", () => {
+ it("should correctly identify total rows", () => {
+ expect(isTotalRow(dataRow)).toBe(false);
+ expect(isTotalRow(subtotalRow)).toBe(false);
+ expect(isTotalRow(totalRow)).toBe(true);
+ });
+ });
+ });
+
+ describe("groupDataByDimension", () => {
+ it("should group data by specified dimension", () => {
+ const result = groupDataByDimension(sampleData, "model");
+
+ expect(Object.keys(result)).toEqual(["gpt-4", "gpt-3.5", "claude"]);
+ expect(result["gpt-4"]).toHaveLength(2);
+ expect(result["gpt-3.5"]).toHaveLength(2);
+ expect(result["claude"]).toHaveLength(1);
+ });
+
+ it("should handle missing dimension values", () => {
+ const dataWithMissing: DatabaseRow[] = [
+ { model: "gpt-4", count: 10 },
+ { count: 15 }, // missing model
+ { model: "gpt-3.5", count: 20 },
+ ];
+
+ const result = groupDataByDimension(dataWithMissing, "model");
+
+ expect(Object.keys(result).sort()).toEqual(["gpt-3.5", "gpt-4", "n/a"]);
+ expect(result["n/a"]).toHaveLength(1);
+ });
+
+ it("should handle empty data", () => {
+ const result = groupDataByDimension([], "model");
+ expect(result).toEqual({});
+ });
+ });
+
+ describe("calculateSubtotals", () => {
+ it("should calculate subtotals for numeric metrics", () => {
+ const data: DatabaseRow[] = [
+ { count: 10, avg_cost: 0.5 },
+ { count: 15, avg_cost: 0.6 },
+ { count: 20, avg_cost: 0.4 },
+ ];
+
+ const result = calculateSubtotals(data, ["count", "avg_cost"]);
+
+ expect(result).toEqual({
+ count: 45,
+ avg_cost: 0.5,
+ });
+ });
+
+ it("should handle missing values", () => {
+ const data: DatabaseRow[] = [
+ { count: 10 },
+ { count: 15, avg_cost: 0.6 },
+ { avg_cost: 0.3 },
+ ];
+
+ const result = calculateSubtotals(data, ["count", "avg_cost"]);
+
+ expect(result).toEqual({
+ count: 25,
+ avg_cost: 0.3,
+ });
+ });
+
+ it("should handle empty data", () => {
+ const result = calculateSubtotals([], ["count", "avg_cost"]);
+
+ expect(result).toEqual({
+ count: 0,
+ avg_cost: 0,
+ });
+ });
+ });
+
+ describe("calculateGrandTotals", () => {
+ it("should calculate grand totals for all data", () => {
+ const result = calculateGrandTotals(sampleData, sampleMetrics);
+
+ expect(result).toEqual({
+ count: 75, // 10 + 15 + 20 + 25 + 5
+ avg_cost: 0.5, // (0.5 + 0.6 + 0.2 + 0.4 + 0.8) / 5
+ });
+ });
+
+ it("should handle empty data", () => {
+ const result = calculateGrandTotals([], sampleMetrics);
+
+ expect(result).toEqual({
+ count: 0,
+ avg_cost: 0,
+ });
+ });
+ });
+
+ describe("createSubtotalRow", () => {
+ it("should create properly formatted subtotal row", () => {
+ const subtotalValues = { count: 25, avg_cost: 1.1 };
+ const result = createSubtotalRow("gpt-4", subtotalValues, 0);
+
+ expect(result).toEqual({
+ id: "subtotal-0-subtotal:gpt-4",
+ type: "subtotal",
+ level: 0,
+ label: "gpt-4 (Subtotal)",
+ values: subtotalValues,
+ isSubtotal: true,
+ dimensionValues: { subtotal: "gpt-4" },
+ });
+ });
+ });
+
+ describe("createGrandTotalRow", () => {
+ it("should create properly formatted grand total row", () => {
+ const metrics = ["count", "avg_cost"];
+ const grandTotalValues = { count: 75, avg_cost: 2.6 };
+ const result = createGrandTotalRow(metrics, grandTotalValues);
+
+ expect(result).toEqual({
+ id: "total-0-total:grand",
+ type: "total",
+ level: 0,
+ label: "Total",
+ values: grandTotalValues,
+ isTotal: true,
+ dimensionValues: { total: "grand" },
+ });
+ });
+ });
+
+ describe("transformToPivotTable", () => {
+ describe("zero dimensions (summary table)", () => {
+ it("should create single total row when no dimensions specified", () => {
+ const config: PivotTableConfig = {
+ dimensions: [],
+ metrics: sampleMetrics,
+ };
+
+ const result = transformToPivotTable(sampleData, config);
+
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({
+ type: "total",
+ level: 0,
+ label: "Total",
+ isTotal: true,
+ });
+ expect(result[0].values).toEqual({
+ count: 75,
+ avg_cost: 0.5,
+ });
+ });
+
+ it("should handle empty data with zero dimensions", () => {
+ const config: PivotTableConfig = {
+ dimensions: [],
+ metrics: sampleMetrics,
+ };
+
+ const result = transformToPivotTable([], config);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].values).toEqual({
+ count: 0,
+ avg_cost: 0,
+ });
+ });
+ });
+
+ describe("single dimension grouping", () => {
+ it("should create grouped table with subtotals and grand total", () => {
+ const config: PivotTableConfig = {
+ dimensions: ["model"],
+ metrics: sampleMetrics,
+ rowLimit: 20,
+ };
+
+ const result = transformToPivotTable(sampleData, config);
+
+ // Should have: 1 grand total + 5 data rows = 6 rows (no subtotals for single dimension)
+ expect(result).toHaveLength(6);
+
+ // Check grand total is first
+ expect(result[0]).toMatchObject({
+ type: "total",
+ level: 0,
+ label: "Total",
+ isTotal: true,
+ });
+
+ // Check structure: data rows after total, no subtotals for single dimension
+ expect(result[1]).toMatchObject({
+ type: "data",
+ level: 0,
+ label: "claude",
+ });
+ });
+
+ it("should apply row limit correctly", () => {
+ const config: PivotTableConfig = {
+ dimensions: ["model"],
+ metrics: sampleMetrics,
+ rowLimit: 2, // Limit to 2 data rows
+ };
+
+ const result = transformToPivotTable(sampleData, config);
+
+ // Should have: 1 grand total + 2 data rows = 3 rows (no subtotals for single dimension)
+ expect(result).toHaveLength(3);
+
+ // Verify grand total is first, then only 2 data rows are included
+ expect(result[0].type).toBe("total");
+ const dataRows = result.filter((row) => row.type === "data");
+ expect(dataRows).toHaveLength(2);
+ });
+ });
+
+ describe("two-dimension grouping", () => {
+ it("should create nested table with proper indentation and subtotals", () => {
+ const config: PivotTableConfig = {
+ dimensions: ["model", "user"],
+ metrics: sampleMetrics,
+ rowLimit: 20,
+ };
+
+ const result = transformToPivotTable(sampleData, config);
+
+ // Should have grand total, subtotals for first dimension, and data rows
+ expect(result.length).toBeGreaterThan(5);
+
+ // Check for proper nesting levels
+ const dataRows = result.filter((row) => row.type === "data");
+ const subtotalRows = result.filter((row) => row.type === "subtotal");
+ const totalRows = result.filter((row) => row.type === "total");
+
+ expect(dataRows.length).toBeGreaterThan(0);
+ expect(subtotalRows.length).toBeGreaterThan(0);
+ expect(totalRows).toHaveLength(1);
+
+ // Check that grand total is first
+ expect(result[0].type).toBe("total");
+
+ // Check indentation levels
+ expect(dataRows.some((row) => row.level === 1)).toBe(true); // Second dimension should be indented at level 1
+ expect(subtotalRows.every((row) => row.level === 0)).toBe(true); // Subtotals at first level (level 0)
+ });
+
+ it("should handle missing values in second dimension", () => {
+ const dataWithMissing: DatabaseRow[] = [
+ { model: "gpt-4", user: "alice", count: 10, avg_cost: 0.5 },
+ { model: "gpt-4", count: 15, avg_cost: 0.6 }, // missing user
+ { model: "gpt-3.5", user: "bob", count: 20, avg_cost: 0.3 },
+ ];
+
+ const config: PivotTableConfig = {
+ dimensions: ["model", "user"],
+ metrics: sampleMetrics,
+ rowLimit: 20,
+ };
+
+ const result = transformToPivotTable(dataWithMissing, config);
+
+ // Should handle missing values gracefully
+ expect(result.length).toBeGreaterThan(0);
+ expect(result.some((row) => row.label.includes("n/a"))).toBe(true);
+ });
+ });
+
+ describe("edge cases and error handling", () => {
+ it("should handle empty data gracefully", () => {
+ const config: PivotTableConfig = {
+ dimensions: ["model"],
+ metrics: sampleMetrics,
+ };
+
+ const result = transformToPivotTable([], config);
+
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({
+ type: "total",
+ level: 0,
+ label: "Total",
+ values: { count: 0, avg_cost: 0 },
+ });
+ });
+
+ it("should handle data with all null values", () => {
+ const nullData: DatabaseRow[] = [
+ { model: null, user: null, count: null, avg_cost: null },
+ { model: null, user: null, count: null, avg_cost: null },
+ ];
+
+ const config: PivotTableConfig = {
+ dimensions: ["model"],
+ metrics: sampleMetrics,
+ };
+
+ const result = transformToPivotTable(nullData, config);
+
+ expect(result.length).toBeGreaterThan(0);
+ expect(result[0].type).toBe("total");
+ });
+
+ it("should validate configuration before processing", () => {
+ const invalidConfig: PivotTableConfig = {
+ dimensions: Array.from(
+ { length: MAX_PIVOT_TABLE_DIMENSIONS + 1 },
+ (_, i) => `dim${i + 1}`,
+ ),
+ metrics: [],
+ };
+
+ expect(() =>
+ transformToPivotTable(sampleData, invalidConfig),
+ ).toThrow();
+ });
+
+ it("should use default row limit when not specified", () => {
+ const config: PivotTableConfig = {
+ dimensions: ["model"],
+ metrics: sampleMetrics,
+ // No rowLimit specified
+ };
+
+ // This should not throw an error and should use DEFAULT_ROW_LIMIT
+ expect(() => transformToPivotTable(sampleData, config)).not.toThrow();
+ });
+
+ it("should handle very large datasets with row limiting", () => {
+ // Create a large dataset
+ const largeData: DatabaseRow[] = Array.from(
+ { length: 100 },
+ (_, i) => ({
+ model: `model-${i % 10}`,
+ user: `user-${i % 5}`,
+ count: i + 1,
+ avg_cost: (i + 1) * 0.1,
+ }),
+ );
+
+ const config: PivotTableConfig = {
+ dimensions: ["model"],
+ metrics: sampleMetrics,
+ rowLimit: 5,
+ };
+
+ const result = transformToPivotTable(largeData, config);
+
+ // Should limit data rows but still include totals
+ const dataRows = result.filter((row) => row.type === "data");
+ expect(dataRows.length).toBeLessThanOrEqual(5);
+
+ // Should still have grand total at the top
+ expect(result[0].type).toBe("total");
+ });
+ });
+
+ describe("configuration edge cases", () => {
+ it("should handle single metric", () => {
+ const config: PivotTableConfig = {
+ dimensions: ["model"],
+ metrics: ["count"],
+ };
+
+ const result = transformToPivotTable(sampleData, config);
+
+ expect(result.length).toBeGreaterThan(0);
+ expect(Object.keys(result[0].values)).toEqual(["count"]);
+ });
+
+ it("should handle many metrics", () => {
+ const manyMetrics = [
+ "count",
+ "avg_cost",
+ "total_tokens",
+ "avg_latency",
+ ];
+ const dataWithManyMetrics: DatabaseRow[] = sampleData.map((row) => ({
+ ...row,
+ total_tokens: 1000,
+ avg_latency: 0.5,
+ }));
+
+ const config: PivotTableConfig = {
+ dimensions: ["model"],
+ metrics: manyMetrics,
+ };
+
+ const result = transformToPivotTable(dataWithManyMetrics, config);
+
+ expect(result.length).toBeGreaterThan(0);
+ expect(Object.keys(result[0].values)).toEqual(manyMetrics);
+ });
+ });
+ });
+
+ describe("multiple metrics and aggregation functions", () => {
+ // Test data with various aggregation types
+ const multiMetricData: DatabaseRow[] = [
+ {
+ environment: "production",
+ model: "gpt-4",
+ count_requests: 100,
+ sum_tokens: 5000,
+ avg_latency: 120,
+ min_cost: 0.05,
+ max_cost: 0.15,
+ p95_duration: 250,
+ },
+ {
+ environment: "production",
+ model: "gpt-3.5",
+ count_requests: 200,
+ sum_tokens: 8000,
+ avg_latency: 80,
+ min_cost: 0.02,
+ max_cost: 0.08,
+ p95_duration: 150,
+ },
+ {
+ environment: "staging",
+ model: "gpt-4",
+ count_requests: 50,
+ sum_tokens: 2500,
+ avg_latency: 140,
+ min_cost: 0.06,
+ max_cost: 0.18,
+ p95_duration: 300,
+ },
+ ];
+
+ const multiMetrics = [
+ "count_requests",
+ "sum_tokens",
+ "avg_latency",
+ "min_cost",
+ "max_cost",
+ "p95_duration",
+ ];
+
+ describe("aggregation type detection and calculation", () => {
+ it("should correctly aggregate multiple metrics with different aggregation types", () => {
+ const config: PivotTableConfig = {
+ dimensions: ["environment"],
+ metrics: multiMetrics,
+ };
+
+ const result = transformToPivotTable(multiMetricData, config);
+
+ // Find the grand total row
+ const totalRow = result.find((row) => row.type === "total");
+ expect(totalRow).toBeDefined();
+
+ if (totalRow) {
+ // Count should be summed: 100 + 200 + 50 = 350
+ expect(totalRow.values.count_requests).toBe(350);
+
+ // Sum should be summed: 5000 + 8000 + 2500 = 15500
+ expect(totalRow.values.sum_tokens).toBe(15500);
+
+ // Average should be averaged: (120 + 80 + 140) / 3 = 113.33...
+ expect(totalRow.values.avg_latency).toBeCloseTo(113.33, 2);
+
+ // Min should be minimum: min(0.05, 0.02, 0.06) = 0.02
+ expect(totalRow.values.min_cost).toBe(0.02);
+
+ // Max should be maximum: max(0.15, 0.08, 0.18) = 0.18
+ expect(totalRow.values.max_cost).toBe(0.18);
+
+ // Percentile should be averaged: (250 + 150 + 300) / 3 = 233.33...
+ expect(totalRow.values.p95_duration).toBeCloseTo(233.33, 2);
+ }
+ });
+
+ it("should correctly calculate subtotals with different aggregation types", () => {
+ const config: PivotTableConfig = {
+ dimensions: ["environment"],
+ metrics: multiMetrics,
+ };
+
+ const result = transformToPivotTable(multiMetricData, config);
+
+ // Since this is single dimension, there should be data rows and a total
+ const dataRows = result.filter((row) => row.type === "data");
+ const productionDataRows = dataRows.filter(
+ (row) =>
+ row.label.includes("production") ||
+ (row.dimensionValues &&
+ row.dimensionValues.environment === "production"),
+ );
+
+ // There should be 2 production data rows
+ expect(productionDataRows.length).toBeGreaterThan(0);
+
+ // Check total row calculations include production data correctly
+ const totalRow = result.find((row) => row.type === "total");
+ expect(totalRow).toBeDefined();
+
+ if (totalRow) {
+ // Production contributes: count=300, sum=13000, avg=(120+80)/2=100
+ // Staging contributes: count=50, sum=2500, avg=140
+ // Total should be: count=350, sum=15500, avg=(100+140)/2=120 (weighted by count would be different)
+ expect(totalRow.values.count_requests).toBe(350);
+ expect(totalRow.values.sum_tokens).toBe(15500);
+ }
+ });
+
+ it("should handle mixed numeric and string values correctly", () => {
+ const mixedData: DatabaseRow[] = [
+ {
+ environment: "prod",
+ count_requests: "100", // String value
+ avg_latency: 120.5, // Numeric value
+ sum_tokens: "5000", // String value
+ },
+ {
+ environment: "prod",
+ count_requests: 200, // Numeric value
+ avg_latency: "80.2", // String value
+ sum_tokens: 8000, // Numeric value
+ },
+ ];
+
+ const config: PivotTableConfig = {
+ dimensions: ["environment"],
+ metrics: ["count_requests", "avg_latency", "sum_tokens"],
+ };
+
+ const result = transformToPivotTable(mixedData, config);
+ const totalRow = result.find((row) => row.type === "total");
+
+ expect(totalRow).toBeDefined();
+ if (totalRow) {
+ // Count: 100 + 200 = 300 (strings parsed correctly)
+ expect(totalRow.values.count_requests).toBe(300);
+
+ // Average: (120.5 + 80.2) / 2 = 100.35
+ expect(totalRow.values.avg_latency).toBeCloseTo(100.35, 2);
+
+ // Sum: 5000 + 8000 = 13000 (strings parsed correctly)
+ expect(totalRow.values.sum_tokens).toBe(13000);
+ }
+ });
+
+ it("should handle edge cases for different aggregation types", () => {
+ const edgeCaseData: DatabaseRow[] = [
+ {
+ category: "A",
+ count_items: 0,
+ avg_score: 0,
+ min_value: 100,
+ max_value: 100,
+ },
+ ];
+
+ const config: PivotTableConfig = {
+ dimensions: ["category"],
+ metrics: ["count_items", "avg_score", "min_value", "max_value"],
+ };
+
+ const result = transformToPivotTable(edgeCaseData, config);
+ const totalRow = result.find((row) => row.type === "total");
+
+ expect(totalRow).toBeDefined();
+ if (totalRow) {
+ expect(totalRow.values.count_items).toBe(0);
+ expect(totalRow.values.avg_score).toBe(0);
+ expect(totalRow.values.min_value).toBe(100);
+ expect(totalRow.values.max_value).toBe(100);
+ }
+ });
+
+ it("should handle empty arrays for aggregation functions", () => {
+ const config: PivotTableConfig = {
+ dimensions: ["nonexistent"],
+ metrics: ["count_requests", "avg_latency"],
+ };
+
+ const result = transformToPivotTable([], config);
+
+ expect(result).toHaveLength(1);
+ const totalRow = result[0];
+ expect(totalRow.type).toBe("total");
+ expect(totalRow.values.count_requests).toBe(0);
+ expect(totalRow.values.avg_latency).toBe(0);
+ });
+ });
+
+ describe("complex multi-dimensional scenarios with multiple metrics", () => {
+ it("should handle two dimensions with multiple aggregation types", () => {
+ const config: PivotTableConfig = {
+ dimensions: ["environment", "model"],
+ metrics: multiMetrics,
+ };
+
+ const result = transformToPivotTable(multiMetricData, config);
+
+ // Should have grand total, subtotals, and data rows
+ const dataRows = result.filter((row) => row.type === "data");
+ const subtotalRows = result.filter((row) => row.type === "subtotal");
+ const totalRow = result.find((row) => row.type === "total");
+
+ expect(dataRows.length).toBe(3); // 3 data points
+ expect(subtotalRows.length).toBeGreaterThan(0); // Environment subtotals
+ expect(totalRow).toBeDefined();
+
+ // Check that grand total is first
+ expect(result[0].type).toBe("total");
+
+ // Check that subtotals correctly aggregate their children
+ const productionSubtotal = subtotalRows.find((row) =>
+ row.label.includes("production"),
+ );
+
+ if (productionSubtotal) {
+ // Production has 2 models: gpt-4 (100 requests) + gpt-3.5 (200 requests) = 300
+ expect(productionSubtotal.values.count_requests).toBe(300);
+
+ // Production tokens: 5000 + 8000 = 13000
+ expect(productionSubtotal.values.sum_tokens).toBe(13000);
+
+ // Production avg latency: (120 + 80) / 2 = 100
+ expect(productionSubtotal.values.avg_latency).toBe(100);
+
+ // Production min cost: min(0.05, 0.02) = 0.02
+ expect(productionSubtotal.values.min_cost).toBe(0.02);
+
+ // Production max cost: max(0.15, 0.08) = 0.15
+ expect(productionSubtotal.values.max_cost).toBe(0.15);
+ }
+ });
+
+ it("should validate metric field name patterns", () => {
+ const testCases = [
+ { metric: "count_requests", expectedType: "count" },
+ { metric: "sum_tokens", expectedType: "sum" },
+ { metric: "avg_latency", expectedType: "avg" },
+ { metric: "average_score", expectedType: "avg" },
+ { metric: "min_cost", expectedType: "min" },
+ { metric: "max_duration", expectedType: "max" },
+ { metric: "p95_latency", expectedType: "percentile" },
+ { metric: "p99_duration", expectedType: "percentile" },
+ { metric: "p50_response", expectedType: "percentile" },
+ { metric: "unknown_metric", expectedType: "sum" }, // defaults to sum
+ ];
+
+ // Test each pattern by creating data and checking the results
+ testCases.forEach(({ metric, expectedType }) => {
+ const testData: DatabaseRow[] = [
+ { category: "A", [metric]: 10 },
+ { category: "A", [metric]: 20 },
+ ];
+
+ const config: PivotTableConfig = {
+ dimensions: ["category"],
+ metrics: [metric],
+ };
+
+ const result = transformToPivotTable(testData, config);
+ const totalRow = result.find((row) => row.type === "total");
+
+ expect(totalRow).toBeDefined();
+ if (totalRow) {
+ const value = totalRow.values[metric];
+
+ switch (expectedType) {
+ case "count":
+ case "sum":
+ expect(value).toBe(30); // 10 + 20
+ break;
+ case "avg":
+ case "percentile":
+ expect(value).toBe(15); // (10 + 20) / 2
+ break;
+ case "min":
+ expect(value).toBe(10); // min(10, 20)
+ break;
+ case "max":
+ expect(value).toBe(20); // max(10, 20)
+ break;
+ }
+ }
+ });
+ });
+
+ it("should maintain precision in floating point calculations", () => {
+ const precisionData: DatabaseRow[] = [
+ { env: "test", avg_value: 0.1 },
+ { env: "test", avg_value: 0.2 },
+ { env: "test", avg_value: 0.3 },
+ ];
+
+ const config: PivotTableConfig = {
+ dimensions: ["env"],
+ metrics: ["avg_value"],
+ };
+
+ const result = transformToPivotTable(precisionData, config);
+ const totalRow = result.find((row) => row.type === "total");
+
+ expect(totalRow).toBeDefined();
+ if (totalRow) {
+ // Should be (0.1 + 0.2 + 0.3) / 3 = 0.2, properly rounded
+ expect(totalRow.values.avg_value).toBeCloseTo(0.2, 10);
+ }
+ });
+ });
+ });
+});
diff --git a/web/src/__tests__/pivot-table.clienttest.tsx b/web/src/__tests__/pivot-table.clienttest.tsx
new file mode 100644
index 0000000000..fb73ae52c4
--- /dev/null
+++ b/web/src/__tests__/pivot-table.clienttest.tsx
@@ -0,0 +1,383 @@
+/**
+ * @fileoverview Unit Tests for PivotTable React Component
+ *
+ * Comprehensive test suite for the PivotTable component functionality including:
+ * - Component rendering with various data scenarios
+ * - Proper styling and CSS class application
+ * - Indentation behavior for nested dimensions
+ * - Empty data and error state handling
+ * - Metric value formatting and display
+ * - Column header formatting
+ *
+ * Uses Jest and React Testing Library for component testing.
+ * This test focuses on component behavior rather than data transformation logic.
+ */
+
+import React from "react";
+import { render, screen } from "@testing-library/react";
+import "@testing-library/jest-dom";
+
+import {
+ PivotTable,
+ type PivotTableProps,
+} from "@/src/features/widgets/chart-library/PivotTable";
+import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";
+
+describe("PivotTable Component", () => {
+ describe("Basic Rendering", () => {
+ test("renders table with simple data", () => {
+ const data: DataPoint[] = [
+ {
+ time_dimension: "2024-01-01",
+ dimension: "gpt-4",
+ metric: 100,
+ },
+ {
+ time_dimension: "2024-01-01",
+ dimension: "gpt-3.5",
+ metric: 75,
+ },
+ ];
+
+ const props: PivotTableProps = {
+ data,
+ config: {
+ dimensions: ["model"],
+ metrics: ["metric"],
+ },
+ };
+
+ render(<PivotTable {...props} />);
+
+ // Check table structure exists
+ expect(screen.getByRole("table")).toBeInTheDocument();
+ // Should have dimension column and metric column
+ expect(screen.getAllByRole("columnheader")).toHaveLength(2);
+ });
+
+ test("displays data when no configuration provided", () => {
+ const data: DataPoint[] = [
+ {
+ time_dimension: "2024-01-01",
+ dimension: "test",
+ metric: 50,
+ },
+ ];
+
+ const props: PivotTableProps = {
+ data,
+ };
+
+ render(<PivotTable {...props} />);
+
+ // Should still render a table
+ expect(screen.getByRole("table")).toBeInTheDocument();
+ });
+ });
+
+ describe("Column Header Formatting", () => {
+ test("formats single dimension header correctly", () => {
+ const data: DataPoint[] = [
+ {
+ time_dimension: "2024-01-01",
+ dimension: "test",
+ metric: 100,
+ },
+ ];
+
+ const props: PivotTableProps = {
+ data,
+ config: {
+ dimensions: ["model_name"],
+ metrics: ["request_count"],
+ },
+ };
+
+ render(<PivotTable {...props} />);
+
+ expect(
+ screen.getByRole("columnheader", { name: "Model Name" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("columnheader", { name: "Request Count" }),
+ ).toBeInTheDocument();
+ });
+
+ test("formats multiple dimension headers correctly", () => {
+ const data: DataPoint[] = [
+ {
+ time_dimension: "2024-01-01",
+ dimension: "test",
+ metric: 100,
+ },
+ ];
+
+ const props: PivotTableProps = {
+ data,
+ config: {
+ dimensions: ["model_name", "time_period"],
+ metrics: ["request_count", "avg_duration"],
+ },
+ };
+
+ render(<PivotTable {...props} />);
+
+ expect(
+ screen.getByRole("columnheader", { name: "Model Name / Time Period" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("columnheader", { name: "Request Count" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("columnheader", { name: "Avg Duration" }),
+ ).toBeInTheDocument();
+ });
+
+ test("defaults to 'Dimension' when no dimensions configured", () => {
+ const data: DataPoint[] = [
+ {
+ time_dimension: "2024-01-01",
+ dimension: "test",
+ metric: 100,
+ },
+ ];
+
+ const props: PivotTableProps = {
+ data,
+ config: {
+ dimensions: [],
+ metrics: ["metric"],
+ },
+ };
+
+ render(<PivotTable {...props} />);
+
+ expect(
+ screen.getByRole("columnheader", { name: "Dimension" }),
+ ).toBeInTheDocument();
+ });
+ });
+
+ describe("Empty Data Handling", () => {
+ test("displays 'No data available' for empty data array", () => {
+ const props: PivotTableProps = {
+ data: [],
+ config: {
+ dimensions: ["model"],
+ metrics: ["metric"],
+ },
+ };
+
+ render(<PivotTable {...props} />);
+
+ expect(screen.getByText("No data available")).toBeInTheDocument();
+ expect(screen.queryByRole("table")).not.toBeInTheDocument();
+ });
+
+ test("displays 'No data available' for null data", () => {
+ const props: PivotTableProps = {
+ data: null as any,
+ config: {
+ dimensions: ["model"],
+ metrics: ["metric"],
+ },
+ };
+
+ render(<PivotTable {...props} />);
+
+ expect(screen.getByText("No data available")).toBeInTheDocument();
+ expect(screen.queryByRole("table")).not.toBeInTheDocument();
+ });
+
+ test("displays 'No data available' for undefined data", () => {
+ const props: PivotTableProps = {
+ data: undefined as any,
+ config: {
+ dimensions: ["model"],
+ metrics: ["metric"],
+ },
+ };
+
+ render(<PivotTable {...props} />);
+
+ expect(screen.getByText("No data available")).toBeInTheDocument();
+ expect(screen.queryByRole("table")).not.toBeInTheDocument();
+ });
+ });
+
+ describe("Responsive Design", () => {
+ test("includes overflow-auto class for responsive scrolling", () => {
+ const data: DataPoint[] = [
+ {
+ time_dimension: "2024-01-01",
+ dimension: "test",
+ metric: 100,
+ },
+ ];
+
+ const props: PivotTableProps = {
+ data,
+ config: {
+ dimensions: ["model"],
+ metrics: ["metric"],
+ },
+ };
+
+ const { container } = render(<PivotTable {...props} />);
+
+ const pivotTableContainer = container.firstChild as HTMLElement;
+ expect(pivotTableContainer).toHaveClass("h-full", "overflow-auto");
+ });
+ });
+
+ describe("Accessibility", () => {
+ test("provides proper table structure for screen readers", () => {
+ const data: DataPoint[] = [
+ {
+ time_dimension: "2024-01-01",
+ dimension: "gpt-4",
+ metric: 100,
+ },
+ ];
+
+ const props: PivotTableProps = {
+ data,
+ config: {
+ dimensions: ["model"],
+ metrics: ["metric"],
+ },
+ };
+
+ render(<PivotTable {...props} />);
+
+ // Check table has proper semantic structure
+ expect(screen.getByRole("table")).toBeInTheDocument();
+ expect(screen.getAllByRole("columnheader")).toHaveLength(2);
+ // Should have at least header row
+ expect(screen.getAllByRole("row").length).toBeGreaterThanOrEqual(1);
+ });
+
+ test("provides proper cell associations", () => {
+ const data: DataPoint[] = [
+ {
+ time_dimension: "2024-01-01",
+ dimension: "test",
+ metric: 100,
+ },
+ ];
+
+ const props: PivotTableProps = {
+ data,
+ config: {
+ dimensions: ["model"],
+ metrics: ["metric"],
+ },
+ };
+
+ render(<PivotTable {...props} />);
+
+ // Header cells should be properly associated
+ const headers = screen.getAllByRole("columnheader");
+ expect(headers.length).toBeGreaterThan(0);
+
+ // Each header should be part of a row
+ headers.forEach((header) => {
+ expect(header.closest("tr")).toBeInTheDocument();
+ });
+ });
+ });
+
+ describe("Component Props", () => {
+ test("handles missing config gracefully", () => {
+ const data: DataPoint[] = [
+ {
+ time_dimension: "2024-01-01",
+ dimension: "test",
+ metric: 100,
+ },
+ ];
+
+ const props: PivotTableProps = {
+ data,
+ // No config provided
+ };
+
+ render(<PivotTable {...props} />);
+
+ // Should still render a table
+ expect(screen.getByRole("table")).toBeInTheDocument();
+ });
+
+ test("passes accessibilityLayer prop correctly", () => {
+ const data: DataPoint[] = [
+ {
+ time_dimension: "2024-01-01",
+ dimension: "test",
+ metric: 100,
+ },
+ ];
+
+ const props: PivotTableProps = {
+ data,
+ accessibilityLayer: true,
+ };
+
+ // Should render without error
+ expect(() => render(<PivotTable {...props} />)).not.toThrow();
+ });
+ });
+
+ describe("Data Processing Integration", () => {
+ test("handles various metric data types", () => {
+ const data: DataPoint[] = [
+ {
+ time_dimension: "2024-01-01",
+ dimension: "test1",
+ metric: 100, // number
+ },
+ {
+ time_dimension: "2024-01-01",
+ dimension: "test2",
+ metric: [
+ [10, 20],
+ [30, 40],
+ ], // nested array
+ },
+ ];
+
+ const props: PivotTableProps = {
+ data,
+ config: {
+ dimensions: ["model"],
+ metrics: ["metric"],
+ },
+ };
+
+ // Should render without error
+ expect(() => render(<PivotTable {...props} />)).not.toThrow();
+ expect(screen.getByRole("table")).toBeInTheDocument();
+ });
+
+ test("handles missing dimension data", () => {
+ const data: DataPoint[] = [
+ {
+ time_dimension: "2024-01-01",
+ dimension: undefined, // missing dimension
+ metric: 100,
+ },
+ ];
+
+ const props: PivotTableProps = {
+ data,
+ config: {
+ dimensions: ["model"],
+ metrics: ["metric"],
+ },
+ };
+
+ // Should render without error
+ expect(() => render(<PivotTable {...props} />)).not.toThrow();
+ expect(screen.getByRole("table")).toBeInTheDocument();
+ });
+ });
+});
diff --git a/web/src/__tests__/queryBuilder.servertest.ts b/web/src/__tests__/queryBuilder.servertest.ts
index 55fefd8572..79ff57e6ef 100644
--- a/web/src/__tests__/queryBuilder.servertest.ts
+++ b/web/src/__tests__/queryBuilder.servertest.ts
@@ -3427,7 +3427,9 @@ describe("queryBuilder", () => {
};
// Execute histogram query with custom bins
- const queryBuilder = new QueryBuilder(customBinHistogramQuery.chartConfig);
+ const queryBuilder = new QueryBuilder(
+ customBinHistogramQuery.chartConfig,
+ );
const { query: compiledQuery, parameters } = queryBuilder.build(
customBinHistogramQuery,
projectId,
diff --git a/web/src/features/query/types.ts b/web/src/features/query/types.ts
index 0417a8440a..0a5969a3d4 100644
--- a/web/src/features/query/types.ts
+++ b/web/src/features/query/types.ts
@@ -114,7 +114,7 @@ export const query = z
}),
)
.nullable(),
- // Chart configuration for chart-specific settings like histogram bins
+ // Chart configuration for chart-specific settings like histogram bins and pivot table dimensions
chartConfig: z
.object({
type: z.string(),
diff --git a/web/src/features/widgets/chart-library/Chart.tsx b/web/src/features/widgets/chart-library/Chart.tsx
index 24913fa07f..9c46295f65 100644
--- a/web/src/features/widgets/chart-library/Chart.tsx
+++ b/web/src/features/widgets/chart-library/Chart.tsx
@@ -11,15 +11,24 @@ import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";
import { Button } from "@/src/components/ui/button";
import { AlertCircle } from "lucide-react";
import { BigNumber } from "@/src/features/widgets/chart-library/BigNumber";
+import { PivotTable } from "@/src/features/widgets/chart-library/PivotTable";
export const Chart = ({
chartType,
data,
rowLimit,
+ chartConfig,
}: {
chartType: DashboardWidgetChartType;
data: DataPoint[];
rowLimit: number;
+ chartConfig?: {
+ type: DashboardWidgetChartType;
+ row_limit?: number;
+ bins?: number;
+ dimensions?: string[];
+ metrics?: string[];
+ };
}) => {
const [forceRender, setForceRender] = useState(false);
const shouldWarn = data.length > 2000 && !forceRender;
@@ -58,6 +67,15 @@ export const Chart = ({
case "NUMBER": {
return <BigNumber data={renderedData} />;
}
+ case "PIVOT_TABLE": {
+ // Extract pivot table configuration from chartConfig
+ const pivotConfig = {
+ dimensions: chartConfig?.dimensions ?? [],
+ metrics: chartConfig?.metrics ?? ["metric"], // Use metrics from chartConfig
+ rowLimit: chartConfig?.row_limit ?? rowLimit,
+ };
+ return <PivotTable data={renderedData} config={pivotConfig} />;
+ }
default:
return <HorizontalBarChart data={renderedData.slice(0, rowLimit)} />;
}
diff --git a/web/src/features/widgets/chart-library/PivotTable.tsx b/web/src/features/widgets/chart-library/PivotTable.tsx
new file mode 100644
index 0000000000..40071c851d
--- /dev/null
+++ b/web/src/features/widgets/chart-library/PivotTable.tsx
@@ -0,0 +1,269 @@
+/**
+ * @fileoverview PivotTable Chart Component
+ *
+ * A configurable pivot table widget component that displays data in a tabular format
+ * with support for multiple dimensions (currently up to 2), metrics as columns,
+ * subtotals, and grand totals.
+ *
+ * Features:
+ * - Dynamic dimension support (0-N dimensions, currently limited to 2)
+ * - Proper indentation for nested dimension levels
+ * - Subtotal and grand total calculations
+ * - Responsive design within dashboard grid
+ * - Consistent styling with Langfuse design system
+ * - Row limiting to prevent performance issues
+ *
+ * Usage:
+ * Used as part of the dashboard widget system to display tabular data
+ * visualizations with grouping and aggregation capabilities.
+ */
+
+import React, { useMemo } from "react";
+import { cn } from "@/src/utils/tailwind";
+import {
+ Table,
+ TableHeader,
+ TableBody,
+ TableHead,
+ TableRow,
+ TableCell,
+} from "@/src/components/ui/table";
+import {
+ transformToPivotTable,
+ extractDimensionValues,
+ extractMetricValues,
+ type PivotTableRow,
+ type PivotTableConfig,
+ type DatabaseRow,
+ DEFAULT_ROW_LIMIT,
+} from "@/src/features/widgets/utils/pivot-table-utils";
+import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";
+import { numberFormatter } from "@/src/utils/numbers";
+import { formatMetricName } from "@/src/features/widgets/utils";
+
+/**
+ * Props interface for the PivotTable component
+ * Uses standard chart data structure with pivot-specific configuration
+ */
+export interface PivotTableProps {
+ /** Array of data points from the chart query */
+ data: ChartProps["data"];
+
+ /** Pivot table specific configuration */
+ config?: PivotTableConfig;
+
+ /** Chart configuration from shadcn/ui (for consistency with other charts) */
+ chartConfig?: ChartProps["config"];
+
+ /** Accessibility layer flag */
+ accessibilityLayer?: boolean;
+}
+
+/**
+ * Individual row component for the pivot table
+ * Handles styling, indentation, and content display for each row type
+ */
+const PivotTableRowComponent: React.FC<{
+ row: PivotTableRow;
+ metrics: string[];
+}> = ({ row, metrics }) => {
+ return (
+ <TableRow
+ className={cn(
+ "border-b transition-colors hover:bg-muted/30",
+ row.isSubtotal && "bg-muted/30",
+ row.isTotal && "bg-muted/50",
+ )}
+ >
+ {/* Dimension column with indentation and styling */}
+ <TableCell
+ className={cn(
+ "p-2 align-middle font-normal",
+ // Apply indentation based on level using explicit Tailwind classes
+ row.level === 1 && "pl-6", // 1.5rem indentation for level 1
+ row.level === 2 && "pl-10", // 2.5rem indentation for level 2
+ // Bold styling for subtotal and total rows
+ (row.isSubtotal || row.isTotal) && "font-semibold",
+ )}
+ style={{
+ // Fallback for levels beyond 2 using inline styles
+ paddingLeft:
+ row.level > 2 ? `${row.level * 1.5 + 0.5}rem` : undefined,
+ }}
+ >
+ {row.label}
+ </TableCell>
+
+ {/* Metric columns */}
+ {metrics.map((metric) => (
+ <TableCell
+ key={metric}
+ className={cn(
+ "p-2 text-right align-middle tabular-nums",
+ (row.isSubtotal || row.isTotal) && "font-semibold",
+ )}
+ >
+ {formatMetricValue(row.values[metric])}
+ </TableCell>
+ ))}
+ </TableRow>
+ );
+};
+
+/**
+ * Formats metric values for display in the table
+ * Handles numbers and strings with appropriate formatting
+ *
+ * @param value - The metric value to format
+ * @returns Formatted string for display
+ */
+function formatMetricValue(value: number | string): string {
+ if (typeof value === "string") {
+ return value;
+ }
+
+ return numberFormatter(value, 2).replace(/\.00$/, "");
+}
+
+/**
+ * Formats metric names for column headers
+ *
+ * @param metricName - The metric field name
+ * @returns Formatted column header
+ */
+function formatColumnHeader(metricName: string): string {
+ return formatMetricName(metricName);
+}
+
+/**
+ * Main PivotTable Component
+ *
+ * Transforms flat data into a pivot table structure and renders it with
+ * proper styling, indentation, and responsive behavior.
+ *
+ * @param data - Array of data points from the chart query
+ * @param config - Pivot table configuration including dimensions and metrics
+ */
+export const PivotTable: React.FC<PivotTableProps> = ({ data, config }) => {
+ // Transform chart data into pivot table structure
+ const pivotTableRows = useMemo(() => {
+ if (!data || data.length === 0) {
+ return [];
+ }
+
+ // Extract configuration with defaults
+ const pivotConfig: PivotTableConfig = {
+ dimensions: config?.dimensions ?? [],
+ metrics: config?.metrics ?? ["metric"], // Default to 'metric' field from DataPoint
+ rowLimit: config?.rowLimit ?? DEFAULT_ROW_LIMIT,
+ };
+
+ // Transform DataPoint[] to DatabaseRow[] format using utility functions
+ const databaseRows: DatabaseRow[] = data.map((point) => {
+ // Cast the point to any to access dynamic fields from the query
+ const rowData = point as any;
+
+ // Create a database row with all fields from the original data
+ const row: DatabaseRow = { ...rowData };
+
+ // Use utility functions to ensure proper extraction and parsing
+ const dimensionValues = extractDimensionValues(
+ row,
+ pivotConfig.dimensions,
+ );
+ const metricValues = extractMetricValues(row, pivotConfig.metrics);
+
+ // Combine dimension and metric values into the final row
+ const result: DatabaseRow = {
+ ...dimensionValues,
+ ...metricValues,
+ };
+
+ // Include time dimension if present
+ if (point.time_dimension !== undefined) {
+ result.time_dimension = point.time_dimension;
+ }
+
+ // Include legacy 'metric' field for backward compatibility
+ if (point.metric !== undefined) {
+ if (typeof point.metric === "number") {
+ result.metric = point.metric;
+ } else if (Array.isArray(point.metric)) {
+ result.metric = point.metric
+ .flat()
+ .reduce((sum, val) => sum + val, 0);
+ }
+ }
+
+ return result;
+ });
+
+ try {
+ return transformToPivotTable(databaseRows, pivotConfig);
+ } catch (error) {
+ console.error("Error transforming data to pivot table:", error);
+ return [];
+ }
+ }, [data, config]);
+
+ // Extract metrics from configuration or fallback to default
+ const metrics = useMemo(() => {
+ return config?.metrics ?? ["metric"];
+ }, [config?.metrics]);
+
+ // Handle empty data state
+ if (!data || data.length === 0) {
+ return (
+ <div className="flex h-full items-center justify-center">
+ <div className="text-center">
+ <p className="text-sm text-muted-foreground">No data available</p>
+ </div>
+ </div>
+ );
+ }
+
+ // Handle transformation errors
+ if (pivotTableRows.length === 0) {
+ return (
+ <div className="flex h-full items-center justify-center">
+ <div className="text-center">
+ <p className="text-sm text-muted-foreground">
+ Unable to process data for pivot table
+ </p>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="h-full overflow-auto px-5 pb-2">
+ <Table>
+ <TableHeader>
+ <TableRow className="border-b bg-muted/50">
+ {/* Dimension column header */}
+ <TableHead className="p-2 text-left font-medium">
+ {config?.dimensions && config.dimensions.length > 0
+ ? config.dimensions.map(formatColumnHeader).join(" / ") // Show all dimensions
+ : "Dimension"}
+ </TableHead>
+
+ {/* Metric column headers */}
+ {metrics.map((metric) => (
+ <TableHead key={metric} className="p-2 text-right font-medium">
+ {formatColumnHeader(metric)}
+ </TableHead>
+ ))}
+ </TableRow>
+ </TableHeader>
+
+ <TableBody>
+ {pivotTableRows.map((row) => (
+ <PivotTableRowComponent key={row.id} row={row} metrics={metrics} />
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ );
+};
+
+export default PivotTable;
diff --git a/web/src/features/widgets/chart-library/utils.ts b/web/src/features/widgets/chart-library/utils.ts
index fe48f33977..e143bb61a7 100644
--- a/web/src/features/widgets/chart-library/utils.ts
+++ b/web/src/features/widgets/chart-library/utils.ts
@@ -51,6 +51,7 @@ export const isTimeSeriesChart = (
case "PIE":
case "HISTOGRAM":
case "NUMBER":
+ case "PIVOT_TABLE":
return false;
default:
return false;
@@ -82,6 +83,8 @@ export function getChartTypeDisplayName(
return "Big Number (Total Value)";
case "HISTOGRAM":
return "Histogram (Total Value)";
+ case "PIVOT_TABLE":
+ return "Pivot Table (Total Value)";
default:
return "Unknown Chart Type";
}
diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsx
index bd7c748265..dd51cb2d96 100644
--- a/web/src/features/widgets/components/DashboardWidget.tsx
+++ b/web/src/features/widgets/components/DashboardWidget.tsx
@@ -17,10 +17,10 @@ import {
Loader2,
} from "lucide-react";
import { useRouter } from "next/router";
-import { startCase } from "lodash";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { showErrorToast } from "@/src/features/notifications/showErrorToast";
import { DownloadButton } from "@/src/features/widgets/chart-library/DownloadButton";
+import { formatMetricName } from "@/src/features/widgets/utils";
export interface WidgetPlacement {
id: string;
@@ -113,10 +113,23 @@ export function DashboardWidget({
return [];
}
return queryResult.data.map((item: any) => {
- // Get the dimension field (first dimension in the query)
- const dimensionField =
- widget.data.dimensions.slice().shift()?.field ?? "none";
- // Get the metric field (first metric in the query with its aggregation)
+ if (widget.data.chartType === "PIVOT_TABLE") {
+ // For pivot tables, preserve all raw data fields without any transformation
+ // The PivotTable component will extract the appropriate metric fields
+ // using the metric field names passed via chartConfig
+ return {
+ dimension:
+ widget.data.dimensions.length > 0
+ ? (widget.data.dimensions[0]?.field ?? "dimension")
+ : "dimension", // Fallback for compatibility
+ metric: 0, // Placeholder - not used for pivot tables
+ time_dimension: item["time_dimension"],
+ // Include all original query fields for pivot table processing
+ ...item,
+ };
+ }
+
+ // Regular chart processing for non-pivot tables
const metric = widget.data.metrics.slice().shift() ?? {
measure: "count",
agg: "count",
@@ -124,6 +137,8 @@ export function DashboardWidget({
const metricField = `${metric.agg}_${metric.measure}`;
const metricValue = item[metricField];
+ const dimensionField =
+ widget.data.dimensions.slice().shift()?.field ?? "none";
return {
dimension:
item[dimensionField] !== undefined
@@ -136,7 +151,7 @@ export function DashboardWidget({
// Objects / numbers / booleans are stringified to avoid React key issues
return String(val);
})()
- : startCase(metricField === "count_count" ? "Count" : metricField),
+ : formatMetricName(metricField),
metric: Array.isArray(metricValue)
? metricValue
: Number(metricValue || 0),
@@ -276,6 +291,16 @@ export function DashboardWidget({
? 100
: (widget.data.chartConfig.row_limit ?? 100)
}
+ chartConfig={{
+ ...widget.data.chartConfig,
+ // For PIVOT_TABLE, enhance chartConfig with dimensions and metric field names
+ ...(widget.data.chartType === "PIVOT_TABLE" && {
+ dimensions: widget.data.dimensions.map((dim) => dim.field),
+ metrics: widget.data.metrics.map(
+ (metric) => `${metric.agg}_${metric.measure}`,
+ ),
+ }),
+ }}
/>
</div>
</div>
diff --git a/web/src/features/widgets/components/WidgetForm.tsx b/web/src/features/widgets/components/WidgetForm.tsx
index 147c486d76..831a783efe 100644
--- a/web/src/features/widgets/components/WidgetForm.tsx
+++ b/web/src/features/widgets/components/WidgetForm.tsx
@@ -47,11 +47,20 @@ import {
BarChartHorizontal,
Hash,
BarChart3,
+ Table,
+ X,
+ Plus,
} from "lucide-react";
import {
buildWidgetName,
buildWidgetDescription,
+ formatMetricName,
} from "@/src/features/widgets/utils";
+import { Badge } from "@/src/components/ui/badge";
+import {
+ MAX_PIVOT_TABLE_DIMENSIONS,
+ MAX_PIVOT_TABLE_METRICS,
+} from "@/src/features/widgets/utils/pivot-table-utils";
type ChartType = {
group: "time-series" | "total-value";
@@ -61,6 +70,10 @@ type ChartType = {
supportsBreakdown: boolean;
};
+import { type WidgetChartConfig } from "@/src/features/widgets/utils";
+
+type ChartConfig = WidgetChartConfig;
+
const chartTypes: ChartType[] = [
{
group: "total-value",
@@ -111,8 +124,30 @@ const chartTypes: ChartType[] = [
icon: PieChart,
supportsBreakdown: true,
},
+ {
+ group: "total-value",
+ name: "Pivot Table",
+ value: "PIVOT_TABLE",
+ icon: Table,
+ supportsBreakdown: true,
+ },
];
+/**
+ * Interface for representing a selected metric combination
+ * Combines measure and aggregation into a single selectable entity
+ */
+interface SelectedMetric {
+ /** Unique identifier for this metric combination */
+ id: string;
+ /** The measure field name (e.g., "count", "latency") */
+ measure: string;
+ /** The aggregation method (e.g., "sum", "avg", "count") */
+ aggregation: z.infer<typeof metricAggregations>;
+ /** Display label for the metric */
+ label: string;
+}
+
export function WidgetForm({
initialValues,
projectId,
@@ -128,11 +163,10 @@ export function WidgetForm({
dimension: string;
filters?: FilterState;
chartType: DashboardWidgetChartType;
- chartConfig?: {
- type: DashboardWidgetChartType;
- row_limit?: number;
- bins?: number;
- };
+ chartConfig?: ChartConfig;
+ // Support for complete widget data (editing mode)
+ metrics?: { measure: string; agg: string }[];
+ dimensions?: { field: string }[];
};
projectId: string;
onSave: (widgetData: {
@@ -143,11 +177,7 @@ export function WidgetForm({
metrics: { measure: string; agg: string }[];
filters: any[];
chartType: DashboardWidgetChartType;
- chartConfig: {
- type: DashboardWidgetChartType;
- row_limit?: number;
- bins?: number;
- };
+ chartConfig: ChartConfig;
}) => void;
widgetId?: string;
}) {
@@ -166,16 +196,50 @@ export function WidgetForm({
const [selectedView, setSelectedView] = useState<z.infer<typeof views>>(
initialValues.view,
);
+
+ // For regular charts: single metric selection
const [selectedMeasure, setSelectedMeasure] = useState<string>(
initialValues.measure,
);
const [selectedAggregation, setSelectedAggregation] = useState<
z.infer<typeof metricAggregations>
>(initialValues.aggregation);
+
+ // For pivot tables: multiple metrics selection
+ const [selectedMetrics, setSelectedMetrics] = useState<SelectedMetric[]>(
+ initialValues.chartType === "PIVOT_TABLE" && initialValues.metrics?.length
+ ? // Initialize from complete metrics data (editing mode)
+ initialValues.metrics.map((metric) => ({
+ id: `${metric.agg}_${metric.measure}`,
+ measure: metric.measure,
+ aggregation: metric.agg as z.infer<typeof metricAggregations>,
+ label: `${startCase(metric.agg)} ${startCase(metric.measure)}`,
+ }))
+ : // Default to single metric (new widget)
+ [
+ {
+ id: `${initialValues.aggregation}_${initialValues.measure}`,
+ measure: initialValues.measure,
+ aggregation: initialValues.aggregation,
+ label: `${startCase(initialValues.aggregation)} ${startCase(initialValues.measure)}`,
+ },
+ ],
+ );
+
const [selectedDimension, setSelectedDimension] = useState<string>(
initialValues.dimension,
);
+ // Pivot table dimensions state (for PIVOT_TABLE chart type)
+ const [pivotDimensions, setPivotDimensions] = useState<string[]>(
+ initialValues.chartType === "PIVOT_TABLE" &&
+ initialValues.dimensions?.length
+ ? // Initialize from complete dimensions data (editing mode)
+ initialValues.dimensions.map((dim) => dim.field)
+ : // Default to empty array (new widget)
+ [],
+ );
+
const [selectedChartType, setSelectedChartType] = useState<string>(
initialValues.chartType,
);
@@ -207,6 +271,55 @@ export function WidgetForm({
}) ?? [],
);
+ // Helper function to update pivot table dimensions
+ const updatePivotDimension = (index: number, value: string) => {
+ const newDimensions = [...pivotDimensions];
+ if (value && value !== "none") {
+ // Set the dimension at the specified index
+ newDimensions[index] = value;
+ } else {
+ // Clear this dimension and all subsequent ones
+ newDimensions.splice(index);
+ }
+ setPivotDimensions(newDimensions);
+ };
+
+ // Helper functions for multiple metrics management
+ const addMetric = () => {
+ // Check if we've reached the maximum metrics limit
+ if (selectedMetrics.length >= MAX_PIVOT_TABLE_METRICS) {
+ showErrorToast(
+ "Error",
+ `Maximum ${MAX_PIVOT_TABLE_METRICS} metrics allowed for pivot tables`,
+ );
+ return;
+ }
+
+ const newMetric: SelectedMetric = {
+ id: `${selectedAggregation}_${selectedMeasure}`,
+ measure: selectedMeasure,
+ aggregation: selectedAggregation,
+ label: `${startCase(selectedAggregation)} ${startCase(selectedMeasure)}`,
+ };
+
+ // Check if this metric combination already exists
+ const existingMetric = selectedMetrics.find((m) => m.id === newMetric.id);
+ if (existingMetric) {
+ showErrorToast("Error", "This metric combination is already selected");
+ return;
+ }
+
+ setSelectedMetrics([...selectedMetrics, newMetric]);
+ };
+
+ const removeMetric = (metricId: string) => {
+ setSelectedMetrics(selectedMetrics.filter((m) => m.id !== metricId));
+ };
+
+ const clearAllMetrics = () => {
+ setSelectedMetrics([]);
+ };
+
const traceFilterOptions = api.traces.filterOptions.useQuery(
{
projectId,
@@ -340,6 +453,62 @@ export function WidgetForm({
}
}, [selectedChartType, selectedDimension]);
+ // Reset pivot dimensions when switching away from PIVOT_TABLE
+ useEffect(() => {
+ if (selectedChartType !== "PIVOT_TABLE" && pivotDimensions.length > 0) {
+ setPivotDimensions([]);
+ }
+ }, [selectedChartType, pivotDimensions.length]);
+
+ // Reset multiple metrics when switching away from PIVOT_TABLE
+ useEffect(() => {
+ if (selectedChartType !== "PIVOT_TABLE" && selectedMetrics.length > 1) {
+ // Keep only the first metric for non-pivot charts
+ setSelectedMetrics(selectedMetrics.slice(0, 1));
+ }
+ }, [selectedChartType, selectedMetrics]);
+
+ // When chart type does not support breakdown, wipe the breakdown dimension
+ useEffect(() => {
+ if (
+ chartTypes.find((c) => c.value === selectedChartType)
+ ?.supportsBreakdown === false &&
+ selectedDimension !== "none"
+ ) {
+ setSelectedDimension("none");
+ }
+ }, [selectedChartType, selectedDimension]);
+
+ // Set aggregation based on chart type and metric, with histogram chart type taking priority
+ useEffect(() => {
+ // Histogram chart type always takes priority
+ if (
+ selectedChartType === "HISTOGRAM" &&
+ selectedAggregation !== "histogram"
+ ) {
+ setSelectedAggregation("histogram");
+ }
+ // If switching away from histogram chart type and aggregation is still histogram, reset to appropriate default
+ else if (
+ selectedChartType !== "HISTOGRAM" &&
+ selectedAggregation === "histogram"
+ ) {
+ if (selectedMeasure === "count") {
+ setSelectedAggregation("count");
+ } else {
+ setSelectedAggregation("sum"); // Default aggregation for non-count metrics
+ }
+ }
+ // Only set to "count" for count metric if not using histogram chart type
+ else if (
+ selectedMeasure === "count" &&
+ selectedChartType !== "HISTOGRAM" &&
+ selectedAggregation !== "count"
+ ) {
+ setSelectedAggregation("count");
+ }
+ }, [selectedMeasure, selectedAggregation, selectedChartType]);
+
// Set aggregation based on chart type and metric, with histogram chart type taking priority
useEffect(() => {
// Histogram chart type always takes priority
@@ -404,16 +573,32 @@ export function WidgetForm({
: new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000); // Default to last 7 days
const toTimestamp = dateRange ? dateRange.to : new Date();
+ // Determine dimensions based on chart type
+ const queryDimensions =
+ selectedChartType === "PIVOT_TABLE"
+ ? pivotDimensions.map((field) => ({ field }))
+ : selectedDimension !== "none"
+ ? [{ field: selectedDimension }]
+ : [];
+
+ // Determine metrics based on chart type
+ const queryMetrics =
+ selectedChartType === "PIVOT_TABLE"
+ ? selectedMetrics.map((metric) => ({
+ measure: metric.measure,
+ aggregation: metric.aggregation,
+ }))
+ : [
+ {
+ measure: selectedMeasure,
+ aggregation: selectedAggregation,
+ },
+ ];
+
return {
view: selectedView,
- dimensions:
- selectedDimension !== "none" ? [{ field: selectedDimension }] : [],
- metrics: [
- {
- measure: selectedMeasure,
- aggregation: selectedAggregation,
- },
- ],
+ dimensions: queryDimensions,
+ metrics: queryMetrics,
filters: [...mapLegacyUiTableFilterToView(selectedView, userFilterState)],
timeDimension: isTimeSeriesChart(
selectedChartType as DashboardWidgetChartType,
@@ -426,17 +611,26 @@ export function WidgetForm({
chartConfig:
selectedChartType === "HISTOGRAM"
? { type: selectedChartType, bins: histogramBins }
- : { type: selectedChartType },
+ : selectedChartType === "PIVOT_TABLE"
+ ? {
+ type: selectedChartType,
+ dimensions: pivotDimensions,
+ row_limit: rowLimit,
+ }
+ : { type: selectedChartType },
};
}, [
selectedView,
selectedDimension,
selectedAggregation,
selectedMeasure,
+ selectedMetrics,
userFilterState,
dateRange,
selectedChartType,
histogramBins,
+ pivotDimensions,
+ rowLimit,
]);
const queryResult = api.dashboard.executeQuery.useQuery(
@@ -457,31 +651,47 @@ export function WidgetForm({
const transformedData: DataPoint[] = useMemo(
() =>
queryResult.data?.map((item: any) => {
- // Get the dimension field (first dimension in the query)
- const dimensionField = selectedDimension;
- // Get the metric field (first metric in the query with its aggregation)
- const metricField = `${selectedAggregation}_${selectedMeasure}`;
- const metric = item[metricField];
-
- return {
- dimension:
- item[dimensionField] !== undefined
- ? (() => {
- const val = item[dimensionField];
- if (typeof val === "string") return val;
- if (val === null || val === undefined || val === "")
- return "n/a";
- if (Array.isArray(val)) return val.join(", ");
- return String(val);
- })()
- : startCase(
- metricField === "count_count" ? "Count" : metricField,
- ),
- metric: Array.isArray(metric) ? metric : Number(metric || 0),
- time_dimension: item["time_dimension"],
- };
+ if (selectedChartType === "PIVOT_TABLE") {
+ // For pivot tables, preserve all raw data fields
+ // The PivotTable component will extract the appropriate metric fields
+ return {
+ dimension:
+ pivotDimensions.length > 0 ? pivotDimensions[0] : "dimension", // Fallback for compatibility
+ metric: 0, // Placeholder - not used for pivot tables
+ time_dimension: item["time_dimension"],
+ // Include all original query fields for pivot table processing
+ ...item,
+ };
+ } else {
+ // Regular chart processing
+ const metricField = `${selectedAggregation}_${selectedMeasure}`;
+ const metric = item[metricField];
+ const dimensionField = selectedDimension;
+ return {
+ dimension:
+ item[dimensionField] !== undefined && dimensionField !== "none"
+ ? (() => {
+ const val = item[dimensionField];
+ if (typeof val === "string") return val;
+ if (val === null || val === undefined || val === "")
+ return "n/a";
+ if (Array.isArray(val)) return val.join(", ");
+ return String(val);
+ })()
+ : formatMetricName(metricField),
+ metric: Array.isArray(metric) ? metric : Number(metric || 0),
+ time_dimension: item["time_dimension"],
+ };
+ }
}) ?? [],
- [queryResult.data, selectedAggregation, selectedDimension, selectedMeasure],
+ [
+ queryResult.data,
+ selectedAggregation,
+ selectedDimension,
+ selectedMeasure,
+ selectedChartType,
+ pivotDimensions,
+ ],
);
const handleSaveWidget = () => {
@@ -490,18 +700,37 @@ export function WidgetForm({
return;
}
+ // Validate pivot table requirements
+ if (selectedChartType === "PIVOT_TABLE" && selectedMetrics.length === 0) {
+ showErrorToast(
+ "Error",
+ "At least one metric is required for pivot tables",
+ );
+ return;
+ }
+
onSave({
name: widgetName,
description: widgetDescription,
view: selectedView,
dimensions:
- selectedDimension !== "none" ? [{ field: selectedDimension }] : [],
- metrics: [
- {
- measure: selectedMeasure,
- agg: selectedAggregation,
- },
- ],
+ selectedChartType === "PIVOT_TABLE"
+ ? pivotDimensions.map((field) => ({ field }))
+ : selectedDimension !== "none"
+ ? [{ field: selectedDimension }]
+ : [],
+ metrics:
+ selectedChartType === "PIVOT_TABLE"
+ ? selectedMetrics.map((metric) => ({
+ measure: metric.measure,
+ agg: metric.aggregation,
+ }))
+ : [
+ {
+ measure: selectedMeasure,
+ agg: selectedAggregation,
+ },
+ ],
filters: mapLegacyUiTableFilterToView(selectedView, userFilterState),
chartType: selectedChartType as DashboardWidgetChartType,
chartConfig: isTimeSeriesChart(
@@ -513,10 +742,15 @@ export function WidgetForm({
type: selectedChartType as DashboardWidgetChartType,
bins: histogramBins,
}
- : {
- type: selectedChartType as DashboardWidgetChartType,
- row_limit: rowLimit,
- },
+ : selectedChartType === "PIVOT_TABLE"
+ ? {
+ type: selectedChartType as DashboardWidgetChartType,
+ row_limit: rowLimit,
+ }
+ : {
+ type: selectedChartType as DashboardWidgetChartType,
+ row_limit: rowLimit,
+ },
});
};
@@ -524,11 +758,26 @@ export function WidgetForm({
useEffect(() => {
if (autoLocked) return;
+ // For pivot tables, combine all dimensions, otherwise use regular dimension
+ const dimensionForNaming =
+ selectedChartType === "PIVOT_TABLE" && pivotDimensions.length > 0
+ ? pivotDimensions.map(startCase).join(" and ")
+ : selectedDimension;
+
+ // For pivot tables, extract actual metric names for the new formatting
+ const isPivotTable = selectedChartType === "PIVOT_TABLE";
+ const metricNames =
+ isPivotTable && selectedMetrics.length > 0
+ ? selectedMetrics.map((m) => m.id) // Use the ID which is "${aggregation}_${measure}"
+ : undefined;
+
const suggested = buildWidgetName({
- aggregation: selectedAggregation,
- measure: selectedMeasure,
- dimension: selectedDimension,
+ aggregation: isPivotTable ? "count" : selectedAggregation,
+ measure: isPivotTable ? "count" : selectedMeasure,
+ dimension: dimensionForNaming,
view: selectedView,
+ metrics: metricNames,
+ isMultiMetric: isPivotTable && selectedMetrics.length > 0,
});
setWidgetName(suggested);
@@ -536,20 +785,38 @@ export function WidgetForm({
autoLocked,
selectedAggregation,
selectedMeasure,
+ selectedMetrics,
selectedDimension,
selectedView,
+ selectedChartType,
+ pivotDimensions,
]);
// Update widget description when selection or filters change, unless locked
useEffect(() => {
if (autoLocked) return;
+ // For pivot tables, combine all dimensions, otherwise use regular dimension
+ const dimensionForDescription =
+ selectedChartType === "PIVOT_TABLE" && pivotDimensions.length > 0
+ ? pivotDimensions.map(startCase).join(" and ")
+ : selectedDimension;
+
+ // For pivot tables, extract actual metric names for the new formatting
+ const isPivotTable = selectedChartType === "PIVOT_TABLE";
+ const metricNames =
+ isPivotTable && selectedMetrics.length > 0
+ ? selectedMetrics.map((m) => m.id) // Use the ID which is "${aggregation}_${measure}"
+ : undefined;
+
const suggested = buildWidgetDescription({
- aggregation: selectedAggregation,
- measure: selectedMeasure,
- dimension: selectedDimension,
+ aggregation: isPivotTable ? "count" : selectedAggregation,
+ measure: isPivotTable ? "count" : selectedMeasure,
+ dimension: dimensionForDescription,
view: selectedView,
filters: userFilterState,
+ metrics: metricNames,
+ isMultiMetric: isPivotTable && selectedMetrics.length > 0,
});
setWidgetDescription(suggested);
@@ -557,9 +824,12 @@ export function WidgetForm({
autoLocked,
selectedAggregation,
selectedMeasure,
+ selectedMetrics,
selectedDimension,
selectedView,
userFilterState,
+ selectedChartType,
+ pivotDimensions,
]);
return (
@@ -610,60 +880,184 @@ export function WidgetForm({
{/* Metrics Selection */}
<div className="space-y-2">
- <Label htmlFor="metrics-select">Metric</Label>
- <Select
- value={selectedMeasure}
- onValueChange={(value) => setSelectedMeasure(value)}
- >
- <SelectTrigger id="metrics-select">
- <SelectValue placeholder="Select metrics" />
- </SelectTrigger>
- <SelectContent>
- {availableMetrics.map((metric) => {
- const meta =
- viewDeclarations[selectedView]?.measures?.[
- metric.value
- ];
- return (
- <WidgetPropertySelectItem
- key={metric.value}
- value={metric.value}
- label={metric.label}
- description={meta?.description}
- unit={meta?.unit}
- type={meta?.type}
- />
- );
- })}
- </SelectContent>
- </Select>
- {selectedMeasure !== "count" && (
- <div className="space-y-1">
+ <Label htmlFor="metrics-select">
+ {selectedChartType === "PIVOT_TABLE" ? "Metrics" : "Metric"}
+ </Label>
+
+ {/* For pivot tables: multiple metrics selection */}
+ {selectedChartType === "PIVOT_TABLE" ? (
+ <div className="space-y-3">
+ {/* Selected metrics display */}
+ {selectedMetrics.length > 0 && (
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium">
+ Selected Metrics ({selectedMetrics.length})
+ </span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={clearAllMetrics}
+ className="h-auto p-1 text-xs"
+ >
+ Clear All
+ </Button>
+ </div>
+ <div className="flex flex-wrap gap-1">
+ {selectedMetrics.map((metric) => (
+ <Badge
+ key={metric.id}
+ variant="secondary"
+ className="flex items-center gap-1"
+ >
+ <span className="text-xs">{metric.label}</span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => removeMetric(metric.id)}
+ className="h-auto p-0 hover:bg-transparent"
+ >
+ <X className="h-3 w-3" />
+ </Button>
+ </Badge>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Add new metric controls */}
+ <div className="space-y-2 rounded-md border p-3">
+ <span className="text-sm font-medium">Add Metric</span>
+ <div className="grid grid-cols-2 gap-2">
+ <Select
+ value={selectedMeasure}
+ onValueChange={(value) => setSelectedMeasure(value)}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Select measure" />
+ </SelectTrigger>
+ <SelectContent>
+ {availableMetrics.map((metric) => {
+ const meta =
+ viewDeclarations[selectedView]?.measures?.[
+ metric.value
+ ];
+ return (
+ <WidgetPropertySelectItem
+ key={metric.value}
+ value={metric.value}
+ label={metric.label}
+ description={meta?.description}
+ unit={meta?.unit}
+ type={meta?.type}
+ />
+ );
+ })}
+ </SelectContent>
+ </Select>
+
+ {selectedMeasure !== "count" && (
+ <Select
+ value={selectedAggregation}
+ onValueChange={(value) =>
+ setSelectedAggregation(
+ value as z.infer<typeof metricAggregations>,
+ )
+ }
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Aggregation" />
+ </SelectTrigger>
+ <SelectContent>
+ {metricAggregations.options.map((aggregation) => (
+ <SelectItem
+ key={aggregation}
+ value={aggregation}
+ >
+ {startCase(aggregation)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ </div>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={addMetric}
+ className="w-full"
+ disabled={
+ selectedMetrics.length >= MAX_PIVOT_TABLE_METRICS
+ }
+ >
+ <Plus className="mr-1 h-3 w-3" />
+ Add Metric
+ {selectedMetrics.length >= MAX_PIVOT_TABLE_METRICS &&
+ ` (Max ${MAX_PIVOT_TABLE_METRICS})`}
+ </Button>
+ </div>
+ </div>
+ ) : (
+ /* For regular charts: single metric selection */
+ <div className="space-y-2">
<Select
- value={selectedAggregation}
- disabled={selectedChartType === "HISTOGRAM"} // Disable when histogram chart type is selected
- onValueChange={(value) =>
- setSelectedAggregation(
- value as z.infer<typeof metricAggregations>,
- )
- }
+ value={selectedMeasure}
+ onValueChange={(value) => setSelectedMeasure(value)}
>
- <SelectTrigger id="aggregation-select">
- <SelectValue placeholder="Select Aggregation" />
+ <SelectTrigger id="metrics-select">
+ <SelectValue placeholder="Select metrics" />
</SelectTrigger>
<SelectContent>
- {metricAggregations.options.map((aggregation) => (
- <SelectItem key={aggregation} value={aggregation}>
- {startCase(aggregation)}
- </SelectItem>
- ))}
+ {availableMetrics.map((metric) => {
+ const meta =
+ viewDeclarations[selectedView]?.measures?.[
+ metric.value
+ ];
+ return (
+ <WidgetPropertySelectItem
+ key={metric.value}
+ value={metric.value}
+ label={metric.label}
+ description={meta?.description}
+ unit={meta?.unit}
+ type={meta?.type}
+ />
+ );
+ })}
</SelectContent>
</Select>
- {selectedChartType === "HISTOGRAM" && (
- <p className="text-xs text-muted-foreground">
- Aggregation is automatically set to
- &quot;histogram&quot; for histogram charts
- </p>
+ {selectedMeasure !== "count" && (
+ <div className="space-y-1">
+ <Select
+ value={selectedAggregation}
+ disabled={selectedChartType === "HISTOGRAM"} // Disable when histogram chart type is selected
+ onValueChange={(value) =>
+ setSelectedAggregation(
+ value as z.infer<typeof metricAggregations>,
+ )
+ }
+ >
+ <SelectTrigger id="aggregation-select">
+ <SelectValue placeholder="Select Aggregation" />
+ </SelectTrigger>
+ <SelectContent>
+ {metricAggregations.options.map((aggregation) => (
+ <SelectItem key={aggregation} value={aggregation}>
+ {startCase(aggregation)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {selectedChartType === "HISTOGRAM" && (
+ <p className="text-xs text-muted-foreground">
+ Aggregation is automatically set to
+ &quot;histogram&quot; for histogram charts
+ </p>
+ )}
+ </div>
)}
</div>
)}
@@ -681,40 +1075,119 @@ export function WidgetForm({
</div>
</div>
- {/* Dimension Selection (Breakdown) */}
+ {/* Dimension Selection - Regular charts (Breakdown) */}
{chartTypes.find((c) => c.value === selectedChartType)
- ?.supportsBreakdown && (
- <div className="space-y-2">
- <Label htmlFor="dimension-select">
- Breakdown Dimension (Optional)
- </Label>
- <Select
- value={selectedDimension}
- onValueChange={setSelectedDimension}
- >
- <SelectTrigger id="dimension-select">
- <SelectValue placeholder="Select a dimension" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="none">None</SelectItem>
- {availableDimensions.map((dimension) => {
- const meta =
- viewDeclarations[selectedView]?.dimensions?.[
- dimension.value
- ];
- return (
- <WidgetPropertySelectItem
- key={dimension.value}
- value={dimension.value}
- label={dimension.label}
- description={meta?.description}
- unit={meta?.unit}
- type={meta?.type}
- />
- );
- })}
- </SelectContent>
- </Select>
+ ?.supportsBreakdown &&
+ selectedChartType !== "PIVOT_TABLE" && (
+ <div className="space-y-2">
+ <Label htmlFor="dimension-select">
+ Breakdown Dimension (Optional)
+ </Label>
+ <Select
+ value={selectedDimension}
+ onValueChange={setSelectedDimension}
+ >
+ <SelectTrigger id="dimension-select">
+ <SelectValue placeholder="Select a dimension" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="none">None</SelectItem>
+ {availableDimensions.map((dimension) => {
+ const meta =
+ viewDeclarations[selectedView]?.dimensions?.[
+ dimension.value
+ ];
+ return (
+ <WidgetPropertySelectItem
+ key={dimension.value}
+ value={dimension.value}
+ label={dimension.label}
+ description={meta?.description}
+ unit={meta?.unit}
+ type={meta?.type}
+ />
+ );
+ })}
+ </SelectContent>
+ </Select>
+ </div>
+ )}
+
+ {/* Pivot Table Dimension Selection */}
+ {selectedChartType === "PIVOT_TABLE" && (
+ <div className="space-y-4">
+ <div>
+ <h4 className="mb-2 text-sm font-semibold">
+ Row Dimensions
+ </h4>
+ <p className="mb-3 text-xs text-muted-foreground">
+ Configure up to {MAX_PIVOT_TABLE_DIMENSIONS} dimensions
+ for pivot table rows. Each dimension creates groupings
+ with subtotals.
+ </p>
+ </div>
+
+ {Array.from(
+ { length: MAX_PIVOT_TABLE_DIMENSIONS },
+ (_, index) => {
+ const isEnabled =
+ index === 0 || pivotDimensions[index - 1]; // Enable if first or previous is selected
+ const selectedDimensions = pivotDimensions.slice(
+ 0,
+ index,
+ ); // Exclude current and later dimensions
+ const currentValue = pivotDimensions[index] || "";
+
+ return (
+ <div key={index} className="space-y-2">
+ <Label htmlFor={`pivot-dimension-${index}`}>
+ Dimension {index + 1} (Optional)
+ </Label>
+ <Select
+ value={currentValue}
+ onValueChange={(value) =>
+ updatePivotDimension(index, value)
+ }
+ disabled={!isEnabled}
+ >
+ <SelectTrigger id={`pivot-dimension-${index}`}>
+ <SelectValue
+ placeholder={
+ isEnabled
+ ? "Select a dimension"
+ : "Select previous dimension first"
+ }
+ />
+ </SelectTrigger>
+ <SelectContent>
+ {index >= 0 && (
+ <SelectItem value="none">None</SelectItem>
+ )}
+ {availableDimensions
+ .filter(
+ (d) => !selectedDimensions.includes(d.value),
+ )
+ .map((dimension) => {
+ const meta =
+ viewDeclarations[selectedView]
+ ?.dimensions?.[dimension.value];
+ return (
+ <WidgetPropertySelectItem
+ key={dimension.value}
+ value={dimension.value}
+ label={dimension.label}
+ description={meta?.description}
+ unit={meta?.unit}
+ type={meta?.type}
+ />
+ );
+ })}
+ </SelectContent>
+ </Select>
+ </div>
+ );
+ },
+ )}
</div>
)}
</div>
@@ -879,6 +1352,24 @@ export function WidgetForm({
chartType={selectedChartType as DashboardWidgetChartType}
data={transformedData}
rowLimit={rowLimit}
+ chartConfig={
+ selectedChartType === "PIVOT_TABLE"
+ ? {
+ type: selectedChartType as DashboardWidgetChartType,
+ dimensions: pivotDimensions,
+ row_limit: rowLimit,
+ metrics: selectedMetrics.map((metric) => metric.id), // Pass metric field names
+ }
+ : selectedChartType === "HISTOGRAM"
+ ? {
+ type: selectedChartType as DashboardWidgetChartType,
+ bins: histogramBins,
+ }
+ : {
+ type: selectedChartType as DashboardWidgetChartType,
+ row_limit: rowLimit,
+ }
+ }
/>
) : (
<CardContent>
diff --git a/web/src/features/widgets/index.ts b/web/src/features/widgets/index.ts
index d138e81b28..8fd9b709eb 100644
--- a/web/src/features/widgets/index.ts
+++ b/web/src/features/widgets/index.ts
@@ -6,3 +6,6 @@ export { Chart } from "./chart-library/Chart";
export { WidgetForm } from "./components/WidgetForm";
export { DashboardWidgetTable, DeleteWidget } from "./components/WidgetTable";
export { DashboardWidget } from "./components/DashboardWidget";
+
+// Export types and utilities
+export { type WidgetChartConfig } from "./utils";
diff --git a/web/src/features/widgets/utils.ts b/web/src/features/widgets/utils.ts
index 8b55459436..a9fd622271 100644
--- a/web/src/features/widgets/utils.ts
+++ b/web/src/features/widgets/utils.ts
@@ -1,26 +1,74 @@
import { startCase } from "lodash";
import { type FilterState } from "@langfuse/shared";
+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";
+
+// Shared widget chart configuration types
+export type WidgetChartConfig = {
+ type: DashboardWidgetChartType;
+ row_limit?: number;
+ bins?: number;
+};
+
+/**
+ * Formats a metric name for display, handling special cases like count_count -> Count
+ */
+export function formatMetricName(metricName: string): string {
+ // Handle the count_count -> Count conversion
+ const cleanedName = metricName === "count_count" ? "Count" : metricName;
+ return startCase(cleanedName);
+}
+
+/**
+ * Formats multiple metric names for display, showing first 3 and "+ X more" if needed
+ */
+export function formatMultipleMetricNames(metricNames: string[]): string {
+ if (metricNames.length === 0) return "No Metrics";
+ if (metricNames.length === 1) return formatMetricName(metricNames[0]);
+
+ const formattedNames = metricNames.map(formatMetricName);
+
+ if (metricNames.length <= 3) {
+ return formattedNames.join(", ");
+ }
+
+ const firstThree = formattedNames.slice(0, 3).join(", ");
+ const remaining = metricNames.length - 3;
+ return `${firstThree} + ${remaining} more`;
+}
export function buildWidgetName({
aggregation,
measure,
dimension,
view,
+ metrics,
+ isMultiMetric = false,
}: {
aggregation: string;
measure: string;
dimension: string;
view: string;
+ metrics?: string[];
+ isMultiMetric?: boolean;
}) {
- const meas = startCase(measure);
let base: string;
- if (measure.toLowerCase() === "count") {
- // For count measures, ignore aggregation and only show the measure
- base = meas;
+
+ if (isMultiMetric && metrics && metrics.length > 0) {
+ // Handle multi-metric scenarios (like pivot tables)
+ const metricDisplay = formatMultipleMetricNames(metrics);
+ base = metricDisplay;
} else {
- const agg = startCase(aggregation.toLowerCase());
- base = `${agg} ${meas}`;
+ // Handle single metric scenarios (existing logic)
+ const meas = formatMetricName(measure);
+ if (measure.toLowerCase() === "count") {
+ // For count measures, ignore aggregation and only show the measure
+ base = meas;
+ } else {
+ const agg = startCase(aggregation.toLowerCase());
+ base = `${agg} ${meas}`;
+ }
}
+
if (dimension && dimension !== "none") {
base += ` by ${startCase(dimension)}`;
}
@@ -34,24 +82,34 @@ export function buildWidgetDescription({
dimension,
view,
filters,
+ metrics,
+ isMultiMetric = false,
}: {
aggregation: string;
measure: string;
dimension: string;
view: string;
filters: FilterState;
+ metrics?: string[];
+ isMultiMetric?: boolean;
}) {
- // Base sentence: "Shows the <agg> <measure> of <view> ..."
- const measLabel = startCase(measure.toLowerCase());
const viewLabel = startCase(view);
-
let sentence: string;
- if (measure.toLowerCase() === "count") {
- sentence = `Shows the count of ${viewLabel}`;
+ if (isMultiMetric && metrics && metrics.length > 0) {
+ // Handle multi-metric scenarios
+ const metricDisplay = formatMultipleMetricNames(metrics);
+ sentence = `Shows ${metricDisplay.toLowerCase()} of ${viewLabel}`;
} else {
- const aggLabel = startCase(aggregation.toLowerCase());
- sentence = `Shows the ${aggLabel.toLowerCase()} ${measLabel.toLowerCase()} of ${viewLabel}`;
+ // Handle single metric scenarios (existing logic)
+ const measLabel = formatMetricName(measure);
+
+ if (measure.toLowerCase() === "count") {
+ sentence = `Shows the count of ${viewLabel}`;
+ } else {
+ const aggLabel = startCase(aggregation.toLowerCase());
+ sentence = `Shows the ${aggLabel.toLowerCase()} ${measLabel.toLowerCase()} of ${viewLabel}`;
+ }
}
// Dimension clause
diff --git a/web/src/features/widgets/utils/pivot-table-utils.ts b/web/src/features/widgets/utils/pivot-table-utils.ts
new file mode 100644
index 0000000000..2b631e68ef
--- /dev/null
+++ b/web/src/features/widgets/utils/pivot-table-utils.ts
@@ -0,0 +1,610 @@
+/**
+ * @fileoverview Utility functions and type definitions for Pivot Table widget functionality
+ *
+ * This module provides core utilities for transforming flat query results into nested
+ * pivot table structures with configurable dimensions, subtotals, and grand totals.
+ *
+ * Key Features:
+ * - Configurable maximum dimensions (currently limited to 2)
+ * - Support for 0-N dimensions with proper nesting and indentation
+ * - Automatic subtotal generation for first dimension level
+ * - Grand total calculation across all metrics
+ * - Row limiting to prevent performance issues
+ *
+ * Usage:
+ * - Used by PivotTable React component for data transformation
+ * - Integrated with QueryBuilder for SQL generation
+ * - Supports future expansion beyond current 2-dimension limit
+ */
+import { isNotNullOrUndefined } from "@/src/utils/types";
+
+/**
+ * Default dimension limit for pivot table data rows
+ * This prevents performance issues and maintains readability
+ */
+export const MAX_PIVOT_TABLE_DIMENSIONS = 2;
+
+/**
+ * Default row limit for pivot table data rows (excluding total rows)
+ * This prevents performance issues with large datasets while maintaining
+ * useful data visibility.
+ */
+export const DEFAULT_ROW_LIMIT = 20;
+
+/**
+ * Maximum number of metrics allowed in a pivot table
+ * This prevents performance issues and maintains readability
+ */
+export const MAX_PIVOT_TABLE_METRICS = 10;
+
+/**
+ * Represents a single row in the processed pivot table structure
+ * Supports different row types for data, subtotals, and grand totals
+ * with appropriate styling and indentation levels.
+ */
+export interface PivotTableRow {
+ /** Unique identifier for this row */
+ id: string;
+
+ /** Type of row determines styling and behavior */
+ type: "data" | "subtotal" | "total";
+
+ /** Indentation level for nested dimensions (0-based) */
+ level: number;
+
+ /** Display label for the row (dimension value or "Total"/"Subtotal") */
+ label: string;
+
+ /** Metric values for this row, keyed by metric name */
+ values: Record<string, number | string>;
+
+ /** Whether this row represents a subtotal */
+ isSubtotal?: boolean;
+
+ /** Whether this row represents the grand total */
+ isTotal?: boolean;
+
+ /** Original dimension values for this row (for data rows only) */
+ dimensionValues?: Record<string, string>;
+}
+
+/**
+ * Configuration for pivot table data transformation
+ * Defines the structure and limits for the resulting table
+ */
+export interface PivotTableConfig {
+ /** Array of dimension field names (max length = MAX_PIVOT_TABLE_DIMENSIONS) */
+ dimensions: string[];
+
+ /** Array of metric field names to display as columns */
+ metrics: string[];
+
+ /** Maximum number of data rows to display (before totals) */
+ rowLimit?: number;
+}
+
+/**
+ * Raw database row structure from query results
+ * Contains dimension values and metric calculations
+ */
+export interface DatabaseRow {
+ /** Dimension field values */
+ [dimensionField: string]: string | number | null;
+}
+
+/**
+ * Validates that the provided configuration is valid for pivot table generation
+ *
+ * @param config - Pivot table configuration to validate
+ * @throws Error if configuration is invalid
+ */
+export function validatePivotTableConfig(config: PivotTableConfig): void {
+ if (config.dimensions.length > MAX_PIVOT_TABLE_DIMENSIONS) {
+ throw new Error(
+ `Cannot create pivot table with ${config.dimensions.length} dimensions. ` +
+ `Maximum supported dimensions: ${MAX_PIVOT_TABLE_DIMENSIONS}`,
+ );
+ }
+
+ if (config.metrics.length === 0) {
+ throw new Error("At least one metric is required for pivot table");
+ }
+
+ if (config.metrics.length > MAX_PIVOT_TABLE_METRICS) {
+ throw new Error(
+ `Cannot create pivot table with ${config.metrics.length} metrics. ` +
+ `Maximum supported metrics: ${MAX_PIVOT_TABLE_METRICS}`,
+ );
+ }
+
+ if (config.rowLimit !== undefined && config.rowLimit <= 0) {
+ throw new Error("Row limit must be a positive number");
+ }
+}
+
+/**
+ * Generates a unique row ID for pivot table rows
+ * Uses dimension values and row type to create stable identifiers
+ *
+ * @param dimensionValues - Values for each dimension field
+ * @param type - Type of row (data, subtotal, total)
+ * @param level - Indentation level for the row
+ * @returns Unique string identifier for the row
+ */
+export function generateRowId(
+ dimensionValues: Record<string, string>,
+ type: PivotTableRow["type"],
+ level: number,
+): string {
+ const valueKey = Object.entries(dimensionValues)
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([key, value]) => `${key}:${value}`)
+ .join("|");
+
+ return `${type}-${level}-${valueKey}`;
+}
+
+/**
+ * Creates an empty metric values object with all metrics set to 0
+ * Used as a fallback for rows with missing data
+ *
+ * @param metrics - Array of metric field names
+ * @returns Object with all metrics initialized to 0
+ */
+export function createEmptyMetricValues(
+ metrics: string[],
+): Record<string, number> {
+ return metrics.reduce(
+ (acc, metric) => {
+ acc[metric] = 0;
+ return acc;
+ },
+ {} as Record<string, number>,
+ );
+}
+
+/**
+ * Recursively processes dimensions to create nested pivot table structure
+ * This function handles N dimensions dynamically instead of hardcoded cases
+ *
+ * @param data - Array of database rows to process at this level
+ * @param remainingDimensions - Array of dimension names still to be processed
+ * @param metrics - Array of metric field names
+ * @param currentLevel - Current indentation level (0-based)
+ * @param dimensionPath - Array of dimension values from parent levels for labeling
+ * @returns Array of pivot table rows for this level and all nested levels
+ */
+function processLevelRecursively(
+ data: DatabaseRow[],
+ remainingDimensions: string[],
+ metrics: string[],
+ totalDimensions: number,
+ dimensionPath: string[],
+): PivotTableRow[] {
+ const rows: PivotTableRow[] = [];
+ const currentDimensionIndex = totalDimensions - remainingDimensions.length;
+
+ // Base case: no more dimensions to process, create data rows
+ if (remainingDimensions.length === 0) {
+ // Data rows should be at level (totalDimensions - 1) for proper indentation
+ const dataLevel = Math.max(0, totalDimensions - 1);
+
+ // Create data rows for the final level
+ const dataRows = data.map((row, index) => {
+ const dimensionValues = extractDimensionValues(row, []);
+ const metricValues = extractMetricValues(row, metrics);
+
+ // Create label from dimension path (all parent dimension values)
+ const label =
+ dimensionPath.length > 0 ? dimensionPath.join(" - ") : "Data";
+
+ return {
+ id: `data-${dataLevel}-${dimensionPath.join("-")}-${index}`,
+ type: "data" as const,
+ level: dataLevel,
+ label,
+ values: metricValues,
+ dimensionValues,
+ };
+ });
+
+ return dataRows;
+ }
+
+ // Recursive case: process current dimension and recurse on remaining dimensions
+ const [currentDimension, ...nextDimensions] = remainingDimensions;
+ const groups = groupDataByDimension(data, currentDimension!);
+ const sortedGroups = Object.entries(groups).sort(([a], [b]) =>
+ a.localeCompare(b),
+ );
+
+ for (const [dimensionValue, groupData] of sortedGroups) {
+ const newDimensionPath = [...dimensionPath, dimensionValue];
+
+ // Add subtotal row for this dimension group BEFORE processing child rows
+ // Only if there are more dimensions to process (not the deepest level)
+ if (nextDimensions.length > 0 && groupData.length > 0) {
+ const subtotalValues = calculateSubtotals(groupData, metrics);
+ const subtotalRow = createSubtotalRow(
+ dimensionValue,
+ subtotalValues,
+ currentDimensionIndex, // Subtotals at current dimension level
+ );
+ rows.push(subtotalRow);
+ }
+
+ // Recursively process remaining dimensions for this group
+ const childRows = processLevelRecursively(
+ groupData,
+ nextDimensions,
+ metrics,
+ totalDimensions,
+ newDimensionPath,
+ );
+
+ rows.push(...childRows);
+ }
+
+ return rows;
+}
+
+/**
+ * Transforms flat query results into nested pivot table structure with totals and subtotals
+ * Uses a recursive algorithm to handle N dimensions dynamically instead of hardcoded cases
+ *
+ * Features:
+ * - Supports any number of dimensions up to MAX_PIVOT_TABLE_DIMENSIONS
+ * - Creates subtotals at each dimension level except the deepest
+ * - Proper indentation and nesting for hierarchical data
+ * - Grand total calculation across all data
+ * - Row limiting applied before processing for performance
+ *
+ * Algorithm:
+ * 1. Recursively groups data by each dimension in order
+ * 2. At each level, processes remaining dimensions for nested structure
+ * 3. Adds subtotals for non-leaf dimension groups
+ * 4. Creates data rows at the deepest level with full dimension path
+ * 5. Appends grand total row at the end
+ *
+ * @param data - Array of raw database rows from query
+ * @param config - Configuration for pivot table generation
+ * @returns Array of processed rows ready for table rendering
+ *
+ * @example
+ * ```typescript
+ * const data = [
+ * { userId: "user1", country: "US", count: 10, avg_score: 85 },
+ * { userId: "user2", country: "US", count: 5, avg_score: 90 },
+ * { userId: "user3", country: "CA", count: 8, avg_score: 78 }
+ * ];
+ *
+ * const config = {
+ * dimensions: ["country", "userId"],
+ * metrics: ["count", "avg_score"],
+ * rowLimit: 20
+ * };
+ *
+ * const result = transformToPivotTable(data, config);
+ * // Returns:
+ * // 1. Data rows for each user grouped by country
+ * // 2. Subtotal rows for each country
+ * // 3. Grand total row for all data
+ * ```
+ */
+export function transformToPivotTable(
+ data: DatabaseRow[],
+ config: PivotTableConfig,
+): PivotTableRow[] {
+ // Validate configuration
+ validatePivotTableConfig(config);
+
+ const { dimensions, metrics, rowLimit = DEFAULT_ROW_LIMIT } = config;
+
+ // Handle empty data
+ if (data.length === 0) {
+ return [createGrandTotalRow(metrics, createEmptyMetricValues(metrics))];
+ }
+
+ // Handle zero dimensions - just return grand total
+ if (dimensions.length === 0) {
+ const grandTotalValues = calculateGrandTotals(data, metrics);
+ return [createGrandTotalRow(metrics, grandTotalValues)];
+ }
+
+ // Apply row limit to data before processing
+ const limitedData = data.slice(0, rowLimit);
+
+ // Add grand total row at the beginning
+ const grandTotalValues = calculateGrandTotals(limitedData, metrics);
+ const grandTotalRow = createGrandTotalRow(metrics, grandTotalValues);
+
+ // Process dimensions recursively
+ const pivotRows = processLevelRecursively(
+ limitedData,
+ dimensions,
+ metrics,
+ dimensions.length, // total number of dimensions
+ [], // dimension path for labeling
+ );
+
+ return [grandTotalRow, ...pivotRows];
+}
+
+/**
+ * Utility function to get dimension values from a database row
+ * Extracts only the specified dimension fields from the row data
+ *
+ * @param row - Database row containing all field values
+ * @param dimensions - Array of dimension field names to extract
+ * @returns Object containing only dimension field values
+ */
+export function extractDimensionValues(
+ row: DatabaseRow,
+ dimensions: string[],
+): Record<string, string> {
+ return dimensions.reduce(
+ (acc, dimension) => {
+ const value = row[dimension];
+ acc[dimension] = value?.toString() ?? "";
+ return acc;
+ },
+ {} as Record<string, string>,
+ );
+}
+
+/**
+ * Utility function to get metric values from a database row
+ * Extracts only the specified metric fields from the row data
+ *
+ * @param row - Database row containing all field values
+ * @param metrics - Array of metric field names to extract
+ * @returns Object containing only metric field values
+ */
+export function extractMetricValues(
+ row: DatabaseRow,
+ metrics: string[],
+): Record<string, number> {
+ return metrics.reduce(
+ (acc, metric) => {
+ const value = row[metric];
+ if (typeof value === "number") {
+ acc[metric] = value;
+ } else if (typeof value === "string") {
+ const parsedValue = parseFloat(value);
+ acc[metric] = isNaN(parsedValue) ? 0 : parsedValue;
+ } else {
+ acc[metric] = 0;
+ }
+ return acc;
+ },
+ {} as Record<string, number>,
+ );
+}
+
+/**
+ * Type guard to check if a row is a data row (not subtotal or total)
+ *
+ * @param row - Pivot table row to check
+ * @returns True if the row contains actual data, false for summary rows
+ */
+export function isDataRow(row: PivotTableRow): boolean {
+ return row.type === "data";
+}
+
+/**
+ * Type guard to check if a row is a subtotal row
+ *
+ * @param row - Pivot table row to check
+ * @returns True if the row is a subtotal, false otherwise
+ */
+export function isSubtotalRow(row: PivotTableRow): boolean {
+ return row.type === "subtotal" || row.isSubtotal === true;
+}
+
+/**
+ * Type guard to check if a row is the grand total row
+ *
+ * @param row - Pivot table row to check
+ * @returns True if the row is the grand total, false otherwise
+ */
+export function isTotalRow(row: PivotTableRow): boolean {
+ return row.type === "total" || row.isTotal === true;
+}
+
+/**
+ * Groups data by a single dimension field
+ * Used for creating single-level groupings in pivot table
+ *
+ * @param data - Array of database rows to group
+ * @param dimensionField - Field name to group by
+ * @returns Object with dimension values as keys and arrays of rows as values
+ */
+export function groupDataByDimension(
+ data: DatabaseRow[],
+ dimensionField: string,
+): Record<string, DatabaseRow[]> {
+ return data.reduce(
+ (acc, row) => {
+ const dimensionValue =
+ (row[dimensionField]?.toString() ?? "").trim() || "n/a";
+ if (!acc[dimensionValue]) {
+ acc[dimensionValue] = [];
+ }
+ acc[dimensionValue]!.push(row);
+ return acc;
+ },
+ {} as Record<string, DatabaseRow[]>,
+ );
+}
+
+/**
+ * Detects the aggregation type from a metric field name
+ * Parses field names like "count_count", "avg_latency", "sum_tokens", "p95_duration"
+ *
+ * @param metricName - The metric field name to analyze
+ * @returns The aggregation type (count, sum, avg, min, max, p95, etc.)
+ */
+function detectAggregationType(metricName: string): string {
+ // Extract the aggregation prefix from field names like "count_count", "avg_latency"
+ const parts = metricName.split("_");
+ if (parts.length >= 2) {
+ const prefix = parts[0]?.toLowerCase();
+ // Map common aggregation prefixes
+ switch (prefix) {
+ case "count":
+ return "count";
+ case "sum":
+ return "sum";
+ case "avg":
+ case "average":
+ return "avg";
+ case "min":
+ return "min";
+ case "max":
+ return "max";
+ case "p95":
+ case "p99":
+ case "p50":
+ return "percentile";
+ default:
+ // Default to sum for unknown aggregations
+ return "sum";
+ }
+ }
+
+ // Default to sum if we can't determine the type
+ return "sum";
+}
+
+/**
+ * Applies the correct aggregation function based on the aggregation type
+ *
+ * @param values - Array of numeric values to aggregate
+ * @param aggregationType - The type of aggregation to perform
+ * @returns The aggregated result
+ */
+function applyAggregation(values: number[], aggregationType: string): number {
+ if (values.length === 0) return 0;
+
+ switch (aggregationType) {
+ case "count":
+ case "sum":
+ return values.reduce((sum, val) => sum + val, 0);
+
+ case "avg":
+ return values.reduce((sum, val) => sum + val, 0) / values.length;
+
+ case "min":
+ return Math.min(...values);
+
+ case "max":
+ return Math.max(...values);
+
+ case "percentile":
+ // For percentiles in subtotals/totals, we'll use the average of the percentile values
+ // This is a reasonable approximation since we can't recalculate the true percentile
+ return values.reduce((sum, val) => sum + val, 0) / values.length;
+
+ default:
+ // Default to sum
+ return values.reduce((sum, val) => sum + val, 0);
+ }
+}
+
+/**
+ * Calculates subtotals for a group of data rows
+ * Aggregates metric values across all rows in the group using the correct aggregation function
+ *
+ * @param data - Array of database rows to calculate subtotals for
+ * @param metrics - Array of metric field names to aggregate
+ * @returns Object with metric names as keys and calculated totals as values
+ */
+export function calculateSubtotals(
+ data: DatabaseRow[],
+ metrics: string[],
+): Record<string, number> {
+ const subtotals: Record<string, number> = {};
+
+ for (const metric of metrics) {
+ // Extract all values for this metric using the utility function
+ const values = data
+ .map((row) => extractMetricValues(row, [metric])[metric])
+ .filter(isNotNullOrUndefined);
+
+ // Detect aggregation type and apply correct function
+ const aggregationType = detectAggregationType(metric);
+ const result = applyAggregation(values, aggregationType);
+
+ // Round to 10 decimal places to avoid floating-point precision issues
+ subtotals[metric] = Math.round(result * 1e10) / 1e10;
+ }
+
+ return subtotals;
+}
+
+/**
+ * Calculates grand totals across all data rows
+ * Aggregates metric values across the entire dataset
+ *
+ * @param data - Array of database rows to calculate grand totals for
+ * @param metrics - Array of metric field names to aggregate
+ * @returns Object with metric names as keys and calculated grand totals as values
+ */
+export function calculateGrandTotals(
+ data: DatabaseRow[],
+ metrics: string[],
+): Record<string, number> {
+ return calculateSubtotals(data, metrics);
+}
+
+/**
+ * Creates a subtotal row for a specific dimension group
+ * Generates subtotal row with appropriate styling and values
+ *
+ * @param dimensionValue - The dimension value this subtotal represents
+ * @param subtotalValues - Calculated subtotal values for metrics
+ * @param level - Indentation level for the row
+ * @returns Formatted pivot table subtotal row
+ */
+export function createSubtotalRow(
+ dimensionValue: string,
+ subtotalValues: Record<string, number>,
+ level: number,
+): PivotTableRow {
+ const dimensionValues = { subtotal: dimensionValue };
+
+ return {
+ id: generateRowId(dimensionValues, "subtotal", level),
+ type: "subtotal",
+ level,
+ label: `${dimensionValue} (Subtotal)`,
+ values: subtotalValues,
+ isSubtotal: true,
+ dimensionValues,
+ };
+}
+
+/**
+ * Creates the grand total row for the pivot table
+ * Generates final total row with all metric grand totals
+ *
+ * @param metrics - Array of metric field names
+ * @param grandTotalValues - Calculated grand total values for metrics
+ * @returns Formatted pivot table grand total row
+ */
+export function createGrandTotalRow(
+ metrics: string[],
+ grandTotalValues: Record<string, number>,
+): PivotTableRow {
+ const dimensionValues = { total: "grand" };
+
+ return {
+ id: generateRowId(dimensionValues, "total", 0),
+ type: "total",
+ level: 0,
+ label: "Total",
+ values: grandTotalValues,
+ isTotal: true,
+ dimensionValues,
+ };
+}
diff --git a/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx b/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx
index 5e130ac785..37a4df3226 100644
--- a/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx
+++ b/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx
@@ -7,6 +7,7 @@ import { showSuccessToast } from "@/src/features/notifications/showSuccessToast"
import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";
import { type views, type metricAggregations } from "@/src/features/query";
import { type z } from "zod/v4";
+import { type WidgetChartConfig } from "@/src/features/widgets/utils";
export default function EditWidget() {
const router = useRouter();
@@ -58,7 +59,7 @@ export default function EditWidget() {
metrics: { measure: string; agg: string }[];
filters: any[];
chartType: DashboardWidgetChartType;
- chartConfig: { type: DashboardWidgetChartType; row_limit?: number; bins?: number };
+ chartConfig: WidgetChartConfig;
}) => {
if (!widgetId) return;
@@ -98,6 +99,10 @@ export default function EditWidget() {
name: widgetData.name,
description: widgetData.description,
view: widgetData.view as z.infer<typeof views>,
+ // Pass complete arrays for editing mode
+ metrics: widgetData.metrics,
+ dimensions: widgetData.dimensions,
+ // Keep single values for backward compatibility and fallbacks
dimension: widgetData.dimensions.slice().shift()?.field ?? "none",
measure: widgetData.metrics.slice().shift()?.measure ?? "count",
aggregation:
diff --git a/web/src/pages/project/[projectId]/widgets/new.tsx b/web/src/pages/project/[projectId]/widgets/new.tsx
index 0f871f9e26..4dabc4e808 100644
--- a/web/src/pages/project/[projectId]/widgets/new.tsx
+++ b/web/src/pages/project/[projectId]/widgets/new.tsx
@@ -1,7 +1,7 @@
import { useRouter } from "next/router";
import Page from "@/src/components/layouts/page";
import { api } from "@/src/utils/api";
-import { WidgetForm } from "@/src/features/widgets";
+import { type WidgetChartConfig, WidgetForm } from "@/src/features/widgets";
import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
import { showErrorToast } from "@/src/features/notifications/showErrorToast";
import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";
@@ -49,7 +49,7 @@ export default function NewWidget() {
metrics: { measure: string; agg: string }[];
filters: any[];
chartType: DashboardWidgetChartType;
- chartConfig: { type: DashboardWidgetChartType; row_limit?: number; bins?: number };
+ chartConfig: WidgetChartConfig;
}) => {
if (!widgetData.name.trim()) {
showErrorToast("Error", "Widget name is required");