feat(reviewiq): Add AI synthesis support to dashboard components

Frontend:
- Add Synthesis type with action plan, insights, annotations
- ExecutiveSummary: Accept synthesis prop for AI narrative
- SentimentPie: Accept insight prop for contextual explanation
- IntensityHeatmap: Accept insight + highlightDomain props
- TimelineChart: Accept insight + annotations props
- All components gracefully degrade when synthesis is null

Backend:
- Add Stage 4: Synthesize for generating AI narratives
- Gathers context from classified spans
- Generates executive narrative, section insights, action plan
- Produces timeline annotations and marketing angles
- Stores synthesis in pipeline.executions table

Components show AI insights with purple gradient styling when available,
fall back to existing behavior when synthesis is not yet generated.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Alejandro Gutiérrez
2026-01-29 02:59:47 +00:00
parent 8f9dd136cd
commit c8ecb4b98f
21 changed files with 3959 additions and 90 deletions

View File

@@ -0,0 +1,259 @@
'use client';
import { useState } from 'react';
import { X, AlertTriangle, Layers, Calendar, Target, User, Lightbulb, FileText } from 'lucide-react';
import type { IssueItem, SpanItem } from '../types';
import { DOMAIN_LABELS, INTENSITY_LABELS, VALENCE_LABELS, VALENCE_COLORS } from '../types';
import { useIssueSpans } from '@/hooks/useReviewIQAnalytics';
import { ReviewModal } from './ReviewModal';
interface IssueDetailModalProps {
issue: IssueItem;
onClose: () => void;
}
/**
* Modal showing issue details and related spans.
*/
export function IssueDetailModal({ issue, onClose }: IssueDetailModalProps) {
const { data: spans, loading, error } = useIssueSpans(issue.issue_id);
const [selectedReview, setSelectedReview] = useState<{
reviewId: string;
spanId: string;
} | null>(null);
return (
<div
className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"
onClick={onClose}
>
<div
className="bg-white rounded-2xl shadow-2xl max-w-3xl w-full max-h-[90vh] overflow-y-auto"
onClick={(e) => e.stopPropagation()}
>
{/* Header */}
<div className="sticky top-0 bg-white border-b-2 border-gray-200 px-6 py-4 rounded-t-2xl">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<AlertTriangle className="w-6 h-6 text-orange-600" />
<div>
<h3 className="text-xl font-bold text-gray-900">
{issue.subcode_name || issue.primary_subcode}
</h3>
<span className="text-sm font-mono text-gray-500">{issue.primary_subcode}</span>
</div>
<span
className={`px-2 py-1 text-xs font-bold rounded border ${
issue.state === 'open'
? 'bg-red-100 text-red-800 border-red-300'
: issue.state === 'resolved'
? 'bg-green-100 text-green-800 border-green-300'
: 'bg-gray-100 text-gray-800 border-gray-300'
}`}
>
{issue.state.toUpperCase()}
</span>
</div>
<button
onClick={onClose}
className="p-2 hover:bg-gray-100 rounded-full transition-colors"
>
<X className="w-5 h-5 text-gray-600" />
</button>
</div>
</div>
{/* Content */}
<div className="p-6 space-y-6">
{/* Issue Info Grid */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<div className="bg-purple-50 rounded-lg p-4 border border-purple-200">
<div className="flex items-center gap-2 mb-1">
<Target className="w-4 h-4 text-purple-600" />
<span className="text-xs font-semibold text-purple-700">URT Code</span>
</div>
<span className="text-lg font-mono font-bold text-purple-900">
{issue.primary_subcode}
</span>
</div>
<div className="bg-blue-50 rounded-lg p-4 border border-blue-200">
<div className="flex items-center gap-2 mb-1">
<Layers className="w-4 h-4 text-blue-600" />
<span className="text-xs font-semibold text-blue-700">Domain</span>
</div>
<span className="text-lg font-bold text-blue-900">
{DOMAIN_LABELS[issue.domain] || issue.domain}
</span>
</div>
<div className="bg-orange-50 rounded-lg p-4 border border-orange-200">
<div className="flex items-center gap-2 mb-1">
<AlertTriangle className="w-4 h-4 text-orange-600" />
<span className="text-xs font-semibold text-orange-700">Priority</span>
</div>
<span className="text-lg font-bold text-orange-900">
{(issue.priority_score * 100).toFixed(0)}%
</span>
</div>
<div className="bg-gray-50 rounded-lg p-4 border border-gray-200">
<div className="flex items-center gap-2 mb-1">
<Calendar className="w-4 h-4 text-gray-600" />
<span className="text-xs font-semibold text-gray-700">Intensity</span>
</div>
<span className="text-lg font-bold text-gray-900">
{issue.max_intensity
? INTENSITY_LABELS[issue.max_intensity] || issue.max_intensity
: 'N/A'}
</span>
</div>
</div>
{/* Entity */}
{issue.entity && (
<div className="bg-gray-50 rounded-lg p-4 border border-gray-200">
<span className="text-sm font-semibold text-gray-700">Related Entity</span>
<p className="text-lg font-medium text-gray-900 mt-1">{issue.entity}</p>
</div>
)}
{/* Solution & Owner Section */}
{(issue.solution || issue.default_owner) && (
<div className="bg-green-50 rounded-lg p-4 border border-green-200 space-y-3">
{issue.solution && (
<div>
<div className="flex items-center gap-2 mb-2">
<Lightbulb className="w-5 h-5 text-green-600" />
<span className="text-sm font-bold text-green-800">Recommended Solution</span>
{issue.solution_complexity && (
<span className={`ml-auto text-xs font-bold px-2 py-1 rounded ${
issue.solution_complexity === 'low'
? 'bg-green-100 text-green-700'
: issue.solution_complexity === 'medium'
? 'bg-yellow-100 text-yellow-700'
: 'bg-red-100 text-red-700'
}`}>
{issue.solution_complexity.charAt(0).toUpperCase() + issue.solution_complexity.slice(1)} Complexity
</span>
)}
</div>
<p className="text-gray-700 leading-relaxed">{issue.solution}</p>
</div>
)}
{issue.default_owner && (
<div className="flex items-center gap-2 pt-2 border-t border-green-200">
<User className="w-4 h-4 text-green-600" />
<span className="text-sm text-green-800">
<span className="font-medium">Assign to:</span>{' '}
<span className="font-bold">{issue.default_owner}</span>
</span>
</div>
)}
</div>
)}
{/* Related Spans */}
<div>
<div className="flex items-center justify-between mb-4">
<h4 className="text-lg font-bold text-gray-900">
Related Spans ({issue.span_count})
</h4>
</div>
{loading ? (
<div className="flex items-center justify-center h-32 text-gray-500">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600" />
</div>
) : error ? (
<div className="flex items-center justify-center h-32 text-red-500">
Failed to load spans: {error}
</div>
) : spans.length === 0 ? (
<div className="flex items-center justify-center h-32 text-gray-500">
No spans found for this issue
</div>
) : (
<div className="space-y-3 max-h-96 overflow-y-auto">
{spans.map((span: SpanItem) => (
<div
key={span.span_id}
className="bg-gray-50 rounded-lg p-4 border border-gray-200"
>
<div className="flex items-start justify-between gap-4">
<p className="text-gray-800 flex-1">{span.span_text}</p>
<div className="flex items-center gap-2 flex-shrink-0">
{span.valence && (
<span
className="px-2 py-1 text-xs font-bold rounded"
style={{
backgroundColor: `${VALENCE_COLORS[span.valence]}20`,
color: VALENCE_COLORS[span.valence],
}}
>
{VALENCE_LABELS[span.valence] || span.valence}
</span>
)}
{span.intensity && (
<span className="px-2 py-1 bg-gray-200 text-gray-700 text-xs font-bold rounded">
{INTENSITY_LABELS[span.intensity] || span.intensity}
</span>
)}
</div>
</div>
<div className="flex items-center justify-between gap-4 mt-2">
<div className="flex items-center gap-4 text-xs text-gray-500">
{span.urt_primary && (
<span className="font-mono">{span.urt_primary}</span>
)}
{span.review_time && (
<span>{new Date(span.review_time).toLocaleDateString()}</span>
)}
{span.entity && <span>Entity: {span.entity}</span>}
</div>
{/* View Full Review Button */}
{span.source_review_id && (
<button
onClick={() =>
setSelectedReview({
reviewId: span.source_review_id!,
spanId: span.span_id,
})
}
className="inline-flex items-center gap-1 px-2 py-1 text-xs font-semibold text-blue-600 hover:bg-blue-50 rounded transition-colors"
>
<FileText className="w-3 h-3" />
View Review
</button>
)}
</div>
</div>
))}
</div>
)}
</div>
</div>
{/* Footer */}
<div className="sticky bottom-0 bg-white border-t-2 border-gray-200 px-6 py-4 rounded-b-2xl">
<button
onClick={onClose}
className="w-full py-3 bg-gray-900 text-white rounded-lg font-semibold hover:bg-gray-800 transition-colors"
>
Close
</button>
</div>
</div>
{/* Review Modal for drill-down */}
{selectedReview && (
<ReviewModal
reviewId={selectedReview.reviewId}
highlightSpanId={selectedReview.spanId}
onClose={() => setSelectedReview(null)}
/>
)}
</div>
);
}

View File

@@ -0,0 +1,286 @@
'use client';
import { useState, useMemo } from 'react';
import {
useReactTable,
getCoreRowModel,
getSortedRowModel,
getPaginationRowModel,
ColumnDef,
flexRender,
SortingState,
} from '@tanstack/react-table';
import { ArrowUpDown, ArrowUp, ArrowDown, ExternalLink, ChevronLeft, ChevronRight } from 'lucide-react';
import type { IssueItem, PaginatedIssues } from '../types';
import { DOMAIN_LABELS, INTENSITY_LABELS } from '../types';
import { IssueDetailModal } from './IssueDetailModal';
interface IssuesTableProps {
issues: PaginatedIssues;
onPageChange?: (page: number) => void;
}
// Priority badge color based on score
const getPriorityColor = (score: number): string => {
if (score >= 0.8) return 'bg-red-100 text-red-800 border-red-300';
if (score >= 0.5) return 'bg-orange-100 text-orange-800 border-orange-300';
if (score >= 0.3) return 'bg-yellow-100 text-yellow-800 border-yellow-300';
return 'bg-gray-100 text-gray-800 border-gray-300';
};
// State badge color
const getStateColor = (state: string): string => {
switch (state) {
case 'open':
return 'bg-red-100 text-red-800 border-red-300';
case 'in_progress':
return 'bg-blue-100 text-blue-800 border-blue-300';
case 'resolved':
return 'bg-green-100 text-green-800 border-green-300';
default:
return 'bg-gray-100 text-gray-800 border-gray-300';
}
};
/**
* Issues table with TanStack Table.
* Click rows to open drill-down modal.
*/
export function IssuesTable({ issues, onPageChange }: IssuesTableProps) {
const [sorting, setSorting] = useState<SortingState>([
{ id: 'priority_score', desc: true },
]);
const [selectedIssue, setSelectedIssue] = useState<IssueItem | null>(null);
const columns = useMemo<ColumnDef<IssueItem>[]>(
() => [
{
accessorKey: 'primary_subcode',
header: ({ column }) => (
<button
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
className="flex items-center gap-2 hover:text-blue-700 font-semibold"
>
Issue
{column.getIsSorted() === 'asc' ? (
<ArrowUp className="w-4 h-4" />
) : column.getIsSorted() === 'desc' ? (
<ArrowDown className="w-4 h-4" />
) : (
<ArrowUpDown className="w-4 h-4 opacity-50" />
)}
</button>
),
cell: ({ row }) => (
<div className="flex flex-col gap-1">
<span className="text-sm font-semibold text-gray-900">
{row.original.subcode_name || row.original.primary_subcode}
</span>
<span className="px-2 py-0.5 bg-purple-100 text-purple-800 text-xs font-mono font-bold rounded border border-purple-300 w-fit">
{row.original.primary_subcode}
</span>
</div>
),
},
{
accessorKey: 'domain',
header: 'Domain',
cell: ({ row }) => (
<span className="text-sm font-medium text-gray-700">
{DOMAIN_LABELS[row.original.domain] || row.original.domain}
</span>
),
},
{
accessorKey: 'default_owner',
header: 'Owner',
cell: ({ row }) => (
<span className="text-xs font-medium px-2 py-1 bg-blue-50 text-blue-700 rounded-full border border-blue-200">
{row.original.default_owner || 'Unassigned'}
</span>
),
},
{
accessorKey: 'state',
header: 'State',
cell: ({ row }) => (
<span
className={`px-2 py-1 text-xs font-bold rounded border ${getStateColor(row.original.state)}`}
>
{row.original.state.toUpperCase()}
</span>
),
},
{
accessorKey: 'priority_score',
header: ({ column }) => (
<button
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
className="flex items-center gap-2 hover:text-blue-700 font-semibold"
>
Priority
{column.getIsSorted() === 'asc' ? (
<ArrowUp className="w-4 h-4" />
) : column.getIsSorted() === 'desc' ? (
<ArrowDown className="w-4 h-4" />
) : (
<ArrowUpDown className="w-4 h-4 opacity-50" />
)}
</button>
),
cell: ({ row }) => (
<span
className={`px-2 py-1 text-xs font-bold rounded border ${getPriorityColor(row.original.priority_score)}`}
>
{(row.original.priority_score * 100).toFixed(0)}%
</span>
),
},
{
accessorKey: 'span_count',
header: 'Spans',
cell: ({ row }) => (
<span className="text-sm font-medium text-gray-700">
{row.original.span_count}
</span>
),
},
{
accessorKey: 'max_intensity',
header: 'Intensity',
cell: ({ row }) => (
<span className="text-sm text-gray-600">
{row.original.max_intensity
? INTENSITY_LABELS[row.original.max_intensity] || row.original.max_intensity
: '-'}
</span>
),
},
{
id: 'actions',
header: '',
cell: ({ row }) => (
<button
onClick={() => setSelectedIssue(row.original)}
className="p-1 hover:bg-gray-100 rounded transition-colors"
title="View details"
>
<ExternalLink className="w-4 h-4 text-gray-500" />
</button>
),
},
],
[]
);
const table = useReactTable({
data: issues.items,
columns,
state: { sorting },
onSortingChange: setSorting,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
initialState: {
pagination: { pageSize: 10 },
},
});
const totalPages = Math.ceil(issues.total / issues.page_size);
return (
<div className="bg-white rounded-xl p-6 shadow-md border-2 border-gray-300">
<div className="flex items-center justify-between mb-4">
<div>
<h3 className="text-xl font-bold text-gray-900">Issues</h3>
<p className="text-sm text-gray-500">
{issues.total} total issues - Click row for details
</p>
</div>
</div>
{issues.items.length === 0 ? (
<div className="flex items-center justify-center h-32 text-gray-500">
No issues found
</div>
) : (
<>
<div className="overflow-x-auto border-2 border-gray-200 rounded-lg">
<table className="w-full">
<thead className="bg-gray-50 border-b-2 border-gray-200">
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<th
key={header.id}
className="px-4 py-3 text-left text-gray-900"
>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</th>
))}
</tr>
))}
</thead>
<tbody className="divide-y divide-gray-200">
{table.getRowModel().rows.map((row) => (
<tr
key={row.id}
className="hover:bg-blue-50 cursor-pointer transition-colors"
onClick={() => setSelectedIssue(row.original)}
>
{row.getVisibleCells().map((cell) => (
<td key={cell.id} className="px-4 py-3">
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
{/* Pagination */}
<div className="flex items-center justify-between mt-4">
<div className="text-sm text-gray-700 font-medium">
Page {issues.page} of {totalPages} ({issues.total} issues)
</div>
<div className="flex gap-2">
<button
onClick={() => onPageChange?.(issues.page - 1)}
disabled={issues.page <= 1}
className="px-3 py-2 border-2 border-gray-300 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50 font-semibold text-gray-900 flex items-center gap-1"
>
<ChevronLeft className="w-4 h-4" />
Previous
</button>
<button
onClick={() => onPageChange?.(issues.page + 1)}
disabled={issues.page >= totalPages}
className="px-3 py-2 border-2 border-gray-300 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50 font-semibold text-gray-900 flex items-center gap-1"
>
Next
<ChevronRight className="w-4 h-4" />
</button>
</div>
</div>
</>
)}
{/* Detail Modal */}
{selectedIssue && (
<IssueDetailModal
issue={selectedIssue}
onClose={() => setSelectedIssue(null)}
/>
)}
</div>
);
}

View File

@@ -0,0 +1,372 @@
'use client';
import { useState, useEffect, useMemo } from 'react';
import {
X,
Star,
ExternalLink,
Calendar,
User,
MapPin,
Loader2,
AlertCircle,
} from 'lucide-react';
import type { FullReview, ReviewSpan } from '../types';
import {
VALENCE_COLORS,
VALENCE_LABELS,
INTENSITY_LABELS,
DOMAIN_LABELS,
DOMAIN_COLORS,
} from '../types';
interface ReviewModalProps {
reviewId: string | null;
source?: string;
highlightSpanId?: string | null;
onClose: () => void;
}
/**
* Modal showing a full review with classified spans highlighted.
* Enables drill-down from any aggregate metric to the raw source data.
*/
export function ReviewModal({
reviewId,
source = 'google',
highlightSpanId,
onClose,
}: ReviewModalProps) {
const [review, setReview] = useState<FullReview | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Fetch review when reviewId changes
useEffect(() => {
if (!reviewId) {
setReview(null);
return;
}
const fetchReview = async () => {
setLoading(true);
setError(null);
try {
const response = await fetch(
`/api/pipelines/reviewiq/reviews/${encodeURIComponent(reviewId)}?source=${encodeURIComponent(source)}`
);
if (!response.ok) {
throw new Error(`Failed to fetch review: ${response.statusText}`);
}
const data = await response.json();
setReview(data);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch review');
} finally {
setLoading(false);
}
};
fetchReview();
}, [reviewId, source]);
// Build highlighted text with spans marked using text-based matching
// (offsets in DB are unreliable, so we find spans by searching for their text)
const highlightedText = useMemo(() => {
if (!review?.review_text || !review.spans.length) {
return review?.review_text || '';
}
const text = review.review_text;
// Find all span positions using text search
const spanPositions: Array<{
start: number;
end: number;
span: ReviewSpan;
}> = [];
for (const span of review.spans) {
if (!span.span_text) continue;
// Try exact match first
let idx = text.indexOf(span.span_text);
// If not found, try case-insensitive
if (idx === -1) {
idx = text.toLowerCase().indexOf(span.span_text.toLowerCase());
}
if (idx !== -1) {
spanPositions.push({
start: idx,
end: idx + span.span_text.length,
span,
});
}
}
if (spanPositions.length === 0) {
// No matches found, return plain text
return review.review_text;
}
// Sort by position and remove overlaps (keep first occurrence)
spanPositions.sort((a, b) => a.start - b.start);
const nonOverlapping: typeof spanPositions = [];
let lastEnd = 0;
for (const pos of spanPositions) {
if (pos.start >= lastEnd) {
nonOverlapping.push(pos);
lastEnd = pos.end;
}
}
// Build segments
const segments: Array<{ text: string; span: ReviewSpan | null }> = [];
let currentPos = 0;
for (const pos of nonOverlapping) {
// Add text before this span
if (pos.start > currentPos) {
segments.push({ text: text.slice(currentPos, pos.start), span: null });
}
// Add the span (use actual text from review, not span_text, to preserve case)
segments.push({ text: text.slice(pos.start, pos.end), span: pos.span });
currentPos = pos.end;
}
// Add remaining text
if (currentPos < text.length) {
segments.push({ text: text.slice(currentPos), span: null });
}
return segments;
}, [review]);
if (!reviewId) return null;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
<div className="bg-white rounded-xl shadow-2xl w-full max-w-3xl max-h-[90vh] overflow-hidden flex flex-col">
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b-2 border-gray-200">
<h2 className="text-xl font-bold text-gray-900">Full Review</h2>
<button
onClick={onClose}
className="p-2 hover:bg-gray-100 rounded-full transition-colors"
>
<X className="w-5 h-5 text-gray-600" />
</button>
</div>
{/* Content */}
<div className="flex-1 overflow-y-auto p-6">
{loading ? (
<div className="flex items-center justify-center h-64">
<Loader2 className="w-8 h-8 text-blue-600 animate-spin" />
</div>
) : error ? (
<div className="flex flex-col items-center justify-center h-64 text-red-600">
<AlertCircle className="w-12 h-12 mb-4" />
<p className="font-semibold">{error}</p>
</div>
) : review ? (
<div className="space-y-6">
{/* Review Metadata */}
<div className="flex items-start justify-between">
<div className="space-y-2">
{/* Author */}
{review.author_name && (
<div className="flex items-center gap-2 text-gray-700">
<User className="w-4 h-4" />
<span className="font-semibold">{review.author_name}</span>
</div>
)}
{/* Business */}
{review.business_name && (
<div className="flex items-center gap-2 text-gray-600 text-sm">
<MapPin className="w-4 h-4" />
<span>{review.business_name}</span>
</div>
)}
{/* Date */}
{review.review_time && (
<div className="flex items-center gap-2 text-gray-500 text-sm">
<Calendar className="w-4 h-4" />
<span>{new Date(review.review_time).toLocaleDateString()}</span>
</div>
)}
</div>
{/* Rating */}
{review.rating !== null && (
<div className="flex items-center gap-1">
{Array.from({ length: 5 }).map((_, i) => (
<Star
key={i}
className={`w-5 h-5 ${
i < review.rating!
? 'text-yellow-400 fill-yellow-400'
: 'text-gray-300'
}`}
/>
))}
</div>
)}
</div>
{/* Review Text with Highlighted Spans */}
<div className="bg-gray-50 rounded-lg p-4 border-2 border-gray-200">
<p className="text-gray-800 leading-relaxed whitespace-pre-wrap">
{Array.isArray(highlightedText) ? (
highlightedText.map((segment, idx) =>
segment.span ? (
<span
key={idx}
className={`relative inline px-1 py-0.5 rounded ${
highlightSpanId === segment.span.span_id
? 'ring-2 ring-blue-500 ring-offset-1'
: ''
}`}
style={{
backgroundColor: segment.span.valence
? `${VALENCE_COLORS[segment.span.valence]}30`
: '#e5e7eb',
borderBottom: segment.span.urt_primary
? `3px solid ${DOMAIN_COLORS[segment.span.urt_primary[0]] || '#6b7280'}`
: 'none',
}}
title={`${segment.span.urt_primary || 'Unknown'} | ${
VALENCE_LABELS[segment.span.valence || ''] || 'N/A'
} | ${INTENSITY_LABELS[segment.span.intensity || ''] || 'N/A'}`}
>
{segment.text}
</span>
) : (
<span key={idx}>{segment.text}</span>
)
)
) : (
highlightedText
)}
</p>
</div>
{/* Legend */}
<div className="flex flex-wrap gap-4 text-xs">
<div className="flex items-center gap-1">
<span
className="w-4 h-4 rounded"
style={{ backgroundColor: `${VALENCE_COLORS['V+']}30` }}
/>
<span>Positive</span>
</div>
<div className="flex items-center gap-1">
<span
className="w-4 h-4 rounded"
style={{ backgroundColor: `${VALENCE_COLORS['V0']}30` }}
/>
<span>Neutral</span>
</div>
<div className="flex items-center gap-1">
<span
className="w-4 h-4 rounded"
style={{ backgroundColor: `${VALENCE_COLORS['V-']}30` }}
/>
<span>Negative</span>
</div>
<span className="text-gray-400">|</span>
<span className="text-gray-600">Underline = URT Domain</span>
</div>
{/* Classified Spans List */}
<div>
<h3 className="text-lg font-bold text-gray-900 mb-3">
Classified Spans ({review.spans.length})
</h3>
<div className="space-y-2">
{review.spans.map((span) => (
<div
key={span.span_id}
className={`p-3 rounded-lg border-2 transition-all ${
highlightSpanId === span.span_id
? 'border-blue-500 bg-blue-50'
: 'border-gray-200 bg-white hover:border-gray-300'
}`}
>
<div className="flex items-start justify-between gap-4">
<p className="text-sm text-gray-700 flex-1 italic">
&ldquo;{span.span_text}&rdquo;
</p>
<div className="flex items-center gap-2 flex-shrink-0">
{/* URT Code */}
{span.urt_primary && (
<span
className="px-2 py-1 text-xs font-mono font-bold rounded"
style={{
backgroundColor: `${DOMAIN_COLORS[span.urt_primary[0]] || '#6b7280'}20`,
color: DOMAIN_COLORS[span.urt_primary[0]] || '#6b7280',
}}
>
{span.urt_primary}
</span>
)}
{/* Valence */}
{span.valence && (
<span
className="px-2 py-1 text-xs font-bold rounded"
style={{
backgroundColor: `${VALENCE_COLORS[span.valence]}20`,
color: VALENCE_COLORS[span.valence],
}}
>
{VALENCE_LABELS[span.valence]}
</span>
)}
{/* Intensity */}
{span.intensity && (
<span className="px-2 py-1 text-xs font-medium bg-gray-100 text-gray-700 rounded">
{INTENSITY_LABELS[span.intensity]}
</span>
)}
</div>
</div>
{/* Domain label */}
{span.urt_primary && (
<div className="mt-2 text-xs text-gray-500">
{DOMAIN_LABELS[span.urt_primary[0]]} Domain
{span.entity && ` · Entity: ${span.entity}`}
</div>
)}
</div>
))}
</div>
</div>
{/* External Link */}
{review.review_url && (
<div className="pt-4 border-t-2 border-gray-200">
<a
href={review.review_url}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white font-semibold rounded-lg hover:bg-blue-700 transition-colors"
>
<ExternalLink className="w-4 h-4" />
View on Google Maps
</a>
</div>
)}
</div>
) : null}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,334 @@
'use client';
import { useState, useMemo, Fragment } from 'react';
import {
useReactTable,
getCoreRowModel,
getSortedRowModel,
getPaginationRowModel,
getExpandedRowModel,
ColumnDef,
flexRender,
SortingState,
Row,
} from '@tanstack/react-table';
import {
ArrowUpDown,
ArrowUp,
ArrowDown,
ChevronLeft,
ChevronRight,
ChevronDown,
ChevronRight as ChevronRightIcon,
FileText,
} from 'lucide-react';
import type { SpanItem, PaginatedSpans } from '../types';
import { VALENCE_LABELS, VALENCE_COLORS, INTENSITY_LABELS, DOMAIN_LABELS } from '../types';
import { ReviewModal } from './ReviewModal';
interface SpansTableProps {
spans: PaginatedSpans;
onPageChange?: (page: number) => void;
}
/**
* Spans table with expandable rows and drill-down to full review.
*/
export function SpansTable({ spans, onPageChange }: SpansTableProps) {
const [sorting, setSorting] = useState<SortingState>([]);
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
const [selectedReview, setSelectedReview] = useState<{
reviewId: string;
spanId: string;
} | null>(null);
const columns = useMemo<ColumnDef<SpanItem>[]>(
() => [
{
id: 'expander',
header: '',
cell: ({ row }) => (
<button
onClick={() => row.toggleExpanded()}
className="p-1 hover:bg-gray-100 rounded transition-colors"
>
{row.getIsExpanded() ? (
<ChevronDown className="w-4 h-4 text-gray-500" />
) : (
<ChevronRightIcon className="w-4 h-4 text-gray-500" />
)}
</button>
),
},
{
accessorKey: 'span_text',
header: 'Text',
cell: ({ row }) => (
<div className="max-w-md">
<p className="text-sm text-gray-800 line-clamp-2">
{row.original.span_text}
</p>
</div>
),
},
{
accessorKey: 'urt_primary',
header: ({ column }) => (
<button
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
className="flex items-center gap-2 hover:text-blue-700 font-semibold"
>
URT Code
{column.getIsSorted() === 'asc' ? (
<ArrowUp className="w-4 h-4" />
) : column.getIsSorted() === 'desc' ? (
<ArrowDown className="w-4 h-4" />
) : (
<ArrowUpDown className="w-4 h-4 opacity-50" />
)}
</button>
),
cell: ({ row }) => (
<span className="px-2 py-1 bg-purple-100 text-purple-800 text-xs font-mono font-bold rounded border border-purple-300">
{row.original.urt_primary || '-'}
</span>
),
},
{
accessorKey: 'valence',
header: 'Sentiment',
cell: ({ row }) => {
const valence = row.original.valence;
if (!valence) return <span className="text-gray-400">-</span>;
return (
<span
className="px-2 py-1 text-xs font-bold rounded"
style={{
backgroundColor: `${VALENCE_COLORS[valence]}20`,
color: VALENCE_COLORS[valence],
}}
>
{VALENCE_LABELS[valence] || valence}
</span>
);
},
},
{
accessorKey: 'intensity',
header: 'Intensity',
cell: ({ row }) => (
<span className="text-sm text-gray-600">
{row.original.intensity
? INTENSITY_LABELS[row.original.intensity] || row.original.intensity
: '-'}
</span>
),
},
{
accessorKey: 'review_time',
header: ({ column }) => (
<button
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
className="flex items-center gap-2 hover:text-blue-700 font-semibold"
>
Date
{column.getIsSorted() === 'asc' ? (
<ArrowUp className="w-4 h-4" />
) : column.getIsSorted() === 'desc' ? (
<ArrowDown className="w-4 h-4" />
) : (
<ArrowUpDown className="w-4 h-4 opacity-50" />
)}
</button>
),
cell: ({ row }) => (
<span className="text-sm text-gray-600">
{row.original.review_time
? new Date(row.original.review_time).toLocaleDateString()
: '-'}
</span>
),
},
],
[]
);
const table = useReactTable({
data: spans.items,
columns,
state: {
sorting,
expanded,
},
onSortingChange: setSorting,
onExpandedChange: setExpanded as any,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getExpandedRowModel: getExpandedRowModel(),
getRowCanExpand: () => true,
initialState: {
pagination: { pageSize: 10 },
},
});
const totalPages = Math.ceil(spans.total / spans.page_size);
// Render expanded row content
const renderExpandedRow = (row: Row<SpanItem>) => {
const span = row.original;
return (
<tr>
<td colSpan={columns.length} className="bg-gray-50 p-4">
<div className="space-y-3">
<div>
<span className="text-sm font-semibold text-gray-700">Full Text</span>
<p className="text-sm text-gray-800 mt-1 whitespace-pre-wrap">
{span.span_text}
</p>
</div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
<div>
<span className="font-semibold text-gray-700">Span ID</span>
<p className="text-gray-600 font-mono text-xs">{span.span_id}</p>
</div>
<div>
<span className="font-semibold text-gray-700">Review ID</span>
<p className="text-gray-600 font-mono text-xs">
{span.source_review_id || '-'}
</p>
</div>
<div>
<span className="font-semibold text-gray-700">Entity</span>
<p className="text-gray-600">{span.entity || '-'}</p>
</div>
<div>
<span className="font-semibold text-gray-700">Domain</span>
<p className="text-gray-600">
{span.urt_primary
? DOMAIN_LABELS[span.urt_primary[0]] || span.urt_primary[0]
: '-'}
</p>
</div>
</div>
{/* View Full Review Button */}
{span.source_review_id && (
<div className="pt-2">
<button
onClick={(e) => {
e.stopPropagation();
setSelectedReview({
reviewId: span.source_review_id!,
spanId: span.span_id,
});
}}
className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white text-sm font-semibold rounded-lg hover:bg-blue-700 transition-colors"
>
<FileText className="w-4 h-4" />
View Full Review
</button>
</div>
)}
</div>
</td>
</tr>
);
};
return (
<div className="bg-white rounded-xl p-6 shadow-md border-2 border-gray-300">
<div className="flex items-center justify-between mb-4">
<div>
<h3 className="text-xl font-bold text-gray-900">Classified Spans</h3>
<p className="text-sm text-gray-500">
{spans.total} total spans - Click row to expand
</p>
</div>
</div>
{spans.items.length === 0 ? (
<div className="flex items-center justify-center h-32 text-gray-500">
No spans found
</div>
) : (
<>
<div className="overflow-x-auto border-2 border-gray-200 rounded-lg">
<table className="w-full">
<thead className="bg-gray-50 border-b-2 border-gray-200">
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<th
key={header.id}
className="px-4 py-3 text-left text-gray-900"
>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</th>
))}
</tr>
))}
</thead>
<tbody className="divide-y divide-gray-200">
{table.getRowModel().rows.map((row) => (
<Fragment key={row.id}>
<tr
className="hover:bg-blue-50 cursor-pointer transition-colors"
onClick={() => row.toggleExpanded()}
>
{row.getVisibleCells().map((cell) => (
<td key={cell.id} className="px-4 py-3">
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</td>
))}
</tr>
{row.getIsExpanded() && renderExpandedRow(row)}
</Fragment>
))}
</tbody>
</table>
</div>
{/* Pagination */}
<div className="flex items-center justify-between mt-4">
<div className="text-sm text-gray-700 font-medium">
Page {spans.page} of {totalPages} ({spans.total} spans)
</div>
<div className="flex gap-2">
<button
onClick={() => onPageChange?.(spans.page - 1)}
disabled={spans.page <= 1}
className="px-3 py-2 border-2 border-gray-300 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50 font-semibold text-gray-900 flex items-center gap-1"
>
<ChevronLeft className="w-4 h-4" />
Previous
</button>
<button
onClick={() => onPageChange?.(spans.page + 1)}
disabled={spans.page >= totalPages}
className="px-3 py-2 border-2 border-gray-300 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50 font-semibold text-gray-900 flex items-center gap-1"
>
Next
<ChevronRight className="w-4 h-4" />
</button>
</div>
</div>
</>
)}
{/* Review Modal for drill-down */}
<ReviewModal
reviewId={selectedReview?.reviewId ?? null}
highlightSpanId={selectedReview?.spanId}
onClose={() => setSelectedReview(null)}
/>
</div>
);
}