Fix UI bugs
This commit is contained in:
@@ -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
|
|
||||||
@@ -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
|
|
||||||
Binary file not shown.
@@ -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); }
|
||||||
|
}
|
||||||
@@ -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 (
|
||||||
|
<div className="confirm-modal-overlay" onClick={onCancel}>
|
||||||
|
<div className="confirm-modal-content" onClick={e => e.stopPropagation()}>
|
||||||
|
{title && <h3 className="confirm-modal-title">{title}</h3>}
|
||||||
|
{message && (
|
||||||
|
<p className="confirm-modal-message">
|
||||||
|
{message.split('\n').map((line, i) => (
|
||||||
|
<React.Fragment key={i}>
|
||||||
|
{line}
|
||||||
|
<br />
|
||||||
|
</React.Fragment>
|
||||||
|
))}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<div className="confirm-modal-actions">
|
||||||
|
<button className="confirm-modal-cancel" onClick={onCancel}>
|
||||||
|
{cancelText || "Cancel"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className={`confirm-modal-confirm ${isDestructive ? 'destructive' : 'primary'}`}
|
||||||
|
onClick={onConfirm}
|
||||||
|
>
|
||||||
|
{confirmText || "OK"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ConfirmModal;
|
||||||
@@ -2,9 +2,15 @@ import { useState, useEffect, useCallback } from 'react';
|
|||||||
import { useAuth } from '../context/AuthContext';
|
import { useAuth } from '../context/AuthContext';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import DOMPurify from 'dompurify';
|
import DOMPurify from 'dompurify';
|
||||||
|
import { useToast } from '../context/ToastContext';
|
||||||
|
import ConfirmModal from '../components/ConfirmModal';
|
||||||
|
|
||||||
export default function AdminDashboard() {
|
export default function AdminDashboard() {
|
||||||
const { authFetch } = useAuth();
|
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 [stats, setStats] = useState({ total_users: 0, pending_personal: 0, pending_business: 0, admins: 0 });
|
||||||
const [users, setUsers] = useState([]);
|
const [users, setUsers] = useState([]);
|
||||||
const [search, setSearch] = useState("");
|
const [search, setSearch] = useState("");
|
||||||
@@ -41,27 +47,42 @@ export default function AdminDashboard() {
|
|||||||
const fetchAdminData = useCallback(async () => {
|
const fetchAdminData = useCallback(async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
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) {
|
let newUsersArray = users;
|
||||||
const payload = await res.json();
|
let adminsCount = stats.admins;
|
||||||
const usersArray = Array.isArray(payload) ? payload : (payload.users || []);
|
|
||||||
setUsers(usersArray);
|
if (usersRes.ok) {
|
||||||
|
const payload = await usersRes.json();
|
||||||
// Compute stats locally
|
newUsersArray = Array.isArray(payload) ? payload : (payload.users || []);
|
||||||
const total = usersArray.length;
|
setUsers(newUsersArray);
|
||||||
const pendingP = usersArray.reduce((acc, u) => acc + (u.pending_personal || 0), 0);
|
adminsCount = newUsersArray.filter(u => u.role === "admin" || u.role === "super_admin").length;
|
||||||
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;
|
|
||||||
|
if (statsRes.ok) {
|
||||||
setStats({ total_users: total, pending_personal: pendingP, pending_business: pendingB, admins: admins });
|
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) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}, [authFetch]);
|
}, [authFetch, filterYear]);
|
||||||
|
|
||||||
const loadTemplates = useCallback(async () => {
|
const loadTemplates = useCallback(async () => {
|
||||||
setTplLoading(true);
|
setTplLoading(true);
|
||||||
@@ -110,9 +131,10 @@ export default function AdminDashboard() {
|
|||||||
setTplFile(null);
|
setTplFile(null);
|
||||||
document.getElementById("tplFile").value = "";
|
document.getElementById("tplFile").value = "";
|
||||||
loadTemplates();
|
loadTemplates();
|
||||||
|
showToast("Template uploaded successfully", "success");
|
||||||
} else {
|
} else {
|
||||||
const err = await res.json();
|
const err = await res.json();
|
||||||
alert(err.detail || "Upload failed");
|
showToast(err.detail || "Upload failed", "error");
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Upload error", err);
|
console.error("Upload error", err);
|
||||||
@@ -120,17 +142,28 @@ export default function AdminDashboard() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const deleteTemplate = async (id) => {
|
const deleteTemplate = async (id) => {
|
||||||
if (!window.confirm("Are you sure you want to delete this template?")) return;
|
setConfirmConfig({
|
||||||
try {
|
isOpen: true,
|
||||||
const res = await authFetch(`/api/upload/admin/templates/${id}`, { method: "DELETE" });
|
title: "Delete Template",
|
||||||
if (res.ok) {
|
message: "Are you sure you want to delete this template?",
|
||||||
loadTemplates();
|
isDestructive: true,
|
||||||
} else {
|
confirmText: "Delete",
|
||||||
alert("Failed to delete template");
|
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;
|
const currentYear = 2025;
|
||||||
@@ -138,6 +171,7 @@ export default function AdminDashboard() {
|
|||||||
|
|
||||||
const filteredUsers = users.filter(u => {
|
const filteredUsers = users.filter(u => {
|
||||||
// Stat Card Filters
|
// 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_personal' && !(u.pending_personal > 0)) return false;
|
||||||
if (userFilter === 'pending_business' && !(u.pending_business > 0)) return false;
|
if (userFilter === 'pending_business' && !(u.pending_business > 0)) return false;
|
||||||
|
|
||||||
@@ -160,6 +194,10 @@ export default function AdminDashboard() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="">
|
<div className="">
|
||||||
|
<ConfirmModal
|
||||||
|
{...confirmConfig}
|
||||||
|
onCancel={() => setConfirmConfig(prev => ({ ...prev, isOpen: false }))}
|
||||||
|
/>
|
||||||
<h1 style={{
|
<h1 style={{
|
||||||
margin: '0 0 32px 0',
|
margin: '0 0 32px 0',
|
||||||
fontSize: '42px',
|
fontSize: '42px',
|
||||||
@@ -250,7 +288,7 @@ export default function AdminDashboard() {
|
|||||||
<div className="stat-value">{stats.total_users}</div>
|
<div className="stat-value">{stats.total_users}</div>
|
||||||
<div className="stat-label">Total Users</div>
|
<div className="stat-label">Total Users</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="stat-card accent-green">
|
<div className={`stat-card accent-green ${userFilter === 'admin' ? 'active-filter' : ''}`} onClick={() => setUserFilter('admin')} style={{ cursor: 'pointer', border: userFilter === 'admin' ? '2px solid var(--green)' : 'none' }}>
|
||||||
<div className="stat-icon"><span className="material-symbols-outlined">security</span></div>
|
<div className="stat-icon"><span className="material-symbols-outlined">security</span></div>
|
||||||
<div className="stat-value">{stats.admins}</div>
|
<div className="stat-value">{stats.admins}</div>
|
||||||
<div className="stat-label">Admin Accounts</div>
|
<div className="stat-label">Admin Accounts</div>
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { useSearchParams, useNavigate } from 'react-router-dom';
|
|||||||
import { useAuth } from '../context/AuthContext';
|
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';
|
||||||
|
import ConfirmModal from '../components/ConfirmModal';
|
||||||
|
|
||||||
|
|
||||||
export default function AdminUserDetail() {
|
export default function AdminUserDetail() {
|
||||||
@@ -17,9 +18,20 @@ export default function AdminUserDetail() {
|
|||||||
const [showAiSummary, setShowAiSummary] = useState({});
|
const [showAiSummary, setShowAiSummary] = useState({});
|
||||||
const [activeTab, setActiveTab] = useState('personal');
|
const [activeTab, setActiveTab] = useState('personal');
|
||||||
const [taxYear, setTaxYear] = useState("");
|
const [taxYear, setTaxYear] = useState("");
|
||||||
|
const [docSort, setDocSort] = useState("newest");
|
||||||
const [loading, setLoading] = useState(true);
|
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
|
// States for Review Emails
|
||||||
const [personalTimeline, setPersonalTimeline] = useState(0);
|
const [personalTimeline, setPersonalTimeline] = useState(0);
|
||||||
const [businessTimeline, setBusinessTimeline] = useState(0);
|
const [businessTimeline, setBusinessTimeline] = useState(0);
|
||||||
@@ -140,37 +152,55 @@ export default function AdminUserDetail() {
|
|||||||
}, [documents, fetchUserDetails]);
|
}, [documents, fetchUserDetails]);
|
||||||
|
|
||||||
const deleteUser = async () => {
|
const deleteUser = async () => {
|
||||||
if (!window.confirm("WARNING: This will permanently delete this user, all their documents, and their audit history. Are you sure?")) return;
|
setConfirmConfig({
|
||||||
try {
|
isOpen: true,
|
||||||
const res = await authFetch(`/api/upload/admin/users/${userId}`, { method: "DELETE" });
|
title: "Delete User",
|
||||||
if (res.ok) {
|
message: "WARNING: This will permanently delete this user, all their documents, and their audit history. Are you sure?",
|
||||||
navigate('/admin-dashboard');
|
isDestructive: true,
|
||||||
} else {
|
confirmText: "Delete User",
|
||||||
alert("Failed to 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) => {
|
const handleChangeRole = async (newRole) => {
|
||||||
if (!window.confirm(`Change user role to ${newRole}?`)) return;
|
setConfirmConfig({
|
||||||
try {
|
isOpen: true,
|
||||||
const res = await authFetch(`/api/auth/admin/users/${userId}/role`, {
|
title: "Change Role",
|
||||||
method: 'PATCH',
|
message: `Change user role to ${newRole}?`,
|
||||||
headers: { 'Content-Type': 'application/json' },
|
isDestructive: false,
|
||||||
body: JSON.stringify({ role: newRole })
|
confirmText: "Confirm",
|
||||||
});
|
onConfirm: async () => {
|
||||||
if (res.ok) {
|
setConfirmConfig(prev => ({ ...prev, isOpen: false }));
|
||||||
showToast("Role updated successfully", "success");
|
try {
|
||||||
fetchUserDetails();
|
const res = await authFetch(`/api/auth/admin/users/${userId}/role`, {
|
||||||
} else {
|
method: 'PATCH',
|
||||||
const data = await res.json();
|
headers: { 'Content-Type': 'application/json' },
|
||||||
showToast(data.detail || "Failed to change role", "error");
|
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 = '') => {
|
const handleDocApprove = async (docId, type, isApproved, note = '') => {
|
||||||
@@ -199,16 +229,25 @@ export default function AdminUserDetail() {
|
|||||||
|
|
||||||
|
|
||||||
const deleteAdminDoc = async (docId) => {
|
const deleteAdminDoc = async (docId) => {
|
||||||
if (!window.confirm("Delete this admin document?")) return;
|
setConfirmConfig({
|
||||||
try {
|
isOpen: true,
|
||||||
const res = await authFetch(`/api/upload/admin-documents/${docId}`, { method: "DELETE" });
|
title: "Delete Document",
|
||||||
if (res.ok) {
|
message: "Delete this admin document?",
|
||||||
showToast("Document deleted", "success");
|
isDestructive: true,
|
||||||
fetchUserDetails();
|
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 = "") => {
|
const sendReturnForApproval = async (docId, note = "") => {
|
||||||
@@ -236,27 +275,36 @@ export default function AdminUserDetail() {
|
|||||||
|
|
||||||
const markFiled = async () => {
|
const markFiled = async () => {
|
||||||
const yearForFiling = taxYear || 2025;
|
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;
|
setConfirmConfig({
|
||||||
setMarkFiledLoading(true);
|
isOpen: true,
|
||||||
try {
|
title: "Mark as Filed",
|
||||||
const res = await authFetch("/api/review/mark-filed", {
|
message: `Mark all approved docs for ${yearForFiling} as FILED?\nThis will send a confirmation email to the client.`,
|
||||||
method: "POST",
|
isDestructive: false,
|
||||||
headers: { "Content-Type": "application/json" },
|
confirmText: "Mark as Filed",
|
||||||
body: JSON.stringify({ user_id: parseInt(userId), tax_year: parseInt(yearForFiling) })
|
onConfirm: async () => {
|
||||||
});
|
setConfirmConfig(prev => ({ ...prev, isOpen: false }));
|
||||||
if (res.ok) {
|
setMarkFiledLoading(true);
|
||||||
const data = await res.json();
|
try {
|
||||||
showToast(`Filed: ${data.personal_filed} personal + ${data.business_filed} business docs`, "success");
|
const res = await authFetch("/api/review/mark-filed", {
|
||||||
fetchUserDetails();
|
method: "POST",
|
||||||
} else {
|
headers: { "Content-Type": "application/json" },
|
||||||
const data = await res.json().catch(() => ({}));
|
body: JSON.stringify({ user_id: parseInt(userId), tax_year: parseInt(yearForFiling) })
|
||||||
showToast(data.detail || "Mark filed failed", "error");
|
});
|
||||||
|
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) => {
|
const uploadAdminDoc = async (file) => {
|
||||||
@@ -352,21 +400,30 @@ export default function AdminUserDetail() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const submitAllDocs = async () => {
|
const submitAllDocs = async () => {
|
||||||
if (!window.confirm("Submit all documents for review?\nAn email will be sent to the user.")) return;
|
setConfirmConfig({
|
||||||
try {
|
isOpen: true,
|
||||||
const res = await authFetch("/api/review/submit", {
|
title: "Submit for Review",
|
||||||
method: "POST",
|
message: "Submit all documents for review?\nAn email will be sent to the user.",
|
||||||
headers: { "Content-Type": "application/json" },
|
isDestructive: false,
|
||||||
body: JSON.stringify({ user_id: userId })
|
confirmText: "Submit",
|
||||||
});
|
onConfirm: async () => {
|
||||||
if (res.ok) {
|
setConfirmConfig(prev => ({ ...prev, isOpen: false }));
|
||||||
showToast("Documents submitted — email sent to user.", "success");
|
try {
|
||||||
} else {
|
const res = await authFetch("/api/review/submit", {
|
||||||
showToast("Failed to submit", "error");
|
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) {
|
if (loading && !userDetail) {
|
||||||
@@ -408,12 +465,27 @@ export default function AdminUserDetail() {
|
|||||||
const currentYear = new Date().getFullYear();
|
const currentYear = new Date().getFullYear();
|
||||||
const yearOptions = [currentYear - 1, currentYear, currentYear + 1];
|
const yearOptions = [currentYear - 1, currentYear, currentYear + 1];
|
||||||
|
|
||||||
const personalDocs = documents.filter(d => d.type === "personal");
|
const sortDocs = (docsArray) => [...docsArray].sort((a, b) => {
|
||||||
const businessDocs = documents.filter(d => d.type === "business");
|
const nameA = a.doc_type || a.doc_label || a.filename || '';
|
||||||
const returnDocs = documents.filter(d => d.type === "admin");
|
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 (
|
return (
|
||||||
<div className="">
|
<div className="">
|
||||||
|
<ConfirmModal
|
||||||
|
{...confirmConfig}
|
||||||
|
onCancel={() => setConfirmConfig(prev => ({ ...prev, isOpen: false }))}
|
||||||
|
/>
|
||||||
|
|
||||||
<button className="btn btn-secondary btn-sm" style={{ marginBottom: '16px', display: 'inline-flex', alignItems: 'center', gap: '4px', borderRadius: 'var(--radius-sm)' }} onClick={() => navigate('/admin-dashboard')}>
|
<button className="btn btn-secondary btn-sm" style={{ marginBottom: '16px', display: 'inline-flex', alignItems: 'center', gap: '4px', borderRadius: 'var(--radius-sm)' }} onClick={() => navigate('/admin-dashboard')}>
|
||||||
<span className="material-symbols-outlined" style={{ fontSize: '18px' }}>arrow_back</span>
|
<span className="material-symbols-outlined" style={{ fontSize: '18px' }}>arrow_back</span>
|
||||||
Back to Dashboard
|
Back to Dashboard
|
||||||
@@ -476,6 +548,15 @@ export default function AdminUserDetail() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="aud-bar-actions">
|
<div className="aud-bar-actions">
|
||||||
<button className="btn btn-primary btn-sm" onClick={submitAllDocs} style={{borderRadius:'var(--radius-sm)'}}>Trigger Submit Review</button>
|
<button className="btn btn-primary btn-sm" onClick={submitAllDocs} style={{borderRadius:'var(--radius-sm)'}}>Trigger Submit Review</button>
|
||||||
|
<div className="aud-year-picker" style={{marginLeft: 'auto'}}>
|
||||||
|
<label className="form-label" style={{margin:0, fontSize: '11px'}}>Sort</label>
|
||||||
|
<select className="select-input" style={{width: 'auto', padding: '6px 12px', fontSize: '13px'}} value={docSort} onChange={(e) => setDocSort(e.target.value)}>
|
||||||
|
<option value="newest">Newest First</option>
|
||||||
|
<option value="oldest">Oldest First</option>
|
||||||
|
<option value="asc">Name (A-Z)</option>
|
||||||
|
<option value="desc">Name (Z-A)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
<div className="aud-year-picker">
|
<div className="aud-year-picker">
|
||||||
<label className="form-label" style={{margin:0, fontSize: '11px'}}>Tax Year</label>
|
<label className="form-label" style={{margin:0, fontSize: '11px'}}>Tax Year</label>
|
||||||
<select className="select-input" style={{width: 'auto', padding: '6px 12px', fontSize: '13px'}} value={taxYear} onChange={(e) => setTaxYear(e.target.value)}>
|
<select className="select-input" style={{width: 'auto', padding: '6px 12px', fontSize: '13px'}} value={taxYear} onChange={(e) => setTaxYear(e.target.value)}>
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
|
import { useToast } from '../context/ToastContext';
|
||||||
|
|
||||||
export default function Contact() {
|
export default function Contact() {
|
||||||
|
const { showToast } = useToast();
|
||||||
const [formData, setFormData] = useState({
|
const [formData, setFormData] = useState({
|
||||||
first_name: '',
|
first_name: '',
|
||||||
last_name: '',
|
last_name: '',
|
||||||
@@ -21,7 +23,7 @@ export default function Contact() {
|
|||||||
body: JSON.stringify(formData)
|
body: JSON.stringify(formData)
|
||||||
});
|
});
|
||||||
if (!res.ok) throw new Error("Failed to send");
|
if (!res.ok) throw new Error("Failed to send");
|
||||||
alert("Message sent! Thank you for contacting us.");
|
showToast("Message sent! Thank you for contacting us.", "success");
|
||||||
setFormData({
|
setFormData({
|
||||||
first_name: '',
|
first_name: '',
|
||||||
last_name: '',
|
last_name: '',
|
||||||
@@ -30,7 +32,7 @@ export default function Contact() {
|
|||||||
message: ''
|
message: ''
|
||||||
});
|
});
|
||||||
} catch (err) { console.error(err);
|
} catch (err) { console.error(err);
|
||||||
alert("Failed to send message");
|
showToast("Failed to send message", "error");
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { useAuth } from '../context/AuthContext';
|
import { useAuth } from '../context/AuthContext';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import { useToast } from '../context/ToastContext';
|
||||||
|
|
||||||
export default function Profile() {
|
export default function Profile() {
|
||||||
const { user, authFetch } = useAuth();
|
const { user, authFetch } = useAuth();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
const { showToast } = useToast();
|
||||||
const [formData, setFormData] = useState({ name: '', phone: '' });
|
const [formData, setFormData] = useState({ name: '', phone: '' });
|
||||||
const [pwData, setPwData] = useState({ currentPw: '', newPw: '', confirmPw: '' });
|
const [pwData, setPwData] = useState({ currentPw: '', newPw: '', confirmPw: '' });
|
||||||
const [showPwSection, setShowPwSection] = useState(false);
|
const [showPwSection, setShowPwSection] = useState(false);
|
||||||
@@ -23,7 +25,7 @@ export default function Profile() {
|
|||||||
const payload = { ...formData };
|
const payload = { ...formData };
|
||||||
if (showPwSection && pwData.newPw) {
|
if (showPwSection && pwData.newPw) {
|
||||||
if (pwData.newPw !== pwData.confirmPw) {
|
if (pwData.newPw !== pwData.confirmPw) {
|
||||||
alert("New passwords do not match");
|
showToast("New passwords do not match", "error");
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -52,12 +54,12 @@ export default function Profile() {
|
|||||||
throw new Error(errorMsg);
|
throw new Error(errorMsg);
|
||||||
}
|
}
|
||||||
|
|
||||||
alert("Profile updated successfully. Please log in again if you changed your password.");
|
showToast("Profile updated successfully. Please log in again if you changed your password.", "success");
|
||||||
if (payload.new_password) {
|
if (payload.new_password) {
|
||||||
window.location.href = '/login';
|
window.location.href = '/login';
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert(err.message);
|
showToast(err.message, "error");
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,14 @@ import { useEffect, useState, useRef, useCallback } from 'react';
|
|||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom';
|
||||||
import { useAuth } from '../context/AuthContext';
|
import { useAuth } from '../context/AuthContext';
|
||||||
import { useToast } from '../context/ToastContext';
|
import { useToast } from '../context/ToastContext';
|
||||||
|
import ConfirmModal from '../components/ConfirmModal';
|
||||||
|
|
||||||
export default function UploadBusiness() {
|
export default function UploadBusiness() {
|
||||||
const { authFetch } = useAuth();
|
const { authFetch } = useAuth();
|
||||||
const { showToast } = useToast();
|
const { showToast } = useToast();
|
||||||
|
const [confirmConfig, setConfirmConfig] = useState({
|
||||||
|
isOpen: false, title: "", message: "", confirmText: "OK", isDestructive: false, onConfirm: () => {}
|
||||||
|
});
|
||||||
const [taxYear, setTaxYear] = useState(2025);
|
const [taxYear, setTaxYear] = useState(2025);
|
||||||
const [docs, setDocs] = useState([]);
|
const [docs, setDocs] = useState([]);
|
||||||
const [templates, setTemplates] = useState([]);
|
const [templates, setTemplates] = useState([]);
|
||||||
@@ -63,18 +67,27 @@ export default function UploadBusiness() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const deleteDoc = async (id) => {
|
const deleteDoc = async (id) => {
|
||||||
if (!window.confirm("Delete this document?\nThis action cannot be undone.")) return;
|
setConfirmConfig({
|
||||||
try {
|
isOpen: true,
|
||||||
const res = await authFetch(`/api/upload/business-documents/${id}`, { method: "DELETE" });
|
title: "Delete Document",
|
||||||
if (res.ok) {
|
message: "Delete this document?\nThis action cannot be undone.",
|
||||||
showToast("Document deleted", "success");
|
isDestructive: true,
|
||||||
fetchTemplatesAndDocs();
|
confirmText: "Delete",
|
||||||
} else {
|
onConfirm: async () => {
|
||||||
showToast("Delete failed", "error");
|
setConfirmConfig(prev => ({ ...prev, isOpen: false }));
|
||||||
|
try {
|
||||||
|
const res = await authFetch(`/api/upload/business-documents/${id}`, { method: "DELETE" });
|
||||||
|
if (res.ok) {
|
||||||
|
showToast("Document deleted", "success");
|
||||||
|
fetchTemplatesAndDocs();
|
||||||
|
} else {
|
||||||
|
showToast("Delete failed", "error");
|
||||||
|
}
|
||||||
|
} catch (err) { console.error(err);
|
||||||
|
showToast("Delete failed", "error");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (err) { console.error(err);
|
});
|
||||||
showToast("Delete failed", "error");
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const viewDoc = async (storageKey) => {
|
const viewDoc = async (storageKey) => {
|
||||||
@@ -132,6 +145,10 @@ export default function UploadBusiness() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
|
<ConfirmModal
|
||||||
|
{...confirmConfig}
|
||||||
|
onCancel={() => setConfirmConfig(prev => ({ ...prev, isOpen: false }))}
|
||||||
|
/>
|
||||||
<div style={{marginBottom: '16px'}}>
|
<div style={{marginBottom: '16px'}}>
|
||||||
<Link to="/dashboard" className="fancy-link" style={{fontSize: '14px', fontWeight: 500}}>← Back to Dashboard</Link>
|
<Link to="/dashboard" className="fancy-link" style={{fontSize: '14px', fontWeight: 500}}>← Back to Dashboard</Link>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -2,10 +2,14 @@ import { useEffect, useState, useRef, useCallback } from 'react';
|
|||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom';
|
||||||
import { useAuth } from '../context/AuthContext';
|
import { useAuth } from '../context/AuthContext';
|
||||||
import { useToast } from '../context/ToastContext';
|
import { useToast } from '../context/ToastContext';
|
||||||
|
import ConfirmModal from '../components/ConfirmModal';
|
||||||
|
|
||||||
export default function UploadPersonal() {
|
export default function UploadPersonal() {
|
||||||
const { authFetch } = useAuth();
|
const { authFetch } = useAuth();
|
||||||
const { showToast } = useToast();
|
const { showToast } = useToast();
|
||||||
|
const [confirmConfig, setConfirmConfig] = useState({
|
||||||
|
isOpen: false, title: "", message: "", confirmText: "OK", isDestructive: false, onConfirm: () => {}
|
||||||
|
});
|
||||||
const [taxYear, setTaxYear] = useState(2025);
|
const [taxYear, setTaxYear] = useState(2025);
|
||||||
const [docs, setDocs] = useState([]);
|
const [docs, setDocs] = useState([]);
|
||||||
const [templates, setTemplates] = useState([]);
|
const [templates, setTemplates] = useState([]);
|
||||||
@@ -65,18 +69,27 @@ export default function UploadPersonal() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const deleteDoc = async (id) => {
|
const deleteDoc = async (id) => {
|
||||||
if (!window.confirm("Delete this document?\nThis action cannot be undone.")) return;
|
setConfirmConfig({
|
||||||
try {
|
isOpen: true,
|
||||||
const res = await authFetch(`/api/upload/personal-documents/${id}`, { method: "DELETE" });
|
title: "Delete Document",
|
||||||
if (res.ok) {
|
message: "Delete this document?\nThis action cannot be undone.",
|
||||||
showToast("Document deleted", "success");
|
isDestructive: true,
|
||||||
fetchTemplatesAndDocs();
|
confirmText: "Delete",
|
||||||
} else {
|
onConfirm: async () => {
|
||||||
showToast("Delete failed", "error");
|
setConfirmConfig(prev => ({ ...prev, isOpen: false }));
|
||||||
|
try {
|
||||||
|
const res = await authFetch(`/api/upload/personal-documents/${id}`, { method: "DELETE" });
|
||||||
|
if (res.ok) {
|
||||||
|
showToast("Document deleted", "success");
|
||||||
|
fetchTemplatesAndDocs();
|
||||||
|
} else {
|
||||||
|
showToast("Delete failed", "error");
|
||||||
|
}
|
||||||
|
} catch (err) { console.error(err);
|
||||||
|
showToast("Delete failed", "error");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (err) { console.error(err);
|
});
|
||||||
showToast("Delete failed", "error");
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const viewDoc = async (storageKey) => {
|
const viewDoc = async (storageKey) => {
|
||||||
@@ -134,6 +147,10 @@ export default function UploadPersonal() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
|
<ConfirmModal
|
||||||
|
{...confirmConfig}
|
||||||
|
onCancel={() => setConfirmConfig(prev => ({ ...prev, isOpen: false }))}
|
||||||
|
/>
|
||||||
<div style={{marginBottom: '16px'}}>
|
<div style={{marginBottom: '16px'}}>
|
||||||
<Link to="/dashboard" className="fancy-link" style={{fontSize: '14px', fontWeight: 500}}>← Back to Dashboard</Link>
|
<Link to="/dashboard" className="fancy-link" style={{fontSize: '14px', fontWeight: 500}}>← Back to Dashboard</Link>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -225,7 +225,8 @@ def assert_admin_can_access(current_user, target_user):
|
|||||||
if current_user.role not in [UserRole.admin, UserRole.super_admin]:
|
if current_user.role not in [UserRole.admin, UserRole.super_admin]:
|
||||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin access required")
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin access required")
|
||||||
|
|
||||||
if target_user.role != UserRole.user:
|
# Admins can only view 'user' accounts. Super admins can view any account.
|
||||||
|
if current_user.role != UserRole.super_admin and target_user.role != UserRole.user:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_403_FORBIDDEN,
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
detail="Admins can only interact with regular user accounts"
|
detail="Admins can only interact with regular user accounts"
|
||||||
|
|||||||
@@ -99,6 +99,7 @@ def _summarize_extracted(extracted_data: dict | None) -> str:
|
|||||||
# ─────────────────────────────────────────────────────────────────────────────
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
@router.get("/admin-status")
|
@router.get("/admin-status")
|
||||||
def get_admin_status(
|
def get_admin_status(
|
||||||
|
tax_year: int | None = Query(None),
|
||||||
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),
|
||||||
@@ -106,16 +107,18 @@ def get_admin_status(
|
|||||||
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 = (
|
|
||||||
db.query(PersonalDocument)
|
pq = db.query(PersonalDocument).filter(PersonalDocument.review_status == "pending", PersonalDocument.deleted_at == None)
|
||||||
.filter(PersonalDocument.review_status == "pending", PersonalDocument.deleted_at == None)
|
if tax_year:
|
||||||
.count()
|
pq = pq.filter(PersonalDocument.tax_year == tax_year)
|
||||||
)
|
pending_personal = pq.count()
|
||||||
pending_business = (
|
|
||||||
db.query(BusinessDocument)
|
admin_accounts = db.query(User).filter(User.role.in_(["admin", "super_admin"])).count()
|
||||||
.filter(BusinessDocument.review_status == "pending", BusinessDocument.deleted_at == None)
|
|
||||||
.count()
|
bq = db.query(BusinessDocument).filter(BusinessDocument.review_status == "pending", BusinessDocument.deleted_at == None)
|
||||||
)
|
if tax_year:
|
||||||
|
bq = bq.filter(BusinessDocument.tax_year == tax_year)
|
||||||
|
pending_business = bq.count()
|
||||||
|
|
||||||
recent_personal = (
|
recent_personal = (
|
||||||
db.query(PersonalDocument).filter(PersonalDocument.deleted_at == None)
|
db.query(PersonalDocument).filter(PersonalDocument.deleted_at == None)
|
||||||
@@ -158,6 +161,7 @@ def get_admin_status(
|
|||||||
"total_pending": total_pending,
|
"total_pending": total_pending,
|
||||||
"recent_uploads": recent_uploads,
|
"recent_uploads": recent_uploads,
|
||||||
"message": message,
|
"message": message,
|
||||||
|
"admin_accounts": admin_accounts,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -218,7 +218,7 @@ def get_document_review_history(
|
|||||||
"actor_role": e.actor_role,
|
"actor_role": e.actor_role,
|
||||||
"action": e.action,
|
"action": e.action,
|
||||||
"to_status": e.to_status,
|
"to_status": e.to_status,
|
||||||
"note": e.note,
|
"note": e.comment,
|
||||||
"created_at": e.created_at.isoformat() + "Z" if e.created_at else None
|
"created_at": e.created_at.isoformat() + "Z" if e.created_at else None
|
||||||
} for e in events
|
} for e in events
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ from fastapi import APIRouter, BackgroundTasks, UploadFile, File, HTTPException,
|
|||||||
from fastapi.responses import FileResponse, StreamingResponse
|
from fastapi.responses import FileResponse, StreamingResponse
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from sqlalchemy.exc import IntegrityError
|
from sqlalchemy.exc import IntegrityError
|
||||||
|
from sqlalchemy import func
|
||||||
from jose import jwt, JWTError
|
from jose import jwt, JWTError
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
REQUIRED_VARS = [
|
||||||
|
"MYSQL_USER",
|
||||||
|
"MYSQL_PASSWORD",
|
||||||
|
"MYSQL_DATABASE",
|
||||||
|
"SECRET_KEY",
|
||||||
|
"SMTP_PASSWORD",
|
||||||
|
"OPENROUTER_API_KEY"
|
||||||
|
]
|
||||||
|
|
||||||
|
def main():
|
||||||
|
missing = []
|
||||||
|
for var in REQUIRED_VARS:
|
||||||
|
val = os.getenv(var)
|
||||||
|
if not val:
|
||||||
|
missing.append(var)
|
||||||
|
elif "password" in val.lower() or "secret" in val.lower() or "your" in val.lower() or "here" in val.lower():
|
||||||
|
if var in ["SECRET_KEY", "MYSQL_PASSWORD"]:
|
||||||
|
missing.append(f"{var} (looks like a placeholder)")
|
||||||
|
else:
|
||||||
|
print(f"WARNING: The value for {var} looks like a placeholder. Some features may not work.")
|
||||||
|
|
||||||
|
if missing:
|
||||||
|
print(f"ERROR: The following required environment variables are missing or invalid: {', '.join(missing)}")
|
||||||
|
print("Please check your .env file or environment configuration.")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
print("Environment validation passed.")
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user