diff --git a/frontend/src/pages/AdminDashboard.jsx b/frontend/src/pages/AdminDashboard.jsx index a1ebac7..af88d19 100644 --- a/frontend/src/pages/AdminDashboard.jsx +++ b/frontend/src/pages/AdminDashboard.jsx @@ -6,7 +6,8 @@ import { useToast } from '../context/ToastContext'; import ConfirmModal from '../components/ConfirmModal'; export default function AdminDashboard() { - const { authFetch } = useAuth(); + const { authFetch, user: currentUser } = useAuth(); + const isSuperAdmin = currentUser?.role === 'super_admin'; const { showToast } = useToast(); const [confirmConfig, setConfirmConfig] = useState({ isOpen: false, title: "", message: "", confirmText: "OK", isDestructive: false, onConfirm: () => {} @@ -19,10 +20,55 @@ export default function AdminDashboard() { const [userFilter, setUserFilter] = useState("all"); const [userSort, setUserSort] = useState("newest"); const [filterYear, setFilterYear] = useState(new Date().getFullYear().toString()); + const [adminAssignmentFilter, setAdminAssignmentFilter] = useState("all"); + const [staffList, setStaffList] = useState([]); const [tab, setTab] = useState("users"); const [loading, setLoading] = useState(true); 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 --- const [tplCategory, setTplCategory] = useState("personal"); const [tplYear, setTplYear] = useState(new Date().getFullYear().toString()); @@ -41,16 +87,35 @@ export default function AdminDashboard() { if (res.ok) { const data = await res.json(); 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); } - finally { setDigestLoading(false); } - }, [authFetch]); + } catch (err) { + console.error(err); + showToast("Network error while generating digest", "error"); + } finally { + setDigestLoading(false); + } + }, [authFetch, showToast]); const fetchAdminData = useCallback(async () => { setLoading(true); 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([ - authFetch(`/api/auth/admin/users?tax_year=${filterYear}`), + authFetch(usersUrl), authFetch(`/api/chatbot/admin-status?tax_year=${filterYear}`), authFetch(`/api/upload/bookmarks`) ]); @@ -90,7 +155,7 @@ export default function AdminDashboard() { } finally { setLoading(false); } - }, [authFetch, filterYear]); + }, [authFetch, filterYear, adminAssignmentFilter, isSuperAdmin]); const loadTemplates = useCallback(async () => { setTplLoading(true); @@ -219,8 +284,8 @@ export default function AdminDashboard() {
{tab === 'users' && ( -
-
+
+
search setSearch(e.target.value)} />
+ + {/* Admin Assignment Filter */} + {isSuperAdmin ? ( + + ) : ( + + )} + e.stopPropagation()} + onChange={(e) => { + e.stopPropagation(); + handleAssignAdmin(u.id, e.target.value); + }} + title="Assign client to admin" + > + + {staffList.map(s => ( + + ))} + + )} +
)}
-
)) )} diff --git a/frontend/src/pages/AdminUserDetail.jsx b/frontend/src/pages/AdminUserDetail.jsx index 672c97e..4aae85d 100644 --- a/frontend/src/pages/AdminUserDetail.jsx +++ b/frontend/src/pages/AdminUserDetail.jsx @@ -51,9 +51,45 @@ export default function AdminUserDetail() { const [auditLog, setAuditLog] = useState([]); const [auditLoaded, setAuditLoaded] = useState(false); const [deadlines, setDeadlines] = useState([]); + const [staffList, setStaffList] = useState([]); 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 () => { setLoading(true); try { @@ -61,7 +97,11 @@ export default function AdminUserDetail() { const res = await authFetch(url); 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; } @@ -519,7 +559,7 @@ export default function AdminUserDetail() {

{userDetail.name || "?"}

{userDetail.email}
-
+
{currentUser?.role === 'super_admin' && currentUser.id !== userDetail.id ? ( handleAssignAdmin(e.target.value)} + > + + {staffList.map(s => ( + + ))} + +
+ ) : ( + + assignment_ind + {userDetail.assigned_admin_id === currentUser?.id ? 'Assigned to You' : (userDetail.assigned_admin_name ? `Assigned to: ${userDetail.assigned_admin_name}` : 'Unassigned')} + + ) + )} + {!userDetail.engagement_acknowledged_at && ( pending Engagement not acknowledged )} diff --git a/services/api/app/auth/security.py b/services/api/app/auth/security.py index ca2286b..4eb76da 100644 --- a/services/api/app/auth/security.py +++ b/services/api/app/auth/security.py @@ -9,7 +9,17 @@ from sqlalchemy.orm import Session from app.db import get_db 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 logger = logging.getLogger(__name__) @@ -107,12 +117,12 @@ async def forgot_password( f'text-decoration:none;border-radius:6px;">' f"Reset Password

" f"This link expires in 15 minutes.

" - f"BookKeepro Team" + f"Support Team" ) background.add_task( send_email, to=user.email, - subject="Reset your BookKeepro password", + subject="Reset your password", body=reset_body, ) @@ -217,7 +227,8 @@ 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). + 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: 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]: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin access required") - # Admins can only view 'user' accounts. Super admins can view any account. - if current_user.role != UserRole.super_admin and target_user.role != UserRole.user: + # Super admins can view and manage any account + if current_user.role == UserRole.super_admin: + return + + # Admins can only view 'user' accounts + if target_user.role != UserRole.user: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, 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 @@ -271,18 +293,18 @@ async def signup(request: Request, payload: SignupRequest, background: Backgroun verify_link = f"{frontend_url}/verify-email?token={verify_token}" verify_body = ( f"Hi {user.name},

" - f"Welcome to BookKeepro! Please verify your email address to activate your account.

" + f"Welcome! Please verify your email address to activate your account.

" f'' f"Verify My Email

" f"This link expires in 24 hours. If you did not sign up, ignore this email.

" - f"BookKeepro Team" + f"Support Team" ) background.add_task( send_email, to=user.email, - subject="Verify your BookKeepro email", + subject="Verify your email", body=verify_body, ) @@ -387,12 +409,12 @@ async def resend_verification( f'text-decoration:none;border-radius:6px;font-weight:600;">' f"Verify My Email

" f"This link expires in 24 hours.

" - f"BookKeepro Team" + f"Support Team" ) background.add_task( send_email, to=user.email, - subject="Verify your BookKeepro email", + subject="Verify your email", body=resend_body, ) 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), limit: int = Query(100, ge=1, le=500), tax_year: int = Query(None), + assigned_admin_id: str | None = Query(None), db: Session = Depends(get_db), current_user=Depends(get_current_user), _=Depends(require_admin), ): """ List users: - - super_admin β†’ sees all users (user + admin + super_admin) - - admin β†’ sees only role=user accounts - Supports skip/limit pagination. Returns pending_docs count per user. + - super_admin β†’ sees all users (user + admin + super_admin) and can filter by assigned_admin_id ("all", "unassigned", or specific admin id) + - 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 and assigned admin info. """ - from sqlalchemy import func as sqlfunc + from sqlalchemy import func as sqlfunc, or_ def _pending_count(uid: int) -> dict: 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: 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: - 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() users = q.offset(skip).limit(limit).all() @@ -541,11 +584,14 @@ def list_users_for_admin( return { "users": [ { - "id": u.id, - "name": u.name, - "email": u.email, - "phone": u.phone, - "role": u.role.value if hasattr(u.role, "value") else str(u.role), + "id": u.id, + "name": u.name, + "email": u.email, + "phone": u.phone, + "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) } 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"

Phone: {client.phone}

" if client.phone else "" + + email_body = f""" +
+
+

Admin Portal

+

Client Portfolio Assignment Notification

+
+
+

Hello {new_admin.name or 'Admin'},

+

Super Admin {super_admin_name} has assigned a client to your portfolio:

+
+

Client Name: {client_display}

+

Client Email: {client.email}

+ {phone_html} +
+

You now have administrative responsibility to review their uploaded documents, upload finalized tax returns, and assist them through filing.

+ +
+
+ This is an automated notification from the Admin Portal. +
+
+ """ + 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"
  • {name}
  • " for name in client_names[:10]) + if len(client_names) > 10: + items_html += f"
  • ...and {len(client_names) - 10} more clients
  • " + + email_body = f""" +
    +
    +

    Admin Portal

    +

    Batch Client Portfolio Assignment Notification

    +
    +
    +

    Hello {new_admin.name or 'Admin'},

    +

    Super Admin {super_admin_name} has assigned {count} client(s) to your portfolio:

    +
      + {items_html} +
    +

    You can view and manage these clients in your Admin Dashboard.

    + +
    +
    + This is an automated notification from the Admin Portal. +
    +
    + """ + 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}", + } + + + diff --git a/services/api/app/models.py b/services/api/app/models.py index 1d45d6f..d27c8f5 100644 --- a/services/api/app/models.py +++ b/services/api/app/models.py @@ -44,6 +44,9 @@ class User(Base): is_verified = Column(Integer, default=0, nullable=False) # 0 = unverified, 1 = verified created_at = Column(DateTime(timezone=True), server_default=func.now()) 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]) # ───────────────────────────────────────────── diff --git a/services/api/app/routers/chatbot.py b/services/api/app/routers/chatbot.py index 404dab1..b08da36 100644 --- a/services/api/app/routers/chatbot.py +++ b/services/api/app/routers/chatbot.py @@ -1,4 +1,4 @@ -ο»Ώimport logging +import logging import json import uuid from datetime import datetime, date, timezone @@ -11,7 +11,16 @@ import os import requests from pydantic import BaseModel, field_validator 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.auth.security import get_current_user, require_admin @@ -104,11 +113,34 @@ def get_admin_status( current_user=Depends(get_current_user), _=Depends(require_admin), ): + if not isinstance(tax_year, int): + tax_year = None + today_start = datetime.combine(date.today(), datetime.min.time(), tzinfo=timezone.utc) - total_users = db.query(User).count() - new_users_today = db.query(User).filter(User.created_at >= today_start).count() + + 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() + 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) + if is_standard_admin: + pq = pq.filter(PersonalDocument.user_id.in_(assigned_uids)) if assigned_uids else pq.filter(False) if tax_year: pq = pq.filter(PersonalDocument.tax_year == tax_year) 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() 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: bq = bq.filter(BusinessDocument.tax_year == tax_year) pending_business = bq.count() 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: admin_docs = admin_docs.filter(AdminDocument.tax_year == tax_year) pending_admin_returns = admin_docs.filter(AdminDocument.review_status == "pending").count() - recent_personal = ( - db.query(PersonalDocument).filter(PersonalDocument.deleted_at == None) - .order_by(PersonalDocument.uploaded_at.desc()).limit(10).all() - ) - recent_business = ( - db.query(BusinessDocument).filter(BusinessDocument.deleted_at == None) - .order_by(BusinessDocument.uploaded_at.desc()).limit(10).all() - ) - recent_admin = ( - db.query(AdminDocument).filter(AdminDocument.deleted_at == None) - .order_by(AdminDocument.uploaded_at.desc()).limit(10).all() - ) + rpq = db.query(PersonalDocument).filter(PersonalDocument.deleted_at == None) + rbq = db.query(BusinessDocument).filter(BusinessDocument.deleted_at == None) + raq = db.query(AdminDocument).filter(AdminDocument.deleted_at == None) + + if is_standard_admin: + if assigned_uids: + rpq = rpq.filter(PersonalDocument.user_id.in_(assigned_uids)) + rbq = rbq.filter(BusinessDocument.user_id.in_(assigned_uids)) + raq = raq.filter(AdminDocument.user_id.in_(assigned_uids)) + else: + 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( [{"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] + @@ -174,7 +216,7 @@ def get_daily_digest( _=Depends(require_admin), ): 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) return {"digest": digest_html, "generated_at": datetime.now().isoformat()} diff --git a/services/api/app/routers/contact.py b/services/api/app/routers/contact.py index 9dc8a09..3fa0453 100644 --- a/services/api/app/routers/contact.py +++ b/services/api/app/routers/contact.py @@ -38,7 +38,7 @@ async def contact_message(request: Request, form: ContactForm, background: Backg background.add_task( send_email, to=ADMIN_EMAIL, - subject="New Contact Enquiry Received β€” Follow-Up Required - BookKeepro", + subject="New Contact Enquiry Received β€” Follow-Up Required", body=f""" Dear Team,

    @@ -51,7 +51,7 @@ async def contact_message(request: Request, form: ContactForm, background: Backg Kindly follow up with the user at the earliest convenience.

    Thank you,
    - BookKeepro Support Team + Support Team """ ) @@ -59,13 +59,13 @@ async def contact_message(request: Request, form: ContactForm, background: Backg background.add_task( send_email, to=form.email, - subject="Thanks for contacting BookKeepro", + subject="Thanks for contacting us", body=f""" Hi {safe_first},

    - Thank you for reaching out to BookKeepro.
    + Thank you for reaching out.
    We’ve received your enquiry, and our team will get back to you shortly.

    Best Regards,
    - BookKeepro Team + Support Team """ ) diff --git a/services/api/app/routers/review.py b/services/api/app/routers/review.py index 487fe72..4a0b9be 100644 --- a/services/api/app/routers/review.py +++ b/services/api/app/routers/review.py @@ -35,7 +35,7 @@ async def submit_review( email_sent = await send_email( to=user.email, - subject="Documents Ready for Review β€” BookKeepro", + subject="Documents Ready for Review", body=f"""

    Dear {user.name or "Sir/Ma'am"},

    Your documents have been successfully submitted and are pending review.

    @@ -45,7 +45,7 @@ async def submit_review( πŸ‘‰ Go to Dashboard

    -

    Kind regards,
    BookKeepro Team

    +

    Kind regards,
    Support Team

    """ ) @@ -88,10 +88,10 @@ async def notify_user_review(
  • Business Documents: {payload.business_timeline} days
  • -

    Kind regards,
    BookKeepro Team

    +

    Kind regards,
    Support Team

    """ - 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}") # Save / reset filing deadlines if timelines were provided @@ -180,12 +180,12 @@ async def admin_doc_response( if payload.status == "rejected" and payload.reason: body += f"

    Reason:

    {payload.reason}

    " - body += "

    BookKeepro System

    " + body += "

    Admin Portal

    " background.add_task( send_email, to=admin_email, - subject=f"Admin Return Status {payload.status.capitalize()} β€” BookKeepro", + subject=f"Admin Return Status {payload.status.capitalize()}", body=body, ) @@ -394,7 +394,7 @@ async def send_return_for_approval( background.add_task( send_email, to=client.email, - subject="Action Required: Please Review Your Tax Return β€” BookKeepro", + subject="Action Required: Please Review Your Tax Return", body=f"""

    Dear {client.name or 'Client'},

    Your tax professional has prepared a document for your review:

    @@ -402,7 +402,7 @@ async def send_return_for_approval( {note_html}

    Please log in to your dashboard to review, approve, or request changes.

    Review Now β†’

    -

    Kind regards,
    BookKeepro Team

    +

    Kind regards,
    Support Team

    """, ) @@ -462,7 +462,7 @@ async def mark_filing_complete( background.add_task( send_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"""

    Dear {client.name or 'Client'},

    Great news! Your {payload.tax_year} tax return has been successfully filed.

    @@ -470,7 +470,7 @@ async def mark_filing_complete( {note_html}

    You can view the status in your dashboard at any time.

    Go to Dashboard β†’

    -

    Thank you for choosing BookKeepro.
    BookKeepro Team

    +

    Thank you.
    Support Team

    """, ) diff --git a/services/api/app/routers/upload.py b/services/api/app/routers/upload.py index 872611b..9ef9dfe 100644 --- a/services/api/app/routers/upload.py +++ b/services/api/app/routers/upload.py @@ -266,12 +266,12 @@ def get_view_url( @router.post("/admin-documents") async def upload_admin_document( + background: BackgroundTasks, file: UploadFile = File(...), doc_key: str = Form(...), doc_label: str = Form(...), user_id: int = Form(...), tax_year: int | None = Form(None), - background: BackgroundTasks = BackgroundTasks(), db: Session = Depends(get_db), current_user=Depends(get_current_user), _=Depends(require_admin), @@ -325,12 +325,12 @@ async def upload_admin_document( background.add_task( send_email, to=target_user.email, - subject="New Document Uploaded β€” BookKeepro", + subject="New Document Uploaded", body=f"""

    Dear {target_user.name or "Sir/Ma'am"},

    An admin has securely uploaded a new document ({doc_label}) to your account.

    -

    You can view this document by logging into your BookKeepro portal.

    -
    BookKeepro Team +

    You can view this document by logging into your portal.

    +
    Support Team """, ) @@ -552,14 +552,14 @@ async def upload_personal_document( background.add_task( send_email, to=admin.email, - subject="New Personal Document Uploaded β€” BookKeepro", + subject="New Personal Document Uploaded", body=f"

    {current_user.email} uploaded a personal document: {file.filename} ({doc_type}).

    ", ) background.add_task( send_email, to=current_user.email, - subject="Personal Document Upload Confirmation β€” BookKeepro", + subject="Personal Document Upload Confirmation", body=f"

    We have successfully received your personal document: {file.filename} ({doc_type}).

    ", ) background.add_task( @@ -725,14 +725,14 @@ async def upload_business_document( background.add_task( send_email, to=admin.email, - subject="New Business Document Uploaded β€” BookKeepro", + subject="New Business Document Uploaded", body=f"

    {current_user.email} uploaded a business document: {file.filename} ({doc_type}).

    ", ) background.add_task( send_email, to=current_user.email, - subject="Business Document Upload Confirmation β€” BookKeepro", + subject="Business Document Upload Confirmation", body=f"

    We have successfully received your business document: {file.filename} ({doc_type}).

    ", ) background.add_task( @@ -825,14 +825,14 @@ async def set_personal_review_status( background.add_task( send_email, to=owner.email, - subject="Action Required: Document Rejected β€” BookKeepro", + subject="Action Required: Document Rejected", body=f"""

    Dear {owner.name or 'Client'},

    Your personal document {doc.filename} (Tax Year {doc.tax_year}) has been rejected by our team.

    {note_html}

    Please log in to your dashboard, review the reason, and re-upload a corrected document.

    Re-upload Personal Documents β†’

    -

    Kind regards,
    BookKeepro Team

    +

    Kind regards,
    Support Team

    """, ) @@ -889,14 +889,14 @@ async def set_business_review_status( background.add_task( send_email, to=owner.email, - subject="Action Required: Document Rejected β€” BookKeepro", + subject="Action Required: Document Rejected", body=f"""

    Dear {owner.name or 'Client'},

    Your business document {doc.filename} (Tax Year {doc.tax_year}) has been rejected by our team.

    {note_html}

    Please log in to your dashboard, review the reason, and re-upload a corrected document.

    Re-upload Business Documents β†’

    -

    Kind regards,
    BookKeepro Team

    +

    Kind regards,
    Support Team

    """, ) @@ -1028,6 +1028,9 @@ def get_user_all_documents( "name": user.name, "email": user.email, "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": ( user.engagement_acknowledged_at.isoformat() if user.engagement_acknowledged_at else None @@ -1163,13 +1166,13 @@ async def notify_upload_complete( background.add_task( send_email, to=current_user.email, - subject=f"{category} Documents Uploaded β€” BookKeepro", + subject=f"{category} Documents Uploaded", body=f"""

    Dear {current_user.name or "Sir/Ma'am"},

    We received {count} {category.lower()} document{"s" if count != 1 else ""} from you.

    Our team will review {"them" if count != 1 else "it"} and update you shortly.

    -
    BookKeepro Team +
    Support Team """, ) 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( send_email, to=admin.email, - subject=f"New {category} Upload β€” BookKeepro", + subject=f"New {category} Upload", body=f"

    {current_user.email} uploaded " f"{count} {category.lower()} document{'s' if count != 1 else ''}.

    ", ) @@ -1203,11 +1206,11 @@ async def notify_personal_approval( background.add_task( send_email, to=user.email, - subject="Personal Documents Approved β€” BookKeepro", + subject="Personal Documents Approved", body=f"""

    Dear {user.name or "Sir/Ma'am"},

    Your personal documents have been successfully reviewed and approved.

    -
    BookKeepro Team +
    Support Team """, ) return {"status": "email_sent"} @@ -1226,11 +1229,11 @@ async def notify_business_approval( background.add_task( send_email, to=user.email, - subject="Business Documents Approved β€” BookKeepro", + subject="Business Documents Approved", body=f"""

    Dear {user.name or "Sir/Ma'am"},

    Your business documents have been successfully reviewed and approved.

    -
    BookKeepro Team +
    Support Team """, ) return {"status": "email_sent"} diff --git a/services/api/app/schemas.py b/services/api/app/schemas.py index 65ca3e6..71a17f5 100644 --- a/services/api/app/schemas.py +++ b/services/api/app/schemas.py @@ -75,6 +75,17 @@ class RoleChangeRequest(BaseModel): 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 # ───────────────────────────────────────────── diff --git a/services/api/app/utils/emailer.py b/services/api/app/utils/emailer.py index fa9f68e..867e9c9 100644 --- a/services/api/app/utils/emailer.py +++ b/services/api/app/utils/emailer.py @@ -32,7 +32,7 @@ async def send_email(to: str, subject: str, body: str) -> bool: if smtp_password: smtp_password = smtp_password.replace(" ", "") 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_ssl_tls = os.getenv("MAIL_SSL_TLS", "False").strip().lower() == "true" diff --git a/services/api/app/utils/login_email.py b/services/api/app/utils/login_email.py index 5e8ab33..2f9477c 100644 --- a/services/api/app/utils/login_email.py +++ b/services/api/app/utils/login_email.py @@ -11,7 +11,7 @@ async def send_signup_welcome_email(to: str, name: str | None = None):

    Dear {display_name},

    - Welcome to BookKeepro πŸŽ‰ + Welcome! πŸŽ‰

    @@ -26,7 +26,7 @@ async def send_signup_welcome_email(to: str, name: str | None = None):

    - πŸ‘‰ Login to BookKeepro + πŸ‘‰ Login to Dashboard

    @@ -36,12 +36,12 @@ async def send_signup_welcome_email(to: str, name: str | None = None):

    Kind regards,
    - BookKeepro Team + Support Team

    """ await send_email( to=to, - subject="Welcome to BookKeepro πŸŽ‰", + subject="Welcome πŸŽ‰", body=body ) diff --git a/services/api/app/utils/scheduler.py b/services/api/app/utils/scheduler.py index ad18adc..3ca303e 100644 --- a/services/api/app/utils/scheduler.py +++ b/services/api/app/utils/scheduler.py @@ -63,11 +63,11 @@ def _run_deadline_reminders():

    This is a reminder that your {doc_label} document filing deadline is in {label} ({dl.deadline_date.strftime('%B %d, %Y')}).

    Please ensure all outstanding actions are completed before the deadline.

    -

    Kind regards,
    BookKeepro Team

    +

    Kind regards,
    Support Team

    """ await send_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, ) @@ -78,7 +78,7 @@ def _run_deadline_reminders(): {user.name or user.email} ({user.email}) is in {label} ({dl.deadline_date.strftime('%B %d, %Y')}).

    Please review the client's status and take any necessary action.

    -

    BookKeepro System

    +

    Admin System

    """ for admin_email in admin_emails: await send_email( diff --git a/services/api/migrate.py b/services/api/migrate.py index 77e867a..b5a84b2 100644 --- a/services/api/migrate.py +++ b/services/api/migrate.py @@ -197,6 +197,29 @@ def upgrade(): except Exception as 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.") except Exception as e: