diff --git a/.env.docker.example b/.env.docker.example deleted file mode 100644 index a711266..0000000 --- a/.env.docker.example +++ /dev/null @@ -1,35 +0,0 @@ -# Docker / Contabo runtime settings -MYSQL_ROOT_PASSWORD=rootpassword -MYSQL_USER=bookkeep -MYSQL_PASSWORD=bookkeepro_pass -MYSQL_HOST=db -MYSQL_PORT=3306 -MYSQL_DATABASE=bookkeepprodb -DATABASE_URL=mysql+pymysql://bookkeep:bookkeepro_pass@db:3306/bookkeepprodb - -# Security & Authentication -SECRET_KEY=change_me_to_a_long_random_secret -ALGORITHM=HS256 -ACCESS_TOKEN_EXPIRE_MINUTES=1440 -FRONTEND_URL=http://localhost:8000 - -# Contabo / S3-compatible storage -CONTABO_ENDPOINT=https://eu2.contabostorage.com -CONTABO_REGION=eu2 -CONTABO_ACCESS_KEY=your_contabo_access_key -CONTABO_SECRET_KEY=your_contabo_secret_key -CONTABO_BUCKET=bookkeepro-docs -PRESIGNED_URL_EXPIRY=3600 - -# Email Configuration (SMTP) -SMTP_USER=your_smtp_user -SMTP_PASSWORD=your_smtp_password -MAIL_FROM=noreply@bookkeepro.net -SMTP_HOST=smtp.yourprovider.com -SMTP_PORT=587 -SMTP_TLS=True -MAIL_SSL_TLS=False -MAIL_FROM_NAME=BookKeepro - -# Application Settings -ADMIN_EMAIL=admin@bookkeepro.net \ No newline at end of file diff --git a/.env.example b/.env.example deleted file mode 100644 index a307dd1..0000000 --- a/.env.example +++ /dev/null @@ -1,34 +0,0 @@ -# Database Configuration -MYSQL_USER=root -MYSQL_PASSWORD= -MYSQL_HOST=localhost -MYSQL_PORT=3306 -MYSQL_DATABASE=bookkeepprodb -DATABASE_URL=mysql+pymysql://root:@localhost:3306/bookkeepprodb - -# Security & Authentication -SECRET_KEY=your_super_secret_key_here -ALGORITHM=HS256 -ACCESS_TOKEN_EXPIRE_MINUTES=1440 -FRONTEND_URL=https://bookkeepro.net - -# Contabo / S3-compatible storage -CONTABO_ENDPOINT=https://eu2.contabostorage.com -CONTABO_REGION=eu2 -CONTABO_ACCESS_KEY=your_contabo_access_key -CONTABO_SECRET_KEY=your_contabo_secret_key -CONTABO_BUCKET=bookkeepro-docs -PRESIGNED_URL_EXPIRY=3600 - -# Email Configuration (SMTP) -SMTP_USER=your_smtp_user -SMTP_PASSWORD=your_smtp_password -MAIL_FROM=noreply@bookkeepro.net -SMTP_HOST=smtp.yourprovider.com -SMTP_PORT=587 -SMTP_TLS=True -MAIL_SSL_TLS=False -MAIL_FROM_NAME=BookKeepro - -# Application Settings -ADMIN_EMAIL=admin@bookkeepro.net diff --git a/frontend/public/Engagement_Letter_Template.pdf b/frontend/public/Engagement_Letter_Template.pdf new file mode 100644 index 0000000..4ddd56d Binary files /dev/null and b/frontend/public/Engagement_Letter_Template.pdf differ diff --git a/frontend/src/components/ConfirmModal.css b/frontend/src/components/ConfirmModal.css new file mode 100644 index 0000000..7bc9df6 --- /dev/null +++ b/frontend/src/components/ConfirmModal.css @@ -0,0 +1,89 @@ +.confirm-modal-overlay { + position: fixed; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + background-color: rgba(0, 0, 0, 0.5); + display: flex; + justify-content: center; + align-items: center; + z-index: 10000; + animation: fadeIn 0.2s ease-in-out; +} + +.confirm-modal-content { + background-color: #fff; + border-radius: 8px; + padding: 24px; + max-width: 400px; + width: 90%; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); + animation: slideUp 0.2s ease-in-out; +} + +.confirm-modal-title { + margin-top: 0; + margin-bottom: 12px; + font-size: 1.2rem; + color: #333; +} + +.confirm-modal-message { + margin-bottom: 24px; + color: #555; + line-height: 1.5; +} + +.confirm-modal-actions { + display: flex; + justify-content: flex-end; + gap: 12px; +} + +.confirm-modal-cancel { + background-color: transparent; + border: 1px solid #ccc; + color: #555; + padding: 8px 16px; + border-radius: 4px; + cursor: pointer; + font-weight: 500; + transition: background-color 0.15s; +} + +.confirm-modal-cancel:hover { + background-color: #f5f5f5; +} + +.confirm-modal-confirm { + padding: 8px 16px; + border-radius: 4px; + border: none; + cursor: pointer; + font-weight: 500; + color: #fff; + transition: opacity 0.15s; +} + +.confirm-modal-confirm:hover { + opacity: 0.9; +} + +.confirm-modal-confirm.primary { + background-color: #007bff; +} + +.confirm-modal-confirm.destructive { + background-color: #dc3545; +} + +@keyframes fadeIn { + from { opacity: 0; } + to { opacity: 1; } +} + +@keyframes slideUp { + from { opacity: 0; transform: translateY(10px); } + to { opacity: 1; transform: translateY(0); } +} diff --git a/frontend/src/components/ConfirmModal.jsx b/frontend/src/components/ConfirmModal.jsx new file mode 100644 index 0000000..ec3b7a8 --- /dev/null +++ b/frontend/src/components/ConfirmModal.jsx @@ -0,0 +1,37 @@ +import React from "react"; +import "./ConfirmModal.css"; + +function ConfirmModal({ isOpen, title, message, confirmText, cancelText, onConfirm, onCancel, isDestructive }) { + if (!isOpen) return null; + + return ( +
+
e.stopPropagation()}> + {title &&

{title}

} + {message && ( +

+ {message.split('\n').map((line, i) => ( + + {line} +
+
+ ))} +

+ )} +
+ + +
+
+
+ ); +} + +export default ConfirmModal; diff --git a/frontend/src/pages/AdminDashboard.jsx b/frontend/src/pages/AdminDashboard.jsx index f36f73b..95adc02 100644 --- a/frontend/src/pages/AdminDashboard.jsx +++ b/frontend/src/pages/AdminDashboard.jsx @@ -2,9 +2,15 @@ import { useState, useEffect, useCallback } from 'react'; import { useAuth } from '../context/AuthContext'; import { useNavigate } from 'react-router-dom'; import DOMPurify from 'dompurify'; +import { useToast } from '../context/ToastContext'; +import ConfirmModal from '../components/ConfirmModal'; export default function AdminDashboard() { const { authFetch } = useAuth(); + const { showToast } = useToast(); + const [confirmConfig, setConfirmConfig] = useState({ + isOpen: false, title: "", message: "", confirmText: "OK", isDestructive: false, onConfirm: () => {} + }); const [stats, setStats] = useState({ total_users: 0, pending_personal: 0, pending_business: 0, admins: 0 }); const [users, setUsers] = useState([]); const [search, setSearch] = useState(""); @@ -41,27 +47,42 @@ export default function AdminDashboard() { const fetchAdminData = useCallback(async () => { setLoading(true); try { - const res = await authFetch(`/api/auth/admin/users?tax_year=${filterYear}`); + const [usersRes, statsRes] = await Promise.all([ + authFetch(`/api/auth/admin/users?tax_year=${filterYear}`), + authFetch(`/api/chatbot/admin-status?tax_year=${filterYear}`) + ]); - if (res.ok) { - const payload = await res.json(); - const usersArray = Array.isArray(payload) ? payload : (payload.users || []); - setUsers(usersArray); - - // Compute stats locally - const total = usersArray.length; - const pendingP = usersArray.reduce((acc, u) => acc + (u.pending_personal || 0), 0); - const pendingB = usersArray.reduce((acc, u) => acc + (u.pending_business || 0), 0); - const admins = usersArray.filter(u => u.role === "admin" || u.role === "super_admin").length; - - setStats({ total_users: total, pending_personal: pendingP, pending_business: pendingB, admins: admins }); + let newUsersArray = users; + let adminsCount = stats.admins; + + if (usersRes.ok) { + const payload = await usersRes.json(); + newUsersArray = Array.isArray(payload) ? payload : (payload.users || []); + setUsers(newUsersArray); + adminsCount = newUsersArray.filter(u => u.role === "admin" || u.role === "super_admin").length; + } + + if (statsRes.ok) { + const statsData = await statsRes.json(); + setStats({ + total_users: statsData.total_users, + pending_personal: statsData.pending_personal, + pending_business: statsData.pending_business, + admins: statsData.admin_accounts + }); + } else { + // Fallback to local computation if admin-status fails + const total = newUsersArray.length; + const pendingP = newUsersArray.reduce((acc, u) => acc + (u.pending_personal || 0), 0); + const pendingB = newUsersArray.reduce((acc, u) => acc + (u.pending_business || 0), 0); + setStats({ total_users: total, pending_personal: pendingP, pending_business: pendingB, admins: adminsCount }); } } catch (err) { console.error(err); } finally { setLoading(false); } - }, [authFetch]); + }, [authFetch, filterYear]); const loadTemplates = useCallback(async () => { setTplLoading(true); @@ -110,9 +131,10 @@ export default function AdminDashboard() { setTplFile(null); document.getElementById("tplFile").value = ""; loadTemplates(); + showToast("Template uploaded successfully", "success"); } else { const err = await res.json(); - alert(err.detail || "Upload failed"); + showToast(err.detail || "Upload failed", "error"); } } catch (err) { console.error("Upload error", err); @@ -120,17 +142,28 @@ export default function AdminDashboard() { }; const deleteTemplate = async (id) => { - if (!window.confirm("Are you sure you want to delete this template?")) return; - try { - const res = await authFetch(`/api/upload/admin/templates/${id}`, { method: "DELETE" }); - if (res.ok) { - loadTemplates(); - } else { - alert("Failed to delete template"); + setConfirmConfig({ + isOpen: true, + title: "Delete Template", + message: "Are you sure you want to delete this template?", + isDestructive: true, + confirmText: "Delete", + onConfirm: async () => { + setConfirmConfig(prev => ({ ...prev, isOpen: false })); + try { + const res = await authFetch(`/api/upload/admin/templates/${id}`, { method: "DELETE" }); + if (res.ok) { + loadTemplates(); + showToast("Template deleted", "success"); + } else { + showToast("Failed to delete template", "error"); + } + } catch (err) { + console.error("Delete error", err); + showToast("Network error", "error"); + } } - } catch (err) { - console.error("Delete error", err); - } + }); }; const currentYear = 2025; @@ -138,6 +171,7 @@ export default function AdminDashboard() { const filteredUsers = users.filter(u => { // Stat Card Filters + if (userFilter === 'admin' && u.role !== 'admin' && u.role !== 'super_admin') return false; if (userFilter === 'pending_personal' && !(u.pending_personal > 0)) return false; if (userFilter === 'pending_business' && !(u.pending_business > 0)) return false; @@ -160,6 +194,10 @@ export default function AdminDashboard() { return (
+ setConfirmConfig(prev => ({ ...prev, isOpen: false }))} + />

{stats.total_users}

Total Users
-
+
setUserFilter('admin')} style={{ cursor: 'pointer', border: userFilter === 'admin' ? '2px solid var(--green)' : 'none' }}>
security
{stats.admins}
Admin Accounts
diff --git a/frontend/src/pages/AdminUserDetail.jsx b/frontend/src/pages/AdminUserDetail.jsx index 9481b4d..8272a6a 100644 --- a/frontend/src/pages/AdminUserDetail.jsx +++ b/frontend/src/pages/AdminUserDetail.jsx @@ -3,6 +3,7 @@ import { useSearchParams, useNavigate } from 'react-router-dom'; import { useAuth } from '../context/AuthContext'; import { useToast } from '../context/ToastContext'; import ExpandableSummaryBlock from '../components/ExpandableSummaryBlock'; +import ConfirmModal from '../components/ConfirmModal'; export default function AdminUserDetail() { @@ -17,9 +18,20 @@ export default function AdminUserDetail() { const [showAiSummary, setShowAiSummary] = useState({}); const [activeTab, setActiveTab] = useState('personal'); const [taxYear, setTaxYear] = useState(""); + const [docSort, setDocSort] = useState("newest"); const [loading, setLoading] = useState(true); + // State for ConfirmModal + const [confirmConfig, setConfirmConfig] = useState({ + isOpen: false, + title: "", + message: "", + confirmText: "OK", + isDestructive: false, + onConfirm: () => {} + }); + // States for Review Emails const [personalTimeline, setPersonalTimeline] = useState(0); const [businessTimeline, setBusinessTimeline] = useState(0); @@ -140,37 +152,55 @@ export default function AdminUserDetail() { }, [documents, fetchUserDetails]); const deleteUser = async () => { - if (!window.confirm("WARNING: This will permanently delete this user, all their documents, and their audit history. Are you sure?")) return; - try { - const res = await authFetch(`/api/upload/admin/users/${userId}`, { method: "DELETE" }); - if (res.ok) { - navigate('/admin-dashboard'); - } else { - alert("Failed to delete user"); + setConfirmConfig({ + isOpen: true, + title: "Delete User", + message: "WARNING: This will permanently delete this user, all their documents, and their audit history. Are you sure?", + isDestructive: true, + confirmText: "Delete User", + onConfirm: async () => { + setConfirmConfig(prev => ({ ...prev, isOpen: false })); + try { + const res = await authFetch(`/api/upload/admin/users/${userId}`, { method: "DELETE" }); + if (res.ok) { + navigate('/admin-dashboard'); + } else { + showToast("Failed to delete user", "error"); + } + } catch (err) { console.error(err); + console.error("Error deleting user", err); + } } - } catch (err) { console.error(err); - console.error("Error deleting user", err); - } + }); }; const handleChangeRole = async (newRole) => { - if (!window.confirm(`Change user role to ${newRole}?`)) return; - try { - const res = await authFetch(`/api/auth/admin/users/${userId}/role`, { - method: 'PATCH', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ role: newRole }) - }); - if (res.ok) { - showToast("Role updated successfully", "success"); - fetchUserDetails(); - } else { - const data = await res.json(); - showToast(data.detail || "Failed to change role", "error"); + setConfirmConfig({ + isOpen: true, + title: "Change Role", + message: `Change user role to ${newRole}?`, + isDestructive: false, + confirmText: "Confirm", + onConfirm: async () => { + setConfirmConfig(prev => ({ ...prev, isOpen: false })); + try { + const res = await authFetch(`/api/auth/admin/users/${userId}/role`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ role: newRole }) + }); + if (res.ok) { + showToast("Role updated successfully", "success"); + fetchUserDetails(); + } else { + const data = await res.json(); + showToast(data.detail || "Failed to change role", "error"); + } + } catch (err) { console.error(err); + showToast("Network error", "error"); + } } - } catch (err) { console.error(err); - showToast("Network error", "error"); - } + }); }; const handleDocApprove = async (docId, type, isApproved, note = '') => { @@ -199,16 +229,25 @@ export default function AdminUserDetail() { const deleteAdminDoc = async (docId) => { - if (!window.confirm("Delete this admin document?")) return; - try { - const res = await authFetch(`/api/upload/admin-documents/${docId}`, { method: "DELETE" }); - if (res.ok) { - showToast("Document deleted", "success"); - fetchUserDetails(); + setConfirmConfig({ + isOpen: true, + title: "Delete Document", + message: "Delete this admin document?", + isDestructive: true, + confirmText: "Delete", + onConfirm: async () => { + setConfirmConfig(prev => ({ ...prev, isOpen: false })); + try { + const res = await authFetch(`/api/upload/admin-documents/${docId}`, { method: "DELETE" }); + if (res.ok) { + showToast("Document deleted", "success"); + fetchUserDetails(); + } + } catch(err) { + console.error(err); + } } - } catch(err) { - console.error(err); - } + }); }; const sendReturnForApproval = async (docId, note = "") => { @@ -236,27 +275,36 @@ export default function AdminUserDetail() { const markFiled = async () => { const yearForFiling = taxYear || 2025; - if (!window.confirm(`Mark all approved docs for ${yearForFiling} as FILED? This will send a confirmation email to the client.`)) return; - setMarkFiledLoading(true); - try { - const res = await authFetch("/api/review/mark-filed", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ user_id: parseInt(userId), tax_year: parseInt(yearForFiling) }) - }); - if (res.ok) { - const data = await res.json(); - showToast(`Filed: ${data.personal_filed} personal + ${data.business_filed} business docs`, "success"); - fetchUserDetails(); - } else { - const data = await res.json().catch(() => ({})); - showToast(data.detail || "Mark filed failed", "error"); + setConfirmConfig({ + isOpen: true, + title: "Mark as Filed", + message: `Mark all approved docs for ${yearForFiling} as FILED?\nThis will send a confirmation email to the client.`, + isDestructive: false, + confirmText: "Mark as Filed", + onConfirm: async () => { + setConfirmConfig(prev => ({ ...prev, isOpen: false })); + setMarkFiledLoading(true); + try { + const res = await authFetch("/api/review/mark-filed", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ user_id: parseInt(userId), tax_year: parseInt(yearForFiling) }) + }); + if (res.ok) { + const data = await res.json(); + showToast(`Filed: ${data.personal_filed} personal + ${data.business_filed} business docs`, "success"); + fetchUserDetails(); + } else { + const data = await res.json().catch(() => ({})); + showToast(data.detail || "Mark filed failed", "error"); + } + } catch (err) { console.error(err); + showToast("Network error", "error"); + } finally { + setMarkFiledLoading(false); + } } - } catch (err) { console.error(err); - showToast("Network error", "error"); - } finally { - setMarkFiledLoading(false); - } + }); }; const uploadAdminDoc = async (file) => { @@ -352,21 +400,30 @@ export default function AdminUserDetail() { }; const submitAllDocs = async () => { - if (!window.confirm("Submit all documents for review?\nAn email will be sent to the user.")) return; - try { - const res = await authFetch("/api/review/submit", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ user_id: userId }) - }); - if (res.ok) { - showToast("Documents submitted — email sent to user.", "success"); - } else { - showToast("Failed to submit", "error"); + setConfirmConfig({ + isOpen: true, + title: "Submit for Review", + message: "Submit all documents for review?\nAn email will be sent to the user.", + isDestructive: false, + confirmText: "Submit", + onConfirm: async () => { + setConfirmConfig(prev => ({ ...prev, isOpen: false })); + try { + const res = await authFetch("/api/review/submit", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ user_id: userId }) + }); + if (res.ok) { + showToast("Documents submitted — email sent to user.", "success"); + } else { + showToast("Failed to submit", "error"); + } + } catch (err) { console.error(err); + showToast("Error submitting documents", "error"); + } } - } catch (err) { console.error(err); - showToast("Error submitting documents", "error"); - } + }); }; if (loading && !userDetail) { @@ -408,12 +465,27 @@ export default function AdminUserDetail() { const currentYear = new Date().getFullYear(); const yearOptions = [currentYear - 1, currentYear, currentYear + 1]; - const personalDocs = documents.filter(d => d.type === "personal"); - const businessDocs = documents.filter(d => d.type === "business"); - const returnDocs = documents.filter(d => d.type === "admin"); + const sortDocs = (docsArray) => [...docsArray].sort((a, b) => { + const nameA = a.doc_type || a.doc_label || a.filename || ''; + const nameB = b.doc_type || b.doc_label || b.filename || ''; + if (docSort === 'asc') return nameA.localeCompare(nameB); + if (docSort === 'desc') return nameB.localeCompare(nameA); + if (docSort === 'newest') return new Date(b.uploaded_at || 0) - new Date(a.uploaded_at || 0); + if (docSort === 'oldest') return new Date(a.uploaded_at || 0) - new Date(b.uploaded_at || 0); + return 0; + }); + + const personalDocs = sortDocs(documents.filter(d => d.type === "personal")); + const businessDocs = sortDocs(documents.filter(d => d.type === "business")); + const returnDocs = sortDocs(documents.filter(d => d.type === "admin")); return (
+ setConfirmConfig(prev => ({ ...prev, isOpen: false }))} + /> +
+
+ + +