Files
AI_CPA/frontend/src/pages/AdminUserDetail.jsx
T

868 lines
43 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useState, useEffect, useCallback, useRef } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { useToast } from '../context/ToastContext';
import ExpandableSummaryBlock from '../components/ExpandableSummaryBlock';
export default function AdminUserDetail() {
const [searchParams] = useSearchParams();
const userId = searchParams.get('user_id');
const navigate = useNavigate();
const { authFetch, user: currentUser } = useAuth();
const { showToast } = useToast();
const [userDetail, setUserDetail] = useState(null);
const [documents, setDocuments] = useState([]);
const [showAiSummary, setShowAiSummary] = useState({});
const [activeTab, setActiveTab] = useState('personal');
const [taxYear, setTaxYear] = useState("");
const [loading, setLoading] = useState(true);
// States for Review Emails
const [personalTimeline, setPersonalTimeline] = useState(0);
const [businessTimeline, setBusinessTimeline] = useState(0);
// Reject comment panel: { docId, type, note }
const [rejectPanel, setRejectPanel] = useState(null);
// Export Excel Function
const exportToExcel = async () => {
try {
showToast("Preparing Excel export...", "info");
const res = await authFetch(`/api/upload/admin/users/${userId}/export`);
if (res.ok) {
const blob = await res.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `user_${userId}_excel_summaries.zip`;
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
showToast("Excel export ready!", "success");
} else {
showToast("Failed to export Excel file", "error");
}
} catch (err) {
console.error(err);
showToast("Error exporting Excel file", "error");
}
};
// States for Audit Log
const [auditLog, setAuditLog] = useState([]);
const [auditLoaded, setAuditLoaded] = useState(false);
const [deadlines, setDeadlines] = useState([]);
const adminDocInputRef = useRef(null);
const fetchUserDetails = useCallback(async () => {
setLoading(true);
try {
const url = taxYear ? `/api/upload/admin/users/${userId}/documents?tax_year=${taxYear}` : `/api/upload/admin/users/${userId}/documents`;
const res = await authFetch(url);
if (!res.ok) {
if (res.status === 403) navigate('/admin-dashboard');
return;
}
const payload = await res.json();
setUserDetail(payload.user);
const userDocs = (payload.documents || []).map(d => ({ ...d, type: d.table }));
const adminDocsRes = await authFetch(`/api/upload/admin-documents?user_id=${userId}`);
let adminDocs = [];
if (adminDocsRes.ok) {
adminDocs = await adminDocsRes.json();
adminDocs = adminDocs.map(d => ({ ...d, type: 'admin', uploaded_at: d.created_at }));
}
const allDocs = [...userDocs, ...adminDocs];
setDocuments(allDocs);
// Fetch filing deadlines
try {
const dlRes = await authFetch(`/api/review/deadlines/${userId}`);
if (dlRes.ok) setDeadlines(await dlRes.json());
} catch {}
} catch (err) {
console.error(err);
} finally {
setLoading(false);
}
}, [authFetch, navigate, taxYear, userId]);
useEffect(() => {
if (!userId) {
navigate('/admin-dashboard');
return;
}
fetchUserDetails();
}, [userId, taxYear, navigate, fetchUserDetails]);
const loadAuditLog = useCallback(async () => {
try {
const res = await authFetch(`/api/auth/admin/audit-logs?user_id=${userId}&limit=30`);
if (res.ok) {
setAuditLog(await res.json());
setAuditLoaded(true);
}
} catch (err) {
console.error(err);
}
}, [authFetch, userId]);
useEffect(() => {
if (activeTab === 'audit' && !auditLoaded) {
loadAuditLog();
}
}, [activeTab, auditLoaded, loadAuditLog]);
// Auto-refresh if any doc is still awaiting AI extraction (background task lag)
useEffect(() => {
const hasPending = documents.some(
d => (d.type === 'personal' || d.type === 'business') && d.extracted_data === null
);
if (!hasPending) return;
const timer = setTimeout(() => fetchUserDetails(), 5000);
return () => clearTimeout(timer);
}, [documents, fetchUserDetails]);
const deleteUser = async () => {
if (!window.confirm("WARNING: This will permanently delete this user, all their documents, and their audit history. Are you sure?")) return;
try {
const res = await authFetch(`/api/upload/admin/users/${userId}`, { method: "DELETE" });
if (res.ok) {
navigate('/admin-dashboard');
} else {
alert("Failed to delete user");
}
} catch (err) { console.error(err);
console.error("Error deleting user", err);
}
};
const handleChangeRole = async (newRole) => {
if (!window.confirm(`Change user role to ${newRole}?`)) return;
try {
const res = await authFetch(`/api/auth/admin/users/${userId}/role`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ role: newRole })
});
if (res.ok) {
showToast("Role updated successfully", "success");
fetchUserDetails();
} else {
const data = await res.json();
showToast(data.detail || "Failed to change role", "error");
}
} catch (err) { console.error(err);
showToast("Network error", "error");
}
};
const handleDocApprove = async (docId, type, isApproved, note = '') => {
try {
const status = isApproved ? 'approved' : 'rejected';
const ep = type === "personal" ? `/api/upload/personal-documents/${docId}/review-status` : `/api/upload/business-documents/${docId}/review-status`;
const res = await authFetch(ep, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ status, note })
});
if (res.ok) {
setRejectPanel(null);
fetchUserDetails(); // reload docs
} else {
showToast("Failed to save review status", "error");
}
} catch (err) { console.error(err);
showToast("Approval error", "error");
}
};
const openRejectPanel = (docId, type) => {
setRejectPanel({ docId, type, note: '' });
};
const deleteAdminDoc = async (docId) => {
if (!window.confirm("Delete this admin document?")) return;
try {
const res = await authFetch(`/api/upload/admin-documents/${docId}`, { method: "DELETE" });
if (res.ok) {
showToast("Document deleted", "success");
fetchUserDetails();
}
} catch(err) {
console.error(err);
}
};
const uploadAdminDoc = async (file) => {
const fd = new FormData();
fd.append("file", file);
fd.append("user_id", userId);
// doc_key and doc_label are required by the backend
const label = file.name.replace(/\.[^.]+$/, ''); // strip extension for a clean label
fd.append("doc_key", `admin_${Date.now()}`);
fd.append("doc_label", label);
try {
const res = await authFetch("/api/upload/admin-documents", {
method: "POST",
body: fd
});
if (res.ok) {
showToast("Admin document uploaded", "success");
fetchUserDetails();
} else {
showToast("Failed to upload admin document", "error");
}
} catch (err) { console.error(err);
showToast("Upload failed", "error");
}
};
const viewDoc = async (storageKey) => {
try {
const res = await authFetch(`/api/upload/view-url?key=${encodeURIComponent(storageKey)}`);
if (res.ok) {
const data = await res.json();
window.open(data.url, "_blank");
} else {
showToast("Could not generate view link", "error");
}
} catch (err) { console.error(err);
showToast("Could not generate view link", "error");
}
};
const handleUpdateExtractedData = async (docId, type, newData) => {
try {
const res = await authFetch(`/api/upload/${type}-documents/${docId}/extracted-data`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ extracted_data: newData })
});
if (res.ok) {
showToast("AI Summary updated successfully", "success");
fetchUserDetails();
} else {
showToast("Failed to update AI Summary", "error");
throw new Error("Failed to update");
}
} catch (err) {
console.error(err);
showToast("Network error while updating", "error");
throw err;
}
};
const sendEmail = async (type) => {
const docsToReview = documents.filter(d => d.type === type);
const approved = docsToReview.filter(d => d.review_status === "approved").map(d => d.doc_type);
const rejected = docsToReview.filter(d => d.review_status === "rejected").map(d => d.doc_type);
if (approved.length === 0 && rejected.length === 0) {
showToast(`No ${type} documents selected.`, "warning");
return;
}
try {
const res = await authFetch("/api/review/notify-user", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
user_id: userId,
type: type,
approved: approved,
rejected: rejected,
personal_timeline: type === "personal" ? personalTimeline : 0,
business_timeline: type === "business" ? businessTimeline : 0
})
});
if (res.ok) {
showToast(`${type.charAt(0).toUpperCase() + type.slice(1)} approval email sent`, "success");
} else {
showToast("Failed to send email", "error");
}
} catch (err) { console.error(err);
showToast("Error sending email", "error");
}
};
const submitAllDocs = async () => {
if (!window.confirm("Submit all documents for review?\nAn email will be sent to the user.")) return;
try {
const res = await authFetch("/api/review/submit", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ user_id: userId })
});
if (res.ok) {
showToast("Documents submitted — email sent to user.", "success");
} else {
showToast("Failed to submit", "error");
}
} catch (err) { console.error(err);
showToast("Error submitting documents", "error");
}
};
if (loading && !userDetail) {
return <div className=""><div className="empty-state"><div className="empty-title">Loading user details...</div></div></div>;
}
if (!userDetail) {
return <div className=""><div className="empty-state"><div className="empty-title">User not found</div></div></div>;
}
const exportAllToZip = async () => {
try {
showToast("Preparing ZIP export... This may take a moment.", "info");
const url = taxYear ? `/api/upload/admin/users/${userId}/export-zip?tax_year=${taxYear}` : `/api/upload/admin/users/${userId}/export-zip`;
const res = await authFetch(url);
if (res.ok) {
const blob = await res.blob();
const downloadUrl = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = downloadUrl;
const safeName = (userDetail?.name || userDetail?.email?.split('@')[0] || `user_${userId}`).replace(/[^a-zA-Z0-9_\- ]/g, '_').trim();
a.download = `${safeName}_documents_${taxYear ? taxYear : 'all'}.zip`;
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(downloadUrl);
showToast("ZIP export ready!", "success");
} else {
showToast("Failed to export ZIP file", "error");
}
} catch (err) {
console.error(err);
showToast("Error exporting ZIP file", "error");
}
};
const currentYear = new Date().getFullYear();
const yearOptions = [currentYear - 1, currentYear, currentYear + 1];
const personalDocs = documents.filter(d => d.type === "personal");
const businessDocs = documents.filter(d => d.type === "business");
const returnDocs = documents.filter(d => d.type === "admin");
return (
<div className="">
<button className="btn btn-secondary btn-sm" style={{ marginBottom: '16px', display: 'inline-flex', alignItems: 'center', gap: '4px', borderRadius: 'var(--radius-sm)' }} onClick={() => navigate('/admin-dashboard')}>
<span className="material-symbols-outlined" style={{ fontSize: '18px' }}>arrow_back</span>
Back to Dashboard
</button>
{/* User Info Bar */}
<div className="card aud-user-bar" style={{marginBottom: '20px'}}>
<div className="aud-bar-inner">
<div className="aud-bar-left">
<div style={{width:'52px', height:'52px', borderRadius:'50%', background:'linear-gradient(135deg,var(--header-bg),var(--blue-light))', display:'flex', alignItems:'center', justifyContent:'center', fontWeight:700, fontSize:'20px', color:'var(--navy)', flexShrink:0}}>
{(userDetail.name || "U").charAt(0).toUpperCase()}
</div>
<div>
<div style={{fontWeight:700, fontSize:'18px', color:'var(--navy)'}}>{userDetail.name || "—"}</div>
<div style={{fontSize:'13px', color:'var(--muted)', marginTop:'2px'}}>{userDetail.email}</div>
<div style={{display:'flex', gap:'8px', marginTop:'6px', flexWrap:'wrap'}}>
{currentUser?.role === 'super_admin' && currentUser.id !== userDetail.id ? (
<select
className="select-input"
style={{padding: '2px 8px', fontSize: '12px', height: 'auto', borderRadius: 'var(--radius-pill)', background: 'var(--card)', border: '1px solid var(--border)'}}
value={userDetail.role}
onChange={(e) => handleChangeRole(e.target.value)}
>
<option value="user">user</option>
<option value="admin">admin</option>
{userDetail.role === 'super_admin' && <option value="super_admin" disabled>super_admin</option>}
</select>
) : (
<span className={`badge ${userDetail.role === 'super_admin' ? 'badge-red' : userDetail.role === 'admin' ? 'badge-orange' : 'badge-blue'}`}>{userDetail.role}</span>
)}
{!userDetail.engagement_acknowledged_at && (
<span className="badge badge-yellow"><span className="material-symbols-outlined" style={{fontSize: '14px'}}>pending</span> Engagement not acknowledged</span>
)}
</div>
{/* Doc count summary */}
<div style={{display:'flex', gap:'12px', marginTop:'10px', flexWrap:'wrap'}}>
<div className="doc-count-chip">
<span className="material-symbols-outlined" style={{fontSize:'14px', color:'var(--emerald)'}}>description</span>
<span style={{fontWeight:600, color:'var(--navy)'}}>{personalDocs.length}</span>
<span style={{color:'var(--muted)'}}>personal</span>
</div>
<div className="doc-count-chip">
<span className="material-symbols-outlined" style={{fontSize:'14px', color:'var(--brass)'}}>business</span>
<span style={{fontWeight:600, color:'var(--navy)'}}>{businessDocs.length}</span>
<span style={{color:'var(--muted)'}}>business</span>
</div>
<div className="doc-count-chip">
<span className="material-symbols-outlined" style={{fontSize:'14px', color:'var(--muted)'}}>upload_file</span>
<span style={{fontWeight:600, color:'var(--navy)'}}>{returnDocs.length}</span>
<span style={{color:'var(--muted)'}}>returns</span>
</div>
<div className="doc-count-chip" style={{borderLeft:'1px solid var(--border)', paddingLeft:'12px'}}>
<span className="material-symbols-outlined" style={{fontSize:'14px', color:'var(--muted)'}}>folder</span>
<span style={{fontWeight:700, color:'var(--navy)'}}>{personalDocs.length + businessDocs.length + returnDocs.length}</span>
<span style={{color:'var(--muted)'}}>total</span>
</div>
</div>
</div>
</div>
<div className="aud-bar-actions">
<button className="btn btn-primary btn-sm" onClick={submitAllDocs} style={{borderRadius:'var(--radius-sm)'}}>Trigger Submit Review</button>
<div className="aud-year-picker">
<label className="form-label" style={{margin:0, fontSize: '11px'}}>Tax Year</label>
<select className="select-input" style={{width: 'auto', padding: '6px 12px', fontSize: '13px'}} value={taxYear} onChange={(e) => setTaxYear(e.target.value)}>
<option value="">All Years</option>
{yearOptions.map(y => <option key={y} value={y}>{y}</option>)}
</select>
</div>
<button className="btn btn-secondary btn-sm" onClick={exportAllToZip} style={{borderRadius:'var(--radius-sm)'}} title="Download All Docs (ZIP)"><span className="material-symbols-outlined" style={{fontSize: '18px'}}>archive</span></button>
<button className="btn btn-danger btn-sm" onClick={deleteUser} style={{borderRadius:'var(--radius-sm)'}}>Delete User</button>
</div>
</div>
</div>
{/* Tabs */}
<div className="tab-bar">
<button className={`tab-btn ${activeTab === 'personal' ? 'active' : ''}`} onClick={() => setActiveTab('personal')}><span className="material-symbols-outlined">description</span> Personal Docs</button>
<button className={`tab-btn ${activeTab === 'business' ? 'active' : ''}`} onClick={() => setActiveTab('business')}><span className="material-symbols-outlined">business</span> Business Docs</button>
<button className={`tab-btn ${activeTab === 'returns' ? 'active' : ''}`} onClick={() => setActiveTab('returns')}>📤 Returns for Review</button>
<button className={`tab-btn ${activeTab === 'audit' ? 'active' : ''}`} onClick={() => setActiveTab('audit')}><span className="material-symbols-outlined">history</span> Audit Trail</button>
</div>
{/* Tab: Personal */}
{activeTab === 'personal' && (
<div className="tab-panel active">
<div className="doc-review-layout">
<div className="doc-review-main">
<div className="card-flat">
{personalDocs.length === 0 ? (
<p className="text-muted">No personal documents uploaded{taxYear ? ` for ${taxYear}` : ''}.</p>
) : (
personalDocs.map(doc => (
<div key={doc.id} className="doc-review-row">
<div className="doc-review-row-top">
<div className="doc-review-info">
<div style={{ fontWeight:700, fontSize:'15px', color:'var(--navy)', lineHeight:'1.3' }}>{doc.doc_type}</div>
<div style={{ fontSize:'12px', color:'var(--muted)', marginTop:'3px' }}>
<span className="material-symbols-outlined" style={{fontSize:'12px', verticalAlign:'middle', marginRight:'3px'}}>calendar_today</span>
{new Date(doc.uploaded_at).toLocaleDateString('en-US', {year:'numeric', month:'short', day:'numeric'})}
{doc.tax_year && <span style={{marginLeft:'8px', fontWeight:600, color:'var(--brass)'}}>TY {doc.tax_year}</span>}
</div>
{doc.notes && <div style={{ fontSize:'12px', color:'var(--warn)', marginTop:'3px', fontWeight:500 }}>⚠ {doc.notes}</div>}
{doc.review_status && (
<div style={{ marginTop:'5px', display:'flex', alignItems:'center', gap:'8px', flexWrap:'wrap' }}>
<span className={`badge ${doc.review_status === 'approved' ? 'badge-green' : doc.review_status === 'rejected' ? 'badge-red' : 'badge-yellow'}`} style={{fontWeight:700}}>
{doc.review_status.toUpperCase()}
</span>
{doc.review_status === 'rejected' && doc.review_note && (
<span style={{fontSize:'12px', color:'#c0392b', fontStyle:'italic'}}>"{doc.review_note}"</span>
)}
</div>
)}
</div>
<div className="doc-review-actions">
<button onClick={() => viewDoc(doc.storage_key)} className="btn btn-secondary btn-sm" style={{borderRadius:'var(--radius-sm)'}}>View</button>
<button className="btn btn-secondary btn-sm" style={{borderRadius:'var(--radius-sm)'}} onClick={() => handleDocApprove(doc.id, doc.type, true)}>Approve</button>
<button className="btn btn-danger btn-sm" style={{borderRadius:'var(--radius-sm)'}} onClick={() => openRejectPanel(doc.id, doc.type)}>Reject</button>
<button
className="btn btn-secondary btn-sm"
style={{borderRadius:'var(--radius-sm)'}}
onClick={() => setShowAiSummary(prev => ({ ...prev, [doc.id]: !prev[doc.id] }))}
>
<span className="material-symbols-outlined" style={{fontSize: '16px', marginRight: '4px', verticalAlign: 'middle'}}>
{showAiSummary[doc.id] ? 'visibility_off' : 'auto_awesome'}
</span>
{showAiSummary[doc.id] ? 'Hide AI Summary' : 'View AI Summary'}
</button>
</div>
</div>
{/* Inline Reject Comment Panel */}
{rejectPanel?.docId === doc.id && rejectPanel?.type === doc.type && (
<div style={{
marginTop: '12px',
padding: '14px 16px',
background: 'rgba(220,53,69,0.05)',
border: '1px solid rgba(220,53,69,0.25)',
borderRadius: 'var(--radius-sm)',
display: 'flex',
flexDirection: 'column',
gap: '10px'
}}>
<div style={{fontWeight:600, fontSize:'13px', color:'#c0392b', display:'flex', alignItems:'center', gap:'6px'}}>
<span className="material-symbols-outlined" style={{fontSize:'16px'}}>feedback</span>
Reason for Rejection (optional)
</div>
<textarea
rows={3}
placeholder="Explain why this document is being rejected..."
value={rejectPanel.note}
onChange={e => setRejectPanel(prev => ({...prev, note: e.target.value}))}
style={{
width: '100%',
padding: '10px 12px',
border: '1px solid rgba(220,53,69,0.35)',
borderRadius: 'var(--radius-sm)',
fontSize: '13px',
resize: 'vertical',
outline: 'none',
fontFamily: 'inherit',
background: 'white',
boxSizing: 'border-box'
}}
/>
<div style={{display:'flex', gap:'8px', justifyContent:'flex-end'}}>
<button
className="btn btn-secondary btn-sm"
style={{borderRadius:'var(--radius-sm)'}}
onClick={() => setRejectPanel(null)}
>Cancel</button>
<button
className="btn btn-danger btn-sm"
style={{borderRadius:'var(--radius-sm)'}}
onClick={() => handleDocApprove(doc.id, doc.type, false, rejectPanel.note)}
>
<span className="material-symbols-outlined" style={{fontSize:'15px', verticalAlign:'middle', marginRight:'4px'}}>block</span>
Confirm Rejection
</button>
</div>
</div>
)}
{showAiSummary[doc.id] && (
<>
{doc.extracted_data && Object.keys(doc.extracted_data).length > 0 ? (
<div className="ai-summary-block">
<div className="ai-summary-label">
<span className="material-symbols-outlined" style={{ fontSize: '14px', verticalAlign: 'middle', marginRight: '4px' }}>auto_awesome</span>
AI Summary
</div>
<ExpandableSummaryBlock
extractedData={doc.extracted_data}
onSave={(newData) => handleUpdateExtractedData(doc.id, doc.type, newData)}
/>
</div>
) : doc.extracted_data === null ? (
<div className="ai-summary-block" style={{ opacity: 0.6 }}>
<div className="ai-summary-label">
<span className="material-symbols-outlined" style={{ fontSize: '14px', verticalAlign: 'middle', marginRight: '4px', animation: 'spin 1.2s linear infinite' }}>progress_activity</span>
AI Summary — Processing…
</div>
</div>
) : null}
</>
)}
</div>
))
)}
</div>
</div>
<div className="doc-review-sidebar">
<div className="card-flat" style={{display:'flex', flexDirection:'column', gap:'16px'}}>
<h3>Filing Timeline</h3>
{deadlines.filter(d => d.doc_type === 'personal').map(d => (
<div key="personal-dl" style={{
margin: '0 0 16px', padding: '12px 16px',
borderRadius: 'var(--radius-sm)',
background: d.is_overdue ? 'rgba(220,53,69,0.08)' : d.days_left <= 1 ? 'rgba(255,140,0,0.10)' : 'rgba(44,122,91,0.08)',
border: `1px solid ${d.is_overdue ? 'rgba(220,53,69,0.3)' : d.days_left <= 1 ? 'rgba(255,140,0,0.35)' : 'rgba(44,122,91,0.20)'}`,
display: 'flex', alignItems: 'center', gap: '10px'
}}>
<span className="material-symbols-outlined" style={{fontSize:'20px', color: d.is_overdue ? '#dc3545' : d.days_left <= 1 ? '#ff8c00' : 'var(--accent)'}}>
{d.is_overdue ? 'warning' : 'schedule'}
</span>
<div>
<div style={{fontWeight: 600, fontSize: '13px', color: d.is_overdue ? '#dc3545' : d.days_left <= 1 ? '#ff8c00' : 'var(--navy)'}}>
{d.is_overdue ? `OVERDUE by ${Math.abs(d.days_left)} day${Math.abs(d.days_left) !== 1 ? 's' : ''}` : `${d.days_left} day${d.days_left !== 1 ? 's' : ''} remaining`}
</div>
<div style={{fontSize: '11px', color: 'var(--muted)'}}>Deadline: {new Date(d.deadline_date).toLocaleDateString('en-US', {year:'numeric',month:'long',day:'numeric'})}</div>
</div>
</div>
))}
<div className="timeline-control">
<button className="tl-btn" onClick={() => setPersonalTimeline(Math.max(0, personalTimeline - 1))}>−</button>
<div>
<div className="tl-value">{personalTimeline}</div>
<div className="tl-label">days</div>
</div>
<button className="tl-btn" onClick={() => setPersonalTimeline(personalTimeline + 1)}>+</button>
</div>
<button className="btn btn-secondary w-full" style={{borderRadius:'var(--radius-sm)'}} onClick={() => sendEmail("personal")}>
Send Personal Approval Email
</button>
</div>
</div>
</div>
</div>
)}
{/* Tab: Business */}
{activeTab === 'business' && (
<div className="tab-panel active">
<div className="doc-review-layout">
<div className="doc-review-main">
<div className="card-flat">
{businessDocs.length === 0 ? (
<p className="text-muted">No business documents uploaded{taxYear ? ` for ${taxYear}` : ''}.</p>
) : (
businessDocs.map(doc => (
<div key={doc.id} className="doc-review-row">
<div className="doc-review-row-top">
<div className="doc-review-info">
<div style={{ fontWeight:700, fontSize:'15px', color:'var(--navy)', lineHeight:'1.3' }}>{doc.doc_type}</div>
<div style={{ fontSize:'12px', color:'var(--muted)', marginTop:'3px' }}>
<span className="material-symbols-outlined" style={{fontSize:'12px', verticalAlign:'middle', marginRight:'3px'}}>calendar_today</span>
{new Date(doc.uploaded_at).toLocaleDateString('en-US', {year:'numeric', month:'short', day:'numeric'})}
{doc.tax_year && <span style={{marginLeft:'8px', fontWeight:600, color:'var(--brass)'}}>TY {doc.tax_year}</span>}
</div>
{doc.notes && <div style={{ fontSize:'12px', color:'var(--warn)', marginTop:'3px', fontWeight:500 }}>⚠ {doc.notes}</div>}
{doc.review_status && (
<div style={{ marginTop:'5px', display:'flex', alignItems:'center', gap:'8px', flexWrap:'wrap' }}>
<span className={`badge ${doc.review_status === 'approved' ? 'badge-green' : doc.review_status === 'rejected' ? 'badge-red' : 'badge-yellow'}`} style={{fontWeight:700}}>
{doc.review_status.toUpperCase()}
</span>
{doc.review_status === 'rejected' && doc.review_note && (
<span style={{fontSize:'12px', color:'#c0392b', fontStyle:'italic'}}>"{doc.review_note}"</span>
)}
</div>
)}
</div>
<div className="doc-review-actions">
<button onClick={() => viewDoc(doc.storage_key)} className="btn btn-secondary btn-sm" style={{borderRadius:'var(--radius-sm)'}}>View</button>
<button className="btn btn-secondary btn-sm" style={{borderRadius:'var(--radius-sm)'}} onClick={() => handleDocApprove(doc.id, doc.type, true)}>Approve</button>
<button className="btn btn-danger btn-sm" style={{borderRadius:'var(--radius-sm)'}} onClick={() => openRejectPanel(doc.id, doc.type)}>Reject</button>
<button
className="btn btn-secondary btn-sm"
style={{borderRadius:'var(--radius-sm)'}}
onClick={() => setShowAiSummary(prev => ({ ...prev, [doc.id]: !prev[doc.id] }))}
>
<span className="material-symbols-outlined" style={{fontSize: '16px', marginRight: '4px', verticalAlign: 'middle'}}>
{showAiSummary[doc.id] ? 'visibility_off' : 'auto_awesome'}
</span>
{showAiSummary[doc.id] ? 'Hide AI Summary' : 'View AI Summary'}
</button>
</div>
</div>
{/* Inline Reject Comment Panel */}
{rejectPanel?.docId === doc.id && rejectPanel?.type === doc.type && (
<div style={{
marginTop: '12px',
padding: '14px 16px',
background: 'rgba(220,53,69,0.05)',
border: '1px solid rgba(220,53,69,0.25)',
borderRadius: 'var(--radius-sm)',
display: 'flex',
flexDirection: 'column',
gap: '10px'
}}>
<div style={{fontWeight:600, fontSize:'13px', color:'#c0392b', display:'flex', alignItems:'center', gap:'6px'}}>
<span className="material-symbols-outlined" style={{fontSize:'16px'}}>feedback</span>
Reason for Rejection (optional)
</div>
<textarea
rows={3}
placeholder="Explain why this document is being rejected..."
value={rejectPanel.note}
onChange={e => setRejectPanel(prev => ({...prev, note: e.target.value}))}
style={{
width: '100%',
padding: '10px 12px',
border: '1px solid rgba(220,53,69,0.35)',
borderRadius: 'var(--radius-sm)',
fontSize: '13px',
resize: 'vertical',
outline: 'none',
fontFamily: 'inherit',
background: 'white',
boxSizing: 'border-box'
}}
/>
<div style={{display:'flex', gap:'8px', justifyContent:'flex-end'}}>
<button
className="btn btn-secondary btn-sm"
style={{borderRadius:'var(--radius-sm)'}}
onClick={() => setRejectPanel(null)}
>Cancel</button>
<button
className="btn btn-danger btn-sm"
style={{borderRadius:'var(--radius-sm)'}}
onClick={() => handleDocApprove(doc.id, doc.type, false, rejectPanel.note)}
>
<span className="material-symbols-outlined" style={{fontSize:'15px', verticalAlign:'middle', marginRight:'4px'}}>block</span>
Confirm Rejection
</button>
</div>
</div>
)}
{showAiSummary[doc.id] && (
<>
{doc.extracted_data && Object.keys(doc.extracted_data).length > 0 ? (
<div className="ai-summary-block">
<div className="ai-summary-label">
<span className="material-symbols-outlined" style={{ fontSize: '14px', verticalAlign: 'middle', marginRight: '4px' }}>auto_awesome</span>
AI Summary
</div>
<ExpandableSummaryBlock
extractedData={doc.extracted_data}
onSave={(newData) => handleUpdateExtractedData(doc.id, doc.type, newData)}
/>
</div>
) : doc.extracted_data === null ? (
<div className="ai-summary-block" style={{ opacity: 0.6 }}>
<div className="ai-summary-label">
<span className="material-symbols-outlined" style={{ fontSize: '14px', verticalAlign: 'middle', marginRight: '4px', animation: 'spin 1.2s linear infinite' }}>progress_activity</span>
AI Summary — Processing…
</div>
</div>
) : null}
</>
)}
</div>
))
)}
</div>
</div>
<div className="doc-review-sidebar">
<div className="card-flat" style={{display:'flex', flexDirection:'column', gap:'16px'}}>
<h3>Filing Timeline</h3>
{deadlines.filter(d => d.doc_type === 'business').map(d => (
<div key="business-dl" style={{
margin: '0 0 16px', padding: '12px 16px',
borderRadius: 'var(--radius-sm)',
background: d.is_overdue ? 'rgba(220,53,69,0.08)' : d.days_left <= 1 ? 'rgba(255,140,0,0.10)' : 'rgba(44,122,91,0.08)',
border: `1px solid ${d.is_overdue ? 'rgba(220,53,69,0.3)' : d.days_left <= 1 ? 'rgba(255,140,0,0.35)' : 'rgba(44,122,91,0.20)'}`,
display: 'flex', alignItems: 'center', gap: '10px'
}}>
<span className="material-symbols-outlined" style={{fontSize:'20px', color: d.is_overdue ? '#dc3545' : d.days_left <= 1 ? '#ff8c00' : 'var(--accent)'}}>
{d.is_overdue ? 'warning' : 'schedule'}
</span>
<div>
<div style={{fontWeight: 600, fontSize: '13px', color: d.is_overdue ? '#dc3545' : d.days_left <= 1 ? '#ff8c00' : 'var(--navy)'}}>
{d.is_overdue ? `OVERDUE by ${Math.abs(d.days_left)} day${Math.abs(d.days_left) !== 1 ? 's' : ''}` : `${d.days_left} day${d.days_left !== 1 ? 's' : ''} remaining`}
</div>
<div style={{fontSize: '11px', color: 'var(--muted)'}}>Deadline: {new Date(d.deadline_date).toLocaleDateString('en-US', {year:'numeric',month:'long',day:'numeric'})}</div>
</div>
</div>
))}
<div className="timeline-control">
<button className="tl-btn" onClick={() => setBusinessTimeline(Math.max(0, businessTimeline - 1))}>−</button>
<div>
<div className="tl-value">{businessTimeline}</div>
<div className="tl-label">days</div>
</div>
<button className="tl-btn" onClick={() => setBusinessTimeline(businessTimeline + 1)}>+</button>
</div>
<button className="btn btn-secondary w-full" style={{borderRadius:'var(--radius-sm)'}} onClick={() => sendEmail("business")}>
Send Business Approval Email
</button>
</div>
</div>
</div>
</div>
)}
{/* Tab: Returns */}
{activeTab === 'returns' && (
<div className="tab-panel active">
<div className="card-flat">
<div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:'16px'}}>
<h3 style={{margin:0}}>Admin Documents</h3>
<div>
<input type="file" hidden ref={adminDocInputRef} accept=".pdf,.doc,.docx,.xls,.xlsx" onChange={e => {if(e.target.files[0]) uploadAdminDoc(e.target.files[0])}} />
<button className="btn btn-primary btn-sm" style={{borderRadius:'var(--radius-sm)'}} onClick={() => adminDocInputRef.current?.click()}>+ Upload Document</button>
</div>
</div>
{returnDocs.length === 0 ? (
<p className="text-muted">No returns or final documents uploaded yet.</p>
) : (
<div className="table-responsive">
<table className="admin-table">
<thead>
<tr>
<th>Filename</th>
<th>Date</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{returnDocs.map(doc => (
<tr key={doc.id}>
<td>
<div style={{fontWeight:500, color:'var(--navy)'}}>{doc.filename}</div>
</td>
<td>{new Date(doc.uploaded_at).toLocaleDateString()}</td>
<td>
<div style={{display:'flex', gap:'8px'}}>
<button className="btn btn-secondary btn-sm" onClick={() => viewDoc(doc.storage_key)}>View</button>
<button className="btn btn-danger btn-sm" onClick={() => deleteAdminDoc(doc.id)}>Delete</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
)}
{/* Tab: Audit */}
{activeTab === 'audit' && (
<div className="tab-panel active">
<div className="card-flat">
<h3 style={{marginBottom:'16px'}}>Recent Activity</h3>
{auditLog.length === 0 ? (
<p className="text-muted">No audit logs found.</p>
) : (
<div className="table-responsive">
<table className="admin-table">
<thead>
<tr>
<th>Date</th>
<th>Action</th>
<th>Details</th>
<th>IP / Agent</th>
</tr>
</thead>
<tbody>
{auditLog.map(log => (
<tr key={log.id}>
<td style={{whiteSpace:'nowrap', color:'var(--muted)'}}>{new Date(log.created_at).toLocaleString()}</td>
<td><span className="badge badge-blue">{log.action}</span></td>
<td>{log.detail}</td>
<td className="text-sm text-muted">
{log.ip_address}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
)}
</div>
);
}