feat/fix: implement chatbot session persistence, resolve auth redirect loops, and polish UI

This commit is contained in:
Atharv1705
2026-08-25 15:30:16 +05:30
parent bf1a019d6c
commit e0f6167d14
69 changed files with 2106 additions and 394 deletions
+46 -6
View File
@@ -1,9 +1,10 @@
import os
import logging
from pathlib import Path
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from fastapi.responses import FileResponse, PlainTextResponse
from slowapi import _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from app.limiter import limiter
@@ -85,15 +86,34 @@ DIST_DIR = os.path.join(FRONTEND_DIR, "dist")
SPA_INDEX = os.path.join(DIST_DIR, "index.html")
def _mount_if_exists(route: str, path: str, name: str) -> None:
class CachedStaticFiles(StaticFiles):
"""StaticFiles subclass that injects Cache-Control headers."""
def __init__(self, *args, max_age: int = 86400, immutable: bool = False, **kwargs):
super().__init__(*args, **kwargs)
parts = [f"public, max-age={max_age}"]
if immutable:
parts.append("immutable")
self._cache_control = ", ".join(parts)
async def get_response(self, path, scope): # type: ignore[override]
resp = await super().get_response(path, scope)
resp.headers["Cache-Control"] = self._cache_control
return resp
def _mount_cached(route: str, path: str, name: str, **kwargs) -> None:
if os.path.isdir(path):
app.mount(route, StaticFiles(directory=path), name=name)
app.mount(route, CachedStaticFiles(directory=path, **kwargs), name=name)
log.info("Mounted static %s → %s", route, path)
_mount_if_exists("/css", os.path.join(DIST_DIR, "css"), "css")
_mount_if_exists("/assets", os.path.join(DIST_DIR, "assets"), "assets")
_mount_if_exists("/images", os.path.join(DIST_DIR, "images"), "images")
# Hashed filenames — cache forever
_mount_cached("/assets", os.path.join(DIST_DIR, "assets"), "assets",
max_age=31_536_000, immutable=True)
# Images & CSS — cache for 1 day
_mount_cached("/css", os.path.join(DIST_DIR, "css"), "css", max_age=86_400)
_mount_cached("/images", os.path.join(DIST_DIR, "images"), "images", max_age=86_400)
# Ensure uploads directory exists
UPLOAD_DIR = os.path.abspath(os.path.join(FRONTEND_DIR, "..", "uploads"))
@@ -113,6 +133,26 @@ def logout():
return {"message": "Logged out"}
# ─────────────────────────────────────────────
# Crawler files — must be served BEFORE the SPA catch-all
# ─────────────────────────────────────────────
@app.get("/robots.txt", tags=["seo"])
def robots_txt():
robots_path = os.path.join(DIST_DIR, "robots.txt")
if os.path.isfile(robots_path):
return FileResponse(robots_path, media_type="text/plain")
return PlainTextResponse("User-agent: *\nAllow: /\n")
@app.get("/llms.txt", tags=["seo"])
def llms_txt():
llms_path = os.path.join(DIST_DIR, "llms.txt")
if os.path.isfile(llms_path):
return FileResponse(llms_path, media_type="text/plain")
return PlainTextResponse("# BookKeepPro\n")
# ─────────────────────────────────────────────
# SPA catch-all — serve index.html for all non-API routes
# React Router handles client-side navigation
+40 -1
View File
@@ -7,6 +7,7 @@ from sqlalchemy import (
Index,
Integer,
String,
Text,
JSON,
UniqueConstraint,
func,
@@ -121,6 +122,9 @@ class AdminDocument(Base):
uploaded_by = Column(Integer, ForeignKey("users.id"), nullable=False) # admin user
user_id = Column(Integer, ForeignKey("users.id"), nullable=False) # target client
deleted_at = Column(DateTime(timezone=True), nullable=True, default=None)
# AI-generated plain-English summary — populated by background task after upload
# None = still processing, non-null = ready to display
ai_summary = Column(Text, nullable=True)
admin = relationship("User", foreign_keys=[uploaded_by])
user = relationship("User", foreign_keys=[user_id])
@@ -177,9 +181,44 @@ class RequiredDocumentTemplate(Base):
category = Column(String(50), nullable=False) # 'personal' or 'business'
tax_year = Column(Integer, nullable=False)
name = Column(String(200), nullable=False)
file_url = Column(String(500), nullable=True) # Null if there is no template file to download
# storage_key: raw filename on disk (e.g. "abc123.pdf"). Fresh presigned URLs
# are generated on every read from this key. Replaces the old file_url pattern
# that baked an expiring JWT into the stored value.
storage_key = Column(String(500), nullable=True)
# file_url kept for backward-compat; self-healed at read time if storage_key is missing
file_url = Column(String(500), nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
__table_args__ = (
UniqueConstraint("category", "tax_year", "name", name="uq_template_cat_year_name"),
)
# ─────────────────────────────────────────────
# Chat Models
# ─────────────────────────────────────────────
class ChatSession(Base):
__tablename__ = "chat_sessions"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), 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())
messages = relationship("ChatMessage", back_populates="session", cascade="all, delete-orphan", order_by="ChatMessage.created_at")
class ChatMessage(Base):
__tablename__ = "chat_messages"
id = Column(Integer, primary_key=True, index=True)
session_id = Column(Integer, ForeignKey("chat_sessions.id"), nullable=False)
role = Column(String(50), nullable=False) # 'user', 'assistant', 'system', 'tool'
content = Column(Text, nullable=True)
tool_calls = Column(JSON, nullable=True)
tool_call_id = Column(String(200), nullable=True)
name = Column(String(200), nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
session = relationship("ChatSession", back_populates="messages")
+227 -76
View File
@@ -1,5 +1,6 @@
import logging
import json
import uuid
from datetime import datetime, date
from fastapi import APIRouter, Depends, Request, Query
from fastapi.responses import StreamingResponse
@@ -10,7 +11,7 @@ import os
import requests
from pydantic import BaseModel, field_validator
from fastapi import HTTPException
from app.models import PersonalDocument, BusinessDocument, User, AuditLog
from app.models import PersonalDocument, BusinessDocument, User, AuditLog, ChatSession, ChatMessage as DBChatMessage
from app.db import get_db
from app.auth.security import get_current_user, require_admin
@@ -20,7 +21,6 @@ router = APIRouter(prefix="/api/chatbot", tags=["chatbot"])
CHAT_MODEL = os.getenv("CHAT_MODEL", "meta-llama/llama-3.3-70b-instruct")
# ─────────────────────────────────────────────────────────────────────────────
# User: doc status (also includes extracted data so user can ask about fields)
# ─────────────────────────────────────────────────────────────────────────────
@@ -45,7 +45,6 @@ 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,
# Include extracted data summary so chatbot can answer field-level questions
"extracted_summary": _summarize_extracted(d.extracted_data)}
for d in personal
]
@@ -81,7 +80,6 @@ def get_doc_status(
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"}
@@ -93,7 +91,7 @@ def _summarize_extracted(extracted_data: dict | None) -> str:
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
return " | ".join(parts[:8])
# ─────────────────────────────────────────────────────────────────────────────
@@ -132,7 +130,7 @@ def get_admin_status(
"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",
"uploaded_at": d.uploaded_at, "status": d.review_status} for d in recent_business],
key=lambda x: x["uploaded_at"], reverse=True
key=lambda x: x["uploaded_at"].isoformat() if x["uploaded_at"] else "", reverse=True
)[:10]
user_map = {u.id: u for u in db.query(User).filter(User.id.in_([r["user_id"] for r in recent_uploads])).all()}
@@ -163,25 +161,18 @@ def get_admin_status(
}
# ─────────────────────────────────────────────────────────────────────────────
# 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(...),
@@ -224,14 +215,10 @@ def get_admin_user_context(
}
# ─────────────────────────────────────────────────────────────────────────────
# 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
action: str
confirm: bool
@router.post("/admin-bulk-action")
def admin_bulk_action(
@@ -240,10 +227,6 @@ def admin_bulk_action(
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."}
@@ -252,10 +235,10 @@ def admin_bulk_action(
if not user:
raise HTTPException(status_code=404, detail="User not found")
action_parts = payload.action.split("_") # e.g. ["approve", "personal"]
action_parts = payload.action.split("_")
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.")
raise HTTPException(status_code=400, detail="Invalid action.")
verb, doc_type = action_parts
new_status = "approved" if verb == "approve" else "rejected"
@@ -284,24 +267,27 @@ def admin_bulk_action(
# ─────────────────────────────────────────────────────────────────────────────
# Shared chat — streaming (new) + conversation memory via messages[]
# Shared chat — streaming (new) + conversation memory via DB
# ─────────────────────────────────────────────────────────────────────────────
class ChatMessage(BaseModel):
class ChatMessageInput(BaseModel):
role: str
content: str
reasoning_details: list | None = None
content: str | None = None
tool_calls: list | None = None
tool_call_id: str | None = None
name: str | None = None
@field_validator("content")
@classmethod
def cap_content(cls, v: str) -> str:
if len(v) > 4000:
def cap_content(cls, v: str | None) -> str | None:
if v and 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
message: str | None = None
messages: list[ChatMessageInput] | None = None
stream: bool = False
session_id: str | None = None
def _build_admin_context(db: Session, current_user) -> str:
status = get_admin_status(db=db, current_user=current_user, _=None)
@@ -318,6 +304,37 @@ def _build_admin_context(db: Session, current_user) -> str:
f"'{r['doc']}' on {r['uploaded_at']} [{r['status']}]\n")
return ctx
@router.get("/history")
def get_chat_history(
session_id: str | None = None,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
):
if not session_id:
return {"session_id": str(uuid.uuid4()), "messages": []}
session = db.query(ChatSession).filter(
ChatSession.session_id == session_id,
ChatSession.user_id == current_user.id
).first()
if not session:
return {"session_id": session_id, "messages": []}
msgs = []
for m in session.messages:
if m.role == "system":
continue
msg = {"role": m.role, "content": m.content}
if m.tool_calls:
msg["tool_calls"] = m.tool_calls
if m.tool_call_id:
msg["tool_call_id"] = m.tool_call_id
if m.name:
msg["name"] = m.name
msgs.append(msg)
return {"session_id": session_id, "messages": msgs}
@router.post("/ask")
@limiter.limit("10/minute")
@@ -335,40 +352,15 @@ def ask_chatbot(
if is_admin:
context = _build_admin_context(db, current_user)
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"]):
words = last_user_msg.replace(",", " ").replace("?", " ").split()
for word in words:
if "@" in word or len(word) > 4:
result = get_admin_user_context(query=word, db=db, current_user=current_user, _=None)
if result.get("found"):
u = result["user"]
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: {u['engagement_acknowledged']}\n"
if docs["personal"]:
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: " + "; ".join(
f"{d['business_type']} ({d['tax_year']}) [{d['status']}]" for d in docs["business"]) + "\n"
if audit:
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 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"
"TOOLS: Use the lookup_user tool to fetch details about a specific user if their name or email is mentioned.\n"
"RULES: Only answer BookKeepPro, accounting, or tax questions. Use live data. Be concise.\n\n"
f"{context}{user_context_addon}"
f"{context}"
)
else:
doc_status = get_doc_status(db=db, current_user=current_user)
@@ -400,24 +392,124 @@ def ask_chatbot(
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})
# DB Persistence setup
session_id = req.session_id or str(uuid.uuid4())
chat_session = db.query(ChatSession).filter(ChatSession.session_id == session_id).first()
if not chat_session:
chat_session = ChatSession(session_id=session_id, user_id=current_user.id)
db.add(chat_session)
sys_msg = DBChatMessage(role="system", content=system_prompt)
chat_session.messages.append(sys_msg)
db.commit()
# Determine incoming user messages
incoming_messages = []
if req.message:
incoming_messages.append({"role": "user", "content": req.message})
elif req.messages:
# Backward compatibility for old frontend: just grab the last message
last_msg = req.messages[-1]
incoming_messages.append({"role": last_msg.role, "content": last_msg.content})
for m in incoming_messages:
db.add(DBChatMessage(
session_id=chat_session.id,
role=m["role"],
content=m.get("content")
))
db.commit()
# Load full conversation history from DB for the LLM
messages = []
for m in chat_session.messages:
msg = {"role": m.role, "content": m.content}
if m.tool_calls:
msg["tool_calls"] = m.tool_calls
if m.tool_call_id:
msg["tool_call_id"] = m.tool_call_id
if m.name:
msg["name"] = m.name
messages.append(msg)
def _get_payload(current_messages, stream=False):
payload = {"model": CHAT_MODEL, "messages": current_messages, "stream": stream}
if is_admin:
payload["tools"] = [{
"type": "function",
"function": {
"name": "lookup_user",
"description": "Lookup a specific user's details, recent activity, and document uploads using their name or email.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The name or email of the user to search for."
}
},
"required": ["query"],
"additionalProperties": False
}
}
}]
return payload
def _execute_tools(tool_calls, current_messages):
for tc in tool_calls:
if tc.get("function", {}).get("name") == "lookup_user":
try:
args = json.loads(tc["function"]["arguments"])
except:
args = {}
result = get_admin_user_context(query=args.get("query", ""), db=db, current_user=current_user, _=None)
tool_result_str = ""
if result.get("found"):
u = result["user"]
docs = result["documents"]
audit = result["audit_log"]
tool_result_str = f"USER DETAIL: {u['name']} ({u['email']})\nRole: {u['role']} | Joined: {u['joined']}\n"
if docs["personal"]:
tool_result_str += "Personal: " + "; ".join(f"{d['doc_type']} ({d['tax_year']}) [{d['status']}]" for d in docs["personal"]) + "\n"
if docs["business"]:
tool_result_str += "Business: " + "; ".join(f"{d['business_type']} ({d['tax_year']}) [{d['status']}]" for d in docs["business"]) + "\n"
if audit:
tool_result_str += "Activity:\n" + "\n".join(f"[{a['at']}] {a['action']} - {a['detail'] or ''}" for a in audit[:5])
else:
tool_result_str = "User not found."
tool_msg = {
"role": "tool",
"tool_call_id": tc["id"],
"name": tc["function"]["name"],
"content": tool_result_str
}
current_messages.append(tool_msg)
db.add(DBChatMessage(
session_id=chat_session.id,
role="tool",
tool_call_id=tc["id"],
name=tc["function"]["name"],
content=tool_result_str
))
db.commit()
# ── Streaming path ────────────────────────────────────────────────────────
if req.stream:
def _stream():
def _stream(current_messages):
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},
json=_get_payload(current_messages, stream=True),
stream=True,
timeout=60,
)
resp.raise_for_status()
tool_calls_buffer = {}
is_tool_call = False
for line in resp.iter_lines():
if line and line != b"data: [DONE]":
raw = line.decode("utf-8")
@@ -426,25 +518,67 @@ def ask_chatbot(
try:
chunk = json.loads(raw)
delta = chunk["choices"][0].get("delta", {})
if "tool_calls" in delta:
is_tool_call = True
for tc in delta["tool_calls"]:
idx = tc["index"]
if idx not in tool_calls_buffer:
tool_calls_buffer[idx] = tc
else:
if "function" in tc and "arguments" in tc["function"]:
if "arguments" not in tool_calls_buffer[idx]["function"]:
tool_calls_buffer[idx]["function"]["arguments"] = ""
tool_calls_buffer[idx]["function"]["arguments"] += tc["function"]["arguments"]
token = delta.get("content", "")
if token:
# Send SSE event
if not hasattr(_stream, "full_content"):
_stream.full_content = ""
_stream.full_content += token
yield f"data: {json.dumps({'token': token})}\n\n"
except Exception:
pass
yield "data: [DONE]\n\n"
if is_tool_call:
tool_calls = list(tool_calls_buffer.values())
tool_msg = {
"role": "assistant",
"content": None,
"tool_calls": tool_calls
}
current_messages.append(tool_msg)
db.add(DBChatMessage(
session_id=chat_session.id,
role="assistant",
content=None,
tool_calls=tool_calls
))
db.commit()
_execute_tools(tool_calls, current_messages)
yield from _stream(current_messages)
else:
if hasattr(_stream, "full_content") and _stream.full_content:
db.add(DBChatMessage(
session_id=chat_session.id,
role="assistant",
content=_stream.full_content
))
db.commit()
_stream.full_content = ""
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")
return StreamingResponse(_stream(messages), media_type="text/event-stream")
# ── Non-streaming path (default) ─────────────────────────────────────────
try:
def _non_stream(current_messages):
response = 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},
json=_get_payload(current_messages, stream=False),
timeout=30,
)
response.raise_for_status()
@@ -455,8 +589,25 @@ def ask_chatbot(
if "choices" not in data:
raise HTTPException(status_code=502, detail="Unexpected AI response.")
return data["choices"][0]["message"]
message = data["choices"][0]["message"]
current_messages.append(message)
db.add(DBChatMessage(
session_id=chat_session.id,
role=message["role"],
content=message.get("content"),
tool_calls=message.get("tool_calls")
))
db.commit()
if "tool_calls" in message:
_execute_tools(message["tool_calls"], current_messages)
return _non_stream(current_messages)
return message
try:
return _non_stream(messages)
except HTTPException:
raise
except Exception as e:
+105 -16
View File
@@ -16,8 +16,8 @@ from app.db import get_db, SessionLocal
import app.crud as crud
from app.auth.security import get_current_user, require_admin, SECRET_KEY, ALGORITHM
from app.utils.emailer import send_email
from app.utils.ai import extract_document_data
from app.schemas import UploadCompleteNotify, ReviewStatusUpdate
from app.utils.ai import extract_document_data, summarize_admin_document
from app.schemas import UploadCompleteNotify, ReviewStatusUpdate, ExtractedDataUpdate
from app.limiter import limiter
from fastapi import Request
@@ -277,6 +277,28 @@ async def upload_admin_document(
crud.log_action(db, "upload_admin_doc", user_id=current_user.id, target=f"admin_doc:{record.id}", detail=f"for user {user_id}")
# Background task 1: AI summary generation
def _generate_summary(doc_id: int, file_path: str, label: str):
summary = summarize_admin_document(str(file_path), label)
if summary:
_db = SessionLocal()
try:
doc = _db.query(AdminDocument).filter_by(id=doc_id).first()
if doc:
doc.ai_summary = summary
_db.commit()
logger.info(f"[Summary] Saved summary for admin_doc:{doc_id}")
finally:
_db.close()
background.add_task(
_generate_summary,
record.id,
str(UPLOAD_DIR / storage_key),
doc_label,
)
# Background task 2: Notify client by email
background.add_task(
send_email,
to=target_user.email,
@@ -330,6 +352,8 @@ def list_admin_documents(
"filename": d.filename,
"storage_key": d.storage_key,
"created_at": d.uploaded_at.isoformat() + "Z" if d.uploaded_at else None,
# None = AI still processing; string = ready to show
"ai_summary": d.ai_summary,
}
for d in docs
]
@@ -663,6 +687,46 @@ def set_business_review_status(
return {"id": doc_id, "review_status": payload.status}
@router.patch("/personal-documents/{doc_id}/extracted-data")
def update_personal_extracted_data(
doc_id: int,
payload: ExtractedDataUpdate,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
"""Admin updates the AI extracted data (JSON) for a personal document."""
doc = db.query(PersonalDocument).filter_by(id=doc_id).first()
if not doc:
raise HTTPException(status_code=404, detail="Document not found")
doc.extracted_data = payload.extracted_data
db.commit()
crud.log_action(db, "update_extracted_data", user_id=current_user.id, target=f"personal_doc:{doc_id}")
return {"id": doc_id, "extracted_data": doc.extracted_data}
@router.patch("/business-documents/{doc_id}/extracted-data")
def update_business_extracted_data(
doc_id: int,
payload: ExtractedDataUpdate,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
"""Admin updates the AI extracted data (JSON) for a business document."""
doc = db.query(BusinessDocument).filter_by(id=doc_id).first()
if not doc:
raise HTTPException(status_code=404, detail="Document not found")
doc.extracted_data = payload.extracted_data
db.commit()
crud.log_action(db, "update_extracted_data", user_id=current_user.id, target=f"business_doc:{doc_id}")
return {"id": doc_id, "extracted_data": doc.extracted_data}
# ─────────────────────────────────────────────
# Admin — all documents for one user
# ─────────────────────────────────────────────
@@ -929,14 +993,31 @@ def list_templates(
.order_by(RequiredDocumentTemplate.id.asc())
.all()
)
return [
{
results = []
for t in templates:
# Resolve the raw storage key, self-healing old rows that stored a
# pre-baked presigned URL in file_url instead of a bare filename.
raw_key = t.storage_key
if not raw_key and t.file_url:
# Legacy row: extract the filename from a URL like
# "/api/upload/file/abc123.pdf?token=..."
try:
raw_key = t.file_url.split("/api/upload/file/")[1].split("?")[0]
# Persist the self-healed key so next read skips this path
t.storage_key = raw_key
db.commit()
except (IndexError, AttributeError):
raw_key = None
results.append({
"id": t.id,
"name": t.name,
"download": get_presigned_url(t.file_url) if t.file_url else None,
}
for t in templates
]
# Fresh presigned URL generated on every read — never stale
# Fallback to legacy file_url for static paths like /images/...
"download": get_presigned_url(raw_key) if raw_key else t.file_url,
})
return results
@router.post("/admin/templates")
async def upload_template(
@@ -952,18 +1033,18 @@ async def upload_template(
if current_user.role != UserRole.super_admin:
raise HTTPException(status_code=403, detail="Only super admins can manage templates")
file_url = None
raw_key = None
if file and file.filename:
storage_key = await upload_to_storage(file)
file_url = storage_key # Store raw key; presigned URLs are generated on-demand in GET
raw_key = await upload_to_storage(file) # raw filename, e.g. "abc123.pdf"
record = RequiredDocumentTemplate(
category=category,
tax_year=tax_year,
name=name,
file_url=file_url,
storage_key=raw_key, # store raw key; fresh URLs generated on every read
file_url=None, # no longer used for new rows
)
try:
db.add(record)
db.commit()
@@ -975,7 +1056,7 @@ async def upload_template(
return {
"id": record.id,
"name": record.name,
"download": get_presigned_url(record.file_url) if record.file_url else None,
"download": get_presigned_url(record.storage_key) if record.storage_key else None,
}
@router.delete("/admin/templates/{template_id}")
@@ -992,8 +1073,16 @@ def delete_template(
if not record:
raise HTTPException(status_code=404, detail="Template not found")
if record.file_url:
delete_from_storage(record.file_url)
# Delete the physical file — prefer storage_key, fall back to legacy file_url path
key_to_delete = record.storage_key
if not key_to_delete and record.file_url:
try:
key_to_delete = record.file_url.split("/api/upload/file/")[1].split("?")[0]
except (IndexError, AttributeError):
key_to_delete = None
if key_to_delete:
delete_from_storage(key_to_delete)
db.delete(record)
db.commit()
+5
View File
@@ -146,6 +146,11 @@ class ReviewStatusUpdate(BaseModel):
return v
class ExtractedDataUpdate(BaseModel):
"""Body for PATCH /api/upload/{personal,business}-documents/{id}/extracted-data"""
extracted_data: dict
class PersonalDocumentOut(BaseModel):
+111
View File
@@ -419,3 +419,114 @@ def extract_document_data(file_path: str, doc_type: str) -> dict | None:
except Exception as e:
logger.error(f"[AI] Extraction pipeline failed for {file_path}: {e}")
return None
# ─────────────────────────────────────────────────────────────────────────────
# Admin document summarizer
# ─────────────────────────────────────────────────────────────────────────────
_SUMMARY_SYSTEM_PROMPT = (
"You are a professional CPA's assistant. "
"Your job is to write a short, plain-English summary of a tax or financial document "
"that will be shown to the client on their secure online portal. "
"Be professional, friendly, and concise. "
"Never include sensitive numbers or personally identifiable information in the summary. "
"Respond with ONLY the summary text — no headers, no bullet points, no markdown."
)
def _extract_text_from_file(file_path: str) -> str:
"""Extract raw text from a PDF or image file. Returns empty string on failure."""
try:
if file_path.lower().endswith(".pdf"):
text = ""
try:
reader = PdfReader(file_path)
for page in reader.pages[:5]:
t = page.extract_text()
if t:
text += t + "\n"
except Exception:
pass
if len(text.strip()) < MIN_TEXT_CHARS:
try:
doc = fitz.open(file_path)
mu = "".join(doc[i].get_text() for i in range(min(5, len(doc))))
doc.close()
if len(mu.strip()) > len(text.strip()):
text = mu
except Exception:
pass
if len(text.strip()) < MIN_TEXT_CHARS:
rendered = _render_pdf_page(file_path)
if rendered:
text = _tesseract_text(rendered)
return text.strip()
elif file_path.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
img = Image.open(file_path)
return _tesseract_text(img).strip()
except Exception as e:
logger.warning(f"[Summary] Text extraction failed for {file_path}: {e}")
return ""
def summarize_admin_document(file_path: str, doc_label: str) -> str | None:
"""
Generate a 2-3 sentence plain-English summary of an admin-uploaded document.
Reuses the existing text extraction pipeline (native PDF text → Tesseract OCR).
Calls the LLM with a client-facing summary prompt instead of a JSON extraction prompt.
Returns:
str — summary text if successful
None — if OPENROUTER_API_KEY not set, file unreadable, or LLM call fails
"""
api_key = os.getenv("OPENROUTER_API_KEY")
if not api_key:
logger.warning("[Summary] OPENROUTER_API_KEY not set — skipping summary")
return None
text = _extract_text_from_file(file_path)
if not text:
logger.info(f"[Summary] No extractable text from {file_path} — skipping")
return "Summary not available for this document type."
prompt = (
f"Document name: {doc_label}\n\n"
f"Document content (first 4000 characters):\n{text[:4000]}\n\n"
"Write a 2-3 sentence plain-English summary of this document for the client. "
"Explain what it is and what they should know about it. "
"Do NOT include any specific dollar amounts, SSNs, EINs, or other sensitive numbers."
)
try:
response = requests.post(
url="https://openrouter.ai/api/v1/chat/completions",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json={
"model": MODEL_TEXT,
"messages": [
{"role": "system", "content": _SUMMARY_SYSTEM_PROMPT},
{"role": "user", "content": prompt},
],
},
timeout=60,
)
response.raise_for_status()
summary = response.json()["choices"][0]["message"]["content"].strip()
logger.info(f"[Summary] Generated {len(summary)} char summary for {doc_label}")
return summary
except Exception as e:
logger.error(f"[Summary] LLM call failed for {doc_label}: {e}")
return None
+4
View File
@@ -75,6 +75,10 @@ def upgrade():
else:
print(f" [WARN] Index {table}: {e}")
# ── v5: Required Document Templates ───────────────────────────────
_add_column(conn, "required_document_templates", "storage_key",
"VARCHAR(500) NULL DEFAULT NULL")
print("\nAll migrations complete.")
except Exception as e:
print(f"Migration error: {e}")