Production ready: mobile responsive UI, ChromaDB persistence, Excel export, and Filing Deadlines

This commit is contained in:
Atharv1705
2026-09-05 17:42:08 +05:30
parent e0f6167d14
commit 46a340dc74
18 changed files with 899 additions and 40 deletions
+2 -2
View File
@@ -435,7 +435,7 @@ _SUMMARY_SYSTEM_PROMPT = (
)
def _extract_text_from_file(file_path: str) -> str:
def extract_raw_text(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"):
@@ -492,7 +492,7 @@ def summarize_admin_document(file_path: str, doc_label: str) -> str | None:
logger.warning("[Summary] OPENROUTER_API_KEY not set — skipping summary")
return None
text = _extract_text_from_file(file_path)
text = extract_raw_text(file_path)
if not text:
logger.info(f"[Summary] No extractable text from {file_path} — skipping")
+128
View File
@@ -0,0 +1,128 @@
"""
scheduler.py — Daily background job to send filing deadline reminders.
Checks for deadlines that are 7 days or 1 day away and sends reminder emails
to both the user and all admins/super-admins.
"""
import logging
from datetime import date, timedelta
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
logger = logging.getLogger(__name__)
_scheduler = BackgroundScheduler(timezone="UTC")
def _run_deadline_reminders():
"""Check all upcoming deadlines and dispatch reminder emails."""
# Import inside to avoid circular imports at module load
from app.db import SessionLocal
from app.models import FilingDeadline, User, UserRole
from app.utils.emailer import send_email
import asyncio
db = SessionLocal()
try:
today = date.today()
thresholds = [
(7, "notified_7d", "7 days"),
(1, "notified_1d", "1 day"),
]
# Fetch all admins/super-admins to CC on reminders
admins = db.query(User).filter(
User.role.in_([UserRole.admin, UserRole.super_admin])
).all()
admin_emails = [a.email for a in admins]
for days_out, flag_col, label in thresholds:
target_date = today + timedelta(days=days_out)
deadlines = (
db.query(FilingDeadline)
.filter(
FilingDeadline.deadline_date == target_date,
getattr(FilingDeadline, flag_col) == False,
)
.all()
)
for dl in deadlines:
user = db.query(User).filter(User.id == dl.user_id).first()
if not user:
continue
doc_label = dl.doc_type.capitalize()
# Email to user
user_body = f"""
<p>Dear {user.name or "Sir/Ma'am"},</p>
<p>This is a reminder that your <strong>{doc_label} document filing deadline</strong>
is in <strong>{label}</strong> ({dl.deadline_date.strftime('%B %d, %Y')}).</p>
<p>Please ensure all outstanding actions are completed before the deadline.</p>
<p>Kind regards,<br><strong>BookKeepro Team</strong></p>
"""
asyncio.get_event_loop().run_until_complete(
send_email(
to=user.email,
subject=f"Reminder: {doc_label} Filing Deadline in {label} — BookKeepro",
body=user_body,
)
)
# Email to all admins
admin_body = f"""
<p>Admin Notice:</p>
<p>The <strong>{doc_label} filing deadline</strong> for client
<strong>{user.name or user.email}</strong> ({user.email}) is in
<strong>{label}</strong> ({dl.deadline_date.strftime('%B %d, %Y')}).</p>
<p>Please review the client's status and take any necessary action.</p>
<p><strong>BookKeepro System</strong></p>
"""
for admin_email in admin_emails:
asyncio.get_event_loop().run_until_complete(
send_email(
to=admin_email,
subject=f"Admin Reminder: {user.email} — {doc_label} Deadline in {label}",
body=admin_body,
)
)
# Mark as notified
setattr(dl, flag_col, True)
db.commit()
logger.info(
"Sent %s deadline reminder for user %s (%s)",
label, dl.user_id, dl.doc_type,
)
except Exception as exc:
logger.error("Deadline reminder job failed: %s", exc)
finally:
db.close()
def start_scheduler():
"""Start the APScheduler. Called once at application startup."""
if _scheduler.running:
return
# Run every day at 08:00 UTC
_scheduler.add_job(
_run_deadline_reminders,
trigger=CronTrigger(hour=8, minute=0, timezone="UTC"),
id="filing_deadline_reminders",
replace_existing=True,
misfire_grace_time=3600, # If the server was down, run if missed by < 1 hr
)
_scheduler.start()
logger.info("APScheduler started — filing deadline reminders active.")
def stop_scheduler():
"""Gracefully stop the scheduler at application shutdown."""
if _scheduler.running:
_scheduler.shutdown(wait=False)
logger.info("APScheduler stopped.")
+105
View File
@@ -0,0 +1,105 @@
import chromadb
from chromadb.config import Settings
import os
import logging
logger = logging.getLogger(__name__)
# Ensure the database directory exists
DB_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'chroma_db'))
os.makedirs(DB_PATH, exist_ok=True)
# Initialize ChromaDB client with persistent storage
client = chromadb.PersistentClient(path=DB_PATH)
# We'll use a single collection for all documents, using metadata to differentiate
collection = client.get_or_create_collection(
name='documents',
metadata={'hnsw:space': 'cosine'}
)
def add_document_embedding(doc_id: int, doc_type: str, user_id: int, text: str):
"""
Adds a document's text to the vector database.
We chunk the text into roughly 1000 character segments to improve search relevance.
"""
if not text or not text.strip():
logger.info(f"[VectorStore] Skipping empty text for doc {doc_id}")
return
logger.info(f"[VectorStore] Adding embeddings for doc {doc_id} (user {user_id})")
# Simple chunking by fixed length (1000 chars)
chunk_size = 1000
chunks = [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]
ids = [f"doc_{doc_type}_{doc_id}_chunk_{i}" for i in range(len(chunks))]
metadatas = [{"doc_id": doc_id, "doc_type": doc_type, "user_id": user_id, "chunk_index": i} for i in range(len(chunks))]
collection.upsert(
documents=chunks,
metadatas=metadatas,
ids=ids
)
logger.info(f"[VectorStore] Added {len(chunks)} chunks for doc {doc_id}")
def search_documents(query: str, user_id: int, limit: int = 5):
"""
Searches for documents matching the query for a specific user.
Returns a list of dicts: {'doc_id': int, 'doc_type': str, 'distance': float}
"""
logger.info(f'[VectorStore] Searching for: "{query}" (user {user_id})')
try:
results = collection.query(
query_texts=[query],
n_results=limit * 2, # Fetch more to account for duplicates
where={"user_id": user_id}
)
if not results or not results['documents'] or len(results['documents'][0]) == 0:
return []
metadatas = results['metadatas'][0]
distances = results['distances'][0]
# We want to return unique documents, keeping the best score for each
doc_scores = {}
for meta, dist in zip(metadatas, distances):
key = f"{meta['doc_type']}_{meta['doc_id']}"
if key not in doc_scores or dist < doc_scores[key]['distance']:
doc_scores[key] = {
'doc_id': meta['doc_id'],
'doc_type': meta['doc_type'],
'distance': dist
}
# Sort by distance
sorted_docs = sorted(doc_scores.values(), key=lambda x: x['distance'])
return sorted_docs[:limit]
except Exception as e:
logger.error(f"[VectorStore] Search failed: {e}")
return []
def delete_document_embeddings(doc_id: int, doc_type: str):
"""
Deletes all vector chunks associated with a specific document.
"""
try:
collection.delete(where={"$and": [{"doc_id": doc_id}, {"doc_type": doc_type}]})
logger.info(f"[VectorStore] Deleted embeddings for {doc_type} document {doc_id}")
except Exception as e:
logger.error(f"[VectorStore] Failed to delete embeddings for doc {doc_id}: {e}")
def delete_user_embeddings(user_id: int):
"""
Deletes all vector chunks associated with a specific user.
"""
try:
collection.delete(where={"user_id": user_id})
logger.info(f"[VectorStore] Deleted all embeddings for user {user_id}")
except Exception as e:
logger.error(f"[VectorStore] Failed to delete embeddings for user {user_id}: {e}")