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
+4 -1
View File
@@ -25,4 +25,7 @@ services/temp/
*.msi
blog_images/
check_docs.py
openrouter_error.log
openrouter_error.log
# Vector Database
chroma_db/
services/api/chroma_db/
+11 -1
View File
@@ -4,10 +4,12 @@ services:
image: nginx:1.25-alpine
ports:
- "80:80"
# - "443:443" # if Nginx terminates HTTPS
- "443:443"
volumes:
- ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
- ./frontend/dist:/usr/share/nginx/html:ro
- ./certbot/conf:/etc/letsencrypt
- ./certbot/www:/var/www/certbot
depends_on:
- app
restart: unless-stopped
@@ -36,9 +38,17 @@ services:
volumes:
- uploads_data:/app/uploads
- chroma_data:/app/services/api/chroma_db
restart: unless-stopped
certbot:
image: certbot/certbot
volumes:
- ./certbot/conf:/etc/letsencrypt
- ./certbot/www:/var/www/certbot
entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'"
db:
image: mysql:8.4
+105 -1
View File
@@ -12,7 +12,8 @@
"lucide-react": "^1.24.0",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router-dom": "^7.18.1"
"react-router-dom": "^7.18.1",
"xlsx": "^0.18.5"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.3.2",
@@ -2003,6 +2004,15 @@
}
}
},
"node_modules/adler-32": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.3.1.tgz",
"integrity": "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/agent-base": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
@@ -2151,6 +2161,28 @@
],
"license": "CC-BY-4.0"
},
"node_modules/cfb": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/cfb/-/cfb-1.2.2.tgz",
"integrity": "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==",
"license": "Apache-2.0",
"dependencies": {
"adler-32": "~1.3.0",
"crc-32": "~1.2.0"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/codepage": {
"version": "1.15.0",
"resolved": "https://registry.npmjs.org/codepage/-/codepage-1.15.0.tgz",
"integrity": "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
@@ -2176,6 +2208,18 @@
"url": "https://opencollective.com/express"
}
},
"node_modules/crc-32": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz",
"integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==",
"license": "Apache-2.0",
"bin": {
"crc32": "bin/crc32.njs"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
@@ -2363,6 +2407,15 @@
"node": ">= 6"
}
},
"node_modules/frac": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/frac/-/frac-1.1.2.tgz",
"integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/fraction.js": {
"version": "5.3.4",
"resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz",
@@ -3168,6 +3221,18 @@
"node": ">=0.10.0"
}
},
"node_modules/ssf": {
"version": "0.11.2",
"resolved": "https://registry.npmjs.org/ssf/-/ssf-0.11.2.tgz",
"integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==",
"license": "Apache-2.0",
"dependencies": {
"frac": "~1.1.2"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/tailwindcss": {
"version": "4.3.2",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.2.tgz",
@@ -3322,6 +3387,45 @@
"optional": true
}
}
},
"node_modules/wmf": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wmf/-/wmf-1.0.2.tgz",
"integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/word": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/word/-/word-0.3.0.tgz",
"integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/xlsx": {
"version": "0.18.5",
"resolved": "https://registry.npmjs.org/xlsx/-/xlsx-0.18.5.tgz",
"integrity": "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==",
"license": "Apache-2.0",
"dependencies": {
"adler-32": "~1.3.0",
"cfb": "~1.2.1",
"codepage": "~1.15.0",
"crc-32": "~1.2.1",
"ssf": "~0.11.2",
"wmf": "~1.0.1",
"word": "~0.3.0"
},
"bin": {
"xlsx": "bin/xlsx.njs"
},
"engines": {
"node": ">=0.8"
}
}
}
}
+2 -1
View File
@@ -14,7 +14,8 @@
"lucide-react": "^1.24.0",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router-dom": "^7.18.1"
"react-router-dom": "^7.18.1",
"xlsx": "^0.18.5"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.3.2",
+67
View File
@@ -442,3 +442,70 @@ body { background: var(--bg); overflow-x: hidden; }
.hero-stats { margin-top: 46px; }
}
@media (max-width: 992px) {
.hero {
flex-direction: column;
justify-content: center;
padding-top: 80px;
padding-bottom: 40px;
}
.hero-inner {
margin-top: 20px;
margin-bottom: 40px;
}
.hero h1 {
font-size: clamp(28px, 8vw, 42px);
}
.footer-top, .mkt-footer-top {
padding: 30px 0 20px;
gap: 24px;
}
.footer, .mkt-footer {
margin-top: 30px;
}
.footer-left {
margin-bottom: 10px;
}
}
@media (max-width: 992px) {
.cta-band {
margin-top: 50px;
padding: 50px 20px;
}
}
@media (max-width: 992px) {
/* Reduce footer length and spacing */
.footer, .mkt-footer {
margin-top: 0;
}
.footer-top, .mkt-footer-top {
padding: 30px 0 10px;
gap: 16px;
}
.footer-left p {
font-size: 13px;
}
.footer-links h3, .footer-contact h3, .mkt-footer-links h3 {
margin-top: 10px;
margin-bottom: 2px;
}
.footer-contact p, .footer-links a {
font-size: 13px;
margin-bottom: 2px;
}
/* Make stat blocks smaller on mobile */
.stat-block {
padding: 16px 14px;
}
.stat-block .stat-figure {
font-size: 26px;
}
.stat-block .stat-caption {
font-size: 10px;
margin-top: 2px;
}
}
@@ -1,3 +1,4 @@
import * as XLSX from 'xlsx';
import { useState } from 'react';
import ExpandableValue from './ExpandableValue';
@@ -62,39 +63,34 @@ export default function ExpandableSummaryBlock({ extractedData, onSave }) {
};
const handleExport = () => {
// Convert extracted data into a 2-column CSV (Field, Value)
// Export extracted AI data as a proper .xlsx file using SheetJS
const { _meta, ...dataFields } = extractedData || {};
const escapeCsv = (str) => {
const s = String(str);
if (s.includes(',') || s.includes('"') || s.includes('\n')) {
return `"${s.replace(/"/g, '""')}"`;
}
return s;
};
const csvRows = ['Field,Value'];
const rows = [['Field', 'Value']];
Object.entries(dataFields).forEach(([key, val]) => {
let valStr = val;
if (Array.isArray(val)) {
valStr = val.join('; ');
} else if (typeof val === 'object' && val !== null) {
valStr = JSON.stringify(val);
}
csvRows.push(`${escapeCsv(key)},${escapeCsv(valStr)}`);
if (Array.isArray(val)) valStr = val.join('; ');
else if (typeof val === 'object' && val !== null) valStr = JSON.stringify(val);
rows.push([String(key), String(valStr ?? '')]);
});
const csvContent = csvRows.join('\n');
const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `extracted_data.csv`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
const ws = XLSX.utils.aoa_to_sheet(rows);
// Bold + green header
['A1', 'B1'].forEach(ref => {
if (ws[ref]) ws[ref].s = { font: { bold: true, color: { rgb: 'FFFFFF' } }, fill: { fgColor: { rgb: '2C7A5B' } } };
});
// Column widths
ws['!cols'] = [
{ wch: Math.max(10, ...Object.keys(dataFields).map(k => k.length + 2)) },
{ wch: 45 },
];
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Extracted Data');
XLSX.writeFile(wb, 'extracted_data.xlsx');
}
const showToggle = entries.length > 3;
const entriesToShow = expanded ? entries : entries.slice(0, 3);
@@ -160,8 +156,8 @@ export default function ExpandableSummaryBlock({ extractedData, onSave }) {
) : <div />}
<div style={{ display: 'flex', gap: '6px' }}>
<button onClick={handleExport} style={{ border: 'none', background: 'transparent', cursor: 'pointer', fontSize: '11px', color: 'var(--muted)', display: 'flex', alignItems: 'center', gap: '4px', padding: '2px' }} title="Export CSV">
<span className="material-symbols-outlined" style={{ fontSize: '14px' }}>download</span> Export CSV
<button onClick={handleExport} style={{ border: 'none', background: 'transparent', cursor: 'pointer', fontSize: '11px', color: 'var(--muted)', display: 'flex', alignItems: 'center', gap: '4px', padding: '2px' }} title="Export Excel">
<span className="material-symbols-outlined" style={{ fontSize: '14px' }}>download</span> Export Excel
</button>
<button onClick={handleEditClick} style={{ border: 'none', background: 'transparent', cursor: 'pointer', fontSize: '11px', color: 'var(--emerald)', display: 'flex', alignItems: 'center', gap: '4px', padding: '2px', fontWeight: 600 }} title="Edit Summary">
<span className="material-symbols-outlined" style={{ fontSize: '14px' }}>edit</span> Edit
+70
View File
@@ -23,9 +23,35 @@ export default function AdminUserDetail() {
const [personalTimeline, setPersonalTimeline] = useState(0);
const [businessTimeline, setBusinessTimeline] = useState(0);
// Export Excel Function
const exportToExcel = async () => {
try {
showToast("Preparing Excel export...", "info");
const res = await authFetch(`/api/upload/admin/users/${userId}/export`);
if (res.ok) {
const blob = await res.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `user_${userId}_documents.xlsx`;
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
showToast("Excel export ready!", "success");
} else {
showToast("Failed to export Excel file", "error");
}
} catch (err) {
console.error(err);
showToast("Error exporting Excel file", "error");
}
};
// States for Audit Log
const [auditLog, setAuditLog] = useState([]);
const [auditLoaded, setAuditLoaded] = useState(false);
const [deadlines, setDeadlines] = useState([]);
const adminDocInputRef = useRef(null);
@@ -55,6 +81,12 @@ export default function AdminUserDetail() {
const allDocs = [...userDocs, ...adminDocs];
setDocuments(allDocs);
// Fetch filing deadlines
try {
const dlRes = await authFetch(`/api/review/deadlines/${userId}`);
if (dlRes.ok) setDeadlines(await dlRes.json());
} catch {}
} catch (err) {
console.error(err);
@@ -432,6 +464,25 @@ export default function AdminUserDetail() {
<div className="doc-review-sidebar">
<div className="card-flat" style={{display:'flex', flexDirection:'column', gap:'16px'}}>
<h3>Filing Timeline</h3>
{deadlines.filter(d => d.doc_type === 'personal').map(d => (
<div key="personal-dl" style={{
margin: '0 0 16px', padding: '12px 16px',
borderRadius: 'var(--radius-sm)',
background: d.is_overdue ? 'rgba(220,53,69,0.08)' : d.days_left <= 1 ? 'rgba(255,140,0,0.10)' : 'rgba(44,122,91,0.08)',
border: `1px solid ${d.is_overdue ? 'rgba(220,53,69,0.3)' : d.days_left <= 1 ? 'rgba(255,140,0,0.35)' : 'rgba(44,122,91,0.20)'}`,
display: 'flex', alignItems: 'center', gap: '10px'
}}>
<span className="material-symbols-outlined" style={{fontSize:'20px', color: d.is_overdue ? '#dc3545' : d.days_left <= 1 ? '#ff8c00' : 'var(--accent)'}}>
{d.is_overdue ? 'warning' : 'schedule'}
</span>
<div>
<div style={{fontWeight: 600, fontSize: '13px', color: d.is_overdue ? '#dc3545' : d.days_left <= 1 ? '#ff8c00' : 'var(--navy)'}}>
{d.is_overdue ? `OVERDUE by ${Math.abs(d.days_left)} day${Math.abs(d.days_left) !== 1 ? 's' : ''}` : `${d.days_left} day${d.days_left !== 1 ? 's' : ''} remaining`}
</div>
<div style={{fontSize: '11px', color: 'var(--muted)'}}>Deadline: {new Date(d.deadline_date).toLocaleDateString('en-US', {year:'numeric',month:'long',day:'numeric'})}</div>
</div>
</div>
))}
<div className="timeline-control">
<button className="tl-btn" onClick={() => setPersonalTimeline(Math.max(0, personalTimeline - 1))}>−</button>
<div>
@@ -510,6 +561,25 @@ export default function AdminUserDetail() {
<div className="doc-review-sidebar">
<div className="card-flat" style={{display:'flex', flexDirection:'column', gap:'16px'}}>
<h3>Filing Timeline</h3>
{deadlines.filter(d => d.doc_type === 'business').map(d => (
<div key="business-dl" style={{
margin: '0 0 16px', padding: '12px 16px',
borderRadius: 'var(--radius-sm)',
background: d.is_overdue ? 'rgba(220,53,69,0.08)' : d.days_left <= 1 ? 'rgba(255,140,0,0.10)' : 'rgba(44,122,91,0.08)',
border: `1px solid ${d.is_overdue ? 'rgba(220,53,69,0.3)' : d.days_left <= 1 ? 'rgba(255,140,0,0.35)' : 'rgba(44,122,91,0.20)'}`,
display: 'flex', alignItems: 'center', gap: '10px'
}}>
<span className="material-symbols-outlined" style={{fontSize:'20px', color: d.is_overdue ? '#dc3545' : d.days_left <= 1 ? '#ff8c00' : 'var(--accent)'}}>
{d.is_overdue ? 'warning' : 'schedule'}
</span>
<div>
<div style={{fontWeight: 600, fontSize: '13px', color: d.is_overdue ? '#dc3545' : d.days_left <= 1 ? '#ff8c00' : 'var(--navy)'}}>
{d.is_overdue ? `OVERDUE by ${Math.abs(d.days_left)} day${Math.abs(d.days_left) !== 1 ? 's' : ''}` : `${d.days_left} day${d.days_left !== 1 ? 's' : ''} remaining`}
</div>
<div style={{fontSize: '11px', color: 'var(--muted)'}}>Deadline: {new Date(d.deadline_date).toLocaleDateString('en-US', {year:'numeric',month:'long',day:'numeric'})}</div>
</div>
</div>
))}
<div className="timeline-control">
<button className="tl-btn" onClick={() => setBusinessTimeline(Math.max(0, businessTimeline - 1))}>−</button>
<div>
+23
View File
@@ -14,9 +14,32 @@ export default function UserDashboard() {
const [docLoading, setDocLoading] = useState(false);
// Track which doc rows have the AI summary panel open
const [expandedSummary, setExpandedSummary] = useState({});
const [searchQuery, setSearchQuery] = useState("");
const [searchResults, setSearchResults] = useState([]);
const [isSearching, setIsSearching] = useState(false);
// ── declare callbacks BEFORE the effects that reference them ──
const handleSearch = async (e) => {
e.preventDefault();
if (!searchQuery.trim()) return;
setIsSearching(true);
try {
const res = await authFetch(`/api/search/semantic?q=${encodeURIComponent(searchQuery)}`);
if (res.ok) {
setSearchResults(await res.json());
} else {
showToast("Search failed", "error");
}
} catch (err) {
console.error(err);
showToast("Search failed", "error");
} finally {
setIsSearching(false);
}
};
const checkEngagement = useCallback(async () => {
try {
const res = await authFetch("/api/auth/me");
+23
View File
@@ -2,6 +2,16 @@ server {
listen 80;
server_name aiindiacpa.duckdns.org 147.93.168.145;
# ── Certbot ACME Challenge ───────────────────────────────────────────────
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
# Redirect all HTTP traffic to HTTPS (uncomment when SSL certs are generated)
# location / {
# return 301 https://$host$request_uri;
# }
# Max upload size — matches backend 10MB limit with buffer
client_max_body_size 15m;
@@ -79,3 +89,16 @@ server {
try_files $uri $uri/ /index.html;
}
}
# ── HTTPS Server Block ───────────────────────────────────────────────────
# Uncomment this block after generating SSL certificates via Certbot
# server {
# listen 443 ssl;
# server_name aiindiacpa.duckdns.org 147.93.168.145;
#
# ssl_certificate /etc/letsencrypt/live/aiindiacpa.duckdns.org/fullchain.pem;
# ssl_certificate_key /etc/letsencrypt/live/aiindiacpa.duckdns.org/privkey.pem;
#
# # (Include the rest of the location blocks from port 80 here)
# }
+28 -1
View File
@@ -12,8 +12,28 @@ from app import models
from app.db import engine
log = logging.getLogger("uvicorn.error")
from contextlib import asynccontextmanager
app = FastAPI(title="BookKeepPro API", docs_url=None, redoc_url=None) # hide docs in production
@asynccontextmanager
async def lifespan(app):
# Startup
try:
from app.utils.scheduler import start_scheduler
start_scheduler()
log.info("Scheduler started via lifespan.")
except Exception as exc:
log.exception("Failed to start scheduler: %s", exc)
yield
# Shutdown
try:
from app.utils.scheduler import stop_scheduler
stop_scheduler()
except Exception:
pass
app = FastAPI(title="BookKeepPro API", docs_url=None, redoc_url=None, lifespan=lifespan) # hide docs in production
# Rate limiter
app.state.limiter = limiter
@@ -37,6 +57,13 @@ try:
except Exception as exc:
log.exception("Failed to load upload router: %s", exc)
try:
from app.routers import search
app.include_router(search.router)
except Exception as exc:
log.exception("Failed to load search router: %s", exc)
try:
from app.routers import contact # type: ignore
app.include_router(contact.router)
+26
View File
@@ -1,6 +1,7 @@
from sqlalchemy import (
Boolean,
Column,
Date,
DateTime,
Enum,
ForeignKey,
@@ -222,3 +223,28 @@ class ChatMessage(Base):
created_at = Column(DateTime(timezone=True), server_default=func.now())
session = relationship("ChatSession", back_populates="messages")
# ─────────────────────────────────────────────
# Filing Deadlines — set by admin when sending review email
# ─────────────────────────────────────────────
class FilingDeadline(Base):
__tablename__ = "filing_deadlines"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
doc_type = Column(String(20), nullable=False) # "personal" or "business"
deadline_date = Column(Date, nullable=False)
days_given = Column(Integer, nullable=False)
notified_7d = Column(Boolean, default=False, nullable=False)
notified_1d = Column(Boolean, default=False, 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())
user = relationship("User")
__table_args__ = (
Index("ix_filing_deadlines_user_id", "user_id"),
Index("ix_filing_deadlines_deadline_date", "deadline_date"),
)
+53 -1
View File
@@ -1,8 +1,9 @@
import os
from datetime import date, timedelta
import logging
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.models import AdminDocument, User, UserRole
from app.models import AdminDocument, User, UserRole, FilingDeadline
from app.db import get_db
from app.utils.emailer import send_email
from app import crud
@@ -92,6 +93,30 @@ async def notify_user_review(
await send_email(to=user.email, subject="Document Review Update — BookKeepro", 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
today = date.today()
for doc_type, days in [("personal", payload.personal_timeline), ("business", payload.business_timeline)]:
if days and days > 0:
existing = db.query(FilingDeadline).filter(
FilingDeadline.user_id == payload.user_id,
FilingDeadline.doc_type == doc_type,
).first()
if existing:
# Reset the deadline and clear reminder flags
existing.deadline_date = today + timedelta(days=days)
existing.days_given = days
existing.notified_7d = False
existing.notified_1d = False
else:
db.add(FilingDeadline(
user_id=payload.user_id,
doc_type=doc_type,
deadline_date=today + timedelta(days=days),
days_given=days,
))
db.commit()
return {"status": "notified"}
@@ -143,3 +168,30 @@ async def admin_doc_response(
logger.info(f"User {current_user.id} {payload.status} admin doc {payload.doc_id}")
return {"status": "notified"}
# ─────────────────────────────────────────────
# Get filing deadlines for a user
# ─────────────────────────────────────────────
@router.get("/deadlines/{user_id}")
def get_filing_deadlines(
user_id: int,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
from app.models import FilingDeadline
deadlines = db.query(FilingDeadline).filter(FilingDeadline.user_id == user_id).all()
today = date.today()
result = []
for dl in deadlines:
days_left = (dl.deadline_date - today).days
result.append({
"doc_type": dl.doc_type,
"deadline_date": dl.deadline_date.isoformat(),
"days_given": dl.days_given,
"days_left": days_left,
"is_overdue": days_left < 0,
})
return result
+67
View File
@@ -0,0 +1,67 @@
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Dict, Any
from app.db import get_db
from app.models import PersonalDocument, BusinessDocument, User
from app.auth.security import get_current_user
from app.utils.vector_store import search_documents
router = APIRouter(
prefix="/api/search",
tags=["Search"]
)
@router.get("/semantic")
def semantic_search(
q: str = Query(..., description="The semantic search query"),
limit: int = Query(5, description="Maximum number of results to return"),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""
Searches for documents matching the query semantics.
Returns matched documents across both personal and business tables.
"""
if not q.strip():
raise HTTPException(status_code=400, detail="Query string cannot be empty")
# Search the vector database
results = search_documents(q, current_user.id, limit=limit)
if not results:
return []
# Fetch full document metadata from DB
enriched_results = []
for res in results:
doc_id = res['doc_id']
doc_type = res['doc_type']
doc = None
if doc_type == "personal":
doc = db.query(PersonalDocument).filter(
PersonalDocument.id == doc_id,
PersonalDocument.user_id == current_user.id,
PersonalDocument.deleted_at == None
).first()
elif doc_type == "business":
doc = db.query(BusinessDocument).filter(
BusinessDocument.id == doc_id,
BusinessDocument.user_id == current_user.id,
BusinessDocument.deleted_at == None
).first()
if doc:
doc_data = {
"id": doc.id,
"table": doc_type,
"original_filename": doc.original_filename,
"document_type": doc.document_type,
"uploaded_at": doc.uploaded_at,
"relevance_score": res['distance']
}
enriched_results.append(doc_data)
return enriched_results
+155 -3
View File
@@ -5,18 +5,19 @@ import logging
from datetime import datetime
import filetype
from fastapi import APIRouter, BackgroundTasks, UploadFile, File, HTTPException, Depends, Form, Query
from fastapi.responses import FileResponse
from fastapi.responses import FileResponse, StreamingResponse
from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError
from jose import jwt, JWTError
from datetime import timedelta
from app.models import AdminDocument, PersonalDocument, BusinessDocument, User, UserRole
from app.models import AdminDocument, PersonalDocument, BusinessDocument, User, UserRole, ChatSession, ChatMessage
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, summarize_admin_document
from app.utils.ai import extract_document_data, summarize_admin_document, extract_raw_text
from app.utils.vector_store import add_document_embedding, delete_document_embeddings, delete_user_embeddings
from app.schemas import UploadCompleteNotify, ReviewStatusUpdate, ExtractedDataUpdate
from app.limiter import limiter
from fastapi import Request
@@ -72,6 +73,12 @@ def process_ai_extraction(table: str, doc_id: int, file_path: str, doc_type: str
doc.extracted_data = cached.extracted_data
doc.file_hash = file_hash
db.commit()
try:
raw_text = extract_raw_text(file_path)
if raw_text:
add_document_embedding(doc.id, table, doc.user_id, raw_text)
except Exception as ve:
logger.error(f"VectorStore Failed to embed {file_path}: {ve}")
return
# No cache — run full extraction
@@ -90,6 +97,12 @@ def process_ai_extraction(table: str, doc_id: int, file_path: str, doc_type: str
doc.extracted_data = extracted
doc.file_hash = file_hash
db.commit()
try:
raw_text = extract_raw_text(file_path)
if raw_text:
add_document_embedding(doc.id, table, doc.user_id, raw_text)
except Exception as ve:
logger.error(f"VectorStore Failed to embed {file_path}: {ve}")
except Exception as e:
logger.error(f"Failed to update DB with AI extraction: {e}")
@@ -1087,3 +1100,142 @@ def delete_template(
db.delete(record)
db.commit()
return {"deleted": True}
from fastapi.responses import StreamingResponse
import csv
import io
import json
@router.get("/admin/users/{user_id}/export")
def export_user_documents_excel(
user_id: int,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
"""Export all documents for a user as a formatted Excel (.xlsx) workbook."""
import io
import json as _json
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
if current_user.role == UserRole.admin and user.role != UserRole.user:
raise HTTPException(status_code=403, detail="Admins can only export documents for regular user accounts")
personal_docs = db.query(PersonalDocument).filter(
PersonalDocument.user_id == user_id, PersonalDocument.deleted_at == None
).all()
business_docs = db.query(BusinessDocument).filter(
BusinessDocument.user_id == user_id, BusinessDocument.deleted_at == None
).all()
# Collect all extracted_data keys to build dynamic columns
extracted_keys = set()
all_docs = []
for d in personal_docs:
row = {
"ID": f"P-{d.id}",
"Table": "Personal",
"Doc Type": d.doc_type,
"Filename": d.filename,
"Uploaded At": d.uploaded_at.strftime("%Y-%m-%d %H:%M") if d.uploaded_at else "",
"Tax Year": d.tax_year or "",
"Review Status": (d.review_status or "").capitalize(),
"Review Note": d.review_note or "",
}
if d.extracted_data:
try:
data = _json.loads(d.extracted_data) if isinstance(d.extracted_data, str) else d.extracted_data
if isinstance(data, dict):
for k, v in data.items():
col = f"AI: {k}"
extracted_keys.add(col)
row[col] = str(v)
except Exception:
pass
all_docs.append(row)
for d in business_docs:
row = {
"ID": f"B-{d.id}",
"Table": "Business",
"Doc Type": d.business_type,
"Filename": d.filename,
"Uploaded At": d.uploaded_at.strftime("%Y-%m-%d %H:%M") if d.uploaded_at else "",
"Tax Year": d.tax_year or "",
"Review Status": (d.review_status or "").capitalize(),
"Review Note": d.review_note or "",
}
if d.extracted_data:
try:
data = _json.loads(d.extracted_data) if isinstance(d.extracted_data, str) else d.extracted_data
if isinstance(data, dict):
for k, v in data.items():
col = f"AI: {k}"
extracted_keys.add(col)
row[col] = str(v)
except Exception:
pass
all_docs.append(row)
base_cols = ["ID", "Table", "Doc Type", "Filename", "Uploaded At", "Tax Year", "Review Status", "Review Note"]
all_cols = base_cols + sorted(list(extracted_keys))
# ── Build workbook ────────────────────────────────────────────────────────
wb = Workbook()
ws = wb.active
ws.title = "Documents"
# Header style
header_fill = PatternFill(fill_type="solid", fgColor="2C7A5B")
header_font = Font(bold=True, color="FFFFFF", size=11)
center_align = Alignment(horizontal="center", vertical="center", wrap_text=True)
thin_border = Border(
left=Side(style="thin"), right=Side(style="thin"),
top=Side(style="thin"), bottom=Side(style="thin"),
)
# Write headers
for col_idx, col_name in enumerate(all_cols, 1):
cell = ws.cell(row=1, column=col_idx, value=col_name)
cell.fill = header_fill
cell.font = header_font
cell.alignment = center_align
cell.border = thin_border
ws.row_dimensions[1].height = 30
ws.freeze_panes = "A2"
# Alternate row fill
alt_fill = PatternFill(fill_type="solid", fgColor="EAF4EF")
# Write data
for row_idx, doc in enumerate(all_docs, 2):
fill = alt_fill if row_idx % 2 == 0 else None
for col_idx, col_name in enumerate(all_cols, 1):
cell = ws.cell(row=row_idx, column=col_idx, value=doc.get(col_name, ""))
cell.alignment = Alignment(vertical="center", wrap_text=False)
cell.border = thin_border
if fill:
cell.fill = fill
# Auto-fit column widths (capped at 40)
for col_idx, col_name in enumerate(all_cols, 1):
max_len = max(len(col_name), *(len(str(doc.get(col_name, ""))) for doc in all_docs)) if all_docs else len(col_name)
ws.column_dimensions[get_column_letter(col_idx)].width = min(max_len + 3, 40)
buf = io.BytesIO()
wb.save(buf)
buf.seek(0)
headers = {
"Content-Disposition": f'attachment; filename="user_{user_id}_documents.xlsx"',
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
}
return StreamingResponse(buf, headers=headers)
+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}")
+5
View File
@@ -39,3 +39,8 @@ pymupdf==1.24.1
Pillow==12.0.0
pytesseract==0.3.13
pypdf==4.3.1
chromadb==0.5.5
openpyxl
APScheduler