chore: apply deployment fixes, timezone fixes, and cleanup unused dependencies
This commit is contained in:
+208
-110
@@ -1,12 +1,14 @@
|
||||
import logging
|
||||
from datetime import datetime, date, timedelta
|
||||
import json
|
||||
from datetime import datetime, date
|
||||
from fastapi import APIRouter, Depends, Request, Query
|
||||
from fastapi.responses import StreamingResponse
|
||||
from app.limiter import limiter
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import func, or_
|
||||
import os
|
||||
import requests
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, field_validator
|
||||
from fastapi import HTTPException
|
||||
from app.models import PersonalDocument, BusinessDocument, User, AuditLog
|
||||
from app.db import get_db
|
||||
@@ -16,16 +18,17 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/chatbot", tags=["chatbot"])
|
||||
|
||||
CHAT_MODEL = os.getenv("CHAT_MODEL", "meta-llama/llama-3.3-70b-instruct")
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# User: doc status
|
||||
# User: doc status (also includes extracted data so user can ask about fields)
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
@router.get("/doc-status")
|
||||
def get_doc_status(
|
||||
db: Session = Depends(get_db),
|
||||
current_user=Depends(get_current_user),
|
||||
):
|
||||
"""Return a consolidated summary of the user's document statuses."""
|
||||
personal = (
|
||||
db.query(PersonalDocument)
|
||||
.filter(PersonalDocument.user_id == current_user.id, PersonalDocument.deleted_at == None)
|
||||
@@ -41,12 +44,15 @@ def get_doc_status(
|
||||
|
||||
personal_list = [
|
||||
{"doc_type": d.doc_type, "status": d.review_status, "note": d.review_note,
|
||||
"tax_year": d.tax_year, "filename": d.filename}
|
||||
"tax_year": d.tax_year, "filename": d.filename,
|
||||
# Include extracted data summary so chatbot can answer field-level questions
|
||||
"extracted_summary": _summarize_extracted(d.extracted_data)}
|
||||
for d in personal
|
||||
]
|
||||
business_list = [
|
||||
{"business_type": d.business_type, "status": d.review_status, "note": d.review_note,
|
||||
"tax_year": d.tax_year, "filename": d.filename}
|
||||
"tax_year": d.tax_year, "filename": d.filename,
|
||||
"extracted_summary": _summarize_extracted(d.extracted_data)}
|
||||
for d in business
|
||||
]
|
||||
|
||||
@@ -74,6 +80,22 @@ def get_doc_status(
|
||||
"message": "".join(msg_lines)}
|
||||
|
||||
|
||||
def _summarize_extracted(extracted_data: dict | None) -> str:
|
||||
"""Convert extracted_data dict to a compact string for chatbot context."""
|
||||
if not extracted_data:
|
||||
return ""
|
||||
skip = {"_meta", "status"}
|
||||
parts = []
|
||||
for k, v in extracted_data.items():
|
||||
if k in skip or v is None:
|
||||
continue
|
||||
if isinstance(v, list):
|
||||
parts.append(f"{k}: {', '.join(str(i) for i in v[:3])}")
|
||||
else:
|
||||
parts.append(f"{k}: {v}")
|
||||
return " | ".join(parts[:8]) # cap at 8 fields to keep context small
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Admin: system overview stats
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
@@ -83,12 +105,9 @@ def get_admin_status(
|
||||
current_user=Depends(get_current_user),
|
||||
_=Depends(require_admin),
|
||||
):
|
||||
"""Return system-wide stats for the admin chatbot."""
|
||||
today_start = datetime.combine(date.today(), datetime.min.time())
|
||||
|
||||
total_users = db.query(User).count()
|
||||
new_users_today = db.query(User).filter(User.created_at >= today_start).count()
|
||||
|
||||
total_users = db.query(User).count()
|
||||
new_users_today = db.query(User).filter(User.created_at >= today_start).count()
|
||||
pending_personal = (
|
||||
db.query(PersonalDocument)
|
||||
.filter(PersonalDocument.review_status == "pending", PersonalDocument.deleted_at == None)
|
||||
@@ -100,48 +119,38 @@ def get_admin_status(
|
||||
.count()
|
||||
)
|
||||
|
||||
# Most recent 10 uploads across both tables
|
||||
recent_personal = (
|
||||
db.query(PersonalDocument)
|
||||
.filter(PersonalDocument.deleted_at == None)
|
||||
.order_by(PersonalDocument.uploaded_at.desc())
|
||||
.limit(10).all()
|
||||
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()
|
||||
db.query(BusinessDocument).filter(BusinessDocument.deleted_at == None)
|
||||
.order_by(BusinessDocument.uploaded_at.desc()).limit(10).all()
|
||||
)
|
||||
|
||||
# Merge and sort to get true top-10 latest
|
||||
recent_uploads = sorted(
|
||||
[{"user_id": d.user_id, "doc": d.doc_type, "type": "personal",
|
||||
[{"user_id": d.user_id, "doc": d.doc_type, "type": "personal",
|
||||
"uploaded_at": d.uploaded_at, "status": d.review_status} for d in recent_personal] +
|
||||
[{"user_id": d.user_id, "doc": d.business_type, "type": "business",
|
||||
[{"user_id": d.user_id, "doc": d.business_type, "type": "business",
|
||||
"uploaded_at": d.uploaded_at, "status": d.review_status} for d in recent_business],
|
||||
key=lambda x: x["uploaded_at"], reverse=True
|
||||
)[:10]
|
||||
|
||||
# Enrich with user names
|
||||
user_map = {u.id: u for u in db.query(User).filter(User.id.in_([r["user_id"] for r in recent_uploads])).all()}
|
||||
for r in recent_uploads:
|
||||
u = user_map.get(r["user_id"])
|
||||
r["user_name"] = u.name if u else "Unknown"
|
||||
r["user_email"] = u.email if u else "Unknown"
|
||||
r["user_name"] = u.name if u else "Unknown"
|
||||
r["user_email"] = u.email if u else "Unknown"
|
||||
r["uploaded_at"] = r["uploaded_at"].strftime("%Y-%m-%d %H:%M") if r["uploaded_at"] else "N/A"
|
||||
|
||||
total_pending = pending_personal + pending_business
|
||||
message = (
|
||||
f"<b>System Overview:</b><br><br>"
|
||||
f"• Total Users: <b>{total_users}</b> (<b>{new_users_today}</b> joined today)<br>"
|
||||
f"• Pending Personal Docs: <b>{pending_personal}</b><br>"
|
||||
f"• Pending Business Docs: <b>{pending_business}</b><br><br>"
|
||||
+ (f"You have <b>{total_pending}</b> documents awaiting review." if total_pending > 0
|
||||
else "All documents have been reviewed!")
|
||||
)
|
||||
total_pending = pending_personal + pending_business
|
||||
if total_pending > 0:
|
||||
message += f"You have <b>{total_pending}</b> documents awaiting review."
|
||||
else:
|
||||
message += "All documents have been reviewed!"
|
||||
|
||||
return {
|
||||
"total_users": total_users,
|
||||
@@ -155,59 +164,57 @@ def get_admin_status(
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Admin: rich context for a specific user (activity + docs)
|
||||
# Admin: daily digest (new)
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
@router.get("/daily-digest")
|
||||
def get_daily_digest(
|
||||
db: Session = Depends(get_db),
|
||||
current_user=Depends(get_current_user),
|
||||
_=Depends(require_admin),
|
||||
):
|
||||
"""Generate an AI plain-English summary of today's activity."""
|
||||
from app.utils.doc_intelligence import build_daily_digest
|
||||
stats = get_admin_status(db=db, current_user=current_user, _=None)
|
||||
digest_html = build_daily_digest(stats)
|
||||
return {"digest": digest_html, "generated_at": datetime.now().isoformat()}
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Admin: user context lookup
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
@router.get("/admin-user-context")
|
||||
def get_admin_user_context(
|
||||
query: str = Query(..., description="User name or email to search for"),
|
||||
query: str = Query(...),
|
||||
db: Session = Depends(get_db),
|
||||
current_user=Depends(get_current_user),
|
||||
_=Depends(require_admin),
|
||||
):
|
||||
"""Search for a user by name/email and return their full activity context."""
|
||||
q = f"%{query}%"
|
||||
user = (
|
||||
db.query(User)
|
||||
.filter(or_(User.name.ilike(q), User.email.ilike(q)))
|
||||
.first()
|
||||
)
|
||||
user = db.query(User).filter(or_(User.name.ilike(q), User.email.ilike(q))).first()
|
||||
if not user:
|
||||
return {"found": False, "message": f"No user found matching '{query}'."}
|
||||
|
||||
# Docs
|
||||
personal = db.query(PersonalDocument).filter(
|
||||
PersonalDocument.user_id == user.id, PersonalDocument.deleted_at == None
|
||||
).order_by(PersonalDocument.uploaded_at.desc()).all()
|
||||
|
||||
business = db.query(BusinessDocument).filter(
|
||||
BusinessDocument.user_id == user.id, BusinessDocument.deleted_at == None
|
||||
).order_by(BusinessDocument.uploaded_at.desc()).all()
|
||||
|
||||
# Audit log (last 20 actions)
|
||||
audit = (
|
||||
db.query(AuditLog)
|
||||
.filter(AuditLog.user_id == user.id)
|
||||
.order_by(AuditLog.created_at.desc())
|
||||
.limit(20).all()
|
||||
)
|
||||
audit = db.query(AuditLog).filter(AuditLog.user_id == user.id).order_by(AuditLog.created_at.desc()).limit(20).all()
|
||||
|
||||
return {
|
||||
"found": True,
|
||||
"user": {
|
||||
"id": user.id,
|
||||
"name": user.name,
|
||||
"email": user.email,
|
||||
"role": user.role.value if hasattr(user.role, "value") else str(user.role),
|
||||
"id": user.id, "name": user.name, "email": user.email,
|
||||
"role": user.role.value if hasattr(user.role, "value") else str(user.role),
|
||||
"joined": user.created_at.strftime("%Y-%m-%d") if user.created_at else "N/A",
|
||||
"engagement_acknowledged": bool(user.engagement_acknowledged_at),
|
||||
},
|
||||
"documents": {
|
||||
"personal": [{"doc_type": d.doc_type, "status": d.review_status,
|
||||
"tax_year": d.tax_year,
|
||||
"uploaded_at": d.uploaded_at.strftime("%Y-%m-%d %H:%M") if d.uploaded_at else "N/A"} for d in personal],
|
||||
"business": [{"business_type": d.business_type, "status": d.review_status,
|
||||
"tax_year": d.tax_year,
|
||||
"uploaded_at": d.uploaded_at.strftime("%Y-%m-%d %H:%M") if d.uploaded_at else "N/A"} for d in business],
|
||||
"personal": [{"doc_type": d.doc_type, "status": d.review_status, "tax_year": d.tax_year,
|
||||
"uploaded_at": d.uploaded_at.strftime("%Y-%m-%d %H:%M") if d.uploaded_at else "N/A"} for d in personal],
|
||||
"business": [{"business_type": d.business_type, "status": d.review_status, "tax_year": d.tax_year,
|
||||
"uploaded_at": d.uploaded_at.strftime("%Y-%m-%d %H:%M") if d.uploaded_at else "N/A"} for d in business],
|
||||
},
|
||||
"audit_log": [
|
||||
{"action": l.action, "detail": l.detail, "ip": l.ip_address,
|
||||
@@ -218,39 +225,102 @@ def get_admin_user_context(
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Shared chat endpoint
|
||||
# Admin: bulk action executor (approve/reject all docs for a user)
|
||||
# Requires explicit confirm=true to execute — safety gate
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
class BulkActionRequest(BaseModel):
|
||||
user_id: int
|
||||
action: str # "approve_personal" | "approve_business" | "reject_personal" | "reject_business"
|
||||
confirm: bool # must be True to execute — prevents accidental execution
|
||||
|
||||
@router.post("/admin-bulk-action")
|
||||
def admin_bulk_action(
|
||||
payload: BulkActionRequest,
|
||||
db: Session = Depends(get_db),
|
||||
current_user=Depends(get_current_user),
|
||||
_=Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Execute a bulk approve/reject action on all pending docs for a user.
|
||||
Requires confirm=true — the frontend must show a confirmation dialog first.
|
||||
"""
|
||||
if not payload.confirm:
|
||||
return {"status": "pending_confirm",
|
||||
"message": "Action not executed. Set confirm=true to proceed."}
|
||||
|
||||
user = db.query(User).filter(User.id == payload.user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
action_parts = payload.action.split("_") # e.g. ["approve", "personal"]
|
||||
if len(action_parts) != 2 or action_parts[0] not in ("approve", "reject") \
|
||||
or action_parts[1] not in ("personal", "business"):
|
||||
raise HTTPException(status_code=400, detail="Invalid action. Use approve_personal, reject_personal, approve_business, or reject_business.")
|
||||
|
||||
verb, doc_type = action_parts
|
||||
new_status = "approved" if verb == "approve" else "rejected"
|
||||
model_class = PersonalDocument if doc_type == "personal" else BusinessDocument
|
||||
|
||||
docs = db.query(model_class).filter(
|
||||
model_class.user_id == payload.user_id,
|
||||
model_class.review_status == "pending",
|
||||
model_class.deleted_at == None,
|
||||
).all()
|
||||
|
||||
count = 0
|
||||
for doc in docs:
|
||||
doc.review_status = new_status
|
||||
count += 1
|
||||
|
||||
db.commit()
|
||||
logger.info(f"Admin {current_user.id} bulk {new_status} {count} {doc_type} docs for user {payload.user_id}")
|
||||
|
||||
return {
|
||||
"status": "executed",
|
||||
"action": payload.action,
|
||||
"count": count,
|
||||
"message": f"{count} {doc_type} document(s) marked as {new_status}.",
|
||||
}
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Shared chat — streaming (new) + conversation memory via messages[]
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
class ChatMessage(BaseModel):
|
||||
role: str
|
||||
content: str
|
||||
reasoning_details: list | None = None
|
||||
|
||||
@field_validator("content")
|
||||
@classmethod
|
||||
def cap_content(cls, v: str) -> str:
|
||||
if len(v) > 4000:
|
||||
raise ValueError("Message must be 4000 characters or fewer")
|
||||
return v
|
||||
|
||||
class ChatRequest(BaseModel):
|
||||
messages: list[ChatMessage]
|
||||
stream: bool = False # client opts into streaming
|
||||
|
||||
|
||||
def _build_admin_context(db: Session, current_user) -> str:
|
||||
"""Build a rich real-time context string for the admin system prompt."""
|
||||
status = get_admin_status(db=db, current_user=current_user, _=None)
|
||||
|
||||
ctx = f"=== LIVE SYSTEM DATA (as of {datetime.now().strftime('%Y-%m-%d %H:%M')}) ===\n"
|
||||
ctx += f"Total registered users: {status['total_users']}\n"
|
||||
ctx += f"New users registered TODAY: {status['new_users_today']}\n"
|
||||
ctx += f"Pending personal docs (system-wide): {status['pending_personal']}\n"
|
||||
ctx += f"Pending business docs (system-wide): {status['pending_business']}\n"
|
||||
ctx += f"Pending personal docs: {status['pending_personal']}\n"
|
||||
ctx += f"Pending business docs: {status['pending_business']}\n"
|
||||
ctx += f"Total pending docs: {status['total_pending']}\n\n"
|
||||
|
||||
if status["recent_uploads"]:
|
||||
ctx += "=== MOST RECENT DOCUMENT UPLOADS ===\n"
|
||||
ctx += "=== MOST RECENT UPLOADS ===\n"
|
||||
for r in status["recent_uploads"]:
|
||||
ctx += (f"- {r['user_name']} ({r['user_email']}) uploaded a "
|
||||
f"{r['type']} doc '{r['doc']}' on {r['uploaded_at']} "
|
||||
f"[status: {r['status']}]\n")
|
||||
ctx += (f"- {r['user_name']} ({r['user_email']}) uploaded {r['type']} "
|
||||
f"'{r['doc']}' on {r['uploaded_at']} [{r['status']}]\n")
|
||||
return ctx
|
||||
|
||||
|
||||
@router.post("/ask")
|
||||
@limiter.limit("5/minute")
|
||||
@limiter.limit("10/minute")
|
||||
def ask_chatbot(
|
||||
request: Request,
|
||||
req: ChatRequest,
|
||||
@@ -266,11 +336,9 @@ def ask_chatbot(
|
||||
if is_admin:
|
||||
context = _build_admin_context(db, current_user)
|
||||
|
||||
# Check if the latest user message references a specific user — if so, fetch their data
|
||||
last_user_msg = next((m.content for m in reversed(req.messages) if m.role == "user"), "")
|
||||
user_context_addon = ""
|
||||
if any(kw in last_user_msg.lower() for kw in ["user", "who", "activity", "uploaded", "registered", "recent"]):
|
||||
# Try to find a name/email in the message
|
||||
words = last_user_msg.replace(",", " ").replace("?", " ").split()
|
||||
for word in words:
|
||||
if "@" in word or len(word) > 4:
|
||||
@@ -280,82 +348,112 @@ def ask_chatbot(
|
||||
docs = result["documents"]
|
||||
audit = result["audit_log"]
|
||||
user_context_addon = f"\n\n=== USER DETAIL: {u['name']} ({u['email']}) ===\n"
|
||||
user_context_addon += f"Role: {u['role']} | Joined: {u['joined']} | Engagement acknowledged: {u['engagement_acknowledged']}\n"
|
||||
user_context_addon += f"Role: {u['role']} | Joined: {u['joined']} | Engagement: {u['engagement_acknowledged']}\n"
|
||||
if docs["personal"]:
|
||||
user_context_addon += "Personal docs: " + "; ".join(
|
||||
f"{d['doc_type']} ({d['tax_year']}) [{d['status']}] uploaded {d['uploaded_at']}"
|
||||
for d in docs["personal"]) + "\n"
|
||||
user_context_addon += "Personal: " + "; ".join(
|
||||
f"{d['doc_type']} ({d['tax_year']}) [{d['status']}]" for d in docs["personal"]) + "\n"
|
||||
if docs["business"]:
|
||||
user_context_addon += "Business docs: " + "; ".join(
|
||||
f"{d['business_type']} ({d['tax_year']}) [{d['status']}] uploaded {d['uploaded_at']}"
|
||||
for d in docs["business"]) + "\n"
|
||||
user_context_addon += "Business: " + "; ".join(
|
||||
f"{d['business_type']} ({d['tax_year']}) [{d['status']}]" for d in docs["business"]) + "\n"
|
||||
if audit:
|
||||
user_context_addon += "Recent activity:\n" + "\n".join(
|
||||
f" [{a['at']}] {a['action']} — {a['detail'] or ''} (IP: {a['ip'] or 'N/A'})"
|
||||
for a in audit[:10]) + "\n"
|
||||
user_context_addon += "Activity:\n" + "\n".join(
|
||||
f" [{a['at']}] {a['action']} — {a['detail'] or ''}"
|
||||
for a in audit[:8]) + "\n"
|
||||
break
|
||||
|
||||
system_prompt = (
|
||||
"You are the BookKeepPro Admin Assistant — a knowledgeable, concise AI that has live access to the system's data.\n\n"
|
||||
"CAPABILITIES:\n"
|
||||
"- You can answer questions about which users uploaded documents and when.\n"
|
||||
"- You can report how many new users registered today or on any date.\n"
|
||||
"- You can show recent activity and document history for any specific user.\n"
|
||||
"- You can answer questions about document review status system-wide.\n\n"
|
||||
"RULES:\n"
|
||||
"- Only answer questions related to BookKeepPro administration, accounting, or taxes.\n"
|
||||
"- Use the live data below to answer. Do NOT make up user names, counts, or dates.\n"
|
||||
"- Be concise and direct. Format answers clearly.\n\n"
|
||||
"You are the BookKeepPro Admin Assistant with live access to system data.\n\n"
|
||||
"CAPABILITIES: Answer questions about uploads, user activity, pending docs, registration counts.\n"
|
||||
"BULK ACTIONS: When asked to approve/reject all docs for a user, respond with a structured "
|
||||
"JSON action block like: {\"bulk_action\": {\"user_id\": N, \"action\": \"approve_personal\", \"confirm\": false}} "
|
||||
"— the frontend will show a confirmation dialog before executing.\n"
|
||||
"RULES: Only answer BookKeepPro, accounting, or tax questions. Use live data. Be concise.\n\n"
|
||||
f"{context}{user_context_addon}"
|
||||
)
|
||||
else:
|
||||
doc_status = get_doc_status(db=db, current_user=current_user)
|
||||
summary = doc_status["summary"]
|
||||
context = f"Total Documents: {summary['total']}\nPending: {summary['pending']}\nApproved: {summary['approved']}\nRejected: {summary['rejected']}\n"
|
||||
context = f"Total: {summary['total']} | Pending: {summary['pending']} | Approved: {summary['approved']} | Rejected: {summary['rejected']}\n"
|
||||
|
||||
if doc_status["personal"]:
|
||||
context += "\nPersonal Documents:\n"
|
||||
for d in doc_status["personal"]:
|
||||
note = f" — Admin note: {d['note']}" if d['note'] else ""
|
||||
context += f" • {d['doc_type']} ({d['tax_year']}): {d['status']}{note}\n"
|
||||
note = f" — Note: {d['note']}" if d['note'] else ""
|
||||
extracted = f" | Data: {d['extracted_summary']}" if d['extracted_summary'] else ""
|
||||
context += f" • {d['doc_type']} ({d['tax_year']}): {d['status']}{note}{extracted}\n"
|
||||
if doc_status["business"]:
|
||||
context += "\nBusiness Documents:\n"
|
||||
for d in doc_status["business"]:
|
||||
note = f" — Admin note: {d['note']}" if d['note'] else ""
|
||||
context += f" • {d['business_type']} ({d['tax_year']}): {d['status']}{note}\n"
|
||||
note = f" — Note: {d['note']}" if d['note'] else ""
|
||||
extracted = f" | Data: {d['extracted_summary']}" if d['extracted_summary'] else ""
|
||||
context += f" • {d['business_type']} ({d['tax_year']}): {d['status']}{note}{extracted}\n"
|
||||
|
||||
system_prompt = (
|
||||
"You are the BookKeepPro Assistant. Help users with this application and basic accounting/tax questions.\n\n"
|
||||
"APPLICATION FLOW:\n"
|
||||
"- Upload documents: Dashboard → Personal Upload or Business Upload page → drag & drop or click to browse.\n"
|
||||
"- Check status: Documents show Pending (waiting for admin), Approved, or Rejected.\n"
|
||||
"- If rejected: see the admin's note on the upload page and re-upload a corrected version.\n"
|
||||
"- Profile: update your name, phone, or password on the Profile page.\n\n"
|
||||
"RULES:\n"
|
||||
"- Only answer questions about BookKeepPro, accounting, or taxes.\n"
|
||||
"- Use the live data below to answer questions about the user's documents.\n\n"
|
||||
"You are the BookKeepPro Assistant. Help users with the app and basic accounting/tax questions.\n\n"
|
||||
"UPLOAD GUIDANCE: If user wants to upload a document, tell them:\n"
|
||||
"- Personal docs → go to /upload-personal\n"
|
||||
"- Business docs → go to /upload-business\n"
|
||||
"- You can also say: 'Click here: [Upload Personal](/upload-personal)'\n\n"
|
||||
"EXTRACTED DATA: You have access to key fields extracted from the user's documents. "
|
||||
"Use this to answer specific questions like 'what is my PAN number' or 'what does my W-2 show'.\n\n"
|
||||
"RULES: Only answer BookKeepPro, accounting, or tax questions.\n\n"
|
||||
f"=== LIVE DATA for {current_user.name or current_user.email} ===\n{context}"
|
||||
)
|
||||
|
||||
# Conversation memory: messages[] from request already contains full history
|
||||
# The frontend persists this in localStorage and replays it on each call
|
||||
messages = [{"role": "system", "content": system_prompt}]
|
||||
for m in req.messages:
|
||||
messages.append({"role": m.role, "content": m.content})
|
||||
|
||||
# ── Streaming path ────────────────────────────────────────────────────────
|
||||
if req.stream:
|
||||
def _stream():
|
||||
try:
|
||||
resp = requests.post(
|
||||
url="https://openrouter.ai/api/v1/chat/completions",
|
||||
headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
|
||||
json={"model": CHAT_MODEL, "messages": messages, "stream": True},
|
||||
stream=True,
|
||||
timeout=60,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
for line in resp.iter_lines():
|
||||
if line and line != b"data: [DONE]":
|
||||
raw = line.decode("utf-8")
|
||||
if raw.startswith("data: "):
|
||||
raw = raw[6:]
|
||||
try:
|
||||
chunk = json.loads(raw)
|
||||
delta = chunk["choices"][0].get("delta", {})
|
||||
token = delta.get("content", "")
|
||||
if token:
|
||||
# Send SSE event
|
||||
yield f"data: {json.dumps({'token': token})}\n\n"
|
||||
except Exception:
|
||||
pass
|
||||
yield "data: [DONE]\n\n"
|
||||
except Exception as e:
|
||||
logger.error(f"Streaming error: {e}")
|
||||
yield f"data: {json.dumps({'error': str(e)})}\n\n"
|
||||
|
||||
return StreamingResponse(_stream(), media_type="text/event-stream")
|
||||
|
||||
# ── Non-streaming path (default) ─────────────────────────────────────────
|
||||
try:
|
||||
response = requests.post(
|
||||
url="https://openrouter.ai/api/v1/chat/completions",
|
||||
headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
|
||||
json={"model": "meta-llama/llama-3.3-70b-instruct", "messages": messages},
|
||||
json={"model": CHAT_MODEL, "messages": messages},
|
||||
timeout=30,
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
if "error" in data:
|
||||
logger.error(f"OpenRouter error: {data['error']}")
|
||||
raise HTTPException(status_code=502, detail="AI service overloaded. Please try again.")
|
||||
if "choices" not in data:
|
||||
raise HTTPException(status_code=502, detail="Unexpected AI response. Please try again.")
|
||||
raise HTTPException(status_code=502, detail="Unexpected AI response.")
|
||||
|
||||
return data["choices"][0]["message"]
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import os
|
||||
from fastapi import APIRouter, BackgroundTasks, HTTPException, Request
|
||||
from app.limiter import limiter
|
||||
from pydantic import BaseModel, EmailStr
|
||||
from pydantic import BaseModel, EmailStr, field_validator
|
||||
from app.utils.emailer import send_email
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["contact"])
|
||||
@@ -16,6 +16,13 @@ class ContactForm(BaseModel):
|
||||
phone: str
|
||||
message: str = ""
|
||||
|
||||
@field_validator("message")
|
||||
@classmethod
|
||||
def cap_message(cls, v: str) -> str:
|
||||
if len(v) > 2000:
|
||||
raise ValueError("Message must be 2000 characters or fewer")
|
||||
return v
|
||||
|
||||
@router.post("/contact")
|
||||
@limiter.limit("5/minute")
|
||||
async def contact_message(request: Request, form: ContactForm, background: BackgroundTasks):
|
||||
|
||||
@@ -8,9 +8,6 @@ from fastapi import APIRouter, BackgroundTasks, UploadFile, File, HTTPException,
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
import boto3
|
||||
from botocore.client import Config
|
||||
from botocore.exceptions import ClientError
|
||||
from jose import jwt, JWTError
|
||||
from datetime import timedelta
|
||||
|
||||
@@ -39,20 +36,61 @@ UPLOAD_DIR = BASE_DIR / "uploads"
|
||||
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def process_ai_extraction(table: str, doc_id: int, file_path: str, doc_type: str):
|
||||
extracted = extract_document_data(file_path, doc_type)
|
||||
if extracted is None:
|
||||
return
|
||||
|
||||
import hashlib
|
||||
|
||||
# Compute SHA-256 hash of the file for deduplication (Item 3)
|
||||
try:
|
||||
with open(file_path, "rb") as f:
|
||||
file_hash = hashlib.sha256(f.read()).hexdigest()
|
||||
except Exception as e:
|
||||
logger.warning(f"[AI] Could not hash file {file_path}: {e}. Proceeding without dedup.")
|
||||
file_hash = None
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
if table == "personal":
|
||||
doc = db.query(PersonalDocument).filter_by(id=doc_id).first()
|
||||
else:
|
||||
doc = db.query(BusinessDocument).filter_by(id=doc_id).first()
|
||||
|
||||
model_class = PersonalDocument if table == "personal" else BusinessDocument
|
||||
|
||||
# Check if another doc with the same file hash already has extracted data
|
||||
if file_hash:
|
||||
cached = (
|
||||
db.query(model_class)
|
||||
.filter(
|
||||
model_class.file_hash == file_hash,
|
||||
model_class.extracted_data != None,
|
||||
model_class.id != doc_id,
|
||||
model_class.deleted_at == None,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if cached:
|
||||
logger.info(
|
||||
f"[AI] Cache hit for hash {file_hash[:12]}… — "
|
||||
f"copying extracted_data from doc id={cached.id} (skipping API call)"
|
||||
)
|
||||
doc = db.query(model_class).filter_by(id=doc_id).first()
|
||||
if doc:
|
||||
doc.extracted_data = cached.extracted_data
|
||||
doc.file_hash = file_hash
|
||||
db.commit()
|
||||
return
|
||||
|
||||
# No cache — run full extraction
|
||||
extracted = extract_document_data(file_path, doc_type)
|
||||
if extracted is None:
|
||||
# Still save the hash so we don't keep retrying a file that always fails
|
||||
if file_hash:
|
||||
doc = db.query(model_class).filter_by(id=doc_id).first()
|
||||
if doc:
|
||||
doc.file_hash = file_hash
|
||||
db.commit()
|
||||
return
|
||||
|
||||
doc = db.query(model_class).filter_by(id=doc_id).first()
|
||||
if doc:
|
||||
doc.extracted_data = extracted
|
||||
doc.file_hash = file_hash
|
||||
db.commit()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to update DB with AI extraction: {e}")
|
||||
finally:
|
||||
@@ -291,7 +329,7 @@ def list_admin_documents(
|
||||
"doc_label": d.doc_label,
|
||||
"filename": d.filename,
|
||||
"storage_key": d.storage_key,
|
||||
"created_at": d.uploaded_at.isoformat() if d.uploaded_at else None,
|
||||
"created_at": d.uploaded_at.isoformat() + "Z" if d.uploaded_at else None,
|
||||
}
|
||||
for d in docs
|
||||
]
|
||||
@@ -670,7 +708,7 @@ def get_user_all_documents(
|
||||
"doc_type": d.doc_type,
|
||||
"filename": d.filename,
|
||||
"storage_key": d.storage_key,
|
||||
"uploaded_at": d.uploaded_at.isoformat() if d.uploaded_at else None,
|
||||
"uploaded_at": d.uploaded_at.isoformat() + "Z" if d.uploaded_at else None,
|
||||
"tax_year": d.tax_year,
|
||||
"review_status": d.review_status,
|
||||
"review_note": d.review_note,
|
||||
@@ -684,7 +722,7 @@ def get_user_all_documents(
|
||||
"doc_type": d.business_type,
|
||||
"filename": d.filename,
|
||||
"storage_key": d.storage_key,
|
||||
"uploaded_at": d.uploaded_at.isoformat() if d.uploaded_at else None,
|
||||
"uploaded_at": d.uploaded_at.isoformat() + "Z" if d.uploaded_at else None,
|
||||
"tax_year": d.tax_year,
|
||||
"review_status": d.review_status,
|
||||
"review_note": d.review_note,
|
||||
@@ -758,13 +796,13 @@ def delete_user_completely(
|
||||
delete_from_storage(doc.storage_key)
|
||||
db.delete(doc)
|
||||
|
||||
# Clean up legacy uploaded_files rows and audit logs to avoid FK constraint errors on db.delete(user)
|
||||
from app.models import UploadedFile, AuditLog
|
||||
# Clean up legacy uploaded_files rows to avoid FK constraint errors on db.delete(user)
|
||||
from app.models import UploadedFile
|
||||
db.query(UploadedFile).filter(UploadedFile.owner_id == user_id).delete()
|
||||
db.query(AuditLog).filter(AuditLog.user_id == user_id).delete()
|
||||
|
||||
db.commit()
|
||||
crud.log_action(db, "delete_user", user_id=current_user.id, target=f"user:{user_id}")
|
||||
# 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}")
|
||||
|
||||
db.delete(user)
|
||||
db.commit()
|
||||
except Exception as e:
|
||||
@@ -895,7 +933,7 @@ def list_templates(
|
||||
{
|
||||
"id": t.id,
|
||||
"name": t.name,
|
||||
"download": t.file_url,
|
||||
"download": get_presigned_url(t.file_url) if t.file_url else None,
|
||||
}
|
||||
for t in templates
|
||||
]
|
||||
@@ -917,7 +955,7 @@ async def upload_template(
|
||||
file_url = None
|
||||
if file and file.filename:
|
||||
storage_key = await upload_to_storage(file)
|
||||
file_url = get_presigned_url(storage_key)
|
||||
file_url = storage_key # Store raw key; presigned URLs are generated on-demand in GET
|
||||
|
||||
record = RequiredDocumentTemplate(
|
||||
category=category,
|
||||
@@ -937,7 +975,7 @@ async def upload_template(
|
||||
return {
|
||||
"id": record.id,
|
||||
"name": record.name,
|
||||
"download": record.file_url,
|
||||
"download": get_presigned_url(record.file_url) if record.file_url else None,
|
||||
}
|
||||
|
||||
@router.delete("/admin/templates/{template_id}")
|
||||
@@ -954,9 +992,8 @@ def delete_template(
|
||||
if not record:
|
||||
raise HTTPException(status_code=404, detail="Template not found")
|
||||
|
||||
if record.file_url and record.file_url.startswith("/uploads/"):
|
||||
storage_key = record.file_url.split("/uploads/")[1]
|
||||
delete_from_storage(storage_key)
|
||||
if record.file_url:
|
||||
delete_from_storage(record.file_url)
|
||||
|
||||
db.delete(record)
|
||||
db.commit()
|
||||
|
||||
Reference in New Issue
Block a user