feat: add super admin user assignment, scoping, and clean email notifications
This commit is contained in:
@@ -6,7 +6,8 @@ import { useToast } from '../context/ToastContext';
|
|||||||
import ConfirmModal from '../components/ConfirmModal';
|
import ConfirmModal from '../components/ConfirmModal';
|
||||||
|
|
||||||
export default function AdminDashboard() {
|
export default function AdminDashboard() {
|
||||||
const { authFetch } = useAuth();
|
const { authFetch, user: currentUser } = useAuth();
|
||||||
|
const isSuperAdmin = currentUser?.role === 'super_admin';
|
||||||
const { showToast } = useToast();
|
const { showToast } = useToast();
|
||||||
const [confirmConfig, setConfirmConfig] = useState({
|
const [confirmConfig, setConfirmConfig] = useState({
|
||||||
isOpen: false, title: "", message: "", confirmText: "OK", isDestructive: false, onConfirm: () => {}
|
isOpen: false, title: "", message: "", confirmText: "OK", isDestructive: false, onConfirm: () => {}
|
||||||
@@ -19,10 +20,55 @@ export default function AdminDashboard() {
|
|||||||
const [userFilter, setUserFilter] = useState("all");
|
const [userFilter, setUserFilter] = useState("all");
|
||||||
const [userSort, setUserSort] = useState("newest");
|
const [userSort, setUserSort] = useState("newest");
|
||||||
const [filterYear, setFilterYear] = useState(new Date().getFullYear().toString());
|
const [filterYear, setFilterYear] = useState(new Date().getFullYear().toString());
|
||||||
|
const [adminAssignmentFilter, setAdminAssignmentFilter] = useState("all");
|
||||||
|
const [staffList, setStaffList] = useState([]);
|
||||||
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();
|
||||||
|
|
||||||
|
// --- Staff List Fetch ---
|
||||||
|
const fetchStaff = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const res = await authFetch('/api/auth/admin/staff');
|
||||||
|
if (res.ok) {
|
||||||
|
setStaffList(await res.json());
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Failed to load staff list", err);
|
||||||
|
}
|
||||||
|
}, [authFetch]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchStaff();
|
||||||
|
}, [fetchStaff]);
|
||||||
|
|
||||||
|
const handleAssignAdmin = async (userId, newAdminId) => {
|
||||||
|
try {
|
||||||
|
const res = await authFetch(`/api/auth/admin/users/${userId}/assign-admin`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ admin_id: newAdminId ? parseInt(newAdminId, 10) : null }),
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
const data = await res.json();
|
||||||
|
showToast(data.message || "Admin assigned", "success");
|
||||||
|
setUsers(prev => prev.map(u => u.id === userId ? {
|
||||||
|
...u,
|
||||||
|
assigned_admin_id: data.assigned_admin_id,
|
||||||
|
assigned_admin_name: data.assigned_admin_name,
|
||||||
|
assigned_admin_email: data.assigned_admin_email,
|
||||||
|
} : u));
|
||||||
|
fetchStaff();
|
||||||
|
} else {
|
||||||
|
const err = await res.json();
|
||||||
|
showToast(err.detail || "Failed to assign admin", "error");
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
showToast("Network error while assigning admin", "error");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// --- Template Management State ---
|
// --- Template Management State ---
|
||||||
const [tplCategory, setTplCategory] = useState("personal");
|
const [tplCategory, setTplCategory] = useState("personal");
|
||||||
const [tplYear, setTplYear] = useState(new Date().getFullYear().toString());
|
const [tplYear, setTplYear] = useState(new Date().getFullYear().toString());
|
||||||
@@ -41,16 +87,35 @@ export default function AdminDashboard() {
|
|||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
setDigestHtml(data.digest);
|
setDigestHtml(data.digest);
|
||||||
|
showToast("Daily digest generated successfully!", "success");
|
||||||
|
} else {
|
||||||
|
const err = await res.json().catch(() => ({}));
|
||||||
|
showToast(err.detail || "Failed to generate daily digest", "error");
|
||||||
}
|
}
|
||||||
} catch (err) { console.error(err); }
|
} catch (err) {
|
||||||
finally { setDigestLoading(false); }
|
console.error(err);
|
||||||
}, [authFetch]);
|
showToast("Network error while generating digest", "error");
|
||||||
|
} finally {
|
||||||
|
setDigestLoading(false);
|
||||||
|
}
|
||||||
|
}, [authFetch, showToast]);
|
||||||
|
|
||||||
const fetchAdminData = useCallback(async () => {
|
const fetchAdminData = useCallback(async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
|
let usersUrl = `/api/auth/admin/users?tax_year=${filterYear}`;
|
||||||
|
if (isSuperAdmin) {
|
||||||
|
if (adminAssignmentFilter !== "all") {
|
||||||
|
usersUrl += `&assigned_admin_id=${adminAssignmentFilter}`;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (adminAssignmentFilter === "unassigned") {
|
||||||
|
usersUrl += `&assigned_admin_id=unassigned`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const [usersRes, statsRes, bookmarksRes] = await Promise.all([
|
const [usersRes, statsRes, bookmarksRes] = await Promise.all([
|
||||||
authFetch(`/api/auth/admin/users?tax_year=${filterYear}`),
|
authFetch(usersUrl),
|
||||||
authFetch(`/api/chatbot/admin-status?tax_year=${filterYear}`),
|
authFetch(`/api/chatbot/admin-status?tax_year=${filterYear}`),
|
||||||
authFetch(`/api/upload/bookmarks`)
|
authFetch(`/api/upload/bookmarks`)
|
||||||
]);
|
]);
|
||||||
@@ -90,7 +155,7 @@ export default function AdminDashboard() {
|
|||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}, [authFetch, filterYear]);
|
}, [authFetch, filterYear, adminAssignmentFilter, isSuperAdmin]);
|
||||||
|
|
||||||
const loadTemplates = useCallback(async () => {
|
const loadTemplates = useCallback(async () => {
|
||||||
setTplLoading(true);
|
setTplLoading(true);
|
||||||
@@ -219,8 +284,8 @@ export default function AdminDashboard() {
|
|||||||
</h1>
|
</h1>
|
||||||
<div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '24px', flexWrap: 'wrap', gap: '16px' }}>
|
<div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '24px', flexWrap: 'wrap', gap: '16px' }}>
|
||||||
{tab === 'users' && (
|
{tab === 'users' && (
|
||||||
<div style={{ display: 'flex', gap: '12px', width: '100%', maxWidth: '500px', flexWrap: 'wrap' }}>
|
<div style={{ display: 'flex', gap: '12px', width: '100%', maxWidth: '820px', flexWrap: 'wrap' }}>
|
||||||
<div className="search-wrap" style={{ flex: 1, minWidth: '200px', position: 'relative' }}>
|
<div className="search-wrap" style={{ flex: 1, minWidth: '180px', position: 'relative' }}>
|
||||||
<span className="material-symbols-outlined search-icon" style={{position: 'absolute', left: '12px', top: '50%', transform: 'translateY(-50%)', color: 'var(--muted)', fontSize: '20px'}}>search</span>
|
<span className="material-symbols-outlined search-icon" style={{position: 'absolute', left: '12px', top: '50%', transform: 'translateY(-50%)', color: 'var(--muted)', fontSize: '20px'}}>search</span>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
@@ -231,6 +296,38 @@ export default function AdminDashboard() {
|
|||||||
onChange={(e) => setSearch(e.target.value)}
|
onChange={(e) => setSearch(e.target.value)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Admin Assignment Filter */}
|
||||||
|
{isSuperAdmin ? (
|
||||||
|
<select
|
||||||
|
className="select-input"
|
||||||
|
style={{ width: 'auto', padding: '10px 16px', borderRadius: 'var(--radius-pill)', border: '1px solid var(--border)', outline: 'none', background: 'white' }}
|
||||||
|
value={adminAssignmentFilter}
|
||||||
|
onChange={(e) => setAdminAssignmentFilter(e.target.value)}
|
||||||
|
title="Filter by assigned administrator"
|
||||||
|
>
|
||||||
|
<option value="all">👥 All Administrators</option>
|
||||||
|
<option value="unassigned">⚠️ Unassigned Clients</option>
|
||||||
|
<optgroup label="Staff Admins">
|
||||||
|
{staffList.map(s => (
|
||||||
|
<option key={s.id} value={s.id}>
|
||||||
|
{s.name || s.email} ({s.assigned_clients_count || 0} clients)
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</optgroup>
|
||||||
|
</select>
|
||||||
|
) : (
|
||||||
|
<select
|
||||||
|
className="select-input"
|
||||||
|
style={{ width: 'auto', padding: '10px 16px', borderRadius: 'var(--radius-pill)', border: '1px solid var(--border)', outline: 'none', background: 'white' }}
|
||||||
|
value={adminAssignmentFilter}
|
||||||
|
onChange={(e) => setAdminAssignmentFilter(e.target.value)}
|
||||||
|
>
|
||||||
|
<option value="all">My Assigned Clients</option>
|
||||||
|
<option value="unassigned">Unassigned Clients</option>
|
||||||
|
</select>
|
||||||
|
)}
|
||||||
|
|
||||||
<select
|
<select
|
||||||
className="select-input"
|
className="select-input"
|
||||||
style={{ width: 'auto', padding: '10px 16px', borderRadius: 'var(--radius-pill)', border: '1px solid var(--border)', outline: 'none', background: 'white' }}
|
style={{ width: 'auto', padding: '10px 16px', borderRadius: 'var(--radius-pill)', border: '1px solid var(--border)', outline: 'none', background: 'white' }}
|
||||||
@@ -384,7 +481,8 @@ export default function AdminDashboard() {
|
|||||||
<div className="u-email">{u.email || "—"}</div>
|
<div className="u-email">{u.email || "—"}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="user-bottom">
|
<div className="user-bottom" style={{ display: 'flex', flexDirection: 'column', gap: '8px', alignItems: 'stretch' }}>
|
||||||
|
<div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap', alignItems: 'center' }}>
|
||||||
<span className={`badge role-badge ${u.role === 'super_admin' ? 'badge-red' : u.role === 'admin' ? 'badge-orange' : 'badge-blue'}`}>
|
<span className={`badge role-badge ${u.role === 'super_admin' ? 'badge-red' : u.role === 'admin' ? 'badge-orange' : 'badge-blue'}`}>
|
||||||
{u.role}
|
{u.role}
|
||||||
</span>
|
</span>
|
||||||
@@ -401,7 +499,49 @@ export default function AdminDashboard() {
|
|||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="click-layer"></div>
|
|
||||||
|
{u.role === 'user' && (
|
||||||
|
<div style={{ paddingTop: '8px', borderTop: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '8px', fontSize: '12px' }}>
|
||||||
|
<span style={{ color: u.assigned_admin_name ? 'var(--navy)' : 'var(--orange)', display: 'inline-flex', alignItems: 'center', gap: '4px', fontWeight: 500 }}>
|
||||||
|
<span className="material-symbols-outlined" style={{ fontSize: '15px', color: u.assigned_admin_name ? 'var(--blue)' : 'var(--orange)' }}>
|
||||||
|
{u.assigned_admin_name ? 'assignment_ind' : 'person_alert'}
|
||||||
|
</span>
|
||||||
|
{u.assigned_admin_name ? u.assigned_admin_name : 'Unassigned'}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
{isSuperAdmin && (
|
||||||
|
<select
|
||||||
|
className="select-input"
|
||||||
|
style={{
|
||||||
|
padding: '2px 8px',
|
||||||
|
fontSize: '11px',
|
||||||
|
borderRadius: 'var(--radius-sm)',
|
||||||
|
background: 'white',
|
||||||
|
border: '1px solid var(--border)',
|
||||||
|
cursor: 'pointer',
|
||||||
|
maxWidth: '135px',
|
||||||
|
position: 'relative',
|
||||||
|
zIndex: 5
|
||||||
|
}}
|
||||||
|
value={u.assigned_admin_id || ""}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
onChange={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
handleAssignAdmin(u.id, e.target.value);
|
||||||
|
}}
|
||||||
|
title="Assign client to admin"
|
||||||
|
>
|
||||||
|
<option value="">-- Unassigned --</option>
|
||||||
|
{staffList.map(s => (
|
||||||
|
<option key={s.id} value={s.id}>
|
||||||
|
{s.name || s.email}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))
|
))
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -51,9 +51,45 @@ export default function AdminUserDetail() {
|
|||||||
const [auditLog, setAuditLog] = useState([]);
|
const [auditLog, setAuditLog] = useState([]);
|
||||||
const [auditLoaded, setAuditLoaded] = useState(false);
|
const [auditLoaded, setAuditLoaded] = useState(false);
|
||||||
const [deadlines, setDeadlines] = useState([]);
|
const [deadlines, setDeadlines] = useState([]);
|
||||||
|
const [staffList, setStaffList] = useState([]);
|
||||||
|
|
||||||
const adminDocInputRef = useRef(null);
|
const adminDocInputRef = useRef(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (currentUser?.role === 'super_admin') {
|
||||||
|
authFetch('/api/auth/admin/staff')
|
||||||
|
.then(res => res.ok ? res.json() : [])
|
||||||
|
.then(data => setStaffList(data))
|
||||||
|
.catch(err => console.error("Failed to load staff list", err));
|
||||||
|
}
|
||||||
|
}, [authFetch, currentUser]);
|
||||||
|
|
||||||
|
const handleAssignAdmin = async (newAdminId) => {
|
||||||
|
try {
|
||||||
|
const res = await authFetch(`/api/auth/admin/users/${userId}/assign-admin`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ admin_id: newAdminId ? parseInt(newAdminId, 10) : null }),
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
const data = await res.json();
|
||||||
|
showToast(data.message || "Admin assignment updated", "success");
|
||||||
|
setUserDetail(prev => ({
|
||||||
|
...prev,
|
||||||
|
assigned_admin_id: data.assigned_admin_id,
|
||||||
|
assigned_admin_name: data.assigned_admin_name,
|
||||||
|
assigned_admin_email: data.assigned_admin_email,
|
||||||
|
}));
|
||||||
|
} else {
|
||||||
|
const err = await res.json();
|
||||||
|
showToast(err.detail || "Failed to assign admin", "error");
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
showToast("Network error while assigning admin", "error");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const fetchUserDetails = useCallback(async () => {
|
const fetchUserDetails = useCallback(async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
@@ -61,7 +97,11 @@ export default function AdminUserDetail() {
|
|||||||
const res = await authFetch(url);
|
const res = await authFetch(url);
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
if (res.status === 403) navigate('/admin-dashboard');
|
if (res.status === 403) {
|
||||||
|
const errData = await res.json().catch(() => ({}));
|
||||||
|
showToast(errData.detail || "Access denied. You are not assigned to handle this user.", "error");
|
||||||
|
navigate('/admin-dashboard');
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -519,7 +559,7 @@ export default function AdminUserDetail() {
|
|||||||
<div>
|
<div>
|
||||||
<h1 style={{fontWeight: 700, fontSize: "18px", color: "var(--navy)", margin: 0}}>{userDetail.name || "?"}</h1>
|
<h1 style={{fontWeight: 700, fontSize: "18px", color: "var(--navy)", margin: 0}}>{userDetail.name || "?"}</h1>
|
||||||
<div style={{fontSize:'13px', color:'var(--muted)', marginTop:'2px'}}>{userDetail.email}</div>
|
<div style={{fontSize:'13px', color:'var(--muted)', marginTop:'2px'}}>{userDetail.email}</div>
|
||||||
<div style={{display:'flex', gap:'8px', marginTop:'6px', flexWrap:'wrap'}}>
|
<div style={{display:'flex', gap:'8px', marginTop:'6px', flexWrap:'wrap', alignItems:'center'}}>
|
||||||
{currentUser?.role === 'super_admin' && currentUser.id !== userDetail.id ? (
|
{currentUser?.role === 'super_admin' && currentUser.id !== userDetail.id ? (
|
||||||
<select
|
<select
|
||||||
className="select-input"
|
className="select-input"
|
||||||
@@ -534,6 +574,34 @@ export default function AdminUserDetail() {
|
|||||||
) : (
|
) : (
|
||||||
<span className={`badge ${userDetail.role === 'super_admin' ? 'badge-red' : userDetail.role === 'admin' ? 'badge-orange' : 'badge-blue'}`}>{userDetail.role}</span>
|
<span className={`badge ${userDetail.role === 'super_admin' ? 'badge-red' : userDetail.role === 'admin' ? 'badge-orange' : 'badge-blue'}`}>{userDetail.role}</span>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Assigned Admin Selector for Super Admin or Badge for Standard Admin */}
|
||||||
|
{userDetail.role === 'user' && (
|
||||||
|
currentUser?.role === 'super_admin' ? (
|
||||||
|
<div style={{ display: 'inline-flex', alignItems: 'center', gap: '6px' }}>
|
||||||
|
<span style={{ fontSize: '12px', color: 'var(--muted)', fontWeight: 600 }}>Assigned Admin:</span>
|
||||||
|
<select
|
||||||
|
className="select-input"
|
||||||
|
style={{ padding: '2px 8px', fontSize: '12px', height: 'auto', borderRadius: 'var(--radius-pill)', background: 'white', border: '1px solid var(--border)' }}
|
||||||
|
value={userDetail.assigned_admin_id || ""}
|
||||||
|
onChange={(e) => handleAssignAdmin(e.target.value)}
|
||||||
|
>
|
||||||
|
<option value="">-- Unassigned --</option>
|
||||||
|
{staffList.map(s => (
|
||||||
|
<option key={s.id} value={s.id}>
|
||||||
|
{s.name || s.email} ({s.role})
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<span className={`badge ${userDetail.assigned_admin_id === currentUser?.id ? 'badge-green' : 'badge-gray'}`} style={{ display: 'inline-flex', alignItems: 'center', gap: '4px' }}>
|
||||||
|
<span className="material-symbols-outlined" style={{ fontSize: '14px' }}>assignment_ind</span>
|
||||||
|
{userDetail.assigned_admin_id === currentUser?.id ? 'Assigned to You' : (userDetail.assigned_admin_name ? `Assigned to: ${userDetail.assigned_admin_name}` : 'Unassigned')}
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
)}
|
||||||
|
|
||||||
{!userDetail.engagement_acknowledged_at && (
|
{!userDetail.engagement_acknowledged_at && (
|
||||||
<span className="badge badge-yellow"><span className="material-symbols-outlined" style={{fontSize: '14px'}}>pending</span> Engagement not acknowledged</span>
|
<span className="badge badge-yellow"><span className="material-symbols-outlined" style={{fontSize: '14px'}}>pending</span> Engagement not acknowledged</span>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -9,7 +9,17 @@ from sqlalchemy.orm import Session
|
|||||||
|
|
||||||
from app.db import get_db
|
from app.db import get_db
|
||||||
import app.crud as crud
|
import app.crud as crud
|
||||||
from app.schemas import SignupRequest, LoginRequest, TokenResponse, ForgotPasswordRequest, ResetPasswordRequest, ResendVerificationRequest, RoleChangeRequest
|
from app.schemas import (
|
||||||
|
SignupRequest,
|
||||||
|
LoginRequest,
|
||||||
|
TokenResponse,
|
||||||
|
ForgotPasswordRequest,
|
||||||
|
ResetPasswordRequest,
|
||||||
|
ResendVerificationRequest,
|
||||||
|
RoleChangeRequest,
|
||||||
|
AssignAdminRequest,
|
||||||
|
BulkAssignAdminRequest,
|
||||||
|
)
|
||||||
from app.models import UserRole, User as UserModel, PersonalDocument, BusinessDocument
|
from app.models import UserRole, User as UserModel, PersonalDocument, BusinessDocument
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -107,12 +117,12 @@ async def forgot_password(
|
|||||||
f'text-decoration:none;border-radius:6px;">'
|
f'text-decoration:none;border-radius:6px;">'
|
||||||
f"Reset Password</a><br><br>"
|
f"Reset Password</a><br><br>"
|
||||||
f"This link expires in 15 minutes.<br><br>"
|
f"This link expires in 15 minutes.<br><br>"
|
||||||
f"BookKeepro Team"
|
f"Support Team"
|
||||||
)
|
)
|
||||||
background.add_task(
|
background.add_task(
|
||||||
send_email,
|
send_email,
|
||||||
to=user.email,
|
to=user.email,
|
||||||
subject="Reset your BookKeepro password",
|
subject="Reset your password",
|
||||||
body=reset_body,
|
body=reset_body,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -217,7 +227,8 @@ def assert_admin_can_access(current_user, target_user):
|
|||||||
Enforces that:
|
Enforces that:
|
||||||
1. The current user is actually an admin/super_admin.
|
1. The current user is actually an admin/super_admin.
|
||||||
2. The target user exists (throws 404).
|
2. The target user exists (throws 404).
|
||||||
3. The target user has a 'user' role (throws 403).
|
3. The target user has a 'user' role (throws 403) unless current_user is super_admin.
|
||||||
|
4. If current_user is a standard admin, the target user must not be assigned to another admin.
|
||||||
"""
|
"""
|
||||||
if not target_user:
|
if not target_user:
|
||||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||||||
@@ -225,13 +236,24 @@ def assert_admin_can_access(current_user, target_user):
|
|||||||
if current_user.role not in [UserRole.admin, UserRole.super_admin]:
|
if current_user.role not in [UserRole.admin, UserRole.super_admin]:
|
||||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin access required")
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin access required")
|
||||||
|
|
||||||
# Admins can only view 'user' accounts. Super admins can view any account.
|
# Super admins can view and manage any account
|
||||||
if current_user.role != UserRole.super_admin and target_user.role != UserRole.user:
|
if current_user.role == UserRole.super_admin:
|
||||||
|
return
|
||||||
|
|
||||||
|
# Admins can only view 'user' accounts
|
||||||
|
if target_user.role != UserRole.user:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_403_FORBIDDEN,
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
detail="Admins can only interact with regular user accounts"
|
detail="Admins can only interact with regular user accounts"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Standard admin: verify client assignment
|
||||||
|
if target_user.assigned_admin_id is not None and target_user.assigned_admin_id != current_user.id:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="This client is assigned to another administrator"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# =========================
|
# =========================
|
||||||
# Auth Routes
|
# Auth Routes
|
||||||
@@ -271,18 +293,18 @@ async def signup(request: Request, payload: SignupRequest, background: Backgroun
|
|||||||
verify_link = f"{frontend_url}/verify-email?token={verify_token}"
|
verify_link = f"{frontend_url}/verify-email?token={verify_token}"
|
||||||
verify_body = (
|
verify_body = (
|
||||||
f"Hi {user.name},<br><br>"
|
f"Hi {user.name},<br><br>"
|
||||||
f"Welcome to BookKeepro! Please verify your email address to activate your account.<br><br>"
|
f"Welcome! Please verify your email address to activate your account.<br><br>"
|
||||||
f'<a href="{verify_link}" '
|
f'<a href="{verify_link}" '
|
||||||
f'style="padding:12px 24px;background:#FF7F11;color:#fff;'
|
f'style="padding:12px 24px;background:#FF7F11;color:#fff;'
|
||||||
f'text-decoration:none;border-radius:6px;font-weight:600;">'
|
f'text-decoration:none;border-radius:6px;font-weight:600;">'
|
||||||
f"Verify My Email</a><br><br>"
|
f"Verify My Email</a><br><br>"
|
||||||
f"This link expires in 24 hours. If you did not sign up, ignore this email.<br><br>"
|
f"This link expires in 24 hours. If you did not sign up, ignore this email.<br><br>"
|
||||||
f"BookKeepro Team"
|
f"Support Team"
|
||||||
)
|
)
|
||||||
background.add_task(
|
background.add_task(
|
||||||
send_email,
|
send_email,
|
||||||
to=user.email,
|
to=user.email,
|
||||||
subject="Verify your BookKeepro email",
|
subject="Verify your email",
|
||||||
body=verify_body,
|
body=verify_body,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -387,12 +409,12 @@ async def resend_verification(
|
|||||||
f'text-decoration:none;border-radius:6px;font-weight:600;">'
|
f'text-decoration:none;border-radius:6px;font-weight:600;">'
|
||||||
f"Verify My Email</a><br><br>"
|
f"Verify My Email</a><br><br>"
|
||||||
f"This link expires in 24 hours.<br><br>"
|
f"This link expires in 24 hours.<br><br>"
|
||||||
f"BookKeepro Team"
|
f"Support Team"
|
||||||
)
|
)
|
||||||
background.add_task(
|
background.add_task(
|
||||||
send_email,
|
send_email,
|
||||||
to=user.email,
|
to=user.email,
|
||||||
subject="Verify your BookKeepro email",
|
subject="Verify your email",
|
||||||
body=resend_body,
|
body=resend_body,
|
||||||
)
|
)
|
||||||
return {"message": "If the email exists and is unverified, a new link has been sent"}
|
return {"message": "If the email exists and is unverified, a new link has been sent"}
|
||||||
@@ -499,17 +521,18 @@ 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),
|
tax_year: int = Query(None),
|
||||||
|
assigned_admin_id: str | 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),
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
List users:
|
List users:
|
||||||
- super_admin → sees all users (user + admin + super_admin)
|
- super_admin → sees all users (user + admin + super_admin) and can filter by assigned_admin_id ("all", "unassigned", or specific admin id)
|
||||||
- admin → sees only role=user accounts
|
- admin → sees their assigned user accounts (assigned_admin_id == current_user.id) or can view unassigned accounts
|
||||||
Supports skip/limit pagination. Returns pending_docs count per user.
|
Supports skip/limit pagination. Returns pending_docs count per user and assigned admin info.
|
||||||
"""
|
"""
|
||||||
from sqlalchemy import func as sqlfunc
|
from sqlalchemy import func as sqlfunc, or_
|
||||||
|
|
||||||
def _pending_count(uid: int) -> dict:
|
def _pending_count(uid: int) -> dict:
|
||||||
p_q = db.query(sqlfunc.count(PersonalDocument.id)).filter(
|
p_q = db.query(sqlfunc.count(PersonalDocument.id)).filter(
|
||||||
@@ -532,8 +555,28 @@ def list_users_for_admin(
|
|||||||
|
|
||||||
if current_user.role == UserRole.super_admin:
|
if current_user.role == UserRole.super_admin:
|
||||||
q = db.query(UserModel)
|
q = db.query(UserModel)
|
||||||
|
if assigned_admin_id == "unassigned":
|
||||||
|
q = q.filter(UserModel.assigned_admin_id == None, UserModel.role == UserRole.user)
|
||||||
|
elif assigned_admin_id and assigned_admin_id != "all":
|
||||||
|
try:
|
||||||
|
aid = int(assigned_admin_id)
|
||||||
|
q = q.filter(UserModel.assigned_admin_id == aid)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
else:
|
else:
|
||||||
q = db.query(UserModel).filter(UserModel.role == UserRole.user)
|
# Standard admin:
|
||||||
|
# By default (or assigned_admin_id == "me"), show clients assigned to this admin.
|
||||||
|
# If assigned_admin_id == "unassigned", show unassigned clients.
|
||||||
|
# If assigned_admin_id == "all", show clients assigned to this admin + unassigned clients.
|
||||||
|
if assigned_admin_id == "unassigned":
|
||||||
|
q = db.query(UserModel).filter(UserModel.role == UserRole.user, UserModel.assigned_admin_id == None)
|
||||||
|
elif assigned_admin_id == "all":
|
||||||
|
q = db.query(UserModel).filter(
|
||||||
|
UserModel.role == UserRole.user,
|
||||||
|
or_(UserModel.assigned_admin_id == current_user.id, UserModel.assigned_admin_id == None)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
q = db.query(UserModel).filter(UserModel.role == UserRole.user, UserModel.assigned_admin_id == current_user.id)
|
||||||
|
|
||||||
total = q.count()
|
total = q.count()
|
||||||
users = q.offset(skip).limit(limit).all()
|
users = q.offset(skip).limit(limit).all()
|
||||||
@@ -546,6 +589,9 @@ def list_users_for_admin(
|
|||||||
"email": u.email,
|
"email": u.email,
|
||||||
"phone": u.phone,
|
"phone": u.phone,
|
||||||
"role": u.role.value if hasattr(u.role, "value") else str(u.role),
|
"role": u.role.value if hasattr(u.role, "value") else str(u.role),
|
||||||
|
"assigned_admin_id": u.assigned_admin_id,
|
||||||
|
"assigned_admin_name": u.assigned_admin.name if u.assigned_admin else None,
|
||||||
|
"assigned_admin_email": u.assigned_admin.email if u.assigned_admin else None,
|
||||||
**_pending_count(u.id), # inlines pending_personal, pending_business, pending_docs (total)
|
**_pending_count(u.id), # inlines pending_personal, pending_business, pending_docs (total)
|
||||||
}
|
}
|
||||||
for u in users
|
for u in users
|
||||||
@@ -685,3 +731,242 @@ def change_user_role(
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────
|
||||||
|
# Admin assignment management
|
||||||
|
# ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
@router.get("/admin/staff")
|
||||||
|
def list_admin_staff(
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user=Depends(get_current_user),
|
||||||
|
_=Depends(require_admin),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Returns list of staff administrators (admin and super_admin) with count of assigned clients.
|
||||||
|
Accessible to admins and super_admins.
|
||||||
|
"""
|
||||||
|
from sqlalchemy import func as sqlfunc
|
||||||
|
staff = (
|
||||||
|
db.query(UserModel)
|
||||||
|
.filter(UserModel.role.in_([UserRole.admin, UserRole.super_admin]))
|
||||||
|
.order_by(UserModel.name.asc(), UserModel.email.asc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
|
||||||
|
counts = dict(
|
||||||
|
db.query(UserModel.assigned_admin_id, sqlfunc.count(UserModel.id))
|
||||||
|
.filter(UserModel.assigned_admin_id != None)
|
||||||
|
.group_by(UserModel.assigned_admin_id)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"id": s.id,
|
||||||
|
"name": s.name or s.email,
|
||||||
|
"email": s.email,
|
||||||
|
"role": s.role.value if hasattr(s.role, "value") else str(s.role),
|
||||||
|
"assigned_clients_count": counts.get(s.id, 0),
|
||||||
|
}
|
||||||
|
for s in staff
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/admin/users/{user_id}/assign-admin")
|
||||||
|
def assign_user_to_admin(
|
||||||
|
user_id: int,
|
||||||
|
payload: AssignAdminRequest,
|
||||||
|
request: Request,
|
||||||
|
background: BackgroundTasks,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user=Depends(get_current_user),
|
||||||
|
_=Depends(require_super_admin),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Assign or unassign a client user to an administrator. Super admin only.
|
||||||
|
Sends an email notification to the assigned admin.
|
||||||
|
"""
|
||||||
|
client = crud.get_user_by_id(db, user_id)
|
||||||
|
if not client:
|
||||||
|
raise HTTPException(status_code=404, detail="Client user not found")
|
||||||
|
|
||||||
|
old_admin_id = client.assigned_admin_id
|
||||||
|
old_admin = crud.get_user_by_id(db, old_admin_id) if old_admin_id else None
|
||||||
|
old_admin_name = f"{old_admin.name or old_admin.email} (#{old_admin.id})" if old_admin else "Unassigned"
|
||||||
|
|
||||||
|
if payload.admin_id is None or payload.admin_id == 0:
|
||||||
|
# Unassign
|
||||||
|
client.assigned_admin_id = None
|
||||||
|
new_admin = None
|
||||||
|
new_admin_name = "Unassigned"
|
||||||
|
else:
|
||||||
|
new_admin = crud.get_user_by_id(db, payload.admin_id)
|
||||||
|
if not new_admin:
|
||||||
|
raise HTTPException(status_code=404, detail="Target admin not found")
|
||||||
|
if new_admin.role not in [UserRole.admin, UserRole.super_admin]:
|
||||||
|
raise HTTPException(status_code=400, detail="Assigned user must have an admin role")
|
||||||
|
client.assigned_admin_id = new_admin.id
|
||||||
|
new_admin_name = f"{new_admin.name or new_admin.email} (#{new_admin.id})"
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
db.refresh(client)
|
||||||
|
|
||||||
|
crud.log_action(
|
||||||
|
db,
|
||||||
|
action="assign_admin",
|
||||||
|
user_id=current_user.id,
|
||||||
|
target=f"user:{client.id}",
|
||||||
|
detail=f"Assigned admin changed: {old_admin_name} → {new_admin_name}",
|
||||||
|
ip_address=request.client.host if request.client else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
f"Super admin {current_user.email} assigned client {client.email} to {new_admin_name}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Send email notification to the assigned admin
|
||||||
|
if new_admin:
|
||||||
|
frontend_url = os.getenv("FRONTEND_URL", "https://aicpa.duckdns.org")
|
||||||
|
client_link = f"{frontend_url}/admin-user-detail?user_id={client.id}"
|
||||||
|
super_admin_name = current_user.name or current_user.email
|
||||||
|
client_display = client.name or client.email
|
||||||
|
phone_html = f"<p style='margin:4px 0;'><strong>Phone:</strong> {client.phone}</p>" if client.phone else ""
|
||||||
|
|
||||||
|
email_body = f"""
|
||||||
|
<div style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;line-height:1.6;color:#1e293b;max-width:580px;margin:0 auto;border:1px solid #e2e8f0;border-radius:12px;overflow:hidden;box-shadow:0 4px 12px rgba(0,0,0,0.05);">
|
||||||
|
<div style="background-color:#0f172a;padding:24px 28px;text-align:left;">
|
||||||
|
<h2 style="color:#ffffff;margin:0;font-size:20px;font-weight:700;letter-spacing:-0.3px;">Admin Portal</h2>
|
||||||
|
<p style="color:#94a3b8;margin:6px 0 0 0;font-size:13px;">Client Portfolio Assignment Notification</p>
|
||||||
|
</div>
|
||||||
|
<div style="padding:28px;">
|
||||||
|
<p style="font-size:15px;margin-top:0;">Hello <strong>{new_admin.name or 'Admin'}</strong>,</p>
|
||||||
|
<p style="font-size:14px;color:#334155;">Super Admin <strong>{super_admin_name}</strong> has assigned a client to your portfolio:</p>
|
||||||
|
<div style="background-color:#f8fafc;border-left:4px solid #0284c7;padding:16px;margin:20px 0;border-radius:6px;font-size:14px;">
|
||||||
|
<p style="margin:4px 0;"><strong>Client Name:</strong> {client_display}</p>
|
||||||
|
<p style="margin:4px 0;"><strong>Client Email:</strong> {client.email}</p>
|
||||||
|
{phone_html}
|
||||||
|
</div>
|
||||||
|
<p style="font-size:14px;color:#475569;">You now have administrative responsibility to review their uploaded documents, upload finalized tax returns, and assist them through filing.</p>
|
||||||
|
<div style="margin:28px 0 16px;">
|
||||||
|
<a href="{client_link}" style="background-color:#0284c7;color:#ffffff;padding:12px 24px;text-decoration:none;border-radius:6px;font-weight:600;font-size:14px;display:inline-block;">
|
||||||
|
Open Client File →
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div style="background-color:#f1f5f9;padding:16px 28px;border-top:1px solid #e2e8f0;font-size:12px;color:#64748b;">
|
||||||
|
This is an automated notification from the Admin Portal.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
"""
|
||||||
|
background.add_task(
|
||||||
|
send_email,
|
||||||
|
to=new_admin.email,
|
||||||
|
subject=f"New Client Assigned: {client_display}",
|
||||||
|
body=email_body,
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"user_id": client.id,
|
||||||
|
"assigned_admin_id": client.assigned_admin_id,
|
||||||
|
"assigned_admin_name": new_admin.name if new_admin else None,
|
||||||
|
"assigned_admin_email": new_admin.email if new_admin else None,
|
||||||
|
"message": f"Client assigned to {new_admin_name}",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/admin/users/bulk-assign-admin")
|
||||||
|
def bulk_assign_users_to_admin(
|
||||||
|
payload: BulkAssignAdminRequest,
|
||||||
|
request: Request,
|
||||||
|
background: BackgroundTasks,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user=Depends(get_current_user),
|
||||||
|
_=Depends(require_super_admin),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Bulk assign multiple clients to an administrator. Super admin only.
|
||||||
|
Sends an email notification to the assigned admin.
|
||||||
|
"""
|
||||||
|
if not payload.user_ids:
|
||||||
|
raise HTTPException(status_code=400, detail="No user IDs provided")
|
||||||
|
|
||||||
|
new_admin = None
|
||||||
|
new_admin_name = "Unassigned"
|
||||||
|
if payload.admin_id is not None and payload.admin_id != 0:
|
||||||
|
new_admin = crud.get_user_by_id(db, payload.admin_id)
|
||||||
|
if not new_admin:
|
||||||
|
raise HTTPException(status_code=404, detail="Target admin not found")
|
||||||
|
if new_admin.role not in [UserRole.admin, UserRole.super_admin]:
|
||||||
|
raise HTTPException(status_code=400, detail="Assigned user must have an admin role")
|
||||||
|
new_admin_name = f"{new_admin.name or new_admin.email} (#{new_admin.id})"
|
||||||
|
|
||||||
|
clients = db.query(UserModel).filter(UserModel.id.in_(payload.user_ids)).all()
|
||||||
|
count = 0
|
||||||
|
client_names = []
|
||||||
|
for client in clients:
|
||||||
|
client.assigned_admin_id = new_admin.id if new_admin else None
|
||||||
|
client_names.append(f"{client.name or client.email} ({client.email})")
|
||||||
|
count += 1
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
crud.log_action(
|
||||||
|
db,
|
||||||
|
action="bulk_assign_admin",
|
||||||
|
user_id=current_user.id,
|
||||||
|
target=f"users:{len(clients)}",
|
||||||
|
detail=f"Bulk assigned {count} clients to {new_admin_name}",
|
||||||
|
ip_address=request.client.host if request.client else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Send email notification to new_admin
|
||||||
|
if new_admin and count > 0:
|
||||||
|
frontend_url = os.getenv("FRONTEND_URL", "https://aicpa.duckdns.org")
|
||||||
|
dashboard_link = f"{frontend_url}/admin-dashboard"
|
||||||
|
super_admin_name = current_user.name or current_user.email
|
||||||
|
items_html = "".join(f"<li style='margin:4px 0;'>{name}</li>" for name in client_names[:10])
|
||||||
|
if len(client_names) > 10:
|
||||||
|
items_html += f"<li style='margin:4px 0;color:#64748b;'><em>...and {len(client_names) - 10} more clients</em></li>"
|
||||||
|
|
||||||
|
email_body = f"""
|
||||||
|
<div style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;line-height:1.6;color:#1e293b;max-width:580px;margin:0 auto;border:1px solid #e2e8f0;border-radius:12px;overflow:hidden;box-shadow:0 4px 12px rgba(0,0,0,0.05);">
|
||||||
|
<div style="background-color:#0f172a;padding:24px 28px;text-align:left;">
|
||||||
|
<h2 style="color:#ffffff;margin:0;font-size:20px;font-weight:700;letter-spacing:-0.3px;">Admin Portal</h2>
|
||||||
|
<p style="color:#94a3b8;margin:6px 0 0 0;font-size:13px;">Batch Client Portfolio Assignment Notification</p>
|
||||||
|
</div>
|
||||||
|
<div style="padding:28px;">
|
||||||
|
<p style="font-size:15px;margin-top:0;">Hello <strong>{new_admin.name or 'Admin'}</strong>,</p>
|
||||||
|
<p style="font-size:14px;color:#334155;">Super Admin <strong>{super_admin_name}</strong> has assigned <strong>{count} client(s)</strong> to your portfolio:</p>
|
||||||
|
<ul style="background-color:#f8fafc;border-left:4px solid #0284c7;padding:12px 16px 12px 32px;margin:20px 0;border-radius:6px;font-size:14px;">
|
||||||
|
{items_html}
|
||||||
|
</ul>
|
||||||
|
<p style="font-size:14px;color:#475569;">You can view and manage these clients in your Admin Dashboard.</p>
|
||||||
|
<div style="margin:28px 0 16px;">
|
||||||
|
<a href="{dashboard_link}" style="background-color:#0284c7;color:#ffffff;padding:12px 24px;text-decoration:none;border-radius:6px;font-weight:600;font-size:14px;display:inline-block;">
|
||||||
|
Go to Admin Dashboard →
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div style="background-color:#f1f5f9;padding:16px 28px;border-top:1px solid #e2e8f0;font-size:12px;color:#64748b;">
|
||||||
|
This is an automated notification from the Admin Portal.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
"""
|
||||||
|
background.add_task(
|
||||||
|
send_email,
|
||||||
|
to=new_admin.email,
|
||||||
|
subject=f"{count} New Clients Assigned to Your Portfolio",
|
||||||
|
body=email_body,
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"count": count,
|
||||||
|
"assigned_admin_id": new_admin.id if new_admin else None,
|
||||||
|
"assigned_admin_name": new_admin.name if new_admin else None,
|
||||||
|
"message": f"Assigned {count} clients to {new_admin_name}",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -44,6 +44,9 @@ class User(Base):
|
|||||||
is_verified = Column(Integer, default=0, nullable=False) # 0 = unverified, 1 = verified
|
is_verified = Column(Integer, default=0, nullable=False) # 0 = unverified, 1 = verified
|
||||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||||
engagement_acknowledged_at = Column(DateTime(timezone=True), nullable=True, default=None)
|
engagement_acknowledged_at = Column(DateTime(timezone=True), nullable=True, default=None)
|
||||||
|
assigned_admin_id = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||||
|
|
||||||
|
assigned_admin = relationship("User", remote_side=[id], foreign_keys=[assigned_admin_id])
|
||||||
|
|
||||||
|
|
||||||
# ─────────────────────────────────────────────
|
# ─────────────────────────────────────────────
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import logging
|
import logging
|
||||||
import json
|
import json
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime, date, timezone
|
from datetime import datetime, date, timezone
|
||||||
@@ -11,7 +11,16 @@ import os
|
|||||||
import requests
|
import requests
|
||||||
from pydantic import BaseModel, field_validator
|
from pydantic import BaseModel, field_validator
|
||||||
from fastapi import HTTPException
|
from fastapi import HTTPException
|
||||||
from app.models import PersonalDocument, BusinessDocument, AdminDocument, User, AuditLog, ChatSession, ChatMessage as DBChatMessage
|
from app.models import (
|
||||||
|
PersonalDocument,
|
||||||
|
BusinessDocument,
|
||||||
|
AdminDocument,
|
||||||
|
User,
|
||||||
|
UserRole,
|
||||||
|
AuditLog,
|
||||||
|
ChatSession,
|
||||||
|
ChatMessage as DBChatMessage,
|
||||||
|
)
|
||||||
from app.db import get_db
|
from app.db import get_db
|
||||||
from app.auth.security import get_current_user, require_admin
|
from app.auth.security import get_current_user, require_admin
|
||||||
|
|
||||||
@@ -104,11 +113,34 @@ def get_admin_status(
|
|||||||
current_user=Depends(get_current_user),
|
current_user=Depends(get_current_user),
|
||||||
_=Depends(require_admin),
|
_=Depends(require_admin),
|
||||||
):
|
):
|
||||||
|
if not isinstance(tax_year, int):
|
||||||
|
tax_year = None
|
||||||
|
|
||||||
today_start = datetime.combine(date.today(), datetime.min.time(), tzinfo=timezone.utc)
|
today_start = datetime.combine(date.today(), datetime.min.time(), tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
is_standard_admin = current_user.role == UserRole.admin
|
||||||
|
assigned_uids = None
|
||||||
|
if is_standard_admin:
|
||||||
|
assigned_uids = [
|
||||||
|
u.id for u in db.query(User.id).filter(
|
||||||
|
User.role == UserRole.user,
|
||||||
|
User.assigned_admin_id == current_user.id
|
||||||
|
).all()
|
||||||
|
]
|
||||||
|
total_users = len(assigned_uids)
|
||||||
|
new_users_today = (
|
||||||
|
db.query(User)
|
||||||
|
.filter(User.id.in_(assigned_uids), User.created_at >= today_start)
|
||||||
|
.count()
|
||||||
|
if assigned_uids else 0
|
||||||
|
)
|
||||||
|
else:
|
||||||
total_users = db.query(User).count()
|
total_users = db.query(User).count()
|
||||||
new_users_today = db.query(User).filter(User.created_at >= today_start).count()
|
new_users_today = db.query(User).filter(User.created_at >= today_start).count()
|
||||||
|
|
||||||
pq = db.query(PersonalDocument).filter(PersonalDocument.review_status == "pending", PersonalDocument.deleted_at == None)
|
pq = db.query(PersonalDocument).filter(PersonalDocument.review_status == "pending", PersonalDocument.deleted_at == None)
|
||||||
|
if is_standard_admin:
|
||||||
|
pq = pq.filter(PersonalDocument.user_id.in_(assigned_uids)) if assigned_uids else pq.filter(False)
|
||||||
if tax_year:
|
if tax_year:
|
||||||
pq = pq.filter(PersonalDocument.tax_year == tax_year)
|
pq = pq.filter(PersonalDocument.tax_year == tax_year)
|
||||||
pending_personal = pq.count()
|
pending_personal = pq.count()
|
||||||
@@ -116,27 +148,37 @@ def get_admin_status(
|
|||||||
admin_accounts = db.query(User).filter(User.role.in_(["admin", "super_admin"])).count()
|
admin_accounts = db.query(User).filter(User.role.in_(["admin", "super_admin"])).count()
|
||||||
|
|
||||||
bq = db.query(BusinessDocument).filter(BusinessDocument.review_status == "pending", BusinessDocument.deleted_at == None)
|
bq = db.query(BusinessDocument).filter(BusinessDocument.review_status == "pending", BusinessDocument.deleted_at == None)
|
||||||
|
if is_standard_admin:
|
||||||
|
bq = bq.filter(BusinessDocument.user_id.in_(assigned_uids)) if assigned_uids else bq.filter(False)
|
||||||
if tax_year:
|
if tax_year:
|
||||||
bq = bq.filter(BusinessDocument.tax_year == tax_year)
|
bq = bq.filter(BusinessDocument.tax_year == tax_year)
|
||||||
pending_business = bq.count()
|
pending_business = bq.count()
|
||||||
|
|
||||||
admin_docs = db.query(AdminDocument).filter(AdminDocument.deleted_at == None)
|
admin_docs = db.query(AdminDocument).filter(AdminDocument.deleted_at == None)
|
||||||
|
if is_standard_admin:
|
||||||
|
admin_docs = admin_docs.filter(AdminDocument.user_id.in_(assigned_uids)) if assigned_uids else admin_docs.filter(False)
|
||||||
if tax_year:
|
if tax_year:
|
||||||
admin_docs = admin_docs.filter(AdminDocument.tax_year == tax_year)
|
admin_docs = admin_docs.filter(AdminDocument.tax_year == tax_year)
|
||||||
pending_admin_returns = admin_docs.filter(AdminDocument.review_status == "pending").count()
|
pending_admin_returns = admin_docs.filter(AdminDocument.review_status == "pending").count()
|
||||||
|
|
||||||
recent_personal = (
|
rpq = db.query(PersonalDocument).filter(PersonalDocument.deleted_at == None)
|
||||||
db.query(PersonalDocument).filter(PersonalDocument.deleted_at == None)
|
rbq = db.query(BusinessDocument).filter(BusinessDocument.deleted_at == None)
|
||||||
.order_by(PersonalDocument.uploaded_at.desc()).limit(10).all()
|
raq = db.query(AdminDocument).filter(AdminDocument.deleted_at == None)
|
||||||
)
|
|
||||||
recent_business = (
|
if is_standard_admin:
|
||||||
db.query(BusinessDocument).filter(BusinessDocument.deleted_at == None)
|
if assigned_uids:
|
||||||
.order_by(BusinessDocument.uploaded_at.desc()).limit(10).all()
|
rpq = rpq.filter(PersonalDocument.user_id.in_(assigned_uids))
|
||||||
)
|
rbq = rbq.filter(BusinessDocument.user_id.in_(assigned_uids))
|
||||||
recent_admin = (
|
raq = raq.filter(AdminDocument.user_id.in_(assigned_uids))
|
||||||
db.query(AdminDocument).filter(AdminDocument.deleted_at == None)
|
else:
|
||||||
.order_by(AdminDocument.uploaded_at.desc()).limit(10).all()
|
rpq = rpq.filter(False)
|
||||||
)
|
rbq = rbq.filter(False)
|
||||||
|
raq = raq.filter(False)
|
||||||
|
|
||||||
|
recent_personal = rpq.order_by(PersonalDocument.uploaded_at.desc()).limit(10).all()
|
||||||
|
recent_business = rbq.order_by(BusinessDocument.uploaded_at.desc()).limit(10).all()
|
||||||
|
recent_admin = raq.order_by(AdminDocument.uploaded_at.desc()).limit(10).all()
|
||||||
|
|
||||||
recent_uploads = sorted(
|
recent_uploads = sorted(
|
||||||
[{"user_id": d.user_id, "doc": d.doc_type, "type": "personal",
|
[{"user_id": d.user_id, "doc": d.doc_type, "type": "personal",
|
||||||
"uploaded_at": d.uploaded_at, "status": d.review_status} for d in recent_personal] +
|
"uploaded_at": d.uploaded_at, "status": d.review_status} for d in recent_personal] +
|
||||||
@@ -174,7 +216,7 @@ def get_daily_digest(
|
|||||||
_=Depends(require_admin),
|
_=Depends(require_admin),
|
||||||
):
|
):
|
||||||
from app.utils.doc_intelligence import build_daily_digest
|
from app.utils.doc_intelligence import build_daily_digest
|
||||||
stats = get_admin_status(db=db, current_user=current_user, _=None)
|
stats = get_admin_status(tax_year=None, db=db, current_user=current_user, _=None)
|
||||||
digest_html = build_daily_digest(stats)
|
digest_html = build_daily_digest(stats)
|
||||||
return {"digest": digest_html, "generated_at": datetime.now().isoformat()}
|
return {"digest": digest_html, "generated_at": datetime.now().isoformat()}
|
||||||
|
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ async def contact_message(request: Request, form: ContactForm, background: Backg
|
|||||||
background.add_task(
|
background.add_task(
|
||||||
send_email,
|
send_email,
|
||||||
to=ADMIN_EMAIL,
|
to=ADMIN_EMAIL,
|
||||||
subject="New Contact Enquiry Received — Follow-Up Required - BookKeepro",
|
subject="New Contact Enquiry Received — Follow-Up Required",
|
||||||
body=f"""
|
body=f"""
|
||||||
Dear Team,
|
Dear Team,
|
||||||
<br><br>
|
<br><br>
|
||||||
@@ -51,7 +51,7 @@ async def contact_message(request: Request, form: ContactForm, background: Backg
|
|||||||
Kindly follow up with the user at the earliest convenience.
|
Kindly follow up with the user at the earliest convenience.
|
||||||
<br><br>
|
<br><br>
|
||||||
Thank you,<br>
|
Thank you,<br>
|
||||||
BookKeepro Support Team
|
Support Team
|
||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -59,13 +59,13 @@ async def contact_message(request: Request, form: ContactForm, background: Backg
|
|||||||
background.add_task(
|
background.add_task(
|
||||||
send_email,
|
send_email,
|
||||||
to=form.email,
|
to=form.email,
|
||||||
subject="Thanks for contacting BookKeepro",
|
subject="Thanks for contacting us",
|
||||||
body=f"""
|
body=f"""
|
||||||
Hi {safe_first},<br><br>
|
Hi {safe_first},<br><br>
|
||||||
Thank you for reaching out to BookKeepro.<br>
|
Thank you for reaching out.<br>
|
||||||
We’ve received your enquiry, and our team will get back to you shortly.<br><br>
|
We’ve received your enquiry, and our team will get back to you shortly.<br><br>
|
||||||
Best Regards,<br>
|
Best Regards,<br>
|
||||||
BookKeepro Team
|
Support Team
|
||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ async def submit_review(
|
|||||||
|
|
||||||
email_sent = await send_email(
|
email_sent = await send_email(
|
||||||
to=user.email,
|
to=user.email,
|
||||||
subject="Documents Ready for Review — BookKeepro",
|
subject="Documents Ready for Review",
|
||||||
body=f"""
|
body=f"""
|
||||||
<p>Dear {user.name or "Sir/Ma'am"},</p>
|
<p>Dear {user.name or "Sir/Ma'am"},</p>
|
||||||
<p>Your documents have been successfully submitted and are pending review.</p>
|
<p>Your documents have been successfully submitted and are pending review.</p>
|
||||||
@@ -45,7 +45,7 @@ async def submit_review(
|
|||||||
👉 Go to Dashboard
|
👉 Go to Dashboard
|
||||||
</a>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
<p style="margin-top:20px;">Kind regards,<br><strong>BookKeepro Team</strong></p>
|
<p style="margin-top:20px;">Kind regards,<br><strong>Support Team</strong></p>
|
||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -88,10 +88,10 @@ async def notify_user_review(
|
|||||||
<li>Business Documents: {payload.business_timeline} days</li>
|
<li>Business Documents: {payload.business_timeline} days</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
<p>Kind regards,<br><strong>BookKeepro Team</strong></p>
|
<p>Kind regards,<br><strong>Support Team</strong></p>
|
||||||
"""
|
"""
|
||||||
|
|
||||||
await send_email(to=user.email, subject="Document Review Update — BookKeepro", body=body)
|
await send_email(to=user.email, subject="Document Review Update", body=body)
|
||||||
logger.info(f"Admin {current_user.id} sent review notification to user {payload.user_id}")
|
logger.info(f"Admin {current_user.id} sent review notification to user {payload.user_id}")
|
||||||
|
|
||||||
# Save / reset filing deadlines if timelines were provided
|
# Save / reset filing deadlines if timelines were provided
|
||||||
@@ -180,12 +180,12 @@ async def admin_doc_response(
|
|||||||
if payload.status == "rejected" and payload.reason:
|
if payload.status == "rejected" and payload.reason:
|
||||||
body += f"<p><strong>Reason:</strong></p><p>{payload.reason}</p>"
|
body += f"<p><strong>Reason:</strong></p><p>{payload.reason}</p>"
|
||||||
|
|
||||||
body += "<p style='margin-top:20px;'>BookKeepro System</p>"
|
body += "<p style='margin-top:20px;'>Admin Portal</p>"
|
||||||
|
|
||||||
background.add_task(
|
background.add_task(
|
||||||
send_email,
|
send_email,
|
||||||
to=admin_email,
|
to=admin_email,
|
||||||
subject=f"Admin Return Status {payload.status.capitalize()} — BookKeepro",
|
subject=f"Admin Return Status {payload.status.capitalize()}",
|
||||||
body=body,
|
body=body,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -394,7 +394,7 @@ async def send_return_for_approval(
|
|||||||
background.add_task(
|
background.add_task(
|
||||||
send_email,
|
send_email,
|
||||||
to=client.email,
|
to=client.email,
|
||||||
subject="Action Required: Please Review Your Tax Return — BookKeepro",
|
subject="Action Required: Please Review Your Tax Return",
|
||||||
body=f"""
|
body=f"""
|
||||||
<p>Dear {client.name or 'Client'},</p>
|
<p>Dear {client.name or 'Client'},</p>
|
||||||
<p>Your tax professional has prepared a document for your review:</p>
|
<p>Your tax professional has prepared a document for your review:</p>
|
||||||
@@ -402,7 +402,7 @@ async def send_return_for_approval(
|
|||||||
{note_html}
|
{note_html}
|
||||||
<p>Please log in to your dashboard to review, approve, or request changes.</p>
|
<p>Please log in to your dashboard to review, approve, or request changes.</p>
|
||||||
<p><a href='{DASHBOARD_LINK}' style='color:#2c7a5b;font-weight:600;font-size:15px;'>Review Now →</a></p>
|
<p><a href='{DASHBOARD_LINK}' style='color:#2c7a5b;font-weight:600;font-size:15px;'>Review Now →</a></p>
|
||||||
<p style='margin-top:20px;'>Kind regards,<br><strong>BookKeepro Team</strong></p>
|
<p style='margin-top:20px;'>Kind regards,<br><strong>Support Team</strong></p>
|
||||||
""",
|
""",
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -462,7 +462,7 @@ async def mark_filing_complete(
|
|||||||
background.add_task(
|
background.add_task(
|
||||||
send_email,
|
send_email,
|
||||||
to=client.email,
|
to=client.email,
|
||||||
subject=f"Your {payload.tax_year} Tax Return Has Been Filed — BookKeepro",
|
subject=f"Your {payload.tax_year} Tax Return Has Been Filed",
|
||||||
body=f"""
|
body=f"""
|
||||||
<p>Dear {client.name or 'Client'},</p>
|
<p>Dear {client.name or 'Client'},</p>
|
||||||
<p>Great news! Your <strong>{payload.tax_year}</strong> tax return has been successfully filed.</p>
|
<p>Great news! Your <strong>{payload.tax_year}</strong> tax return has been successfully filed.</p>
|
||||||
@@ -470,7 +470,7 @@ async def mark_filing_complete(
|
|||||||
{note_html}
|
{note_html}
|
||||||
<p>You can view the status in your dashboard at any time.</p>
|
<p>You can view the status in your dashboard at any time.</p>
|
||||||
<p><a href='{DASHBOARD_LINK}' style='color:#2c7a5b;font-weight:600;'>Go to Dashboard →</a></p>
|
<p><a href='{DASHBOARD_LINK}' style='color:#2c7a5b;font-weight:600;'>Go to Dashboard →</a></p>
|
||||||
<p style='margin-top:20px;'>Thank you for choosing BookKeepro.<br><strong>BookKeepro Team</strong></p>
|
<p style='margin-top:20px;'>Thank you.<br><strong>Support Team</strong></p>
|
||||||
""",
|
""",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -266,12 +266,12 @@ def get_view_url(
|
|||||||
|
|
||||||
@router.post("/admin-documents")
|
@router.post("/admin-documents")
|
||||||
async def upload_admin_document(
|
async def upload_admin_document(
|
||||||
|
background: BackgroundTasks,
|
||||||
file: UploadFile = File(...),
|
file: UploadFile = File(...),
|
||||||
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),
|
tax_year: int | None = Form(None),
|
||||||
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),
|
||||||
@@ -325,12 +325,12 @@ async def upload_admin_document(
|
|||||||
background.add_task(
|
background.add_task(
|
||||||
send_email,
|
send_email,
|
||||||
to=target_user.email,
|
to=target_user.email,
|
||||||
subject="New Document Uploaded — BookKeepro",
|
subject="New Document Uploaded",
|
||||||
body=f"""
|
body=f"""
|
||||||
<p>Dear {target_user.name or "Sir/Ma'am"},</p>
|
<p>Dear {target_user.name or "Sir/Ma'am"},</p>
|
||||||
<p>An admin has securely uploaded a new document (<strong>{doc_label}</strong>) to your account.</p>
|
<p>An admin has securely uploaded a new document (<strong>{doc_label}</strong>) to your account.</p>
|
||||||
<p>You can view this document by logging into your BookKeepro portal.</p>
|
<p>You can view this document by logging into your portal.</p>
|
||||||
<br><strong>BookKeepro Team</strong>
|
<br><strong>Support Team</strong>
|
||||||
""",
|
""",
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -552,14 +552,14 @@ async def upload_personal_document(
|
|||||||
background.add_task(
|
background.add_task(
|
||||||
send_email,
|
send_email,
|
||||||
to=admin.email,
|
to=admin.email,
|
||||||
subject="New Personal Document Uploaded — BookKeepro",
|
subject="New Personal Document Uploaded",
|
||||||
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(
|
background.add_task(
|
||||||
send_email,
|
send_email,
|
||||||
to=current_user.email,
|
to=current_user.email,
|
||||||
subject="Personal Document Upload Confirmation — BookKeepro",
|
subject="Personal Document Upload Confirmation",
|
||||||
body=f"<p>We have successfully received your personal document: <strong>{file.filename}</strong> ({doc_type}).</p>",
|
body=f"<p>We have successfully received your personal document: <strong>{file.filename}</strong> ({doc_type}).</p>",
|
||||||
)
|
)
|
||||||
background.add_task(
|
background.add_task(
|
||||||
@@ -725,14 +725,14 @@ async def upload_business_document(
|
|||||||
background.add_task(
|
background.add_task(
|
||||||
send_email,
|
send_email,
|
||||||
to=admin.email,
|
to=admin.email,
|
||||||
subject="New Business Document Uploaded — BookKeepro",
|
subject="New Business Document Uploaded",
|
||||||
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(
|
background.add_task(
|
||||||
send_email,
|
send_email,
|
||||||
to=current_user.email,
|
to=current_user.email,
|
||||||
subject="Business Document Upload Confirmation — BookKeepro",
|
subject="Business Document Upload Confirmation",
|
||||||
body=f"<p>We have successfully received your business document: <strong>{file.filename}</strong> ({doc_type}).</p>",
|
body=f"<p>We have successfully received your business document: <strong>{file.filename}</strong> ({doc_type}).</p>",
|
||||||
)
|
)
|
||||||
background.add_task(
|
background.add_task(
|
||||||
@@ -825,14 +825,14 @@ async def set_personal_review_status(
|
|||||||
background.add_task(
|
background.add_task(
|
||||||
send_email,
|
send_email,
|
||||||
to=owner.email,
|
to=owner.email,
|
||||||
subject="Action Required: Document Rejected — BookKeepro",
|
subject="Action Required: Document Rejected",
|
||||||
body=f"""
|
body=f"""
|
||||||
<p>Dear {owner.name or 'Client'},</p>
|
<p>Dear {owner.name or 'Client'},</p>
|
||||||
<p>Your personal document <strong>{doc.filename}</strong> (Tax Year {doc.tax_year}) has been <strong style='color:#c0392b;'>rejected</strong> by our team.</p>
|
<p>Your personal document <strong>{doc.filename}</strong> (Tax Year {doc.tax_year}) has been <strong style='color:#c0392b;'>rejected</strong> by our team.</p>
|
||||||
{note_html}
|
{note_html}
|
||||||
<p>Please log in to your dashboard, review the reason, and re-upload a corrected document.</p>
|
<p>Please log in to your dashboard, review the reason, and re-upload a corrected document.</p>
|
||||||
<p><a href='{FRONTEND_URL}/upload-personal' style='color:#0077c8;font-weight:600;'>Re-upload Personal Documents →</a></p>
|
<p><a href='{FRONTEND_URL}/upload-personal' style='color:#0077c8;font-weight:600;'>Re-upload Personal Documents →</a></p>
|
||||||
<p style='margin-top:20px;'>Kind regards,<br><strong>BookKeepro Team</strong></p>
|
<p style='margin-top:20px;'>Kind regards,<br><strong>Support Team</strong></p>
|
||||||
""",
|
""",
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -889,14 +889,14 @@ async def set_business_review_status(
|
|||||||
background.add_task(
|
background.add_task(
|
||||||
send_email,
|
send_email,
|
||||||
to=owner.email,
|
to=owner.email,
|
||||||
subject="Action Required: Document Rejected — BookKeepro",
|
subject="Action Required: Document Rejected",
|
||||||
body=f"""
|
body=f"""
|
||||||
<p>Dear {owner.name or 'Client'},</p>
|
<p>Dear {owner.name or 'Client'},</p>
|
||||||
<p>Your business document <strong>{doc.filename}</strong> (Tax Year {doc.tax_year}) has been <strong style='color:#c0392b;'>rejected</strong> by our team.</p>
|
<p>Your business document <strong>{doc.filename}</strong> (Tax Year {doc.tax_year}) has been <strong style='color:#c0392b;'>rejected</strong> by our team.</p>
|
||||||
{note_html}
|
{note_html}
|
||||||
<p>Please log in to your dashboard, review the reason, and re-upload a corrected document.</p>
|
<p>Please log in to your dashboard, review the reason, and re-upload a corrected document.</p>
|
||||||
<p><a href='{FRONTEND_URL}/upload-business' style='color:#0077c8;font-weight:600;'>Re-upload Business Documents →</a></p>
|
<p><a href='{FRONTEND_URL}/upload-business' style='color:#0077c8;font-weight:600;'>Re-upload Business Documents →</a></p>
|
||||||
<p style='margin-top:20px;'>Kind regards,<br><strong>BookKeepro Team</strong></p>
|
<p style='margin-top:20px;'>Kind regards,<br><strong>Support Team</strong></p>
|
||||||
""",
|
""",
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -1028,6 +1028,9 @@ def get_user_all_documents(
|
|||||||
"name": user.name,
|
"name": user.name,
|
||||||
"email": user.email,
|
"email": user.email,
|
||||||
"role": user.role.value if hasattr(user.role, "value") else str(user.role),
|
"role": user.role.value if hasattr(user.role, "value") else str(user.role),
|
||||||
|
"assigned_admin_id": user.assigned_admin_id,
|
||||||
|
"assigned_admin_name": user.assigned_admin.name if user.assigned_admin else None,
|
||||||
|
"assigned_admin_email": user.assigned_admin.email if user.assigned_admin else None,
|
||||||
"engagement_acknowledged_at": (
|
"engagement_acknowledged_at": (
|
||||||
user.engagement_acknowledged_at.isoformat()
|
user.engagement_acknowledged_at.isoformat()
|
||||||
if user.engagement_acknowledged_at else None
|
if user.engagement_acknowledged_at else None
|
||||||
@@ -1163,13 +1166,13 @@ async def notify_upload_complete(
|
|||||||
background.add_task(
|
background.add_task(
|
||||||
send_email,
|
send_email,
|
||||||
to=current_user.email,
|
to=current_user.email,
|
||||||
subject=f"{category} Documents Uploaded — BookKeepro",
|
subject=f"{category} Documents Uploaded",
|
||||||
body=f"""
|
body=f"""
|
||||||
<p>Dear {current_user.name or "Sir/Ma'am"},</p>
|
<p>Dear {current_user.name or "Sir/Ma'am"},</p>
|
||||||
<p>We received <strong>{count}</strong> {category.lower()}
|
<p>We received <strong>{count}</strong> {category.lower()}
|
||||||
document{"s" if count != 1 else ""} from you.</p>
|
document{"s" if count != 1 else ""} from you.</p>
|
||||||
<p>Our team will review {"them" if count != 1 else "it"} and update you shortly.</p>
|
<p>Our team will review {"them" if count != 1 else "it"} and update you shortly.</p>
|
||||||
<br><strong>BookKeepro Team</strong>
|
<br><strong>Support Team</strong>
|
||||||
""",
|
""",
|
||||||
)
|
)
|
||||||
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()
|
||||||
@@ -1177,7 +1180,7 @@ async def notify_upload_complete(
|
|||||||
background.add_task(
|
background.add_task(
|
||||||
send_email,
|
send_email,
|
||||||
to=admin.email,
|
to=admin.email,
|
||||||
subject=f"New {category} Upload — BookKeepro",
|
subject=f"New {category} Upload",
|
||||||
body=f"<p><strong>{current_user.email}</strong> uploaded "
|
body=f"<p><strong>{current_user.email}</strong> uploaded "
|
||||||
f"{count} {category.lower()} document{'s' if count != 1 else ''}.</p>",
|
f"{count} {category.lower()} document{'s' if count != 1 else ''}.</p>",
|
||||||
)
|
)
|
||||||
@@ -1203,11 +1206,11 @@ async def notify_personal_approval(
|
|||||||
background.add_task(
|
background.add_task(
|
||||||
send_email,
|
send_email,
|
||||||
to=user.email,
|
to=user.email,
|
||||||
subject="Personal Documents Approved — BookKeepro",
|
subject="Personal Documents Approved",
|
||||||
body=f"""
|
body=f"""
|
||||||
<p>Dear {user.name or "Sir/Ma'am"},</p>
|
<p>Dear {user.name or "Sir/Ma'am"},</p>
|
||||||
<p>Your personal documents have been successfully reviewed and approved.</p>
|
<p>Your personal documents have been successfully reviewed and approved.</p>
|
||||||
<br><strong>BookKeepro Team</strong>
|
<br><strong>Support Team</strong>
|
||||||
""",
|
""",
|
||||||
)
|
)
|
||||||
return {"status": "email_sent"}
|
return {"status": "email_sent"}
|
||||||
@@ -1226,11 +1229,11 @@ async def notify_business_approval(
|
|||||||
background.add_task(
|
background.add_task(
|
||||||
send_email,
|
send_email,
|
||||||
to=user.email,
|
to=user.email,
|
||||||
subject="Business Documents Approved — BookKeepro",
|
subject="Business Documents Approved",
|
||||||
body=f"""
|
body=f"""
|
||||||
<p>Dear {user.name or "Sir/Ma'am"},</p>
|
<p>Dear {user.name or "Sir/Ma'am"},</p>
|
||||||
<p>Your business documents have been successfully reviewed and approved.</p>
|
<p>Your business documents have been successfully reviewed and approved.</p>
|
||||||
<br><strong>BookKeepro Team</strong>
|
<br><strong>Support Team</strong>
|
||||||
""",
|
""",
|
||||||
)
|
)
|
||||||
return {"status": "email_sent"}
|
return {"status": "email_sent"}
|
||||||
|
|||||||
@@ -75,6 +75,17 @@ class RoleChangeRequest(BaseModel):
|
|||||||
return v.lower()
|
return v.lower()
|
||||||
|
|
||||||
|
|
||||||
|
class AssignAdminRequest(BaseModel):
|
||||||
|
"""Body for PATCH /api/auth/admin/users/{id}/assign-admin — super_admin only."""
|
||||||
|
admin_id: Optional[int] = None
|
||||||
|
|
||||||
|
|
||||||
|
class BulkAssignAdminRequest(BaseModel):
|
||||||
|
"""Body for POST /api/auth/admin/users/bulk-assign-admin — super_admin only."""
|
||||||
|
user_ids: List[int]
|
||||||
|
admin_id: Optional[int] = None
|
||||||
|
|
||||||
|
|
||||||
# ─────────────────────────────────────────────
|
# ─────────────────────────────────────────────
|
||||||
# Review schemas
|
# Review schemas
|
||||||
# ─────────────────────────────────────────────
|
# ─────────────────────────────────────────────
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ async def send_email(to: str, subject: str, body: str) -> bool:
|
|||||||
if smtp_password:
|
if smtp_password:
|
||||||
smtp_password = smtp_password.replace(" ", "")
|
smtp_password = smtp_password.replace(" ", "")
|
||||||
mail_from_email = os.getenv("MAIL_FROM") or smtp_user
|
mail_from_email = os.getenv("MAIL_FROM") or smtp_user
|
||||||
mail_from_name = os.getenv("MAIL_FROM_NAME", "BookKeepro")
|
mail_from_name = os.getenv("MAIL_FROM_NAME", "Admin Portal")
|
||||||
smtp_tls = os.getenv("SMTP_TLS", "True").strip().lower() == "true"
|
smtp_tls = os.getenv("SMTP_TLS", "True").strip().lower() == "true"
|
||||||
smtp_ssl_tls = os.getenv("MAIL_SSL_TLS", "False").strip().lower() == "true"
|
smtp_ssl_tls = os.getenv("MAIL_SSL_TLS", "False").strip().lower() == "true"
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ async def send_signup_welcome_email(to: str, name: str | None = None):
|
|||||||
<p>Dear {display_name},</p>
|
<p>Dear {display_name},</p>
|
||||||
|
|
||||||
<p>
|
<p>
|
||||||
Welcome to <strong>BookKeepro</strong> 🎉
|
Welcome! 🎉
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p>
|
<p>
|
||||||
@@ -26,7 +26,7 @@ async def send_signup_welcome_email(to: str, name: str | None = None):
|
|||||||
<p>
|
<p>
|
||||||
<a href="{_FRONTEND_URL}/login"
|
<a href="{_FRONTEND_URL}/login"
|
||||||
style="color:#0077c8;font-weight:600;text-decoration:none;">
|
style="color:#0077c8;font-weight:600;text-decoration:none;">
|
||||||
👉 Login to BookKeepro
|
👉 Login to Dashboard
|
||||||
</a>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
@@ -36,12 +36,12 @@ async def send_signup_welcome_email(to: str, name: str | None = None):
|
|||||||
|
|
||||||
<p style="margin-top:20px;">
|
<p style="margin-top:20px;">
|
||||||
Kind regards,<br>
|
Kind regards,<br>
|
||||||
<strong>BookKeepro Team</strong>
|
<strong>Support Team</strong>
|
||||||
</p>
|
</p>
|
||||||
"""
|
"""
|
||||||
|
|
||||||
await send_email(
|
await send_email(
|
||||||
to=to,
|
to=to,
|
||||||
subject="Welcome to BookKeepro 🎉",
|
subject="Welcome 🎉",
|
||||||
body=body
|
body=body
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -63,11 +63,11 @@ def _run_deadline_reminders():
|
|||||||
<p>This is a reminder that your <strong>{doc_label} document filing deadline</strong>
|
<p>This is a reminder that your <strong>{doc_label} document filing deadline</strong>
|
||||||
is in <strong>{label}</strong> ({dl.deadline_date.strftime('%B %d, %Y')}).</p>
|
is in <strong>{label}</strong> ({dl.deadline_date.strftime('%B %d, %Y')}).</p>
|
||||||
<p>Please ensure all outstanding actions are completed before the deadline.</p>
|
<p>Please ensure all outstanding actions are completed before the deadline.</p>
|
||||||
<p>Kind regards,<br><strong>BookKeepro Team</strong></p>
|
<p>Kind regards,<br><strong>Support Team</strong></p>
|
||||||
"""
|
"""
|
||||||
await send_email(
|
await send_email(
|
||||||
to=user.email,
|
to=user.email,
|
||||||
subject=f"Reminder: {doc_label} Filing Deadline in {label} — BookKeepro",
|
subject=f"Reminder: {doc_label} Filing Deadline in {label}",
|
||||||
body=user_body,
|
body=user_body,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -78,7 +78,7 @@ def _run_deadline_reminders():
|
|||||||
<strong>{user.name or user.email}</strong> ({user.email}) is in
|
<strong>{user.name or user.email}</strong> ({user.email}) is in
|
||||||
<strong>{label}</strong> ({dl.deadline_date.strftime('%B %d, %Y')}).</p>
|
<strong>{label}</strong> ({dl.deadline_date.strftime('%B %d, %Y')}).</p>
|
||||||
<p>Please review the client's status and take any necessary action.</p>
|
<p>Please review the client's status and take any necessary action.</p>
|
||||||
<p><strong>BookKeepro System</strong></p>
|
<p><strong>Admin System</strong></p>
|
||||||
"""
|
"""
|
||||||
for admin_email in admin_emails:
|
for admin_email in admin_emails:
|
||||||
await send_email(
|
await send_email(
|
||||||
|
|||||||
@@ -197,6 +197,29 @@ def upgrade():
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f" [WARN] Template seed: {e}")
|
print(f" [WARN] Template seed: {e}")
|
||||||
|
|
||||||
|
# -- v9: Assigned admin support for users --------------------------
|
||||||
|
_add_column(conn, "users", "assigned_admin_id", "INT NULL DEFAULT NULL")
|
||||||
|
try:
|
||||||
|
conn.execute(text("ALTER TABLE users ADD CONSTRAINT fk_users_assigned_admin FOREIGN KEY (assigned_admin_id) REFERENCES users(id) ON DELETE SET NULL;"))
|
||||||
|
print(" [OK] Added fk_users_assigned_admin constraint")
|
||||||
|
except Exception as e:
|
||||||
|
msg = str(e).lower()
|
||||||
|
if "duplicate" in msg or "already exists" in msg:
|
||||||
|
print(" [SKIP] fk_users_assigned_admin already exists")
|
||||||
|
else:
|
||||||
|
print(f" [WARN] fk_users_assigned_admin: {e}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
conn.execute(text("CREATE INDEX ix_users_assigned_admin_id ON users(assigned_admin_id);"))
|
||||||
|
print(" [OK] Added ix_users_assigned_admin_id index")
|
||||||
|
except Exception as e:
|
||||||
|
msg = str(e).lower()
|
||||||
|
if "duplicate" in msg or "already exists" in msg:
|
||||||
|
print(" [SKIP] ix_users_assigned_admin_id already exists")
|
||||||
|
else:
|
||||||
|
print(f" [WARN] ix_users_assigned_admin_id: {e}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
print("\nAll migrations complete.")
|
print("\nAll migrations complete.")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
Reference in New Issue
Block a user