'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('import'); const [stats, setStats] = useState({ 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 (
← Dashboard

Data Admin

{stats.accounts} accounts {stats.pipeline} deals {stats.activities} activities {stats.targets} targets Goals & Progress
{message && (
{message.text}
)}
{(['import', 'accounts', 'pipeline', 'activities', 'targets', 'quality'] as Tab[]).map(t => ( ))}
{tab === 'import' && { refreshStats(); showMessage('success', 'Import complete!'); }} onError={showMessage} loading={loading} setLoading={setLoading} />} {tab === 'accounts' && } {tab === 'pipeline' && } {tab === 'activities' && } {tab === 'targets' && } {tab === 'quality' && setTab(t)} />}
); } 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('accounts'); const fileRef = useRef(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 (

Import from Google Sheets

Export each tab from your Google Sheet as CSV (File → Download → Comma-separated values), then upload them here. The import is idempotent — accounts and pipeline records are upserted by their ID, so re-importing is safe.

Quick Import: Upload All CSVs at Once

Name your files with the tab name (e.g. Pipeline.csv, Accounts.csv, Activity_Log.csv, Targets.csv).

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" />

Import Single Tab

{['accounts', 'pipeline', 'activities', 'targets'].map(t => ( ))}

Expected Column Headers

Your CSV files should have these headers in Row 1 (case-sensitive):

Accounts:{' '} Account_Name, District_Name, Tier, Priority, AgentMinder_Status (+ optional: Current_ARR_USD, Touch_Count, Date_First_Touched, Date_Last_Touched, MAP_In_Place_YN)
Pipeline:{' '} Opportunity_ID, Account_Name, District_Name, Stage, Forecast_Category, Amount_USD, Created_Date, Expected_Close_Date
Activity_Log:{' '} Activity_Date, Activity_Type, Account_Name, District_Name (+ optional: Contact_Name, Notes)
Targets:{' '} Account_Name, Implementation_Stage (+ optional: Go_Live_Date, Health_Status, Notes)
); } const FIELD_OPTIONS: Record = { 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 = { 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 | null; onSave: (data: Record) => void; onCancel: () => void; }) { const fields = TABLE_FIELDS[table] || []; const [form, setForm] = useState>(() => { const init: Record = {}; fields.forEach(f => { init[f.key] = record ? String(record[f.key] ?? '') : ''; }); return init; }); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); const data: Record = {}; 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 (

{record ? 'Edit Record' : 'Add New Record'}

{fields.map(f => (
{f.key === 'Competitors' && f.options ? (
{f.options.map(opt => { const selected = (form[f.key] || '').split(',').filter(Boolean); const checked = selected.includes(opt); return ( ); })}
) : f.options ? ( ) : ( 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]" /> )}
))}
); } function DataTable({ table, onUpdate, showMessage }: { table: string; onUpdate: () => void; showMessage: (type: 'success' | 'error', text: string) => void; }) { const [data, setData] = useState[]>([]); const [loading, setLoading] = useState(true); const [search, setSearch] = useState(''); const [showForm, setShowForm] = useState(false); const [editRecord, setEditRecord] = useState | 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) => { 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) => { 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
Loading...
; 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 (
{(showForm || editRecord) && ( { setShowForm(false); setEditRecord(null); }} /> )}
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]" /> {filtered.length} records {!showForm && !editRecord && ( )}
{displayKeys.map(k => ( ))} {filtered.slice(0, 200).map((row, i) => ( {displayKeys.map(k => ( ))} ))}
{k}
{isAccounts && k === 'Account_Name' ? ( {row.Logo_URL ? ( { (e.target as HTMLImageElement).style.display = 'none'; }} /> ) : ( {String(row[k] ?? '').charAt(0)} )} {String(row[k] ?? '')} ) : ( String(row[k] ?? '') )}
{filtered.length > 200 && (
Showing first 200 of {filtered.length} records
)}
); } 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(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
Analyzing data quality...
; if (!data) return
Unable to load quality report.
; 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 (
{/* Summary Row */}
{/* Completeness Score */}
{Math.round(data.completeness)}% Completeness
{/* Issue Counts */}
High Severity
{highCount}
issues need attention
Medium Severity
{medCount}
issues to review
Low Severity
{lowCount}
minor improvements
{/* Coverage Info */}
Scanned: {data.totalAccounts} accounts | {data.totalPipeline} pipeline records | {data.issues.length} total issues
{/* Issues Table */} {data.issues.length > 0 && (

Issues

{(['high', 'medium', 'low'] as const).map(severity => data.issues .filter(i => i.severity === severity) .map((issue, idx) => ( )) )}
Severity Table Record Issue
{severity} {issue.table} {issue.record_id} {issue.message}
)}
); }