chore: apply deployment fixes, timezone fixes, and cleanup unused dependencies

This commit is contained in:
Atharv1705
2026-08-12 12:00:07 +05:30
parent a1ea3aadc0
commit bf1a019d6c
22 changed files with 1237 additions and 570 deletions
+4
View File
@@ -25,6 +25,10 @@ frontend/.vite
.ruff_cache .ruff_cache
services/api/temp services/api/temp
# Database files — production uses MySQL via Docker service
*.db
*.sqlite3
# User uploads — stored in a named Docker volume, not in the image # User uploads — stored in a named Docker volume, not in the image
uploads uploads
+10 -1
View File
@@ -16,4 +16,13 @@ oauth_token.json
# User Uploads & Temp Data # User Uploads & Temp Data
uploads/ uploads/
services/temp/ services/temp/
# Blog / temporary files
*.md
*.docx
*.patch
*.msi
blog_images/
check_docs.py
openrouter_error.log
+1 -1
View File
@@ -19,7 +19,7 @@
<h4>Contact</h4> <h4>Contact</h4>
<p>📍 USA: McKinney, TX</p> <p>📍 USA: McKinney, TX</p>
<p>📍 India: Pune, Maharashtra</p> <p>📍 India: Pune, Maharashtra</p>
<p>📧 vedant.aiindia@gmail.com</p> <p>📧 atharvg.aiindia@gmail.com</p>
<p>📞 +918275367267</p> <p>📞 +918275367267</p>
</div> </div>
-1
View File
@@ -5,7 +5,6 @@
<link rel="icon" type="image/svg+xml" href="/vite.svg" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>BookKeepPro</title> <title>BookKeepPro</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet"/>
<link rel="stylesheet" href="/css/base.css"/> <link rel="stylesheet" href="/css/base.css"/>
<link rel="stylesheet" href="/css/components.css"/> <link rel="stylesheet" href="/css/components.css"/>
<link rel="stylesheet" href="/css/animations.css"/> <link rel="stylesheet" href="/css/animations.css"/>
+132 -98
View File
@@ -1,27 +1,26 @@
import { useState, useRef, useEffect } from 'react'; import { useState, useRef, useEffect, useCallback } from 'react';
import { useAuth } from '../context/AuthContext'; import { useAuth } from '../context/AuthContext';
import { useLocation } from 'react-router-dom'; import { useLocation } from 'react-router-dom';
const STORAGE_KEY = 'admin_chat_history';
const MAX_HISTORY = 40; // messages to persist
const FAQ_DATA = { const FAQ_DATA = {
"Document Review": [ "Document Review": [
{ q: "How do I review a document?", a: "From the Admin Dashboard, click on any user. You'll see their uploaded documents. Click Approve or Reject and leave a note if needed." }, { q: "How do I review a document?", a: "From the Admin Dashboard, click on any user. You'll see their uploaded documents. Click Approve or Reject and leave a note if needed." },
{ q: "What happens when I reject a document?", a: "The document's status changes to Rejected and the user is notified. They will see your review note and can upload a corrected version to replace it." }, { q: "What happens when I reject a document?", a: "The document status changes to Rejected and the user is notified. They can upload a corrected version." },
{ q: "How do I upload admin documents for a user?", a: "Go to the user's detail page and scroll down to Admin Documents. You can upload tax returns, reports, and other finalized forms there." } { q: "How do I upload admin documents for a user?", a: "Go to the user's detail page → Returns for Review tab → click '+ Upload Document'." }
], ],
"User Management": [ "User Management": [
{ q: "How do I see user details?", a: "Click on any user in the Admin Dashboard table to open their detailed view — documents, audit trail, and filing timeline." }, { q: "How do I see user details?", a: "Click any user in the Admin Dashboard table to open their full detail view." },
{ q: "Can I add another admin?", a: "Super Admins can only be created via the backend script `create_super_admin.py` for security reasons." } { q: "Can I add another admin?", a: "Super Admins can only be created via the backend script `create_super_admin.py`." }
], ],
"Notifications": [ "Notifications": [
{ q: "How are users notified?", a: "Users receive automated emails on signup, document submission, and when you approve or reject their documents." } { q: "How are users notified?", a: "Users receive emails on signup, document submission, and when you approve or reject their documents." }
] ]
}; };
const CATEGORY_ICONS = { const CATEGORY_ICONS = { "Document Review": "📑", "User Management": "👥", "Notifications": "🔔" };
"Document Review": "📑",
"User Management": "👥",
"Notifications": "🔔",
};
const formatMessage = (text) => { const formatMessage = (text) => {
if (!text) return ''; if (!text) return '';
@@ -36,42 +35,80 @@ export default function AdminChatbot() {
const { user, authFetch } = useAuth(); const { user, authFetch } = useAuth();
const location = useLocation(); const location = useLocation();
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const [messages, setMessages] = useState([]); const [view, setView] = useState('menu');
const [view, setView] = useState('menu'); // menu | category | chat
const [activeCategory, setActiveCategory] = useState(null); const [activeCategory, setActiveCategory] = useState(null);
const [inputText, setInputText] = useState(""); const [inputText, setInputText] = useState("");
const [menuInput, setMenuInput] = useState(""); // free-text from menu const [menuInput, setMenuInput] = useState("");
const [isTyping, setIsTyping] = useState(false); const [isTyping, setIsTyping] = useState(false);
const [pendingBulk, setPendingBulk] = useState(null); // bulk action awaiting confirmation
const chatEndRef = useRef(null); const chatEndRef = useRef(null);
useEffect(() => { setIsOpen(false); }, [location.pathname]); // ── Conversation memory via localStorage ──────────────────────────────────
const [messages, setMessages] = useState(() => {
try {
const saved = localStorage.getItem(STORAGE_KEY);
return saved ? JSON.parse(saved) : [];
} catch { return []; }
});
// Persist messages to localStorage whenever they change
useEffect(() => { useEffect(() => {
chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }); try {
}, [messages, view]); localStorage.setItem(STORAGE_KEY, JSON.stringify(messages.slice(-MAX_HISTORY)));
} catch { /* storage full — ignore */ }
}, [messages]);
const toggleChat = () => setIsOpen(o => !o); useEffect(() => { setIsOpen(false); }, [location.pathname]);
useEffect(() => { chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages, view]);
/* ── quick-action: system overview ── */ const clearHistory = () => {
setMessages([]);
localStorage.removeItem(STORAGE_KEY);
};
// ── System overview ───────────────────────────────────────────────────────
const handleAdminStatusCheck = async () => { const handleAdminStatusCheck = async () => {
setMessages(prev => [...prev, { type: 'user', text: 'Give me a system overview.' }]); setMessages(prev => [...prev, { type: 'user', role: 'user', text: 'Give me a system overview.' }]);
setView('chat'); setView('chat');
try { try {
const res = await authFetch('/api/chatbot/admin-status'); const res = await authFetch('/api/chatbot/admin-status');
if (res.ok) { if (res.ok) {
const data = await res.json(); const data = await res.json();
setMessages(prev => [...prev, { type: 'bot', text: data.message }]); setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: data.message }]);
} else { } else {
setMessages(prev => [...prev, { type: 'bot', text: 'Could not fetch system status right now.' }]); setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Could not fetch system status right now.' }]);
} }
} catch { } catch {
setMessages(prev => [...prev, { type: 'bot', text: 'Network error.' }]); setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Network error.' }]);
} }
}; };
/* ── send a message to /ask ── */ // ── Bulk action executor with confirmation ────────────────────────────────
const sendMessage = async (text, existingMessages) => { const executeBulkAction = async (action) => {
if (!action) return;
try {
const res = await authFetch('/api/chatbot/admin-bulk-action', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...action, confirm: true }),
});
if (res.ok) {
const data = await res.json();
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: `✅ ${data.message}` }]);
} else {
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Action failed. Please try from the user detail page.' }]);
}
} catch {
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Network error during bulk action.' }]);
} finally {
setPendingBulk(null);
}
};
// ── Send message (with full history for memory) ───────────────────────────
const sendMessage = useCallback(async (text, overrideMessages) => {
const userMsg = { type: 'user', role: 'user', text }; const userMsg = { type: 'user', role: 'user', text };
const allMessages = [...(existingMessages ?? messages), userMsg]; const allMessages = [...(overrideMessages ?? messages), userMsg];
setMessages(allMessages); setMessages(allMessages);
setInputText(""); setInputText("");
setMenuInput(""); setMenuInput("");
@@ -83,6 +120,7 @@ export default function AdminChatbot() {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ body: JSON.stringify({
stream: false,
messages: allMessages.map(m => ({ messages: allMessages.map(m => ({
role: m.role || (m.type === 'bot' ? 'assistant' : 'user'), role: m.role || (m.type === 'bot' ? 'assistant' : 'user'),
content: m.text, content: m.text,
@@ -90,9 +128,27 @@ export default function AdminChatbot() {
})), })),
}), }),
}); });
if (res.ok) { if (res.ok) {
const data = await res.json(); const data = await res.json();
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: data.content || "Sorry, I couldn't understand that." }]); const replyText = data.content || "Sorry, I couldn't understand that.";
// Check if response contains a bulk_action JSON block
const bulkMatch = replyText.match(/\{[^{}]*"bulk_action"[^{}]*\}/s);
if (bulkMatch) {
try {
const parsed = JSON.parse(bulkMatch[0]);
if (parsed.bulk_action) {
setPendingBulk(parsed.bulk_action);
const cleanText = replyText.replace(bulkMatch[0], '').trim();
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: cleanText || "I can do that. Please confirm below." }]);
setIsTyping(false);
return;
}
} catch { /* not valid JSON, render as text */ }
}
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: replyText }]);
} else { } else {
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Having trouble connecting. Please try again.' }]); setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Having trouble connecting. Please try again.' }]);
} }
@@ -101,123 +157,108 @@ export default function AdminChatbot() {
} finally { } finally {
setIsTyping(false); setIsTyping(false);
} }
}; }, [messages, authFetch]);
const handleSendMessage = async (e) => {
e.preventDefault();
if (!inputText.trim()) return;
await sendMessage(inputText.trim());
};
const handleMenuAsk = async (e) => {
e.preventDefault();
if (!menuInput.trim()) return;
await sendMessage(menuInput.trim(), []);
};
const handleSendMessage = (e) => { e.preventDefault(); if (inputText.trim()) sendMessage(inputText.trim()); };
const handleMenuAsk = (e) => { e.preventDefault(); if (menuInput.trim()) sendMessage(menuInput.trim(), []); };
const askFaq = (faq) => { const askFaq = (faq) => {
setMessages(prev => [...prev, { type: 'user', text: faq.q }, { type: 'bot', text: faq.a }]); setMessages(prev => [...prev, { type: 'user', text: faq.q }, { type: 'bot', text: faq.a }]);
setView('chat'); setView('chat');
}; };
if (!user || (user.role !== 'admin' && user.role !== 'super_admin') || !location.pathname.startsWith('/admin')) { if (!user || (user.role !== 'admin' && user.role !== 'super_admin') || !location.pathname.startsWith('/admin')) return null;
return null;
}
return ( return (
<> <>
<button <button className={`chatbot-fab ${isOpen ? 'open' : ''}`} onClick={() => setIsOpen(o => !o)}
className={`chatbot-fab ${isOpen ? 'open' : ''}`}
onClick={toggleChat}
aria-label="Open admin assistant" aria-label="Open admin assistant"
style={{ background: 'linear-gradient(135deg, var(--navy) 0%, var(--blue) 100%)' }} style={{ background: 'linear-gradient(135deg, var(--navy) 0%, var(--blue) 100%)' }}>
>
<span className="fab-icon">🤖</span> <span className="fab-icon">🤖</span>
<span className="notif-dot"></span> <span className="notif-dot"></span>
</button> </button>
{isOpen && ( {isOpen && (
<div className="chatbot-window visible"> <div className="chatbot-window visible">
{/* header */}
<div className="chatbot-header" style={{ background: 'var(--ink)' }}> <div className="chatbot-header" style={{ background: 'var(--ink)' }}>
<div className="bot-avatar">🤖</div> <div className="bot-avatar">🤖</div>
<div className="bot-info"> <div className="bot-info">
<h4>Admin Assistant</h4> <h4>Admin Assistant</h4>
<span>Live system insights</span> <span>Live system insights</span>
</div> </div>
<button className="close-chat" onClick={toggleChat}>✕</button> <div style={{ display: 'flex', gap: '4px', alignItems: 'center' }}>
{messages.length > 0 && (
<button onClick={clearHistory} title="Clear history"
style={{ background: 'none', border: 'none', color: 'rgba(255,255,255,0.6)', cursor: 'pointer', fontSize: '11px', padding: '4px' }}>
🗑
</button>
)}
<button className="close-chat" onClick={() => setIsOpen(false)}>✕</button>
</div>
</div> </div>
{/* messages area */}
<div className="chatbot-messages"> <div className="chatbot-messages">
{/* ── MENU VIEW ── */}
{view === 'menu' && ( {view === 'menu' && (
<> <>
<div className="chatbot-welcome-text"> <div className="chatbot-welcome-text">
<span className="material-symbols-outlined sparkle">auto_awesome</span> <span className="material-symbols-outlined sparkle">auto_awesome</span>
<p>What do you need today?</p> <p>What do you need today?</p>
</div> </div>
{/* free-text ask from menu */}
<form onSubmit={handleMenuAsk} style={{ marginBottom: '12px', display: 'flex', gap: '6px' }}> <form onSubmit={handleMenuAsk} style={{ marginBottom: '12px', display: 'flex', gap: '6px' }}>
<input <input type="text" value={menuInput} onChange={e => setMenuInput(e.target.value)}
type="text"
value={menuInput}
onChange={e => setMenuInput(e.target.value)}
placeholder="Ask anything… e.g. who uploaded today?" placeholder="Ask anything… e.g. who uploaded today?"
style={{ flex: 1, padding: '8px 12px', borderRadius: 'var(--radius-pill)', border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--navy)', fontSize: '13px' }} style={{ flex: 1, padding: '8px 12px', borderRadius: 'var(--radius-pill)', border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--navy)', fontSize: '13px' }} />
/> <button type="submit" style={{ background: 'var(--emerald)', color: '#fff', border: 'none', borderRadius: 'var(--radius-pill)', padding: '8px 14px', cursor: 'pointer', fontSize: '13px' }}>Ask</button>
<button type="submit" style={{ background: 'var(--emerald)', color: '#fff', border: 'none', borderRadius: 'var(--radius-pill)', padding: '8px 14px', cursor: 'pointer', fontSize: '13px' }}>
Ask
</button>
</form> </form>
<button className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '8px' }} onClick={handleAdminStatusCheck}> <button className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '8px' }} onClick={handleAdminStatusCheck}>
<span className="qr-icon">📊</span> System Overview <span className="qr-icon">📊</span> System Overview
</button> </button>
{messages.length > 0 && (
<button className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '8px' }} onClick={() => setView('chat')}>
<span className="qr-icon">💬</span> Continue conversation
</button>
)}
{Object.keys(FAQ_DATA).map(cat => ( {Object.keys(FAQ_DATA).map(cat => (
<button key={cat} className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '8px' }} onClick={() => { setActiveCategory(cat); setView('category'); }}> <button key={cat} className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '8px' }}
onClick={() => { setActiveCategory(cat); setView('category'); }}>
<span className="qr-icon">{CATEGORY_ICONS[cat]}</span> {cat} <span className="qr-icon">{CATEGORY_ICONS[cat]}</span> {cat}
</button> </button>
))} ))}
</> </>
)} )}
{/* ── CATEGORY VIEW ── */}
{view === 'category' && ( {view === 'category' && (
<> <>
<button className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '16px', background: 'transparent', border: 'none' }} onClick={() => setView('menu')}> <button className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '16px', background: 'transparent', border: 'none' }} onClick={() => setView('menu')}>← Back</button>
← Back to menu
</button>
<h4 style={{ margin: '0 0 12px', fontSize: '14px', color: 'var(--navy)' }}>{activeCategory}</h4> <h4 style={{ margin: '0 0 12px', fontSize: '14px', color: 'var(--navy)' }}>{activeCategory}</h4>
{FAQ_DATA[activeCategory].map((faq, i) => ( {FAQ_DATA[activeCategory].map((faq, i) => (
<button key={i} className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '8px' }} onClick={() => askFaq(faq)}> <button key={i} className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '8px' }} onClick={() => askFaq(faq)}>{faq.q}</button>
{faq.q}
</button>
))} ))}
</> </>
)} )}
{/* ── CHAT VIEW ── */}
{view === 'chat' && ( {view === 'chat' && (
<> <>
<button className="quick-reply-btn" onClick={() => setView('menu')} style={{ display: 'flex', width: '100%', marginBottom: '16px', background: 'transparent', border: 'none' }}> <button className="quick-reply-btn" onClick={() => setView('menu')}
← Back to menu style={{ display: 'flex', width: '100%', marginBottom: '16px', background: 'transparent', border: 'none' }}>← Back to menu</button>
</button>
{messages.map((msg, i) => ( {messages.map((msg, i) => (
<div <div key={i} className={`chat-msg ${msg.type === 'bot' ? 'bot' : 'user'}`}
key={i} {...(msg.type === 'bot' ? { dangerouslySetInnerHTML: { __html: formatMessage(msg.text) } } : { children: msg.text })} />
className={`chat-msg ${msg.type === 'bot' ? 'bot' : 'user'}`}
{...(msg.type === 'bot'
? { dangerouslySetInnerHTML: { __html: formatMessage(msg.text) } }
: { children: msg.text })}
/>
))} ))}
{isTyping && ( {isTyping && <div className="chat-msg bot" style={{ fontStyle: 'italic', opacity: 0.7 }}>Admin Assistant is typing…</div>}
<div className="chat-msg bot" style={{ fontStyle: 'italic', opacity: 0.7 }}>
Admin Assistant is typing… {/* Bulk action confirmation card */}
{pendingBulk && (
<div style={{ background: 'var(--warn-bg)', border: '1px solid var(--warn)', borderRadius: 'var(--radius-sm)', padding: '12px', margin: '8px 0' }}>
<div style={{ fontWeight: 700, fontSize: '13px', color: 'var(--warn)', marginBottom: '8px' }}>
⚠️ Confirm bulk action
</div>
<div style={{ fontSize: '13px', marginBottom: '10px' }}>
<b>{pendingBulk.action?.replace('_', ' ')}</b> all pending {pendingBulk.action?.split('_')[1]} docs for user ID {pendingBulk.user_id}?
</div>
<div style={{ display: 'flex', gap: '8px' }}>
<button className="btn btn-primary btn-sm" onClick={() => executeBulkAction(pendingBulk)}>Yes, execute</button>
<button className="btn btn-secondary btn-sm" onClick={() => { setPendingBulk(null); setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Cancelled. No changes made.' }]); }}>Cancel</button>
</div>
</div> </div>
)} )}
<div ref={chatEndRef} /> <div ref={chatEndRef} />
@@ -225,20 +266,13 @@ export default function AdminChatbot() {
)} )}
</div> </div>
{/* footer input — always shown in chat view */}
<div className="chatbot-footer" style={{ padding: '12px', borderTop: '1px solid var(--border)', background: 'var(--bg)' }}> <div className="chatbot-footer" style={{ padding: '12px', borderTop: '1px solid var(--border)', background: 'var(--bg)' }}>
{view === 'chat' ? ( {view === 'chat' ? (
<form onSubmit={handleSendMessage} style={{ display: 'flex', gap: '8px' }}> <form onSubmit={handleSendMessage} style={{ display: 'flex', gap: '8px' }}>
<input <input type="text" value={inputText} onChange={e => setInputText(e.target.value)}
type="text"
value={inputText}
onChange={e => setInputText(e.target.value)}
placeholder="Ask a question…" placeholder="Ask a question…"
style={{ flex: 1, padding: '8px 12px', borderRadius: 'var(--radius-pill)', border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--navy)' }} style={{ flex: 1, padding: '8px 12px', borderRadius: 'var(--radius-pill)', border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--navy)' }} />
/> <button type="submit" style={{ background: 'var(--emerald)', color: '#fff', border: 'none', borderRadius: 'var(--radius-pill)', padding: '8px 16px', cursor: 'pointer' }}>Send</button>
<button type="submit" style={{ background: 'var(--emerald)', color: '#fff', border: 'none', borderRadius: 'var(--radius-pill)', padding: '8px 16px', cursor: 'pointer' }}>
Send
</button>
</form> </form>
) : ( ) : (
<p style={{ margin: 0, fontSize: '13px', color: 'var(--muted)' }}>Admin tools &amp; shortcuts</p> <p style={{ margin: 0, fontSize: '13px', color: 'var(--muted)' }}>Admin tools &amp; shortcuts</p>
+161 -167
View File
@@ -1,176 +1,164 @@
import { useState, useRef, useEffect } from 'react'; import { useState, useRef, useEffect, useCallback } from 'react';
import { useAuth } from '../context/AuthContext'; import { useAuth } from '../context/AuthContext';
import { useLocation } from 'react-router-dom'; import { useLocation, useNavigate } from 'react-router-dom';
const STORAGE_KEY = 'user_chat_history';
const MAX_HISTORY = 30;
const FAQ_DATA = { const FAQ_DATA = {
// ... (keep the same FAQ_DATA below this)
"Account": [ "Account": [
{ q: "How do I reset my password?", a: 'Go to the login page and click "Forgot Password". Enter your email and we\'ll send a reset link to your inbox.' }, { q: "How do I reset my password?", a: 'Go to the login page and click "Forgot Password". Enter your email and we\'ll send a reset link.' },
{ q: "How do I verify my email?", a: 'Check your inbox for a verification email from BookKeepPro. Click the link inside to verify.' }, { q: "How do I verify my email?", a: 'Check your inbox for a verification email from BookKeepPro. Click the link inside to verify.' },
{ q: "How do I update my profile?", a: 'Go to your Profile page to update your name, phone number, or change your password.' }, { q: "How do I update my profile?", a: 'Go to your Profile page to update your name, phone number, or change your password.' },
], ],
"Documents": [ "Documents": [
{ q: "What file types are accepted?", a: "We accept PDF, JPG, PNG, WEBP, DOC, and DOCX files. The maximum file size is 10 MB." }, { q: "What file types are accepted?", a: "We accept PDF, JPG, PNG, WEBP, DOC, and DOCX files. Maximum file size is 10 MB." },
{ q: 'What does "Pending" status mean?', a: 'Your document has been uploaded successfully and is waiting for an admin to review it.' }, { q: 'What does "Pending" status mean?', a: 'Your document has been uploaded and is waiting for an admin to review it.' },
{ q: 'What does "Rejected" mean?', a: "The admin found an issue with your document. Check the review note for details." }, { q: 'What does "Rejected" mean?', a: "The admin found an issue. Check the review note for details and re-upload a corrected version." },
], ],
"Tax Filing": [ "Tax Filing": [
{ q: "What tax years are supported?", a: "We currently support tax years 2023, 2024, 2025, and 2026." }, { q: "What tax years are supported?", a: "We currently support tax years 2023, 2024, 2025, and 2026." },
{ q: "What personal documents do I need?", a: 'An Individual Taxpayer Organizer for your tax year.' }, { q: "What personal documents do I need?", a: 'An Individual Taxpayer Organizer for your tax year.' },
], ],
"Security": [ "Security": [
{ q: "Is my data secure?", a: "Absolutely. All files are stored securely on our servers with encrypted access tokens." }, { q: "Is my data secure?", a: "Yes. All files are stored securely on our servers with encrypted access tokens." },
] ]
}; };
const CATEGORY_ICONS = { const CATEGORY_ICONS = { "Account": "👤", "Documents": "📄", "Tax Filing": "📋", "Security": "🔒" };
"Account": "👤",
"Documents": "📄",
"Tax Filing": "📋",
"Security": "🔒"
};
const formatMessage = (text) => { const formatMessage = (text) => {
if (!text) return ''; if (!text) return '';
let html = text; return text
html = html.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>'); .replace(/\*\*(.*?)\*\*/g, '<b>$1</b>')
html = html.replace(/\*(.*?)\*/g, '<i>$1</i>'); .replace(/\*(.*?)\*/g, '<i>$1</i>')
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer" style="color: var(--blue); text-decoration: underline;">$1</a>'); .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" style="color:var(--blue);text-decoration:underline">$1</a>')
html = html.replace(/\n/g, '<br/>'); .replace(/\n/g, '<br/>');
return html;
}; };
export default function Chatbot() { export default function Chatbot() {
const { user, authFetch } = useAuth(); const { user, authFetch } = useAuth();
const location = useLocation(); const location = useLocation();
const [isOpen, setIsOpen] = useState(false); const navigate = useNavigate();
const [messages, setMessages] = useState([]); const [isOpen, setIsOpen] = useState(false);
const [view, setView] = useState('menu'); // menu, category, chat const [view, setView] = useState('menu');
const [activeCategory, setActiveCategory] = useState(null); const [activeCategory, setActiveCategory] = useState(null);
const [inputText, setInputText] = useState(""); const [inputText, setInputText] = useState("");
const [menuInput, setMenuInput] = useState(""); // free-text from menu const [menuInput, setMenuInput] = useState("");
const [isTyping, setIsTyping] = useState(false); const [isTyping, setIsTyping] = useState(false);
const chatEndRef = useRef(null); const chatEndRef = useRef(null);
// Close chatbot when navigating // ── Conversation memory via localStorage ──────────────────────────────────
useEffect(() => { const [messages, setMessages] = useState(() => {
setIsOpen(false); try {
}, [location.pathname]); const saved = localStorage.getItem(STORAGE_KEY);
return saved ? JSON.parse(saved) : [];
} catch { return []; }
});
useEffect(() => { useEffect(() => {
if (chatEndRef.current) { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(messages.slice(-MAX_HISTORY))); }
chatEndRef.current.scrollIntoView({ behavior: 'smooth' }); catch { /* storage full */ }
} }, [messages]);
}, [messages, view]);
const toggleChat = () => setIsOpen(!isOpen); useEffect(() => { setIsOpen(false); }, [location.pathname]);
useEffect(() => { chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages, view]);
const clearHistory = () => { setMessages([]); localStorage.removeItem(STORAGE_KEY); };
// ── Document status quick-check ────────────────────────────────────────────
const handleDocStatusCheck = async () => { const handleDocStatusCheck = async () => {
if (!user) { if (!user) return;
setMessages([...messages, { type: 'bot', text: 'You need to log in to check your document status.' }]); setMessages(prev => [...prev, { type: 'user', role: 'user', text: 'Check my document status' }]);
setView('chat');
return;
}
setMessages([...messages, { type: 'user', text: 'Check my document status' }]);
setView('chat'); setView('chat');
try { try {
const res = await authFetch('/api/chatbot/doc-status'); const res = await authFetch('/api/chatbot/doc-status');
if (res.ok) { if (res.ok) {
const data = await res.json(); const data = await res.json();
setMessages(prev => [...prev, { type: 'bot', text: data.message }]); setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: data.message }]);
} else { } else {
setMessages(prev => [...prev, { type: 'bot', text: 'Sorry, I could not fetch your document status right now.' }]); setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Could not fetch your document status right now.' }]);
} }
} catch (err) { } catch {
setMessages(prev => [...prev, { type: 'bot', text: 'Network error occurred.' }]); setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Network error occurred.' }]);
} }
}; };
const selectCategory = (cat) => { // ── Upload shortcut (deeplink) ─────────────────────────────────────────────
setActiveCategory(cat); const handleUploadShortcut = (type) => {
setView('category'); setIsOpen(false);
navigate(type === 'personal' ? '/upload-personal' : '/upload-business');
}; };
// ── Send message with full history for memory ──────────────────────────────
const sendMessage = useCallback(async (text, overrideMessages) => {
const userMsg = { type: 'user', role: 'user', text };
const allMessages = [...(overrideMessages ?? messages), userMsg];
setMessages(allMessages);
setInputText("");
setMenuInput("");
setView('chat');
setIsTyping(true);
// Detect upload intent — shortcut before hitting API
const lower = text.toLowerCase();
if (lower.includes('upload') && (lower.includes('personal') || lower.includes('w-2') || lower.includes('w2'))) {
setIsTyping(false);
setMessages(prev => [...prev, {
type: 'bot', role: 'assistant',
text: 'I can take you there directly! Click below to go to the Personal Upload page.',
action: { type: 'navigate', dest: 'personal', label: '📄 Go to Personal Upload' }
}]);
return;
}
if (lower.includes('upload') && (lower.includes('business') || lower.includes('llc') || lower.includes('1099'))) {
setIsTyping(false);
setMessages(prev => [...prev, {
type: 'bot', role: 'assistant',
text: 'I can take you there directly! Click below to go to the Business Upload page.',
action: { type: 'navigate', dest: 'business', label: '🏢 Go to Business Upload' }
}]);
return;
}
try {
const res = await authFetch('/api/chatbot/ask', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
stream: false,
messages: allMessages.map(m => ({
role: m.role || (m.type === 'bot' ? 'assistant' : 'user'),
content: m.text,
reasoning_details: null,
})),
}),
});
if (res.ok) {
const data = await res.json();
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: data.content || "Sorry, I couldn't understand that." }]);
} else {
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Having trouble connecting. Please try again.' }]);
}
} catch {
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Network error. Please try again.' }]);
} finally {
setIsTyping(false);
}
}, [messages, authFetch]);
const handleSendMessage = (e) => { e.preventDefault(); if (inputText.trim()) sendMessage(inputText.trim()); };
const handleMenuAsk = (e) => { e.preventDefault(); if (menuInput.trim()) sendMessage(menuInput.trim(), []); };
const askFaq = (faq) => { const askFaq = (faq) => {
setMessages(prev => [...prev, { type: 'user', text: faq.q }, { type: 'bot', text: faq.a }]); setMessages(prev => [...prev, { type: 'user', text: faq.q }, { type: 'bot', text: faq.a }]);
setView('chat'); setView('chat');
}; };
const resetToMenu = () => { if (!user || user.role === 'admin' || user.role === 'super_admin' || location.pathname.startsWith('/admin')) return null;
setView('menu');
};
const handleSendMessage = async (e) => {
e.preventDefault();
if (!inputText.trim()) return;
const userMessage = { type: 'user', role: 'user', text: inputText.trim() };
const currentMessages = [...messages, userMessage];
setMessages(currentMessages);
setInputText("");
setView('chat');
setIsTyping(true);
try {
const backendMessages = currentMessages.map(m => ({
role: m.role || (m.type === 'bot' ? 'assistant' : 'user'),
content: m.text,
reasoning_details: null,
}));
const res = await authFetch('/api/chatbot/ask', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ messages: backendMessages }),
});
if (res.ok) {
const data = await res.json();
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: data.content || "Sorry, I couldn't understand that." }]);
} else {
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Having trouble connecting. Please try again.' }]);
}
} catch {
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Network error. Please try again.' }]);
} finally {
setIsTyping(false);
}
};
const handleMenuAsk = async (e) => {
e.preventDefault();
if (!menuInput.trim()) return;
const userMessage = { type: 'user', role: 'user', text: menuInput.trim() };
setMessages([userMessage]);
setMenuInput("");
setView('chat');
setIsTyping(true);
try {
const res = await authFetch('/api/chatbot/ask', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ messages: [{ role: 'user', content: userMessage.text, reasoning_details: null }] }),
});
if (res.ok) {
const data = await res.json();
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: data.content || "Sorry, I couldn't understand that." }]);
} else {
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Having trouble connecting. Please try again.' }]);
}
} catch {
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Network error. Please try again.' }]);
} finally {
setIsTyping(false);
}
};
if (!user || user.role === 'admin' || user.role === 'super_admin' || location.pathname.startsWith('/admin')) {
return null; // Admin has a different dashboard, and logged out users shouldn't see it
}
return ( return (
<> <>
<button className={`chatbot-fab ${isOpen ? 'open' : ''}`} onClick={toggleChat} aria-label="Open chat assistant"> <button className={`chatbot-fab ${isOpen ? 'open' : ''}`} onClick={() => setIsOpen(o => !o)} aria-label="Open chat assistant">
<span className="fab-icon">💬</span> <span className="fab-icon">💬</span>
<span className="notif-dot"></span> <span className="notif-dot"></span>
</button> </button>
@@ -179,11 +167,14 @@ export default function Chatbot() {
<div className="chatbot-window visible"> <div className="chatbot-window visible">
<div className="chatbot-header"> <div className="chatbot-header">
<div className="bot-avatar">🤖</div> <div className="bot-avatar">🤖</div>
<div className="bot-info"> <div className="bot-info"><h4>BookKeep Assistant</h4><span>Online and ready to help</span></div>
<h4>BookKeep Assistant</h4> <div style={{ display: 'flex', gap: '4px', alignItems: 'center' }}>
<span>Online and ready to help</span> {messages.length > 0 && (
<button onClick={clearHistory} title="Clear history"
style={{ background: 'none', border: 'none', color: 'var(--muted)', cursor: 'pointer', fontSize: '11px', padding: '4px' }}>🗑</button>
)}
<button className="close-chat" onClick={() => setIsOpen(false)}>✕</button>
</div> </div>
<button className="close-chat" onClick={toggleChat}>✕</button>
</div> </div>
<div className="chatbot-messages"> <div className="chatbot-messages">
@@ -193,29 +184,36 @@ export default function Chatbot() {
<span className="material-symbols-outlined sparkle">auto_awesome</span> <span className="material-symbols-outlined sparkle">auto_awesome</span>
<p>How can we help you today?</p> <p>How can we help you today?</p>
</div> </div>
{/* free-text ask from menu */}
<form onSubmit={handleMenuAsk} style={{ marginBottom: '12px', display: 'flex', gap: '6px' }}> <form onSubmit={handleMenuAsk} style={{ marginBottom: '12px', display: 'flex', gap: '6px' }}>
<input <input type="text" value={menuInput} onChange={e => setMenuInput(e.target.value)}
type="text"
value={menuInput}
onChange={e => setMenuInput(e.target.value)}
placeholder="Ask anything…" placeholder="Ask anything…"
style={{ flex: 1, padding: '8px 12px', borderRadius: 'var(--radius-pill)', border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--navy)', fontSize: '13px' }} style={{ flex: 1, padding: '8px 12px', borderRadius: 'var(--radius-pill)', border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--navy)', fontSize: '13px' }} />
/> <button type="submit" style={{ background: 'var(--emerald)', color: '#fff', border: 'none', borderRadius: 'var(--radius-pill)', padding: '8px 14px', cursor: 'pointer', fontSize: '13px' }}>Ask</button>
<button type="submit" style={{ background: 'var(--emerald)', color: '#fff', border: 'none', borderRadius: 'var(--radius-pill)', padding: '8px 14px', cursor: 'pointer', fontSize: '13px' }}>
Ask
</button>
</form> </form>
{/* Upload shortcuts */}
<div style={{ display: 'flex', gap: '8px', marginBottom: '10px' }}>
<button className="quick-reply-btn" style={{ flex: 1 }} onClick={() => handleUploadShortcut('personal')}>
📄 Upload Personal Docs
</button>
<button className="quick-reply-btn" style={{ flex: 1 }} onClick={() => handleUploadShortcut('business')}>
🏢 Upload Business Docs
</button>
</div>
{user && ( {user && (
<button className="quick-reply-btn" style={{display: 'flex', width: '100%', marginBottom: '8px'}} onClick={handleDocStatusCheck}> <button className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '8px' }} onClick={handleDocStatusCheck}>
<span className="qr-icon">📋</span> <span className="qr-icon">📋</span> Check Document Status
Check Document Status </button>
)}
{messages.length > 0 && (
<button className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '8px' }} onClick={() => setView('chat')}>
<span className="qr-icon">💬</span> Continue conversation
</button> </button>
)} )}
{Object.keys(FAQ_DATA).map(cat => ( {Object.keys(FAQ_DATA).map(cat => (
<button key={cat} className="quick-reply-btn" style={{display: 'flex', width: '100%', marginBottom: '8px'}} onClick={() => selectCategory(cat)}> <button key={cat} className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '8px' }}
onClick={() => { setActiveCategory(cat); setView('category'); }}>
<span className="qr-icon">{CATEGORY_ICONS[cat]}</span> {cat} FAQ <span className="qr-icon">{CATEGORY_ICONS[cat]}</span> {cat} FAQ
</button> </button>
))} ))}
@@ -224,52 +222,48 @@ export default function Chatbot() {
{view === 'category' && ( {view === 'category' && (
<> <>
<button className="quick-reply-btn" style={{display: 'flex', width: '100%', marginBottom: '16px', background: 'transparent', border: 'none'}} onClick={resetToMenu}>← Back to menu</button> <button className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '16px', background: 'transparent', border: 'none' }} onClick={() => setView('menu')}>← Back</button>
<h4 style={{margin:'0 0 12px', fontSize:'14px', color:'var(--navy)'}}>{activeCategory} Questions</h4> <h4 style={{ margin: '0 0 12px', fontSize: '14px', color: 'var(--navy)' }}>{activeCategory} Questions</h4>
{FAQ_DATA[activeCategory].map((faq, i) => ( {FAQ_DATA[activeCategory].map((faq, i) => (
<button key={i} className="quick-reply-btn" style={{display: 'flex', width: '100%', marginBottom: '8px'}} onClick={() => askFaq(faq)}> <button key={i} className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '8px' }} onClick={() => askFaq(faq)}>{faq.q}</button>
{faq.q}
</button>
))} ))}
</> </>
)} )}
{view === 'chat' && ( {view === 'chat' && (
<> <>
<button className="quick-reply-btn" onClick={resetToMenu} style={{display: 'flex', width: '100%', marginBottom: '16px', background: 'transparent', border: 'none'}}> <button className="quick-reply-btn" onClick={() => setView('menu')} style={{ display: 'flex', width: '100%', marginBottom: '16px', background: 'transparent', border: 'none' }}>← Back to menu</button>
← Back to menu
</button>
{messages.map((msg, i) => ( {messages.map((msg, i) => (
<div key={i} className={`chat-msg ${msg.type === 'bot' ? 'bot' : 'user'}`} <div key={i}>
{...(msg.type === 'bot' ? { dangerouslySetInnerHTML: { __html: formatMessage(msg.text) } } : { children: msg.text })} <div className={`chat-msg ${msg.type === 'bot' ? 'bot' : 'user'}`}
/> {...(msg.type === 'bot' ? { dangerouslySetInnerHTML: { __html: formatMessage(msg.text) } } : { children: msg.text })} />
))} {/* Upload action button if bot suggested navigation */}
{isTyping && ( {msg.action?.type === 'navigate' && (
<div className="chat-msg bot" style={{ fontStyle: 'italic', opacity: 0.7 }}> <div style={{ marginTop: '6px', marginLeft: '12px' }}>
BookKeep Assistant is typing... <button className="btn btn-primary btn-sm" style={{ borderRadius: 'var(--radius-pill)' }}
onClick={() => handleUploadShortcut(msg.action.dest)}>
{msg.action.label}
</button>
</div>
)}
</div> </div>
)} ))}
{isTyping && <div className="chat-msg bot" style={{ fontStyle: 'italic', opacity: 0.7 }}>BookKeep Assistant is typing…</div>}
<div ref={chatEndRef} /> <div ref={chatEndRef} />
</> </>
)} )}
</div> </div>
<div className="chatbot-footer" style={{ padding: '12px', borderTop: '1px solid var(--border)', background: 'var(--bg)' }}> <div className="chatbot-footer" style={{ padding: '12px', borderTop: '1px solid var(--border)', background: 'var(--bg)' }}>
{view === 'chat' ? ( {view === 'chat' ? (
<form onSubmit={handleSendMessage} style={{ display: 'flex', gap: '8px' }}> <form onSubmit={handleSendMessage} style={{ display: 'flex', gap: '8px' }}>
<input <input type="text" value={inputText} onChange={e => setInputText(e.target.value)}
type="text"
value={inputText}
onChange={(e) => setInputText(e.target.value)}
placeholder="Ask a question..." placeholder="Ask a question..."
style={{ flex: 1, padding: '8px 12px', borderRadius: 'var(--radius-pill)', border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--navy)' }} style={{ flex: 1, padding: '8px 12px', borderRadius: 'var(--radius-pill)', border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--navy)' }} />
/> <button type="submit" style={{ background: 'var(--emerald)', color: '#fff', border: 'none', borderRadius: 'var(--radius-pill)', padding: '8px 16px', cursor: 'pointer' }}>Send</button>
<button type="submit" style={{ background: 'var(--emerald)', color: '#fff', border: 'none', borderRadius: 'var(--radius-pill)', padding: '8px 16px', cursor: 'pointer' }}>
Send
</button>
</form> </form>
) : ( ) : (
<p style={{ margin: 0 }}>Need more help? <a href="/contact">Contact Support</a></p> <p style={{ margin: 0, fontSize: '13px', color: 'var(--muted)' }}>Need more help? <a href="/contact">Contact Support</a></p>
)} )}
</div> </div>
</div> </div>
@@ -1,10 +1,20 @@
import { useState } from 'react'; import { useState } from 'react';
import ExpandableValue from './ExpandableValue'; import ExpandableValue from './ExpandableValue';
const CONFIDENCE_STYLES = {
high: { icon: '🟢', color: 'var(--success)', bg: 'var(--success-bg)' },
medium: { icon: '🟡', color: 'var(--warn)', bg: 'var(--warn-bg)' },
low: { icon: '🟠', color: '#d97706', bg: '#fff7ed' },
unknown: { icon: '⚪', color: 'var(--muted)', bg: 'var(--paper)' },
};
export default function ExpandableSummaryBlock({ extractedData }) { export default function ExpandableSummaryBlock({ extractedData }) {
const [expanded, setExpanded] = useState(false); const [expanded, setExpanded] = useState(false);
const entries = Object.entries(extractedData); // Separate _meta from the actual data fields
const { _meta, ...dataFields } = extractedData || {};
const entries = Object.entries(dataFields);
if (entries.length === 0) { if (entries.length === 0) {
return ( return (
<div style={{ fontSize: '12px', color: 'var(--muted)', fontStyle: 'italic' }}> <div style={{ fontSize: '12px', color: 'var(--muted)', fontStyle: 'italic' }}>
@@ -15,12 +25,38 @@ export default function ExpandableSummaryBlock({ extractedData }) {
const showToggle = entries.length > 3; const showToggle = entries.length > 3;
const entriesToShow = expanded ? entries : entries.slice(0, 3); const entriesToShow = expanded ? entries : entries.slice(0, 3);
const confidenceStyle = CONFIDENCE_STYLES[_meta?.tier] || CONFIDENCE_STYLES.unknown;
return ( return (
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}> <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
{/* Confidence tier badge */}
{_meta && (
<div
title={_meta.description}
style={{
display: 'inline-flex',
alignItems: 'center',
gap: '5px',
fontSize: '10px',
fontWeight: 700,
fontFamily: 'var(--font-mono)',
color: confidenceStyle.color,
background: confidenceStyle.bg,
padding: '2px 8px',
borderRadius: 'var(--radius-xs)',
alignSelf: 'flex-start',
cursor: 'help',
letterSpacing: '0.3px',
}}
>
{confidenceStyle.icon} {_meta.label}
</div>
)}
{/* Field rows */}
{entriesToShow.map(([key, value]) => ( {entriesToShow.map(([key, value]) => (
<div key={key}> <div key={key}>
{/* Field label — uppercase, bold, navy */}
<div style={{ <div style={{
fontSize: '11px', fontSize: '11px',
color: 'var(--navy)', color: 'var(--navy)',
@@ -31,7 +67,6 @@ export default function ExpandableSummaryBlock({ extractedData }) {
}}> }}>
{key} {key}
</div> </div>
{/* Field value — bold navy */}
<div style={{ fontSize: '13px', fontWeight: 600, color: 'var(--navy)' }}> <div style={{ fontSize: '13px', fontWeight: 600, color: 'var(--navy)' }}>
<ExpandableValue value={value} isArray={Array.isArray(value)} /> <ExpandableValue value={value} isArray={Array.isArray(value)} />
</div> </div>
+35
View File
@@ -19,6 +19,21 @@ export default function AdminDashboard() {
const [tplFile, setTplFile] = useState(null); const [tplFile, setTplFile] = useState(null);
const [tplLoading, setTplLoading] = useState(false); const [tplLoading, setTplLoading] = useState(false);
const [digestHtml, setDigestHtml] = useState(null);
const [digestLoading, setDigestLoading] = useState(false);
const fetchDigest = useCallback(async () => {
setDigestLoading(true);
try {
const res = await authFetch('/api/chatbot/daily-digest');
if (res.ok) {
const data = await res.json();
setDigestHtml(data.digest);
}
} catch (err) { console.error(err); }
finally { setDigestLoading(false); }
}, [authFetch]);
const fetchAdminData = useCallback(async () => { const fetchAdminData = useCallback(async () => {
setLoading(true); setLoading(true);
try { try {
@@ -156,6 +171,26 @@ export default function AdminDashboard() {
{/* Users Tab */} {/* Users Tab */}
{tab === 'users' && ( {tab === 'users' && (
<> <>
{/* Daily Digest */}
<div className="card" style={{ marginBottom: '20px', background: 'var(--emerald-light)', border: '1px solid rgba(31,93,70,0.2)' }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: '12px' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
<span className="material-symbols-outlined" style={{ color: 'var(--emerald)', fontSize: '22px' }}>auto_awesome</span>
<div>
<div style={{ fontWeight: 700, fontSize: '14px', color: 'var(--navy)' }}>AI Daily Digest</div>
<div style={{ fontSize: '12px', color: 'var(--muted)' }}>Plain-English summary of today's activity</div>
</div>
</div>
<button className="btn btn-secondary btn-sm" onClick={fetchDigest} disabled={digestLoading} style={{ borderRadius: 'var(--radius-sm)' }}>
{digestLoading ? 'Generating…' : '✨ Generate Digest'}
</button>
</div>
{digestHtml && (
<div style={{ marginTop: '12px', paddingTop: '12px', borderTop: '1px solid rgba(31,93,70,0.2)', fontSize: '13px', color: 'var(--navy)', lineHeight: '1.7' }}
dangerouslySetInnerHTML={{ __html: digestHtml }} />
)}
</div>
{/* Stats Bar */} {/* Stats Bar */}
<div className="admin-stats"> <div className="admin-stats">
<div className="stat-card accent-blue"> <div className="stat-card accent-blue">
+7 -3
View File
@@ -4,6 +4,7 @@ import { useAuth } from '../context/AuthContext';
import { useToast } from '../context/ToastContext'; import { useToast } from '../context/ToastContext';
import ExpandableSummaryBlock from '../components/ExpandableSummaryBlock'; import ExpandableSummaryBlock from '../components/ExpandableSummaryBlock';
export default function AdminUserDetail() { export default function AdminUserDetail() {
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const userId = searchParams.get('user_id'); const userId = searchParams.get('user_id');
@@ -17,6 +18,7 @@ export default function AdminUserDetail() {
const [taxYear, setTaxYear] = useState(""); const [taxYear, setTaxYear] = useState("");
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
// States for Review Emails // States for Review Emails
const [personalTimeline, setPersonalTimeline] = useState(0); const [personalTimeline, setPersonalTimeline] = useState(0);
const [businessTimeline, setBusinessTimeline] = useState(0); const [businessTimeline, setBusinessTimeline] = useState(0);
@@ -41,10 +43,8 @@ export default function AdminUserDetail() {
const payload = await res.json(); const payload = await res.json();
setUserDetail(payload.user); setUserDetail(payload.user);
// Map 'table' to 'type' for personal and business docs
const userDocs = (payload.documents || []).map(d => ({ ...d, type: d.table })); const userDocs = (payload.documents || []).map(d => ({ ...d, type: d.table }));
// Fetch admin docs separately
const adminDocsRes = await authFetch(`/api/upload/admin-documents?user_id=${userId}`); const adminDocsRes = await authFetch(`/api/upload/admin-documents?user_id=${userId}`);
let adminDocs = []; let adminDocs = [];
if (adminDocsRes.ok) { if (adminDocsRes.ok) {
@@ -52,7 +52,10 @@ export default function AdminUserDetail() {
adminDocs = adminDocs.map(d => ({ ...d, type: 'admin', uploaded_at: d.created_at })); adminDocs = adminDocs.map(d => ({ ...d, type: 'admin', uploaded_at: d.created_at }));
} }
setDocuments([...userDocs, ...adminDocs]); const allDocs = [...userDocs, ...adminDocs];
setDocuments(allDocs);
} catch (err) { } catch (err) {
console.error(err); console.error(err);
} finally { } finally {
@@ -338,6 +341,7 @@ export default function AdminUserDetail() {
</div> </div>
</div> </div>
{/* Tabs */} {/* Tabs */}
<div className="tab-bar"> <div className="tab-bar">
<button className={`tab-btn ${activeTab === 'personal' ? 'active' : ''}`} onClick={() => setActiveTab('personal')}><span className="material-symbols-outlined">description</span> Personal Docs</button> <button className={`tab-btn ${activeTab === 'personal' ? 'active' : ''}`} onClick={() => setActiveTab('personal')}><span className="material-symbols-outlined">description</span> Personal Docs</button>
+16 -2
View File
@@ -24,7 +24,12 @@ export default function Login() {
}); });
if (!res.ok) { if (!res.ok) {
throw new Error("Invalid credentials"); const errData = await res.json().catch(() => ({}));
if (res.status === 403 && errData.detail === "EMAIL_NOT_VERIFIED") {
setError("EMAIL_NOT_VERIFIED");
return;
}
throw new Error(errData.detail || "Invalid credentials");
} }
const data = await res.json(); const data = await res.json();
@@ -60,7 +65,16 @@ export default function Login() {
<h1>Sign In</h1> <h1>Sign In</h1>
<p className="auth-subtitle">Enter your credentials to continue</p> <p className="auth-subtitle">Enter your credentials to continue</p>
{error && <div style={{color: 'var(--error)', marginBottom: '1rem', fontSize: '14px'}}>{error}</div>} {error && (
<div style={{color: 'var(--error)', marginBottom: '1rem', fontSize: '14px'}}>
{error === 'EMAIL_NOT_VERIFIED' ? (
<>
Your email is not verified. Please check your inbox or{' '}
<Link to="/resend-verification" className="fancy-link">resend the verification link</Link>.
</>
) : error}
</div>
)}
<form onSubmit={handleLogin}> <form onSubmit={handleLogin}>
<div className="form-group"> <div className="form-group">
-58
View File
@@ -1,58 +0,0 @@
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {
colors: {
brand: {
blue: '#0077C8',
'blue-dark': '#005fa3',
'blue-light': '#e9f5ff',
orange: '#FF7F11',
'orange-dark': '#e56e0d',
'orange-light': '#fff3e0',
navy: '#0B2540',
accent: '#3AB4F2',
bg: '#f1f7fb',
card: '#ffffff',
muted: '#6b7a86',
border: '#e2eaf2',
},
status: {
success: '#2e7d32',
'success-bg': '#e6f9ec',
error: '#c62828',
'error-bg': '#fdecea',
warn: '#f57f17',
'warn-bg': '#fff8e1',
},
header: {
bg: '#BEE2FA',
},
footer: {
bot: '#A9D9F8',
}
},
fontFamily: {
sans: ['Poppins', 'system-ui', 'sans-serif'],
},
borderRadius: {
'xs': '6px',
'sm': '10px',
'md': '14px',
'lg': '20px',
'pill': '999px',
},
boxShadow: {
'xs': '0 1px 4px rgba(0,0,0,0.06)',
'sm': '0 2px 10px rgba(0,0,0,0.07)',
'md': '0 6px 24px rgba(0,0,0,0.09)',
'lg': '0 16px 48px rgba(0,0,0,0.12)',
}
},
},
plugins: [],
}
+8 -6
View File
@@ -95,7 +95,7 @@ async def forgot_password(
reset_token = create_password_reset_token(user.email) reset_token = create_password_reset_token(user.email)
frontend_url = os.getenv("FRONTEND_URL", "https://bookkeepro.net") frontend_url = os.getenv("FRONTEND_URL", "https://aiindiacpa.duckdns.org")
reset_link = f"{frontend_url}/reset-password?token={reset_token}" reset_link = f"{frontend_url}/reset-password?token={reset_token}"
reset_body = ( reset_body = (
@@ -240,7 +240,7 @@ async def signup(request: Request, payload: SignupRequest, background: Backgroun
# Send verification email in background (non-blocking) # Send verification email in background (non-blocking)
if not is_admin: if not is_admin:
verify_token = create_email_verification_token(user.email) verify_token = create_email_verification_token(user.email)
frontend_url = os.getenv("FRONTEND_URL", "https://bookkeepro.net") frontend_url = os.getenv("FRONTEND_URL", "https://aiindiacpa.duckdns.org")
verify_link = f"{frontend_url}/verify-email?token={verify_token}" verify_link = f"{frontend_url}/verify-email?token={verify_token}"
verify_body = ( verify_body = (
f"Hi {user.name},<br><br>" f"Hi {user.name},<br><br>"
@@ -335,7 +335,9 @@ def verify_email(token: str, db: Session = Depends(get_db)):
@router.post("/resend-verification") @router.post("/resend-verification")
@limiter.limit("3/hour")
async def resend_verification( async def resend_verification(
request: Request,
payload: ResendVerificationRequest, payload: ResendVerificationRequest,
background: BackgroundTasks, background: BackgroundTasks,
db: Session = Depends(get_db), db: Session = Depends(get_db),
@@ -347,7 +349,7 @@ async def resend_verification(
return {"message": "If the email exists and is unverified, a new link has been sent"} return {"message": "If the email exists and is unverified, a new link has been sent"}
verify_token = create_email_verification_token(user.email) verify_token = create_email_verification_token(user.email)
frontend_url = os.getenv("FRONTEND_URL", "https://bookkeepro.net") frontend_url = os.getenv("FRONTEND_URL", "https://aiindiacpa.duckdns.org")
verify_link = f"{frontend_url}/verify-email?token={verify_token}" verify_link = f"{frontend_url}/verify-email?token={verify_token}"
resend_body = ( resend_body = (
@@ -383,7 +385,7 @@ def me(current_user=Depends(get_current_user)):
"phone": current_user.phone, "phone": current_user.phone,
"role": role, "role": role,
"engagement_acknowledged_at": ( "engagement_acknowledged_at": (
current_user.engagement_acknowledged_at.isoformat() current_user.engagement_acknowledged_at.isoformat() + "Z"
if current_user.engagement_acknowledged_at else None if current_user.engagement_acknowledged_at else None
), ),
} }
@@ -405,7 +407,7 @@ def acknowledge_engagement(
crud.log_action(db, "engagement_acknowledged", user_id=current_user.id) crud.log_action(db, "engagement_acknowledged", user_id=current_user.id)
return { return {
"acknowledged": True, "acknowledged": True,
"acknowledged_at": current_user.engagement_acknowledged_at.isoformat(), "acknowledged_at": current_user.engagement_acknowledged_at.isoformat() + "Z",
} }
@@ -539,7 +541,7 @@ def get_audit_logs(
"target": l.target, "target": l.target,
"detail": l.detail, "detail": l.detail,
"ip_address": l.ip_address, "ip_address": l.ip_address,
"created_at": l.created_at.isoformat() if l.created_at else None, "created_at": l.created_at.isoformat() + "Z" if l.created_at else None,
} }
for l in logs for l in logs
] ]
+1 -1
View File
@@ -61,7 +61,7 @@ _ALLOWED_ORIGINS = [
o.strip() o.strip()
for o in os.getenv( for o in os.getenv(
"ALLOWED_ORIGINS", "ALLOWED_ORIGINS",
"https://aiindiacpa.duckdns.org,http://localhost:8000", "https://aiindiacpa.duckdns.org",
).split(",") ).split(",")
if o.strip() if o.strip()
] ]
+2
View File
@@ -63,6 +63,7 @@ class PersonalDocument(Base):
review_note = Column(String(500), nullable=True) review_note = Column(String(500), nullable=True)
tax_year = Column(Integer, default=2025, nullable=False) tax_year = Column(Integer, default=2025, nullable=False)
extracted_data = Column(JSON, nullable=True) extracted_data = Column(JSON, nullable=True)
file_hash = Column(String(64), nullable=True, index=True) # SHA-256 for dedup
user = relationship("User") user = relationship("User")
@@ -90,6 +91,7 @@ class BusinessDocument(Base):
review_note = Column(String(500), nullable=True) review_note = Column(String(500), nullable=True)
tax_year = Column(Integer, default=2025, nullable=False) tax_year = Column(Integer, default=2025, nullable=False)
extracted_data = Column(JSON, nullable=True) extracted_data = Column(JSON, nullable=True)
file_hash = Column(String(64), nullable=True, index=True) # SHA-256 for dedup
user = relationship("User") user = relationship("User")
+208 -110
View File
@@ -1,12 +1,14 @@
import logging import logging
from datetime import datetime, date, timedelta import json
from datetime import datetime, date
from fastapi import APIRouter, Depends, Request, Query from fastapi import APIRouter, Depends, Request, Query
from fastapi.responses import StreamingResponse
from app.limiter import limiter from app.limiter import limiter
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from sqlalchemy import func, or_ from sqlalchemy import func, or_
import os import os
import requests import requests
from pydantic import BaseModel from pydantic import BaseModel, field_validator
from fastapi import HTTPException from fastapi import HTTPException
from app.models import PersonalDocument, BusinessDocument, User, AuditLog from app.models import PersonalDocument, BusinessDocument, User, AuditLog
from app.db import get_db from app.db import get_db
@@ -16,16 +18,17 @@ logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/chatbot", tags=["chatbot"]) router = APIRouter(prefix="/api/chatbot", tags=["chatbot"])
CHAT_MODEL = os.getenv("CHAT_MODEL", "meta-llama/llama-3.3-70b-instruct")
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
# User: doc status # User: doc status (also includes extracted data so user can ask about fields)
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
@router.get("/doc-status") @router.get("/doc-status")
def get_doc_status( def get_doc_status(
db: Session = Depends(get_db), db: Session = Depends(get_db),
current_user=Depends(get_current_user), current_user=Depends(get_current_user),
): ):
"""Return a consolidated summary of the user's document statuses."""
personal = ( personal = (
db.query(PersonalDocument) db.query(PersonalDocument)
.filter(PersonalDocument.user_id == current_user.id, PersonalDocument.deleted_at == None) .filter(PersonalDocument.user_id == current_user.id, PersonalDocument.deleted_at == None)
@@ -41,12 +44,15 @@ def get_doc_status(
personal_list = [ personal_list = [
{"doc_type": d.doc_type, "status": d.review_status, "note": d.review_note, {"doc_type": d.doc_type, "status": d.review_status, "note": d.review_note,
"tax_year": d.tax_year, "filename": d.filename} "tax_year": d.tax_year, "filename": d.filename,
# Include extracted data summary so chatbot can answer field-level questions
"extracted_summary": _summarize_extracted(d.extracted_data)}
for d in personal for d in personal
] ]
business_list = [ business_list = [
{"business_type": d.business_type, "status": d.review_status, "note": d.review_note, {"business_type": d.business_type, "status": d.review_status, "note": d.review_note,
"tax_year": d.tax_year, "filename": d.filename} "tax_year": d.tax_year, "filename": d.filename,
"extracted_summary": _summarize_extracted(d.extracted_data)}
for d in business for d in business
] ]
@@ -74,6 +80,22 @@ def get_doc_status(
"message": "".join(msg_lines)} "message": "".join(msg_lines)}
def _summarize_extracted(extracted_data: dict | None) -> str:
"""Convert extracted_data dict to a compact string for chatbot context."""
if not extracted_data:
return ""
skip = {"_meta", "status"}
parts = []
for k, v in extracted_data.items():
if k in skip or v is None:
continue
if isinstance(v, list):
parts.append(f"{k}: {', '.join(str(i) for i in v[:3])}")
else:
parts.append(f"{k}: {v}")
return " | ".join(parts[:8]) # cap at 8 fields to keep context small
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
# Admin: system overview stats # Admin: system overview stats
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
@@ -83,12 +105,9 @@ def get_admin_status(
current_user=Depends(get_current_user), current_user=Depends(get_current_user),
_=Depends(require_admin), _=Depends(require_admin),
): ):
"""Return system-wide stats for the admin chatbot."""
today_start = datetime.combine(date.today(), datetime.min.time()) today_start = datetime.combine(date.today(), datetime.min.time())
total_users = db.query(User).count()
total_users = db.query(User).count() new_users_today = db.query(User).filter(User.created_at >= today_start).count()
new_users_today = db.query(User).filter(User.created_at >= today_start).count()
pending_personal = ( pending_personal = (
db.query(PersonalDocument) db.query(PersonalDocument)
.filter(PersonalDocument.review_status == "pending", PersonalDocument.deleted_at == None) .filter(PersonalDocument.review_status == "pending", PersonalDocument.deleted_at == None)
@@ -100,48 +119,38 @@ def get_admin_status(
.count() .count()
) )
# Most recent 10 uploads across both tables
recent_personal = ( recent_personal = (
db.query(PersonalDocument) db.query(PersonalDocument).filter(PersonalDocument.deleted_at == None)
.filter(PersonalDocument.deleted_at == None) .order_by(PersonalDocument.uploaded_at.desc()).limit(10).all()
.order_by(PersonalDocument.uploaded_at.desc())
.limit(10).all()
) )
recent_business = ( recent_business = (
db.query(BusinessDocument) db.query(BusinessDocument).filter(BusinessDocument.deleted_at == None)
.filter(BusinessDocument.deleted_at == None) .order_by(BusinessDocument.uploaded_at.desc()).limit(10).all()
.order_by(BusinessDocument.uploaded_at.desc())
.limit(10).all()
) )
# Merge and sort to get true top-10 latest
recent_uploads = sorted( recent_uploads = sorted(
[{"user_id": d.user_id, "doc": d.doc_type, "type": "personal", [{"user_id": d.user_id, "doc": d.doc_type, "type": "personal",
"uploaded_at": d.uploaded_at, "status": d.review_status} for d in recent_personal] + "uploaded_at": d.uploaded_at, "status": d.review_status} for d in recent_personal] +
[{"user_id": d.user_id, "doc": d.business_type, "type": "business", [{"user_id": d.user_id, "doc": d.business_type, "type": "business",
"uploaded_at": d.uploaded_at, "status": d.review_status} for d in recent_business], "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"], reverse=True
)[:10] )[:10]
# Enrich with user names
user_map = {u.id: u for u in db.query(User).filter(User.id.in_([r["user_id"] for r in recent_uploads])).all()} user_map = {u.id: u for u in db.query(User).filter(User.id.in_([r["user_id"] for r in recent_uploads])).all()}
for r in recent_uploads: for r in recent_uploads:
u = user_map.get(r["user_id"]) u = user_map.get(r["user_id"])
r["user_name"] = u.name if u else "Unknown" r["user_name"] = u.name if u else "Unknown"
r["user_email"] = u.email if u else "Unknown" r["user_email"] = u.email if u else "Unknown"
r["uploaded_at"] = r["uploaded_at"].strftime("%Y-%m-%d %H:%M") if r["uploaded_at"] else "N/A" r["uploaded_at"] = r["uploaded_at"].strftime("%Y-%m-%d %H:%M") if r["uploaded_at"] else "N/A"
total_pending = pending_personal + pending_business
message = ( message = (
f"<b>System Overview:</b><br><br>" f"<b>System Overview:</b><br><br>"
f"• Total Users: <b>{total_users}</b> (<b>{new_users_today}</b> joined today)<br>" f"• Total Users: <b>{total_users}</b> (<b>{new_users_today}</b> joined today)<br>"
f"• Pending Personal Docs: <b>{pending_personal}</b><br>" f"• Pending Personal Docs: <b>{pending_personal}</b><br>"
f"• Pending Business Docs: <b>{pending_business}</b><br><br>" f"• Pending Business Docs: <b>{pending_business}</b><br><br>"
+ (f"You have <b>{total_pending}</b> documents awaiting review." if total_pending > 0
else "All documents have been reviewed!")
) )
total_pending = pending_personal + pending_business
if total_pending > 0:
message += f"You have <b>{total_pending}</b> documents awaiting review."
else:
message += "All documents have been reviewed!"
return { return {
"total_users": total_users, "total_users": total_users,
@@ -155,59 +164,57 @@ def get_admin_status(
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
# Admin: rich context for a specific user (activity + docs) # Admin: daily digest (new)
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
@router.get("/daily-digest")
def get_daily_digest(
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
"""Generate an AI plain-English summary of today's activity."""
from app.utils.doc_intelligence import build_daily_digest
stats = get_admin_status(db=db, current_user=current_user, _=None)
digest_html = build_daily_digest(stats)
return {"digest": digest_html, "generated_at": datetime.now().isoformat()}
# ─────────────────────────────────────────────────────────────────────────────
# Admin: user context lookup
# ─────────────────────────────────────────────────────────────────────────────
@router.get("/admin-user-context") @router.get("/admin-user-context")
def get_admin_user_context( def get_admin_user_context(
query: str = Query(..., description="User name or email to search for"), query: str = Query(...),
db: Session = Depends(get_db), db: Session = Depends(get_db),
current_user=Depends(get_current_user), current_user=Depends(get_current_user),
_=Depends(require_admin), _=Depends(require_admin),
): ):
"""Search for a user by name/email and return their full activity context."""
q = f"%{query}%" q = f"%{query}%"
user = ( user = db.query(User).filter(or_(User.name.ilike(q), User.email.ilike(q))).first()
db.query(User)
.filter(or_(User.name.ilike(q), User.email.ilike(q)))
.first()
)
if not user: if not user:
return {"found": False, "message": f"No user found matching '{query}'."} return {"found": False, "message": f"No user found matching '{query}'."}
# Docs
personal = db.query(PersonalDocument).filter( personal = db.query(PersonalDocument).filter(
PersonalDocument.user_id == user.id, PersonalDocument.deleted_at == None PersonalDocument.user_id == user.id, PersonalDocument.deleted_at == None
).order_by(PersonalDocument.uploaded_at.desc()).all() ).order_by(PersonalDocument.uploaded_at.desc()).all()
business = db.query(BusinessDocument).filter( business = db.query(BusinessDocument).filter(
BusinessDocument.user_id == user.id, BusinessDocument.deleted_at == None BusinessDocument.user_id == user.id, BusinessDocument.deleted_at == None
).order_by(BusinessDocument.uploaded_at.desc()).all() ).order_by(BusinessDocument.uploaded_at.desc()).all()
audit = db.query(AuditLog).filter(AuditLog.user_id == user.id).order_by(AuditLog.created_at.desc()).limit(20).all()
# Audit log (last 20 actions)
audit = (
db.query(AuditLog)
.filter(AuditLog.user_id == user.id)
.order_by(AuditLog.created_at.desc())
.limit(20).all()
)
return { return {
"found": True, "found": True,
"user": { "user": {
"id": user.id, "id": user.id, "name": user.name, "email": user.email,
"name": user.name, "role": user.role.value if hasattr(user.role, "value") else str(user.role),
"email": user.email,
"role": user.role.value if hasattr(user.role, "value") else str(user.role),
"joined": user.created_at.strftime("%Y-%m-%d") if user.created_at else "N/A", "joined": user.created_at.strftime("%Y-%m-%d") if user.created_at else "N/A",
"engagement_acknowledged": bool(user.engagement_acknowledged_at), "engagement_acknowledged": bool(user.engagement_acknowledged_at),
}, },
"documents": { "documents": {
"personal": [{"doc_type": d.doc_type, "status": d.review_status, "personal": [{"doc_type": d.doc_type, "status": d.review_status, "tax_year": d.tax_year,
"tax_year": d.tax_year, "uploaded_at": d.uploaded_at.strftime("%Y-%m-%d %H:%M") if d.uploaded_at else "N/A"} for d in personal],
"uploaded_at": d.uploaded_at.strftime("%Y-%m-%d %H:%M") if d.uploaded_at else "N/A"} for d in personal], "business": [{"business_type": d.business_type, "status": d.review_status, "tax_year": d.tax_year,
"business": [{"business_type": d.business_type, "status": d.review_status, "uploaded_at": d.uploaded_at.strftime("%Y-%m-%d %H:%M") if d.uploaded_at else "N/A"} for d in business],
"tax_year": d.tax_year,
"uploaded_at": d.uploaded_at.strftime("%Y-%m-%d %H:%M") if d.uploaded_at else "N/A"} for d in business],
}, },
"audit_log": [ "audit_log": [
{"action": l.action, "detail": l.detail, "ip": l.ip_address, {"action": l.action, "detail": l.detail, "ip": l.ip_address,
@@ -218,39 +225,102 @@ def get_admin_user_context(
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
# Shared chat endpoint # Admin: bulk action executor (approve/reject all docs for a user)
# Requires explicit confirm=true to execute — safety gate
# ─────────────────────────────────────────────────────────────────────────────
class BulkActionRequest(BaseModel):
user_id: int
action: str # "approve_personal" | "approve_business" | "reject_personal" | "reject_business"
confirm: bool # must be True to execute — prevents accidental execution
@router.post("/admin-bulk-action")
def admin_bulk_action(
payload: BulkActionRequest,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
"""
Execute a bulk approve/reject action on all pending docs for a user.
Requires confirm=true — the frontend must show a confirmation dialog first.
"""
if not payload.confirm:
return {"status": "pending_confirm",
"message": "Action not executed. Set confirm=true to proceed."}
user = db.query(User).filter(User.id == payload.user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
action_parts = payload.action.split("_") # e.g. ["approve", "personal"]
if len(action_parts) != 2 or action_parts[0] not in ("approve", "reject") \
or action_parts[1] not in ("personal", "business"):
raise HTTPException(status_code=400, detail="Invalid action. Use approve_personal, reject_personal, approve_business, or reject_business.")
verb, doc_type = action_parts
new_status = "approved" if verb == "approve" else "rejected"
model_class = PersonalDocument if doc_type == "personal" else BusinessDocument
docs = db.query(model_class).filter(
model_class.user_id == payload.user_id,
model_class.review_status == "pending",
model_class.deleted_at == None,
).all()
count = 0
for doc in docs:
doc.review_status = new_status
count += 1
db.commit()
logger.info(f"Admin {current_user.id} bulk {new_status} {count} {doc_type} docs for user {payload.user_id}")
return {
"status": "executed",
"action": payload.action,
"count": count,
"message": f"{count} {doc_type} document(s) marked as {new_status}.",
}
# ─────────────────────────────────────────────────────────────────────────────
# Shared chat — streaming (new) + conversation memory via messages[]
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
class ChatMessage(BaseModel): class ChatMessage(BaseModel):
role: str role: str
content: str content: str
reasoning_details: list | None = None reasoning_details: list | None = None
@field_validator("content")
@classmethod
def cap_content(cls, v: str) -> str:
if len(v) > 4000:
raise ValueError("Message must be 4000 characters or fewer")
return v
class ChatRequest(BaseModel): class ChatRequest(BaseModel):
messages: list[ChatMessage] messages: list[ChatMessage]
stream: bool = False # client opts into streaming
def _build_admin_context(db: Session, current_user) -> str: def _build_admin_context(db: Session, current_user) -> str:
"""Build a rich real-time context string for the admin system prompt."""
status = get_admin_status(db=db, current_user=current_user, _=None) status = get_admin_status(db=db, current_user=current_user, _=None)
ctx = f"=== LIVE SYSTEM DATA (as of {datetime.now().strftime('%Y-%m-%d %H:%M')}) ===\n" ctx = f"=== LIVE SYSTEM DATA (as of {datetime.now().strftime('%Y-%m-%d %H:%M')}) ===\n"
ctx += f"Total registered users: {status['total_users']}\n" ctx += f"Total registered users: {status['total_users']}\n"
ctx += f"New users registered TODAY: {status['new_users_today']}\n" ctx += f"New users registered TODAY: {status['new_users_today']}\n"
ctx += f"Pending personal docs (system-wide): {status['pending_personal']}\n" ctx += f"Pending personal docs: {status['pending_personal']}\n"
ctx += f"Pending business docs (system-wide): {status['pending_business']}\n" ctx += f"Pending business docs: {status['pending_business']}\n"
ctx += f"Total pending docs: {status['total_pending']}\n\n" ctx += f"Total pending docs: {status['total_pending']}\n\n"
if status["recent_uploads"]: if status["recent_uploads"]:
ctx += "=== MOST RECENT DOCUMENT UPLOADS ===\n" ctx += "=== MOST RECENT UPLOADS ===\n"
for r in status["recent_uploads"]: for r in status["recent_uploads"]:
ctx += (f"- {r['user_name']} ({r['user_email']}) uploaded a " ctx += (f"- {r['user_name']} ({r['user_email']}) uploaded {r['type']} "
f"{r['type']} doc '{r['doc']}' on {r['uploaded_at']} " f"'{r['doc']}' on {r['uploaded_at']} [{r['status']}]\n")
f"[status: {r['status']}]\n")
return ctx return ctx
@router.post("/ask") @router.post("/ask")
@limiter.limit("5/minute") @limiter.limit("10/minute")
def ask_chatbot( def ask_chatbot(
request: Request, request: Request,
req: ChatRequest, req: ChatRequest,
@@ -266,11 +336,9 @@ def ask_chatbot(
if is_admin: if is_admin:
context = _build_admin_context(db, current_user) context = _build_admin_context(db, current_user)
# Check if the latest user message references a specific user — if so, fetch their data
last_user_msg = next((m.content for m in reversed(req.messages) if m.role == "user"), "") last_user_msg = next((m.content for m in reversed(req.messages) if m.role == "user"), "")
user_context_addon = "" user_context_addon = ""
if any(kw in last_user_msg.lower() for kw in ["user", "who", "activity", "uploaded", "registered", "recent"]): if any(kw in last_user_msg.lower() for kw in ["user", "who", "activity", "uploaded", "registered", "recent"]):
# Try to find a name/email in the message
words = last_user_msg.replace(",", " ").replace("?", " ").split() words = last_user_msg.replace(",", " ").replace("?", " ").split()
for word in words: for word in words:
if "@" in word or len(word) > 4: if "@" in word or len(word) > 4:
@@ -280,82 +348,112 @@ def ask_chatbot(
docs = result["documents"] docs = result["documents"]
audit = result["audit_log"] audit = result["audit_log"]
user_context_addon = f"\n\n=== USER DETAIL: {u['name']} ({u['email']}) ===\n" user_context_addon = f"\n\n=== USER DETAIL: {u['name']} ({u['email']}) ===\n"
user_context_addon += f"Role: {u['role']} | Joined: {u['joined']} | Engagement acknowledged: {u['engagement_acknowledged']}\n" user_context_addon += f"Role: {u['role']} | Joined: {u['joined']} | Engagement: {u['engagement_acknowledged']}\n"
if docs["personal"]: if docs["personal"]:
user_context_addon += "Personal docs: " + "; ".join( user_context_addon += "Personal: " + "; ".join(
f"{d['doc_type']} ({d['tax_year']}) [{d['status']}] uploaded {d['uploaded_at']}" f"{d['doc_type']} ({d['tax_year']}) [{d['status']}]" for d in docs["personal"]) + "\n"
for d in docs["personal"]) + "\n"
if docs["business"]: if docs["business"]:
user_context_addon += "Business docs: " + "; ".join( user_context_addon += "Business: " + "; ".join(
f"{d['business_type']} ({d['tax_year']}) [{d['status']}] uploaded {d['uploaded_at']}" f"{d['business_type']} ({d['tax_year']}) [{d['status']}]" for d in docs["business"]) + "\n"
for d in docs["business"]) + "\n"
if audit: if audit:
user_context_addon += "Recent activity:\n" + "\n".join( user_context_addon += "Activity:\n" + "\n".join(
f" [{a['at']}] {a['action']} — {a['detail'] or ''} (IP: {a['ip'] or 'N/A'})" f" [{a['at']}] {a['action']} — {a['detail'] or ''}"
for a in audit[:10]) + "\n" for a in audit[:8]) + "\n"
break break
system_prompt = ( system_prompt = (
"You are the BookKeepPro Admin Assistant — a knowledgeable, concise AI that has live access to the system's data.\n\n" "You are the BookKeepPro Admin Assistant with live access to system data.\n\n"
"CAPABILITIES:\n" "CAPABILITIES: Answer questions about uploads, user activity, pending docs, registration counts.\n"
"- You can answer questions about which users uploaded documents and when.\n" "BULK ACTIONS: When asked to approve/reject all docs for a user, respond with a structured "
"- You can report how many new users registered today or on any date.\n" "JSON action block like: {\"bulk_action\": {\"user_id\": N, \"action\": \"approve_personal\", \"confirm\": false}} "
"- You can show recent activity and document history for any specific user.\n" "— the frontend will show a confirmation dialog before executing.\n"
"- You can answer questions about document review status system-wide.\n\n" "RULES: Only answer BookKeepPro, accounting, or tax questions. Use live data. Be concise.\n\n"
"RULES:\n"
"- Only answer questions related to BookKeepPro administration, accounting, or taxes.\n"
"- Use the live data below to answer. Do NOT make up user names, counts, or dates.\n"
"- Be concise and direct. Format answers clearly.\n\n"
f"{context}{user_context_addon}" f"{context}{user_context_addon}"
) )
else: else:
doc_status = get_doc_status(db=db, current_user=current_user) doc_status = get_doc_status(db=db, current_user=current_user)
summary = doc_status["summary"] summary = doc_status["summary"]
context = f"Total Documents: {summary['total']}\nPending: {summary['pending']}\nApproved: {summary['approved']}\nRejected: {summary['rejected']}\n" context = f"Total: {summary['total']} | Pending: {summary['pending']} | Approved: {summary['approved']} | Rejected: {summary['rejected']}\n"
if doc_status["personal"]: if doc_status["personal"]:
context += "\nPersonal Documents:\n" context += "\nPersonal Documents:\n"
for d in doc_status["personal"]: for d in doc_status["personal"]:
note = f" — Admin note: {d['note']}" if d['note'] else "" note = f" — Note: {d['note']}" if d['note'] else ""
context += f" • {d['doc_type']} ({d['tax_year']}): {d['status']}{note}\n" extracted = f" | Data: {d['extracted_summary']}" if d['extracted_summary'] else ""
context += f" • {d['doc_type']} ({d['tax_year']}): {d['status']}{note}{extracted}\n"
if doc_status["business"]: if doc_status["business"]:
context += "\nBusiness Documents:\n" context += "\nBusiness Documents:\n"
for d in doc_status["business"]: for d in doc_status["business"]:
note = f" — Admin note: {d['note']}" if d['note'] else "" note = f" — Note: {d['note']}" if d['note'] else ""
context += f" • {d['business_type']} ({d['tax_year']}): {d['status']}{note}\n" extracted = f" | Data: {d['extracted_summary']}" if d['extracted_summary'] else ""
context += f" • {d['business_type']} ({d['tax_year']}): {d['status']}{note}{extracted}\n"
system_prompt = ( system_prompt = (
"You are the BookKeepPro Assistant. Help users with this application and basic accounting/tax questions.\n\n" "You are the BookKeepPro Assistant. Help users with the app and basic accounting/tax questions.\n\n"
"APPLICATION FLOW:\n" "UPLOAD GUIDANCE: If user wants to upload a document, tell them:\n"
"- Upload documents: Dashboard → Personal Upload or Business Upload page → drag & drop or click to browse.\n" "- Personal docs → go to /upload-personal\n"
"- Check status: Documents show Pending (waiting for admin), Approved, or Rejected.\n" "- Business docs → go to /upload-business\n"
"- If rejected: see the admin's note on the upload page and re-upload a corrected version.\n" "- You can also say: 'Click here: [Upload Personal](/upload-personal)'\n\n"
"- Profile: update your name, phone, or password on the Profile page.\n\n" "EXTRACTED DATA: You have access to key fields extracted from the user's documents. "
"RULES:\n" "Use this to answer specific questions like 'what is my PAN number' or 'what does my W-2 show'.\n\n"
"- Only answer questions about BookKeepPro, accounting, or taxes.\n" "RULES: Only answer BookKeepPro, accounting, or tax questions.\n\n"
"- Use the live data below to answer questions about the user's documents.\n\n"
f"=== LIVE DATA for {current_user.name or current_user.email} ===\n{context}" 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}] messages = [{"role": "system", "content": system_prompt}]
for m in req.messages: for m in req.messages:
messages.append({"role": m.role, "content": m.content}) messages.append({"role": m.role, "content": m.content})
# ── Streaming path ────────────────────────────────────────────────────────
if req.stream:
def _stream():
try:
resp = requests.post(
url="https://openrouter.ai/api/v1/chat/completions",
headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
json={"model": CHAT_MODEL, "messages": messages, "stream": True},
stream=True,
timeout=60,
)
resp.raise_for_status()
for line in resp.iter_lines():
if line and line != b"data: [DONE]":
raw = line.decode("utf-8")
if raw.startswith("data: "):
raw = raw[6:]
try:
chunk = json.loads(raw)
delta = chunk["choices"][0].get("delta", {})
token = delta.get("content", "")
if token:
# Send SSE event
yield f"data: {json.dumps({'token': token})}\n\n"
except Exception:
pass
yield "data: [DONE]\n\n"
except Exception as e:
logger.error(f"Streaming error: {e}")
yield f"data: {json.dumps({'error': str(e)})}\n\n"
return StreamingResponse(_stream(), media_type="text/event-stream")
# ── Non-streaming path (default) ─────────────────────────────────────────
try: try:
response = requests.post( response = requests.post(
url="https://openrouter.ai/api/v1/chat/completions", url="https://openrouter.ai/api/v1/chat/completions",
headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}, headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
json={"model": "meta-llama/llama-3.3-70b-instruct", "messages": messages}, json={"model": CHAT_MODEL, "messages": messages},
timeout=30, timeout=30,
) )
response.raise_for_status() response.raise_for_status()
data = response.json() data = response.json()
if "error" in data: if "error" in data:
logger.error(f"OpenRouter error: {data['error']}")
raise HTTPException(status_code=502, detail="AI service overloaded. Please try again.") raise HTTPException(status_code=502, detail="AI service overloaded. Please try again.")
if "choices" not in data: if "choices" not in data:
raise HTTPException(status_code=502, detail="Unexpected AI response. Please try again.") raise HTTPException(status_code=502, detail="Unexpected AI response.")
return data["choices"][0]["message"] return data["choices"][0]["message"]
+8 -1
View File
@@ -1,7 +1,7 @@
import os import os
from fastapi import APIRouter, BackgroundTasks, HTTPException, Request from fastapi import APIRouter, BackgroundTasks, HTTPException, Request
from app.limiter import limiter from app.limiter import limiter
from pydantic import BaseModel, EmailStr from pydantic import BaseModel, EmailStr, field_validator
from app.utils.emailer import send_email from app.utils.emailer import send_email
router = APIRouter(prefix="/api", tags=["contact"]) router = APIRouter(prefix="/api", tags=["contact"])
@@ -16,6 +16,13 @@ class ContactForm(BaseModel):
phone: str phone: str
message: str = "" message: str = ""
@field_validator("message")
@classmethod
def cap_message(cls, v: str) -> str:
if len(v) > 2000:
raise ValueError("Message must be 2000 characters or fewer")
return v
@router.post("/contact") @router.post("/contact")
@limiter.limit("5/minute") @limiter.limit("5/minute")
async def contact_message(request: Request, form: ContactForm, background: BackgroundTasks): async def contact_message(request: Request, form: ContactForm, background: BackgroundTasks):
+63 -26
View File
@@ -8,9 +8,6 @@ from fastapi import APIRouter, BackgroundTasks, UploadFile, File, HTTPException,
from fastapi.responses import FileResponse from fastapi.responses import FileResponse
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError from sqlalchemy.exc import IntegrityError
import boto3
from botocore.client import Config
from botocore.exceptions import ClientError
from jose import jwt, JWTError from jose import jwt, JWTError
from datetime import timedelta from datetime import timedelta
@@ -39,20 +36,61 @@ UPLOAD_DIR = BASE_DIR / "uploads"
UPLOAD_DIR.mkdir(parents=True, exist_ok=True) UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
def process_ai_extraction(table: str, doc_id: int, file_path: str, doc_type: str): def process_ai_extraction(table: str, doc_id: int, file_path: str, doc_type: str):
extracted = extract_document_data(file_path, doc_type) import hashlib
if extracted is None:
return # Compute SHA-256 hash of the file for deduplication (Item 3)
try:
with open(file_path, "rb") as f:
file_hash = hashlib.sha256(f.read()).hexdigest()
except Exception as e:
logger.warning(f"[AI] Could not hash file {file_path}: {e}. Proceeding without dedup.")
file_hash = None
db = SessionLocal() db = SessionLocal()
try: try:
if table == "personal": model_class = PersonalDocument if table == "personal" else BusinessDocument
doc = db.query(PersonalDocument).filter_by(id=doc_id).first()
else: # Check if another doc with the same file hash already has extracted data
doc = db.query(BusinessDocument).filter_by(id=doc_id).first() if file_hash:
cached = (
db.query(model_class)
.filter(
model_class.file_hash == file_hash,
model_class.extracted_data != None,
model_class.id != doc_id,
model_class.deleted_at == None,
)
.first()
)
if cached:
logger.info(
f"[AI] Cache hit for hash {file_hash[:12]}… — "
f"copying extracted_data from doc id={cached.id} (skipping API call)"
)
doc = db.query(model_class).filter_by(id=doc_id).first()
if doc:
doc.extracted_data = cached.extracted_data
doc.file_hash = file_hash
db.commit()
return
# No cache — run full extraction
extracted = extract_document_data(file_path, doc_type)
if extracted is None:
# Still save the hash so we don't keep retrying a file that always fails
if file_hash:
doc = db.query(model_class).filter_by(id=doc_id).first()
if doc:
doc.file_hash = file_hash
db.commit()
return
doc = db.query(model_class).filter_by(id=doc_id).first()
if doc: if doc:
doc.extracted_data = extracted doc.extracted_data = extracted
doc.file_hash = file_hash
db.commit() db.commit()
except Exception as e: except Exception as e:
logger.error(f"Failed to update DB with AI extraction: {e}") logger.error(f"Failed to update DB with AI extraction: {e}")
finally: finally:
@@ -291,7 +329,7 @@ def list_admin_documents(
"doc_label": d.doc_label, "doc_label": d.doc_label,
"filename": d.filename, "filename": d.filename,
"storage_key": d.storage_key, "storage_key": d.storage_key,
"created_at": d.uploaded_at.isoformat() if d.uploaded_at else None, "created_at": d.uploaded_at.isoformat() + "Z" if d.uploaded_at else None,
} }
for d in docs for d in docs
] ]
@@ -670,7 +708,7 @@ def get_user_all_documents(
"doc_type": d.doc_type, "doc_type": d.doc_type,
"filename": d.filename, "filename": d.filename,
"storage_key": d.storage_key, "storage_key": d.storage_key,
"uploaded_at": d.uploaded_at.isoformat() if d.uploaded_at else None, "uploaded_at": d.uploaded_at.isoformat() + "Z" if d.uploaded_at else None,
"tax_year": d.tax_year, "tax_year": d.tax_year,
"review_status": d.review_status, "review_status": d.review_status,
"review_note": d.review_note, "review_note": d.review_note,
@@ -684,7 +722,7 @@ def get_user_all_documents(
"doc_type": d.business_type, "doc_type": d.business_type,
"filename": d.filename, "filename": d.filename,
"storage_key": d.storage_key, "storage_key": d.storage_key,
"uploaded_at": d.uploaded_at.isoformat() if d.uploaded_at else None, "uploaded_at": d.uploaded_at.isoformat() + "Z" if d.uploaded_at else None,
"tax_year": d.tax_year, "tax_year": d.tax_year,
"review_status": d.review_status, "review_status": d.review_status,
"review_note": d.review_note, "review_note": d.review_note,
@@ -758,13 +796,13 @@ def delete_user_completely(
delete_from_storage(doc.storage_key) delete_from_storage(doc.storage_key)
db.delete(doc) db.delete(doc)
# Clean up legacy uploaded_files rows and audit logs to avoid FK constraint errors on db.delete(user) # Clean up legacy uploaded_files rows to avoid FK constraint errors on db.delete(user)
from app.models import UploadedFile, AuditLog from app.models import UploadedFile
db.query(UploadedFile).filter(UploadedFile.owner_id == user_id).delete() db.query(UploadedFile).filter(UploadedFile.owner_id == user_id).delete()
db.query(AuditLog).filter(AuditLog.user_id == user_id).delete()
db.commit() # Log before deleting the user (audit_logs.user_id FK is SET NULL, so logs survive)
crud.log_action(db, "delete_user", user_id=current_user.id, target=f"user:{user_id}") crud.log_action(db, "delete_user", user_id=current_user.id, target=f"user:{user_id}", detail=f"{user.email}")
db.delete(user) db.delete(user)
db.commit() db.commit()
except Exception as e: except Exception as e:
@@ -895,7 +933,7 @@ def list_templates(
{ {
"id": t.id, "id": t.id,
"name": t.name, "name": t.name,
"download": t.file_url, "download": get_presigned_url(t.file_url) if t.file_url else None,
} }
for t in templates for t in templates
] ]
@@ -917,7 +955,7 @@ async def upload_template(
file_url = None file_url = None
if file and file.filename: if file and file.filename:
storage_key = await upload_to_storage(file) storage_key = await upload_to_storage(file)
file_url = get_presigned_url(storage_key) file_url = storage_key # Store raw key; presigned URLs are generated on-demand in GET
record = RequiredDocumentTemplate( record = RequiredDocumentTemplate(
category=category, category=category,
@@ -937,7 +975,7 @@ async def upload_template(
return { return {
"id": record.id, "id": record.id,
"name": record.name, "name": record.name,
"download": record.file_url, "download": get_presigned_url(record.file_url) if record.file_url else None,
} }
@router.delete("/admin/templates/{template_id}") @router.delete("/admin/templates/{template_id}")
@@ -954,9 +992,8 @@ def delete_template(
if not record: if not record:
raise HTTPException(status_code=404, detail="Template not found") raise HTTPException(status_code=404, detail="Template not found")
if record.file_url and record.file_url.startswith("/uploads/"): if record.file_url:
storage_key = record.file_url.split("/uploads/")[1] delete_from_storage(record.file_url)
delete_from_storage(storage_key)
db.delete(record) db.delete(record)
db.commit() db.commit()
+150 -45
View File
@@ -18,10 +18,11 @@ MIN_TESS_WORDS = 30 # Stage 2: Tesseract must return at least this many words
RENDER_DPI = 2.5 # PyMuPDF render scale (2.5x ≈ 212 DPI) RENDER_DPI = 2.5 # PyMuPDF render scale (2.5x ≈ 212 DPI)
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
# Models # Models — configurable via .env, hardcoded values are defaults
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
MODEL_TEXT = "meta-llama/llama-3.3-70b-instruct" # Stage 1 & 2 — FREE tier MODEL_TEXT = os.getenv("OCR_TEXT_MODEL", "meta-llama/llama-3.3-70b-instruct")
MODEL_VISION = "qwen/qwen2.5-vl-72b-instruct" # Stage 3 — best document OCR MODEL_VISION = os.getenv("OCR_VISION_MODEL", "qwen/qwen2.5-vl-72b-instruct")
MODEL_FALLBACK = os.getenv("OCR_FALLBACK_MODEL", "google/gemma-3-27b-it")
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
# Prompts # Prompts
@@ -42,23 +43,51 @@ BLANK_FORM_PROMPT = (
"Return ONLY valid JSON, no markdown." "Return ONLY valid JSON, no markdown."
) )
# ─────────────────────────────────────────────────────────────────────────────
# Confidence tier definitions (Item 1)
# ─────────────────────────────────────────────────────────────────────────────
_CONFIDENCE_TIERS = {
1: {
"stage": 1,
"tier": "high",
"label": "Native PDF text",
"description": "Extracted directly from the PDF text layer — highly reliable.",
"color": "green",
},
2: {
"stage": 2,
"tier": "medium",
"label": "OCR (Tesseract)",
"description": "Read from a scanned/image page via local OCR — review key numbers.",
"color": "yellow",
},
3: {
"stage": 3,
"tier": "low",
"label": "Vision model",
"description": "Read from image by AI vision model — verify carefully.",
"color": "orange",
},
}
def _build_user_prompt(doc_type: str) -> str: def _add_confidence(result: dict | None, stage: int, word_count: int = 0) -> dict | None:
return ( """
f"Document type hint: {doc_type}\n\n" Attach a _meta block to an extraction result indicating which pipeline
"You are a precise data extraction AI. Read this document and extract its key information.\n\n" stage produced it and how reliable the output is likely to be.
"STRICT RULES:\n" Returns None unchanged so callers can still check `if result is None`.
"1. Use field names exactly as they appear in the document " """
"(e.g. 'PAN Number', 'Date of Birth', 'Employer Name', 'Tax Year').\n" if result is None:
"2. For LEGAL DOCUMENTS, LETTERS, or CONTRACTS: extract key terms — " return None
"services included, responsibilities, fees, tax forms mentioned, deadlines, party names.\n" meta = dict(_CONFIDENCE_TIERS.get(stage, {"stage": stage, "tier": "unknown",
"3. Extract ONLY fields that have actual content — do NOT add null or empty fields.\n" "label": "Unknown", "color": "gray"}))
"4. Dates: format as DD/MM/YYYY. A run-together date like '27082022' → '27/08/2022'.\n" if stage == 2 and word_count:
"5. For list fields (services, items, fees) use JSON arrays.\n" meta["label"] = f"OCR ({word_count} words)"
"6. Ignore bilingual label noise (Hindi/Devanagari text) — extract English values only.\n" meta["description"] = (
"7. If the document is truly a blank unfilled form with zero data, return {}.\n" f"Tesseract OCR found {word_count} words. "
"8. Return ONLY a valid JSON object — no markdown, no explanation." + ("Reasonable confidence." if word_count >= 60 else "Low word count — check key fields manually.")
) )
result["_meta"] = meta
return result
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
@@ -119,11 +148,14 @@ def _tesseract_text(pil_image: Image.Image) -> str:
break break
config = "--psm 6 --oem 3" config = "--psm 6 --oem 3"
# Tesseract language pack — configurable via TESSERACT_LANG env var
# Default: eng+hin for bilingual Indian documents
tess_lang = os.getenv("TESSERACT_LANG", "eng+hin")
try: try:
text = pytesseract.image_to_string(pil_image, lang="eng+hin", config=config).strip() text = pytesseract.image_to_string(pil_image, lang=tess_lang, config=config).strip()
logger.debug(f"[Tesseract] eng+hin produced {len(text.split())} words") logger.debug(f"[Tesseract] {tess_lang} produced {len(text.split())} words")
except Exception: except Exception:
logger.debug("[Tesseract] eng+hin unavailable, using eng only") logger.debug(f"[Tesseract] {tess_lang} unavailable, using eng only")
text = pytesseract.image_to_string(pil_image, lang="eng", config=config).strip() text = pytesseract.image_to_string(pil_image, lang="eng", config=config).strip()
return text return text
@@ -144,10 +176,16 @@ def _call_openrouter(
) -> dict | None: ) -> dict | None:
""" """
POST to OpenRouter and return parsed JSON dict, or None on failure. POST to OpenRouter and return parsed JSON dict, or None on failure.
If the model returns {} (blank/unfilled doc), retries with a metadata
prompt so the admin always sees form_type / purpose / tax_year. Fallback chain (Item 4):
1. Try requested model.
2. If that fails AND it isn't already the fallback model, retry with MODEL_FALLBACK.
Blank template handling:
If the model returns {} (unfilled form), retries with a metadata prompt
so the admin always sees form_type / purpose / tax_year instead of nothing.
""" """
def _post(content): def _post(m: str, content: list) -> dict | None:
try: try:
response = requests.post( response = requests.post(
url="https://openrouter.ai/api/v1/chat/completions", url="https://openrouter.ai/api/v1/chat/completions",
@@ -156,7 +194,7 @@ def _call_openrouter(
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
json={ json={
"model": model, "model": m,
"messages": [ "messages": [
{"role": "system", "content": SYSTEM_PROMPT}, {"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": content}, {"role": "user", "content": content},
@@ -174,19 +212,25 @@ def _call_openrouter(
raw = raw[:-3] raw = raw[:-3]
return json.loads(raw.strip()) return json.loads(raw.strip())
except Exception as e: except Exception as e:
logger.error(f"[OpenRouter] {model} call failed: {e}") logger.error(f"[OpenRouter] {m} call failed: {e}")
return None return None
result = _post(user_content) # Primary attempt
result = _post(model, user_content)
# If model returned {} (blank template), retry with metadata-only prompt # Fallback to secondary model if primary failed (Item 4)
if result is None and model != MODEL_FALLBACK:
logger.warning(f"[AI] {model} failed — retrying with fallback {MODEL_FALLBACK}")
result = _post(MODEL_FALLBACK, user_content)
# Blank template fallback — retry with metadata prompt if result is {}
if result == {} and original_text: if result == {} and original_text:
logger.info("[AI] Empty result — retrying with blank-form metadata prompt") logger.info("[AI] Empty result — retrying with blank-form metadata prompt")
fallback_content = [{ fallback_content = [{
"type": "text", "type": "text",
"text": f"{BLANK_FORM_PROMPT}\n\nDocument text:\n{original_text[:3000]}" "text": f"{BLANK_FORM_PROMPT}\n\nDocument text:\n{original_text[:3000]}"
}] }]
result = _post(fallback_content) or {} result = _post(model, fallback_content) or {}
return result return result
@@ -195,21 +239,50 @@ def _call_openrouter(
# Main extraction entry point # Main extraction entry point
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
def _build_user_prompt(doc_type: str) -> str:
return (
f"Document type hint: {doc_type}\n\n"
"You are a precise data extraction AI. Read this document and extract its key information.\n\n"
"STRICT RULES:\n"
"1. Use field names exactly as they appear in the document "
"(e.g. 'PAN Number', 'Date of Birth', 'Employer Name', 'Tax Year').\n"
"2. For LEGAL DOCUMENTS, LETTERS, or CONTRACTS: extract key terms — "
"services included, responsibilities, fees, tax forms mentioned, deadlines, party names.\n"
"3. Extract ONLY fields that have actual content — do NOT add null or empty fields.\n"
"4. Dates: format as DD/MM/YYYY. A run-together date like '27082022' → '27/08/2022'.\n"
"5. For list fields (services, items, fees) use JSON arrays.\n"
"6. Ignore bilingual label noise (Hindi/Devanagari text) — extract English values only.\n"
"7. If the document is truly a blank unfilled form with zero data, return {}.\n"
"8. Return ONLY a valid JSON object — no markdown, no explanation."
)
def extract_document_data(file_path: str, doc_type: str) -> dict | None: def extract_document_data(file_path: str, doc_type: str) -> dict | None:
""" """
3-stage extraction pipeline: 3-stage extraction pipeline with confidence scoring.
Stage 1 — Native text (FREE) Stage 1 — Native text (FREE)
pypdf + PyMuPDF pull embedded text from the PDF. pypdf + PyMuPDF pull embedded text from PDF.
>= MIN_TEXT_CHARS → llama-3.3-70b (free tier) >= MIN_TEXT_CHARS → MODEL_TEXT.
If MODEL_TEXT fails, falls through to Stage 2 (Item 2 fix — was silent None before).
Stage 2 — Tesseract OCR (FREE, local CPU) Stage 2 — Tesseract OCR (FREE, local CPU)
PyMuPDF renders page at 2.5x DPI. PyMuPDF renders page at 2.5x DPI.
Tesseract reads with eng+hin for bilingual docs. Tesseract reads with eng+hin for bilingual docs.
>= MIN_TESS_WORDS → llama-3.3-70b (free tier) >= MIN_TESS_WORDS → MODEL_TEXT.
If MODEL_TEXT fails, falls through to Stage 3.
Stage 3 — Qwen2.5-VL-72B vision (paid, minimal cost) Stage 3 — Vision model (paid, minimal cost)
Sends rendered page image to Qwen via OpenRouter. Sends rendered page image to MODEL_VISION via OpenRouter.
Confidence scoring (Item 1):
Every successful result gets a _meta block:
{"stage": 1|2|3, "tier": "high"|"medium"|"low",
"label": "...", "description": "...", "color": "..."}
Model fallback (Item 4):
Each _call_openrouter call tries MODEL_TEXT/MODEL_VISION first,
then MODEL_FALLBACK if the primary fails.
Blank template fallback: Blank template fallback:
If any stage returns {}, a second call extracts If any stage returns {}, a second call extracts
@@ -227,7 +300,12 @@ def extract_document_data(file_path: str, doc_type: str) -> dict | None:
logger.info(f"[AI] Unsupported file type, skipping: {file_path}") logger.info(f"[AI] Unsupported file type, skipping: {file_path}")
return None return None
user_prompt = _build_user_prompt(doc_type) # Item 5: For other_* uploads, detect actual doc type from text content
# Required-slot uploads already carry the real template name — skip classifier for those
effective_doc_type = doc_type
# Classifier runs after text is available (done inline below per stage)
user_prompt = _build_user_prompt(effective_doc_type)
try: try:
# ── PDF ─────────────────────────────────────────────────────────────── # ── PDF ───────────────────────────────────────────────────────────────
@@ -256,9 +334,20 @@ def extract_document_data(file_path: str, doc_type: str) -> dict | None:
logger.warning(f"[Stage1] PyMuPDF text failed: {e}") logger.warning(f"[Stage1] PyMuPDF text failed: {e}")
if len(text.strip()) >= MIN_TEXT_CHARS: if len(text.strip()) >= MIN_TEXT_CHARS:
logger.info(f"[Stage1] Text PDF ({len(text.strip())} chars) → {MODEL_TEXT}") # Item 5: classify other_* using actual extracted text
if doc_type.startswith("other_"):
from app.utils.doc_classifier import get_doc_type_for_prompt
effective_doc_type = get_doc_type_for_prompt(
doc_type, text.strip(), os.path.basename(file_path)
)
user_prompt = _build_user_prompt(effective_doc_type)
logger.info(f"[Stage1] Text PDF ({len(text.strip())} chars) → {MODEL_TEXT} [{effective_doc_type}]")
content = [{"type": "text", "text": f"{user_prompt}\n\nDocument text:\n{text.strip()}"}] content = [{"type": "text", "text": f"{user_prompt}\n\nDocument text:\n{text.strip()}"}]
return _call_openrouter(api_key, MODEL_TEXT, content, original_text=text.strip()) result = _call_openrouter(api_key, MODEL_TEXT, content, original_text=text.strip())
if result is not None:
return _add_confidence(result, stage=1) # ← Item 1: confidence
# Item 2 fix: Stage 1 failure now falls through to Stage 2/3
logger.warning("[Stage1] Text model failed — falling through to Stage 2")
# Stage 2 & 3 need rendered image # Stage 2 & 3 need rendered image
rendered = _render_pdf_page(file_path) rendered = _render_pdf_page(file_path)
@@ -270,11 +359,18 @@ def extract_document_data(file_path: str, doc_type: str) -> dict | None:
word_count = len(tess_text.split()) word_count = len(tess_text.split())
if word_count >= MIN_TESS_WORDS: if word_count >= MIN_TESS_WORDS:
logger.info(f"[Stage2] Tesseract {word_count} words → {MODEL_TEXT} (free)") # Item 5: classify other_* using Tesseract text if Stage 1 text was too short
if doc_type.startswith("other_"):
from app.utils.doc_classifier import get_doc_type_for_prompt
effective_doc_type = get_doc_type_for_prompt(
doc_type, tess_text, os.path.basename(file_path)
)
user_prompt = _build_user_prompt(effective_doc_type)
logger.info(f"[Stage2] Tesseract {word_count} words → {MODEL_TEXT} (free) [{effective_doc_type}]")
content = [{"type": "text", "text": f"{user_prompt}\n\nDocument text (OCR):\n{tess_text}"}] content = [{"type": "text", "text": f"{user_prompt}\n\nDocument text (OCR):\n{tess_text}"}]
result = _call_openrouter(api_key, MODEL_TEXT, content, original_text=tess_text) result = _call_openrouter(api_key, MODEL_TEXT, content, original_text=tess_text)
if result is not None: if result is not None:
return result return _add_confidence(result, stage=2, word_count=word_count) # ← Item 1
logger.warning("[Stage2] Text model failed — falling through to Stage 3") logger.warning("[Stage2] Text model failed — falling through to Stage 3")
else: else:
logger.info(f"[Stage2] Tesseract only {word_count} words (threshold {MIN_TESS_WORDS}) → Stage 3") logger.info(f"[Stage2] Tesseract only {word_count} words (threshold {MIN_TESS_WORDS}) → Stage 3")
@@ -285,7 +381,8 @@ def extract_document_data(file_path: str, doc_type: str) -> dict | None:
{"type": "text", "text": user_prompt}, {"type": "text", "text": user_prompt},
{"type": "image_url", "image_url": {"url": image_to_base64(rendered)}}, {"type": "image_url", "image_url": {"url": image_to_base64(rendered)}},
] ]
return _call_openrouter(api_key, MODEL_VISION, content) result = _call_openrouter(api_key, MODEL_VISION, content)
return _add_confidence(result, stage=3) # ← Item 1 (None stays None)
# ── Image ───────────────────────────────────────────────────────────── # ── Image ─────────────────────────────────────────────────────────────
elif is_image: elif is_image:
@@ -295,11 +392,18 @@ def extract_document_data(file_path: str, doc_type: str) -> dict | None:
word_count = len(tess_text.split()) word_count = len(tess_text.split())
if word_count >= MIN_TESS_WORDS: if word_count >= MIN_TESS_WORDS:
logger.info(f"[Stage2-img] Tesseract {word_count} words → {MODEL_TEXT} (free)") # Item 5: classify other_* from Tesseract text on image files
if doc_type.startswith("other_"):
from app.utils.doc_classifier import get_doc_type_for_prompt
effective_doc_type = get_doc_type_for_prompt(
doc_type, tess_text, os.path.basename(file_path)
)
user_prompt = _build_user_prompt(effective_doc_type)
logger.info(f"[Stage2-img] Tesseract {word_count} words → {MODEL_TEXT} (free) [{effective_doc_type}]")
content = [{"type": "text", "text": f"{user_prompt}\n\nDocument text (OCR):\n{tess_text}"}] content = [{"type": "text", "text": f"{user_prompt}\n\nDocument text (OCR):\n{tess_text}"}]
result = _call_openrouter(api_key, MODEL_TEXT, content, original_text=tess_text) result = _call_openrouter(api_key, MODEL_TEXT, content, original_text=tess_text)
if result is not None: if result is not None:
return result return _add_confidence(result, stage=2, word_count=word_count) # ← Item 1
logger.warning("[Stage2-img] Text model failed — Stage 3") logger.warning("[Stage2-img] Text model failed — Stage 3")
else: else:
logger.info(f"[Stage2-img] Tesseract only {word_count} words → Stage 3") logger.info(f"[Stage2-img] Tesseract only {word_count} words → Stage 3")
@@ -309,7 +413,8 @@ def extract_document_data(file_path: str, doc_type: str) -> dict | None:
{"type": "text", "text": user_prompt}, {"type": "text", "text": user_prompt},
{"type": "image_url", "image_url": {"url": image_to_base64(img)}}, {"type": "image_url", "image_url": {"url": image_to_base64(img)}},
] ]
return _call_openrouter(api_key, MODEL_VISION, content) result = _call_openrouter(api_key, MODEL_VISION, content)
return _add_confidence(result, stage=3) # ← Item 1
except Exception as e: except Exception as e:
logger.error(f"[AI] Extraction pipeline failed for {file_path}: {e}") logger.error(f"[AI] Extraction pipeline failed for {file_path}: {e}")
+89
View File
@@ -0,0 +1,89 @@
"""
Document type classifier for the "other_*" catch-all upload bucket.
When a user uploads via the "Additional Documents" slot, doc_type is set to
`other_<timestamp>_<index>` — a meaningless slug. This module detects the
actual document type from OCR text + filename so the extraction prompt
becomes type-specific rather than generic.
Only used for `other_*` uploads. Required-slot uploads already carry the
real template name (e.g. "Individual Tax Organizer 2025") from the DB.
"""
from __future__ import annotations
import re
import logging
from enum import Enum
from typing import Optional
logger = logging.getLogger(__name__)
class DocCategory(str, Enum):
PAN_CARD = "PAN Card"
AADHAAR = "Aadhaar Card"
W2 = "W-2 Wage Statement"
FORM_1099 = "1099 Income Form"
ENGAGEMENT_LETTER = "Engagement Letter"
TAX_ORGANIZER = "Tax Organizer"
INVOICE = "Invoice / Bill"
BANK_STATEMENT = "Bank Statement"
PASSPORT = "Passport"
DRIVING_LICENSE = "Driving License"
GENERIC = "Other Document"
# Priority-ordered keyword patterns — first match wins
_PATTERNS: list[tuple[re.Pattern, DocCategory]] = [
# Government IDs
(re.compile(r'\bPERMANENT\s+ACCOUNT\s+NUMBER\b|\bINCOME\s+TAX\s+DEPT\b', re.I), DocCategory.PAN_CARD),
(re.compile(r'\bAADHAAR\b|\bUIDPAI\b|\bUIDAI\b|\bENROLMENT\s+NO\b', re.I), DocCategory.AADHAAR),
(re.compile(r'\bPASSPORT\b|\bREPUBLIC\s+OF\b.*\bPASSPORT\b', re.I), DocCategory.PASSPORT),
(re.compile(r'\bDRIVING\s+(LICENCE|LICENSE)\b|\bDL\s+NO\b|\bMOTOR\s+VEHICLE\b', re.I), DocCategory.DRIVING_LICENSE),
# US Tax forms
(re.compile(r'\bW-?2\b.*\bWAGES\b|\bWAGES.*TIPS.*OTHER\b|\bFEDERAL\s+INCOME\s+TAX\s+WITHHELD\b', re.I), DocCategory.W2),
(re.compile(r'\b1099-?[A-Z]{0,4}\b|\bNONEMPLOYEE\s+COMPENSATION\b|\bMISCELLANEOUS\s+INCOME\b', re.I), DocCategory.FORM_1099),
# Accounting documents
(re.compile(r'\bENGAGEMENT\s+LETTER\b|\bTAX\s+RETURN\s+PREPARATION\s+SERVICES\b', re.I), DocCategory.ENGAGEMENT_LETTER),
(re.compile(r'\bTAX\s+ORGANIZER\b|\bLLC\s+TAX\b|\bS[-\s]?CORP\b|\bPARTNERSHIP\s+TAX\b', re.I), DocCategory.TAX_ORGANIZER),
(re.compile(r'\bINVOICE\b|\bINV\s*(NO|#|:)\b|\bGST\s+INVOICE\b|\bTAX\s+INVOICE\b', re.I), DocCategory.INVOICE),
(re.compile(r'\bACCOUNT\s+STATEMENT\b|\bSTATEMENT\s+OF\s+ACCOUNT\b|\bOPENING\s+BALANCE\b|\bCLOSING\s+BALANCE\b', re.I), DocCategory.BANK_STATEMENT),
]
def classify_other_doc(
ocr_text: str,
filename: str = "",
) -> DocCategory:
"""
Detect the actual document type from OCR text and filename.
Returns DocCategory.GENERIC if nothing matches.
Args:
ocr_text: Raw text extracted from the document (any amount).
filename: Original upload filename — used as a secondary hint.
"""
corpus = f"{filename} {ocr_text}"
for pattern, category in _PATTERNS:
if pattern.search(corpus):
logger.info(f"[DocClassifier] Detected '{category.value}' from other_* upload")
return category
logger.info("[DocClassifier] No match — defaulting to GENERIC")
return DocCategory.GENERIC
def get_doc_type_for_prompt(original_doc_type: str, ocr_text: str, filename: str = "") -> str:
"""
Returns the best doc_type string to use in the extraction prompt.
For required-slot uploads (doc_type = real template name from DB),
returns as-is. For other_* uploads, runs the classifier and returns
the detected category's human-readable label.
"""
if not original_doc_type.startswith("other_"):
return original_doc_type
category = classify_other_doc(ocr_text=ocr_text, filename=filename)
return category.value
+236
View File
@@ -0,0 +1,236 @@
"""
Document Intelligence Utilities.
Provides:
1. field_validator — regex-based type validation for extracted fields
2. reconcile_user_docs — cross-document field comparison (name/ID mismatches)
3. build_daily_digest — AI-generated plain-English summary of today's activity
"""
from __future__ import annotations
import re
import os
import logging
import requests
from datetime import datetime, date
from typing import Any
logger = logging.getLogger(__name__)
# ─────────────────────────────────────────────────────────────────────────────
# 1. Field type validation
# ─────────────────────────────────────────────────────────────────────────────
# Field name patterns → (regex that the VALUE must match, human label for error)
_FIELD_VALIDATORS: list[tuple[re.Pattern, re.Pattern, str]] = [
# key pattern value pattern error label
(re.compile(r'pan[_\s]?(number|no)?', re.I), re.compile(r'^[A-Z]{5}\d{4}[A-Z]$'), "PAN (AAAAA9999A)"),
(re.compile(r'aadhaar[_\s]?(no|number)?', re.I), re.compile(r'^\d{4}\s?\d{4}\s?\d{4}$'), "Aadhaar (12 digits)"),
(re.compile(r'(ein|employer[_\s]?id)', re.I), re.compile(r'^\d{2}-\d{7}$'), "EIN (XX-XXXXXXX)"),
(re.compile(r'ssn|social[_\s]?security', re.I), re.compile(r'^\d{3}-\d{2}-\d{4}$'), "SSN (XXX-XX-XXXX)"),
(re.compile(r'date[_\s]?of[_\s]?birth|dob', re.I),
re.compile(r'^\d{2}/\d{2}/\d{4}$'), "DOB (DD/MM/YYYY)"),
(re.compile(r'(inv|invoice)[_\s]?(dt|date)', re.I),
re.compile(r'^\d{2}/\d{2}/\d{4}$'), "Date (DD/MM/YYYY)"),
(re.compile(r'tax[_\s]?year', re.I), re.compile(r'^\d{4}$'), "Tax Year (4 digits)"),
(re.compile(r'gst[_\s]?(no|number)?', re.I),
re.compile(r'^\d{2}[A-Z]{5}\d{4}[A-Z][1-9A-Z]Z[0-9A-Z]$'), "GSTIN (15-char format)"),
]
def validate_extracted_fields(extracted_data: dict) -> list[dict]:
"""
Run format validation against extracted fields.
Returns a list of validation warnings (empty list = all clear).
Each warning: {"field": str, "value": str, "expected": str, "severity": "warning"|"error"}
"""
if not extracted_data:
return []
warnings = []
for key, value in extracted_data.items():
if key == "_meta" or value is None or not isinstance(value, str):
continue
val = value.strip()
for key_pattern, val_pattern, label in _FIELD_VALIDATORS:
if key_pattern.search(key):
if not val_pattern.match(val):
warnings.append({
"field": key,
"value": val,
"expected": label,
"severity": "warning",
})
break # only one pattern per field
if warnings:
logger.info(f"[Validation] {len(warnings)} field format warnings on extracted data")
return warnings
# ─────────────────────────────────────────────────────────────────────────────
# 2. Cross-document reconciliation
# ─────────────────────────────────────────────────────────────────────────────
# Fields to compare across documents — (canonical_name, list of key aliases)
_RECONCILE_FIELDS = [
("name", ["name", "full name", "taxpayer name", "account name"]),
("pan", ["pan number", "pan", "pan_number", "permanent account number"]),
("dob", ["date of birth", "dob", "date_of_birth", "birth date"]),
("ein", ["ein", "employer id", "employer identification number"]),
("tax_year",["tax year", "tax_year", "taxyear", "year"]),
]
def _find_field(data: dict, aliases: list[str]) -> str | None:
"""Case-insensitive lookup of a field by any of its aliases."""
for key, val in data.items():
if any(alias in key.lower() for alias in aliases):
if val and isinstance(val, str):
return val.strip().lower()
return None
def reconcile_user_documents(docs: list[dict]) -> list[dict]:
"""
Compare key fields across a user's extracted documents.
Returns mismatches as a list of flags.
`docs` is a list of {"doc_type": str, "extracted_data": dict} dicts.
Each flag: {"field": str, "doc_a": str, "value_a": str,
"doc_b": str, "value_b": str, "severity": "warning"}
"""
if len(docs) < 2:
return []
# Only include docs that have real extracted data (not blank templates)
real_docs = [
d for d in docs
if d.get("extracted_data") and
d["extracted_data"].get("status") != "blank_template" and
isinstance(d["extracted_data"], dict)
]
if len(real_docs) < 2:
return []
flags = []
for canonical, aliases in _RECONCILE_FIELDS:
# Collect (doc_label, value) for all docs that have this field
present = []
for d in real_docs:
val = _find_field(d["extracted_data"], aliases)
if val:
present.append((d.get("doc_type", "Unknown"), val))
if len(present) < 2:
continue
# Compare all pairs
for i in range(len(present)):
for j in range(i + 1, len(present)):
label_a, val_a = present[i]
label_b, val_b = present[j]
# Normalize: strip spaces/hyphens for ID-style fields
norm_a = re.sub(r'[\s\-]', '', val_a)
norm_b = re.sub(r'[\s\-]', '', val_b)
if norm_a != norm_b:
flags.append({
"field": canonical,
"doc_a": label_a,
"value_a": val_a,
"doc_b": label_b,
"value_b": val_b,
"severity": "warning",
"message": f"'{canonical}' mismatch: '{val_a}' in {label_a} vs '{val_b}' in {label_b}",
})
if flags:
logger.info(f"[Reconciliation] {len(flags)} cross-document mismatches found")
return flags
# ─────────────────────────────────────────────────────────────────────────────
# 3. Admin daily digest
# ─────────────────────────────────────────────────────────────────────────────
def build_daily_digest(db_stats: dict) -> str:
"""
Generate a plain-English daily digest using the LLM.
`db_stats` should contain the same structure as get_admin_status() returns.
Returns a formatted HTML string for display in the admin dashboard.
"""
api_key = os.getenv("OPENROUTER_API_KEY")
if not api_key:
return _fallback_digest(db_stats)
today = date.today().strftime("%B %d, %Y")
stats_text = (
f"Date: {today}\n"
f"New users registered today: {db_stats.get('new_users_today', 0)}\n"
f"Total users: {db_stats.get('total_users', 0)}\n"
f"Pending personal docs: {db_stats.get('pending_personal', 0)}\n"
f"Pending business docs: {db_stats.get('pending_business', 0)}\n"
f"Total pending docs: {db_stats.get('total_pending', 0)}\n"
)
recent = db_stats.get("recent_uploads", [])
if recent:
stats_text += "\nRecent uploads today:\n"
for r in recent[:5]:
stats_text += f"- {r['user_name']} uploaded {r['doc']} ({r['type']}) at {r['uploaded_at']}\n"
prompt = (
"You are an accounting firm assistant. Write a brief, friendly, plain-English daily digest "
"for the admin team based on today's activity data below. "
"Keep it to 3-4 bullet points. Be specific about numbers. Use a professional but warm tone.\n\n"
f"TODAY'S ACTIVITY DATA:\n{stats_text}\n\n"
"Write the digest now. Use bullet points (•). No markdown headers."
)
try:
model = os.getenv("OCR_TEXT_MODEL", "meta-llama/llama-3.3-70b-instruct")
response = requests.post(
url="https://openrouter.ai/api/v1/chat/completions",
headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
json={
"model": model,
"messages": [{"role": "user", "content": prompt}],
"max_tokens": 300,
},
timeout=20,
)
response.raise_for_status()
content = response.json()["choices"][0]["message"]["content"].strip()
# Wrap bullets in styled HTML
lines = content.split("\n")
html_lines = []
for line in lines:
line = line.strip()
if line.startswith("•") or line.startswith("-"):
html_lines.append(f"<li>{line.lstrip('•-').strip()}</li>")
elif line:
html_lines.append(f"<p>{line}</p>")
return f"<ul style='margin:0;padding-left:18px'>{''.join(html_lines)}</ul>"
except Exception as e:
logger.error(f"[DailyDigest] LLM call failed: {e}")
return _fallback_digest(db_stats)
def _fallback_digest(stats: dict) -> str:
today = date.today().strftime("%B %d, %Y")
total = stats.get("total_pending", 0)
new_u = stats.get("new_users_today", 0)
lines = [
f"<li>Today is {today}.</li>",
f"<li>{new_u} new user(s) registered today.</li>",
f"<li>{total} document(s) currently awaiting review.</li>",
]
pp = stats.get("pending_personal", 0)
pb = stats.get("pending_business", 0)
if pp or pb:
lines.append(f"<li>{pp} personal and {pb} business documents are pending.</li>")
return f"<ul style='margin:0;padding-left:18px'>{''.join(lines)}</ul>"
+68 -15
View File
@@ -1,31 +1,84 @@
"""
Incremental migration script — safe to re-run on any existing DB.
Each ALTER TABLE is wrapped individually so a failure on one column
never blocks the rest. "Duplicate column" errors are silently skipped.
"""
import sys import sys
import os import os
# Add the root directory to sys.path so we can import app
sys.path.append(os.path.abspath(os.path.dirname(__file__))) sys.path.append(os.path.abspath(os.path.dirname(__file__)))
from app.db import engine from app.db import engine
from sqlalchemy import text from sqlalchemy import text
from sqlalchemy.exc import OperationalError, ProgrammingError from sqlalchemy.exc import OperationalError, ProgrammingError
def _add_column(conn, table: str, column: str, definition: str):
"""Add a column if it doesn't already exist. Silently skips duplicates."""
try:
conn.execute(text(f"ALTER TABLE {table} ADD COLUMN {column} {definition}"))
print(f" [OK] Added {table}.{column}")
except (OperationalError, ProgrammingError) as e:
msg = str(e).lower()
if "duplicate column" in msg or "already exists" in msg:
print(f" [SKIP] {table}.{column} already exists")
else:
print(f" [WARN] {table}.{column}: {e}")
def upgrade(): def upgrade():
print("Running migrations...")
try: try:
with engine.begin() as conn: with engine.begin() as conn:
try:
conn.execute(text("ALTER TABLE personal_documents ADD COLUMN extracted_data JSON")) # ── v1: AI extraction data ────────────────────────────────────────
print("Added extracted_data to personal_documents") _add_column(conn, "personal_documents", "extracted_data", "JSON")
except (OperationalError, ProgrammingError) as e: _add_column(conn, "business_documents", "extracted_data", "JSON")
print(f"personal_documents: {e}")
# ── v2: Engagement acknowledgement on users ───────────────────────
try: _add_column(conn, "users", "engagement_acknowledged_at",
conn.execute(text("ALTER TABLE business_documents ADD COLUMN extracted_data JSON")) "DATETIME NULL DEFAULT NULL")
print("Added extracted_data to business_documents")
except (OperationalError, ProgrammingError) as e: # ── v3: Unique indexes for document dedup ─────────────────────────
print(f"business_documents: {e}") for stmt in [
"ALTER TABLE personal_documents DROP INDEX uq_personal_doc_user_type_year",
print("Migration complete.") "ALTER TABLE personal_documents ADD UNIQUE INDEX uq_personal_doc_user_type_year (user_id, doc_type, tax_year)",
"ALTER TABLE business_documents DROP INDEX uq_business_doc_user_type_year",
"ALTER TABLE business_documents ADD UNIQUE INDEX uq_business_doc_user_type_year (user_id, business_type, tax_year)",
]:
try:
conn.execute(text(stmt))
print(f" [OK] {stmt[:60]}...")
except (OperationalError, ProgrammingError) as e:
msg = str(e).lower()
if "duplicate" in msg or "already exists" in msg or "can't drop" in msg:
print(f" [SKIP] Already applied: {stmt[:50]}...")
else:
print(f" [WARN] {e}")
# ── v4: File hash column for extraction deduplication (Item 3) ────
_add_column(conn, "personal_documents", "file_hash",
"VARCHAR(64) NULL DEFAULT NULL")
_add_column(conn, "business_documents", "file_hash",
"VARCHAR(64) NULL DEFAULT NULL")
# Add index on file_hash for fast cache lookups
for table in ("personal_documents", "business_documents"):
try:
conn.execute(text(
f"CREATE INDEX ix_{table}_file_hash ON {table} (file_hash)"
))
print(f" [OK] Index ix_{table}_file_hash created")
except (OperationalError, ProgrammingError) as e:
if "duplicate" in str(e).lower() or "already exists" in str(e).lower():
print(f" [SKIP] Index ix_{table}_file_hash already exists")
else:
print(f" [WARN] Index {table}: {e}")
print("\nAll migrations complete.")
except Exception as e: except Exception as e:
print(f"Error: {e}") print(f"Migration error: {e}")
if __name__ == "__main__": if __name__ == "__main__":
upgrade() upgrade()
-32
View File
@@ -1,14 +1,7 @@
aiosmtplib==5.0.0 aiosmtplib==5.0.0
annotated-doc==0.0.4
annotated-types==0.7.0 annotated-types==0.7.0
anyio==4.12.0 anyio==4.12.0
argon2-cffi==25.1.0
argon2-cffi-bindings==25.1.0
bcrypt==4.1.2 bcrypt==4.1.2
blinker==1.9.0
boto3==1.34.131
botocore==1.34.162
cachetools==6.2.2
certifi==2025.11.12 certifi==2025.11.12
cffi==2.0.0 cffi==2.0.0
charset-normalizer==3.4.4 charset-normalizer==3.4.4
@@ -19,52 +12,27 @@ dnspython==2.8.0
ecdsa==0.19.1 ecdsa==0.19.1
email-validator==2.3.0 email-validator==2.3.0
fastapi==0.123.0 fastapi==0.123.0
fastapi-mail==1.6.1
slowapi==0.1.9 slowapi==0.1.9
google-api-core==2.28.1
google-api-python-client==2.187.0
google-auth==2.41.1
google-auth-httplib2==0.2.1
google-auth-oauthlib==1.2.3
googleapis-common-protos==1.72.0
greenlet==3.2.4 greenlet==3.2.4
h11==0.16.0 h11==0.16.0
httplib2==0.31.0
httptools==0.7.1 httptools==0.7.1
idna==3.11 idna==3.11
Jinja2==3.1.6
MarkupSafe==3.0.3
oauthlib==3.3.1
passlib==1.7.4
proto-plus==1.26.1
protobuf==6.33.2
pyasn1==0.6.1
pyasn1_modules==0.4.2
pycparser==2.23 pycparser==2.23
pydantic==2.12.5 pydantic==2.12.5
pydantic-settings==2.12.0 pydantic-settings==2.12.0
pydantic_core==2.41.5 pydantic_core==2.41.5
PyJWT==2.10.1
PyMySQL==1.1.2 PyMySQL==1.1.2
pyparsing==3.2.5
python-dotenv==1.2.1 python-dotenv==1.2.1
python-jose==3.5.0 python-jose==3.5.0
python-multipart==0.0.20 python-multipart==0.0.20
PyYAML==6.0.3
regex==2025.11.3
requests==2.32.5 requests==2.32.5
requests-oauthlib==2.0.0
rsa==4.9.1
six==1.17.0 six==1.17.0
SQLAlchemy==2.0.44 SQLAlchemy==2.0.44
starlette==0.50.0 starlette==0.50.0
typing-inspection==0.4.2 typing-inspection==0.4.2
typing_extensions==4.15.0 typing_extensions==4.15.0
uritemplate==4.2.0
urllib3==2.6.0 urllib3==2.6.0
uvicorn==0.38.0 uvicorn==0.38.0
watchfiles==1.1.1
websockets==15.0.1
filetype==1.2.0 filetype==1.2.0
pymupdf==1.24.1 pymupdf==1.24.1