diff --git a/.gitignore b/.gitignore index c034bdc..e049bce 100644 --- a/.gitignore +++ b/.gitignore @@ -25,4 +25,7 @@ services/temp/ *.msi blog_images/ check_docs.py -openrouter_error.log \ No newline at end of file +openrouter_error.log +# Vector Database +chroma_db/ +services/api/chroma_db/ diff --git a/docker-compose.yml b/docker-compose.yml index 56a3b37..186da48 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -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 diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 8614077..f3a5acb 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -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" + } } } } diff --git a/frontend/package.json b/frontend/package.json index 4b435be..6a3cd10 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -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", diff --git a/frontend/public/css/marketing.css b/frontend/public/css/marketing.css index 1c2ebf1..6f1a3e0 100644 --- a/frontend/public/css/marketing.css +++ b/frontend/public/css/marketing.css @@ -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; + } +} diff --git a/frontend/src/components/ExpandableSummaryBlock.jsx b/frontend/src/components/ExpandableSummaryBlock.jsx index 8266d7d..867cf5d 100644 --- a/frontend/src/components/ExpandableSummaryBlock.jsx +++ b/frontend/src/components/ExpandableSummaryBlock.jsx @@ -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 }) { ) :
}
-
@@ -510,6 +561,25 @@ export default function AdminUserDetail() {

Filing Timeline

+ {deadlines.filter(d => d.doc_type === 'business').map(d => ( +
+ + {d.is_overdue ? 'warning' : 'schedule'} + +
+
+ {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`} +
+
Deadline: {new Date(d.deadline_date).toLocaleDateString('en-US', {year:'numeric',month:'long',day:'numeric'})}
+
+
+ ))}
diff --git a/frontend/src/pages/UserDashboard.jsx b/frontend/src/pages/UserDashboard.jsx index 4d4c5e7..1d49778 100644 --- a/frontend/src/pages/UserDashboard.jsx +++ b/frontend/src/pages/UserDashboard.jsx @@ -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"); diff --git a/nginx/default.conf b/nginx/default.conf index 58c8a28..039cc2c 100644 --- a/nginx/default.conf +++ b/nginx/default.conf @@ -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) +# } diff --git a/services/api/app/main.py b/services/api/app/main.py index 82c156f..e31661a 100644 --- a/services/api/app/main.py +++ b/services/api/app/main.py @@ -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) diff --git a/services/api/app/models.py b/services/api/app/models.py index c3e4271..63bb475 100644 --- a/services/api/app/models.py +++ b/services/api/app/models.py @@ -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"), + ) diff --git a/services/api/app/routers/review.py b/services/api/app/routers/review.py index a9e5264..b6a27ee 100644 --- a/services/api/app/routers/review.py +++ b/services/api/app/routers/review.py @@ -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 diff --git a/services/api/app/routers/search.py b/services/api/app/routers/search.py new file mode 100644 index 0000000..ecec6b2 --- /dev/null +++ b/services/api/app/routers/search.py @@ -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 diff --git a/services/api/app/routers/upload.py b/services/api/app/routers/upload.py index d04d838..a62c705 100644 --- a/services/api/app/routers/upload.py +++ b/services/api/app/routers/upload.py @@ -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) + diff --git a/services/api/app/utils/ai.py b/services/api/app/utils/ai.py index dd4822a..e60731f 100644 --- a/services/api/app/utils/ai.py +++ b/services/api/app/utils/ai.py @@ -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") diff --git a/services/api/app/utils/scheduler.py b/services/api/app/utils/scheduler.py new file mode 100644 index 0000000..229a935 --- /dev/null +++ b/services/api/app/utils/scheduler.py @@ -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""" +

Dear {user.name or "Sir/Ma'am"},

+

This is a reminder that your {doc_label} document filing deadline + is in {label} ({dl.deadline_date.strftime('%B %d, %Y')}).

+

Please ensure all outstanding actions are completed before the deadline.

+

Kind regards,
BookKeepro Team

+ """ + 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""" +

Admin Notice:

+

The {doc_label} filing deadline for client + {user.name or user.email} ({user.email}) is in + {label} ({dl.deadline_date.strftime('%B %d, %Y')}).

+

Please review the client's status and take any necessary action.

+

BookKeepro System

+ """ + 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.") diff --git a/services/api/app/utils/vector_store.py b/services/api/app/utils/vector_store.py new file mode 100644 index 0000000..12e2686 --- /dev/null +++ b/services/api/app/utils/vector_store.py @@ -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}") diff --git a/services/api/requirements.txt b/services/api/requirements.txt index c7d0a2b..86dae57 100644 --- a/services/api/requirements.txt +++ b/services/api/requirements.txt @@ -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