feat: add super admin user assignment, scoping, and clean email notifications
This commit is contained in:
@@ -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</a><br><br>"
|
||||
f"This link expires in 15 minutes.<br><br>"
|
||||
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},<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'style="padding:12px 24px;background:#FF7F11;color:#fff;'
|
||||
f'text-decoration:none;border-radius:6px;font-weight:600;">'
|
||||
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"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</a><br><br>"
|
||||
f"This link expires in 24 hours.<br><br>"
|
||||
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"<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
|
||||
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])
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
@@ -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()}
|
||||
|
||||
|
||||
@@ -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,
|
||||
<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.
|
||||
<br><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(
|
||||
send_email,
|
||||
to=form.email,
|
||||
subject="Thanks for contacting BookKeepro",
|
||||
subject="Thanks for contacting us",
|
||||
body=f"""
|
||||
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>
|
||||
Best Regards,<br>
|
||||
BookKeepro Team
|
||||
Support Team
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
@@ -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"""
|
||||
<p>Dear {user.name or "Sir/Ma'am"},</p>
|
||||
<p>Your documents have been successfully submitted and are pending review.</p>
|
||||
@@ -45,7 +45,7 @@ async def submit_review(
|
||||
👉 Go to Dashboard
|
||||
</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>
|
||||
"""
|
||||
)
|
||||
|
||||
@@ -88,10 +88,10 @@ async def notify_user_review(
|
||||
<li>Business Documents: {payload.business_timeline} days</li>
|
||||
</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}")
|
||||
|
||||
# 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"<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(
|
||||
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"""
|
||||
<p>Dear {client.name or 'Client'},</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}
|
||||
<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 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(
|
||||
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"""
|
||||
<p>Dear {client.name or 'Client'},</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}
|
||||
<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 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")
|
||||
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"""
|
||||
<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>You can view this document by logging into your BookKeepro portal.</p>
|
||||
<br><strong>BookKeepro Team</strong>
|
||||
<p>You can view this document by logging into your portal.</p>
|
||||
<br><strong>Support Team</strong>
|
||||
""",
|
||||
)
|
||||
|
||||
@@ -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"<p><strong>{current_user.email}</strong> uploaded a personal document: <strong>{file.filename}</strong> ({doc_type}).</p>",
|
||||
)
|
||||
|
||||
background.add_task(
|
||||
send_email,
|
||||
to=current_user.email,
|
||||
subject="Personal Document Upload Confirmation — BookKeepro",
|
||||
subject="Personal Document Upload Confirmation",
|
||||
body=f"<p>We have successfully received your personal document: <strong>{file.filename}</strong> ({doc_type}).</p>",
|
||||
)
|
||||
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"<p><strong>{current_user.email}</strong> uploaded a business document: <strong>{file.filename}</strong> ({doc_type}).</p>",
|
||||
)
|
||||
|
||||
background.add_task(
|
||||
send_email,
|
||||
to=current_user.email,
|
||||
subject="Business Document Upload Confirmation — BookKeepro",
|
||||
subject="Business Document Upload Confirmation",
|
||||
body=f"<p>We have successfully received your business document: <strong>{file.filename}</strong> ({doc_type}).</p>",
|
||||
)
|
||||
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"""
|
||||
<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>
|
||||
{note_html}
|
||||
<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 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(
|
||||
send_email,
|
||||
to=owner.email,
|
||||
subject="Action Required: Document Rejected — BookKeepro",
|
||||
subject="Action Required: Document Rejected",
|
||||
body=f"""
|
||||
<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>
|
||||
{note_html}
|
||||
<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 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,
|
||||
"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"""
|
||||
<p>Dear {current_user.name or "Sir/Ma'am"},</p>
|
||||
<p>We received <strong>{count}</strong> {category.lower()}
|
||||
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>
|
||||
<br><strong>BookKeepro Team</strong>
|
||||
<br><strong>Support Team</strong>
|
||||
""",
|
||||
)
|
||||
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"<p><strong>{current_user.email}</strong> uploaded "
|
||||
f"{count} {category.lower()} document{'s' if count != 1 else ''}.</p>",
|
||||
)
|
||||
@@ -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"""
|
||||
<p>Dear {user.name or "Sir/Ma'am"},</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"}
|
||||
@@ -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"""
|
||||
<p>Dear {user.name or "Sir/Ma'am"},</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"}
|
||||
|
||||
@@ -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
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ async def send_signup_welcome_email(to: str, name: str | None = None):
|
||||
<p>Dear {display_name},</p>
|
||||
|
||||
<p>
|
||||
Welcome to <strong>BookKeepro</strong> 🎉
|
||||
Welcome! 🎉
|
||||
</p>
|
||||
|
||||
<p>
|
||||
@@ -26,7 +26,7 @@ async def send_signup_welcome_email(to: str, name: str | None = None):
|
||||
<p>
|
||||
<a href="{_FRONTEND_URL}/login"
|
||||
style="color:#0077c8;font-weight:600;text-decoration:none;">
|
||||
👉 Login to BookKeepro
|
||||
👉 Login to Dashboard
|
||||
</a>
|
||||
</p>
|
||||
|
||||
@@ -36,12 +36,12 @@ async def send_signup_welcome_email(to: str, name: str | None = None):
|
||||
|
||||
<p style="margin-top:20px;">
|
||||
Kind regards,<br>
|
||||
<strong>BookKeepro Team</strong>
|
||||
<strong>Support Team</strong>
|
||||
</p>
|
||||
"""
|
||||
|
||||
await send_email(
|
||||
to=to,
|
||||
subject="Welcome to BookKeepro 🎉",
|
||||
subject="Welcome 🎉",
|
||||
body=body
|
||||
)
|
||||
|
||||
@@ -63,11 +63,11 @@ def _run_deadline_reminders():
|
||||
<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>
|
||||
<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(
|
||||
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():
|
||||
<strong>{user.name or user.email}</strong> ({user.email}) is in
|
||||
<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><strong>BookKeepro System</strong></p>
|
||||
<p><strong>Admin System</strong></p>
|
||||
"""
|
||||
for admin_email in admin_emails:
|
||||
await send_email(
|
||||
|
||||
Reference in New Issue
Block a user