Cleanup and bugfixes
This commit is contained in:
@@ -208,7 +208,7 @@ class ChatSession(Base):
|
||||
__tablename__ = "chat_sessions"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
session_id = Column(String(100), unique=True, index=True, nullable=False)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import os
|
||||
from datetime import date, timedelta
|
||||
import logging
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models import AdminDocument, User, UserRole, FilingDeadline
|
||||
from app.db import get_db
|
||||
@@ -300,3 +300,153 @@ def get_filing_deadlines(
|
||||
"is_overdue": days_left < 0,
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Gap #1: Admin sends a return to client for approval
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
class SendReturnRequest(BaseModel if False else object):
|
||||
pass
|
||||
|
||||
from pydantic import BaseModel as _BM
|
||||
|
||||
class SendReturnPayload(_BM):
|
||||
doc_id: int
|
||||
note: str = ""
|
||||
|
||||
|
||||
@router.post("/send-return-for-approval")
|
||||
async def send_return_for_approval(
|
||||
payload: SendReturnPayload,
|
||||
background: BackgroundTasks,
|
||||
db: Session = Depends(get_db),
|
||||
current_user=Depends(get_current_user),
|
||||
_=Depends(require_admin),
|
||||
):
|
||||
"""Admin marks an admin doc as 'sent_for_approval' and emails the client. Admin only."""
|
||||
doc = db.query(AdminDocument).filter_by(id=payload.doc_id).first()
|
||||
if not doc:
|
||||
raise HTTPException(status_code=404, detail="Document not found")
|
||||
|
||||
doc.review_status = "sent_for_approval"
|
||||
if payload.note:
|
||||
doc.review_note = payload.note
|
||||
db.commit()
|
||||
|
||||
crud.log_action(
|
||||
db, "sent_return_for_approval",
|
||||
user_id=current_user.id,
|
||||
target=f"admin_doc:{doc.id}",
|
||||
detail=f"client:{doc.user_id}",
|
||||
)
|
||||
|
||||
from app.models import DocumentReviewEvent
|
||||
event = DocumentReviewEvent(
|
||||
doc_kind="admin",
|
||||
doc_id=doc.id,
|
||||
owner_user_id=doc.user_id,
|
||||
actor_id=current_user.id,
|
||||
actor_role="admin",
|
||||
action="sent_for_approval",
|
||||
from_status="pending",
|
||||
to_status="sent_for_approval",
|
||||
comment=payload.note or None,
|
||||
tax_year=doc.tax_year,
|
||||
)
|
||||
db.add(event)
|
||||
db.commit()
|
||||
|
||||
client = db.query(User).filter_by(id=doc.user_id).first()
|
||||
if client:
|
||||
note_html = f"<p><em>{payload.note}</em></p>" if payload.note else ""
|
||||
background.add_task(
|
||||
send_email,
|
||||
to=client.email,
|
||||
subject="Action Required: Please Review Your Tax Return — BookKeepro",
|
||||
body=f"""
|
||||
<p>Dear {client.name or 'Client'},</p>
|
||||
<p>Your tax professional has prepared a document for your review:</p>
|
||||
<p><strong>{doc.doc_label}</strong> (Tax Year {doc.tax_year or 'N/A'})</p>
|
||||
{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>
|
||||
""",
|
||||
)
|
||||
|
||||
return {"status": "sent", "doc_id": doc.id, "review_status": doc.review_status}
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Gap #5: Mark a user's filing as fully filed/locked
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
class MarkFiledPayload(_BM):
|
||||
user_id: int
|
||||
tax_year: int
|
||||
note: str = ""
|
||||
|
||||
|
||||
@router.post("/mark-filed")
|
||||
async def mark_filing_complete(
|
||||
payload: MarkFiledPayload,
|
||||
background: BackgroundTasks,
|
||||
db: Session = Depends(get_db),
|
||||
current_user=Depends(get_current_user),
|
||||
_=Depends(require_admin),
|
||||
):
|
||||
"""Admin marks all approved docs for a user/year as 'filed'. Sends confirmation email."""
|
||||
from app.models import PersonalDocument, BusinessDocument
|
||||
|
||||
personal_docs = db.query(PersonalDocument).filter(
|
||||
PersonalDocument.user_id == payload.user_id,
|
||||
PersonalDocument.tax_year == payload.tax_year,
|
||||
PersonalDocument.deleted_at == None,
|
||||
PersonalDocument.review_status == "approved",
|
||||
).all()
|
||||
business_docs = db.query(BusinessDocument).filter(
|
||||
BusinessDocument.user_id == payload.user_id,
|
||||
BusinessDocument.tax_year == payload.tax_year,
|
||||
BusinessDocument.deleted_at == None,
|
||||
BusinessDocument.review_status == "approved",
|
||||
).all()
|
||||
|
||||
for doc in personal_docs:
|
||||
doc.review_status = "filed"
|
||||
for doc in business_docs:
|
||||
doc.review_status = "filed"
|
||||
db.commit()
|
||||
|
||||
crud.log_action(
|
||||
db, "filing_complete",
|
||||
user_id=current_user.id,
|
||||
target=f"user:{payload.user_id}",
|
||||
detail=f"tax_year:{payload.tax_year} personal:{len(personal_docs)} business:{len(business_docs)}",
|
||||
)
|
||||
|
||||
client = crud.get_user_by_id(db, payload.user_id)
|
||||
if client:
|
||||
note_html = f"<p><em>{payload.note}</em></p>" if payload.note else ""
|
||||
background.add_task(
|
||||
send_email,
|
||||
to=client.email,
|
||||
subject=f"Your {payload.tax_year} Tax Return Has Been Filed — BookKeepro",
|
||||
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>
|
||||
<p>Total documents filed: {len(personal_docs) + len(business_docs)}</p>
|
||||
{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>
|
||||
""",
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "filed",
|
||||
"user_id": payload.user_id,
|
||||
"tax_year": payload.tax_year,
|
||||
"personal_filed": len(personal_docs),
|
||||
"business_filed": len(business_docs),
|
||||
}
|
||||
|
||||
@@ -54,11 +54,12 @@ def semantic_search(
|
||||
).first()
|
||||
|
||||
if doc:
|
||||
d_type = doc.doc_type if doc_type == "personal" else doc.business_type
|
||||
doc_data = {
|
||||
"id": doc.id,
|
||||
"table": doc_type,
|
||||
"original_filename": doc.original_filename,
|
||||
"document_type": doc.document_type,
|
||||
"filename": doc.filename,
|
||||
"document_type": d_type,
|
||||
"uploaded_at": doc.uploaded_at,
|
||||
"relevance_score": res['distance']
|
||||
}
|
||||
|
||||
@@ -28,6 +28,8 @@ router = APIRouter(prefix="/api/upload", tags=["upload"])
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
FRONTEND_URL = os.getenv("FRONTEND_URL", "https://aiindiacpa.duckdns.org")
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Local File Storage (Contabo VPS Disk)
|
||||
# ─────────────────────────────────────────────
|
||||
@@ -89,6 +91,15 @@ def process_ai_extraction(table: str, doc_id: int, file_path: str, doc_type: str
|
||||
doc = db.query(model_class).filter_by(id=doc_id).first()
|
||||
if doc:
|
||||
doc.file_hash = file_hash
|
||||
# Fix H2: Prevent 'Processing...' forever by setting a placeholder
|
||||
doc.extracted_data = {
|
||||
"_meta": {
|
||||
"status": "unsupported",
|
||||
"label": "Data Not Available",
|
||||
"description": "AI extraction is not supported for this file type or no text was found.",
|
||||
"color": "gray"
|
||||
}
|
||||
}
|
||||
db.commit()
|
||||
return
|
||||
|
||||
@@ -474,13 +485,36 @@ async def upload_personal_document(
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
# Clean up the already-uploaded S3 object
|
||||
delete_from_storage(storage_key)
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="You have already uploaded this document for this tax year. "
|
||||
"Delete the existing one to replace it."
|
||||
)
|
||||
# Check if there's an existing rejected/deleted doc to replace (B4 fix: allow re-upload)
|
||||
existing = db.query(PersonalDocument).filter(
|
||||
PersonalDocument.user_id == current_user.id,
|
||||
PersonalDocument.doc_type == doc_type,
|
||||
PersonalDocument.tax_year == tax_year,
|
||||
).first()
|
||||
if existing and (existing.review_status == "rejected" or existing.deleted_at is not None):
|
||||
old_storage_key = existing.storage_key
|
||||
existing.filename = file.filename
|
||||
existing.storage_key = storage_key
|
||||
existing.content_type = file.content_type
|
||||
existing.review_status = "pending"
|
||||
existing.review_note = None
|
||||
existing.deleted_at = None
|
||||
existing.extracted_data = None
|
||||
existing.uploaded_at = func.now()
|
||||
db.commit()
|
||||
db.refresh(existing)
|
||||
record = existing
|
||||
if old_storage_key:
|
||||
delete_from_storage(old_storage_key)
|
||||
elif existing and existing.deleted_at is None:
|
||||
delete_from_storage(storage_key)
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="You have already uploaded this document for this tax year. Delete the existing one to replace it."
|
||||
)
|
||||
else:
|
||||
delete_from_storage(storage_key)
|
||||
raise HTTPException(status_code=409, detail="You have already uploaded this document for this tax year.")
|
||||
db.refresh(record)
|
||||
|
||||
# Append uploaded event
|
||||
@@ -621,12 +655,36 @@ async def upload_business_document(
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
delete_from_storage(storage_key)
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="You have already uploaded this document for this tax year. "
|
||||
"Delete the existing one to replace it."
|
||||
)
|
||||
# Check if there's an existing rejected doc to replace (B4 fix: allow re-upload)
|
||||
existing = db.query(BusinessDocument).filter(
|
||||
BusinessDocument.user_id == current_user.id,
|
||||
BusinessDocument.business_type == doc_type,
|
||||
BusinessDocument.tax_year == tax_year,
|
||||
).first()
|
||||
if existing and (existing.review_status == "rejected" or existing.deleted_at is not None):
|
||||
old_storage_key = existing.storage_key
|
||||
existing.filename = file.filename
|
||||
existing.storage_key = storage_key
|
||||
existing.content_type = file.content_type
|
||||
existing.review_status = "pending"
|
||||
existing.review_note = None
|
||||
existing.deleted_at = None
|
||||
existing.extracted_data = None
|
||||
existing.uploaded_at = func.now()
|
||||
db.commit()
|
||||
db.refresh(existing)
|
||||
record = existing
|
||||
if old_storage_key:
|
||||
delete_from_storage(old_storage_key)
|
||||
elif existing and existing.deleted_at is None:
|
||||
delete_from_storage(storage_key)
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="You have already uploaded this document for this tax year. Delete the existing one to replace it."
|
||||
)
|
||||
else:
|
||||
delete_from_storage(storage_key)
|
||||
raise HTTPException(status_code=409, detail="You have already uploaded this document for this tax year.")
|
||||
db.refresh(record)
|
||||
|
||||
# Append uploaded event
|
||||
@@ -702,9 +760,10 @@ def delete_business_document(
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
@router.patch("/personal-documents/{doc_id}/review-status")
|
||||
def set_personal_review_status(
|
||||
async def set_personal_review_status(
|
||||
doc_id: int,
|
||||
payload: ReviewStatusUpdate,
|
||||
background: BackgroundTasks,
|
||||
db: Session = Depends(get_db),
|
||||
current_user=Depends(get_current_user),
|
||||
_=Depends(require_admin),
|
||||
@@ -714,6 +773,7 @@ def set_personal_review_status(
|
||||
if not doc:
|
||||
raise HTTPException(status_code=404, detail="Document not found")
|
||||
|
||||
prev_status = doc.review_status
|
||||
doc.review_status = payload.status
|
||||
doc.review_note = payload.note
|
||||
db.commit()
|
||||
@@ -724,13 +784,34 @@ def set_personal_review_status(
|
||||
target=f"personal_doc:{doc_id}",
|
||||
detail=f"owner:{doc.user_id}" + (f" note:{payload.note}" if payload.note else ""),
|
||||
)
|
||||
|
||||
# Email client on rejection (Gap #3 fix)
|
||||
if payload.status == "rejected" and prev_status != "rejected":
|
||||
owner = db.query(User).filter_by(id=doc.user_id).first()
|
||||
if owner:
|
||||
note_html = f"<p><strong>Reason:</strong> {payload.note}</p>" if payload.note else ""
|
||||
background.add_task(
|
||||
send_email,
|
||||
to=owner.email,
|
||||
subject="Action Required: Document Rejected — BookKeepro",
|
||||
body=f"""
|
||||
<p>Dear {owner.name or 'Client'},</p>
|
||||
<p>Your personal document <strong>{doc.doc_type}</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>
|
||||
""",
|
||||
)
|
||||
|
||||
return {"id": doc_id, "review_status": payload.status}
|
||||
|
||||
|
||||
@router.patch("/business-documents/{doc_id}/review-status")
|
||||
def set_business_review_status(
|
||||
async def set_business_review_status(
|
||||
doc_id: int,
|
||||
payload: ReviewStatusUpdate,
|
||||
background: BackgroundTasks,
|
||||
db: Session = Depends(get_db),
|
||||
current_user=Depends(get_current_user),
|
||||
_=Depends(require_admin),
|
||||
@@ -740,6 +821,7 @@ def set_business_review_status(
|
||||
if not doc:
|
||||
raise HTTPException(status_code=404, detail="Document not found")
|
||||
|
||||
prev_status = doc.review_status
|
||||
doc.review_status = payload.status
|
||||
doc.review_note = payload.note
|
||||
db.commit()
|
||||
@@ -750,6 +832,26 @@ def set_business_review_status(
|
||||
target=f"business_doc:{doc_id}",
|
||||
detail=f"owner:{doc.user_id}" + (f" note:{payload.note}" if payload.note else ""),
|
||||
)
|
||||
|
||||
# Email client on rejection (Gap #3 fix)
|
||||
if payload.status == "rejected" and prev_status != "rejected":
|
||||
owner = db.query(User).filter_by(id=doc.user_id).first()
|
||||
if owner:
|
||||
note_html = f"<p><strong>Reason:</strong> {payload.note}</p>" if payload.note else ""
|
||||
background.add_task(
|
||||
send_email,
|
||||
to=owner.email,
|
||||
subject="Action Required: Document Rejected — BookKeepro",
|
||||
body=f"""
|
||||
<p>Dear {owner.name or 'Client'},</p>
|
||||
<p>Your business document <strong>{doc.business_type}</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>
|
||||
""",
|
||||
)
|
||||
|
||||
return {"id": doc_id, "review_status": payload.status}
|
||||
|
||||
|
||||
@@ -938,9 +1040,28 @@ def delete_user_completely(
|
||||
db.delete(doc)
|
||||
|
||||
# Clean up legacy uploaded_files rows to avoid FK constraint errors on db.delete(user)
|
||||
from app.models import UploadedFile
|
||||
from app.models import UploadedFile, ChatSession, ChatMessage
|
||||
db.query(UploadedFile).filter(UploadedFile.owner_id == user_id).delete()
|
||||
|
||||
# Fix B5: Delete user chat history to prevent FK constraint errors
|
||||
sessions = db.query(ChatSession).filter(ChatSession.user_id == user_id).all()
|
||||
for session in sessions:
|
||||
db.query(ChatMessage).filter(ChatMessage.session_id == session.id).delete()
|
||||
db.query(ChatSession).filter(ChatSession.user_id == user_id).delete()
|
||||
|
||||
# Manual cleanup for other tables without reliable ON DELETE CASCADE in older SQLite schemas
|
||||
from app.models import FilingDeadline, DocumentReviewEvent, AdminDocumentBookmark
|
||||
db.query(FilingDeadline).filter(FilingDeadline.user_id == user_id).delete()
|
||||
db.query(DocumentReviewEvent).filter(DocumentReviewEvent.owner_user_id == user_id).delete()
|
||||
db.query(AdminDocumentBookmark).filter(AdminDocumentBookmark.admin_id == user_id).delete()
|
||||
|
||||
# Delete embeddings
|
||||
try:
|
||||
delete_user_embeddings(user_id)
|
||||
logger.info(f"Deleted embeddings for user {user_id}")
|
||||
except Exception as emb_err:
|
||||
logger.error(f"Failed to delete embeddings for user {user_id}: {emb_err}")
|
||||
|
||||
# Log before deleting the user (audit_logs.user_id FK is SET NULL, so logs survive)
|
||||
crud.log_action(db, "delete_user", user_id=current_user.id, target=f"user:{user_id}", detail=f"{user.email}")
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ def _run_deadline_reminders():
|
||||
<p>Please ensure all outstanding actions are completed before the deadline.</p>
|
||||
<p>Kind regards,<br><strong>BookKeepro Team</strong></p>
|
||||
"""
|
||||
asyncio.get_event_loop().run_until_complete(
|
||||
asyncio.run(
|
||||
send_email(
|
||||
to=user.email,
|
||||
subject=f"Reminder: {doc_label} Filing Deadline in {label} — BookKeepro",
|
||||
@@ -82,7 +82,7 @@ def _run_deadline_reminders():
|
||||
<p><strong>BookKeepro System</strong></p>
|
||||
"""
|
||||
for admin_email in admin_emails:
|
||||
asyncio.get_event_loop().run_until_complete(
|
||||
asyncio.run(
|
||||
send_email(
|
||||
to=admin_email,
|
||||
subject=f"Admin Reminder: {user.email} — {doc_label} Deadline in {label}",
|
||||
|
||||
Reference in New Issue
Block a user