feat: add super admin user assignment, scoping, and clean email notifications

This commit is contained in:
Atharv1705
2026-10-30 16:07:46 +05:30
parent 1cca347752
commit b7c935df5a
13 changed files with 680 additions and 105 deletions
+59 -17
View File
@@ -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()}
+5 -5
View File
@@ -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
"""
)
+10 -10
View File
@@ -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>
""",
)
+22 -19
View File
@@ -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"}