feat(reviewiq): Redesign dashboard with user-friendly UX
- ExecutiveSummary: Add rating badge with emoji, AI narrative section, #1 Problem/#1 Strength cards, domain complaints with progress bars - SentimentPie: Replace pie chart with card-based design showing sentiment score, emoji indicators (😊😟😐🤔), percentages - IntensityHeatmap: Transform to Praise vs Complaints heatmap with friendly domain labels (👥 Staff, 💰 Pricing, etc.) - URTBarChart: Horizontal progress bars with emojis, health indicators - TimelineChart: Add view toggles (Sentiment/Volume/Rating), trend indicator, fix chronological order (oldest→newest left→right) - ReviewIQDashboard: Streamline from 11 sections to 5, remove redundancy Removed redundant components: - DomainScores (merged into ExecutiveSummary) - KPISection (stats in header) - RatingSimulator (in ExecutiveSummary) - StrengthsWeaknesses (in ExecutiveSummary) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
171
web/components/reviewiq/ReviewIQDashboard.tsx
Normal file
171
web/components/reviewiq/ReviewIQDashboard.tsx
Normal file
@@ -0,0 +1,171 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { RefreshCw, BarChart3 } from 'lucide-react';
|
||||
import { ReviewIQFilterProvider, useReviewIQFilters } from '@/contexts/ReviewIQFilterContext';
|
||||
import { useReviewIQAnalytics } from '@/hooks/useReviewIQAnalytics';
|
||||
import { FilterBar } from './FilterBar';
|
||||
import { DashboardSkeleton, DashboardError, DashboardEmpty } from './DashboardSkeleton';
|
||||
import { SentimentPie } from './charts/SentimentPie';
|
||||
import { IntensityHeatmap } from './charts/IntensityHeatmap';
|
||||
import { TimelineChart } from './charts/TimelineChart';
|
||||
import { IssuesTable } from './tables/IssuesTable';
|
||||
import { SpansTable } from './tables/SpansTable';
|
||||
import { ExecutiveSummary } from './insights/ExecutiveSummary';
|
||||
import { OpportunityMatrix } from './insights/OpportunityMatrix';
|
||||
import type { URTDomain } from './types';
|
||||
|
||||
interface ReviewIQDashboardProps {
|
||||
jobId?: string | null;
|
||||
businessId?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inner dashboard component that uses the filter context.
|
||||
*
|
||||
* Streamlined flow (no redundancy):
|
||||
* 1. Hero: Executive Summary (rating, AI insights, #1 problem/strength, top complaints)
|
||||
* 2. Explore: Sentiment + Category Heatmap (side by side)
|
||||
* 3. Action: Opportunity Matrix (what to fix)
|
||||
* 4. Trends: Timeline
|
||||
* 5. Deep Dive: Issues & Spans tables
|
||||
*/
|
||||
function ReviewIQDashboardInner({ jobId, businessId }: ReviewIQDashboardProps) {
|
||||
const { filters, setURTDomain } = useReviewIQFilters();
|
||||
const [issuesPage, setIssuesPage] = useState(1);
|
||||
const [spansPage, setSpansPage] = useState(1);
|
||||
|
||||
const { data, loading, error, refetch } = useReviewIQAnalytics({
|
||||
jobId,
|
||||
businessId,
|
||||
filters,
|
||||
issuesPage,
|
||||
issuesPageSize: 10,
|
||||
spansPage,
|
||||
spansPageSize: 10,
|
||||
});
|
||||
|
||||
const handleIssuesPageChange = (page: number) => setIssuesPage(page);
|
||||
const handleSpansPageChange = (page: number) => setSpansPage(page);
|
||||
|
||||
// No job selected
|
||||
if (!jobId && !businessId) {
|
||||
return <DashboardEmpty />;
|
||||
}
|
||||
|
||||
// Loading state
|
||||
if (loading && !data) {
|
||||
return <DashboardSkeleton />;
|
||||
}
|
||||
|
||||
// Error state
|
||||
if (error) {
|
||||
return <DashboardError message={error} onRetry={refetch} />;
|
||||
}
|
||||
|
||||
// No data
|
||||
if (!data) {
|
||||
return <DashboardEmpty />;
|
||||
}
|
||||
|
||||
// Handle domain click for filtering
|
||||
const handleDomainClick = (domain: URTDomain) => {
|
||||
setURTDomain(filters.urtDomain === domain ? null : domain);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* ═══════════════════════════════════════════════════════════════
|
||||
HEADER
|
||||
═══════════════════════════════════════════════════════════════ */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-xl">
|
||||
<BarChart3 className="w-6 h-6 text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">ReviewIQ Analytics</h1>
|
||||
<p className="text-sm text-gray-500">
|
||||
{data.overview.total_reviews.toLocaleString()} reviews • {data.overview.total_spans.toLocaleString()} insights extracted
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={refetch}
|
||||
disabled={loading}
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded-lg font-semibold hover:bg-blue-700 transition-colors flex items-center gap-2 disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
Refresh
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Active Filters Bar */}
|
||||
<FilterBar />
|
||||
|
||||
{/* ═══════════════════════════════════════════════════════════════
|
||||
SECTION 1: EXECUTIVE SUMMARY (Hero)
|
||||
Rating, AI summary, #1 Problem, #1 Strength, Top Complaints
|
||||
═══════════════════════════════════════════════════════════════ */}
|
||||
<ExecutiveSummary
|
||||
insights={data.insights}
|
||||
avgRating={data.overview.avg_rating}
|
||||
domainScores={data.domain_scores}
|
||||
onDomainClick={handleDomainClick}
|
||||
/>
|
||||
|
||||
{/* ═══════════════════════════════════════════════════════════════
|
||||
SECTION 2: EXPLORE (Sentiment + Categories)
|
||||
Side-by-side: How customers feel + What they talk about
|
||||
═══════════════════════════════════════════════════════════════ */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<SentimentPie data={data.sentiment.distribution} />
|
||||
<IntensityHeatmap data={data.urt.domains} />
|
||||
</div>
|
||||
|
||||
{/* ═══════════════════════════════════════════════════════════════
|
||||
SECTION 3: ACTION (Opportunity Matrix)
|
||||
What to fix - prioritized by impact vs effort
|
||||
═══════════════════════════════════════════════════════════════ */}
|
||||
<OpportunityMatrix matrix={data.insights.opportunity_matrix} />
|
||||
|
||||
{/* ═══════════════════════════════════════════════════════════════
|
||||
SECTION 4: TRENDS (Timeline)
|
||||
How things change over time
|
||||
═══════════════════════════════════════════════════════════════ */}
|
||||
<TimelineChart data={data.timeline} />
|
||||
|
||||
{/* ═══════════════════════════════════════════════════════════════
|
||||
SECTION 5: DEEP DIVE (Tables)
|
||||
Detailed issues and individual mentions
|
||||
═══════════════════════════════════════════════════════════════ */}
|
||||
<div className="grid lg:grid-cols-2 gap-6">
|
||||
<IssuesTable issues={data.issues} onPageChange={handleIssuesPageChange} />
|
||||
<SpansTable spans={data.spans} onPageChange={handleSpansPageChange} />
|
||||
</div>
|
||||
|
||||
{/* Debug Info (dev only) */}
|
||||
{process.env.NODE_ENV === 'development' && (
|
||||
<details className="bg-gray-100 rounded-lg p-4 text-sm">
|
||||
<summary className="cursor-pointer font-semibold text-gray-700">
|
||||
Debug: Filters Applied
|
||||
</summary>
|
||||
<pre className="mt-2 bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto">
|
||||
{JSON.stringify(data.filters_applied, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Main ReviewIQ Dashboard with filter context provider.
|
||||
*/
|
||||
export function ReviewIQDashboard({ jobId, businessId }: ReviewIQDashboardProps) {
|
||||
return (
|
||||
<ReviewIQFilterProvider>
|
||||
<ReviewIQDashboardInner jobId={jobId} businessId={businessId} />
|
||||
</ReviewIQFilterProvider>
|
||||
);
|
||||
}
|
||||
305
web/components/reviewiq/charts/IntensityHeatmap.tsx
Normal file
305
web/components/reviewiq/charts/IntensityHeatmap.tsx
Normal file
@@ -0,0 +1,305 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo } from 'react';
|
||||
import { Filter, ThumbsUp, ThumbsDown, TrendingUp, TrendingDown, Minus } from 'lucide-react';
|
||||
import type { URTDomainPoint, URTDomain, Sentiment } from '../types';
|
||||
import { useReviewIQFilters } from '@/contexts/ReviewIQFilterContext';
|
||||
|
||||
interface SentimentHeatmapProps {
|
||||
data: URTDomainPoint[];
|
||||
}
|
||||
|
||||
// User-friendly domain config with emojis and descriptions
|
||||
const DOMAIN_CONFIG: Record<string, {
|
||||
emoji: string;
|
||||
label: string;
|
||||
description: string;
|
||||
}> = {
|
||||
P: { emoji: '👥', label: 'Staff & Service', description: 'How staff treats customers' },
|
||||
V: { emoji: '💰', label: 'Pricing & Value', description: 'Price, fees, and value for money' },
|
||||
J: { emoji: '⏱️', label: 'Speed & Process', description: 'Wait times and procedures' },
|
||||
O: { emoji: '🛍️', label: 'Product Quality', description: 'Quality of goods/services' },
|
||||
A: { emoji: '📍', label: 'Availability', description: 'Hours, location, accessibility' },
|
||||
E: { emoji: '🏢', label: 'Facilities', description: 'Cleanliness, comfort, ambiance' },
|
||||
R: { emoji: '🤝', label: 'Trust & Ethics', description: 'Honesty, reliability, fairness' },
|
||||
};
|
||||
|
||||
// Ordered domains by typical business priority
|
||||
const DOMAIN_ORDER = ['P', 'V', 'J', 'O', 'A', 'E', 'R'];
|
||||
|
||||
// Color scales
|
||||
const getPositiveColor = (value: number, max: number): string => {
|
||||
if (max === 0 || value === 0) return '#f3f4f6';
|
||||
const intensity = value / max;
|
||||
if (intensity < 0.25) return '#dcfce7'; // Light green
|
||||
if (intensity < 0.5) return '#86efac';
|
||||
if (intensity < 0.75) return '#22c55e';
|
||||
return '#15803d'; // Dark green
|
||||
};
|
||||
|
||||
const getNegativeColor = (value: number, max: number): string => {
|
||||
if (max === 0 || value === 0) return '#f3f4f6';
|
||||
const intensity = value / max;
|
||||
if (intensity < 0.25) return '#fee2e2'; // Light red
|
||||
if (intensity < 0.5) return '#fca5a5';
|
||||
if (intensity < 0.75) return '#ef4444';
|
||||
return '#b91c1c'; // Dark red
|
||||
};
|
||||
|
||||
/**
|
||||
* Sentiment Heatmap - Shows Praise vs Complaints by Domain.
|
||||
* User-friendly design with emojis and clear labels.
|
||||
* Click to filter by domain and sentiment.
|
||||
*/
|
||||
export function IntensityHeatmap({ data }: SentimentHeatmapProps) {
|
||||
const { filters, setURTDomain, toggleSentiment } = useReviewIQFilters();
|
||||
|
||||
// Check if cross-filters are active
|
||||
const hasSentimentFilter = filters.sentiment.length > 0;
|
||||
const hasDomainFilter = filters.urtDomain !== null;
|
||||
const hasCrossFilter = hasSentimentFilter || hasDomainFilter;
|
||||
|
||||
// Process and sort data
|
||||
const processedData = useMemo(() => {
|
||||
// Create lookup map
|
||||
const lookup = new Map<string, URTDomainPoint>();
|
||||
let maxPositive = 0;
|
||||
let maxNegative = 0;
|
||||
|
||||
data.forEach((d) => {
|
||||
lookup.set(d.domain, d);
|
||||
if (d.positive_count > maxPositive) maxPositive = d.positive_count;
|
||||
if (d.negative_count > maxNegative) maxNegative = d.negative_count;
|
||||
});
|
||||
|
||||
// Sort by domain order, then build rows
|
||||
const rows = DOMAIN_ORDER
|
||||
.filter(domain => lookup.has(domain))
|
||||
.map(domain => {
|
||||
const d = lookup.get(domain)!;
|
||||
const total = d.positive_count + d.negative_count + d.neutral_count;
|
||||
const positiveRatio = total > 0 ? d.positive_count / total : 0;
|
||||
const negativeRatio = total > 0 ? d.negative_count / total : 0;
|
||||
|
||||
// Determine trend indicator
|
||||
let trend: 'up' | 'down' | 'neutral' = 'neutral';
|
||||
if (positiveRatio > 0.6) trend = 'up';
|
||||
else if (negativeRatio > 0.4) trend = 'down';
|
||||
|
||||
return {
|
||||
domain: d.domain,
|
||||
config: DOMAIN_CONFIG[d.domain] || {
|
||||
emoji: '📊',
|
||||
label: d.domain_name || d.domain,
|
||||
description: ''
|
||||
},
|
||||
positive: d.positive_count,
|
||||
negative: d.negative_count,
|
||||
total,
|
||||
positiveRatio,
|
||||
negativeRatio,
|
||||
trend,
|
||||
};
|
||||
});
|
||||
|
||||
return { rows, maxPositive, maxNegative };
|
||||
}, [data]);
|
||||
|
||||
const handleCellClick = (domain: string, sentiment: 'positive' | 'negative') => {
|
||||
setURTDomain(domain as URTDomain);
|
||||
// Clear other sentiments and set the clicked one
|
||||
if (!filters.sentiment.includes(sentiment)) {
|
||||
toggleSentiment(sentiment);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDomainClick = (domain: string) => {
|
||||
setURTDomain(domain as URTDomain);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`bg-white rounded-xl p-6 shadow-md transition-all ${
|
||||
hasCrossFilter
|
||||
? 'border-2 border-purple-400 ring-1 ring-purple-200'
|
||||
: 'border-2 border-gray-300 hover:border-blue-400'
|
||||
}`}>
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div>
|
||||
<h3 className="text-lg font-bold text-gray-900">Feedback by Category</h3>
|
||||
<p className="text-sm text-gray-500 mt-1">Click any cell to filter reviews</p>
|
||||
</div>
|
||||
{hasCrossFilter && (
|
||||
<div className="flex items-center gap-1 text-xs text-purple-600 bg-purple-50 px-2 py-1 rounded-full">
|
||||
<Filter className="w-3 h-3" />
|
||||
<span>Filtered</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{data.length === 0 ? (
|
||||
<div className="flex items-center justify-center h-64 text-gray-500">
|
||||
No feedback data available
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="p-2 text-left text-sm font-bold text-gray-700 w-1/2">
|
||||
Category
|
||||
</th>
|
||||
<th className="p-2 text-center text-sm font-bold text-gray-700">
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
<ThumbsUp className="w-4 h-4 text-green-600" />
|
||||
<span className="text-green-700">Praise</span>
|
||||
</div>
|
||||
</th>
|
||||
<th className="p-2 text-center text-sm font-bold text-gray-700">
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
<ThumbsDown className="w-4 h-4 text-red-600" />
|
||||
<span className="text-red-700">Complaints</span>
|
||||
</div>
|
||||
</th>
|
||||
<th className="p-2 text-center text-sm font-bold text-gray-500 w-16">
|
||||
Health
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{processedData.rows.map((row) => {
|
||||
const isDomainActive = filters.urtDomain === row.domain;
|
||||
const isPositiveActive = isDomainActive && filters.sentiment.includes('positive');
|
||||
const isNegativeActive = isDomainActive && filters.sentiment.includes('negative');
|
||||
|
||||
return (
|
||||
<tr
|
||||
key={row.domain}
|
||||
className={`border-t border-gray-100 transition-colors ${
|
||||
isDomainActive ? 'bg-blue-50' : 'hover:bg-gray-50'
|
||||
}`}
|
||||
>
|
||||
{/* Domain Label */}
|
||||
<td className="p-2">
|
||||
<button
|
||||
onClick={() => handleDomainClick(row.domain)}
|
||||
className="flex items-center gap-2 text-left group w-full"
|
||||
>
|
||||
<span className="text-xl">{row.config.emoji}</span>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-semibold text-gray-900 group-hover:text-blue-600 transition-colors">
|
||||
{row.config.label}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 truncate">
|
||||
{row.config.description}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</td>
|
||||
|
||||
{/* Praise Cell */}
|
||||
<td className="p-1.5">
|
||||
<button
|
||||
onClick={() => handleCellClick(row.domain, 'positive')}
|
||||
className={`
|
||||
w-full h-14 rounded-lg text-sm font-bold
|
||||
transition-all hover:scale-105 hover:shadow-md
|
||||
flex flex-col items-center justify-center
|
||||
${isPositiveActive ? 'ring-2 ring-green-500 ring-offset-2' : ''}
|
||||
`}
|
||||
style={{
|
||||
backgroundColor: getPositiveColor(row.positive, processedData.maxPositive),
|
||||
color: row.positive > processedData.maxPositive * 0.5 ? 'white' : '#166534',
|
||||
}}
|
||||
title={`${row.positive} positive mentions (${Math.round(row.positiveRatio * 100)}%)`}
|
||||
>
|
||||
<span className="text-lg">{row.positive > 0 ? row.positive : '-'}</span>
|
||||
{row.positive > 0 && (
|
||||
<span className="text-xs opacity-75">
|
||||
{Math.round(row.positiveRatio * 100)}%
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</td>
|
||||
|
||||
{/* Complaints Cell */}
|
||||
<td className="p-1.5">
|
||||
<button
|
||||
onClick={() => handleCellClick(row.domain, 'negative')}
|
||||
className={`
|
||||
w-full h-14 rounded-lg text-sm font-bold
|
||||
transition-all hover:scale-105 hover:shadow-md
|
||||
flex flex-col items-center justify-center
|
||||
${isNegativeActive ? 'ring-2 ring-red-500 ring-offset-2' : ''}
|
||||
`}
|
||||
style={{
|
||||
backgroundColor: getNegativeColor(row.negative, processedData.maxNegative),
|
||||
color: row.negative > processedData.maxNegative * 0.5 ? 'white' : '#991b1b',
|
||||
}}
|
||||
title={`${row.negative} negative mentions (${Math.round(row.negativeRatio * 100)}%)`}
|
||||
>
|
||||
<span className="text-lg">{row.negative > 0 ? row.negative : '-'}</span>
|
||||
{row.negative > 0 && (
|
||||
<span className="text-xs opacity-75">
|
||||
{Math.round(row.negativeRatio * 100)}%
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</td>
|
||||
|
||||
{/* Health Indicator */}
|
||||
<td className="p-2 text-center">
|
||||
<div className="flex items-center justify-center">
|
||||
{row.trend === 'up' && (
|
||||
<div className="flex items-center gap-1 text-green-600" title="Mostly positive feedback">
|
||||
<TrendingUp className="w-5 h-5" />
|
||||
</div>
|
||||
)}
|
||||
{row.trend === 'down' && (
|
||||
<div className="flex items-center gap-1 text-red-600" title="Needs attention">
|
||||
<TrendingDown className="w-5 h-5" />
|
||||
</div>
|
||||
)}
|
||||
{row.trend === 'neutral' && (
|
||||
<div className="flex items-center gap-1 text-gray-400" title="Mixed feedback">
|
||||
<Minus className="w-5 h-5" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{/* Legend */}
|
||||
<div className="flex items-center justify-between mt-4 pt-4 border-t border-gray-100">
|
||||
<div className="flex items-center gap-4 text-xs text-gray-600">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium">Praise scale:</span>
|
||||
<div className="flex gap-0.5">
|
||||
<div className="w-4 h-3 rounded" style={{ backgroundColor: '#dcfce7' }} />
|
||||
<div className="w-4 h-3 rounded" style={{ backgroundColor: '#86efac' }} />
|
||||
<div className="w-4 h-3 rounded" style={{ backgroundColor: '#22c55e' }} />
|
||||
<div className="w-4 h-3 rounded" style={{ backgroundColor: '#15803d' }} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium">Complaints scale:</span>
|
||||
<div className="flex gap-0.5">
|
||||
<div className="w-4 h-3 rounded" style={{ backgroundColor: '#fee2e2' }} />
|
||||
<div className="w-4 h-3 rounded" style={{ backgroundColor: '#fca5a5' }} />
|
||||
<div className="w-4 h-3 rounded" style={{ backgroundColor: '#ef4444' }} />
|
||||
<div className="w-4 h-3 rounded" style={{ backgroundColor: '#b91c1c' }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">
|
||||
<TrendingDown className="w-3 h-3 inline text-red-500" /> = needs attention
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
273
web/components/reviewiq/charts/SentimentPie.tsx
Normal file
273
web/components/reviewiq/charts/SentimentPie.tsx
Normal file
@@ -0,0 +1,273 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo } from 'react';
|
||||
import { X, Filter, Smile, Frown, Meh, AlertTriangle } from 'lucide-react';
|
||||
import type { SentimentDataPoint, Sentiment } from '../types';
|
||||
import { DOMAIN_LABELS } from '../types';
|
||||
import { useReviewIQFilters } from '@/contexts/ReviewIQFilterContext';
|
||||
|
||||
interface SentimentPieProps {
|
||||
data: SentimentDataPoint[];
|
||||
}
|
||||
|
||||
// User-friendly sentiment config
|
||||
const SENTIMENT_CONFIG: Record<string, {
|
||||
emoji: string;
|
||||
icon: typeof Smile;
|
||||
label: string;
|
||||
description: string;
|
||||
color: string;
|
||||
bgColor: string;
|
||||
borderColor: string;
|
||||
}> = {
|
||||
'V+': {
|
||||
emoji: '😊',
|
||||
icon: Smile,
|
||||
label: 'Happy',
|
||||
description: 'Positive experiences',
|
||||
color: '#22c55e',
|
||||
bgColor: '#dcfce7',
|
||||
borderColor: '#86efac',
|
||||
},
|
||||
'V-': {
|
||||
emoji: '😟',
|
||||
icon: Frown,
|
||||
label: 'Unhappy',
|
||||
description: 'Negative experiences',
|
||||
color: '#ef4444',
|
||||
bgColor: '#fee2e2',
|
||||
borderColor: '#fca5a5',
|
||||
},
|
||||
'V0': {
|
||||
emoji: '😐',
|
||||
icon: Meh,
|
||||
label: 'Neutral',
|
||||
description: 'Factual mentions',
|
||||
color: '#eab308',
|
||||
bgColor: '#fef9c3',
|
||||
borderColor: '#fde047',
|
||||
},
|
||||
'V±': {
|
||||
emoji: '🤔',
|
||||
icon: AlertTriangle,
|
||||
label: 'Mixed',
|
||||
description: 'Both good & bad',
|
||||
color: '#f97316',
|
||||
bgColor: '#ffedd5',
|
||||
borderColor: '#fdba74',
|
||||
},
|
||||
};
|
||||
|
||||
// Map valence codes to sentiment filter values
|
||||
const valenceToSentiment: Record<string, Sentiment | null> = {
|
||||
'V+': 'positive',
|
||||
'V0': 'neutral',
|
||||
'V-': 'negative',
|
||||
'V±': 'negative', // Mixed is treated as negative for filtering
|
||||
};
|
||||
|
||||
// Display order
|
||||
const SENTIMENT_ORDER = ['V+', 'V-', 'V0', 'V±'];
|
||||
|
||||
/**
|
||||
* Sentiment Overview - Visual cards showing how customers feel.
|
||||
* User-friendly design with emojis and clear numbers.
|
||||
* Click to filter by sentiment.
|
||||
*/
|
||||
export function SentimentPie({ data }: SentimentPieProps) {
|
||||
const { filters, toggleSentiment } = useReviewIQFilters();
|
||||
|
||||
// Process data
|
||||
const processedData = useMemo(() => {
|
||||
const lookup = new Map<string, SentimentDataPoint>();
|
||||
let totalReviews = 0;
|
||||
let totalMentions = 0;
|
||||
|
||||
data.forEach((d) => {
|
||||
lookup.set(d.valence, d);
|
||||
totalReviews += d.review_count;
|
||||
totalMentions += d.count;
|
||||
});
|
||||
|
||||
// Build cards in order
|
||||
const cards = SENTIMENT_ORDER
|
||||
.filter(valence => lookup.has(valence))
|
||||
.map(valence => {
|
||||
const d = lookup.get(valence)!;
|
||||
const config = SENTIMENT_CONFIG[valence];
|
||||
|
||||
return {
|
||||
valence,
|
||||
config,
|
||||
reviewCount: d.review_count,
|
||||
mentionCount: d.count,
|
||||
percentage: d.percentage,
|
||||
};
|
||||
});
|
||||
|
||||
// Calculate overall sentiment score (0-100)
|
||||
const positive = lookup.get('V+');
|
||||
const negative = lookup.get('V-');
|
||||
const posCount = positive?.review_count || 0;
|
||||
const negCount = negative?.review_count || 0;
|
||||
const sentimentScore = totalReviews > 0
|
||||
? Math.round(((posCount - negCount) / totalReviews + 1) * 50)
|
||||
: 50;
|
||||
|
||||
return { cards, totalReviews, totalMentions, sentimentScore };
|
||||
}, [data]);
|
||||
|
||||
const handleClick = (valence: string) => {
|
||||
const sentiment = valenceToSentiment[valence];
|
||||
if (sentiment) {
|
||||
toggleSentiment(sentiment);
|
||||
}
|
||||
};
|
||||
|
||||
const isFiltering = filters.sentiment.length > 0;
|
||||
const hasDomainFilter = filters.urtDomain !== null;
|
||||
|
||||
// Determine sentiment indicator color
|
||||
const getScoreColor = () => {
|
||||
if (processedData.sentimentScore >= 60) return 'text-green-600';
|
||||
if (processedData.sentimentScore >= 40) return 'text-yellow-600';
|
||||
return 'text-red-600';
|
||||
};
|
||||
|
||||
const getScoreEmoji = () => {
|
||||
if (processedData.sentimentScore >= 70) return '🎉';
|
||||
if (processedData.sentimentScore >= 55) return '👍';
|
||||
if (processedData.sentimentScore >= 45) return '😐';
|
||||
if (processedData.sentimentScore >= 30) return '😕';
|
||||
return '😰';
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`bg-white rounded-xl p-6 shadow-md transition-all ${
|
||||
isFiltering
|
||||
? 'border-3 border-blue-500 ring-2 ring-blue-200'
|
||||
: hasDomainFilter
|
||||
? 'border-2 border-purple-400 ring-1 ring-purple-200'
|
||||
: 'border-2 border-gray-300 hover:border-blue-400'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div>
|
||||
<h3 className="text-lg font-bold text-gray-900">How Customers Feel</h3>
|
||||
<p className="text-sm text-gray-500 mt-1">
|
||||
{processedData.totalReviews.toLocaleString()} reviews analyzed
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{hasDomainFilter && !isFiltering && (
|
||||
<span className="flex items-center gap-1 text-xs text-purple-600 bg-purple-50 px-2 py-1 rounded-full">
|
||||
<Filter className="w-3 h-3" />
|
||||
{DOMAIN_LABELS[filters.urtDomain!]}
|
||||
</span>
|
||||
)}
|
||||
{isFiltering && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-blue-700 font-medium">
|
||||
{filters.sentiment.join(', ')}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => {
|
||||
filters.sentiment.forEach((s) => toggleSentiment(s));
|
||||
}}
|
||||
className="p-1 hover:bg-gray-200 rounded-full transition-colors"
|
||||
title="Clear filter"
|
||||
>
|
||||
<X className="w-4 h-4 text-gray-600" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{processedData.cards.length === 0 ? (
|
||||
<div className="flex items-center justify-center h-64 text-gray-500">
|
||||
No sentiment data available
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Overall Sentiment Score */}
|
||||
<div className="flex items-center justify-center mb-4 p-3 bg-gray-50 rounded-lg">
|
||||
<div className="text-center">
|
||||
<div className="text-3xl mb-1">{getScoreEmoji()}</div>
|
||||
<div className={`text-2xl font-bold ${getScoreColor()}`}>
|
||||
{processedData.sentimentScore}%
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">Sentiment Score</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Sentiment Cards Grid */}
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{processedData.cards.map((card) => {
|
||||
const sentiment = valenceToSentiment[card.valence];
|
||||
const isActive = sentiment && filters.sentiment.includes(sentiment);
|
||||
const Icon = card.config.icon;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={card.valence}
|
||||
onClick={() => handleClick(card.valence)}
|
||||
className={`p-3 rounded-xl transition-all text-left ${
|
||||
isActive
|
||||
? 'ring-2 ring-blue-500 ring-offset-2'
|
||||
: 'hover:scale-105 hover:shadow-md'
|
||||
}`}
|
||||
style={{
|
||||
backgroundColor: card.config.bgColor,
|
||||
borderWidth: '2px',
|
||||
borderColor: card.config.borderColor,
|
||||
}}
|
||||
>
|
||||
<div className="flex items-start justify-between">
|
||||
<div>
|
||||
<div className="text-2xl mb-1">{card.config.emoji}</div>
|
||||
<div
|
||||
className="font-bold text-sm"
|
||||
style={{ color: card.config.color }}
|
||||
>
|
||||
{card.config.label}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<div
|
||||
className="text-xl font-bold"
|
||||
style={{ color: card.config.color }}
|
||||
>
|
||||
{card.percentage.toFixed(0)}%
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">
|
||||
{card.reviewCount} reviews
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Mini progress bar */}
|
||||
<div className="mt-2 h-1.5 bg-white/50 rounded-full overflow-hidden">
|
||||
<div
|
||||
className="h-full rounded-full transition-all duration-500"
|
||||
style={{
|
||||
width: `${card.percentage}%`,
|
||||
backgroundColor: card.config.color,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Tip */}
|
||||
<div className="mt-4 pt-3 border-t border-gray-100 text-center text-xs text-gray-500">
|
||||
Click any card to filter reviews by sentiment
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
488
web/components/reviewiq/charts/TimelineChart.tsx
Normal file
488
web/components/reviewiq/charts/TimelineChart.tsx
Normal file
@@ -0,0 +1,488 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useMemo } from 'react';
|
||||
import {
|
||||
ComposedChart,
|
||||
Bar,
|
||||
Line,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
ResponsiveContainer,
|
||||
Brush,
|
||||
Area,
|
||||
ReferenceLine,
|
||||
} from 'recharts';
|
||||
import { X, TrendingUp, TrendingDown, Minus, Calendar, Filter } from 'lucide-react';
|
||||
import type { TimelinePoint, TimeRange } from '../types';
|
||||
import { DOMAIN_LABELS } from '../types';
|
||||
import { useReviewIQFilters } from '@/contexts/ReviewIQFilterContext';
|
||||
|
||||
interface TimelineChartProps {
|
||||
data: TimelinePoint[];
|
||||
}
|
||||
|
||||
type ViewMode = 'sentiment' | 'volume' | 'rating';
|
||||
|
||||
const VIEW_OPTIONS: { value: ViewMode; emoji: string; label: string; description: string }[] = [
|
||||
{ value: 'sentiment', emoji: '😊', label: 'Sentiment', description: 'Positive vs Negative over time' },
|
||||
{ value: 'volume', emoji: '📊', label: 'Volume', description: 'Review & mention counts' },
|
||||
{ value: 'rating', emoji: '⭐', label: 'Rating', description: 'Average rating trend' },
|
||||
];
|
||||
|
||||
const TIME_RANGE_OPTIONS: { value: TimeRange; label: string; description: string }[] = [
|
||||
{ value: '7d', label: '7D', description: 'Last 7 days' },
|
||||
{ value: '14d', label: '2W', description: 'Last 2 weeks' },
|
||||
{ value: '30d', label: '1M', description: 'Last month' },
|
||||
{ value: '90d', label: '3M', description: 'Last 3 months' },
|
||||
{ value: '1y', label: '1Y', description: 'Last year' },
|
||||
{ value: 'all', label: 'All', description: 'All time' },
|
||||
];
|
||||
|
||||
/**
|
||||
* Timeline Chart - Shows trends over time.
|
||||
* User-friendly design with view toggles and interactive brush.
|
||||
* Responds to domain/sentiment filters.
|
||||
*/
|
||||
export function TimelineChart({ data }: TimelineChartProps) {
|
||||
const { filters, setTimeRange, setBrushRange } = useReviewIQFilters();
|
||||
const [viewMode, setViewMode] = useState<ViewMode>('sentiment');
|
||||
const [localBrushRange, setLocalBrushRange] = useState<{
|
||||
startIndex: number;
|
||||
endIndex: number;
|
||||
} | null>(null);
|
||||
|
||||
// Sort data chronologically (oldest first, most recent on right)
|
||||
const sortedData = useMemo(() => {
|
||||
return [...data].sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
|
||||
}, [data]);
|
||||
|
||||
// Calculate summary stats
|
||||
const stats = useMemo(() => {
|
||||
if (sortedData.length === 0) return null;
|
||||
|
||||
const totalReviews = sortedData.reduce((sum, d) => sum + d.review_count, 0);
|
||||
const totalPositive = sortedData.reduce((sum, d) => sum + d.positive_count, 0);
|
||||
const totalNegative = sortedData.reduce((sum, d) => sum + d.negative_count, 0);
|
||||
const avgRating = sortedData.reduce((sum, d) => sum + (d.avg_rating || 0), 0) / sortedData.length;
|
||||
|
||||
// Calculate trend (compare last 30% vs first 30%)
|
||||
const splitPoint = Math.floor(sortedData.length * 0.3);
|
||||
const earlyData = sortedData.slice(0, splitPoint);
|
||||
const recentData = sortedData.slice(-splitPoint);
|
||||
|
||||
const earlyPositiveRatio = earlyData.length > 0
|
||||
? earlyData.reduce((sum, d) => sum + d.positive_count, 0) /
|
||||
Math.max(1, earlyData.reduce((sum, d) => sum + d.positive_count + d.negative_count, 0))
|
||||
: 0;
|
||||
const recentPositiveRatio = recentData.length > 0
|
||||
? recentData.reduce((sum, d) => sum + d.positive_count, 0) /
|
||||
Math.max(1, recentData.reduce((sum, d) => sum + d.positive_count + d.negative_count, 0))
|
||||
: 0;
|
||||
|
||||
const trendDirection = recentPositiveRatio > earlyPositiveRatio + 0.05
|
||||
? 'improving'
|
||||
: recentPositiveRatio < earlyPositiveRatio - 0.05
|
||||
? 'declining'
|
||||
: 'stable';
|
||||
|
||||
return {
|
||||
totalReviews,
|
||||
totalPositive,
|
||||
totalNegative,
|
||||
avgRating,
|
||||
positiveRatio: totalReviews > 0 ? (totalPositive / (totalPositive + totalNegative)) * 100 : 0,
|
||||
trendDirection,
|
||||
dateRange: {
|
||||
start: sortedData[0]?.date,
|
||||
end: sortedData[sortedData.length - 1]?.date,
|
||||
},
|
||||
};
|
||||
}, [sortedData]);
|
||||
|
||||
// Handle brush change
|
||||
const handleBrushChange = (range: { startIndex?: number; endIndex?: number }) => {
|
||||
if (
|
||||
range &&
|
||||
typeof range.startIndex === 'number' &&
|
||||
typeof range.endIndex === 'number'
|
||||
) {
|
||||
setLocalBrushRange({ startIndex: range.startIndex, endIndex: range.endIndex });
|
||||
|
||||
// Only set filter if not full range
|
||||
if (range.startIndex !== 0 || range.endIndex !== sortedData.length - 1) {
|
||||
const startDate = sortedData[range.startIndex]?.date;
|
||||
const endDate = sortedData[range.endIndex]?.date;
|
||||
if (startDate && endDate) {
|
||||
setBrushRange({ start: startDate, end: endDate });
|
||||
}
|
||||
} else {
|
||||
setBrushRange(null);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const clearBrushRange = () => {
|
||||
setLocalBrushRange({ startIndex: 0, endIndex: sortedData.length - 1 });
|
||||
setBrushRange(null);
|
||||
};
|
||||
|
||||
const hasBrushFilter = filters.brushRange !== null;
|
||||
const hasDomainFilter = filters.urtDomain !== null;
|
||||
const hasSentimentFilter = filters.sentiment.length > 0;
|
||||
const hasAnyFilter = hasBrushFilter || hasDomainFilter || hasSentimentFilter;
|
||||
|
||||
// Format date for display
|
||||
const formatDate = (dateStr: string) => {
|
||||
const date = new Date(dateStr);
|
||||
return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`bg-white rounded-xl p-6 shadow-md transition-all ${
|
||||
hasBrushFilter
|
||||
? 'border-3 border-blue-500 ring-2 ring-blue-200'
|
||||
: hasAnyFilter
|
||||
? 'border-2 border-purple-400 ring-1 ring-purple-200'
|
||||
: 'border-2 border-gray-300 hover:border-blue-400'
|
||||
}`}
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4 mb-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="p-2 bg-blue-100 rounded-lg">
|
||||
<Calendar className="w-6 h-6 text-blue-600" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-bold text-gray-900">Trends Over Time</h3>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
{stats ? (
|
||||
<>
|
||||
{stats.totalReviews.toLocaleString()} reviews
|
||||
{stats.dateRange.start && stats.dateRange.end && (
|
||||
<span className="text-gray-400">
|
||||
{' '}• {formatDate(stats.dateRange.start)} - {formatDate(stats.dateRange.end)}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
'No data available'
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Controls */}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{/* Active filters indicator */}
|
||||
{(hasDomainFilter || hasSentimentFilter) && (
|
||||
<div className="flex items-center gap-1 text-xs text-purple-600 bg-purple-50 px-2 py-1 rounded-full">
|
||||
<Filter className="w-3 h-3" />
|
||||
{hasDomainFilter && DOMAIN_LABELS[filters.urtDomain!]}
|
||||
{hasDomainFilter && hasSentimentFilter && ' + '}
|
||||
{hasSentimentFilter && filters.sentiment.join(', ')}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Clear brush button */}
|
||||
{hasBrushFilter && (
|
||||
<button
|
||||
onClick={clearBrushRange}
|
||||
className="px-3 py-1.5 text-sm font-semibold rounded-lg bg-red-100 text-red-700 hover:bg-red-200 transition-all flex items-center gap-1"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
Clear Range
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Time range buttons */}
|
||||
<div className="flex items-center bg-gray-100 rounded-lg p-1">
|
||||
{TIME_RANGE_OPTIONS.map((opt) => (
|
||||
<button
|
||||
key={opt.value}
|
||||
onClick={() => {
|
||||
setTimeRange(opt.value);
|
||||
clearBrushRange();
|
||||
}}
|
||||
className={`px-2.5 py-1 text-xs font-semibold rounded-md transition-all ${
|
||||
filters.timeRange === opt.value && !hasBrushFilter
|
||||
? 'bg-blue-600 text-white shadow-sm'
|
||||
: 'text-gray-600 hover:bg-gray-200'
|
||||
}`}
|
||||
title={opt.description}
|
||||
>
|
||||
{opt.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* View Mode Toggle */}
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
{VIEW_OPTIONS.map((opt) => (
|
||||
<button
|
||||
key={opt.value}
|
||||
onClick={() => setViewMode(opt.value)}
|
||||
className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-semibold transition-all ${
|
||||
viewMode === opt.value
|
||||
? 'bg-blue-100 text-blue-700 ring-2 ring-blue-300'
|
||||
: 'bg-gray-50 text-gray-600 hover:bg-gray-100'
|
||||
}`}
|
||||
title={opt.description}
|
||||
>
|
||||
<span className="text-lg">{opt.emoji}</span>
|
||||
<span>{opt.label}</span>
|
||||
</button>
|
||||
))}
|
||||
|
||||
{/* Trend indicator */}
|
||||
{stats && (
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<span className="text-sm text-gray-500">Trend:</span>
|
||||
{stats.trendDirection === 'improving' && (
|
||||
<div className="flex items-center gap-1 text-green-600 bg-green-50 px-2 py-1 rounded-full">
|
||||
<TrendingUp className="w-4 h-4" />
|
||||
<span className="text-xs font-semibold">Improving</span>
|
||||
</div>
|
||||
)}
|
||||
{stats.trendDirection === 'declining' && (
|
||||
<div className="flex items-center gap-1 text-red-600 bg-red-50 px-2 py-1 rounded-full">
|
||||
<TrendingDown className="w-4 h-4" />
|
||||
<span className="text-xs font-semibold">Declining</span>
|
||||
</div>
|
||||
)}
|
||||
{stats.trendDirection === 'stable' && (
|
||||
<div className="flex items-center gap-1 text-gray-600 bg-gray-100 px-2 py-1 rounded-full">
|
||||
<Minus className="w-4 h-4" />
|
||||
<span className="text-xs font-semibold">Stable</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{sortedData.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center h-80 text-gray-500">
|
||||
<Calendar className="w-12 h-12 text-gray-300 mb-2" />
|
||||
<span>No timeline data available</span>
|
||||
</div>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height={350}>
|
||||
<ComposedChart
|
||||
data={sortedData}
|
||||
margin={{ top: 10, right: 30, left: 0, bottom: 30 }}
|
||||
>
|
||||
<defs>
|
||||
<linearGradient id="positiveGradient" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#22c55e" stopOpacity={0.8} />
|
||||
<stop offset="95%" stopColor="#22c55e" stopOpacity={0.1} />
|
||||
</linearGradient>
|
||||
<linearGradient id="negativeGradient" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#ef4444" stopOpacity={0.8} />
|
||||
<stop offset="95%" stopColor="#ef4444" stopOpacity={0.1} />
|
||||
</linearGradient>
|
||||
<linearGradient id="volumeGradient" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#3b82f6" stopOpacity={0.8} />
|
||||
<stop offset="95%" stopColor="#3b82f6" stopOpacity={0.1} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" vertical={false} />
|
||||
|
||||
<XAxis
|
||||
dataKey="date"
|
||||
tick={{ fill: '#6b7280', fontSize: 11 }}
|
||||
tickLine={false}
|
||||
axisLine={{ stroke: '#e5e7eb' }}
|
||||
tickFormatter={formatDate}
|
||||
interval="preserveStartEnd"
|
||||
/>
|
||||
|
||||
{/* Sentiment View */}
|
||||
{viewMode === 'sentiment' && (
|
||||
<>
|
||||
<YAxis
|
||||
tick={{ fill: '#6b7280', fontSize: 11 }}
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
label={{
|
||||
value: 'Mentions',
|
||||
angle: -90,
|
||||
position: 'insideLeft',
|
||||
fill: '#9ca3af',
|
||||
fontSize: 12,
|
||||
}}
|
||||
/>
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="positive_count"
|
||||
stackId="sentiment"
|
||||
fill="url(#positiveGradient)"
|
||||
stroke="#22c55e"
|
||||
strokeWidth={2}
|
||||
name="😊 Positive"
|
||||
/>
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="negative_count"
|
||||
stackId="sentiment"
|
||||
fill="url(#negativeGradient)"
|
||||
stroke="#ef4444"
|
||||
strokeWidth={2}
|
||||
name="😟 Negative"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Volume View */}
|
||||
{viewMode === 'volume' && (
|
||||
<>
|
||||
<YAxis
|
||||
tick={{ fill: '#6b7280', fontSize: 11 }}
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
label={{
|
||||
value: 'Count',
|
||||
angle: -90,
|
||||
position: 'insideLeft',
|
||||
fill: '#9ca3af',
|
||||
fontSize: 12,
|
||||
}}
|
||||
/>
|
||||
<Bar
|
||||
dataKey="review_count"
|
||||
fill="#3b82f6"
|
||||
opacity={0.8}
|
||||
name="📝 Reviews"
|
||||
radius={[4, 4, 0, 0]}
|
||||
/>
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="span_count"
|
||||
stroke="#8b5cf6"
|
||||
strokeWidth={2}
|
||||
dot={{ fill: '#8b5cf6', r: 3 }}
|
||||
name="💬 Mentions"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Rating View */}
|
||||
{viewMode === 'rating' && (
|
||||
<>
|
||||
<YAxis
|
||||
domain={[0, 5]}
|
||||
ticks={[0, 1, 2, 3, 4, 5]}
|
||||
tick={{ fill: '#6b7280', fontSize: 11 }}
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
label={{
|
||||
value: 'Rating',
|
||||
angle: -90,
|
||||
position: 'insideLeft',
|
||||
fill: '#9ca3af',
|
||||
fontSize: 12,
|
||||
}}
|
||||
/>
|
||||
<ReferenceLine y={4} stroke="#22c55e" strokeDasharray="5 5" label={{ value: 'Good', fill: '#22c55e', fontSize: 10 }} />
|
||||
<ReferenceLine y={3} stroke="#eab308" strokeDasharray="5 5" label={{ value: 'OK', fill: '#eab308', fontSize: 10 }} />
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="avg_rating"
|
||||
fill="url(#volumeGradient)"
|
||||
stroke="#3b82f6"
|
||||
strokeWidth={3}
|
||||
name="⭐ Avg Rating"
|
||||
dot={{ fill: '#3b82f6', r: 4, strokeWidth: 2, stroke: '#fff' }}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Tooltip
|
||||
contentStyle={{
|
||||
backgroundColor: '#ffffff',
|
||||
border: 'none',
|
||||
borderRadius: '12px',
|
||||
boxShadow: '0 10px 40px rgba(0,0,0,0.15)',
|
||||
padding: '12px 16px',
|
||||
}}
|
||||
content={({ active, payload, label }) => {
|
||||
if (active && payload && payload.length) {
|
||||
const data = payload[0]?.payload as TimelinePoint;
|
||||
return (
|
||||
<div className="min-w-[180px]">
|
||||
<p className="font-bold text-gray-900 mb-2 pb-2 border-b border-gray-100">
|
||||
📅 {formatDate(String(label))}
|
||||
</p>
|
||||
|
||||
{viewMode === 'sentiment' && (
|
||||
<>
|
||||
<div className="flex items-center justify-between py-1">
|
||||
<span className="text-green-600">😊 Positive</span>
|
||||
<span className="font-bold text-green-600">{data.positive_count}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between py-1">
|
||||
<span className="text-red-600">😟 Negative</span>
|
||||
<span className="font-bold text-red-600">{data.negative_count}</span>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{viewMode === 'volume' && (
|
||||
<>
|
||||
<div className="flex items-center justify-between py-1">
|
||||
<span className="text-blue-600">📝 Reviews</span>
|
||||
<span className="font-bold text-blue-600">{data.review_count}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between py-1">
|
||||
<span className="text-purple-600">💬 Mentions</span>
|
||||
<span className="font-bold text-purple-600">{data.span_count}</span>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{viewMode === 'rating' && (
|
||||
<div className="flex items-center justify-between py-1">
|
||||
<span className="text-blue-600">⭐ Avg Rating</span>
|
||||
<span className="font-bold text-blue-600">
|
||||
{data.avg_rating?.toFixed(1) || 'N/A'}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-2 pt-2 border-t border-gray-100 text-xs text-gray-500">
|
||||
{data.review_count} reviews this period
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Brush for date range selection */}
|
||||
<Brush
|
||||
dataKey="date"
|
||||
height={40}
|
||||
stroke="#3b82f6"
|
||||
fill="#f8fafc"
|
||||
travellerWidth={10}
|
||||
startIndex={localBrushRange?.startIndex ?? 0}
|
||||
endIndex={localBrushRange?.endIndex ?? sortedData.length - 1}
|
||||
onChange={handleBrushChange}
|
||||
tickFormatter={formatDate}
|
||||
/>
|
||||
</ComposedChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
|
||||
{/* Footer hint */}
|
||||
<div className="mt-2 text-center text-xs text-gray-500">
|
||||
💡 Drag the handles below the chart to zoom into a specific date range
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
238
web/components/reviewiq/charts/URTBarChart.tsx
Normal file
238
web/components/reviewiq/charts/URTBarChart.tsx
Normal file
@@ -0,0 +1,238 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo } from 'react';
|
||||
import { X, Filter, TrendingUp, TrendingDown, Minus } from 'lucide-react';
|
||||
import type { URTDomainPoint, URTDomain } from '../types';
|
||||
import { useReviewIQFilters } from '@/contexts/ReviewIQFilterContext';
|
||||
|
||||
interface URTBarChartProps {
|
||||
data: URTDomainPoint[];
|
||||
}
|
||||
|
||||
// User-friendly domain config with emojis and descriptions
|
||||
const DOMAIN_CONFIG: Record<string, {
|
||||
emoji: string;
|
||||
label: string;
|
||||
color: string;
|
||||
bgColor: string;
|
||||
}> = {
|
||||
P: { emoji: '👥', label: 'Staff & Service', color: '#3b82f6', bgColor: '#dbeafe' },
|
||||
V: { emoji: '💰', label: 'Pricing & Value', color: '#ec4899', bgColor: '#fce7f3' },
|
||||
J: { emoji: '⏱️', label: 'Speed & Process', color: '#8b5cf6', bgColor: '#ede9fe' },
|
||||
O: { emoji: '🛍️', label: 'Product Quality', color: '#f97316', bgColor: '#ffedd5' },
|
||||
A: { emoji: '📍', label: 'Availability', color: '#10b981', bgColor: '#d1fae5' },
|
||||
E: { emoji: '🏢', label: 'Facilities', color: '#06b6d4', bgColor: '#cffafe' },
|
||||
R: { emoji: '🤝', label: 'Trust & Ethics', color: '#f59e0b', bgColor: '#fef3c7' },
|
||||
};
|
||||
|
||||
// Ordered domains by typical business priority
|
||||
const DOMAIN_ORDER = ['P', 'V', 'J', 'O', 'A', 'E', 'R'];
|
||||
|
||||
/**
|
||||
* Domain Distribution - Horizontal bar chart showing what customers talk about.
|
||||
* User-friendly design with emojis and clear progress bars.
|
||||
* Click to filter by domain.
|
||||
*/
|
||||
export function URTBarChart({ data }: URTBarChartProps) {
|
||||
const { filters, setURTDomain } = useReviewIQFilters();
|
||||
|
||||
// Process and sort data
|
||||
const processedData = useMemo(() => {
|
||||
const lookup = new Map<string, URTDomainPoint>();
|
||||
let maxCount = 0;
|
||||
let totalMentions = 0;
|
||||
|
||||
data.forEach((d) => {
|
||||
lookup.set(d.domain, d);
|
||||
if (d.count > maxCount) maxCount = d.count;
|
||||
totalMentions += d.count;
|
||||
});
|
||||
|
||||
// Sort by domain order, then build rows
|
||||
const rows = DOMAIN_ORDER
|
||||
.filter(domain => lookup.has(domain))
|
||||
.map(domain => {
|
||||
const d = lookup.get(domain)!;
|
||||
const config = DOMAIN_CONFIG[d.domain] || {
|
||||
emoji: '📊',
|
||||
label: d.domain_name || d.domain,
|
||||
color: '#6b7280',
|
||||
bgColor: '#f3f4f6',
|
||||
};
|
||||
|
||||
const percentage = totalMentions > 0 ? (d.count / totalMentions) * 100 : 0;
|
||||
const barWidth = maxCount > 0 ? (d.count / maxCount) * 100 : 0;
|
||||
|
||||
// Health indicator based on positive/negative ratio
|
||||
const total = d.positive_count + d.negative_count + d.neutral_count;
|
||||
const positiveRatio = total > 0 ? d.positive_count / total : 0;
|
||||
const negativeRatio = total > 0 ? d.negative_count / total : 0;
|
||||
|
||||
let health: 'good' | 'warning' | 'critical' = 'warning';
|
||||
if (positiveRatio > 0.6) health = 'good';
|
||||
else if (negativeRatio > 0.5) health = 'critical';
|
||||
|
||||
return {
|
||||
domain: d.domain,
|
||||
config,
|
||||
count: d.count,
|
||||
reviewCount: d.review_count,
|
||||
percentage,
|
||||
barWidth,
|
||||
health,
|
||||
positiveCount: d.positive_count,
|
||||
negativeCount: d.negative_count,
|
||||
};
|
||||
})
|
||||
// Sort by count descending
|
||||
.sort((a, b) => b.count - a.count);
|
||||
|
||||
return { rows, maxCount, totalMentions };
|
||||
}, [data]);
|
||||
|
||||
const handleClick = (domain: string) => {
|
||||
setURTDomain(filters.urtDomain === domain ? null : domain as URTDomain);
|
||||
};
|
||||
|
||||
const isFiltering = filters.urtDomain !== null;
|
||||
const hasSentimentFilter = filters.sentiment.length > 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`bg-white rounded-xl p-6 shadow-md transition-all ${
|
||||
isFiltering
|
||||
? 'border-3 border-blue-500 ring-2 ring-blue-200'
|
||||
: hasSentimentFilter
|
||||
? 'border-2 border-purple-400 ring-1 ring-purple-200'
|
||||
: 'border-2 border-gray-300 hover:border-blue-400'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div>
|
||||
<h3 className="text-lg font-bold text-gray-900">What Customers Talk About</h3>
|
||||
<p className="text-sm text-gray-500 mt-1">
|
||||
{processedData.totalMentions.toLocaleString()} total mentions
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{hasSentimentFilter && !isFiltering && (
|
||||
<span className="flex items-center gap-1 text-xs text-purple-600 bg-purple-50 px-2 py-1 rounded-full">
|
||||
<Filter className="w-3 h-3" />
|
||||
{filters.sentiment.join(', ')}
|
||||
</span>
|
||||
)}
|
||||
{isFiltering && (
|
||||
<>
|
||||
<span className="px-2 py-1 bg-blue-100 text-blue-800 text-xs font-bold rounded-full">
|
||||
{DOMAIN_CONFIG[filters.urtDomain!]?.label || filters.urtDomain}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => setURTDomain(null)}
|
||||
className="p-1 hover:bg-gray-200 rounded-full transition-colors"
|
||||
title="Clear filter"
|
||||
>
|
||||
<X className="w-4 h-4 text-gray-600" />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{processedData.rows.length === 0 ? (
|
||||
<div className="flex items-center justify-center h-64 text-gray-500">
|
||||
No data available
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{processedData.rows.map((row) => {
|
||||
const isActive = filters.urtDomain === row.domain;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={row.domain}
|
||||
onClick={() => handleClick(row.domain)}
|
||||
className={`w-full text-left transition-all rounded-lg p-3 ${
|
||||
isActive
|
||||
? 'bg-blue-50 ring-2 ring-blue-500'
|
||||
: 'hover:bg-gray-50'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Emoji */}
|
||||
<span className="text-2xl flex-shrink-0">{row.config.emoji}</span>
|
||||
|
||||
{/* Label and Bar */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<span className={`font-semibold ${isActive ? 'text-blue-700' : 'text-gray-900'}`}>
|
||||
{row.config.label}
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-bold text-gray-700">
|
||||
{row.count.toLocaleString()}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">
|
||||
({row.percentage.toFixed(0)}%)
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Progress Bar */}
|
||||
<div className="h-3 bg-gray-100 rounded-full overflow-hidden">
|
||||
<div
|
||||
className="h-full rounded-full transition-all duration-500"
|
||||
style={{
|
||||
width: `${row.barWidth}%`,
|
||||
backgroundColor: isActive ? '#3b82f6' : row.config.color,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Sentiment mini-stats */}
|
||||
<div className="flex items-center gap-3 mt-1.5 text-xs">
|
||||
<span className="text-green-600 font-medium">
|
||||
👍 {row.positiveCount}
|
||||
</span>
|
||||
<span className="text-red-600 font-medium">
|
||||
👎 {row.negativeCount}
|
||||
</span>
|
||||
<span className="text-gray-500">
|
||||
{row.reviewCount} reviews
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Health Indicator */}
|
||||
<div className="flex-shrink-0">
|
||||
{row.health === 'good' && (
|
||||
<TrendingUp className="w-5 h-5 text-green-500" />
|
||||
)}
|
||||
{row.health === 'critical' && (
|
||||
<TrendingDown className="w-5 h-5 text-red-500" />
|
||||
)}
|
||||
{row.health === 'warning' && (
|
||||
<Minus className="w-5 h-5 text-gray-400" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Legend */}
|
||||
<div className="flex items-center justify-center gap-4 mt-4 pt-3 border-t border-gray-100 text-xs text-gray-500">
|
||||
<span className="flex items-center gap-1">
|
||||
<TrendingUp className="w-3 h-3 text-green-500" /> Mostly positive
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<Minus className="w-3 h-3 text-gray-400" /> Mixed
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<TrendingDown className="w-3 h-3 text-red-500" /> Needs attention
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
432
web/components/reviewiq/insights/ExecutiveSummary.tsx
Normal file
432
web/components/reviewiq/insights/ExecutiveSummary.tsx
Normal file
@@ -0,0 +1,432 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
Sparkles,
|
||||
TrendingUp,
|
||||
TrendingDown,
|
||||
Languages,
|
||||
Loader2,
|
||||
Star,
|
||||
Target,
|
||||
AlertTriangle,
|
||||
CheckCircle2,
|
||||
ChevronRight,
|
||||
Zap,
|
||||
Award,
|
||||
} from 'lucide-react';
|
||||
import { useTranslation } from '@/hooks/useTranslation';
|
||||
import type { Insights, WeaknessItem, OpportunitySpan, OpportunityMatrix, DomainScore, URTDomain } from '../types';
|
||||
import { getSubcodeDefinition } from '@/lib/taxonomy/data';
|
||||
|
||||
interface ExecutiveSummaryProps {
|
||||
insights: Insights;
|
||||
avgRating: number | null;
|
||||
domainScores?: DomainScore[];
|
||||
onDriverClick?: (subcode: string) => void;
|
||||
onDomainClick?: (domain: URTDomain) => void;
|
||||
}
|
||||
|
||||
// User-friendly domain config
|
||||
const DOMAIN_CONFIG: Record<string, { emoji: string; label: string }> = {
|
||||
P: { emoji: '👥', label: 'Staff & Service' },
|
||||
V: { emoji: '💰', label: 'Pricing & Value' },
|
||||
J: { emoji: '⏱️', label: 'Speed & Process' },
|
||||
O: { emoji: '🛍️', label: 'Product Quality' },
|
||||
A: { emoji: '📍', label: 'Availability' },
|
||||
E: { emoji: '🏢', label: 'Facilities' },
|
||||
R: { emoji: '🤝', label: 'Trust & Ethics' },
|
||||
};
|
||||
|
||||
// Get rating emoji and label
|
||||
const getRatingDisplay = (rating: number | null) => {
|
||||
if (!rating) return { emoji: '❓', label: 'No rating', color: 'text-gray-500' };
|
||||
if (rating >= 4.5) return { emoji: '🌟', label: 'Excellent', color: 'text-green-600' };
|
||||
if (rating >= 4.0) return { emoji: '😊', label: 'Good', color: 'text-green-500' };
|
||||
if (rating >= 3.5) return { emoji: '🙂', label: 'Average', color: 'text-yellow-600' };
|
||||
if (rating >= 3.0) return { emoji: '😐', label: 'Fair', color: 'text-orange-500' };
|
||||
return { emoji: '😟', label: 'Needs Work', color: 'text-red-500' };
|
||||
};
|
||||
|
||||
// Domain complaints section
|
||||
function TopComplaintsSection({
|
||||
domainScores,
|
||||
weaknesses,
|
||||
opportunityMatrix,
|
||||
onDomainClick,
|
||||
}: {
|
||||
domainScores: DomainScore[];
|
||||
weaknesses: WeaknessItem[];
|
||||
opportunityMatrix: OpportunityMatrix | null;
|
||||
onDomainClick?: (domain: URTDomain) => void;
|
||||
}) {
|
||||
const { translate, getState } = useTranslation('en');
|
||||
|
||||
// Get example quote for a domain
|
||||
const getQuoteForDomain = (domainKey: string): OpportunitySpan | null => {
|
||||
const weakness = weaknesses.find(w => w.domain === domainKey);
|
||||
if (weakness?.example_spans?.length) {
|
||||
return weakness.example_spans[0];
|
||||
}
|
||||
|
||||
if (opportunityMatrix) {
|
||||
const allOpportunities = [
|
||||
...opportunityMatrix.quick_wins,
|
||||
...opportunityMatrix.critical,
|
||||
...opportunityMatrix.nice_to_have,
|
||||
...opportunityMatrix.strategic,
|
||||
];
|
||||
const opportunity = allOpportunities.find(o => o.domain === domainKey && o.spans?.length);
|
||||
if (opportunity?.spans?.length) {
|
||||
return opportunity.spans[0];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
// Calculate and sort by negative percentage
|
||||
const sorted = domainScores
|
||||
.map(d => ({
|
||||
...d,
|
||||
negativePercent: d.total_count > 0
|
||||
? Math.round((d.negative_count / d.total_count) * 100)
|
||||
: 0,
|
||||
quote: getQuoteForDomain(d.domain),
|
||||
config: DOMAIN_CONFIG[d.domain] || { emoji: '📊', label: d.name },
|
||||
}))
|
||||
.sort((a, b) => b.negativePercent - a.negativePercent)
|
||||
.slice(0, 4);
|
||||
|
||||
const handleTranslate = (e: React.MouseEvent, text: string, id: string) => {
|
||||
e.stopPropagation();
|
||||
translate(text, id);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{sorted.map((domain) => {
|
||||
const quoteId = `domain-${domain.domain}`;
|
||||
const translationState = getState(quoteId);
|
||||
const displayText = translationState.isTranslated && domain.quote
|
||||
? translationState.translated
|
||||
: domain.quote?.span_text;
|
||||
|
||||
const severity = domain.negativePercent >= 40 ? 'critical' :
|
||||
domain.negativePercent >= 25 ? 'warning' : 'ok';
|
||||
|
||||
return (
|
||||
<button
|
||||
key={domain.domain}
|
||||
onClick={() => onDomainClick?.(domain.domain as URTDomain)}
|
||||
className={`w-full p-3 rounded-xl border-2 transition-all hover:shadow-md text-left ${
|
||||
severity === 'critical' ? 'bg-red-50 border-red-200 hover:border-red-300' :
|
||||
severity === 'warning' ? 'bg-orange-50 border-orange-200 hover:border-orange-300' :
|
||||
'bg-gray-50 border-gray-200 hover:border-gray-300'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Emoji */}
|
||||
<span className="text-2xl">{domain.config.emoji}</span>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<span className="font-semibold text-gray-900">
|
||||
{domain.config.label}
|
||||
</span>
|
||||
<span className={`text-sm font-bold ${
|
||||
severity === 'critical' ? 'text-red-600' :
|
||||
severity === 'warning' ? 'text-orange-600' :
|
||||
'text-gray-600'
|
||||
}`}>
|
||||
{domain.negativePercent}% complaints
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Progress bar */}
|
||||
<div className="h-2 bg-gray-200 rounded-full overflow-hidden">
|
||||
<div
|
||||
className={`h-full rounded-full transition-all ${
|
||||
severity === 'critical' ? 'bg-red-500' :
|
||||
severity === 'warning' ? 'bg-orange-500' :
|
||||
'bg-green-500'
|
||||
}`}
|
||||
style={{ width: `${Math.min(100, domain.negativePercent)}%` }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Quote */}
|
||||
{domain.quote && displayText && (
|
||||
<div className="mt-2 flex items-start gap-2">
|
||||
<p className="text-xs text-gray-600 italic line-clamp-1 flex-1">
|
||||
"{displayText}"
|
||||
</p>
|
||||
<button
|
||||
onClick={(e) => handleTranslate(e, domain.quote!.span_text, quoteId)}
|
||||
disabled={translationState.isLoading}
|
||||
className={`p-1 rounded flex-shrink-0 transition-colors ${
|
||||
translationState.isTranslated
|
||||
? 'bg-blue-100 hover:bg-blue-200'
|
||||
: 'bg-white/50 hover:bg-white'
|
||||
}`}
|
||||
title={translationState.isTranslated ? 'Show original' : 'Translate'}
|
||||
>
|
||||
{translationState.isLoading ? (
|
||||
<Loader2 className="w-3 h-3 text-blue-500 animate-spin" />
|
||||
) : (
|
||||
<Languages className={`w-3 h-3 ${
|
||||
translationState.isTranslated ? 'text-blue-600' : 'text-gray-400'
|
||||
}`} />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ChevronRight className="w-4 h-4 text-gray-400 flex-shrink-0" />
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ExecutiveSummary({
|
||||
insights,
|
||||
avgRating,
|
||||
domainScores,
|
||||
onDriverClick,
|
||||
onDomainClick,
|
||||
}: ExecutiveSummaryProps) {
|
||||
const { strengths, weaknesses, executive_summary, opportunity_matrix, rating_simulator } = insights;
|
||||
const [showFullSummary, setShowFullSummary] = useState(false);
|
||||
|
||||
const topStrength = strengths[0];
|
||||
const topWeakness = weaknesses[0];
|
||||
const ratingDisplay = getRatingDisplay(avgRating);
|
||||
|
||||
// Calculate potential rating improvement
|
||||
const potentialRating = rating_simulator?.if_fix_top_3 ||
|
||||
(avgRating && topWeakness?.projected_rating_impact
|
||||
? avgRating + topWeakness.projected_rating_impact
|
||||
: null);
|
||||
|
||||
// If no insights, show minimal summary
|
||||
if (!executive_summary && !topStrength && !topWeakness) {
|
||||
return (
|
||||
<div className="bg-gradient-to-br from-slate-50 to-blue-50 rounded-2xl border-2 border-blue-100 p-6">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="p-3 bg-blue-100 rounded-xl">
|
||||
<Sparkles className="w-6 h-6 text-blue-600" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-bold text-gray-900">Executive Summary</h3>
|
||||
<p className="text-sm text-gray-500">AI-powered insights from your reviews</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 p-4 bg-white/60 rounded-xl border border-blue-100">
|
||||
<span className="text-3xl">📊</span>
|
||||
<div>
|
||||
<p className="font-medium text-gray-700">More data needed</p>
|
||||
<p className="text-sm text-gray-500">
|
||||
Continue collecting reviews to unlock actionable insights and recommendations.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 rounded-2xl border-2 border-blue-100 overflow-hidden">
|
||||
{/* Header */}
|
||||
<div className="p-6 pb-4">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-3 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-xl shadow-lg">
|
||||
<Sparkles className="w-6 h-6 text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-bold text-gray-900">Executive Summary</h3>
|
||||
<p className="text-sm text-gray-500">AI-powered insights from your reviews</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Rating Badge */}
|
||||
{avgRating && (
|
||||
<div className="flex items-center gap-3 p-3 bg-white rounded-xl shadow-sm border border-gray-100">
|
||||
<div className="text-center">
|
||||
<div className="text-3xl">{ratingDisplay.emoji}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Star className="w-4 h-4 text-yellow-500 fill-yellow-500" />
|
||||
<span className={`text-2xl font-bold ${ratingDisplay.color}`}>
|
||||
{avgRating.toFixed(1)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">{ratingDisplay.label}</div>
|
||||
</div>
|
||||
{potentialRating && potentialRating > avgRating && (
|
||||
<div className="pl-3 border-l border-gray-200">
|
||||
<div className="text-xs text-gray-500">Potential</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<TrendingUp className="w-3 h-3 text-green-500" />
|
||||
<span className="text-lg font-bold text-green-600">
|
||||
{potentialRating.toFixed(1)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* AI Summary */}
|
||||
{executive_summary && (
|
||||
<div className="px-6 pb-4">
|
||||
<div className="p-4 bg-white/70 rounded-xl border border-blue-100">
|
||||
<div className="flex items-start gap-2">
|
||||
<span className="text-lg">💡</span>
|
||||
<div>
|
||||
<p className={`text-gray-700 leading-relaxed ${!showFullSummary && 'line-clamp-2'}`}>
|
||||
{executive_summary}
|
||||
</p>
|
||||
{executive_summary.length > 150 && (
|
||||
<button
|
||||
onClick={() => setShowFullSummary(!showFullSummary)}
|
||||
className="text-blue-600 text-sm font-medium mt-1 hover:underline"
|
||||
>
|
||||
{showFullSummary ? 'Show less' : 'Read more'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Key Metrics Cards */}
|
||||
<div className="px-6 pb-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
{/* Top Problem */}
|
||||
{topWeakness && (
|
||||
<button
|
||||
onClick={() => onDriverClick?.(topWeakness.subcode)}
|
||||
className="group p-4 bg-white rounded-xl border-2 border-red-100 hover:border-red-300 hover:shadow-lg transition-all text-left"
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="p-2 bg-red-100 rounded-lg group-hover:bg-red-200 transition-colors">
|
||||
<AlertTriangle className="w-5 h-5 text-red-600" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className="text-xs font-bold text-red-600 uppercase tracking-wide">
|
||||
🔥 #1 Problem
|
||||
</span>
|
||||
</div>
|
||||
<div className="font-bold text-gray-900 truncate">
|
||||
{topWeakness.subcode_name}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 truncate mt-0.5">
|
||||
{getSubcodeDefinition(topWeakness.subcode)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3 mt-2">
|
||||
<span className="text-sm font-bold text-red-600">
|
||||
{topWeakness.negative_percentage.toFixed(0)}% negative
|
||||
</span>
|
||||
<span className="text-xs text-gray-400">
|
||||
{topWeakness.span_count} mentions
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{topWeakness.projected_rating_impact && (
|
||||
<div className="text-right flex-shrink-0">
|
||||
<div className="text-xs text-gray-500">If fixed</div>
|
||||
<div className="flex items-center gap-1 text-green-600">
|
||||
<Zap className="w-4 h-4" />
|
||||
<span className="font-bold">
|
||||
+{topWeakness.projected_rating_impact.toFixed(2)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Top Strength */}
|
||||
{topStrength && (
|
||||
<button
|
||||
onClick={() => onDriverClick?.(topStrength.subcode)}
|
||||
className="group p-4 bg-white rounded-xl border-2 border-green-100 hover:border-green-300 hover:shadow-lg transition-all text-left"
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="p-2 bg-green-100 rounded-lg group-hover:bg-green-200 transition-colors">
|
||||
<Award className="w-5 h-5 text-green-600" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className="text-xs font-bold text-green-600 uppercase tracking-wide">
|
||||
⭐ #1 Strength
|
||||
</span>
|
||||
</div>
|
||||
<div className="font-bold text-gray-900 truncate">
|
||||
{topStrength.subcode_name}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 truncate mt-0.5">
|
||||
{getSubcodeDefinition(topStrength.subcode)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3 mt-2">
|
||||
<span className="text-sm font-bold text-green-600">
|
||||
{topStrength.positive_percentage.toFixed(0)}% positive
|
||||
</span>
|
||||
<span className="text-xs text-gray-400">
|
||||
{topStrength.span_count} mentions
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right flex-shrink-0">
|
||||
<div className="text-xs text-gray-500">Marketing</div>
|
||||
<CheckCircle2 className="w-5 h-5 text-green-500 ml-auto" />
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Complaint Breakdown */}
|
||||
{domainScores && domainScores.length > 0 && (
|
||||
<div className="px-6 pb-6">
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<Target className="w-4 h-4 text-gray-600" />
|
||||
<span className="font-semibold text-gray-700">Where Customers Complain Most</span>
|
||||
</div>
|
||||
<TopComplaintsSection
|
||||
domainScores={domainScores}
|
||||
weaknesses={weaknesses}
|
||||
opportunityMatrix={opportunity_matrix}
|
||||
onDomainClick={onDomainClick}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Quick Actions Footer */}
|
||||
<div className="px-6 py-4 bg-gradient-to-r from-blue-500/5 to-indigo-500/5 border-t border-blue-100">
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-gray-500">
|
||||
💡 Click any card to drill down into details
|
||||
</span>
|
||||
<div className="flex items-center gap-1 text-blue-600">
|
||||
<span className="font-medium">Powered by AI</span>
|
||||
<Sparkles className="w-4 h-4" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user