chore: apply deployment fixes, timezone fixes, and cleanup unused dependencies
This commit is contained in:
@@ -1,27 +1,26 @@
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { useState, useRef, useEffect, useCallback } from 'react';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
|
||||
const STORAGE_KEY = 'admin_chat_history';
|
||||
const MAX_HISTORY = 40; // messages to persist
|
||||
|
||||
const FAQ_DATA = {
|
||||
"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: "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: "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: "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 → Returns for Review tab → click '+ Upload Document'." }
|
||||
],
|
||||
"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: "Can I add another admin?", a: "Super Admins can only be created via the backend script `create_super_admin.py` for security reasons." }
|
||||
{ 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`." }
|
||||
],
|
||||
"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 = {
|
||||
"Document Review": "📑",
|
||||
"User Management": "👥",
|
||||
"Notifications": "🔔",
|
||||
};
|
||||
const CATEGORY_ICONS = { "Document Review": "📑", "User Management": "👥", "Notifications": "🔔" };
|
||||
|
||||
const formatMessage = (text) => {
|
||||
if (!text) return '';
|
||||
@@ -36,42 +35,80 @@ export default function AdminChatbot() {
|
||||
const { user, authFetch } = useAuth();
|
||||
const location = useLocation();
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [messages, setMessages] = useState([]);
|
||||
const [view, setView] = useState('menu'); // menu | category | chat
|
||||
const [view, setView] = useState('menu');
|
||||
const [activeCategory, setActiveCategory] = useState(null);
|
||||
const [inputText, setInputText] = useState("");
|
||||
const [menuInput, setMenuInput] = useState(""); // free-text from menu
|
||||
const [menuInput, setMenuInput] = useState("");
|
||||
const [isTyping, setIsTyping] = useState(false);
|
||||
const [pendingBulk, setPendingBulk] = useState(null); // bulk action awaiting confirmation
|
||||
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(() => {
|
||||
chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
|
||||
}, [messages, view]);
|
||||
try {
|
||||
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 () => {
|
||||
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');
|
||||
try {
|
||||
const res = await authFetch('/api/chatbot/admin-status');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setMessages(prev => [...prev, { type: 'bot', text: data.message }]);
|
||||
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: data.message }]);
|
||||
} 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 {
|
||||
setMessages(prev => [...prev, { type: 'bot', text: 'Network error.' }]);
|
||||
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Network error.' }]);
|
||||
}
|
||||
};
|
||||
|
||||
/* ── send a message to /ask ── */
|
||||
const sendMessage = async (text, existingMessages) => {
|
||||
// ── Bulk action executor with confirmation ────────────────────────────────
|
||||
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 allMessages = [...(existingMessages ?? messages), userMsg];
|
||||
const allMessages = [...(overrideMessages ?? messages), userMsg];
|
||||
setMessages(allMessages);
|
||||
setInputText("");
|
||||
setMenuInput("");
|
||||
@@ -83,6 +120,7 @@ export default function AdminChatbot() {
|
||||
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,
|
||||
@@ -90,9 +128,27 @@ export default function AdminChatbot() {
|
||||
})),
|
||||
}),
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
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 {
|
||||
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Having trouble connecting. Please try again.' }]);
|
||||
}
|
||||
@@ -101,123 +157,108 @@ export default function AdminChatbot() {
|
||||
} finally {
|
||||
setIsTyping(false);
|
||||
}
|
||||
};
|
||||
|
||||
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(), []);
|
||||
};
|
||||
}, [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) => {
|
||||
setMessages(prev => [...prev, { type: 'user', text: faq.q }, { type: 'bot', text: faq.a }]);
|
||||
setView('chat');
|
||||
};
|
||||
|
||||
if (!user || (user.role !== 'admin' && user.role !== 'super_admin') || !location.pathname.startsWith('/admin')) {
|
||||
return null;
|
||||
}
|
||||
if (!user || (user.role !== 'admin' && user.role !== 'super_admin') || !location.pathname.startsWith('/admin')) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
className={`chatbot-fab ${isOpen ? 'open' : ''}`}
|
||||
onClick={toggleChat}
|
||||
<button className={`chatbot-fab ${isOpen ? 'open' : ''}`} onClick={() => setIsOpen(o => !o)}
|
||||
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="notif-dot"></span>
|
||||
</button>
|
||||
|
||||
{isOpen && (
|
||||
<div className="chatbot-window visible">
|
||||
{/* header */}
|
||||
<div className="chatbot-header" style={{ background: 'var(--ink)' }}>
|
||||
<div className="bot-avatar">🤖</div>
|
||||
<div className="bot-info">
|
||||
<h4>Admin Assistant</h4>
|
||||
<span>Live system insights</span>
|
||||
</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>
|
||||
|
||||
{/* messages area */}
|
||||
<div className="chatbot-messages">
|
||||
|
||||
{/* ── MENU VIEW ── */}
|
||||
{view === 'menu' && (
|
||||
<>
|
||||
<div className="chatbot-welcome-text">
|
||||
<span className="material-symbols-outlined sparkle">auto_awesome</span>
|
||||
<p>What do you need today?</p>
|
||||
</div>
|
||||
|
||||
{/* free-text ask from menu */}
|
||||
<form onSubmit={handleMenuAsk} style={{ marginBottom: '12px', display: 'flex', gap: '6px' }}>
|
||||
<input
|
||||
type="text"
|
||||
value={menuInput}
|
||||
onChange={e => setMenuInput(e.target.value)}
|
||||
<input type="text" value={menuInput} onChange={e => setMenuInput(e.target.value)}
|
||||
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' }}
|
||||
/>
|
||||
<button type="submit" style={{ background: 'var(--emerald)', color: '#fff', border: 'none', borderRadius: 'var(--radius-pill)', padding: '8px 14px', cursor: 'pointer', fontSize: '13px' }}>
|
||||
Ask
|
||||
</button>
|
||||
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>
|
||||
</form>
|
||||
|
||||
<button className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '8px' }} onClick={handleAdminStatusCheck}>
|
||||
<span className="qr-icon">📊</span> System Overview
|
||||
</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 => (
|
||||
<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}
|
||||
</button>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* ── CATEGORY VIEW ── */}
|
||||
{view === 'category' && (
|
||||
<>
|
||||
<button className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '16px', background: 'transparent', border: 'none' }} onClick={() => setView('menu')}>
|
||||
← 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}</h4>
|
||||
{FAQ_DATA[activeCategory].map((faq, i) => (
|
||||
<button key={i} className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '8px' }} onClick={() => askFaq(faq)}>
|
||||
{faq.q}
|
||||
</button>
|
||||
<button key={i} className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '8px' }} onClick={() => askFaq(faq)}>{faq.q}</button>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* ── CHAT VIEW ── */}
|
||||
{view === 'chat' && (
|
||||
<>
|
||||
<button className="quick-reply-btn" onClick={() => setView('menu')} style={{ display: 'flex', width: '100%', marginBottom: '16px', background: 'transparent', border: 'none' }}>
|
||||
← Back to menu
|
||||
</button>
|
||||
<button className="quick-reply-btn" onClick={() => setView('menu')}
|
||||
style={{ display: 'flex', width: '100%', marginBottom: '16px', background: 'transparent', border: 'none' }}>← Back to menu</button>
|
||||
{messages.map((msg, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={`chat-msg ${msg.type === 'bot' ? 'bot' : 'user'}`}
|
||||
{...(msg.type === 'bot'
|
||||
? { dangerouslySetInnerHTML: { __html: formatMessage(msg.text) } }
|
||||
: { children: msg.text })}
|
||||
/>
|
||||
<div key={i} className={`chat-msg ${msg.type === 'bot' ? 'bot' : 'user'}`}
|
||||
{...(msg.type === 'bot' ? { dangerouslySetInnerHTML: { __html: formatMessage(msg.text) } } : { children: msg.text })} />
|
||||
))}
|
||||
{isTyping && (
|
||||
<div className="chat-msg bot" style={{ fontStyle: 'italic', opacity: 0.7 }}>
|
||||
Admin Assistant is typing…
|
||||
{isTyping && <div className="chat-msg bot" style={{ fontStyle: 'italic', opacity: 0.7 }}>Admin Assistant is typing…</div>}
|
||||
|
||||
{/* 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 ref={chatEndRef} />
|
||||
@@ -225,20 +266,13 @@ export default function AdminChatbot() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* footer input — always shown in chat view */}
|
||||
<div className="chatbot-footer" style={{ padding: '12px', borderTop: '1px solid var(--border)', background: 'var(--bg)' }}>
|
||||
{view === 'chat' ? (
|
||||
<form onSubmit={handleSendMessage} style={{ display: 'flex', gap: '8px' }}>
|
||||
<input
|
||||
type="text"
|
||||
value={inputText}
|
||||
onChange={e => setInputText(e.target.value)}
|
||||
<input type="text" value={inputText} onChange={e => setInputText(e.target.value)}
|
||||
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)' }}
|
||||
/>
|
||||
<button type="submit" style={{ background: 'var(--emerald)', color: '#fff', border: 'none', borderRadius: 'var(--radius-pill)', padding: '8px 16px', cursor: 'pointer' }}>
|
||||
Send
|
||||
</button>
|
||||
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>
|
||||
</form>
|
||||
) : (
|
||||
<p style={{ margin: 0, fontSize: '13px', color: 'var(--muted)' }}>Admin tools & shortcuts</p>
|
||||
|
||||
+161
-167
@@ -1,176 +1,164 @@
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { useState, useRef, useEffect, useCallback } from 'react';
|
||||
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 = {
|
||||
// ... (keep the same FAQ_DATA below this)
|
||||
"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 update my profile?", a: 'Go to your Profile page to update your name, phone number, or change your password.' },
|
||||
],
|
||||
"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 does "Pending" status mean?', a: 'Your document has been uploaded successfully 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 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 and is waiting for an admin to review it.' },
|
||||
{ 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": [
|
||||
{ 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.' },
|
||||
],
|
||||
"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 = {
|
||||
"Account": "👤",
|
||||
"Documents": "📄",
|
||||
"Tax Filing": "📋",
|
||||
"Security": "🔒"
|
||||
};
|
||||
const CATEGORY_ICONS = { "Account": "👤", "Documents": "📄", "Tax Filing": "📋", "Security": "🔒" };
|
||||
|
||||
const formatMessage = (text) => {
|
||||
if (!text) return '';
|
||||
let html = text;
|
||||
html = html.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>');
|
||||
html = html.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>');
|
||||
html = html.replace(/\n/g, '<br/>');
|
||||
return html;
|
||||
return text
|
||||
.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>')
|
||||
.replace(/\*(.*?)\*/g, '<i>$1</i>')
|
||||
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" style="color:var(--blue);text-decoration:underline">$1</a>')
|
||||
.replace(/\n/g, '<br/>');
|
||||
};
|
||||
|
||||
export default function Chatbot() {
|
||||
const { user, authFetch } = useAuth();
|
||||
const location = useLocation();
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [messages, setMessages] = useState([]);
|
||||
const [view, setView] = useState('menu'); // menu, category, chat
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [view, setView] = useState('menu');
|
||||
const [activeCategory, setActiveCategory] = useState(null);
|
||||
const [inputText, setInputText] = useState("");
|
||||
const [menuInput, setMenuInput] = useState(""); // free-text from menu
|
||||
const [isTyping, setIsTyping] = useState(false);
|
||||
const [inputText, setInputText] = useState("");
|
||||
const [menuInput, setMenuInput] = useState("");
|
||||
const [isTyping, setIsTyping] = useState(false);
|
||||
const chatEndRef = useRef(null);
|
||||
|
||||
// Close chatbot when navigating
|
||||
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 []; }
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (chatEndRef.current) {
|
||||
chatEndRef.current.scrollIntoView({ behavior: 'smooth' });
|
||||
}
|
||||
}, [messages, view]);
|
||||
try { localStorage.setItem(STORAGE_KEY, JSON.stringify(messages.slice(-MAX_HISTORY))); }
|
||||
catch { /* storage full */ }
|
||||
}, [messages]);
|
||||
|
||||
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 () => {
|
||||
if (!user) {
|
||||
setMessages([...messages, { type: 'bot', text: 'You need to log in to check your document status.' }]);
|
||||
setView('chat');
|
||||
return;
|
||||
}
|
||||
|
||||
setMessages([...messages, { type: 'user', text: 'Check my document status' }]);
|
||||
if (!user) return;
|
||||
setMessages(prev => [...prev, { type: 'user', role: 'user', text: 'Check my document status' }]);
|
||||
setView('chat');
|
||||
|
||||
try {
|
||||
const res = await authFetch('/api/chatbot/doc-status');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setMessages(prev => [...prev, { type: 'bot', text: data.message }]);
|
||||
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: data.message }]);
|
||||
} 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) {
|
||||
setMessages(prev => [...prev, { type: 'bot', text: 'Network error occurred.' }]);
|
||||
} catch {
|
||||
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Network error occurred.' }]);
|
||||
}
|
||||
};
|
||||
|
||||
const selectCategory = (cat) => {
|
||||
setActiveCategory(cat);
|
||||
setView('category');
|
||||
// ── Upload shortcut (deeplink) ─────────────────────────────────────────────
|
||||
const handleUploadShortcut = (type) => {
|
||||
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) => {
|
||||
setMessages(prev => [...prev, { type: 'user', text: faq.q }, { type: 'bot', text: faq.a }]);
|
||||
setView('chat');
|
||||
};
|
||||
|
||||
const resetToMenu = () => {
|
||||
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
|
||||
}
|
||||
if (!user || user.role === 'admin' || user.role === 'super_admin' || location.pathname.startsWith('/admin')) return null;
|
||||
|
||||
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="notif-dot"></span>
|
||||
</button>
|
||||
@@ -179,11 +167,14 @@ export default function Chatbot() {
|
||||
<div className="chatbot-window visible">
|
||||
<div className="chatbot-header">
|
||||
<div className="bot-avatar">🤖</div>
|
||||
<div className="bot-info">
|
||||
<h4>BookKeep Assistant</h4>
|
||||
<span>Online and ready to help</span>
|
||||
<div className="bot-info"><h4>BookKeep Assistant</h4><span>Online and ready to help</span></div>
|
||||
<div style={{ display: 'flex', gap: '4px', alignItems: 'center' }}>
|
||||
{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>
|
||||
<button className="close-chat" onClick={toggleChat}>✕</button>
|
||||
</div>
|
||||
|
||||
<div className="chatbot-messages">
|
||||
@@ -193,29 +184,36 @@ export default function Chatbot() {
|
||||
<span className="material-symbols-outlined sparkle">auto_awesome</span>
|
||||
<p>How can we help you today?</p>
|
||||
</div>
|
||||
|
||||
{/* free-text ask from menu */}
|
||||
<form onSubmit={handleMenuAsk} style={{ marginBottom: '12px', display: 'flex', gap: '6px' }}>
|
||||
<input
|
||||
type="text"
|
||||
value={menuInput}
|
||||
onChange={e => setMenuInput(e.target.value)}
|
||||
<input type="text" value={menuInput} onChange={e => setMenuInput(e.target.value)}
|
||||
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' }}
|
||||
/>
|
||||
<button type="submit" style={{ background: 'var(--emerald)', color: '#fff', border: 'none', borderRadius: 'var(--radius-pill)', padding: '8px 14px', cursor: 'pointer', fontSize: '13px' }}>
|
||||
Ask
|
||||
</button>
|
||||
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>
|
||||
</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 && (
|
||||
<button className="quick-reply-btn" style={{display: 'flex', width: '100%', marginBottom: '8px'}} onClick={handleDocStatusCheck}>
|
||||
<span className="qr-icon">📋</span>
|
||||
Check Document Status
|
||||
<button className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '8px' }} onClick={handleDocStatusCheck}>
|
||||
<span className="qr-icon">📋</span> 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>
|
||||
)}
|
||||
{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
|
||||
</button>
|
||||
))}
|
||||
@@ -224,52 +222,48 @@ export default function Chatbot() {
|
||||
|
||||
{view === 'category' && (
|
||||
<>
|
||||
<button className="quick-reply-btn" style={{display: 'flex', width: '100%', marginBottom: '16px', background: 'transparent', border: 'none'}} onClick={resetToMenu}>← Back to menu</button>
|
||||
<h4 style={{margin:'0 0 12px', fontSize:'14px', color:'var(--navy)'}}>{activeCategory} Questions</h4>
|
||||
<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>
|
||||
{FAQ_DATA[activeCategory].map((faq, i) => (
|
||||
<button key={i} className="quick-reply-btn" style={{display: 'flex', width: '100%', marginBottom: '8px'}} onClick={() => askFaq(faq)}>
|
||||
{faq.q}
|
||||
</button>
|
||||
<button key={i} className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '8px' }} onClick={() => askFaq(faq)}>{faq.q}</button>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
|
||||
{view === 'chat' && (
|
||||
<>
|
||||
<button className="quick-reply-btn" onClick={resetToMenu} style={{display: 'flex', width: '100%', marginBottom: '16px', background: 'transparent', border: 'none'}}>
|
||||
← Back to menu
|
||||
</button>
|
||||
<button className="quick-reply-btn" onClick={() => setView('menu')} style={{ display: 'flex', width: '100%', marginBottom: '16px', background: 'transparent', border: 'none' }}>← Back to menu</button>
|
||||
{messages.map((msg, i) => (
|
||||
<div key={i} className={`chat-msg ${msg.type === 'bot' ? 'bot' : 'user'}`}
|
||||
{...(msg.type === 'bot' ? { dangerouslySetInnerHTML: { __html: formatMessage(msg.text) } } : { children: msg.text })}
|
||||
/>
|
||||
))}
|
||||
{isTyping && (
|
||||
<div className="chat-msg bot" style={{ fontStyle: 'italic', opacity: 0.7 }}>
|
||||
BookKeep Assistant is typing...
|
||||
<div key={i}>
|
||||
<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 */}
|
||||
{msg.action?.type === 'navigate' && (
|
||||
<div style={{ marginTop: '6px', marginLeft: '12px' }}>
|
||||
<button className="btn btn-primary btn-sm" style={{ borderRadius: 'var(--radius-pill)' }}
|
||||
onClick={() => handleUploadShortcut(msg.action.dest)}>
|
||||
{msg.action.label}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
))}
|
||||
{isTyping && <div className="chat-msg bot" style={{ fontStyle: 'italic', opacity: 0.7 }}>BookKeep Assistant is typing…</div>}
|
||||
<div ref={chatEndRef} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
<div className="chatbot-footer" style={{ padding: '12px', borderTop: '1px solid var(--border)', background: 'var(--bg)' }}>
|
||||
{view === 'chat' ? (
|
||||
<form onSubmit={handleSendMessage} style={{ display: 'flex', gap: '8px' }}>
|
||||
<input
|
||||
type="text"
|
||||
value={inputText}
|
||||
onChange={(e) => setInputText(e.target.value)}
|
||||
<input type="text" value={inputText} onChange={e => setInputText(e.target.value)}
|
||||
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)' }}
|
||||
/>
|
||||
<button type="submit" style={{ background: 'var(--emerald)', color: '#fff', border: 'none', borderRadius: 'var(--radius-pill)', padding: '8px 16px', cursor: 'pointer' }}>
|
||||
Send
|
||||
</button>
|
||||
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>
|
||||
</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>
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
import { useState } from 'react';
|
||||
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 }) {
|
||||
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) {
|
||||
return (
|
||||
<div style={{ fontSize: '12px', color: 'var(--muted)', fontStyle: 'italic' }}>
|
||||
@@ -15,12 +25,38 @@ export default function ExpandableSummaryBlock({ extractedData }) {
|
||||
|
||||
const showToggle = entries.length > 3;
|
||||
const entriesToShow = expanded ? entries : entries.slice(0, 3);
|
||||
const confidenceStyle = CONFIDENCE_STYLES[_meta?.tier] || CONFIDENCE_STYLES.unknown;
|
||||
|
||||
return (
|
||||
<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]) => (
|
||||
<div key={key}>
|
||||
{/* Field label — uppercase, bold, navy */}
|
||||
<div style={{
|
||||
fontSize: '11px',
|
||||
color: 'var(--navy)',
|
||||
@@ -31,7 +67,6 @@ export default function ExpandableSummaryBlock({ extractedData }) {
|
||||
}}>
|
||||
{key}
|
||||
</div>
|
||||
{/* Field value — bold navy */}
|
||||
<div style={{ fontSize: '13px', fontWeight: 600, color: 'var(--navy)' }}>
|
||||
<ExpandableValue value={value} isArray={Array.isArray(value)} />
|
||||
</div>
|
||||
|
||||
@@ -19,6 +19,21 @@ export default function AdminDashboard() {
|
||||
const [tplFile, setTplFile] = useState(null);
|
||||
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 () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
@@ -156,6 +171,26 @@ export default function AdminDashboard() {
|
||||
{/* Users Tab */}
|
||||
{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 */}
|
||||
<div className="admin-stats">
|
||||
<div className="stat-card accent-blue">
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useAuth } from '../context/AuthContext';
|
||||
import { useToast } from '../context/ToastContext';
|
||||
import ExpandableSummaryBlock from '../components/ExpandableSummaryBlock';
|
||||
|
||||
|
||||
export default function AdminUserDetail() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const userId = searchParams.get('user_id');
|
||||
@@ -17,6 +18,7 @@ export default function AdminUserDetail() {
|
||||
const [taxYear, setTaxYear] = useState("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
|
||||
// States for Review Emails
|
||||
const [personalTimeline, setPersonalTimeline] = useState(0);
|
||||
const [businessTimeline, setBusinessTimeline] = useState(0);
|
||||
@@ -41,10 +43,8 @@ export default function AdminUserDetail() {
|
||||
const payload = await res.json();
|
||||
setUserDetail(payload.user);
|
||||
|
||||
// Map 'table' to 'type' for personal and business docs
|
||||
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}`);
|
||||
let adminDocs = [];
|
||||
if (adminDocsRes.ok) {
|
||||
@@ -52,7 +52,10 @@ export default function AdminUserDetail() {
|
||||
adminDocs = adminDocs.map(d => ({ ...d, type: 'admin', uploaded_at: d.created_at }));
|
||||
}
|
||||
|
||||
setDocuments([...userDocs, ...adminDocs]);
|
||||
const allDocs = [...userDocs, ...adminDocs];
|
||||
setDocuments(allDocs);
|
||||
|
||||
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
} finally {
|
||||
@@ -338,6 +341,7 @@ export default function AdminUserDetail() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="tab-bar">
|
||||
<button className={`tab-btn ${activeTab === 'personal' ? 'active' : ''}`} onClick={() => setActiveTab('personal')}><span className="material-symbols-outlined">description</span> Personal Docs</button>
|
||||
|
||||
@@ -24,7 +24,12 @@ export default function Login() {
|
||||
});
|
||||
|
||||
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();
|
||||
@@ -60,7 +65,16 @@ export default function Login() {
|
||||
<h1>Sign In</h1>
|
||||
<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}>
|
||||
<div className="form-group">
|
||||
|
||||
Reference in New Issue
Block a user