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

1139 lines
57 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';
import ConfirmModal from '../components/ConfirmModal';
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 [docSort, setDocSort] = useState("newest");
const [loading, setLoading] = useState(true);
// State for ConfirmModal
const [confirmConfig, setConfirmConfig] = useState({
isOpen: false,
title: "",
message: "",
confirmText: "OK",
isDestructive: false,
onConfirm: () => {}
});
// 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);
// Send-for-approval panel: { docId, note }
const [sendApprovalPanel, setSendApprovalPanel] = useState(null);
const [sendingApproval, setSendingApproval] = useState(false);
const [markFiledLoading, setMarkFiledLoading] = useState(false);
// 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 () => {
setConfirmConfig({
isOpen: true,
title: "Delete User",
message: "WARNING: This will permanently delete this user, all their documents, and their audit history. Are you sure?",
isDestructive: true,
confirmText: "Delete User",
onConfirm: async () => {
setConfirmConfig(prev => ({ ...prev, isOpen: false }));
try {
const res = await authFetch(`/api/upload/admin/users/${userId}`, { method: "DELETE" });
if (res.ok) {
navigate('/admin-dashboard');
} else {
showToast("Failed to delete user", "error");
}
} catch (err) { console.error(err);
console.error("Error deleting user", err);
}
}
});
};
const handleChangeRole = async (newRole) => {
setConfirmConfig({
isOpen: true,
title: "Change Role",
message: `Change user role to ${newRole}?`,
isDestructive: false,
confirmText: "Confirm",
onConfirm: async () => {
setConfirmConfig(prev => ({ ...prev, isOpen: false }));
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) => {
setConfirmConfig({
isOpen: true,
title: "Delete Document",
message: "Delete this admin document?",
isDestructive: true,
confirmText: "Delete",
onConfirm: async () => {
setConfirmConfig(prev => ({ ...prev, isOpen: false }));
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 sendReturnForApproval = async (docId, note = "") => {
setSendingApproval(true);
try {
const res = await authFetch("/api/review/send-return-for-approval", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ doc_id: docId, note })
});
if (res.ok) {
setSendApprovalPanel(null);
showToast("Document sent to client for approval ✔", "success");
fetchUserDetails();
} else {
const data = await res.json().catch(() => ({}));
showToast(data.detail || "Failed to send", "error");
}
} catch (err) { console.error(err);
showToast("Network error", "error");
} finally {
setSendingApproval(false);
}
};
const markFiled = async () => {
const yearForFiling = taxYear || new Date().getFullYear();
setConfirmConfig({
isOpen: true,
title: "Mark as Filed",
message: `Mark all approved docs for ${yearForFiling} as FILED?\nThis will send a confirmation email to the client.`,
isDestructive: false,
confirmText: "Mark as Filed",
onConfirm: async () => {
setConfirmConfig(prev => ({ ...prev, isOpen: false }));
setMarkFiledLoading(true);
try {
const res = await authFetch("/api/review/mark-filed", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ user_id: parseInt(userId), tax_year: parseInt(yearForFiling) })
});
if (res.ok) {
const data = await res.json();
showToast(`Filed: ${data.personal_filed} personal + ${data.business_filed} business docs`, "success");
fetchUserDetails();
} else {
const data = await res.json().catch(() => ({}));
showToast(data.detail || "Mark filed failed", "error");
}
} catch (err) { console.error(err);
showToast("Network error", "error");
} finally {
setMarkFiledLoading(false);
}
}
});
};
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 downloadDoc = async (storageKey, originalFilename) => {
try {
const res = await authFetch(`/api/upload/view-url?key=${encodeURIComponent(storageKey)}`);
if (res.ok) {
const data = await res.json();
const fileRes = await fetch(data.url);
const blob = await fileRes.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = originalFilename || storageKey.split('/').pop() || 'document';
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
} else {
showToast("Could not generate download link", "error");
}
} catch (err) {
console.error(err);
showToast("Error downloading document", "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 () => {
setConfirmConfig({
isOpen: true,
title: "Submit for Review",
message: "Submit all documents for review?\nAn email will be sent to the user.",
isDestructive: false,
confirmText: "Submit",
onConfirm: async () => {
setConfirmConfig(prev => ({ ...prev, isOpen: false }));
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 sortDocs = (docsArray) => [...docsArray].sort((a, b) => {
const nameA = a.doc_type || a.doc_label || a.filename || '';
const nameB = b.doc_type || b.doc_label || b.filename || '';
if (docSort === 'asc') return nameA.localeCompare(nameB);
if (docSort === 'desc') return nameB.localeCompare(nameA);
if (docSort === 'newest') return new Date(b.uploaded_at || 0) - new Date(a.uploaded_at || 0);
if (docSort === 'oldest') return new Date(a.uploaded_at || 0) - new Date(b.uploaded_at || 0);
return 0;
});
const personalDocs = sortDocs(documents.filter(d => d.type === "personal"));
const businessDocs = sortDocs(documents.filter(d => d.type === "business"));
const returnDocs = sortDocs(documents.filter(d => d.type === "admin"));
const toggleBookmark = async (docKind, docId, isCurrentlyBookmarked) => {
try {
const method = isCurrentlyBookmarked ? "DELETE" : "PUT";
const res = await authFetch(`/api/upload/bookmarks/${docKind}/${docId}`, { method });
if (res.ok) {
showToast(isCurrentlyBookmarked ? "Bookmark removed" : "Document bookmarked", "success");
fetchUserDetails();
} else {
showToast("Failed to update bookmark", "error");
}
} catch (err) {
console.error(err);
showToast("Error updating bookmark", "error");
}
};
return (
<div className="">
<ConfirmModal
{...confirmConfig}
onCancel={() => setConfirmConfig(prev => ({ ...prev, isOpen: false }))}
/>
<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" style={{marginLeft: 'auto'}}>
<label className="form-label" style={{margin:0, fontSize: '11px'}}>Sort</label>
<select className="select-input" style={{width: 'auto', padding: '6px 12px', fontSize: '13px'}} value={docSort} onChange={(e) => setDocSort(e.target.value)}>
<option value="newest">Newest First</option>
<option value="oldest">Oldest First</option>
<option value="asc">Name (A-Z)</option>
<option value="desc">Name (Z-A)</option>
</select>
</div>
<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.filename || 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 onClick={() => downloadDoc(doc.storage_key, doc.filename)} className="btn btn-secondary btn-sm" style={{borderRadius:'var(--radius-sm)', display:'flex', alignItems:'center', gap:'4px'}}><span className="material-symbols-outlined" style={{fontSize:'16px'}}>download</span></button>
<button onClick={() => toggleBookmark(doc.type || 'admin', doc.id, doc.bookmarked)} className="btn btn-secondary btn-sm" style={{borderRadius:'var(--radius-sm)', display:'flex', alignItems:'center', gap:'4px', padding:'4px 8px'}} title={doc.bookmarked ? "Remove Bookmark" : "Bookmark"}>
<span className="material-symbols-outlined" style={{fontSize:'18px', color: doc.bookmarked ? 'var(--orange)' : 'inherit'}}>
{doc.bookmarked ? 'star' : 'star_border'}
</span>
</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.filename || 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 onClick={() => downloadDoc(doc.storage_key, doc.filename)} className="btn btn-secondary btn-sm" style={{borderRadius:'var(--radius-sm)', display:'flex', alignItems:'center', gap:'4px'}}><span className="material-symbols-outlined" style={{fontSize:'16px'}}>download</span></button>
<button onClick={() => toggleBookmark(doc.type || 'admin', doc.id, doc.bookmarked)} className="btn btn-secondary btn-sm" style={{borderRadius:'var(--radius-sm)', display:'flex', alignItems:'center', gap:'4px', padding:'4px 8px'}} title={doc.bookmarked ? "Remove Bookmark" : "Bookmark"}>
<span className="material-symbols-outlined" style={{fontSize:'18px', color: doc.bookmarked ? 'var(--orange)' : 'inherit'}}>
{doc.bookmarked ? 'star' : 'star_border'}
</span>
</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', flexWrap:'wrap', gap:'8px'}}>
<h3 style={{margin:0}}>Admin Returns / Documents</h3>
<div style={{display:'flex', gap:'8px', flexWrap:'wrap'}}>
<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 Return</button>
<button
className="btn btn-secondary btn-sm"
style={{borderRadius:'var(--radius-sm)', background:'#2c7a5b', color:'#fff', borderColor:'#2c7a5b'}}
onClick={markFiled}
disabled={markFiledLoading}
title={`Mark all approved docs for ${taxYear || 'selected year'} as Filed`}
>
{markFiledLoading ? 'Filing...' : '✔ Mark as Filed'}
</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>Document</th>
<th>Tax Year</th>
<th>Date</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{returnDocs.map(doc => (
<>
<tr key={doc.id}>
<td>
<div style={{fontWeight:500, color:'var(--navy)'}}>{doc.doc_label || doc.filename}</div>
<div className="text-sm text-muted">{doc.filename}</div>
</td>
<td>{doc.tax_year || <span className="text-muted">N/A</span>}</td>
<td>{new Date(doc.uploaded_at).toLocaleDateString()}</td>
<td>
{(() => {
const s = doc.review_status || 'pending';
const cls = s === 'approved' ? 'badge-green' : s === 'rejected' ? 'badge-red' : s === 'sent_for_approval' ? 'badge-blue' : s === 'filed' ? 'badge-green' : 'badge-yellow';
return (
<div>
<span className={`badge ${cls}`} style={{fontWeight:700}}>{s.replace(/_/g,' ').toUpperCase()}</span>
{doc.review_note && <div className="text-sm text-muted" style={{marginTop:'3px', fontSize:'11px'}}>{doc.review_note}</div>}
</div>
);
})()}
</td>
<td>
<div style={{display:'flex', gap:'6px', flexWrap:'wrap'}}>
<button className="btn btn-secondary btn-sm" onClick={() => viewDoc(doc.storage_key)}>View</button>
<button className="btn btn-secondary btn-sm" onClick={() => downloadDoc(doc.storage_key, doc.filename)} style={{display:'flex', alignItems:'center', gap:'4px'}}><span className="material-symbols-outlined" style={{fontSize:'16px'}}>download</span></button>
<button onClick={() => toggleBookmark(doc.type || 'admin', doc.id, doc.bookmarked)} className="btn btn-secondary btn-sm" style={{borderRadius:'var(--radius-sm)', display:'flex', alignItems:'center', gap:'4px', padding:'4px 8px'}} title={doc.bookmarked ? "Remove Bookmark" : "Bookmark"}>
<span className="material-symbols-outlined" style={{fontSize:'18px', color: doc.bookmarked ? 'var(--orange)' : 'inherit'}}>
{doc.bookmarked ? 'star' : 'star_border'}
</span>
</button>
{doc.review_status !== 'filed' && doc.review_status !== 'approved' && (
<button
className="btn btn-primary btn-sm"
style={{background:'#2c7a5b', borderColor:'#2c7a5b', fontSize:'12px'}}
onClick={() => setSendApprovalPanel({ docId: doc.id, note: '' })}
disabled={sendingApproval}
>
📤 Send for Approval
</button>
)}
<button className="btn btn-danger btn-sm" onClick={() => deleteAdminDoc(doc.id)}>Delete</button>
</div>
</td>
</tr>
{/* Inline Send-for-Approval Panel */}
{sendApprovalPanel?.docId === doc.id && (
<tr key={`send-${doc.id}`}>
<td colSpan={5} style={{padding:'0'}}>
<div style={{
padding:'14px 16px',
background:'rgba(44,122,91,0.05)',
border:'1px solid rgba(44,122,91,0.25)',
borderTop:'none',
display:'flex', flexDirection:'column', gap:'10px'
}}>
<div style={{fontWeight:600, fontSize:'13px', color:'#2c7a5b'}}>
📤 Send this document to client for review
</div>
<textarea
rows={2}
placeholder="Optional note to client (e.g. 'Please review page 3')..."
value={sendApprovalPanel.note}
onChange={e => setSendApprovalPanel(prev => ({...prev, note: e.target.value}))}
style={{
width:'100%', padding:'8px 12px',
border:'1px solid rgba(44,122,91,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" onClick={() => setSendApprovalPanel(null)}>Cancel</button>
<button
className="btn btn-primary btn-sm"
style={{background:'#2c7a5b', borderColor:'#2c7a5b'}}
disabled={sendingApproval}
onClick={() => sendReturnForApproval(doc.id, sendApprovalPanel.note)}
>
{sendingApproval ? 'Sending...' : 'Confirm & Email Client'}
</button>
</div>
</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>
);
}