Implement workflow improvements: admin document review, user email notifications, and engagement letter download
This commit is contained in:
Generated
+17
@@ -9,6 +9,7 @@
|
|||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"axios": "^1.18.1",
|
"axios": "^1.18.1",
|
||||||
|
"dompurify": "^3.4.16",
|
||||||
"lucide-react": "^1.24.0",
|
"lucide-react": "^1.24.0",
|
||||||
"react": "^19.2.7",
|
"react": "^19.2.7",
|
||||||
"react-dom": "^19.2.7",
|
"react-dom": "^19.2.7",
|
||||||
@@ -1978,6 +1979,13 @@
|
|||||||
"@types/react": "^19.2.0"
|
"@types/react": "^19.2.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/trusted-types": {
|
||||||
|
"version": "2.0.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
|
||||||
|
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
"node_modules/@vitejs/plugin-react": {
|
"node_modules/@vitejs/plugin-react": {
|
||||||
"version": "6.0.3",
|
"version": "6.0.3",
|
||||||
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.0.3.tgz",
|
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.0.3.tgz",
|
||||||
@@ -2263,6 +2271,15 @@
|
|||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/dompurify": {
|
||||||
|
"version": "3.4.16",
|
||||||
|
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.16.tgz",
|
||||||
|
"integrity": "sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==",
|
||||||
|
"license": "(MPL-2.0 OR Apache-2.0)",
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@types/trusted-types": "^2.0.7"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/dunder-proto": {
|
"node_modules/dunder-proto": {
|
||||||
"version": "1.0.1",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"axios": "^1.18.1",
|
"axios": "^1.18.1",
|
||||||
|
"dompurify": "^3.4.16",
|
||||||
"lucide-react": "^1.24.0",
|
"lucide-react": "^1.24.0",
|
||||||
"react": "^19.2.7",
|
"react": "^19.2.7",
|
||||||
"react-dom": "^19.2.7",
|
"react-dom": "^19.2.7",
|
||||||
|
|||||||
@@ -690,7 +690,7 @@
|
|||||||
.aud-bar-actions {
|
.aud-bar-actions {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 10px;
|
gap: 10px;
|
||||||
align-items: center;
|
align-items: flex-end;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
}
|
}
|
||||||
.aud-year-picker {
|
.aud-year-picker {
|
||||||
|
|||||||
@@ -21,12 +21,28 @@ const FAQ_DATA = {
|
|||||||
|
|
||||||
const CATEGORY_ICONS = { "Document Review": "📑", "User Management": "👥", "Notifications": "🔔" };
|
const CATEGORY_ICONS = { "Document Review": "📑", "User Management": "👥", "Notifications": "🔔" };
|
||||||
|
|
||||||
|
const escapeHtml = (unsafe) => {
|
||||||
|
return unsafe
|
||||||
|
.replace(/&/g, "&")
|
||||||
|
.replace(/</g, "<")
|
||||||
|
.replace(/>/g, ">")
|
||||||
|
.replace(/"/g, """)
|
||||||
|
.replace(/'/g, "'");
|
||||||
|
};
|
||||||
|
|
||||||
const formatMessage = (text) => {
|
const formatMessage = (text) => {
|
||||||
if (!text) return '';
|
if (!text) return '';
|
||||||
return text
|
let safeText = escapeHtml(text);
|
||||||
|
return safeText
|
||||||
.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>')
|
.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>')
|
||||||
.replace(/\*(.*?)\*/g, '<i>$1</i>')
|
.replace(/\*(.*?)\*/g, '<i>$1</i>')
|
||||||
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer" style="color:var(--blue);text-decoration:underline">$1</a>')
|
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, text, url) => {
|
||||||
|
let decodedUrl = url.replace(/'/g, "'").replace(/"/g, '"').replace(/&/g, '&');
|
||||||
|
if (decodedUrl.toLowerCase().trim().startsWith('javascript:')) {
|
||||||
|
return escapeHtml(match);
|
||||||
|
}
|
||||||
|
return `<a href="${url}" target="_blank" rel="noopener noreferrer" style="color:var(--blue);text-decoration:underline">${text}</a>`;
|
||||||
|
})
|
||||||
.replace(/\n/g, '<br/>');
|
.replace(/\n/g, '<br/>');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -26,12 +26,28 @@ const FAQ_DATA = {
|
|||||||
|
|
||||||
const CATEGORY_ICONS = { "Account": "👤", "Documents": "📄", "Tax Filing": "📋", "Security": "🔒" };
|
const CATEGORY_ICONS = { "Account": "👤", "Documents": "📄", "Tax Filing": "📋", "Security": "🔒" };
|
||||||
|
|
||||||
|
const escapeHtml = (unsafe) => {
|
||||||
|
return unsafe
|
||||||
|
.replace(/&/g, "&")
|
||||||
|
.replace(/</g, "<")
|
||||||
|
.replace(/>/g, ">")
|
||||||
|
.replace(/"/g, """)
|
||||||
|
.replace(/'/g, "'");
|
||||||
|
};
|
||||||
|
|
||||||
const formatMessage = (text) => {
|
const formatMessage = (text) => {
|
||||||
if (!text) return '';
|
if (!text) return '';
|
||||||
return text
|
let safeText = escapeHtml(text);
|
||||||
|
return safeText
|
||||||
.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>')
|
.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>')
|
||||||
.replace(/\*(.*?)\*/g, '<i>$1</i>')
|
.replace(/\*(.*?)\*/g, '<i>$1</i>')
|
||||||
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" style="color:var(--blue);text-decoration:underline">$1</a>')
|
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, text, url) => {
|
||||||
|
let decodedUrl = url.replace(/'/g, "'").replace(/"/g, '"').replace(/&/g, '&');
|
||||||
|
if (decodedUrl.toLowerCase().trim().startsWith('javascript:')) {
|
||||||
|
return escapeHtml(match);
|
||||||
|
}
|
||||||
|
return `<a href="${url}" style="color:var(--blue);text-decoration:underline">${text}</a>`;
|
||||||
|
})
|
||||||
.replace(/\n/g, '<br/>');
|
.replace(/\n/g, '<br/>');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -71,7 +71,15 @@ export default function ExpandableSummaryBlock({ extractedData, onSave }) {
|
|||||||
let valStr = val;
|
let valStr = val;
|
||||||
if (Array.isArray(val)) valStr = val.join('; ');
|
if (Array.isArray(val)) valStr = val.join('; ');
|
||||||
else if (typeof val === 'object' && val !== null) valStr = JSON.stringify(val);
|
else if (typeof val === 'object' && val !== null) valStr = JSON.stringify(val);
|
||||||
rows.push([String(key), String(valStr ?? '')]);
|
|
||||||
|
let finalKey = String(key);
|
||||||
|
let finalVal = String(valStr ?? '');
|
||||||
|
|
||||||
|
// Sanitize CSV/Excel Formula Injection
|
||||||
|
if (/^[=+\-@]/.test(finalKey)) finalKey = "'" + finalKey;
|
||||||
|
if (/^[=+\-@]/.test(finalVal)) finalVal = "'" + finalVal;
|
||||||
|
|
||||||
|
rows.push([finalKey, finalVal]);
|
||||||
});
|
});
|
||||||
|
|
||||||
const ws = XLSX.utils.aoa_to_sheet(rows);
|
const ws = XLSX.utils.aoa_to_sheet(rows);
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ export default function DashboardLayout() {
|
|||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<main className="page-main page-enter">
|
<main className={`${(user?.role === 'admin' || user?.role === 'super_admin') ? 'page-main-wide' : 'page-main'} page-enter`}>
|
||||||
<Outlet />
|
<Outlet />
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,12 +1,16 @@
|
|||||||
import { useState, useEffect, useCallback } from 'react';
|
import { useState, useEffect, useCallback } from 'react';
|
||||||
import { useAuth } from '../context/AuthContext';
|
import { useAuth } from '../context/AuthContext';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import DOMPurify from 'dompurify';
|
||||||
|
|
||||||
export default function AdminDashboard() {
|
export default function AdminDashboard() {
|
||||||
const { authFetch } = useAuth();
|
const { authFetch } = useAuth();
|
||||||
const [stats, setStats] = useState({ total_users: 0, pending_personal: 0, pending_business: 0, admins: 0 });
|
const [stats, setStats] = useState({ total_users: 0, pending_personal: 0, pending_business: 0, admins: 0 });
|
||||||
const [users, setUsers] = useState([]);
|
const [users, setUsers] = useState([]);
|
||||||
const [search, setSearch] = useState("");
|
const [search, setSearch] = useState("");
|
||||||
|
const [userFilter, setUserFilter] = useState("all");
|
||||||
|
const [userSort, setUserSort] = useState("newest");
|
||||||
|
const [filterYear, setFilterYear] = useState(new Date().getFullYear().toString());
|
||||||
const [tab, setTab] = useState("users");
|
const [tab, setTab] = useState("users");
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
@@ -37,7 +41,7 @@ export default function AdminDashboard() {
|
|||||||
const fetchAdminData = useCallback(async () => {
|
const fetchAdminData = useCallback(async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const res = await authFetch("/api/auth/admin/users");
|
const res = await authFetch(`/api/auth/admin/users?tax_year=${filterYear}`);
|
||||||
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
const payload = await res.json();
|
const payload = await res.json();
|
||||||
@@ -78,7 +82,7 @@ export default function AdminDashboard() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchAdminData();
|
fetchAdminData();
|
||||||
}, [authFetch, fetchAdminData]);
|
}, [authFetch, fetchAdminData, filterYear]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (tab === "templates") {
|
if (tab === "templates") {
|
||||||
@@ -133,28 +137,76 @@ export default function AdminDashboard() {
|
|||||||
const yearOptions = [currentYear - 1, currentYear, currentYear + 1];
|
const yearOptions = [currentYear - 1, currentYear, currentYear + 1];
|
||||||
|
|
||||||
const filteredUsers = users.filter(u => {
|
const filteredUsers = users.filter(u => {
|
||||||
|
// Stat Card Filters
|
||||||
|
if (userFilter === 'pending_personal' && !(u.pending_personal > 0)) return false;
|
||||||
|
if (userFilter === 'pending_business' && !(u.pending_business > 0)) return false;
|
||||||
|
|
||||||
if (!search) return true;
|
if (!search) return true;
|
||||||
const q = search.toLowerCase();
|
const q = search.toLowerCase();
|
||||||
return (u.name?.toLowerCase().includes(q) || u.email?.toLowerCase().includes(q));
|
return (u.name?.toLowerCase().includes(q) || u.email?.toLowerCase().includes(q));
|
||||||
|
}).sort((a, b) => {
|
||||||
|
if (userSort === 'asc') return (a.name || '').localeCompare(b.name || '');
|
||||||
|
if (userSort === 'desc') return (b.name || '').localeCompare(a.name || '');
|
||||||
|
if (userSort === 'highest_pending') {
|
||||||
|
const aPending = (a.pending_personal || 0) + (a.pending_business || 0);
|
||||||
|
const bPending = (b.pending_personal || 0) + (b.pending_business || 0);
|
||||||
|
return bPending - aPending;
|
||||||
|
}
|
||||||
|
// Default fallback to ID if created_at is missing
|
||||||
|
if (userSort === 'newest') return (b.id || 0) - (a.id || 0);
|
||||||
|
if (userSort === 'oldest') return (a.id || 0) - (b.id || 0);
|
||||||
|
return 0;
|
||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="page-main-wide page-enter">
|
<div className="">
|
||||||
<div className="flex-between align-center" style={{ marginBottom: '24px', flexWrap: 'wrap', gap: '16px' }}>
|
<h1 style={{
|
||||||
<h1 style={{ margin: 0, fontSize: '28px', color: 'var(--navy)' }}>
|
margin: '0 0 32px 0',
|
||||||
Users <span style={{ color: 'var(--muted)', fontWeight: 400 }}>{tab === 'templates' ? 'Templates' : ''}</span>
|
fontSize: '42px',
|
||||||
</h1>
|
fontFamily: 'var(--font-display)',
|
||||||
|
fontWeight: '800',
|
||||||
|
color: 'var(--ink)',
|
||||||
|
textAlign: 'center',
|
||||||
|
letterSpacing: '-0.5px'
|
||||||
|
}}>
|
||||||
|
Admin Dashboard <span style={{ color: 'var(--brass)', fontWeight: 600, fontSize: '32px' }}>{tab === 'templates' ? '| Templates' : ''}</span>
|
||||||
|
</h1>
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '24px', flexWrap: 'wrap', gap: '16px' }}>
|
||||||
{tab === 'users' && (
|
{tab === 'users' && (
|
||||||
<div className="search-wrap" style={{ width: '100%', maxWidth: '300px' }}>
|
<div style={{ display: 'flex', gap: '12px', width: '100%', maxWidth: '500px', flexWrap: 'wrap' }}>
|
||||||
<span className="material-symbols-outlined search-icon" style={{position: 'absolute', left: '12px', top: '50%', transform: 'translateY(-50%)', color: 'var(--muted)', fontSize: '20px'}}>search</span>
|
<div className="search-wrap" style={{ flex: 1, minWidth: '200px', position: 'relative' }}>
|
||||||
<input
|
<span className="material-symbols-outlined search-icon" style={{position: 'absolute', left: '12px', top: '50%', transform: 'translateY(-50%)', color: 'var(--muted)', fontSize: '20px'}}>search</span>
|
||||||
type="text"
|
<input
|
||||||
className="search-input"
|
type="text"
|
||||||
style={{ width: '100%', padding: '10px 12px 10px 40px', border: '1px solid var(--border)', borderRadius: 'var(--radius-full)', outline: 'none' }}
|
className="search-input"
|
||||||
placeholder="Search by name or email"
|
style={{ width: '100%', padding: '10px 12px 10px 40px', border: '1px solid var(--border)', borderRadius: 'var(--radius-full)', outline: 'none' }}
|
||||||
value={search}
|
placeholder="Search by name or email"
|
||||||
onChange={(e) => setSearch(e.target.value)}
|
value={search}
|
||||||
/>
|
onChange={(e) => setSearch(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<select
|
||||||
|
className="select-input"
|
||||||
|
style={{ width: 'auto', padding: '10px 16px', borderRadius: 'var(--radius-full)', border: '1px solid var(--border)', outline: 'none', background: 'white' }}
|
||||||
|
value={userSort}
|
||||||
|
onChange={(e) => setUserSort(e.target.value)}
|
||||||
|
>
|
||||||
|
<option value="newest">Newest First</option>
|
||||||
|
<option value="oldest">Oldest First</option>
|
||||||
|
<option value="highest_pending">Highest Pending</option>
|
||||||
|
<option value="asc">Name (A-Z)</option>
|
||||||
|
<option value="desc">Name (Z-A)</option>
|
||||||
|
</select>
|
||||||
|
<select
|
||||||
|
className="select-input"
|
||||||
|
style={{ width: 'auto', padding: '10px 16px', borderRadius: 'var(--radius-full)', border: '1px solid var(--border)', outline: 'none', background: 'white' }}
|
||||||
|
value={filterYear}
|
||||||
|
onChange={(e) => setFilterYear(e.target.value)}
|
||||||
|
>
|
||||||
|
<option value={currentYear - 1}>TY {currentYear - 1}</option>
|
||||||
|
<option value={currentYear}>TY {currentYear}</option>
|
||||||
|
<option value={currentYear + 1}>TY {currentYear + 1}</option>
|
||||||
|
</select>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -187,13 +239,13 @@ export default function AdminDashboard() {
|
|||||||
</div>
|
</div>
|
||||||
{digestHtml && (
|
{digestHtml && (
|
||||||
<div style={{ marginTop: '12px', paddingTop: '12px', borderTop: '1px solid rgba(31,93,70,0.2)', fontSize: '13px', color: 'var(--navy)', lineHeight: '1.7' }}
|
<div style={{ marginTop: '12px', paddingTop: '12px', borderTop: '1px solid rgba(31,93,70,0.2)', fontSize: '13px', color: 'var(--navy)', lineHeight: '1.7' }}
|
||||||
dangerouslySetInnerHTML={{ __html: digestHtml }} />
|
dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(digestHtml) }} />
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Stats Bar */}
|
{/* Stats Bar */}
|
||||||
<div className="admin-stats">
|
<div className="admin-stats">
|
||||||
<div className="stat-card accent-blue">
|
<div className={`stat-card accent-blue ${userFilter === 'all' ? 'active-filter' : ''}`} onClick={() => setUserFilter('all')} style={{ cursor: 'pointer', border: userFilter === 'all' ? '2px solid var(--blue)' : 'none' }}>
|
||||||
<div className="stat-icon"><span className="material-symbols-outlined">group</span></div>
|
<div className="stat-icon"><span className="material-symbols-outlined">group</span></div>
|
||||||
<div className="stat-value">{stats.total_users}</div>
|
<div className="stat-value">{stats.total_users}</div>
|
||||||
<div className="stat-label">Total Users</div>
|
<div className="stat-label">Total Users</div>
|
||||||
@@ -203,12 +255,12 @@ export default function AdminDashboard() {
|
|||||||
<div className="stat-value">{stats.admins}</div>
|
<div className="stat-value">{stats.admins}</div>
|
||||||
<div className="stat-label">Admin Accounts</div>
|
<div className="stat-label">Admin Accounts</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="stat-card accent-orange">
|
<div className={`stat-card accent-orange ${userFilter === 'pending_personal' ? 'active-filter' : ''}`} onClick={() => setUserFilter('pending_personal')} style={{ cursor: 'pointer', border: userFilter === 'pending_personal' ? '2px solid var(--orange)' : 'none' }}>
|
||||||
<div className="stat-icon"><span className="material-symbols-outlined">description</span></div>
|
<div className="stat-icon"><span className="material-symbols-outlined">description</span></div>
|
||||||
<div className="stat-value">{stats.pending_personal}</div>
|
<div className="stat-value">{stats.pending_personal}</div>
|
||||||
<div className="stat-label">Pending Personal</div>
|
<div className="stat-label">Pending Personal</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="stat-card accent-orange">
|
<div className={`stat-card accent-orange ${userFilter === 'pending_business' ? 'active-filter' : ''}`} onClick={() => setUserFilter('pending_business')} style={{ cursor: 'pointer', border: userFilter === 'pending_business' ? '2px solid var(--orange)' : 'none' }}>
|
||||||
<div className="stat-icon"><span className="material-symbols-outlined">business</span></div>
|
<div className="stat-icon"><span className="material-symbols-outlined">business</span></div>
|
||||||
<div className="stat-value">{stats.pending_business}</div>
|
<div className="stat-value">{stats.pending_business}</div>
|
||||||
<div className="stat-label">Pending Business</div>
|
<div className="stat-label">Pending Business</div>
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ export default function AdminUserDetail() {
|
|||||||
|
|
||||||
const [userDetail, setUserDetail] = useState(null);
|
const [userDetail, setUserDetail] = useState(null);
|
||||||
const [documents, setDocuments] = useState([]);
|
const [documents, setDocuments] = useState([]);
|
||||||
|
const [showAiSummary, setShowAiSummary] = useState({});
|
||||||
const [activeTab, setActiveTab] = useState('personal');
|
const [activeTab, setActiveTab] = useState('personal');
|
||||||
const [taxYear, setTaxYear] = useState("");
|
const [taxYear, setTaxYear] = useState("");
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
@@ -23,6 +24,9 @@ export default function AdminUserDetail() {
|
|||||||
const [personalTimeline, setPersonalTimeline] = useState(0);
|
const [personalTimeline, setPersonalTimeline] = useState(0);
|
||||||
const [businessTimeline, setBusinessTimeline] = useState(0);
|
const [businessTimeline, setBusinessTimeline] = useState(0);
|
||||||
|
|
||||||
|
// Reject comment panel: { docId, type, note }
|
||||||
|
const [rejectPanel, setRejectPanel] = useState(null);
|
||||||
|
|
||||||
// Export Excel Function
|
// Export Excel Function
|
||||||
const exportToExcel = async () => {
|
const exportToExcel = async () => {
|
||||||
try {
|
try {
|
||||||
@@ -33,7 +37,7 @@ export default function AdminUserDetail() {
|
|||||||
const url = window.URL.createObjectURL(blob);
|
const url = window.URL.createObjectURL(blob);
|
||||||
const a = document.createElement('a');
|
const a = document.createElement('a');
|
||||||
a.href = url;
|
a.href = url;
|
||||||
a.download = `user_${userId}_documents.xlsx`;
|
a.download = `user_${userId}_excel_summaries.zip`;
|
||||||
document.body.appendChild(a);
|
document.body.appendChild(a);
|
||||||
a.click();
|
a.click();
|
||||||
a.remove();
|
a.remove();
|
||||||
@@ -165,26 +169,31 @@ export default function AdminUserDetail() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDocApprove = async (docId, type, isApproved) => {
|
const handleDocApprove = async (docId, type, isApproved, note = '') => {
|
||||||
try {
|
try {
|
||||||
const status = isApproved ? 'approved' : 'rejected';
|
const status = isApproved ? 'approved' : 'rejected';
|
||||||
const ep = type === "personal" ? `/api/upload/personal-documents/${docId}/review-status` : `/api/upload/business-documents/${docId}/review-status`;
|
const ep = type === "personal" ? `/api/upload/personal-documents/${docId}/review-status` : `/api/upload/business-documents/${docId}/review-status`;
|
||||||
const res = await authFetch(ep, {
|
const res = await authFetch(ep, {
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ status, note: "" })
|
body: JSON.stringify({ status, note })
|
||||||
});
|
});
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
|
setRejectPanel(null);
|
||||||
fetchUserDetails(); // reload docs
|
fetchUserDetails(); // reload docs
|
||||||
} else {
|
} else {
|
||||||
showToast("Failed to save review status", "error");
|
showToast("Failed to save review status", "error");
|
||||||
}
|
}
|
||||||
} catch (err) { console.error(err);
|
} catch (err) { console.error(err);
|
||||||
console.error("Approval error", err);
|
|
||||||
showToast("Approval error", "error");
|
showToast("Approval error", "error");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const openRejectPanel = (docId, type) => {
|
||||||
|
setRejectPanel({ docId, type, note: '' });
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
const deleteAdminDoc = async (docId) => {
|
const deleteAdminDoc = async (docId) => {
|
||||||
if (!window.confirm("Delete this admin document?")) return;
|
if (!window.confirm("Delete this admin document?")) return;
|
||||||
try {
|
try {
|
||||||
@@ -309,13 +318,38 @@ export default function AdminUserDetail() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (loading && !userDetail) {
|
if (loading && !userDetail) {
|
||||||
return <div className="page-main-wide page-enter"><div className="empty-state"><div className="empty-title">Loading user details...</div></div></div>;
|
return <div className=""><div className="empty-state"><div className="empty-title">Loading user details...</div></div></div>;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!userDetail) {
|
if (!userDetail) {
|
||||||
return <div className="page-main-wide page-enter"><div className="empty-state"><div className="empty-title">User not found</div></div></div>;
|
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;
|
||||||
|
a.download = `user_${userId}_documents.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 currentYear = new Date().getFullYear();
|
||||||
const yearOptions = [currentYear - 1, currentYear, currentYear + 1];
|
const yearOptions = [currentYear - 1, currentYear, currentYear + 1];
|
||||||
|
|
||||||
@@ -324,7 +358,12 @@ export default function AdminUserDetail() {
|
|||||||
const returnDocs = documents.filter(d => d.type === "admin");
|
const returnDocs = documents.filter(d => d.type === "admin");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="page-main-wide page-enter">
|
<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 */}
|
{/* User Info Bar */}
|
||||||
<div className="card aud-user-bar" style={{marginBottom: '20px'}}>
|
<div className="card aud-user-bar" style={{marginBottom: '20px'}}>
|
||||||
<div className="aud-bar-inner">
|
<div className="aud-bar-inner">
|
||||||
@@ -389,6 +428,7 @@ export default function AdminUserDetail() {
|
|||||||
{yearOptions.map(y => <option key={y} value={y}>{y}</option>)}
|
{yearOptions.map(y => <option key={y} value={y}>{y}</option>)}
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</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>
|
<button className="btn btn-danger btn-sm" onClick={deleteUser} style={{borderRadius:'var(--radius-sm)'}}>Delete User</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -424,19 +464,87 @@ export default function AdminUserDetail() {
|
|||||||
</div>
|
</div>
|
||||||
{doc.notes && <div style={{ fontSize:'12px', color:'var(--warn)', marginTop:'3px', fontWeight:500 }}>⚠ {doc.notes}</div>}
|
{doc.notes && <div style={{ fontSize:'12px', color:'var(--warn)', marginTop:'3px', fontWeight:500 }}>⚠ {doc.notes}</div>}
|
||||||
{doc.review_status && (
|
{doc.review_status && (
|
||||||
<div style={{ marginTop:'5px' }}>
|
<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}}>
|
<span className={`badge ${doc.review_status === 'approved' ? 'badge-green' : doc.review_status === 'rejected' ? 'badge-red' : 'badge-yellow'}`} style={{fontWeight:700}}>
|
||||||
{doc.review_status.toUpperCase()}
|
{doc.review_status.toUpperCase()}
|
||||||
</span>
|
</span>
|
||||||
|
{doc.review_status === 'rejected' && doc.review_note && (
|
||||||
|
<span style={{fontSize:'12px', color:'#c0392b', fontStyle:'italic'}}>"{doc.review_note}"</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="doc-review-actions">
|
<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={() => 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-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={() => handleDocApprove(doc.id, doc.type, false)}>Reject</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>
|
||||||
</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 ? (
|
{doc.extracted_data && Object.keys(doc.extracted_data).length > 0 ? (
|
||||||
<div className="ai-summary-block">
|
<div className="ai-summary-block">
|
||||||
<div className="ai-summary-label">
|
<div className="ai-summary-label">
|
||||||
@@ -456,6 +564,8 @@ export default function AdminUserDetail() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
))
|
))
|
||||||
)}
|
)}
|
||||||
@@ -521,19 +631,87 @@ export default function AdminUserDetail() {
|
|||||||
</div>
|
</div>
|
||||||
{doc.notes && <div style={{ fontSize:'12px', color:'var(--warn)', marginTop:'3px', fontWeight:500 }}>⚠ {doc.notes}</div>}
|
{doc.notes && <div style={{ fontSize:'12px', color:'var(--warn)', marginTop:'3px', fontWeight:500 }}>⚠ {doc.notes}</div>}
|
||||||
{doc.review_status && (
|
{doc.review_status && (
|
||||||
<div style={{ marginTop:'5px' }}>
|
<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}}>
|
<span className={`badge ${doc.review_status === 'approved' ? 'badge-green' : doc.review_status === 'rejected' ? 'badge-red' : 'badge-yellow'}`} style={{fontWeight:700}}>
|
||||||
{doc.review_status.toUpperCase()}
|
{doc.review_status.toUpperCase()}
|
||||||
</span>
|
</span>
|
||||||
|
{doc.review_status === 'rejected' && doc.review_note && (
|
||||||
|
<span style={{fontSize:'12px', color:'#c0392b', fontStyle:'italic'}}>"{doc.review_note}"</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="doc-review-actions">
|
<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={() => 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-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={() => handleDocApprove(doc.id, doc.type, false)}>Reject</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>
|
||||||
</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 ? (
|
{doc.extracted_data && Object.keys(doc.extracted_data).length > 0 ? (
|
||||||
<div className="ai-summary-block">
|
<div className="ai-summary-block">
|
||||||
<div className="ai-summary-label">
|
<div className="ai-summary-label">
|
||||||
@@ -541,7 +719,7 @@ export default function AdminUserDetail() {
|
|||||||
AI Summary
|
AI Summary
|
||||||
</div>
|
</div>
|
||||||
<ExpandableSummaryBlock
|
<ExpandableSummaryBlock
|
||||||
extractedData={doc.extracted_data}
|
extractedData={doc.extracted_data}
|
||||||
onSave={(newData) => handleUpdateExtractedData(doc.id, doc.type, newData)}
|
onSave={(newData) => handleUpdateExtractedData(doc.id, doc.type, newData)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -553,6 +731,8 @@ export default function AdminUserDetail() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
))
|
))
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { useAuth } from '../context/AuthContext';
|
import { useAuth } from '../context/AuthContext';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
|
||||||
export default function Profile() {
|
export default function Profile() {
|
||||||
const { user, authFetch } = useAuth();
|
const { user, authFetch } = useAuth();
|
||||||
|
const navigate = useNavigate();
|
||||||
const [formData, setFormData] = useState({ name: '', phone: '' });
|
const [formData, setFormData] = useState({ name: '', phone: '' });
|
||||||
const [pwData, setPwData] = useState({ currentPw: '', newPw: '', confirmPw: '' });
|
const [pwData, setPwData] = useState({ currentPw: '', newPw: '', confirmPw: '' });
|
||||||
const [showPwSection, setShowPwSection] = useState(false);
|
const [showPwSection, setShowPwSection] = useState(false);
|
||||||
@@ -63,6 +65,14 @@ export default function Profile() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ maxWidth: '680px', margin: '0 auto' }}>
|
<div style={{ maxWidth: '680px', margin: '0 auto' }}>
|
||||||
|
<button
|
||||||
|
className="btn btn-secondary btn-sm"
|
||||||
|
style={{ marginBottom: '16px', display: 'inline-flex', alignItems: 'center', gap: '4px', borderRadius: 'var(--radius-sm)' }}
|
||||||
|
onClick={() => navigate((user?.role === 'admin' || user?.role === 'super_admin') ? '/admin-dashboard' : '/dashboard')}
|
||||||
|
>
|
||||||
|
<span className="material-symbols-outlined" style={{ fontSize: '18px' }}>arrow_back</span>
|
||||||
|
Back to Dashboard
|
||||||
|
</button>
|
||||||
<div className="page-heading">
|
<div className="page-heading">
|
||||||
<div>
|
<div>
|
||||||
<h1>My Profile</h1>
|
<h1>My Profile</h1>
|
||||||
|
|||||||
@@ -119,12 +119,12 @@ export default function UploadBusiness() {
|
|||||||
body: JSON.stringify({ file_count: docs.length, doc_category: "Business" })
|
body: JSON.stringify({ file_count: docs.length, doc_category: "Business" })
|
||||||
});
|
});
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
showToast("Admin notified successfully", "success");
|
showToast("Documents sent for approval", "success");
|
||||||
} else {
|
} else {
|
||||||
showToast("Failed to notify admin", "error");
|
showToast("Failed to send for approval", "error");
|
||||||
}
|
}
|
||||||
} catch (err) { console.error(err);
|
} catch (err) { console.error(err);
|
||||||
showToast("Error notifying admin", "error");
|
showToast("Error sending for approval", "error");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -180,7 +180,7 @@ export default function UploadBusiness() {
|
|||||||
<input
|
<input
|
||||||
type="file"
|
type="file"
|
||||||
hidden
|
hidden
|
||||||
accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx,.xls,.xlsx"
|
accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx,.xls,.xlsx,.zip"
|
||||||
ref={el => fileInputRefs.current[dt.name] = el}
|
ref={el => fileInputRefs.current[dt.name] = el}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
if (e.target.files[0]) {
|
if (e.target.files[0]) {
|
||||||
@@ -232,7 +232,7 @@ export default function UploadBusiness() {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
+ Choose Files
|
+ Choose Files
|
||||||
<input type="file" multiple hidden accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx,.xls,.xlsx" onChange={handleExtraUpload} />
|
<input type="file" multiple hidden accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx,.xls,.xlsx,.zip" onChange={handleExtraUpload} />
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -276,11 +276,11 @@ export default function UploadBusiness() {
|
|||||||
<div style={{display:'flex', alignItems:'center', justifyContent:'space-between', flexWrap:'wrap', gap:'16px'}}>
|
<div style={{display:'flex', alignItems:'center', justifyContent:'space-between', flexWrap:'wrap', gap:'16px'}}>
|
||||||
<div>
|
<div>
|
||||||
<h3 style={{marginBottom:'4px'}}>Finished Uploading?</h3>
|
<h3 style={{marginBottom:'4px'}}>Finished Uploading?</h3>
|
||||||
<p className="text-sm" style={{margin:0}}>Notify your accountant that your business documents are ready for review.</p>
|
<p className="text-sm" style={{margin:0}}>Send your business documents for review.</p>
|
||||||
</div>
|
</div>
|
||||||
<button className="btn btn-primary" onClick={notifyComplete}>
|
<button className="btn btn-primary" onClick={notifyComplete}>
|
||||||
<span className="material-symbols-outlined">send</span>
|
<span className="material-symbols-outlined">send</span>
|
||||||
Notify Admin: Uploads Complete
|
Send for Approval
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -121,12 +121,12 @@ export default function UploadPersonal() {
|
|||||||
body: JSON.stringify({ file_count: docs.length, doc_category: "Personal" })
|
body: JSON.stringify({ file_count: docs.length, doc_category: "Personal" })
|
||||||
});
|
});
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
showToast("Admin notified successfully", "success");
|
showToast("Documents sent for approval", "success");
|
||||||
} else {
|
} else {
|
||||||
showToast("Failed to notify admin", "error");
|
showToast("Failed to send for approval", "error");
|
||||||
}
|
}
|
||||||
} catch (err) { console.error(err);
|
} catch (err) { console.error(err);
|
||||||
showToast("Error notifying admin", "error");
|
showToast("Error sending for approval", "error");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -182,7 +182,7 @@ export default function UploadPersonal() {
|
|||||||
<input
|
<input
|
||||||
type="file"
|
type="file"
|
||||||
hidden
|
hidden
|
||||||
accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx"
|
accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx,.xls,.xlsx,.zip"
|
||||||
ref={el => fileInputRefs.current[dt.name] = el}
|
ref={el => fileInputRefs.current[dt.name] = el}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
if (e.target.files[0]) {
|
if (e.target.files[0]) {
|
||||||
@@ -234,7 +234,7 @@ export default function UploadPersonal() {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
+ Choose Files
|
+ Choose Files
|
||||||
<input type="file" multiple hidden accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx" onChange={handleExtraUpload} />
|
<input type="file" multiple hidden accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx,.xls,.xlsx,.zip" onChange={handleExtraUpload} />
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -278,11 +278,11 @@ export default function UploadPersonal() {
|
|||||||
<div style={{display:'flex', alignItems:'center', justifyContent:'space-between', flexWrap:'wrap', gap:'16px'}}>
|
<div style={{display:'flex', alignItems:'center', justifyContent:'space-between', flexWrap:'wrap', gap:'16px'}}>
|
||||||
<div>
|
<div>
|
||||||
<h3 style={{marginBottom:'4px'}}>Finished Uploading?</h3>
|
<h3 style={{marginBottom:'4px'}}>Finished Uploading?</h3>
|
||||||
<p className="text-sm" style={{margin:0}}>Notify your accountant that your personal documents are ready for review.</p>
|
<p className="text-sm" style={{margin:0}}>Send your personal documents for review.</p>
|
||||||
</div>
|
</div>
|
||||||
<button className="btn btn-primary" onClick={notifyComplete}>
|
<button className="btn btn-primary" onClick={notifyComplete}>
|
||||||
<span className="material-symbols-outlined">send</span>
|
<span className="material-symbols-outlined">send</span>
|
||||||
Notify Admin: Uploads Complete
|
Send for Approval
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -12,11 +12,15 @@ export default function UserDashboard() {
|
|||||||
const [adminDocs, setAdminDocs] = useState([]);
|
const [adminDocs, setAdminDocs] = useState([]);
|
||||||
const [loadingDocs, setLoadingDocs] = useState(false);
|
const [loadingDocs, setLoadingDocs] = useState(false);
|
||||||
const [docLoading, setDocLoading] = useState(false);
|
const [docLoading, setDocLoading] = useState(false);
|
||||||
|
const [engagementLink, setEngagementLink] = useState(null);
|
||||||
// Track which doc rows have the AI summary panel open
|
// Track which doc rows have the AI summary panel open
|
||||||
const [expandedSummary, setExpandedSummary] = useState({});
|
const [expandedSummary, setExpandedSummary] = useState({});
|
||||||
const [searchQuery, setSearchQuery] = useState("");
|
const [searchQuery, setSearchQuery] = useState("");
|
||||||
const [searchResults, setSearchResults] = useState([]);
|
const [searchResults, setSearchResults] = useState([]);
|
||||||
const [isSearching, setIsSearching] = useState(false);
|
const [isSearching, setIsSearching] = useState(false);
|
||||||
|
// Reject comment panel for admin docs: { docId, note }
|
||||||
|
const [rejectPanel, setRejectPanel] = useState(null);
|
||||||
|
|
||||||
|
|
||||||
// ── declare callbacks BEFORE the effects that reference them ──
|
// ── declare callbacks BEFORE the effects that reference them ──
|
||||||
|
|
||||||
@@ -50,8 +54,22 @@ export default function UserDashboard() {
|
|||||||
setEngagementDisabled(true);
|
setEngagementDisabled(true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const tplRes = await authFetch("/api/upload/templates?category=engagement&tax_year=2025");
|
||||||
|
if (tplRes.ok) {
|
||||||
|
const tpls = await tplRes.json();
|
||||||
|
if (tpls && tpls.length > 0) {
|
||||||
|
setEngagementLink(tpls[0].download);
|
||||||
|
} else {
|
||||||
|
// Fallback static link if no template is defined
|
||||||
|
setEngagementLink("/Engagement_Letter_Template.pdf");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
setEngagementLink("/Engagement_Letter_Template.pdf");
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
|
setEngagementLink("/Engagement_Letter_Template.pdf");
|
||||||
}
|
}
|
||||||
}, [authFetch]);
|
}, [authFetch]);
|
||||||
|
|
||||||
@@ -116,13 +134,8 @@ export default function UserDashboard() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const respondDoc = async (docId, approved) => {
|
const respondDoc = async (docId, approved, reason = "") => {
|
||||||
if (docLoading) return;
|
if (docLoading) return;
|
||||||
let reason = "";
|
|
||||||
if (!approved) {
|
|
||||||
reason = window.prompt("Reason for rejection:");
|
|
||||||
if (reason === null) return;
|
|
||||||
}
|
|
||||||
setDocLoading(true);
|
setDocLoading(true);
|
||||||
try {
|
try {
|
||||||
const res = await authFetch("/api/review/admin-doc-response", {
|
const res = await authFetch("/api/review/admin-doc-response", {
|
||||||
@@ -131,7 +144,9 @@ export default function UserDashboard() {
|
|||||||
body: JSON.stringify({ doc_id: docId, status: approved ? "approved" : "rejected", reason })
|
body: JSON.stringify({ doc_id: docId, status: approved ? "approved" : "rejected", reason })
|
||||||
});
|
});
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
|
setRejectPanel(null);
|
||||||
showToast(`Document ${approved ? 'approved' : 'rejected'} successfully`, "success");
|
showToast(`Document ${approved ? 'approved' : 'rejected'} successfully`, "success");
|
||||||
|
loadAdminDocs();
|
||||||
} else {
|
} else {
|
||||||
showToast("Failed to submit response", "error");
|
showToast("Failed to submit response", "error");
|
||||||
}
|
}
|
||||||
@@ -142,6 +157,11 @@ export default function UserDashboard() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const openUserRejectPanel = (docId) => {
|
||||||
|
setRejectPanel({ docId, note: '' });
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
const toggleSummary = (docId) => {
|
const toggleSummary = (docId) => {
|
||||||
setExpandedSummary(prev => ({ ...prev, [docId]: !prev[docId] }));
|
setExpandedSummary(prev => ({ ...prev, [docId]: !prev[docId] }));
|
||||||
};
|
};
|
||||||
@@ -156,8 +176,25 @@ export default function UserDashboard() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="card fade-up">
|
<div className="card fade-up">
|
||||||
<h3 style={{marginBottom: '16px'}}>Engagement Letter</h3>
|
<div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: '16px', marginBottom: '16px'}}>
|
||||||
<p className="text-sm" style={{marginBottom: '16px'}}>Please acknowledge the engagement letter before uploading documents.</p>
|
<div>
|
||||||
|
<h3 style={{margin: 0, marginBottom: '4px'}}>Engagement Letter</h3>
|
||||||
|
<p className="text-sm">Please review and acknowledge the engagement letter before uploading documents.</p>
|
||||||
|
</div>
|
||||||
|
{engagementLink && (
|
||||||
|
<a
|
||||||
|
href={engagementLink}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="btn btn-secondary btn-sm"
|
||||||
|
style={{display: 'flex', alignItems: 'center', gap: '6px', borderRadius: 'var(--radius-pill)'}}
|
||||||
|
>
|
||||||
|
<span className="material-symbols-outlined" style={{fontSize: '18px'}}>download</span>
|
||||||
|
Download PDF
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
<label style={{
|
<label style={{
|
||||||
display: 'flex', alignItems: 'center', gap: '12px', padding: '16px',
|
display: 'flex', alignItems: 'center', gap: '12px', padding: '16px',
|
||||||
background: 'var(--bg)', borderRadius: 'var(--radius-sm)', border: '1px solid var(--border)',
|
background: 'var(--bg)', borderRadius: 'var(--radius-sm)', border: '1px solid var(--border)',
|
||||||
@@ -224,6 +261,7 @@ export default function UserDashboard() {
|
|||||||
<tr>
|
<tr>
|
||||||
<th>Document Name</th>
|
<th>Document Name</th>
|
||||||
<th>Date Provided</th>
|
<th>Date Provided</th>
|
||||||
|
<th>Status</th>
|
||||||
<th>Actions</th>
|
<th>Actions</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -236,126 +274,81 @@ export default function UserDashboard() {
|
|||||||
<div className="text-sm text-muted">{doc.filename}</div>
|
<div className="text-sm text-muted">{doc.filename}</div>
|
||||||
</td>
|
</td>
|
||||||
<td>{new Date(doc.created_at).toLocaleDateString()}</td>
|
<td>{new Date(doc.created_at).toLocaleDateString()}</td>
|
||||||
|
<td>
|
||||||
|
{doc.review_status ? (
|
||||||
|
<div>
|
||||||
|
<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 && (
|
||||||
|
<div style={{fontSize:'12px', color:'#c0392b', fontStyle:'italic', marginTop:'4px'}}>
|
||||||
|
Reason: "{doc.review_note}"
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<span className="badge badge-yellow">PENDING</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<div style={{display:'flex', gap:'8px', flexWrap:'wrap', alignItems:'center'}}>
|
<div style={{display:'flex', gap:'8px', flexWrap:'wrap', alignItems:'center'}}>
|
||||||
<button className="btn btn-secondary btn-sm" onClick={() => viewDoc(doc.storage_key)}>View</button>
|
<button className="btn btn-secondary btn-sm" onClick={() => viewDoc(doc.storage_key)}>View</button>
|
||||||
<button className="btn btn-primary btn-sm" onClick={() => respondDoc(doc.id, true)} disabled={docLoading}>Approve</button>
|
<button className="btn btn-primary btn-sm" onClick={() => respondDoc(doc.id, true)} disabled={docLoading}>Approve</button>
|
||||||
<button className="btn btn-danger btn-sm" onClick={() => respondDoc(doc.id, false)} disabled={docLoading}>Reject</button>
|
<button className="btn btn-danger btn-sm" onClick={() => openUserRejectPanel(doc.id)} disabled={docLoading}>Reject</button>
|
||||||
|
|
||||||
{/* AI Summary badge / button */}
|
|
||||||
{doc.ai_summary === null ? (
|
|
||||||
<span style={{
|
|
||||||
display: 'inline-flex', alignItems: 'center', gap: '6px',
|
|
||||||
fontSize: '11.5px', fontWeight: 500,
|
|
||||||
color: 'var(--brass-dark)',
|
|
||||||
padding: '5px 12px', borderRadius: 'var(--radius-pill)',
|
|
||||||
background: 'var(--brass-light)',
|
|
||||||
border: '1px solid rgba(176,128,61,0.25)',
|
|
||||||
letterSpacing: '0.01em',
|
|
||||||
}}>
|
|
||||||
<span style={{display:'inline-block', animation:'spin 1.5s linear infinite', fontSize:'13px'}}>✦</span>
|
|
||||||
Analyzing…
|
|
||||||
</span>
|
|
||||||
) : doc.ai_summary ? (
|
|
||||||
<button
|
|
||||||
onClick={() => toggleSummary(doc.id)}
|
|
||||||
style={{
|
|
||||||
display: 'inline-flex', alignItems: 'center', gap: '6px',
|
|
||||||
fontSize: '11.5px', fontWeight: 600,
|
|
||||||
padding: '5px 14px', borderRadius: 'var(--radius-pill)',
|
|
||||||
border: expandedSummary[doc.id]
|
|
||||||
? '1px solid var(--accent)'
|
|
||||||
: '1px solid rgba(44,122,91,0.35)',
|
|
||||||
cursor: 'pointer',
|
|
||||||
background: expandedSummary[doc.id]
|
|
||||||
? 'var(--accent)'
|
|
||||||
: 'linear-gradient(135deg, rgba(44,122,91,0.10) 0%, rgba(31,93,70,0.06) 100%)',
|
|
||||||
color: expandedSummary[doc.id] ? '#fff' : 'var(--accent)',
|
|
||||||
boxShadow: expandedSummary[doc.id] ? 'var(--shadow-sm)' : 'none',
|
|
||||||
transition: 'all 0.22s ease',
|
|
||||||
letterSpacing: '0.01em',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<span style={{fontSize:'13px'}}>✨</span>
|
|
||||||
{expandedSummary[doc.id] ? 'Hide Summary' : 'AI Summary'}
|
|
||||||
</button>
|
|
||||||
) : null}
|
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|
||||||
{/* Expanded AI Summary panel — spans full row width */}
|
{/* Inline Reject Panel */}
|
||||||
{expandedSummary[doc.id] && doc.ai_summary && (
|
{rejectPanel?.docId === doc.id && (
|
||||||
<tr key={`${doc.id}-summary`}>
|
<tr key={`reject-${doc.id}`}>
|
||||||
<td colSpan={3} style={{padding: '0 0 14px'}}>
|
<td colSpan={4} style={{padding:'0'}}>
|
||||||
<div style={{
|
<div style={{
|
||||||
|
padding: '14px 16px',
|
||||||
|
background: 'rgba(220,53,69,0.05)',
|
||||||
|
border: '1px solid rgba(220,53,69,0.25)',
|
||||||
|
borderTop: 'none',
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
borderRadius: 'var(--radius-md)',
|
flexDirection: 'column',
|
||||||
overflow: 'hidden',
|
gap: '10px'
|
||||||
border: '1px solid rgba(44,122,91,0.20)',
|
|
||||||
boxShadow: '0 4px 20px -6px rgba(44,122,91,0.18)',
|
|
||||||
background: 'linear-gradient(135deg, rgba(44,122,91,0.07) 0%, rgba(31,93,70,0.03) 100%)',
|
|
||||||
backdropFilter: 'blur(8px)',
|
|
||||||
animation: 'fadeUp 0.2s ease',
|
|
||||||
}}>
|
}}>
|
||||||
{/* Left accent strip */}
|
<div style={{fontWeight:600, fontSize:'13px', color:'#c0392b', display:'flex', alignItems:'center', gap:'6px'}}>
|
||||||
<div style={{
|
<span className="material-symbols-outlined" style={{fontSize:'16px'}}>feedback</span>
|
||||||
width: '4px', flexShrink: 0,
|
Reason for Rejection (optional)
|
||||||
background: 'linear-gradient(180deg, var(--accent) 0%, var(--brass) 100%)',
|
</div>
|
||||||
}} />
|
<textarea
|
||||||
|
rows={3}
|
||||||
<div style={{padding: '16px 20px', flex: 1}}>
|
placeholder="Tell the admin why you are rejecting this document..."
|
||||||
{/* Header row */}
|
value={rejectPanel.note}
|
||||||
<div style={{
|
onChange={e => setRejectPanel(prev => ({...prev, note: e.target.value}))}
|
||||||
display: 'flex', alignItems: 'center', gap: '8px',
|
style={{
|
||||||
marginBottom: '10px'
|
width: '100%',
|
||||||
}}>
|
padding: '10px 12px',
|
||||||
<div style={{
|
border: '1px solid rgba(220,53,69,0.35)',
|
||||||
width: '28px', height: '28px', borderRadius: 'var(--radius-xs)',
|
borderRadius: 'var(--radius-sm)',
|
||||||
background: 'linear-gradient(135deg, var(--accent) 0%, var(--emerald-dark) 100%)',
|
fontSize: '13px',
|
||||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
resize: 'vertical',
|
||||||
fontSize: '14px', flexShrink: 0,
|
outline: 'none',
|
||||||
boxShadow: '0 2px 8px rgba(44,122,91,0.30)',
|
fontFamily: 'inherit',
|
||||||
}}>
|
background: 'white',
|
||||||
✨
|
boxSizing: 'border-box'
|
||||||
</div>
|
}}
|
||||||
<div>
|
/>
|
||||||
<div style={{
|
<div style={{display:'flex', gap:'8px', justifyContent:'flex-end'}}>
|
||||||
fontSize: '10px', fontWeight: 700,
|
<button
|
||||||
letterSpacing: '0.08em', textTransform: 'uppercase',
|
className="btn btn-secondary btn-sm"
|
||||||
color: 'var(--accent)',
|
style={{borderRadius:'var(--radius-sm)'}}
|
||||||
}}>AI Document Summary</div>
|
onClick={() => setRejectPanel(null)}
|
||||||
<div style={{
|
>Cancel</button>
|
||||||
fontSize: '11px', color: 'var(--muted)', marginTop: '1px'
|
<button
|
||||||
}}>Generated by BookKeepPro AI</div>
|
className="btn btn-danger btn-sm"
|
||||||
</div>
|
style={{borderRadius:'var(--radius-sm)'}}
|
||||||
</div>
|
disabled={docLoading}
|
||||||
|
onClick={() => respondDoc(doc.id, false, rejectPanel.note)}
|
||||||
{/* Summary text */}
|
>
|
||||||
<p style={{
|
<span className="material-symbols-outlined" style={{fontSize:'15px', verticalAlign:'middle', marginRight:'4px'}}>block</span>
|
||||||
fontSize: '13.5px', lineHeight: '1.7',
|
Confirm Rejection
|
||||||
color: 'var(--ink)',
|
</button>
|
||||||
margin: 0,
|
|
||||||
fontFamily: 'var(--font-body)',
|
|
||||||
}}>
|
|
||||||
{doc.ai_summary}
|
|
||||||
</p>
|
|
||||||
|
|
||||||
{/* Footer disclaimer */}
|
|
||||||
<div style={{
|
|
||||||
display: 'flex', alignItems: 'center', gap: '6px',
|
|
||||||
marginTop: '12px',
|
|
||||||
paddingTop: '10px',
|
|
||||||
borderTop: '1px solid rgba(44,122,91,0.12)',
|
|
||||||
}}>
|
|
||||||
<span style={{fontSize:'11px', color:'var(--muted)'}}>⚠</span>
|
|
||||||
<span style={{
|
|
||||||
fontSize: '11px', color: 'var(--muted)',
|
|
||||||
fontStyle: 'italic',
|
|
||||||
}}>
|
|
||||||
AI-generated summary — always review the original document for authoritative information.
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ def create_access_token(
|
|||||||
payload = {
|
payload = {
|
||||||
"sub": subject,
|
"sub": subject,
|
||||||
"role": role.lower(),
|
"role": role.lower(),
|
||||||
|
"type": "access",
|
||||||
"exp": expire,
|
"exp": expire,
|
||||||
}
|
}
|
||||||
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
|
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
|
||||||
@@ -169,8 +170,12 @@ def get_current_user(
|
|||||||
try:
|
try:
|
||||||
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||||||
email: str | None = payload.get("sub")
|
email: str | None = payload.get("sub")
|
||||||
|
# Old access tokens omitted 'type', so we default to 'access'.
|
||||||
if not email:
|
# Reset and verification tokens explicitly set their type, so they will fail this check.
|
||||||
|
token_type = payload.get("type", "access")
|
||||||
|
|
||||||
|
# We must explicitly check type claim to prevent reset tokens from acting as access tokens
|
||||||
|
if not email or token_type != "access":
|
||||||
raise credentials_exception
|
raise credentials_exception
|
||||||
|
|
||||||
except JWTError:
|
except JWTError:
|
||||||
@@ -207,8 +212,29 @@ def require_super_admin(current_user=Depends(get_current_user)):
|
|||||||
return current_user
|
return current_user
|
||||||
|
|
||||||
|
|
||||||
|
def assert_admin_can_access(current_user, target_user):
|
||||||
|
"""
|
||||||
|
Enforces that:
|
||||||
|
1. The current user is actually an admin/super_admin.
|
||||||
|
2. The target user exists (throws 404).
|
||||||
|
3. The target user has a 'user' role (throws 403).
|
||||||
|
"""
|
||||||
|
if not target_user:
|
||||||
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||||||
|
|
||||||
|
if current_user.role not in [UserRole.admin, UserRole.super_admin]:
|
||||||
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin access required")
|
||||||
|
|
||||||
|
if target_user.role != UserRole.user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Admins can only interact with regular user accounts"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# =========================
|
# =========================
|
||||||
# Auth Routes
|
# Auth Routes
|
||||||
|
|
||||||
# =========================
|
# =========================
|
||||||
|
|
||||||
@router.post("/signup", response_model=TokenResponse)
|
@router.post("/signup", response_model=TokenResponse)
|
||||||
@@ -469,6 +495,7 @@ def update_me(
|
|||||||
def list_users_for_admin(
|
def list_users_for_admin(
|
||||||
skip: int = Query(0, ge=0),
|
skip: int = Query(0, ge=0),
|
||||||
limit: int = Query(100, ge=1, le=500),
|
limit: int = Query(100, ge=1, le=500),
|
||||||
|
tax_year: int = Query(None),
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
current_user=Depends(get_current_user),
|
current_user=Depends(get_current_user),
|
||||||
_=Depends(require_admin),
|
_=Depends(require_admin),
|
||||||
@@ -482,16 +509,22 @@ def list_users_for_admin(
|
|||||||
from sqlalchemy import func as sqlfunc
|
from sqlalchemy import func as sqlfunc
|
||||||
|
|
||||||
def _pending_count(uid: int) -> dict:
|
def _pending_count(uid: int) -> dict:
|
||||||
p = db.query(sqlfunc.count(PersonalDocument.id)).filter(
|
p_q = db.query(sqlfunc.count(PersonalDocument.id)).filter(
|
||||||
PersonalDocument.user_id == uid,
|
PersonalDocument.user_id == uid,
|
||||||
PersonalDocument.review_status == "pending",
|
PersonalDocument.review_status == "pending",
|
||||||
PersonalDocument.deleted_at == None,
|
PersonalDocument.deleted_at == None,
|
||||||
).scalar() or 0
|
)
|
||||||
b = db.query(sqlfunc.count(BusinessDocument.id)).filter(
|
b_q = db.query(sqlfunc.count(BusinessDocument.id)).filter(
|
||||||
BusinessDocument.user_id == uid,
|
BusinessDocument.user_id == uid,
|
||||||
BusinessDocument.review_status == "pending",
|
BusinessDocument.review_status == "pending",
|
||||||
BusinessDocument.deleted_at == None,
|
BusinessDocument.deleted_at == None,
|
||||||
).scalar() or 0
|
)
|
||||||
|
if tax_year is not None:
|
||||||
|
p_q = p_q.filter(PersonalDocument.tax_year == tax_year)
|
||||||
|
b_q = b_q.filter(BusinessDocument.tax_year == tax_year)
|
||||||
|
|
||||||
|
p = p_q.scalar() or 0
|
||||||
|
b = b_q.scalar() or 0
|
||||||
return {"pending_personal": p, "pending_business": b, "pending_docs": p + b}
|
return {"pending_personal": p, "pending_business": b, "pending_docs": p + b}
|
||||||
|
|
||||||
if current_user.role == UserRole.super_admin:
|
if current_user.role == UserRole.super_admin:
|
||||||
|
|||||||
@@ -200,3 +200,4 @@ def spa_fallback(full_path: str):
|
|||||||
status_code=404,
|
status_code=404,
|
||||||
detail="Frontend not built. Run 'npm run build' in /frontend.",
|
detail="Frontend not built. Run 'npm run build' in /frontend.",
|
||||||
)
|
)
|
||||||
|
# reload
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ class PersonalDocument(Base):
|
|||||||
content_type = Column(String(100))
|
content_type = Column(String(100))
|
||||||
uploaded_at = Column(DateTime(timezone=True), server_default=func.now())
|
uploaded_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||||
deleted_at = Column(DateTime(timezone=True), nullable=True, default=None)
|
deleted_at = Column(DateTime(timezone=True), nullable=True, default=None)
|
||||||
review_status = Column(String(20), default="pending", nullable=False)
|
review_status = Column(String(20), default="draft", nullable=False)
|
||||||
review_note = Column(String(500), nullable=True)
|
review_note = Column(String(500), nullable=True)
|
||||||
tax_year = Column(Integer, default=2025, nullable=False)
|
tax_year = Column(Integer, default=2025, nullable=False)
|
||||||
extracted_data = Column(JSON, nullable=True)
|
extracted_data = Column(JSON, nullable=True)
|
||||||
@@ -89,7 +89,7 @@ class BusinessDocument(Base):
|
|||||||
content_type = Column(String(100))
|
content_type = Column(String(100))
|
||||||
uploaded_at = Column(DateTime(timezone=True), server_default=func.now())
|
uploaded_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||||
deleted_at = Column(DateTime(timezone=True), nullable=True, default=None)
|
deleted_at = Column(DateTime(timezone=True), nullable=True, default=None)
|
||||||
review_status = Column(String(20), default="pending", nullable=False)
|
review_status = Column(String(20), default="draft", nullable=False)
|
||||||
review_note = Column(String(500), nullable=True)
|
review_note = Column(String(500), nullable=True)
|
||||||
tax_year = Column(Integer, default=2025, nullable=False)
|
tax_year = Column(Integer, default=2025, nullable=False)
|
||||||
extracted_data = Column(JSON, nullable=True)
|
extracted_data = Column(JSON, nullable=True)
|
||||||
@@ -127,6 +127,12 @@ class AdminDocument(Base):
|
|||||||
# None = still processing, non-null = ready to display
|
# None = still processing, non-null = ready to display
|
||||||
ai_summary = Column(Text, nullable=True)
|
ai_summary = Column(Text, nullable=True)
|
||||||
|
|
||||||
|
# Workflow additions
|
||||||
|
tax_year = Column(Integer, nullable=True)
|
||||||
|
review_status = Column(String(20), default="pending", nullable=False)
|
||||||
|
review_note = Column(String(500), nullable=True)
|
||||||
|
reviewed_at = Column(DateTime(timezone=True), nullable=True)
|
||||||
|
|
||||||
admin = relationship("User", foreign_keys=[uploaded_by])
|
admin = relationship("User", foreign_keys=[uploaded_by])
|
||||||
user = relationship("User", foreign_keys=[user_id])
|
user = relationship("User", foreign_keys=[user_id])
|
||||||
|
|
||||||
@@ -248,3 +254,46 @@ class FilingDeadline(Base):
|
|||||||
Index("ix_filing_deadlines_user_id", "user_id"),
|
Index("ix_filing_deadlines_user_id", "user_id"),
|
||||||
Index("ix_filing_deadlines_deadline_date", "deadline_date"),
|
Index("ix_filing_deadlines_deadline_date", "deadline_date"),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────
|
||||||
|
# Workflow & Review System
|
||||||
|
# ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
class DocumentReviewEvent(Base):
|
||||||
|
__tablename__ = "document_review_events"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
doc_kind = Column(String(50), nullable=False) # 'admin' | 'personal' | 'business'
|
||||||
|
doc_id = Column(Integer, nullable=False)
|
||||||
|
owner_user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||||
|
actor_id = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
|
||||||
|
actor_role = Column(String(20), nullable=False) # 'user' | 'admin' | 'super_admin'
|
||||||
|
action = Column(String(50), nullable=False) # 'uploaded', 'returned_for_review', 'approved', 'rejected', 'resubmitted', 'admin_comment'
|
||||||
|
from_status = Column(String(20), nullable=True)
|
||||||
|
to_status = Column(String(20), nullable=True)
|
||||||
|
tax_year = Column(Integer, nullable=True)
|
||||||
|
comment = Column(Text, nullable=True)
|
||||||
|
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||||
|
|
||||||
|
owner = relationship("User", foreign_keys=[owner_user_id])
|
||||||
|
actor = relationship("User", foreign_keys=[actor_id])
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
Index("ix_document_review_events_composite", "doc_kind", "doc_id", "created_at"),
|
||||||
|
Index("ix_document_review_events_owner", "owner_user_id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
class AdminDocumentBookmark(Base):
|
||||||
|
__tablename__ = "admin_document_bookmarks"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
admin_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||||
|
doc_kind = Column(String(50), nullable=False)
|
||||||
|
doc_id = Column(Integer, nullable=False)
|
||||||
|
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||||
|
|
||||||
|
admin = relationship("User")
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("admin_id", "doc_kind", "doc_id", name="uq_admin_bookmark"),
|
||||||
|
)
|
||||||
|
|||||||
@@ -145,6 +145,26 @@ async def admin_doc_response(
|
|||||||
f"belonging to user {doc.user_id}"
|
f"belonging to user {doc.user_id}"
|
||||||
)
|
)
|
||||||
raise HTTPException(status_code=403, detail="Not authorized")
|
raise HTTPException(status_code=403, detail="Not authorized")
|
||||||
|
|
||||||
|
doc.review_status = payload.status
|
||||||
|
if payload.reason:
|
||||||
|
doc.review_note = payload.reason
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
from app.models import DocumentReviewEvent
|
||||||
|
event = DocumentReviewEvent(
|
||||||
|
doc_kind="admin",
|
||||||
|
doc_id=doc.id,
|
||||||
|
owner_user_id=doc.user_id,
|
||||||
|
actor_id=current_user.id,
|
||||||
|
actor_role="user",
|
||||||
|
action=payload.status,
|
||||||
|
to_status=payload.status,
|
||||||
|
note=payload.reason,
|
||||||
|
tax_year=doc.tax_year
|
||||||
|
)
|
||||||
|
db.add(event)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
admin = db.query(User).filter_by(id=doc.uploaded_by).first()
|
admin = db.query(User).filter_by(id=doc.uploaded_by).first()
|
||||||
if not admin:
|
if not admin:
|
||||||
@@ -168,7 +188,92 @@ async def admin_doc_response(
|
|||||||
|
|
||||||
logger.info(f"User {current_user.id} {payload.status} admin doc {payload.doc_id}")
|
logger.info(f"User {current_user.id} {payload.status} admin doc {payload.doc_id}")
|
||||||
return {"status": "notified"}
|
return {"status": "notified"}
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────
|
||||||
|
# Update Status and History
|
||||||
|
# ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
@router.get("/history/{doc_kind}/{doc_id}")
|
||||||
|
def get_document_review_history(
|
||||||
|
doc_kind: str,
|
||||||
|
doc_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user=Depends(get_current_user),
|
||||||
|
):
|
||||||
|
from app.models import DocumentReviewEvent
|
||||||
|
events = db.query(DocumentReviewEvent).filter_by(
|
||||||
|
doc_kind=doc_kind,
|
||||||
|
doc_id=doc_id
|
||||||
|
).order_by(DocumentReviewEvent.created_at.asc()).all()
|
||||||
|
|
||||||
|
# If standard user, verify ownership
|
||||||
|
if current_user.role == UserRole.user:
|
||||||
|
if not events or events[0].owner_user_id != current_user.id:
|
||||||
|
raise HTTPException(status_code=403, detail="Unauthorized")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"history": [
|
||||||
|
{
|
||||||
|
"id": e.id,
|
||||||
|
"actor_role": e.actor_role,
|
||||||
|
"action": e.action,
|
||||||
|
"to_status": e.to_status,
|
||||||
|
"note": e.note,
|
||||||
|
"created_at": e.created_at.isoformat() + "Z" if e.created_at else None
|
||||||
|
} for e in events
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
from pydantic import BaseModel
|
||||||
|
class StatusUpdateRequest(BaseModel):
|
||||||
|
status: str
|
||||||
|
note: str | None = None
|
||||||
|
|
||||||
|
@router.put("/status/{doc_kind}/{doc_id}")
|
||||||
|
def update_document_status(
|
||||||
|
doc_kind: str,
|
||||||
|
doc_id: int,
|
||||||
|
payload: StatusUpdateRequest,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user=Depends(require_admin),
|
||||||
|
):
|
||||||
|
from app.models import PersonalDocument, BusinessDocument, DocumentReviewEvent
|
||||||
|
model_map = {
|
||||||
|
'admin': AdminDocument,
|
||||||
|
'personal': PersonalDocument,
|
||||||
|
'business': BusinessDocument
|
||||||
|
}
|
||||||
|
if doc_kind not in model_map:
|
||||||
|
raise HTTPException(status_code=400, detail="Invalid doc_kind")
|
||||||
|
|
||||||
|
doc = db.query(model_map[doc_kind]).filter_by(id=doc_id).first()
|
||||||
|
if not doc:
|
||||||
|
raise HTTPException(status_code=404, detail="Document not found")
|
||||||
|
|
||||||
|
doc.review_status = payload.status
|
||||||
|
if payload.note is not None:
|
||||||
|
doc.review_note = payload.note
|
||||||
|
if payload.status == 'approved':
|
||||||
|
from datetime import datetime
|
||||||
|
doc.reviewed_at = datetime.utcnow()
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
event = DocumentReviewEvent(
|
||||||
|
doc_kind=doc_kind,
|
||||||
|
doc_id=doc.id,
|
||||||
|
owner_user_id=doc.user_id,
|
||||||
|
actor_id=current_user.id,
|
||||||
|
actor_role="admin",
|
||||||
|
action="status_updated",
|
||||||
|
to_status=payload.status,
|
||||||
|
note=payload.note,
|
||||||
|
tax_year=doc.tax_year
|
||||||
|
)
|
||||||
|
db.add(event)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
return {"status": "ok", "review_status": doc.review_status}
|
||||||
|
|
||||||
# ─────────────────────────────────────────────
|
# ─────────────────────────────────────────────
|
||||||
# Get filing deadlines for a user
|
# Get filing deadlines for a user
|
||||||
|
|||||||
+305
-151
@@ -4,7 +4,7 @@ import uuid
|
|||||||
import logging
|
import logging
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import filetype
|
import filetype
|
||||||
from fastapi import APIRouter, BackgroundTasks, UploadFile, File, HTTPException, Depends, Form, Query
|
from fastapi import APIRouter, BackgroundTasks, UploadFile, File, HTTPException, Depends, Form, Query, Response
|
||||||
from fastapi.responses import FileResponse, StreamingResponse
|
from fastapi.responses import FileResponse, StreamingResponse
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from sqlalchemy.exc import IntegrityError
|
from sqlalchemy.exc import IntegrityError
|
||||||
@@ -14,7 +14,7 @@ from datetime import timedelta
|
|||||||
from app.models import AdminDocument, PersonalDocument, BusinessDocument, User, UserRole, ChatSession, ChatMessage
|
from app.models import AdminDocument, PersonalDocument, BusinessDocument, User, UserRole, ChatSession, ChatMessage
|
||||||
from app.db import get_db, SessionLocal
|
from app.db import get_db, SessionLocal
|
||||||
import app.crud as crud
|
import app.crud as crud
|
||||||
from app.auth.security import get_current_user, require_admin, SECRET_KEY, ALGORITHM
|
from app.auth.security import get_current_user, require_admin, assert_admin_can_access, SECRET_KEY, ALGORITHM
|
||||||
from app.utils.emailer import send_email
|
from app.utils.emailer import send_email
|
||||||
from app.utils.ai import extract_document_data, summarize_admin_document, extract_raw_text
|
from app.utils.ai import extract_document_data, summarize_admin_document, extract_raw_text
|
||||||
from app.utils.vector_store import add_document_embedding, delete_document_embeddings, delete_user_embeddings
|
from app.utils.vector_store import add_document_embedding, delete_document_embeddings, delete_user_embeddings
|
||||||
@@ -128,7 +128,9 @@ async def upload_to_storage(file: UploadFile) -> str:
|
|||||||
"application/msword",
|
"application/msword",
|
||||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||||
"application/vnd.ms-excel",
|
"application/vnd.ms-excel",
|
||||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
"application/zip",
|
||||||
|
"application/x-zip-compressed"
|
||||||
}
|
}
|
||||||
|
|
||||||
kind = filetype.guess(contents)
|
kind = filetype.guess(contents)
|
||||||
@@ -137,8 +139,8 @@ async def upload_to_storage(file: UploadFile) -> str:
|
|||||||
ext = os.path.splitext(file.filename or "file")[1].lower()
|
ext = os.path.splitext(file.filename or "file")[1].lower()
|
||||||
|
|
||||||
# Fallback for legacy .doc, .xls, and inconsistent .docx/.xlsx sniffing (which are just zip files)
|
# Fallback for legacy .doc, .xls, and inconsistent .docx/.xlsx sniffing (which are just zip files)
|
||||||
if sniffed_mime is None or sniffed_mime == "application/zip":
|
if sniffed_mime is None or sniffed_mime in ["application/zip", "application/x-zip-compressed"]:
|
||||||
if ext in [".doc", ".docx", ".xls", ".xlsx"] and file.content_type in ALLOWED_TYPES:
|
if ext in [".doc", ".docx", ".xls", ".xlsx", ".zip"] and file.content_type in ALLOWED_TYPES:
|
||||||
sniffed_mime = file.content_type
|
sniffed_mime = file.content_type
|
||||||
|
|
||||||
if sniffed_mime not in ALLOWED_TYPES:
|
if sniffed_mime not in ALLOWED_TYPES:
|
||||||
@@ -256,21 +258,14 @@ async def upload_admin_document(
|
|||||||
doc_key: str = Form(...),
|
doc_key: str = Form(...),
|
||||||
doc_label: str = Form(...),
|
doc_label: str = Form(...),
|
||||||
user_id: int = Form(...),
|
user_id: int = Form(...),
|
||||||
|
tax_year: int | None = Form(None),
|
||||||
background: BackgroundTasks = BackgroundTasks(),
|
background: BackgroundTasks = BackgroundTasks(),
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
current_user=Depends(get_current_user),
|
current_user=Depends(get_current_user),
|
||||||
_=Depends(require_admin),
|
_=Depends(require_admin),
|
||||||
):
|
):
|
||||||
target_user = crud.get_user_by_id(db, user_id)
|
target_user = crud.get_user_by_id(db, user_id)
|
||||||
if not target_user:
|
assert_admin_can_access(current_user, target_user)
|
||||||
raise HTTPException(status_code=404, detail="Target user not found")
|
|
||||||
|
|
||||||
# Regular admins can only upload documents for user-role accounts
|
|
||||||
if current_user.role == UserRole.admin and target_user.role != UserRole.user:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=403,
|
|
||||||
detail="Admins can only upload documents for regular user accounts"
|
|
||||||
)
|
|
||||||
|
|
||||||
logger.info(f"Admin {current_user.id} uploading document for user {user_id}")
|
logger.info(f"Admin {current_user.id} uploading document for user {user_id}")
|
||||||
storage_key = await upload_to_storage(file)
|
storage_key = await upload_to_storage(file)
|
||||||
@@ -283,33 +278,33 @@ async def upload_admin_document(
|
|||||||
content_type=file.content_type,
|
content_type=file.content_type,
|
||||||
uploaded_by=current_user.id,
|
uploaded_by=current_user.id,
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
|
ai_summary="",
|
||||||
|
tax_year=tax_year,
|
||||||
|
review_status="pending"
|
||||||
)
|
)
|
||||||
db.add(record)
|
db.add(record)
|
||||||
db.commit()
|
db.commit()
|
||||||
db.refresh(record)
|
db.refresh(record)
|
||||||
|
|
||||||
|
# Append uploaded event
|
||||||
|
from app.models import DocumentReviewEvent
|
||||||
|
event = DocumentReviewEvent(
|
||||||
|
doc_kind="admin",
|
||||||
|
doc_id=record.id,
|
||||||
|
owner_user_id=user_id,
|
||||||
|
actor_id=current_user.id,
|
||||||
|
actor_role="admin",
|
||||||
|
action="uploaded",
|
||||||
|
to_status="pending",
|
||||||
|
tax_year=tax_year
|
||||||
|
)
|
||||||
|
db.add(event)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
crud.log_action(db, "upload_admin_doc", user_id=current_user.id, target=f"admin_doc:{record.id}", detail=f"for user {user_id}")
|
crud.log_action(db, "upload_admin_doc", user_id=current_user.id, target=f"admin_doc:{record.id}", detail=f"for user {user_id}")
|
||||||
|
|
||||||
# Background task 1: AI summary generation
|
# AI extraction removed as per request
|
||||||
def _generate_summary(doc_id: int, file_path: str, label: str):
|
|
||||||
summary = summarize_admin_document(str(file_path), label)
|
|
||||||
if summary:
|
|
||||||
_db = SessionLocal()
|
|
||||||
try:
|
|
||||||
doc = _db.query(AdminDocument).filter_by(id=doc_id).first()
|
|
||||||
if doc:
|
|
||||||
doc.ai_summary = summary
|
|
||||||
_db.commit()
|
|
||||||
logger.info(f"[Summary] Saved summary for admin_doc:{doc_id}")
|
|
||||||
finally:
|
|
||||||
_db.close()
|
|
||||||
|
|
||||||
background.add_task(
|
|
||||||
_generate_summary,
|
|
||||||
record.id,
|
|
||||||
str(UPLOAD_DIR / storage_key),
|
|
||||||
doc_label,
|
|
||||||
)
|
|
||||||
|
|
||||||
# Background task 2: Notify client by email
|
# Background task 2: Notify client by email
|
||||||
background.add_task(
|
background.add_task(
|
||||||
@@ -334,10 +329,14 @@ async def upload_admin_document(
|
|||||||
|
|
||||||
@router.get("/admin-documents")
|
@router.get("/admin-documents")
|
||||||
def list_admin_documents(
|
def list_admin_documents(
|
||||||
|
response: Response,
|
||||||
user_id: int | None = None,
|
user_id: int | None = None,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
current_user=Depends(get_current_user),
|
current_user=Depends(get_current_user),
|
||||||
):
|
):
|
||||||
|
response.headers["Cache-Control"] = "no-store"
|
||||||
|
bookmarked_doc_ids = set()
|
||||||
|
|
||||||
if current_user.role in [UserRole.admin, UserRole.super_admin]:
|
if current_user.role in [UserRole.admin, UserRole.super_admin]:
|
||||||
if not user_id:
|
if not user_id:
|
||||||
raise HTTPException(status_code=400, detail="user_id is required for admin")
|
raise HTTPException(status_code=400, detail="user_id is required for admin")
|
||||||
@@ -347,6 +346,13 @@ def list_admin_documents(
|
|||||||
.order_by(AdminDocument.uploaded_at.desc())
|
.order_by(AdminDocument.uploaded_at.desc())
|
||||||
.all()
|
.all()
|
||||||
)
|
)
|
||||||
|
from app.models import AdminDocumentBookmark
|
||||||
|
bookmarks = db.query(AdminDocumentBookmark).filter(
|
||||||
|
AdminDocumentBookmark.admin_id == current_user.id,
|
||||||
|
AdminDocumentBookmark.doc_kind == 'admin'
|
||||||
|
).all()
|
||||||
|
bookmarked_doc_ids = {b.doc_id for b in bookmarks}
|
||||||
|
|
||||||
elif current_user.role == UserRole.user:
|
elif current_user.role == UserRole.user:
|
||||||
docs = (
|
docs = (
|
||||||
db.query(AdminDocument)
|
db.query(AdminDocument)
|
||||||
@@ -365,8 +371,11 @@ def list_admin_documents(
|
|||||||
"filename": d.filename,
|
"filename": d.filename,
|
||||||
"storage_key": d.storage_key,
|
"storage_key": d.storage_key,
|
||||||
"created_at": d.uploaded_at.isoformat() + "Z" if d.uploaded_at else None,
|
"created_at": d.uploaded_at.isoformat() + "Z" if d.uploaded_at else None,
|
||||||
# None = AI still processing; string = ready to show
|
|
||||||
"ai_summary": d.ai_summary,
|
"ai_summary": d.ai_summary,
|
||||||
|
"tax_year": d.tax_year,
|
||||||
|
"review_status": d.review_status,
|
||||||
|
"review_note": d.review_note,
|
||||||
|
"bookmarked": d.id in bookmarked_doc_ids
|
||||||
}
|
}
|
||||||
for d in docs
|
for d in docs
|
||||||
]
|
]
|
||||||
@@ -458,6 +467,7 @@ async def upload_personal_document(
|
|||||||
storage_key=storage_key,
|
storage_key=storage_key,
|
||||||
content_type=file.content_type,
|
content_type=file.content_type,
|
||||||
tax_year=tax_year,
|
tax_year=tax_year,
|
||||||
|
review_status="pending"
|
||||||
)
|
)
|
||||||
db.add(record)
|
db.add(record)
|
||||||
try:
|
try:
|
||||||
@@ -472,6 +482,22 @@ async def upload_personal_document(
|
|||||||
"Delete the existing one to replace it."
|
"Delete the existing one to replace it."
|
||||||
)
|
)
|
||||||
db.refresh(record)
|
db.refresh(record)
|
||||||
|
|
||||||
|
# Append uploaded event
|
||||||
|
from app.models import DocumentReviewEvent
|
||||||
|
event = DocumentReviewEvent(
|
||||||
|
doc_kind="personal",
|
||||||
|
doc_id=record.id,
|
||||||
|
owner_user_id=current_user.id,
|
||||||
|
actor_id=current_user.id,
|
||||||
|
actor_role="user",
|
||||||
|
action="uploaded",
|
||||||
|
to_status="pending",
|
||||||
|
tax_year=tax_year
|
||||||
|
)
|
||||||
|
db.add(event)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
crud.log_action(db, "upload_personal", user_id=current_user.id, target=f"personal_doc:{record.id}", detail=file.filename)
|
crud.log_action(db, "upload_personal", user_id=current_user.id, target=f"personal_doc:{record.id}", detail=file.filename)
|
||||||
|
|
||||||
admins = db.query(User).filter(User.role.in_([UserRole.admin, UserRole.super_admin])).all()
|
admins = db.query(User).filter(User.role.in_([UserRole.admin, UserRole.super_admin])).all()
|
||||||
@@ -482,7 +508,13 @@ async def upload_personal_document(
|
|||||||
subject="New Personal Document Uploaded — BookKeepro",
|
subject="New Personal Document Uploaded — BookKeepro",
|
||||||
body=f"<p><strong>{current_user.email}</strong> uploaded a personal document: <strong>{file.filename}</strong> ({doc_type}).</p>",
|
body=f"<p><strong>{current_user.email}</strong> uploaded a personal document: <strong>{file.filename}</strong> ({doc_type}).</p>",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
background.add_task(
|
||||||
|
send_email,
|
||||||
|
to=current_user.email,
|
||||||
|
subject="Personal Document Upload Confirmation — BookKeepro",
|
||||||
|
body=f"<p>We have successfully received your personal document: <strong>{file.filename}</strong> ({doc_type}).</p>",
|
||||||
|
)
|
||||||
background.add_task(
|
background.add_task(
|
||||||
process_ai_extraction,
|
process_ai_extraction,
|
||||||
"personal",
|
"personal",
|
||||||
@@ -490,7 +522,6 @@ async def upload_personal_document(
|
|||||||
str(UPLOAD_DIR / storage_key),
|
str(UPLOAD_DIR / storage_key),
|
||||||
doc_type
|
doc_type
|
||||||
)
|
)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"id": record.id,
|
"id": record.id,
|
||||||
"filename": record.filename,
|
"filename": record.filename,
|
||||||
@@ -583,6 +614,7 @@ async def upload_business_document(
|
|||||||
storage_key=storage_key,
|
storage_key=storage_key,
|
||||||
content_type=file.content_type,
|
content_type=file.content_type,
|
||||||
tax_year=tax_year,
|
tax_year=tax_year,
|
||||||
|
review_status="pending"
|
||||||
)
|
)
|
||||||
db.add(record)
|
db.add(record)
|
||||||
try:
|
try:
|
||||||
@@ -596,6 +628,22 @@ async def upload_business_document(
|
|||||||
"Delete the existing one to replace it."
|
"Delete the existing one to replace it."
|
||||||
)
|
)
|
||||||
db.refresh(record)
|
db.refresh(record)
|
||||||
|
|
||||||
|
# Append uploaded event
|
||||||
|
from app.models import DocumentReviewEvent
|
||||||
|
event = DocumentReviewEvent(
|
||||||
|
doc_kind="business",
|
||||||
|
doc_id=record.id,
|
||||||
|
owner_user_id=current_user.id,
|
||||||
|
actor_id=current_user.id,
|
||||||
|
actor_role="user",
|
||||||
|
action="uploaded",
|
||||||
|
to_status="pending",
|
||||||
|
tax_year=tax_year
|
||||||
|
)
|
||||||
|
db.add(event)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
crud.log_action(db, "upload_business", user_id=current_user.id, target=f"business_doc:{record.id}", detail=file.filename)
|
crud.log_action(db, "upload_business", user_id=current_user.id, target=f"business_doc:{record.id}", detail=file.filename)
|
||||||
|
|
||||||
admins = db.query(User).filter(User.role.in_([UserRole.admin, UserRole.super_admin])).all()
|
admins = db.query(User).filter(User.role.in_([UserRole.admin, UserRole.super_admin])).all()
|
||||||
@@ -607,6 +655,12 @@ async def upload_business_document(
|
|||||||
body=f"<p><strong>{current_user.email}</strong> uploaded a business document: <strong>{file.filename}</strong> ({doc_type}).</p>",
|
body=f"<p><strong>{current_user.email}</strong> uploaded a business document: <strong>{file.filename}</strong> ({doc_type}).</p>",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
background.add_task(
|
||||||
|
send_email,
|
||||||
|
to=current_user.email,
|
||||||
|
subject="Business Document Upload Confirmation — BookKeepro",
|
||||||
|
body=f"<p>We have successfully received your business document: <strong>{file.filename}</strong> ({doc_type}).</p>",
|
||||||
|
)
|
||||||
background.add_task(
|
background.add_task(
|
||||||
process_ai_extraction,
|
process_ai_extraction,
|
||||||
"business",
|
"business",
|
||||||
@@ -614,7 +668,6 @@ async def upload_business_document(
|
|||||||
str(UPLOAD_DIR / storage_key),
|
str(UPLOAD_DIR / storage_key),
|
||||||
doc_type
|
doc_type
|
||||||
)
|
)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"id": record.id,
|
"id": record.id,
|
||||||
"filename": record.filename,
|
"filename": record.filename,
|
||||||
@@ -746,22 +799,18 @@ def update_business_extracted_data(
|
|||||||
|
|
||||||
@router.get("/admin/users/{user_id}/documents")
|
@router.get("/admin/users/{user_id}/documents")
|
||||||
def get_user_all_documents(
|
def get_user_all_documents(
|
||||||
|
response: Response,
|
||||||
user_id: int,
|
user_id: int,
|
||||||
tax_year: int | None = None,
|
tax_year: int | None = Query(None),
|
||||||
|
status: str | None = Query(None),
|
||||||
|
bookmarked: bool | None = Query(None),
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
current_user=Depends(get_current_user),
|
current_user=Depends(get_current_user),
|
||||||
_=Depends(require_admin),
|
_=Depends(require_admin),
|
||||||
):
|
):
|
||||||
user = db.query(User).filter(User.id == user_id).first()
|
response.headers["Cache-Control"] = "no-store"
|
||||||
if not user:
|
user = crud.get_user_by_id(db, user_id)
|
||||||
raise HTTPException(status_code=404, detail="User not found")
|
assert_admin_can_access(current_user, user)
|
||||||
|
|
||||||
# Regular admins can only view documents for user-role accounts
|
|
||||||
if current_user.role == UserRole.admin and user.role != UserRole.user:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=403,
|
|
||||||
detail="Admins can only view documents for regular user accounts"
|
|
||||||
)
|
|
||||||
|
|
||||||
logger.info(f"Admin {current_user.id} retrieving all documents for user {user_id}")
|
logger.info(f"Admin {current_user.id} retrieving all documents for user {user_id}")
|
||||||
|
|
||||||
@@ -771,15 +820,29 @@ def get_user_all_documents(
|
|||||||
bq = db.query(BusinessDocument).filter(
|
bq = db.query(BusinessDocument).filter(
|
||||||
BusinessDocument.user_id == user_id, BusinessDocument.deleted_at == None
|
BusinessDocument.user_id == user_id, BusinessDocument.deleted_at == None
|
||||||
)
|
)
|
||||||
|
|
||||||
if tax_year:
|
if tax_year:
|
||||||
pq = pq.filter(PersonalDocument.tax_year == tax_year)
|
pq = pq.filter(PersonalDocument.tax_year == tax_year)
|
||||||
bq = bq.filter(BusinessDocument.tax_year == tax_year)
|
bq = bq.filter(BusinessDocument.tax_year == tax_year)
|
||||||
|
if status:
|
||||||
|
pq = pq.filter(PersonalDocument.review_status == status)
|
||||||
|
bq = bq.filter(BusinessDocument.review_status == status)
|
||||||
|
|
||||||
|
from app.models import AdminDocumentBookmark
|
||||||
|
bookmarks = db.query(AdminDocumentBookmark).filter(
|
||||||
|
AdminDocumentBookmark.admin_id == current_user.id
|
||||||
|
).all()
|
||||||
|
bookmarked_personal = {b.doc_id for b in bookmarks if b.doc_kind == 'personal'}
|
||||||
|
bookmarked_business = {b.doc_id for b in bookmarks if b.doc_kind == 'business'}
|
||||||
|
|
||||||
personal_docs = pq.order_by(PersonalDocument.uploaded_at.desc()).all()
|
personal_docs = pq.order_by(PersonalDocument.uploaded_at.desc()).all()
|
||||||
business_docs = bq.order_by(BusinessDocument.uploaded_at.desc()).all()
|
business_docs = bq.order_by(BusinessDocument.uploaded_at.desc()).all()
|
||||||
|
|
||||||
documents = [
|
documents = []
|
||||||
{
|
for d in personal_docs:
|
||||||
|
is_bm = d.id in bookmarked_personal
|
||||||
|
if bookmarked and not is_bm: continue
|
||||||
|
documents.append({
|
||||||
"id": d.id,
|
"id": d.id,
|
||||||
"table": "personal",
|
"table": "personal",
|
||||||
"doc_type": d.doc_type,
|
"doc_type": d.doc_type,
|
||||||
@@ -790,10 +853,12 @@ def get_user_all_documents(
|
|||||||
"review_status": d.review_status,
|
"review_status": d.review_status,
|
||||||
"review_note": d.review_note,
|
"review_note": d.review_note,
|
||||||
"extracted_data": d.extracted_data,
|
"extracted_data": d.extracted_data,
|
||||||
}
|
"bookmarked": is_bm,
|
||||||
for d in personal_docs
|
})
|
||||||
] + [
|
for d in business_docs:
|
||||||
{
|
is_bm = d.id in bookmarked_business
|
||||||
|
if bookmarked and not is_bm: continue
|
||||||
|
documents.append({
|
||||||
"id": d.id,
|
"id": d.id,
|
||||||
"table": "business",
|
"table": "business",
|
||||||
"doc_type": d.business_type,
|
"doc_type": d.business_type,
|
||||||
@@ -804,9 +869,8 @@ def get_user_all_documents(
|
|||||||
"review_status": d.review_status,
|
"review_status": d.review_status,
|
||||||
"review_note": d.review_note,
|
"review_note": d.review_note,
|
||||||
"extracted_data": d.extracted_data,
|
"extracted_data": d.extracted_data,
|
||||||
}
|
"bookmarked": is_bm,
|
||||||
for d in business_docs
|
})
|
||||||
]
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"user": {
|
"user": {
|
||||||
@@ -1113,12 +1177,12 @@ def export_user_documents_excel(
|
|||||||
current_user=Depends(get_current_user),
|
current_user=Depends(get_current_user),
|
||||||
_=Depends(require_admin),
|
_=Depends(require_admin),
|
||||||
):
|
):
|
||||||
"""Export all documents for a user as a formatted Excel (.xlsx) workbook."""
|
"""Export all documents for a user as separate Excel files in a ZIP archive."""
|
||||||
import io
|
import io
|
||||||
|
import zipfile
|
||||||
import json as _json
|
import json as _json
|
||||||
from openpyxl import Workbook
|
from openpyxl import Workbook
|
||||||
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
|
from openpyxl.styles import Font, PatternFill, Alignment
|
||||||
from openpyxl.utils import get_column_letter
|
|
||||||
|
|
||||||
user = db.query(User).filter(User.id == user_id).first()
|
user = db.query(User).filter(User.id == user_id).first()
|
||||||
if not user:
|
if not user:
|
||||||
@@ -1133,109 +1197,199 @@ def export_user_documents_excel(
|
|||||||
BusinessDocument.user_id == user_id, BusinessDocument.deleted_at == None
|
BusinessDocument.user_id == user_id, BusinessDocument.deleted_at == None
|
||||||
).all()
|
).all()
|
||||||
|
|
||||||
# Collect all extracted_data keys to build dynamic columns
|
def sanitize_val(v):
|
||||||
extracted_keys = set()
|
s = str(v)
|
||||||
all_docs = []
|
if s.startswith(('=', '+', '-', '@')):
|
||||||
|
return "'" + s
|
||||||
|
return s
|
||||||
|
|
||||||
for d in personal_docs:
|
zip_buffer = io.BytesIO()
|
||||||
row = {
|
with zipfile.ZipFile(zip_buffer, "a", zipfile.ZIP_DEFLATED, False) as zip_file:
|
||||||
"ID": f"P-{d.id}",
|
for docs, prefix in [(personal_docs, "Personal"), (business_docs, "Business")]:
|
||||||
"Table": "Personal",
|
for d in docs:
|
||||||
"Doc Type": d.doc_type,
|
wb = Workbook()
|
||||||
"Filename": d.filename,
|
ws = wb.active
|
||||||
"Uploaded At": d.uploaded_at.strftime("%Y-%m-%d %H:%M") if d.uploaded_at else "",
|
ws.title = "AI Summary"
|
||||||
"Tax Year": d.tax_year or "",
|
ws.append(["Field", "Value"])
|
||||||
"Review Status": (d.review_status or "").capitalize(),
|
|
||||||
"Review Note": d.review_note or "",
|
header_font = Font(bold=True, color="FFFFFF")
|
||||||
}
|
header_fill = PatternFill(start_color="2C7A5B", end_color="2C7A5B", fill_type="solid")
|
||||||
if d.extracted_data:
|
for cell in ws[1]:
|
||||||
try:
|
cell.font = header_font
|
||||||
data = _json.loads(d.extracted_data) if isinstance(d.extracted_data, str) else d.extracted_data
|
cell.fill = header_fill
|
||||||
if isinstance(data, dict):
|
|
||||||
for k, v in data.items():
|
|
||||||
col = f"AI: {k}"
|
|
||||||
extracted_keys.add(col)
|
|
||||||
row[col] = str(v)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
all_docs.append(row)
|
|
||||||
|
|
||||||
for d in business_docs:
|
ws.append(["ID", f"{prefix[0]}-{d.id}"])
|
||||||
row = {
|
doc_type_val = getattr(d, 'doc_type', getattr(d, 'business_type', 'Unknown'))
|
||||||
"ID": f"B-{d.id}",
|
ws.append(["Type", sanitize_val(doc_type_val)])
|
||||||
"Table": "Business",
|
ws.append(["Filename", sanitize_val(d.filename)])
|
||||||
"Doc Type": d.business_type,
|
ws.append(["Tax Year", d.tax_year or ""])
|
||||||
"Filename": d.filename,
|
ws.append(["Status", sanitize_val(d.review_status or "")])
|
||||||
"Uploaded At": d.uploaded_at.strftime("%Y-%m-%d %H:%M") if d.uploaded_at else "",
|
|
||||||
"Tax Year": d.tax_year or "",
|
|
||||||
"Review Status": (d.review_status or "").capitalize(),
|
|
||||||
"Review Note": d.review_note or "",
|
|
||||||
}
|
|
||||||
if d.extracted_data:
|
|
||||||
try:
|
|
||||||
data = _json.loads(d.extracted_data) if isinstance(d.extracted_data, str) else d.extracted_data
|
|
||||||
if isinstance(data, dict):
|
|
||||||
for k, v in data.items():
|
|
||||||
col = f"AI: {k}"
|
|
||||||
extracted_keys.add(col)
|
|
||||||
row[col] = str(v)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
all_docs.append(row)
|
|
||||||
|
|
||||||
base_cols = ["ID", "Table", "Doc Type", "Filename", "Uploaded At", "Tax Year", "Review Status", "Review Note"]
|
if d.extracted_data:
|
||||||
all_cols = base_cols + sorted(list(extracted_keys))
|
ws.append([])
|
||||||
|
ws.append(["--- Extracted AI Data ---", ""])
|
||||||
|
try:
|
||||||
|
data = _json.loads(d.extracted_data) if isinstance(d.extracted_data, str) else d.extracted_data
|
||||||
|
if isinstance(data, dict):
|
||||||
|
for k, v in data.items():
|
||||||
|
val_str = str(v)
|
||||||
|
if isinstance(v, list):
|
||||||
|
val_str = "; ".join(map(str, v))
|
||||||
|
elif isinstance(v, dict):
|
||||||
|
val_str = _json.dumps(v)
|
||||||
|
ws.append([sanitize_val(str(k)), sanitize_val(val_str)])
|
||||||
|
except Exception:
|
||||||
|
ws.append(["Error parsing data", ""])
|
||||||
|
|
||||||
# ── Build workbook ────────────────────────────────────────────────────────
|
ws.column_dimensions['A'].width = 30
|
||||||
wb = Workbook()
|
ws.column_dimensions['B'].width = 60
|
||||||
ws = wb.active
|
|
||||||
ws.title = "Documents"
|
|
||||||
|
|
||||||
# Header style
|
excel_buffer = io.BytesIO()
|
||||||
header_fill = PatternFill(fill_type="solid", fgColor="2C7A5B")
|
wb.save(excel_buffer)
|
||||||
header_font = Font(bold=True, color="FFFFFF", size=11)
|
excel_buffer.seek(0)
|
||||||
center_align = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
|
||||||
thin_border = Border(
|
safe_filename = d.filename.replace("/", "_").replace("\\", "_")
|
||||||
left=Side(style="thin"), right=Side(style="thin"),
|
file_name = f"{prefix}_{d.id}_{safe_filename}.xlsx"
|
||||||
top=Side(style="thin"), bottom=Side(style="thin"),
|
zip_file.writestr(file_name, excel_buffer.read())
|
||||||
|
|
||||||
|
zip_buffer.seek(0)
|
||||||
|
headers = {
|
||||||
|
"Content-Disposition": f'attachment; filename="user_{user_id}_excel_summaries.zip"',
|
||||||
|
"Content-Type": "application/zip",
|
||||||
|
}
|
||||||
|
return StreamingResponse(zip_buffer, headers=headers)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/admin/users/{user_id}/export-zip")
|
||||||
|
def export_user_documents_zip(
|
||||||
|
user_id: int,
|
||||||
|
tax_year: int | None = None,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user=Depends(get_current_user),
|
||||||
|
_=Depends(require_admin),
|
||||||
|
):
|
||||||
|
target_user = db.query(User).filter(User.id == user_id).first()
|
||||||
|
if not target_user:
|
||||||
|
raise HTTPException(status_code=404, detail="Target user not found")
|
||||||
|
|
||||||
|
if current_user.role == UserRole.admin and target_user.role != UserRole.user:
|
||||||
|
raise HTTPException(status_code=403, detail="Admins can only export documents for regular user accounts")
|
||||||
|
|
||||||
|
pq = db.query(PersonalDocument).filter(
|
||||||
|
PersonalDocument.user_id == user_id, PersonalDocument.deleted_at == None
|
||||||
|
)
|
||||||
|
bq = db.query(BusinessDocument).filter(
|
||||||
|
BusinessDocument.user_id == user_id, BusinessDocument.deleted_at == None
|
||||||
|
)
|
||||||
|
aq = db.query(AdminDocument).filter(
|
||||||
|
AdminDocument.user_id == user_id, AdminDocument.deleted_at == None
|
||||||
)
|
)
|
||||||
|
|
||||||
# Write headers
|
if tax_year:
|
||||||
for col_idx, col_name in enumerate(all_cols, 1):
|
pq = pq.filter(PersonalDocument.tax_year == tax_year)
|
||||||
cell = ws.cell(row=1, column=col_idx, value=col_name)
|
bq = bq.filter(BusinessDocument.tax_year == tax_year)
|
||||||
cell.fill = header_fill
|
|
||||||
cell.font = header_font
|
|
||||||
cell.alignment = center_align
|
|
||||||
cell.border = thin_border
|
|
||||||
|
|
||||||
ws.row_dimensions[1].height = 30
|
p_docs = pq.all()
|
||||||
ws.freeze_panes = "A2"
|
b_docs = bq.all()
|
||||||
|
a_docs = aq.all()
|
||||||
|
|
||||||
# Alternate row fill
|
import zipfile
|
||||||
alt_fill = PatternFill(fill_type="solid", fgColor="EAF4EF")
|
import io
|
||||||
|
|
||||||
# Write data
|
zip_buffer = io.BytesIO()
|
||||||
for row_idx, doc in enumerate(all_docs, 2):
|
with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file:
|
||||||
fill = alt_fill if row_idx % 2 == 0 else None
|
for docs, prefix in [(p_docs, "Personal"), (b_docs, "Business"), (a_docs, "Admin")]:
|
||||||
for col_idx, col_name in enumerate(all_cols, 1):
|
for doc in docs:
|
||||||
cell = ws.cell(row=row_idx, column=col_idx, value=doc.get(col_name, ""))
|
if doc.storage_key:
|
||||||
cell.alignment = Alignment(vertical="center", wrap_text=False)
|
s_key = doc.storage_key
|
||||||
cell.border = thin_border
|
if s_key.startswith("uploads/"):
|
||||||
if fill:
|
s_key = s_key.split("uploads/")[1]
|
||||||
cell.fill = fill
|
file_path = UPLOAD_DIR / s_key
|
||||||
|
if file_path.exists():
|
||||||
|
# Make sure filename is safe and unique
|
||||||
|
filename = doc.filename or "document"
|
||||||
|
zip_file.write(file_path, f"{prefix}/{doc.id}_{filename}")
|
||||||
|
|
||||||
# Auto-fit column widths (capped at 40)
|
zip_buffer.seek(0)
|
||||||
for col_idx, col_name in enumerate(all_cols, 1):
|
|
||||||
max_len = max(len(col_name), *(len(str(doc.get(col_name, ""))) for doc in all_docs)) if all_docs else len(col_name)
|
|
||||||
ws.column_dimensions[get_column_letter(col_idx)].width = min(max_len + 3, 40)
|
|
||||||
|
|
||||||
buf = io.BytesIO()
|
filename = f"user_{user_id}_documents_{tax_year if tax_year else 'all'}.zip"
|
||||||
wb.save(buf)
|
|
||||||
buf.seek(0)
|
|
||||||
|
|
||||||
headers = {
|
return StreamingResponse(
|
||||||
"Content-Disposition": f'attachment; filename="user_{user_id}_documents.xlsx"',
|
zip_buffer,
|
||||||
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
media_type="application/zip",
|
||||||
|
headers={"Content-Disposition": f"attachment; filename={filename}"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────
|
||||||
|
# Bookmarks
|
||||||
|
# ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
@router.get("/bookmarks")
|
||||||
|
def get_bookmarks(
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user=Depends(require_admin),
|
||||||
|
):
|
||||||
|
from app.models import AdminDocumentBookmark
|
||||||
|
bookmarks = db.query(AdminDocumentBookmark).filter_by(
|
||||||
|
admin_id=current_user.id
|
||||||
|
).all()
|
||||||
|
return {
|
||||||
|
"bookmarks": [
|
||||||
|
{"doc_kind": b.doc_kind, "doc_id": b.doc_id}
|
||||||
|
for b in bookmarks
|
||||||
|
]
|
||||||
}
|
}
|
||||||
return StreamingResponse(buf, headers=headers)
|
|
||||||
|
|
||||||
|
@router.put("/bookmarks/{doc_kind}/{doc_id}")
|
||||||
|
def add_bookmark(
|
||||||
|
doc_kind: str,
|
||||||
|
doc_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user=Depends(require_admin),
|
||||||
|
):
|
||||||
|
if doc_kind not in ['admin', 'personal', 'business']:
|
||||||
|
raise HTTPException(status_code=400, detail="Invalid doc_kind")
|
||||||
|
|
||||||
|
from app.models import AdminDocumentBookmark
|
||||||
|
existing = db.query(AdminDocumentBookmark).filter_by(
|
||||||
|
admin_id=current_user.id,
|
||||||
|
doc_kind=doc_kind,
|
||||||
|
doc_id=doc_id
|
||||||
|
).first()
|
||||||
|
|
||||||
|
if not existing:
|
||||||
|
bm = AdminDocumentBookmark(
|
||||||
|
admin_id=current_user.id,
|
||||||
|
doc_kind=doc_kind,
|
||||||
|
doc_id=doc_id
|
||||||
|
)
|
||||||
|
db.add(bm)
|
||||||
|
try:
|
||||||
|
db.commit()
|
||||||
|
except IntegrityError:
|
||||||
|
db.rollback()
|
||||||
|
raise HTTPException(status_code=400, detail="Bookmark failed")
|
||||||
|
|
||||||
|
return {"status": "ok", "bookmarked": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/bookmarks/{doc_kind}/{doc_id}")
|
||||||
|
def remove_bookmark(
|
||||||
|
doc_kind: str,
|
||||||
|
doc_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user=Depends(require_admin),
|
||||||
|
):
|
||||||
|
from app.models import AdminDocumentBookmark
|
||||||
|
existing = db.query(AdminDocumentBookmark).filter_by(
|
||||||
|
admin_id=current_user.id,
|
||||||
|
doc_kind=doc_kind,
|
||||||
|
doc_id=doc_id
|
||||||
|
).first()
|
||||||
|
|
||||||
|
if existing:
|
||||||
|
db.delete(existing)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
return {"status": "ok", "bookmarked": False}
|
||||||
|
|||||||
@@ -81,7 +81,69 @@ def upgrade():
|
|||||||
|
|
||||||
# ── v6: AI summary for admin documents ────────────────────────────────
|
# ── v6: AI summary for admin documents ────────────────────────────────
|
||||||
_add_column(conn, "admin_documents", "ai_summary", "TEXT NULL DEFAULT NULL")
|
_add_column(conn, "admin_documents", "ai_summary", "TEXT NULL DEFAULT NULL")
|
||||||
|
# ── v005: Workflow Improvements ─────────────────────────────────────
|
||||||
|
_add_column(conn, "admin_documents", "tax_year", "INT NULL DEFAULT NULL")
|
||||||
|
_add_column(conn, "admin_documents", "review_status", "VARCHAR(20) NOT NULL DEFAULT 'pending'")
|
||||||
|
_add_column(conn, "admin_documents", "review_note", "VARCHAR(500) NULL DEFAULT NULL")
|
||||||
|
_add_column(conn, "admin_documents", "reviewed_at", "DATETIME NULL DEFAULT NULL")
|
||||||
|
|
||||||
|
# Set existing docs to pending
|
||||||
|
conn.execute(text("UPDATE admin_documents SET review_status = 'pending' WHERE review_status IS NULL OR review_status = '';"))
|
||||||
|
|
||||||
|
# Create document_review_events table
|
||||||
|
try:
|
||||||
|
conn.execute(text("""
|
||||||
|
CREATE TABLE IF NOT EXISTS document_review_events (
|
||||||
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
doc_kind VARCHAR(50) NOT NULL,
|
||||||
|
doc_id INT NOT NULL,
|
||||||
|
owner_user_id INT NOT NULL,
|
||||||
|
actor_id INT NULL,
|
||||||
|
actor_role VARCHAR(20) NOT NULL,
|
||||||
|
action VARCHAR(50) NOT NULL,
|
||||||
|
from_status VARCHAR(20) NULL,
|
||||||
|
to_status VARCHAR(20) NULL,
|
||||||
|
tax_year INT NULL,
|
||||||
|
comment TEXT NULL,
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
FOREIGN KEY (owner_user_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
FOREIGN KEY (actor_id) REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
INDEX ix_document_review_events_composite (doc_kind, doc_id, created_at),
|
||||||
|
INDEX ix_document_review_events_owner (owner_user_id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
"""))
|
||||||
|
print(" [OK] Table document_review_events created or exists")
|
||||||
|
except Exception as e:
|
||||||
|
print(f" [WARN] Table document_review_events: {e}")
|
||||||
|
|
||||||
|
# Create admin_document_bookmarks table
|
||||||
|
try:
|
||||||
|
conn.execute(text("""
|
||||||
|
CREATE TABLE IF NOT EXISTS admin_document_bookmarks (
|
||||||
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
admin_id INT NOT NULL,
|
||||||
|
doc_kind VARCHAR(50) NOT NULL,
|
||||||
|
doc_id INT NOT NULL,
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
FOREIGN KEY (admin_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
UNIQUE KEY uq_admin_bookmark (admin_id, doc_kind, doc_id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
"""))
|
||||||
|
print(" [OK] Table admin_document_bookmarks created or exists")
|
||||||
|
except Exception as e:
|
||||||
|
print(f" [WARN] Table admin_document_bookmarks: {e}")
|
||||||
|
|
||||||
|
# Backfill one uploaded event per admin_document
|
||||||
|
try:
|
||||||
|
conn.execute(text("""
|
||||||
|
INSERT INTO document_review_events (doc_kind, doc_id, owner_user_id, actor_id, actor_role, action, from_status, to_status, tax_year, created_at)
|
||||||
|
SELECT 'admin', id, user_id, uploaded_by, 'admin', 'uploaded', NULL, 'pending', tax_year, uploaded_at
|
||||||
|
FROM admin_documents
|
||||||
|
WHERE id NOT IN (SELECT doc_id FROM document_review_events WHERE doc_kind = 'admin' AND action = 'uploaded');
|
||||||
|
"""))
|
||||||
|
print(" [OK] Backfilled uploaded events for admin_documents")
|
||||||
|
except Exception as e:
|
||||||
|
print(f" [WARN] Backfill uploaded events: {e}")
|
||||||
|
|
||||||
print("\nAll migrations complete.")
|
print("\nAll migrations complete.")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
-- v005_workflow_improvements.sql
|
||||||
|
|
||||||
|
ALTER TABLE admin_documents ADD COLUMN tax_year INT NULL DEFAULT NULL;
|
||||||
|
ALTER TABLE admin_documents ADD COLUMN review_status VARCHAR(20) NOT NULL DEFAULT 'pending';
|
||||||
|
ALTER TABLE admin_documents ADD COLUMN review_note VARCHAR(500) NULL DEFAULT NULL;
|
||||||
|
ALTER TABLE admin_documents ADD COLUMN reviewed_at DATETIME NULL DEFAULT NULL;
|
||||||
|
|
||||||
|
UPDATE admin_documents SET review_status = 'pending' WHERE review_status IS NULL OR review_status = '';
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS document_review_events (
|
||||||
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
doc_kind VARCHAR(50) NOT NULL,
|
||||||
|
doc_id INT NOT NULL,
|
||||||
|
owner_user_id INT NOT NULL,
|
||||||
|
actor_id INT NULL,
|
||||||
|
actor_role VARCHAR(20) NOT NULL,
|
||||||
|
action VARCHAR(50) NOT NULL,
|
||||||
|
from_status VARCHAR(20) NULL,
|
||||||
|
to_status VARCHAR(20) NULL,
|
||||||
|
tax_year INT NULL,
|
||||||
|
comment TEXT NULL,
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
FOREIGN KEY (owner_user_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
FOREIGN KEY (actor_id) REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
INDEX ix_document_review_events_composite (doc_kind, doc_id, created_at),
|
||||||
|
INDEX ix_document_review_events_owner (owner_user_id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS admin_document_bookmarks (
|
||||||
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
admin_id INT NOT NULL,
|
||||||
|
doc_kind VARCHAR(50) NOT NULL,
|
||||||
|
doc_id INT NOT NULL,
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
FOREIGN KEY (admin_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
UNIQUE KEY uq_admin_bookmark (admin_id, doc_kind, doc_id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
INSERT INTO document_review_events (doc_kind, doc_id, owner_user_id, actor_id, actor_role, action, from_status, to_status, tax_year, created_at)
|
||||||
|
SELECT 'admin', id, user_id, uploaded_by, 'admin', 'uploaded', NULL, 'pending', tax_year, uploaded_at
|
||||||
|
FROM admin_documents
|
||||||
|
WHERE id NOT IN (SELECT doc_id FROM document_review_events WHERE doc_kind = 'admin' AND action = 'uploaded');
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import os
|
||||||
|
import uuid
|
||||||
|
import datetime
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from app.database import SessionLocal
|
||||||
|
from app.models import User, PersonalDocument, BusinessDocument, UserRole
|
||||||
|
from app.auth.security import get_password_hash
|
||||||
|
|
||||||
|
UPLOAD_DIR = "/app/uploads"
|
||||||
|
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
||||||
|
|
||||||
|
MOCK_USERS = [
|
||||||
|
{"name": "James Smith", "email": "james.smith@example.com"},
|
||||||
|
{"name": "Robert Johnson", "email": "robert.j@example.com"},
|
||||||
|
{"name": "John Williams", "email": "john.williams@example.com"},
|
||||||
|
{"name": "Michael Brown", "email": "michael.brown@example.com"},
|
||||||
|
{"name": "David Jones", "email": "david.jones@example.com"},
|
||||||
|
{"name": "William Garcia", "email": "william.g@example.com"},
|
||||||
|
{"name": "Richard Martinez", "email": "richard.m@example.com"},
|
||||||
|
{"name": "Joseph Davis", "email": "joseph.davis@example.com"},
|
||||||
|
{"name": "Thomas Rodriguez", "email": "thomas.r@example.com"},
|
||||||
|
{"name": "Charles Martinez", "email": "charles.m@example.com"},
|
||||||
|
]
|
||||||
|
|
||||||
|
def generate_pdf(filepath, title, content):
|
||||||
|
minimal_pdf = b"%PDF-1.0\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj 2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj 3 0 obj<</Type/Page/MediaBox[0 0 3 3]>>endobj\nxref\n0 4\n0000000000 65535 f\n0000000010 00000 n\n0000000053 00000 n\n0000000102 00000 n\ntrailer<</Size 4/Root 1 0 R>>\nstartxref\n149\n%EOF\n"
|
||||||
|
with open(filepath, 'wb') as f:
|
||||||
|
f.write(minimal_pdf)
|
||||||
|
|
||||||
|
def seed_data():
|
||||||
|
db: Session = SessionLocal()
|
||||||
|
|
||||||
|
# Create Users
|
||||||
|
for user_data in MOCK_USERS:
|
||||||
|
existing_user = db.query(User).filter(User.email == user_data["email"]).first()
|
||||||
|
if not existing_user:
|
||||||
|
new_user = User(
|
||||||
|
name=user_data["name"],
|
||||||
|
email=user_data["email"],
|
||||||
|
hashed_password=get_password_hash("Password123!"),
|
||||||
|
role=UserRole.user
|
||||||
|
)
|
||||||
|
db.add(new_user)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(new_user)
|
||||||
|
print(f"Created user: {new_user.email}")
|
||||||
|
user_id = new_user.id
|
||||||
|
else:
|
||||||
|
user_id = existing_user.id
|
||||||
|
print(f"User already exists: {existing_user.email}")
|
||||||
|
|
||||||
|
# Add Personal Document
|
||||||
|
p_filename = f"W2_{user_data['name'].replace(' ', '_')}_2024.pdf"
|
||||||
|
p_storage_key = f"{uuid.uuid4()}_{p_filename}"
|
||||||
|
p_filepath = os.path.join(UPLOAD_DIR, p_storage_key)
|
||||||
|
|
||||||
|
generate_pdf(p_filepath, "Form W-2 Wage and Tax Statement", f"Generated for {user_data['name']} (Personal)")
|
||||||
|
|
||||||
|
p_doc = PersonalDocument(
|
||||||
|
user_id=user_id,
|
||||||
|
doc_type="W-2",
|
||||||
|
filename=p_filename,
|
||||||
|
storage_key=p_storage_key,
|
||||||
|
content_type="application/pdf",
|
||||||
|
file_hash=p_storage_key, # dummy hash
|
||||||
|
review_status="pending",
|
||||||
|
tax_year=2024
|
||||||
|
)
|
||||||
|
db.add(p_doc)
|
||||||
|
|
||||||
|
# Add Business Document
|
||||||
|
b_filename = f"1099_{user_data['name'].replace(' ', '_')}_2024.pdf"
|
||||||
|
b_storage_key = f"{uuid.uuid4()}_{b_filename}"
|
||||||
|
b_filepath = os.path.join(UPLOAD_DIR, b_storage_key)
|
||||||
|
|
||||||
|
generate_pdf(b_filepath, "Form 1099 Miscellaneous Income", f"Generated for {user_data['name']} (Business)")
|
||||||
|
|
||||||
|
b_doc = BusinessDocument(
|
||||||
|
user_id=user_id,
|
||||||
|
doc_type="1099",
|
||||||
|
filename=b_filename,
|
||||||
|
storage_key=b_storage_key,
|
||||||
|
content_type="application/pdf",
|
||||||
|
file_hash=b_storage_key, # dummy hash
|
||||||
|
review_status="pending",
|
||||||
|
tax_year=2024
|
||||||
|
)
|
||||||
|
db.add(b_doc)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
print(f"Added personal & business documents for {user_data['name']}")
|
||||||
|
|
||||||
|
db.close()
|
||||||
|
print("Seeding complete.")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
seed_data()
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import sys
|
||||||
|
sys.path.append(r'c:\Users\abhil\Desktop\Bookkeepro-redesigned\Bookkeep\services\api')
|
||||||
|
from app.db import SessionLocal
|
||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
db = SessionLocal()
|
||||||
|
db.execute(text("UPDATE personal_documents SET review_status = 'pending' WHERE review_status = 'draft'"))
|
||||||
|
db.execute(text("UPDATE business_documents SET review_status = 'pending' WHERE review_status = 'draft'"))
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
from app.models import DocumentReviewEvent, PersonalDocument, BusinessDocument
|
||||||
|
|
||||||
|
# Also append uploaded events
|
||||||
|
for doc in db.query(PersonalDocument).all():
|
||||||
|
if not db.query(DocumentReviewEvent).filter_by(doc_kind='personal', doc_id=doc.id, action='uploaded').first():
|
||||||
|
db.add(DocumentReviewEvent(doc_kind='personal', doc_id=doc.id, owner_user_id=doc.user_id, actor_id=doc.user_id, actor_role='user', action='uploaded', to_status='pending', tax_year=doc.tax_year, created_at=doc.uploaded_at))
|
||||||
|
|
||||||
|
for doc in db.query(BusinessDocument).all():
|
||||||
|
if not db.query(DocumentReviewEvent).filter_by(doc_kind='business', doc_id=doc.id, action='uploaded').first():
|
||||||
|
db.add(DocumentReviewEvent(doc_kind='business', doc_id=doc.id, owner_user_id=doc.user_id, actor_id=doc.user_id, actor_role='user', action='uploaded', to_status='pending', tax_year=doc.tax_year, created_at=doc.uploaded_at))
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
print('Done updating db')
|
||||||
Reference in New Issue
Block a user