Files
campaign-command-center/src/app/admin/page.tsx
Chris Olson d2d5632086 Implement Phase 2 features for Campaign Command Center
Adds 14 new features across the dashboard:
- Deal Risk Scoring (0-100) with risk factors on pipeline deals
- Account Health Score with multi-factor analysis on account cards
- Next Best Action Engine on Executive Overview
- Account Notes with pin/edit/delete in activity overlay and account detail
- Stakeholder Contact Map with role, sentiment, email, LinkedIn
- Competitive Intelligence Tracker with multi-select competitors and filtering
- CSV/Excel Export on accounts, activities, and pipeline pages
- Data Quality Dashboard in admin with completeness scoring
- Campaign Playbook Templates with 5 default plays and account progress tracking
- Goals & District Targets with quarterly tracking and progress bars
- Weekly Status Report (printable) and Executive Summary (printable)
- Activity Effectiveness Scoring showing pipeline conversion by activity type
- Mobile Activity FAB for quick activity logging on mobile
- Multi-User Auth (NextAuth + Google OAuth, @broadcom.com domain, role-based)

Also adds Phase 2 API route, scoring utilities, sidebar navigation updates,
and database schema extensions for notes, contacts, snapshots, playbooks,
and district targets.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-08-31 18:07:46 -04:00

731 lines
33 KiB
TypeScript

'use client';
import { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
type Tab = 'import' | 'accounts' | 'pipeline' | 'activities' | 'targets' | 'quality';
interface Stats {
accounts: number;
pipeline: number;
activities: number;
targets: number;
}
export default function AdminPage() {
const [tab, setTab] = useState<Tab>('import');
const [stats, setStats] = useState<Stats>({ accounts: 0, pipeline: 0, activities: 0, targets: 0 });
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
useEffect(() => {
fetch('/api/admin').then(r => r.json()).then(d => setStats(d.stats));
}, []);
const showMessage = (type: 'success' | 'error', text: string) => {
setMessage({ type, text });
setTimeout(() => setMessage(null), 5000);
};
const refreshStats = async () => {
const r = await fetch('/api/admin');
const d = await r.json();
setStats(d.stats);
};
return (
<div className="min-h-screen bg-[#f5f6f8]">
<header className="bg-[#1B1D36] text-white px-6 py-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<Link href="/" className="text-white/70 hover:text-white text-sm">
&larr; Dashboard
</Link>
<h1 className="text-lg font-bold">Data Admin</h1>
</div>
<div className="flex gap-4 text-sm items-center">
<span className="bg-white/10 px-3 py-1 rounded">{stats.accounts} accounts</span>
<span className="bg-white/10 px-3 py-1 rounded">{stats.pipeline} deals</span>
<span className="bg-white/10 px-3 py-1 rounded">{stats.activities} activities</span>
<span className="bg-white/10 px-3 py-1 rounded">{stats.targets} targets</span>
<Link href="/admin/goals" className="px-3 py-1 rounded bg-[#0098C7] hover:bg-[#007ba3] text-white font-medium transition">
Goals &amp; Progress
</Link>
</div>
</header>
{message && (
<div className={`px-6 py-3 text-sm font-medium ${message.type === 'success' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
{message.text}
</div>
)}
<div className="px-6 pt-4 flex gap-1 border-b border-gray-200 bg-white">
{(['import', 'accounts', 'pipeline', 'activities', 'targets', 'quality'] as Tab[]).map(t => (
<button
key={t}
onClick={() => setTab(t)}
className={`px-4 py-2.5 text-sm font-medium capitalize rounded-t-lg transition ${
tab === t
? 'bg-[#f5f6f8] text-[#1B1D36] border-t-2 border-x border-[#0098C7]'
: 'text-gray-500 hover:text-gray-800 hover:bg-gray-50'
}`}
>
{t === 'import' ? 'Import Data' : t === 'quality' ? 'Data Quality' : t}
</button>
))}
</div>
<div className="p-6">
{tab === 'import' && <ImportTab onComplete={() => { refreshStats(); showMessage('success', 'Import complete!'); }} onError={showMessage} loading={loading} setLoading={setLoading} />}
{tab === 'accounts' && <DataTable table="accounts" onUpdate={refreshStats} showMessage={showMessage} />}
{tab === 'pipeline' && <DataTable table="pipeline" onUpdate={refreshStats} showMessage={showMessage} />}
{tab === 'activities' && <DataTable table="activities" onUpdate={refreshStats} showMessage={showMessage} />}
{tab === 'targets' && <DataTable table="targets" onUpdate={refreshStats} showMessage={showMessage} />}
{tab === 'quality' && <DataQualityPanel onNavigate={(t: Tab) => setTab(t)} />}
</div>
</div>
);
}
function ImportTab({ onComplete, onError, loading, setLoading }: {
onComplete: () => void;
onError: (type: 'success' | 'error', text: string) => void;
loading: boolean;
setLoading: (v: boolean) => void;
}) {
const [csvTab, setCsvTab] = useState<string>('accounts');
const fileRef = useRef<HTMLInputElement>(null);
const handleFileUpload = async (file: File, tabName: string) => {
setLoading(true);
try {
const text = await file.text();
const res = await fetch('/api/import', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ tab: tabName, csv: text }),
});
const result = await res.json();
if (result.success) {
onComplete();
} else {
onError('error', result.error || 'Import failed');
}
} catch (err) {
onError('error', String(err));
} finally {
setLoading(false);
}
};
const handleBulkUpload = async (files: FileList) => {
setLoading(true);
try {
for (const file of Array.from(files)) {
const name = file.name.toLowerCase().replace('.csv', '');
let tabName = name;
if (name.includes('pipeline')) tabName = 'pipeline';
else if (name.includes('account')) tabName = 'accounts';
else if (name.includes('activity')) tabName = 'activities';
else if (name.includes('target') || name.includes('implementation')) tabName = 'targets';
const text = await file.text();
await fetch('/api/import', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ tab: tabName, csv: text }),
});
}
onComplete();
} catch (err) {
onError('error', String(err));
} finally {
setLoading(false);
}
};
return (
<div className="max-w-3xl space-y-8">
<div className="bg-white rounded-xl border border-gray-200 p-6">
<h2 className="text-lg font-bold text-[#1B1D36] mb-2">Import from Google Sheets</h2>
<p className="text-sm text-gray-500 mb-4">
Export each tab from your Google Sheet as CSV (File &rarr; Download &rarr; Comma-separated values), then upload them here.
The import is idempotent &mdash; accounts and pipeline records are upserted by their ID, so re-importing is safe.
</p>
<div className="bg-[#f5f6f8] rounded-lg p-4 mb-4">
<h3 className="text-sm font-semibold mb-3">Quick Import: Upload All CSVs at Once</h3>
<p className="text-xs text-gray-500 mb-3">
Name your files with the tab name (e.g. <code className="bg-gray-200 px-1 rounded">Pipeline.csv</code>, <code className="bg-gray-200 px-1 rounded">Accounts.csv</code>, <code className="bg-gray-200 px-1 rounded">Activity_Log.csv</code>, <code className="bg-gray-200 px-1 rounded">Targets.csv</code>).
</p>
<input
type="file"
accept=".csv"
multiple
onChange={e => e.target.files && handleBulkUpload(e.target.files)}
disabled={loading}
className="block w-full text-sm file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-[#0098C7] file:text-white hover:file:bg-[#007ba3] file:cursor-pointer disabled:opacity-50"
/>
</div>
<div className="border-t border-gray-200 pt-4">
<h3 className="text-sm font-semibold mb-3">Import Single Tab</h3>
<div className="flex gap-2 mb-3">
{['accounts', 'pipeline', 'activities', 'targets'].map(t => (
<button
key={t}
onClick={() => setCsvTab(t)}
className={`px-3 py-1.5 text-xs font-medium rounded-lg capitalize transition ${
csvTab === t ? 'bg-[#1B1D36] text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
}`}
>
{t}
</button>
))}
</div>
<div className="flex gap-2">
<input
ref={fileRef}
type="file"
accept=".csv"
disabled={loading}
className="block flex-1 text-sm file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-gray-700 file:text-white hover:file:bg-gray-800 file:cursor-pointer disabled:opacity-50"
/>
<button
onClick={() => {
const f = fileRef.current?.files?.[0];
if (f) handleFileUpload(f, csvTab);
}}
disabled={loading}
className="px-4 py-2 bg-[#0098C7] text-white text-sm font-semibold rounded-lg hover:bg-[#007ba3] disabled:opacity-50"
>
{loading ? 'Importing...' : `Import as ${csvTab}`}
</button>
</div>
</div>
</div>
<div className="bg-white rounded-xl border border-gray-200 p-6">
<h2 className="text-lg font-bold text-[#1B1D36] mb-2">Expected Column Headers</h2>
<p className="text-sm text-gray-500 mb-4">Your CSV files should have these headers in Row 1 (case-sensitive):</p>
<div className="space-y-3 text-sm">
<div>
<span className="font-semibold">Accounts:</span>{' '}
<code className="text-xs bg-gray-100 px-1 rounded">Account_Name, District_Name, Tier, Priority, AgentMinder_Status</code>
<span className="text-gray-400 ml-1">(+ optional: Current_ARR_USD, Touch_Count, Date_First_Touched, Date_Last_Touched, MAP_In_Place_YN)</span>
</div>
<div>
<span className="font-semibold">Pipeline:</span>{' '}
<code className="text-xs bg-gray-100 px-1 rounded">Opportunity_ID, Account_Name, District_Name, Stage, Forecast_Category, Amount_USD, Created_Date, Expected_Close_Date</code>
</div>
<div>
<span className="font-semibold">Activity_Log:</span>{' '}
<code className="text-xs bg-gray-100 px-1 rounded">Activity_Date, Activity_Type, Account_Name, District_Name</code>
<span className="text-gray-400 ml-1">(+ optional: Contact_Name, Notes)</span>
</div>
<div>
<span className="font-semibold">Targets:</span>{' '}
<code className="text-xs bg-gray-100 px-1 rounded">Account_Name, Implementation_Stage</code>
<span className="text-gray-400 ml-1">(+ optional: Go_Live_Date, Health_Status, Notes)</span>
</div>
</div>
</div>
</div>
);
}
const FIELD_OPTIONS: Record<string, string[]> = {
Tier: ['Tier 1', 'Tier 2', 'Tier 3', 'Tier 4'],
Priority: ['High', 'Medium', 'Low'],
AgentMinder_Status: ['Not Touched', '10% - Prospect', '15% - Prospect - No Opp', '20% - Research', '40% - Verify', '60% - Prove', '80% - Pricing', '100% - Closed Won', 'Lost'],
District_Name: ['SE-MISS-VALLEY', 'SE-PEACHTREE', 'SE-SUNSHINE', 'SE-MID-ATL'],
MAP_In_Place_YN: ['Y', 'N'],
Stage: ['01-Qualified', '02-Discovery', '03-Evaluation', '04-Business Case', '05-Negotiation', '06-Closed Won', '07-Closed Lost'],
Forecast_Category: ['Commit', 'Best Case', 'Pipeline', 'Omitted', 'Closed'],
Deal_Type: ['Cross-Sell', 'Net-New Division', 'Net-New Logo', 'Expansion'],
Activity_Type: ['Launch Briefing', 'Discovery', 'Demo', 'Exec Meeting', 'Webinar Attendance', 'Email Sequence Touch', 'Renewal Conversation', 'QBR Attach', 'Referral Ask'],
Play: ['Attach', 'Renewal-Trigger', 'Referral', 'Inbound', 'Whitespace'],
Channel: ['In Person', 'Video Call', 'Phone', 'Email', 'Webinar', 'LinkedIn', 'Event'],
Persona: ['Economic Buyer', 'Champion', 'Technical Evaluator', 'End User', 'Procurement'],
Outcome: ['Advanced', 'Follow-up Scheduled', 'Opportunity Created', 'No Decision Yet', 'No Response', 'No Interest', 'Disqualified'],
Implementation_Stage: ['Not Started', 'In Progress', 'Live', 'At Risk', 'Stalled'],
Health_Status: ['Green', 'Yellow', 'Red'],
Competitors: ['Microsoft', 'Okta', 'Google', 'Sailpoint', 'AWS', 'Other'],
};
interface FieldDef { key: string; label: string; required?: boolean; type?: string; options?: string[] }
const TABLE_FIELDS: Record<string, FieldDef[]> = {
accounts: [
{ key: 'Account_Name', label: 'Account Name', required: true },
{ key: 'District_Name', label: 'District', required: true, options: FIELD_OPTIONS.District_Name },
{ key: 'Tier', label: 'Tier', options: FIELD_OPTIONS.Tier },
{ key: 'Priority', label: 'Priority', options: FIELD_OPTIONS.Priority },
{ key: 'AgentMinder_Status', label: 'Status', options: FIELD_OPTIONS.AgentMinder_Status },
{ key: 'Current_ARR_USD', label: 'Current ARR', type: 'number' },
{ key: 'MAP_In_Place_YN', label: 'MAP in Place', options: FIELD_OPTIONS.MAP_In_Place_YN },
{ key: 'Company_URL', label: 'Company URL' },
{ key: 'Logo_URL', label: 'Logo URL' },
{ key: 'Area_Sales_Leader', label: 'Area Sales Leader' },
{ key: 'DM', label: 'DM' },
{ key: 'AD', label: 'AD' },
{ key: 'IMS_BA', label: 'IMS BA' },
{ key: 'Next_Renewal_Date', label: 'Next Renewal Date', type: 'date' },
{ key: 'Next_Renewal_EAR', label: 'Next Renewal EAR', type: 'number' },
{ key: 'Anchor_Contract_Date', label: 'Anchor Contract Date', type: 'date' },
{ key: 'Anchor_Contract_EAR', label: 'Anchor Contract EAR', type: 'number' },
{ key: 'Google_Drive_URL', label: 'Google Drive Link' },
{ key: 'Campaign_Artifacts_URL', label: 'Campaign Artifacts Link' },
{ key: 'Competitors', label: 'Competitors', options: FIELD_OPTIONS.Competitors },
],
pipeline: [
{ key: 'Opportunity_ID', label: 'Opp ID', required: true },
{ key: 'Account_Name', label: 'Account Name', required: true },
{ key: 'District_Name', label: 'District', required: true, options: FIELD_OPTIONS.District_Name },
{ key: 'Stage', label: 'Stage', options: FIELD_OPTIONS.Stage },
{ key: 'Forecast_Category', label: 'Forecast', options: FIELD_OPTIONS.Forecast_Category },
{ key: 'Deal_Type', label: 'Deal Type', options: FIELD_OPTIONS.Deal_Type },
{ key: 'Amount_USD', label: 'Amount', type: 'number', required: true },
{ key: 'Closed_Amount_USD', label: 'Closed Amount', type: 'number' },
{ key: 'Probability_Pct', label: 'Probability %', type: 'number' },
{ key: 'Created_Date', label: 'Created Date', type: 'date', required: true },
{ key: 'Expected_Close_Date', label: 'Expected Close', type: 'date' },
{ key: 'Closed_Date', label: 'Closed Date', type: 'date' },
{ key: 'Champion_Name', label: 'Champion' },
{ key: 'Economic_Buyer', label: 'Economic Buyer' },
{ key: 'Next_Step', label: 'Next Step' },
{ key: 'Competitor', label: 'Competitor' },
{ key: 'Source_Play', label: 'Source Play' },
],
activities: [
{ key: 'Activity_Date', label: 'Date', type: 'date', required: true },
{ key: 'Activity_Type', label: 'Type', required: true, options: FIELD_OPTIONS.Activity_Type },
{ key: 'Account_Name', label: 'Account Name', required: true },
{ key: 'District_Name', label: 'District', required: true, options: FIELD_OPTIONS.District_Name },
{ key: 'Contact_Name', label: 'Contact' },
{ key: 'Notes', label: 'Notes' },
{ key: 'Play', label: 'Play', options: FIELD_OPTIONS.Play },
{ key: 'Channel', label: 'Channel', options: FIELD_OPTIONS.Channel },
{ key: 'Persona', label: 'Persona', options: FIELD_OPTIONS.Persona },
{ key: 'Outcome', label: 'Outcome', options: FIELD_OPTIONS.Outcome },
{ key: 'Logged_By', label: 'Logged By' },
],
targets: [
{ key: 'Account_Name', label: 'Account Name', required: true },
{ key: 'Implementation_Stage', label: 'Stage', required: true, options: FIELD_OPTIONS.Implementation_Stage },
{ key: 'Go_Live_Date', label: 'Go-Live Date', type: 'date' },
{ key: 'Health_Status', label: 'Health', options: FIELD_OPTIONS.Health_Status },
{ key: 'Notes', label: 'Notes' },
],
};
function RecordForm({ table, record, onSave, onCancel }: {
table: string;
record: Record<string, unknown> | null;
onSave: (data: Record<string, unknown>) => void;
onCancel: () => void;
}) {
const fields = TABLE_FIELDS[table] || [];
const [form, setForm] = useState<Record<string, string>>(() => {
const init: Record<string, string> = {};
fields.forEach(f => {
init[f.key] = record ? String(record[f.key] ?? '') : '';
});
return init;
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const data: Record<string, unknown> = {};
fields.forEach(f => {
const v = form[f.key]?.trim();
if (f.type === 'number') {
data[f.key] = v ? Number(v) : null;
} else {
data[f.key] = v || null;
}
});
onSave(data);
};
return (
<form onSubmit={handleSubmit} className="bg-white rounded-xl border border-gray-200 p-5 mb-4">
<h3 className="text-sm font-bold text-[#1B1D36] mb-4">{record ? 'Edit Record' : 'Add New Record'}</h3>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
{fields.map(f => (
<div key={f.key}>
<label className="block text-xs font-medium text-gray-600 mb-1">
{f.label} {f.required && <span className="text-red-500">*</span>}
</label>
{f.key === 'Competitors' && f.options ? (
<div className="flex flex-wrap gap-2 pt-1">
{f.options.map(opt => {
const selected = (form[f.key] || '').split(',').filter(Boolean);
const checked = selected.includes(opt);
return (
<label key={opt} className="flex items-center gap-1.5 text-sm cursor-pointer">
<input
type="checkbox"
checked={checked}
onChange={() => {
const next = checked ? selected.filter(v => v !== opt) : [...selected, opt];
setForm(prev => ({ ...prev, [f.key]: next.join(',') }));
}}
className="rounded border-gray-300 text-[#0098C7] focus:ring-[#0098C7]/30"
/>
{opt}
</label>
);
})}
</div>
) : f.options ? (
<select
value={form[f.key] || ''}
onChange={e => setForm(prev => ({ ...prev, [f.key]: e.target.value }))}
required={f.required}
className="w-full px-2.5 py-1.5 border border-gray-300 rounded-lg text-sm bg-white focus:outline-none focus:ring-2 focus:ring-[#0098C7]/30 focus:border-[#0098C7]"
>
<option value=""> Select </option>
{f.options.map(opt => (
<option key={opt} value={opt}>{opt}</option>
))}
</select>
) : (
<input
type={f.type === 'number' ? 'number' : f.type === 'date' ? 'date' : 'text'}
step={f.type === 'number' ? 'any' : undefined}
value={form[f.key] || ''}
onChange={e => setForm(prev => ({ ...prev, [f.key]: e.target.value }))}
required={f.required}
className="w-full px-2.5 py-1.5 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#0098C7]/30 focus:border-[#0098C7]"
/>
)}
</div>
))}
</div>
<div className="flex gap-2 mt-4">
<button type="submit" className="px-4 py-2 bg-[#0098C7] text-white text-sm font-semibold rounded-lg hover:bg-[#007ba3]">
{record ? 'Save Changes' : 'Add Record'}
</button>
<button type="button" onClick={onCancel} className="px-4 py-2 bg-gray-100 text-gray-600 text-sm font-medium rounded-lg hover:bg-gray-200">
Cancel
</button>
</div>
</form>
);
}
function DataTable({ table, onUpdate, showMessage }: {
table: string;
onUpdate: () => void;
showMessage: (type: 'success' | 'error', text: string) => void;
}) {
const [data, setData] = useState<Record<string, unknown>[]>([]);
const [loading, setLoading] = useState(true);
const [search, setSearch] = useState('');
const [showForm, setShowForm] = useState(false);
const [editRecord, setEditRecord] = useState<Record<string, unknown> | null>(null);
const loadData = async () => {
setLoading(true);
const res = await fetch('/api/admin', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'list', table }),
});
const result = await res.json();
setData(result.data || []);
setLoading(false);
};
useEffect(() => { loadData(); }, [table]);
const handleDelete = async (record: Record<string, unknown>) => {
if (!confirm('Delete this record?')) return;
await fetch('/api/admin', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'delete', table, record }),
});
showMessage('success', 'Record deleted');
loadData();
onUpdate();
};
const handleSave = async (record: Record<string, unknown>) => {
try {
const res = await fetch('/api/admin', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'upsert', table, record }),
});
const result = await res.json();
if (result.success) {
showMessage('success', editRecord ? 'Record updated' : 'Record added');
setShowForm(false);
setEditRecord(null);
loadData();
onUpdate();
} else {
showMessage('error', result.error || 'Save failed');
}
} catch (err) {
showMessage('error', String(err));
}
};
if (loading) return <div className="text-gray-500 text-sm">Loading...</div>;
const allKeys = data.length > 0 ? Object.keys(data[0]) : [];
const isAccounts = table === 'accounts';
const displayKeys = allKeys.filter(k => k !== 'id' && !(isAccounts && (k === 'Logo_URL' || k === 'Google_Drive_URL' || k === 'Campaign_Artifacts_URL' || k === 'Competitors')));
const filtered = data.filter(row =>
search === '' || Object.values(row).some(v => String(v ?? '').toLowerCase().includes(search.toLowerCase()))
);
return (
<div>
{(showForm || editRecord) && (
<RecordForm
table={table}
record={editRecord}
onSave={handleSave}
onCancel={() => { setShowForm(false); setEditRecord(null); }}
/>
)}
<div className="flex items-center gap-4 mb-4">
<input
type="text"
placeholder="Search records..."
value={search}
onChange={e => setSearch(e.target.value)}
className="px-3 py-2 border border-gray-300 rounded-lg text-sm w-64 focus:outline-none focus:ring-2 focus:ring-[#0098C7]"
/>
<span className="text-sm text-gray-500">{filtered.length} records</span>
{!showForm && !editRecord && (
<button
onClick={() => setShowForm(true)}
className="ml-auto px-4 py-2 bg-[#0098C7] text-white text-sm font-semibold rounded-lg hover:bg-[#007ba3] flex items-center gap-1.5"
>
<svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" /></svg>
Add Record
</button>
)}
</div>
<div className="overflow-x-auto bg-white rounded-xl border border-gray-200">
<table className="w-full text-sm">
<thead>
<tr className="bg-gray-50 border-b border-gray-200">
{displayKeys.map(k => (
<th key={k} className="text-left px-3 py-2.5 font-semibold text-gray-700 whitespace-nowrap">{k}</th>
))}
<th className="px-3 py-2.5 w-24"></th>
</tr>
</thead>
<tbody>
{filtered.slice(0, 200).map((row, i) => (
<tr key={i} className="border-b border-gray-100 hover:bg-gray-50">
{displayKeys.map(k => (
<td key={k} className="px-3 py-2 text-gray-700 whitespace-nowrap max-w-[200px] truncate" title={String(row[k] ?? '')}>
{isAccounts && k === 'Account_Name' ? (
<span className="flex items-center gap-2">
{row.Logo_URL ? (
<img src={String(row.Logo_URL)} alt="" className="w-5 h-5 rounded object-contain flex-shrink-0" onError={e => { (e.target as HTMLImageElement).style.display = 'none'; }} />
) : (
<span className="w-5 h-5 rounded bg-gray-200 flex-shrink-0 flex items-center justify-center text-[10px] font-bold text-gray-400">
{String(row[k] ?? '').charAt(0)}
</span>
)}
{String(row[k] ?? '')}
</span>
) : (
String(row[k] ?? '')
)}
</td>
))}
<td className="px-3 py-2 flex gap-2">
<button onClick={() => { setEditRecord(row); setShowForm(false); }} className="text-[#0098C7] hover:text-[#007ba3] text-xs font-medium">
Edit
</button>
<button onClick={() => handleDelete(row)} className="text-red-500 hover:text-red-700 text-xs font-medium">
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
{filtered.length > 200 && (
<div className="px-3 py-2 text-xs text-gray-400">Showing first 200 of {filtered.length} records</div>
)}
</div>
</div>
);
}
interface QualityIssue {
type: string;
severity: 'high' | 'medium' | 'low';
message: string;
table: string;
record_id: string;
}
interface QualityReport {
issues: QualityIssue[];
completeness: number;
totalAccounts: number;
totalPipeline: number;
}
function DataQualityPanel({ onNavigate }: { onNavigate: (tab: Tab) => void }) {
const [data, setData] = useState<QualityReport | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('/api/phase2', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'quality.report' }),
})
.then(r => r.json())
.then(d => { setData(d.data); setLoading(false); })
.catch(() => setLoading(false));
}, []);
if (loading) return <div className="text-gray-500 text-sm">Analyzing data quality...</div>;
if (!data) return <div className="text-gray-500 text-sm">Unable to load quality report.</div>;
const highCount = data.issues.filter(i => i.severity === 'high').length;
const medCount = data.issues.filter(i => i.severity === 'medium').length;
const lowCount = data.issues.filter(i => i.severity === 'low').length;
const circumference = 2 * Math.PI * 70;
const progress = (data.completeness / 100) * circumference;
const scoreColor = data.completeness >= 80 ? '#16A34A' : data.completeness >= 60 ? '#F59E0B' : '#EF4444';
const tableToTab = (table: string): Tab => {
if (table === 'accounts') return 'accounts';
if (table === 'pipeline') return 'pipeline';
if (table === 'activities') return 'activities';
return 'accounts';
};
return (
<div className="max-w-5xl space-y-6">
{/* Summary Row */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
{/* Completeness Score */}
<div className="bg-white rounded-xl border border-gray-200 p-6 flex flex-col items-center justify-center md:col-span-1">
<div className="relative w-40 h-40">
<svg viewBox="0 0 160 160" className="w-full h-full -rotate-90">
<circle cx="80" cy="80" r="70" fill="none" stroke="#E2E8F0" strokeWidth="10" />
<circle
cx="80" cy="80" r="70"
fill="none"
stroke={scoreColor}
strokeWidth="10"
strokeLinecap="round"
strokeDasharray={`${progress} ${circumference}`}
/>
</svg>
<div className="absolute inset-0 flex flex-col items-center justify-center">
<span className="text-3xl font-bold" style={{ color: scoreColor }}>{Math.round(data.completeness)}%</span>
<span className="text-xs text-gray-500">Completeness</span>
</div>
</div>
</div>
{/* Issue Counts */}
<div className="md:col-span-3 grid grid-cols-3 gap-4">
<div className="bg-white rounded-xl border border-gray-200 p-5">
<div className="flex items-center gap-2 mb-2">
<div className="w-3 h-3 rounded-full bg-red-500" />
<span className="text-xs font-medium text-gray-500 uppercase tracking-wider">High Severity</span>
</div>
<div className="text-3xl font-bold text-red-600">{highCount}</div>
<div className="text-xs text-gray-400 mt-1">issues need attention</div>
</div>
<div className="bg-white rounded-xl border border-gray-200 p-5">
<div className="flex items-center gap-2 mb-2">
<div className="w-3 h-3 rounded-full bg-amber-500" />
<span className="text-xs font-medium text-gray-500 uppercase tracking-wider">Medium Severity</span>
</div>
<div className="text-3xl font-bold text-amber-600">{medCount}</div>
<div className="text-xs text-gray-400 mt-1">issues to review</div>
</div>
<div className="bg-white rounded-xl border border-gray-200 p-5">
<div className="flex items-center gap-2 mb-2">
<div className="w-3 h-3 rounded-full bg-gray-400" />
<span className="text-xs font-medium text-gray-500 uppercase tracking-wider">Low Severity</span>
</div>
<div className="text-3xl font-bold text-gray-500">{lowCount}</div>
<div className="text-xs text-gray-400 mt-1">minor improvements</div>
</div>
</div>
</div>
{/* Coverage Info */}
<div className="bg-white rounded-xl border border-gray-200 p-4 flex items-center gap-6 text-sm">
<span className="text-gray-500">Scanned:</span>
<span className="font-semibold">{data.totalAccounts} accounts</span>
<span className="text-gray-300">|</span>
<span className="font-semibold">{data.totalPipeline} pipeline records</span>
<span className="text-gray-300">|</span>
<span className="font-semibold">{data.issues.length} total issues</span>
</div>
{/* Issues Table */}
{data.issues.length > 0 && (
<div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
<div className="px-5 py-3 border-b border-gray-200 bg-gray-50">
<h3 className="text-sm font-bold text-[#1B1D36]">Issues</h3>
</div>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-gray-200 bg-gray-50">
<th className="text-left px-4 py-2 font-semibold text-gray-600 w-24">Severity</th>
<th className="text-left px-4 py-2 font-semibold text-gray-600 w-24">Table</th>
<th className="text-left px-4 py-2 font-semibold text-gray-600 w-40">Record</th>
<th className="text-left px-4 py-2 font-semibold text-gray-600">Issue</th>
<th className="px-4 py-2 w-20"></th>
</tr>
</thead>
<tbody>
{(['high', 'medium', 'low'] as const).map(severity =>
data.issues
.filter(i => i.severity === severity)
.map((issue, idx) => (
<tr key={`${severity}-${idx}`} className="border-b border-gray-100 hover:bg-gray-50">
<td className="px-4 py-2">
<span className={`inline-block px-2 py-0.5 rounded-full text-[10px] font-semibold text-white ${
severity === 'high' ? 'bg-red-500' : severity === 'medium' ? 'bg-amber-500' : 'bg-gray-400'
}`}>
{severity}
</span>
</td>
<td className="px-4 py-2 text-gray-600 capitalize">{issue.table}</td>
<td className="px-4 py-2 text-gray-700 font-medium truncate max-w-[160px]" title={issue.record_id}>{issue.record_id}</td>
<td className="px-4 py-2 text-gray-600">{issue.message}</td>
<td className="px-4 py-2">
<button
onClick={() => onNavigate(tableToTab(issue.table))}
className="px-2.5 py-1 text-xs font-medium text-[#0098C7] hover:text-[#007ba3] border border-[#0098C7]/30 rounded-lg hover:bg-[#0098C7]/5 transition"
>
Fix
</button>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
)}
</div>
);
}