feat: Add extensible multi-pipeline integration system

This commit implements a plugin-like pipeline architecture with:

Pipeline Core Package (packages/pipeline-core/):
- BasePipeline abstract class all pipelines implement
- PipelineRegistry for database-backed discovery/management
- PipelineRunner for execution with status tracking
- DashboardConfig contracts for dynamic widget definitions

Database Migration (006_pipeline_registry.sql):
- pipeline.registry table for registered pipelines
- pipeline.executions table for execution history
- Views for execution stats and monitoring

ReviewIQ Pipeline Refactor:
- Implements BasePipeline interface
- Adds get_dashboard_config() with widget definitions
- Adds get_widget_data() methods for all dashboard widgets
- Maintains backward compatibility with Pipeline alias

Generic Pipeline API (api/routes/pipelines.py):
- GET /api/pipelines - List all registered pipelines
- GET /api/pipelines/{id} - Pipeline details
- POST /api/pipelines/{id}/execute - Execute pipeline
- GET /api/pipelines/{id}/dashboard - Dashboard config
- GET /api/pipelines/{id}/widgets/{w} - Widget data
- GET /api/pipelines/{id}/executions - Execution history

Frontend Dynamic Dashboard System:
- DynamicDashboard component renders from config
- WidgetRegistry maps types to components
- Widget components: StatCard, LineChart, BarChart,
  PieChart, DataTable, Heatmap
- Pipeline API client library

Frontend Pipeline Pages:
- /pipelines - List all registered pipelines
- /pipelines/[id] - Dynamic dashboard for pipeline
- /pipelines/[id]/executions - Execution history
- Pipelines nav item in Sidebar

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Alejandro Gutiérrez
2026-01-24 19:05:38 +00:00
parent d64f06ba9e
commit 824634aa76
30 changed files with 5697 additions and 95 deletions

View File

@@ -50,6 +50,16 @@ export default function Sidebar() {
label: 'Analytics',
matchPaths: ['/analytics'],
},
{
href: '/pipelines',
icon: (
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z" />
</svg>
),
label: 'Pipelines',
matchPaths: ['/pipelines'],
},
{
href: '/dashboard/scrapers',
icon: (

View File

@@ -0,0 +1,148 @@
'use client';
import { useState, useEffect, useCallback } from 'react';
import { ChevronDown, ChevronRight } from 'lucide-react';
import type { DashboardSection as DashboardSectionType, WidgetData } from '@/lib/pipeline-types';
import { getWidgetData } from '@/lib/pipeline-api';
import { renderWidget } from './WidgetRegistry';
interface DashboardSectionProps {
section: DashboardSectionType;
pipelineId: string;
businessId?: string;
timeRange?: string;
}
/**
* Renders a dashboard section with its widgets.
*/
export function DashboardSection({
section,
pipelineId,
businessId,
timeRange = '30d',
}: DashboardSectionProps) {
const [collapsed, setCollapsed] = useState(section.collapsed ?? false);
const [widgetData, setWidgetData] = useState<Record<string, WidgetData | null>>({});
const [widgetLoading, setWidgetLoading] = useState<Record<string, boolean>>({});
const [widgetErrors, setWidgetErrors] = useState<Record<string, string | undefined>>({});
const [tablePagination, setTablePagination] = useState<Record<string, number>>({});
// Fetch data for a single widget
const fetchWidgetData = useCallback(
async (widgetId: string, page?: number) => {
setWidgetLoading((prev) => ({ ...prev, [widgetId]: true }));
setWidgetErrors((prev) => ({ ...prev, [widgetId]: undefined }));
try {
const data = await getWidgetData(pipelineId, widgetId, {
business_id: businessId,
time_range: timeRange,
page: page || tablePagination[widgetId] || 1,
});
setWidgetData((prev) => ({ ...prev, [widgetId]: data }));
} catch (error) {
setWidgetErrors((prev) => ({
...prev,
[widgetId]: error instanceof Error ? error.message : 'Failed to load',
}));
} finally {
setWidgetLoading((prev) => ({ ...prev, [widgetId]: false }));
}
},
[pipelineId, businessId, timeRange, tablePagination]
);
// Fetch all widget data on mount and when params change
useEffect(() => {
if (!collapsed) {
section.widgets.forEach((widget) => {
fetchWidgetData(widget.id);
});
}
}, [section.widgets, collapsed, pipelineId, businessId, timeRange]);
// Handle page change for tables
const handlePageChange = (widgetId: string, page: number) => {
setTablePagination((prev) => ({ ...prev, [widgetId]: page }));
fetchWidgetData(widgetId, page);
};
// Calculate grid layout
// Using a 12-column grid
const getGridClass = (widget: typeof section.widgets[0]) => {
const { grid } = widget;
// Map grid units to Tailwind classes
const colSpanClasses: Record<number, string> = {
1: 'col-span-1',
2: 'col-span-2',
3: 'col-span-3',
4: 'col-span-4',
5: 'col-span-5',
6: 'col-span-6',
7: 'col-span-7',
8: 'col-span-8',
9: 'col-span-9',
10: 'col-span-10',
11: 'col-span-11',
12: 'col-span-12',
};
const rowSpanClasses: Record<number, string> = {
1: 'row-span-1',
2: 'row-span-2',
3: 'row-span-3',
4: 'row-span-4',
};
return `${colSpanClasses[grid.w] || 'col-span-4'} ${rowSpanClasses[grid.h] || 'row-span-1'}`;
};
return (
<div className="mb-6">
{/* Section Header */}
<button
onClick={() => setCollapsed(!collapsed)}
className="flex items-center w-full text-left mb-4 group"
>
{collapsed ? (
<ChevronRight className="w-5 h-5 text-gray-500 mr-2" />
) : (
<ChevronDown className="w-5 h-5 text-gray-500 mr-2" />
)}
<div>
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100 group-hover:text-blue-600">
{section.title}
</h2>
{section.description && (
<p className="text-sm text-gray-500">{section.description}</p>
)}
</div>
</button>
{/* Widgets Grid */}
{!collapsed && (
<div
className="grid grid-cols-12 gap-4"
style={{
gridAutoRows: '140px', // Base row height
}}
>
{section.widgets.map((widget) => (
<div key={widget.id} className={getGridClass(widget)}>
{renderWidget(
widget,
widgetData[widget.id] || null,
widgetLoading[widget.id] ?? true,
widgetErrors[widget.id],
() => fetchWidgetData(widget.id),
widget.type === 'table'
? (page) => handlePageChange(widget.id, page)
: undefined,
tablePagination[widget.id] || 1
)}
</div>
))}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,106 @@
'use client';
import { useState } from 'react';
import { RefreshCw, Calendar, Building2 } from 'lucide-react';
import type { DashboardConfig } from '@/lib/pipeline-types';
import { DashboardSection } from './DashboardSection';
interface DynamicDashboardProps {
pipelineId: string;
config: DashboardConfig;
businessId?: string;
}
// Time range options
const TIME_RANGES = [
{ value: '7d', label: 'Last 7 days' },
{ value: '14d', label: 'Last 14 days' },
{ value: '30d', label: 'Last 30 days' },
{ value: '90d', label: 'Last 90 days' },
];
/**
* Dynamic dashboard that renders from a DashboardConfig.
*
* This component:
* - Renders sections based on the config
* - Provides time range and business filters
* - Handles global refresh
*/
export function DynamicDashboard({
pipelineId,
config,
businessId: initialBusinessId,
}: DynamicDashboardProps) {
const [timeRange, setTimeRange] = useState(config.default_time_range || '30d');
const [businessId, setBusinessId] = useState(initialBusinessId);
const [refreshKey, setRefreshKey] = useState(0);
// Force refresh all widgets
const handleRefresh = () => {
setRefreshKey((prev) => prev + 1);
};
return (
<div className="space-y-6">
{/* Dashboard Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">
{config.title}
</h1>
{config.description && (
<p className="text-gray-500 mt-1">{config.description}</p>
)}
</div>
{/* Controls */}
<div className="flex items-center space-x-3">
{/* Business Filter (placeholder) */}
{businessId && (
<div className="flex items-center text-sm text-gray-600 dark:text-gray-400 bg-gray-100 dark:bg-gray-800 px-3 py-2 rounded-md">
<Building2 className="w-4 h-4 mr-2" />
<span className="truncate max-w-[150px]">{businessId}</span>
</div>
)}
{/* Time Range Selector */}
<div className="relative">
<select
value={timeRange}
onChange={(e) => setTimeRange(e.target.value)}
className="appearance-none bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md pl-9 pr-8 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
{TIME_RANGES.map((range) => (
<option key={range.value} value={range.value}>
{range.label}
</option>
))}
</select>
<Calendar className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
</div>
{/* Refresh Button */}
<button
onClick={handleRefresh}
className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-md"
title="Refresh all widgets"
>
<RefreshCw className="w-5 h-5" />
</button>
</div>
</div>
{/* Sections */}
{config.sections.map((section) => (
<DashboardSection
key={`${section.id}-${refreshKey}`}
section={section}
pipelineId={pipelineId}
businessId={businessId}
timeRange={timeRange}
/>
))}
</div>
);
}

View File

@@ -0,0 +1,98 @@
'use client';
import type { ComponentType } from 'react';
import type { WidgetConfig, WidgetType, WidgetData } from '@/lib/pipeline-types';
import { StatCard } from './widgets/StatCard';
import { LineChartWidget } from './widgets/LineChart';
import { BarChartWidget } from './widgets/BarChart';
import { PieChartWidget } from './widgets/PieChart';
import { DataTableWidget } from './widgets/DataTable';
import { HeatmapWidget } from './widgets/Heatmap';
// Common widget props
export interface WidgetComponentProps {
config: WidgetConfig;
data: WidgetData | null;
loading: boolean;
error?: string;
onRefresh?: () => void;
onPageChange?: (page: number) => void;
currentPage?: number;
}
// Widget component type
type WidgetComponent = ComponentType<WidgetComponentProps>;
/**
* Registry mapping widget types to their React components.
*/
const WIDGET_COMPONENTS: Record<WidgetType, WidgetComponent> = {
stat_card: StatCard as WidgetComponent,
line_chart: LineChartWidget as WidgetComponent,
bar_chart: BarChartWidget as WidgetComponent,
pie_chart: PieChartWidget as WidgetComponent,
table: DataTableWidget as WidgetComponent,
heatmap: HeatmapWidget as WidgetComponent,
// Placeholder for unimplemented types
area_chart: LineChartWidget as WidgetComponent, // Use line chart as fallback
gauge: StatCard as WidgetComponent, // Use stat card as fallback
};
/**
* Get the component for a widget type.
*/
export function getWidgetComponent(type: WidgetType): WidgetComponent | null {
return WIDGET_COMPONENTS[type] || null;
}
/**
* Check if a widget type is supported.
*/
export function isWidgetTypeSupported(type: string): type is WidgetType {
return type in WIDGET_COMPONENTS;
}
/**
* Render a widget based on its configuration.
*/
export function renderWidget(
config: WidgetConfig,
data: WidgetData | null,
loading: boolean,
error?: string,
onRefresh?: () => void,
onPageChange?: (page: number) => void,
currentPage?: number
): React.ReactNode {
const Component = WIDGET_COMPONENTS[config.type];
if (!Component) {
return (
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
<p className="text-red-500">Unknown widget type: {config.type}</p>
</div>
);
}
return (
<Component
config={config}
data={data}
loading={loading}
error={error}
onRefresh={onRefresh}
onPageChange={onPageChange}
currentPage={currentPage}
/>
);
}
// Export widget components for direct use
export {
StatCard,
LineChartWidget,
BarChartWidget,
PieChartWidget,
DataTableWidget,
HeatmapWidget,
};

View File

@@ -0,0 +1,26 @@
/**
* Dashboard component exports.
*
* This module provides the dynamic dashboard system that renders
* pipeline dashboards from configuration.
*/
// Main components
export { DynamicDashboard } from './DynamicDashboard';
export { DashboardSection } from './DashboardSection';
// Widget registry
export {
getWidgetComponent,
isWidgetTypeSupported,
renderWidget,
} from './WidgetRegistry';
// Individual widgets
export { StatCard } from './widgets/StatCard';
export { LineChartWidget } from './widgets/LineChart';
export { BarChartWidget } from './widgets/BarChart';
export { PieChartWidget } from './widgets/PieChart';
export { DataTableWidget } from './widgets/DataTable';
export { HeatmapWidget } from './widgets/Heatmap';
export { WidgetWrapper } from './widgets/WidgetWrapper';

View File

@@ -0,0 +1,106 @@
'use client';
import {
BarChart as RechartsBarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
ResponsiveContainer,
} from 'recharts';
import type { WidgetConfig, ChartData, ChartWidgetConfig } from '@/lib/pipeline-types';
import { WidgetWrapper } from './WidgetWrapper';
interface BarChartWidgetProps {
config: WidgetConfig;
data: ChartData | null;
loading: boolean;
error?: string;
onRefresh?: () => void;
}
// Default colors for series
const DEFAULT_COLORS = [
'#3b82f6', // blue
'#22c55e', // green
'#ef4444', // red
'#eab308', // yellow
'#8b5cf6', // purple
'#ec4899', // pink
'#06b6d4', // cyan
];
/**
* Bar chart widget using Recharts.
*/
export function BarChartWidget({
config,
data,
loading,
error,
onRefresh,
}: BarChartWidgetProps) {
const chartConfig = config.config as ChartWidgetConfig;
const chartData = data?.data || [];
return (
<WidgetWrapper config={config} loading={loading} error={error} onRefresh={onRefresh}>
{chartData.length === 0 ? (
<div className="flex items-center justify-center h-full text-gray-500">
No data available
</div>
) : (
<ResponsiveContainer width="100%" height="100%">
<RechartsBarChart
data={chartData}
margin={{ top: 5, right: 20, left: 0, bottom: 5 }}
>
{chartConfig.show_grid !== false && (
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
)}
<XAxis
dataKey={chartConfig.x_axis?.key || 'x'}
tick={{ fontSize: 12 }}
tickLine={false}
axisLine={{ stroke: '#e5e7eb' }}
/>
<YAxis
tick={{ fontSize: 12 }}
tickLine={false}
axisLine={{ stroke: '#e5e7eb' }}
label={
chartConfig.y_axis?.label
? {
value: chartConfig.y_axis.label,
angle: -90,
position: 'insideLeft',
style: { fontSize: 12 },
}
: undefined
}
/>
<Tooltip
contentStyle={{
backgroundColor: 'white',
border: '1px solid #e5e7eb',
borderRadius: '0.375rem',
}}
/>
{chartConfig.show_legend !== false && <Legend />}
{chartConfig.series?.map((series, index) => (
<Bar
key={series.key}
dataKey={series.key}
name={series.name}
fill={series.color || DEFAULT_COLORS[index % DEFAULT_COLORS.length]}
radius={[4, 4, 0, 0]}
/>
))}
</RechartsBarChart>
</ResponsiveContainer>
)}
</WidgetWrapper>
);
}

View File

@@ -0,0 +1,134 @@
'use client';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import type { WidgetConfig, TableData, TableWidgetConfig } from '@/lib/pipeline-types';
import { WidgetWrapper } from './WidgetWrapper';
interface DataTableWidgetProps {
config: WidgetConfig;
data: TableData | null;
loading: boolean;
error?: string;
onRefresh?: () => void;
onPageChange?: (page: number) => void;
currentPage?: number;
}
/**
* Data table widget with pagination.
*/
export function DataTableWidget({
config,
data,
loading,
error,
onRefresh,
onPageChange,
currentPage = 1,
}: DataTableWidgetProps) {
const tableConfig = config.config as TableWidgetConfig;
const rows = data?.data || [];
const total = data?.total || 0;
const pageSize = tableConfig.page_size || 10;
const totalPages = Math.ceil(total / pageSize);
return (
<WidgetWrapper config={config} loading={loading} error={error} onRefresh={onRefresh}>
{rows.length === 0 ? (
<div className="flex items-center justify-center h-full text-gray-500">
No data available
</div>
) : (
<div className="flex flex-col h-full">
{/* Table */}
<div className="flex-1 overflow-auto">
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
<thead className="bg-gray-50 dark:bg-gray-800 sticky top-0">
<tr>
{tableConfig.columns.map((col) => (
<th
key={col.key}
className={`px-4 py-3 text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider ${
col.align === 'right'
? 'text-right'
: col.align === 'center'
? 'text-center'
: 'text-left'
}`}
style={{ width: col.width ? `${col.width}px` : undefined }}
>
{col.header}
</th>
))}
</tr>
</thead>
<tbody className="bg-white dark:bg-gray-900 divide-y divide-gray-200 dark:divide-gray-700">
{rows.map((row, rowIndex) => (
<tr
key={row[tableConfig.row_key] as string || rowIndex}
className="hover:bg-gray-50 dark:hover:bg-gray-800"
>
{tableConfig.columns.map((col) => (
<td
key={col.key}
className={`px-4 py-3 text-sm text-gray-900 dark:text-gray-100 whitespace-nowrap ${
col.align === 'right'
? 'text-right'
: col.align === 'center'
? 'text-center'
: 'text-left'
}`}
>
{formatCellValue(row[col.key], col.format)}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
{/* Pagination */}
{tableConfig.show_pagination !== false && totalPages > 1 && onPageChange && (
<div className="flex items-center justify-between px-4 py-3 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800">
<div className="text-sm text-gray-500">
Showing {(currentPage - 1) * pageSize + 1} to{' '}
{Math.min(currentPage * pageSize, total)} of {total}
</div>
<div className="flex items-center space-x-2">
<button
onClick={() => onPageChange(currentPage - 1)}
disabled={currentPage <= 1}
className="p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed"
>
<ChevronLeft className="w-5 h-5" />
</button>
<span className="text-sm text-gray-700 dark:text-gray-300">
Page {currentPage} of {totalPages}
</span>
<button
onClick={() => onPageChange(currentPage + 1)}
disabled={currentPage >= totalPages}
className="p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed"
>
<ChevronRight className="w-5 h-5" />
</button>
</div>
</div>
)}
</div>
)}
</WidgetWrapper>
);
}
function formatCellValue(value: unknown, format?: string): string {
if (value === null || value === undefined) return '-';
if (typeof value === 'number') {
if (format?.includes('%')) {
return `${value.toFixed(1)}%`;
}
return value.toLocaleString();
}
return String(value);
}

View File

@@ -0,0 +1,128 @@
'use client';
import type { WidgetConfig, ChartData, HeatmapConfig } from '@/lib/pipeline-types';
import { WidgetWrapper } from './WidgetWrapper';
interface HeatmapWidgetProps {
config: WidgetConfig;
data: ChartData | null;
loading: boolean;
error?: string;
onRefresh?: () => void;
}
/**
* Heatmap widget for displaying 2D data grids.
*/
export function HeatmapWidget({
config,
data,
loading,
error,
onRefresh,
}: HeatmapWidgetProps) {
const heatmapConfig = config.config as HeatmapConfig;
const rawData = data?.data || [];
// Extract unique x and y values
const xValues = [...new Set(rawData.map((d) => d[heatmapConfig.x_key] as string))];
const yValues = [...new Set(rawData.map((d) => d[heatmapConfig.y_key] as string))];
// Find min/max values for color scaling
const values = rawData.map((d) => d[heatmapConfig.value_key] as number);
const minValue = Math.min(...values, 0);
const maxValue = Math.max(...values, 1);
// Create lookup map
const valueMap = new Map<string, number>();
rawData.forEach((d) => {
const key = `${d[heatmapConfig.y_key]}-${d[heatmapConfig.x_key]}`;
valueMap.set(key, d[heatmapConfig.value_key] as number);
});
// Get color for a value
const getColor = (value: number): string => {
const colors = heatmapConfig.color_scale || ['#f0fdf4', '#22c55e'];
const ratio = maxValue === minValue ? 0.5 : (value - minValue) / (maxValue - minValue);
// Simple interpolation between first and last color
if (colors.length === 2) {
return interpolateColor(colors[0], colors[1], ratio);
}
return colors[Math.min(Math.floor(ratio * colors.length), colors.length - 1)];
};
return (
<WidgetWrapper config={config} loading={loading} error={error} onRefresh={onRefresh}>
{rawData.length === 0 ? (
<div className="flex items-center justify-center h-full text-gray-500">
No data available
</div>
) : (
<div className="overflow-auto h-full">
<table className="min-w-full">
<thead>
<tr>
<th className="px-2 py-2 text-xs font-medium text-gray-500" />
{xValues.map((x) => (
<th
key={x}
className="px-2 py-2 text-xs font-medium text-gray-500 text-center"
>
{x}
</th>
))}
</tr>
</thead>
<tbody>
{yValues.map((y) => (
<tr key={y}>
<td className="px-2 py-2 text-xs font-medium text-gray-700 dark:text-gray-300">
{y}
</td>
{xValues.map((x) => {
const key = `${y}-${x}`;
const value = valueMap.get(key) || 0;
return (
<td
key={key}
className="px-2 py-2 text-center"
style={{ backgroundColor: getColor(value) }}
title={`${y}, ${x}: ${value}`}
>
{heatmapConfig.show_values && (
<span className="text-xs font-medium text-gray-800">
{value.toLocaleString()}
</span>
)}
</td>
);
})}
</tr>
))}
</tbody>
</table>
</div>
)}
</WidgetWrapper>
);
}
/**
* Interpolate between two hex colors.
*/
function interpolateColor(color1: string, color2: string, ratio: number): string {
const hex = (c: string) => parseInt(c, 16);
const r1 = hex(color1.slice(1, 3));
const g1 = hex(color1.slice(3, 5));
const b1 = hex(color1.slice(5, 7));
const r2 = hex(color2.slice(1, 3));
const g2 = hex(color2.slice(3, 5));
const b2 = hex(color2.slice(5, 7));
const r = Math.round(r1 + (r2 - r1) * ratio);
const g = Math.round(g1 + (g2 - g1) * ratio);
const b = Math.round(b1 + (b2 - b1) * ratio);
return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;
}

View File

@@ -0,0 +1,109 @@
'use client';
import {
LineChart as RechartsLineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
ResponsiveContainer,
} from 'recharts';
import type { WidgetConfig, ChartData, ChartWidgetConfig } from '@/lib/pipeline-types';
import { WidgetWrapper } from './WidgetWrapper';
interface LineChartWidgetProps {
config: WidgetConfig;
data: ChartData | null;
loading: boolean;
error?: string;
onRefresh?: () => void;
}
// Default colors for series
const DEFAULT_COLORS = [
'#3b82f6', // blue
'#22c55e', // green
'#ef4444', // red
'#eab308', // yellow
'#8b5cf6', // purple
'#ec4899', // pink
'#06b6d4', // cyan
];
/**
* Line chart widget using Recharts.
*/
export function LineChartWidget({
config,
data,
loading,
error,
onRefresh,
}: LineChartWidgetProps) {
const chartConfig = config.config as ChartWidgetConfig;
const chartData = data?.data || [];
return (
<WidgetWrapper config={config} loading={loading} error={error} onRefresh={onRefresh}>
{chartData.length === 0 ? (
<div className="flex items-center justify-center h-full text-gray-500">
No data available
</div>
) : (
<ResponsiveContainer width="100%" height="100%">
<RechartsLineChart
data={chartData}
margin={{ top: 5, right: 20, left: 0, bottom: 5 }}
>
{chartConfig.show_grid !== false && (
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
)}
<XAxis
dataKey={chartConfig.x_axis?.key || 'x'}
tick={{ fontSize: 12 }}
tickLine={false}
axisLine={{ stroke: '#e5e7eb' }}
/>
<YAxis
tick={{ fontSize: 12 }}
tickLine={false}
axisLine={{ stroke: '#e5e7eb' }}
label={
chartConfig.y_axis?.label
? {
value: chartConfig.y_axis.label,
angle: -90,
position: 'insideLeft',
style: { fontSize: 12 },
}
: undefined
}
/>
<Tooltip
contentStyle={{
backgroundColor: 'white',
border: '1px solid #e5e7eb',
borderRadius: '0.375rem',
}}
/>
{chartConfig.show_legend !== false && <Legend />}
{chartConfig.series?.map((series, index) => (
<Line
key={series.key}
type="monotone"
dataKey={series.key}
name={series.name}
stroke={series.color || DEFAULT_COLORS[index % DEFAULT_COLORS.length]}
strokeWidth={2}
dot={false}
activeDot={{ r: 4 }}
/>
))}
</RechartsLineChart>
</ResponsiveContainer>
)}
</WidgetWrapper>
);
}

View File

@@ -0,0 +1,106 @@
'use client';
import {
PieChart as RechartsPieChart,
Pie,
Cell,
Tooltip,
Legend,
ResponsiveContainer,
} from 'recharts';
import type { WidgetConfig, ChartData, PieChartConfig } from '@/lib/pipeline-types';
import { WidgetWrapper } from './WidgetWrapper';
interface PieChartWidgetProps {
config: WidgetConfig;
data: ChartData | null;
loading: boolean;
error?: string;
onRefresh?: () => void;
}
// Default colors for pie slices
const DEFAULT_COLORS = [
'#3b82f6', // blue
'#22c55e', // green
'#ef4444', // red
'#eab308', // yellow
'#8b5cf6', // purple
'#ec4899', // pink
'#06b6d4', // cyan
'#f97316', // orange
];
/**
* Pie/Donut chart widget using Recharts.
*/
export function PieChartWidget({
config,
data,
loading,
error,
onRefresh,
}: PieChartWidgetProps) {
const chartConfig = config.config as PieChartConfig;
const chartData = data?.data || [];
const colors = chartConfig.colors || DEFAULT_COLORS;
const innerRadius = chartConfig.inner_radius || 0; // 0 = pie, > 0 = donut
// Transform data to use consistent keys
const transformedData = chartData.map((item) => ({
name: item[chartConfig.label_key] as string,
value: item[chartConfig.value_key] as number,
}));
return (
<WidgetWrapper config={config} loading={loading} error={error} onRefresh={onRefresh}>
{transformedData.length === 0 ? (
<div className="flex items-center justify-center h-full text-gray-500">
No data available
</div>
) : (
<ResponsiveContainer width="100%" height="100%">
<RechartsPieChart>
<Pie
data={transformedData}
cx="50%"
cy="50%"
innerRadius={innerRadius}
outerRadius="80%"
dataKey="value"
nameKey="name"
label={
chartConfig.show_labels !== false
? ({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`
: undefined
}
labelLine={chartConfig.show_labels !== false}
>
{transformedData.map((_, index) => (
<Cell
key={`cell-${index}`}
fill={colors[index % colors.length]}
/>
))}
</Pie>
<Tooltip
contentStyle={{
backgroundColor: 'white',
border: '1px solid #e5e7eb',
borderRadius: '0.375rem',
}}
formatter={(value: number) => [value.toLocaleString(), 'Count']}
/>
{chartConfig.show_legend !== false && (
<Legend
layout="horizontal"
verticalAlign="bottom"
align="center"
/>
)}
</RechartsPieChart>
</ResponsiveContainer>
)}
</WidgetWrapper>
);
}

View File

@@ -0,0 +1,113 @@
'use client';
import {
TrendingUp,
TrendingDown,
MessageSquare,
CheckCircle,
AlertTriangle,
Star,
Activity,
} from 'lucide-react';
import type { WidgetConfig, StatCardData, StatCardConfig } from '@/lib/pipeline-types';
import { WidgetWrapper } from './WidgetWrapper';
interface StatCardProps {
config: WidgetConfig;
data: StatCardData | null;
loading: boolean;
error?: string;
onRefresh?: () => void;
}
// Icon mapping
const ICONS: Record<string, React.ComponentType<{ className?: string }>> = {
'message-square': MessageSquare,
'check-circle': CheckCircle,
'alert-triangle': AlertTriangle,
star: Star,
activity: Activity,
};
// Color mapping
const COLORS: Record<string, string> = {
blue: 'text-blue-600 bg-blue-100 dark:text-blue-400 dark:bg-blue-900/30',
green: 'text-green-600 bg-green-100 dark:text-green-400 dark:bg-green-900/30',
red: 'text-red-600 bg-red-100 dark:text-red-400 dark:bg-red-900/30',
yellow: 'text-yellow-600 bg-yellow-100 dark:text-yellow-400 dark:bg-yellow-900/30',
purple: 'text-purple-600 bg-purple-100 dark:text-purple-400 dark:bg-purple-900/30',
gray: 'text-gray-600 bg-gray-100 dark:text-gray-400 dark:bg-gray-700',
};
/**
* Format a value according to a format string.
* Supports: {value:,} for thousands, {value:.1f} for decimals, {value:.1%} for percentages
*/
function formatValue(value: number | string, format?: string): string {
if (!format) return String(value);
const num = typeof value === 'string' ? parseFloat(value) : value;
if (isNaN(num)) return String(value);
// Simple format parsing
if (format.includes(':,}')) {
return num.toLocaleString();
}
if (format.includes(':.1f}')) {
return num.toFixed(1);
}
if (format.includes(':.2f}')) {
return num.toFixed(2);
}
if (format.includes(':.1%}')) {
return (num * 100).toFixed(1) + '%';
}
return String(value);
}
/**
* Stat card widget for displaying KPIs.
*/
export function StatCard({ config, data, loading, error, onRefresh }: StatCardProps) {
const widgetConfig = config.config as StatCardConfig;
const Icon = widgetConfig.icon ? ICONS[widgetConfig.icon] : Activity;
const colorClass = widgetConfig.color ? COLORS[widgetConfig.color] : COLORS.gray;
// Extract value and trend from data
const value = data?.[widgetConfig.value_key] ?? 0;
const trend = widgetConfig.trend_key ? data?.[widgetConfig.trend_key] : undefined;
return (
<WidgetWrapper config={config} loading={loading} error={error} onRefresh={onRefresh}>
<div className="flex items-center justify-between h-full">
<div className="flex-1">
<p className="text-3xl font-bold text-gray-900 dark:text-gray-100">
{formatValue(value, widgetConfig.format)}
</p>
{trend !== undefined && (
<div className="flex items-center mt-1">
{Number(trend) >= 0 ? (
<TrendingUp className="w-4 h-4 text-green-500 mr-1" />
) : (
<TrendingDown className="w-4 h-4 text-red-500 mr-1" />
)}
<span
className={`text-sm ${
Number(trend) >= 0 ? 'text-green-600' : 'text-red-600'
}`}
>
{formatValue(trend, widgetConfig.trend_format || '{value:.1f}')}
</span>
</div>
)}
</div>
{Icon && (
<div className={`p-3 rounded-full ${colorClass}`}>
<Icon className="w-6 h-6" />
</div>
)}
</div>
</WidgetWrapper>
);
}

View File

@@ -0,0 +1,66 @@
'use client';
import { RefreshCw, AlertCircle } from 'lucide-react';
import type { WidgetConfig } from '@/lib/pipeline-types';
interface WidgetWrapperProps {
config: WidgetConfig;
loading: boolean;
error?: string;
onRefresh?: () => void;
children: React.ReactNode;
}
/**
* Common wrapper for dashboard widgets.
* Handles loading, error states, and refresh functionality.
*/
export function WidgetWrapper({
config,
loading,
error,
onRefresh,
children,
}: WidgetWrapperProps) {
return (
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm h-full flex flex-col">
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-gray-700">
<h3 className="font-medium text-gray-900 dark:text-gray-100 text-sm">
{config.title}
</h3>
{onRefresh && (
<button
onClick={onRefresh}
disabled={loading}
className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 disabled:opacity-50"
title="Refresh"
>
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
</button>
)}
</div>
{/* Content */}
<div className="flex-1 p-4 overflow-auto">
{error ? (
<div className="flex items-center justify-center h-full">
<div className="text-center">
<AlertCircle className="w-8 h-8 text-red-500 mx-auto mb-2" />
<p className="text-sm text-red-600 dark:text-red-400">{error}</p>
</div>
</div>
) : loading ? (
<div className="flex items-center justify-center h-full">
<div className="animate-pulse flex flex-col items-center">
<div className="h-4 w-24 bg-gray-200 dark:bg-gray-700 rounded mb-2" />
<div className="h-3 w-16 bg-gray-200 dark:bg-gray-700 rounded" />
</div>
</div>
) : (
children
)}
</div>
</div>
);
}