feat: major platform upgrade — AI extraction pipeline, responsive UI, admin chatbot enhancements

CRITICAL FIXES
- Fix blank pages: useCallback declared after useEffect in all 5 pages
- Fix showToast undefined everywhere (ToastContext exported addToast not showToast)
- Fix admin doc upload always 422 (missing doc_key + doc_label form fields)
- Fix audit log wrong field names (log.details -> log.detail, remove user_agent)
- Fix SPA catch-all missing in main.py (direct URL access was 404)
- Fix chatbot using broken nvidia free model -> llama-3.3-70b

AI EXTRACTION PIPELINE
- 3-stage pipeline: Stage1 native text (free) -> Stage2 Tesseract OCR (free CPU) -> Stage3 Qwen vision (paid)
- Tesseract installed with eng+hin bilingual support, psm6, 2.5x DPI
- Scanned PDF fallback via PyMuPDF page render
- Blank template fallback: returns form_type/purpose/tax_year instead of empty
- Improved prompt: extracts actual document field names, no predefined terms
- Auto-poll UI: shows Processing spinner when extraction is running
- backfill_extraction.py: re-process all docs, fixed empty-dict-as-None bug

ADMIN DASHBOARD
- Pending docs split into Pending Personal + Pending Business stat cards
- User cards show typed badges: N personal / N business instead of generic N pending
- Backend returns pending_personal, pending_business, pending_docs per user

ADMIN USER DETAIL
- Doc count chips in user info bar: personal / business / returns / total
- Doc name bold 15px, date with calendar icon + TY chip, status as colored badges
- Responsive layout: doc-review-layout CSS classes replace inline flex styles
- Filing Timeline sidebar stacks above doc list on mobile
- AI Summary: bold labels and values, blank template shows metadata

CHATBOT ENHANCEMENTS
- Ask anything free-text input on menu screen (both admin and user chatbots)
- Admin: live context with latest uploads by date, new users today
- Admin: per-user activity lookup by name/email (docs + audit log)
- New endpoint: /api/chatbot/admin-user-context
- ExpandableSummaryBlock + ExpandableValue: bold navy field labels and values

RESPONSIVENESS
- components.css: 480px/640px/768px breakpoints for all pages
- Admin table, stat cards, tabs, toasts, FAB all properly responsive
- Auth shell stacks on mobile correctly
This commit is contained in:
Atharv1705
2026-08-05 11:41:06 +05:30
parent c2e22902c8
commit 9c7f25e06f
36 changed files with 3357 additions and 5279 deletions
+10
View File
@@ -6,6 +6,16 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
WORKDIR /app
# Install Tesseract OCR + English + Hindi language data (Stage 2 of extraction pipeline)
# tesseract-ocr: ~50MB — CPU-only, no GPU needed
# tesseract-ocr-hin: Hindi language pack for bilingual Indian documents (Aadhaar, PAN, etc.)
RUN apt-get update && apt-get install -y --no-install-recommends \
tesseract-ocr \
tesseract-ocr-eng \
tesseract-ocr-hin \
libgl1 \
&& rm -rf /var/lib/apt/lists/*
COPY services/api/requirements.txt /tmp/requirements.txt
RUN python - <<'PY'
from pathlib import Path
+46 -68
View File
@@ -1,91 +1,69 @@
/* ============================================================
animations.css — Micro-interactions & transitions
animations.css — Micro-interactions & motion (Ledger system)
============================================================ */
/* ── Page transition ─────────────────────────────────────── */
.page-enter {
animation: fadeIn 0.3s ease both;
}
.page-enter { animation: fadeIn 0.35s ease both; }
/* ── Card hover lift ─────────────────────────────────────── */
.lift {
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.lift:hover {
transform: translateY(-3px);
box-shadow: var(--shadow-md);
}
.lift { transition: transform 0.2s ease, box-shadow 0.2s ease; }
.lift:hover { transform: translateY(-3px); box-shadow: var(--shadow-md); }
/* ── Button press feedback ───────────────────────────────── */
.btn:active { transform: translateY(1px) scale(0.97); }
/* ── Pulse (for pending badge) ───────────────────────────── */
@keyframes pulse-orange {
0%, 100% { box-shadow: 0 0 0 0 rgba(255,127,17,0.35); }
50% { box-shadow: 0 0 0 5px rgba(255,127,17,0); }
@keyframes pulse-brass {
0%, 100% { box-shadow: 0 0 0 0 rgba(176,128,61,0.35); }
50% { box-shadow: 0 0 0 5px rgba(176,128,61,0); }
}
.pulse { animation: pulse-orange 2s infinite; }
.pulse { animation: pulse-brass 2s infinite; }
/* ── Skeleton shimmer ────────────────────────────────────── */
@keyframes shimmer {
from { background-position: -600px 0; }
to { background-position: 600px 0; }
}
.skeleton {
background: linear-gradient(90deg, #e8edf2 25%, #f4f6f9 50%, #e8edf2 75%);
background-size: 600px 100%;
animation: shimmer 1.4s infinite linear;
border-radius: var(--radius-sm);
color: transparent !important;
}
@keyframes fadeUp { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }
.fade-up { animation: fadeUp 0.4s ease both; }
/* ── Slide in from right (toast) ─────────────────────────── */
@keyframes toast-in {
from { opacity: 0; transform: translateX(20px); }
to { opacity: 1; transform: translateX(0); }
}
/* ── Fade up (cards on load) ─────────────────────────────── */
@keyframes fadeUp {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
.fade-up { animation: fadeUp 0.3s ease both; }
/* ── Staggered children ──────────────────────────────────── */
.stagger > *:nth-child(1) { animation-delay: 0.00s; }
.stagger > *:nth-child(2) { animation-delay: 0.05s; }
.stagger > *:nth-child(3) { animation-delay: 0.10s; }
.stagger > *:nth-child(4) { animation-delay: 0.15s; }
.stagger > *:nth-child(5) { animation-delay: 0.20s; }
.stagger > *:nth-child(6) { animation-delay: 0.25s; }
.stagger > *:nth-child(2) { animation-delay: 0.06s; }
.stagger > *:nth-child(3) { animation-delay: 0.12s; }
.stagger > *:nth-child(4) { animation-delay: 0.18s; }
.stagger > *:nth-child(5) { animation-delay: 0.24s; }
.stagger > *:nth-child(6) { animation-delay: 0.30s; }
/* ── Checkbox animate ────────────────────────────────────── */
input[type=checkbox] {
accent-color: var(--blue);
width: 16px;
height: 16px;
cursor: pointer;
}
input[type=checkbox] { accent-color: var(--emerald); width: 16px; height: 16px; cursor: pointer; }
/* ── Focus ring ──────────────────────────────────────────── */
:focus-visible {
outline: 2px solid var(--blue);
outline-offset: 2px;
}
/* ── Smooth link underline ───────────────────────────────── */
/* Ledger-rule underline — the signature link treatment: a brass
rule draws itself in, like a line struck under a checked entry */
.fancy-link {
position: relative;
text-decoration: none;
color: var(--blue);
color: var(--emerald);
}
.fancy-link::after {
content: '';
position: absolute;
bottom: -1px; left: 0;
bottom: -2px; left: 0;
width: 0; height: 1.5px;
background: var(--blue);
transition: width 0.2s ease;
background: var(--brass);
transition: width 0.25s cubic-bezier(0.4,0,0.2,1);
}
.fancy-link:hover::after { width: 100%; }
/* Scroll reveal — sections rise into place as they enter view */
.reveal {
opacity: 0;
transform: translateY(22px);
transition: opacity 0.6s cubic-bezier(0.16,1,0.3,1), transform 0.6s cubic-bezier(0.16,1,0.3,1);
}
.reveal.in-view { opacity: 1; transform: translateY(0); }
.reveal-delay-1.in-view { transition-delay: 0.08s; }
.reveal-delay-2.in-view { transition-delay: 0.16s; }
.reveal-delay-3.in-view { transition-delay: 0.24s; }
/* Ruled counter tick — used behind hero stat figures */
@keyframes tickIn {
from { opacity: 0; transform: translateY(6px); }
to { opacity: 1; transform: translateY(0); }
}
.tick-in { animation: tickIn 0.5s cubic-bezier(0.16,1,0.3,1) both; }
/* Spin — used for AI Summary "Processing..." indicator */
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
+168 -122
View File
@@ -1,68 +1,118 @@
/* ============================================================
base.css — BookKeepPro Design System
Shared by every page. Load first.
============================================================ */
@import url('https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,1,0');
@import url('https://fonts.googleapis.com/css2?family=Fraunces:ital,opsz,wght@0,9..144,400;0,9..144,500;0,9..144,600;0,9..144,700;1,9..144,500&family=IBM+Plex+Sans:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500;600&display=swap');
@import "tailwindcss";
/* ============================================================
base.css — BookKeepPro Design System · "Ledger"
Ink, brass and parchment — a bookkeeping identity built on
the working materials of the trade: ruled paper, tabular
figures, and the quiet authority of a well-kept ledger.
============================================================ */
/* ── Brand Tokens ─────────────────────────────────────────── */
:root {
--blue: #0077C8;
--blue-dark: #005fa3;
--blue-light: #e9f5ff;
--orange: #FF7F11;
--orange-dark: #e56e0d;
--orange-light: #fff3e0;
--header-bg: #BEE2FA;
--footer-bot: #A9D9F8;
--navy: #0B2540;
--accent: #3AB4F2;
--bg: #f1f7fb;
--card: #ffffff;
--muted: #6b7a86;
--border: #e2eaf2;
--success: #2e7d32;
--success-bg: #e6f9ec;
--error: #c62828;
--error-bg: #fdecea;
--warn: #f57f17;
--warn-bg: #fff8e1;
/* core palette */
--ink: #17211D;
--ink-soft: #2A362F;
--brass: #B0803D;
--brass-dark: #8F6528;
--brass-light: rgba(176, 128, 61, 0.12);
--emerald: #1F5D46;
--emerald-dark: #163F30;
--emerald-light:rgba(31, 93, 70, 0.10);
--paper: #F5F2E9;
--paper-raised: #FFFFFF;
/* legacy variable names kept so every existing component re-skins automatically */
--blue: var(--emerald);
--blue-dark: var(--emerald-dark);
--blue-light: var(--emerald-light);
--orange: var(--brass);
--orange-dark: var(--brass-dark);
--orange-light: var(--brass-light);
--header-bg: #EFEADA;
--footer-bot: #EFEADA;
--navy: var(--ink);
--accent: #2C7A5B;
--bg: var(--paper);
--card: var(--paper-raised);
--muted: #6B7268;
--border: #E3DDC9;
--success: #1F5D46;
--success-bg: rgba(31, 93, 70, 0.10);
--error: #A63A3A;
--error-bg: rgba(166, 58, 58, 0.10);
--warn: #B0803D;
--warn-bg: rgba(176, 128, 61, 0.12);
--font-display: 'Fraunces', 'Georgia', serif;
--font-body: 'IBM Plex Sans', system-ui, sans-serif;
--font-mono: 'IBM Plex Mono', ui-monospace, monospace;
--radius-xs: 6px;
--radius-sm: 10px;
--radius-md: 14px;
--radius-lg: 20px;
--radius-lg: 22px;
--radius-pill: 999px;
--shadow-xs: 0 1px 4px rgba(0,0,0,0.06);
--shadow-sm: 0 2px 10px rgba(0,0,0,0.07);
--shadow-md: 0 6px 24px rgba(0,0,0,0.09);
--shadow-lg: 0 16px 48px rgba(0,0,0,0.12);
--shadow-xs: 0 1px 2px 0 rgba(23, 33, 29, 0.06);
--shadow-sm: 0 4px 10px -2px rgba(23, 33, 29, 0.10);
--shadow-md: 0 12px 28px -8px rgba(23, 33, 29, 0.16);
--shadow-lg: 0 24px 56px -12px rgba(23, 33, 29, 0.22);
--shadow-glow: 0 0 0 6px rgba(176, 128, 61, 0.14);
--transition: 0.2s ease;
--transition: 0.28s cubic-bezier(0.4, 0, 0.2, 1);
--glass-blur: blur(14px);
--ruled: repeating-linear-gradient(
to bottom,
transparent 0,
transparent 27px,
rgba(23, 33, 29, 0.05) 27px,
rgba(23, 33, 29, 0.05) 28px
);
}
/* ── Reset ───────────────────────────────────────────────── */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
html { font-size: 16px; scroll-behavior: smooth; }
@media (prefers-reduced-motion: reduce) {
html { scroll-behavior: auto; }
*, *::before, *::after { animation-duration: 0.001ms !important; animation-iteration-count: 1 !important; transition-duration: 0.001ms !important; }
}
body {
font-family: "Poppins", system-ui, sans-serif;
font-family: var(--font-body);
background: var(--bg);
color: #222;
color: var(--ink);
min-height: 100vh;
-webkit-font-smoothing: antialiased;
}
img { max-width: 100%; display: block; }
a { color: var(--blue); text-decoration: none; }
a:hover { color: var(--blue-dark); }
a { color: var(--emerald); text-decoration: none; }
a:hover { color: var(--emerald-dark); }
.material-symbols-outlined { font-size: inherit; vertical-align: middle; line-height: 1; font-variation-settings: 'FILL' 1, 'wght' 400, 'GRAD' 0, 'opsz' 24; }
.tnum { font-family: var(--font-mono); font-variant-numeric: tabular-nums; letter-spacing: -0.01em; }
/* ── Typography ──────────────────────────────────────────── */
h1 { font-size: clamp(22px,3vw,30px); font-weight: 700; color: var(--navy); line-height: 1.25; }
h2 { font-size: clamp(18px,2.5vw,24px); font-weight: 600; color: var(--navy); line-height: 1.3; }
h3 { font-size: clamp(15px,2vw,18px); font-weight: 600; color: var(--navy); }
p { line-height: 1.7; color: #444; }
h1, h2, h3 { font-family: var(--font-display); color: var(--ink); }
h1 { font-size: clamp(24px, 3.4vw, 34px); font-weight: 600; line-height: 1.15; letter-spacing: -0.01em; }
h2 { font-size: clamp(19px, 2.6vw, 26px); font-weight: 600; line-height: 1.25; }
h3 { font-size: clamp(16px, 2vw, 19px); font-weight: 600; }
p { line-height: 1.7; color: #3E463F; }
small, .text-sm { font-size: 13px; color: var(--muted); }
.text-muted { color: var(--muted); }
.eyebrow {
font-family: var(--font-mono);
font-size: 11.5px;
font-weight: 500;
letter-spacing: 0.14em;
text-transform: uppercase;
color: var(--brass-dark);
display: inline-flex;
align-items: center;
gap: 8px;
}
.eyebrow::before { content: ''; width: 18px; height: 1px; background: var(--brass); display: inline-block; }
/* ── Card ────────────────────────────────────────────────── */
.card {
@@ -71,9 +121,9 @@ small, .text-sm { font-size: 13px; color: var(--muted); }
box-shadow: var(--shadow-sm);
border: 1px solid var(--border);
padding: clamp(20px, 4vw, 32px);
transition: box-shadow var(--transition);
transition: box-shadow var(--transition), transform var(--transition);
}
.card:hover { box-shadow: var(--shadow-md); }
.card:hover { box-shadow: var(--shadow-md); transform: translateY(-2px); }
.card-flat { background: var(--card); border-radius: var(--radius-md); border: 1px solid var(--border); padding: clamp(16px, 3vw, 24px); }
/* ── Buttons ─────────────────────────────────────────────── */
@@ -82,30 +132,37 @@ small, .text-sm { font-size: 13px; color: var(--muted); }
align-items: center;
justify-content: center;
gap: 6px;
padding: 11px 22px;
font-family: inherit;
padding: 11px 24px;
font-family: var(--font-body);
font-size: 14px;
font-weight: 600;
border: none;
border-radius: var(--radius-pill);
border-radius: var(--radius-sm);
cursor: pointer;
transition: background var(--transition), transform var(--transition), box-shadow var(--transition);
transition: transform 0.12s ease, background var(--transition), box-shadow var(--transition), border-color var(--transition);
white-space: nowrap;
}
.btn:active { transform: translateY(1px) scale(0.97); }
.btn:disabled { opacity: 0.55; cursor: not-allowed; transform: none; }
.btn:active { transform: translateY(1px) scale(0.98); }
.btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
.btn-primary { background: var(--orange); color: #fff; }
.btn-primary:hover:not(:disabled) { background: var(--orange-dark); box-shadow: 0 4px 12px rgba(255,127,17,0.3); }
.btn-primary { background: var(--brass); color: #fff; }
.btn-primary:hover:not(:disabled) { background: var(--brass-dark); box-shadow: 0 6px 18px rgba(176,128,61,0.32); }
.btn-secondary { background: var(--blue); color: #fff; }
.btn-secondary:hover:not(:disabled) { background: var(--blue-dark); box-shadow: 0 4px 12px rgba(0,119,200,0.25); }
.btn-secondary { background: var(--emerald); color: #fff; }
.btn-secondary:hover:not(:disabled) { background: var(--emerald-dark); box-shadow: 0 6px 18px rgba(31,93,70,0.28); }
.btn-ghost { background: transparent; color: var(--muted); border: 1.5px solid var(--border); border-radius: var(--radius-sm); padding: 10px 18px; }
.btn-ghost:hover:not(:disabled) { background: var(--bg); color: var(--navy); border-color: #c0cfe0; }
.btn-outline {
background: transparent;
color: var(--ink);
border: 1.5px solid var(--ink);
}
.btn-outline:hover:not(:disabled) { background: var(--ink); color: #fff; }
.btn-danger { background: #ff4d4d; color: #fff; }
.btn-danger:hover:not(:disabled) { background: #e03c3c; box-shadow: 0 4px 12px rgba(255,77,77,0.3); }
.btn-ghost { background: transparent; color: var(--muted); border: 1.5px solid var(--border); }
.btn-ghost:hover:not(:disabled) { background: var(--paper); color: var(--ink); border-color: #cfc7ad; }
.btn-danger { background: var(--error); color: #fff; }
.btn-danger:hover:not(:disabled) { background: #8a2f2f; box-shadow: 0 6px 18px rgba(166,58,58,0.3); }
.btn-sm { padding: 7px 16px; font-size: 13px; }
.btn-xs { padding: 5px 12px; font-size: 12px; }
@@ -117,46 +174,47 @@ small, .text-sm { font-size: 13px; color: var(--muted); }
padding: 12px 16px;
border: 1.5px solid var(--border);
border-radius: var(--radius-sm);
font-family: inherit;
font-family: var(--font-body);
font-size: 14px;
color: #222;
color: var(--ink);
background: #fff;
transition: border-color var(--transition), box-shadow var(--transition);
}
.input:focus, .select-input:focus {
outline: none;
border-color: var(--blue);
box-shadow: 0 0 0 3px rgba(0,119,200,0.10);
border-color: var(--emerald);
box-shadow: 0 0 0 3px rgba(31,93,70,0.12);
}
.input::placeholder { color: #a8b5c2; }
.input[readonly] { background: #f8fafc; color: var(--muted); cursor: default; }
label.form-label { display: block; font-size: 13px; font-weight: 500; color: #444; margin-bottom: 6px; }
.input::placeholder { color: #A8A190; }
.input[readonly] { background: var(--paper); color: var(--muted); cursor: default; }
label.form-label { display: block; font-size: 12.5px; font-weight: 600; letter-spacing: 0.02em; color: var(--ink-soft); margin-bottom: 6px; }
.form-group { margin-bottom: 18px; }
.password-wrap { position: relative; }
.password-wrap .input { padding-right: 56px; }
.password-toggle {
position: absolute; right: 14px; top: 50%; transform: translateY(-50%);
background: none; border: none; color: var(--blue); font-weight: 600; font-size: 13px; cursor: pointer;
background: none; border: none; color: var(--emerald); font-weight: 600; font-size: 13px; cursor: pointer;
}
/* ── Badges ──────────────────────────────────────────────── */
.badge {
display: inline-flex; align-items: center; gap: 4px;
padding: 3px 10px; border-radius: var(--radius-pill);
padding: 3px 10px; border-radius: var(--radius-xs);
font-size: 11px; font-weight: 700; letter-spacing: 0.3px;
white-space: nowrap;
font-family: var(--font-mono);
}
.badge-blue { background: var(--blue-light); color: var(--blue); }
.badge-orange { background: var(--orange-light); color: #e65100; border: 1px solid #ffc89a; }
.badge-red { background: #fce4ec; color: var(--error); }
.badge-blue { background: var(--emerald-light); color: var(--emerald); }
.badge-orange { background: var(--brass-light); color: var(--brass-dark); border: 1px solid rgba(176,128,61,0.35); }
.badge-red { background: var(--error-bg); color: var(--error); }
.badge-green { background: var(--success-bg); color: var(--success); }
.badge-yellow { background: var(--warn-bg); color: var(--warn); border: 1px solid #ffe082; }
.badge-muted { background: #f0f4f8; color: var(--muted); }
.badge-yellow { background: var(--warn-bg); color: var(--warn); border: 1px solid rgba(176,128,61,0.3); }
.badge-muted { background: var(--paper); color: var(--muted); }
/* ── Status Pills (doc review) ───────────────────────────── */
.pill-approved { background:var(--success-bg); color:var(--success); border:1px solid #a5d6a7; padding:2px 10px; border-radius:20px; font-size:11px; font-weight:700; }
.pill-rejected { background:var(--error-bg); color:var(--error); border:1px solid #ef9a9a; padding:2px 10px; border-radius:20px; font-size:11px; font-weight:700; }
.pill-pending { background:var(--warn-bg); color:var(--warn); border:1px solid #ffe082; padding:2px 10px; border-radius:20px; font-size:11px; font-weight:700; }
.pill-approved { background:var(--success-bg); color:var(--success); border:1px solid rgba(31,93,70,0.3); padding:2px 10px; border-radius:var(--radius-xs); font-size:11px; font-weight:700; font-family: var(--font-mono); }
.pill-rejected { background:var(--error-bg); color:var(--error); border:1px solid rgba(166,58,58,0.3); padding:2px 10px; border-radius:var(--radius-xs); font-size:11px; font-weight:700; font-family: var(--font-mono); }
.pill-pending { background:var(--warn-bg); color:var(--brass-dark); border:1px solid rgba(176,128,61,0.3); padding:2px 10px; border-radius:var(--radius-xs); font-size:11px; font-weight:700; font-family: var(--font-mono); }
/* ── Divider ─────────────────────────────────────────────── */
.divider { border: none; border-top: 1px solid var(--border); margin: 20px 0; }
@@ -182,9 +240,9 @@ label.form-label { display: block; font-size: 13px; font-weight: 500; color: #44
/* ── Animations ──────────────────────────────────────────── */
@keyframes fadeIn { from { opacity:0; transform:translateY(6px); } to { opacity:1; transform:none; } }
@keyframes slideUp { from { opacity:0; transform:translateY(12px); } to { opacity:1; transform:none; } }
.fade-in { animation: fadeIn 0.3s ease both; }
.slide-up { animation: slideUp 0.35s ease both; }
@keyframes slideUp { from { opacity:0; transform:translateY(14px); } to { opacity:1; transform:none; } }
.fade-in { animation: fadeIn 0.35s ease both; }
.slide-up { animation: slideUp 0.4s ease both; }
/* ── Skeleton loading ────────────────────────────────────── */
@keyframes shimmer {
@@ -192,7 +250,7 @@ label.form-label { display: block; font-size: 13px; font-weight: 500; color: #44
to { background-position: 600px 0; }
}
.skeleton {
background: linear-gradient(90deg, #e8edf2 25%, #f4f6f9 50%, #e8edf2 75%);
background: linear-gradient(90deg, #EDE8D9 25%, #F5F2E9 50%, #EDE8D9 75%);
background-size: 600px 100%;
animation: shimmer 1.4s infinite linear;
border-radius: var(--radius-sm);
@@ -218,65 +276,53 @@ label.form-label { display: block; font-size: 13px; font-weight: 500; color: #44
.text-center { text-align: center; }
.font-600 { font-weight: 600; }
/* --- UI/UX Polish --- */
/* Button Micro-animations */
.btn {
transition: transform 0.1s ease, background 0.2s ease, box-shadow 0.2s ease;
}
.btn:active {
transform: scale(0.96);
/* Focus visibility */
:focus-visible {
outline: 2px solid var(--emerald);
outline-offset: 2px;
}
/* Focus States for Accessibility */
.input:focus,
input[type="text"]:focus,
input[type="email"]:focus,
input[type="password"]:focus,
/* Button + input micro-interactions */
.btn:active { transform: scale(0.97); }
.input:focus,
input[type="text"]:focus,
input[type="email"]:focus,
input[type="password"]:focus,
textarea:focus {
outline: none;
border-color: var(--blue) !important;
box-shadow: 0 0 0 3px rgba(0, 119, 200, 0.25) !important;
border-color: var(--emerald) !important;
box-shadow: 0 0 0 3px rgba(31,93,70,0.14) !important;
transition: border-color 0.2s ease, box-shadow 0.2s ease;
}
/* Document & Admin Card Lift Effects */
.doc-card, .doc-row, .admin-docs-td {
transition: transform 0.2s ease, box-shadow 0.2s ease, background 0.2s ease;
}
.doc-row:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0,0,0,0.05);
background: #fafafa;
}
/* --- Dark Mode Overrides --- */
/* ── Dark Mode Overrides ─────────────────────────────────── */
.dark-theme {
--bg: #0B1521;
--card: #152538;
--navy: #f1f7fb;
--muted: #a8b5c2;
--border: #2A3F54;
--header-bg: #0F2B44;
--footer-bot: #06182B;
--blue-light: #0d263b;
--orange-light: #2d1a0a;
--success-bg: #0b2e13;
--error-bg: #420f0f;
--warn-bg: #3d2508;
--shadow-xs: 0 1px 4px rgba(0,0,0,0.3);
--bg: #10160F;
--card: #1A2119;
--navy: #F2EFE4;
--ink: #F2EFE4;
--muted: #A6AC9F;
--border: #2B3529;
--header-bg: #182018;
--footer-bot: #10160F;
--blue-light: rgba(90, 168, 138, 0.16);
--orange-light: rgba(196, 150, 82, 0.16);
--emerald-light:rgba(90, 168, 138, 0.16);
--brass-light: rgba(196, 150, 82, 0.16);
--success-bg: rgba(90, 168, 138, 0.14);
--error-bg: rgba(214, 110, 110, 0.14);
--warn-bg: rgba(196, 150, 82, 0.16);
--shadow-xs: 0 1px 4px rgba(0,0,0,0.35);
--shadow-sm: 0 2px 10px rgba(0,0,0,0.4);
--shadow-md: 0 6px 24px rgba(0,0,0,0.5);
--shadow-lg: 0 16px 48px rgba(0,0,0,0.6);
}
/* Ensure text on dark theme maps correctly if using base html/body color */
body.dark-theme {
background-color: var(--bg);
color: var(--navy);
color: var(--ink);
}
.dark-theme .input, .dark-theme .select-input { background: var(--card); color: var(--ink); border-color: var(--border); }
+97 -305
View File
@@ -1,102 +1,84 @@
/* ============================================================
chatbot.css — BookKeepPro Chatbot Widget
Floating chat bubble + chat window
chatbot.css — BookKeepPro Chatbot Widget (Ledger system)
============================================================ */
/* ── Chat Bubble (FAB) ──────────────────────────────────── */
.chatbot-fab {
position: fixed;
bottom: 24px;
right: 24px;
width: 58px;
height: 58px;
width: 56px;
height: 56px;
border-radius: 50%;
background: linear-gradient(135deg, var(--blue) 0%, var(--accent) 100%);
background: var(--ink);
color: #fff;
border: none;
border: 1px solid rgba(255, 255, 255, 0.14);
cursor: pointer;
box-shadow: 0 4px 20px rgba(0, 119, 200, 0.35);
box-shadow: var(--shadow-lg);
display: flex;
align-items: center;
justify-content: center;
font-size: 28px;
font-size: 26px;
z-index: 9998;
transition: transform 0.25s ease, box-shadow 0.25s ease;
}
.chatbot-fab:hover {
transform: scale(1.08);
box-shadow: 0 6px 28px rgba(0, 119, 200, 0.45);
}
.chatbot-fab:active {
transform: scale(0.96);
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s ease, background 0.3s ease;
}
.chatbot-fab:hover { transform: scale(1.07); background: var(--emerald-dark); }
.chatbot-fab:active { transform: scale(0.96); }
.chatbot-fab .fab-icon { transition: transform 0.3s ease; }
.chatbot-fab.open .fab-icon { transform: rotate(90deg); }
/* Pulse ring animation */
.chatbot-fab::before {
content: "";
position: absolute;
inset: -4px;
border-radius: 50%;
border: 2px solid var(--blue);
border: 1.5px solid var(--brass);
opacity: 0;
animation: chatPulse 2.5s ease-out infinite;
}
.chatbot-fab.open::before { animation: none; opacity: 0; }
@keyframes chatPulse {
0% { transform: scale(1); opacity: 0.5; }
0% { transform: scale(1); opacity: 0.45; }
100% { transform: scale(1.4); opacity: 0; }
}
/* Notification dot */
.chatbot-fab .notif-dot {
position: absolute;
top: 2px;
right: 2px;
width: 14px;
height: 14px;
top: 2px; right: 2px;
width: 13px; height: 13px;
border-radius: 50%;
background: var(--orange);
border: 2px solid #fff;
background: var(--brass);
border: 2px solid var(--ink);
animation: dotBounce 1.5s ease infinite;
}
.chatbot-fab.open .notif-dot { display: none; }
@keyframes dotBounce {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.2); }
}
@keyframes dotBounce { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.2); } }
/* ── Chat Window ────────────────────────────────────────── */
.chatbot-window {
position: fixed;
bottom: 96px;
bottom: 92px;
right: 24px;
width: 380px;
max-height: 520px;
border-radius: var(--radius-md);
background: var(--card);
box-shadow: 0 12px 48px rgba(0, 0, 0, 0.15);
border-radius: var(--radius-lg);
background: #FFFFFF;
border: 1px solid var(--border);
box-shadow: var(--shadow-lg);
display: flex;
flex-direction: column;
z-index: 9999;
overflow: hidden;
opacity: 0;
transform: translateY(20px) scale(0.95);
transform: translateY(16px) scale(0.97);
pointer-events: none;
transition: opacity 0.3s ease, transform 0.3s ease;
}
.chatbot-window.visible {
opacity: 1;
transform: translateY(0) scale(1);
pointer-events: auto;
transition: opacity 0.35s cubic-bezier(0.4, 0, 0.2, 1), transform 0.35s cubic-bezier(0.4, 0, 0.2, 1);
}
.chatbot-window.visible { opacity: 1; transform: translateY(0) scale(1); pointer-events: auto; }
/* ── Header ─────────────────────────────────────────────── */
.chatbot-header {
background: linear-gradient(135deg, var(--blue) 0%, #005fa3 100%);
background: var(--ink);
background-image: var(--ruled);
color: #fff;
padding: 16px 18px;
display: flex;
@@ -105,302 +87,112 @@
flex-shrink: 0;
}
.chatbot-header .bot-avatar {
width: 38px;
height: 38px;
border-radius: 50%;
background: rgba(255, 255, 255, 0.2);
display: flex;
align-items: center;
justify-content: center;
font-size: 20px;
flex-shrink: 0;
}
.chatbot-header .bot-info h4 {
font-size: 14px;
font-weight: 600;
margin: 0;
color: #fff;
}
.chatbot-header .bot-info span {
font-size: 11px;
opacity: 0.8;
width: 36px; height: 36px; border-radius: 50%;
background: var(--brass);
display: flex; align-items: center; justify-content: center;
font-size: 18px; flex-shrink: 0; color: #fff;
}
.chatbot-header .bot-info h4 { font-size: 14px; font-weight: 600; margin: 0; color: #fff; font-family: var(--font-body); }
.chatbot-header .bot-info span { font-size: 11px; opacity: 0.75; }
.chatbot-header .close-chat {
margin-left: auto;
background: rgba(255, 255, 255, 0.15);
border: none;
color: #fff;
width: 30px;
height: 30px;
border-radius: 50%;
cursor: pointer;
font-size: 16px;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.2s;
}
.chatbot-header .close-chat:hover {
background: rgba(255, 255, 255, 0.3);
margin-left: auto; background: rgba(255,255,255,0.12); border: none; color: #fff;
width: 28px; height: 28px; border-radius: 50%; cursor: pointer; font-size: 15px;
display: flex; align-items: center; justify-content: center; transition: background 0.2s;
}
.chatbot-header .close-chat:hover { background: rgba(255,255,255,0.25); }
/* ── Messages Area ──────────────────────────────────────── */
.chatbot-messages {
flex: 1;
overflow-y: auto;
padding: 16px;
display: flex;
flex-direction: column;
gap: 10px;
background: #f8fbfe;
min-height: 200px;
max-height: 340px;
flex: 1; overflow-y: auto; padding: 22px 18px;
display: flex; flex-direction: column; gap: 12px;
background: var(--paper);
min-height: 200px; max-height: 380px; scroll-behavior: smooth;
}
.chatbot-welcome-text {
display: flex; align-items: center; justify-content: center; gap: 8px;
margin-bottom: 8px; padding: 10px;
background: var(--emerald-light);
border-radius: var(--radius-sm);
border: 1px solid rgba(31,93,70,0.15);
}
.chatbot-welcome-text p { font-size: 13px; font-weight: 500; color: var(--ink); margin: 0; }
.chatbot-welcome-text .sparkle { font-size: 17px; color: var(--brass); }
.chatbot-messages::-webkit-scrollbar { width: 5px; }
.chatbot-messages::-webkit-scrollbar-track { background: transparent; }
.chatbot-messages::-webkit-scrollbar-thumb { background: #c5d9ee; border-radius: 10px; }
.chatbot-messages::-webkit-scrollbar-thumb { background: #d8d0b6; border-radius: 10px; }
/* ── Message Bubbles ────────────────────────────────────── */
.chat-msg {
max-width: 85%;
padding: 10px 14px;
border-radius: 14px;
font-size: 13px;
line-height: 1.5;
animation: msgSlideIn 0.3s ease;
word-wrap: break-word;
}
@keyframes msgSlideIn {
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: translateY(0); }
max-width: 85%; padding: 10px 14px; border-radius: 13px;
font-size: 13px; line-height: 1.5; animation: msgSlideIn 0.3s ease; word-wrap: break-word;
}
@keyframes msgSlideIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
.chat-msg.bot {
background: #fff;
color: #222;
border: 1px solid var(--border);
border-bottom-left-radius: 4px;
align-self: flex-start;
box-shadow: 0 1px 4px rgba(0,0,0,0.04);
background: #fff; color: var(--ink); border: 1px solid var(--border);
border-bottom-left-radius: 4px; align-self: flex-start; box-shadow: var(--shadow-xs);
}
.chat-msg.user {
background: linear-gradient(135deg, var(--blue), var(--accent));
color: #fff;
border-bottom-right-radius: 4px;
align-self: flex-end;
background: var(--emerald); color: #fff; border-bottom-right-radius: 4px; align-self: flex-end;
}
/* ── Typing Indicator ───────────────────────────────────── */
.typing-indicator {
display: flex;
gap: 4px;
padding: 12px 16px;
align-self: flex-start;
}
.typing-indicator span {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--blue);
opacity: 0.4;
animation: typingDot 1.2s ease-in-out infinite;
}
.typing-indicator { display: flex; gap: 4px; padding: 12px 16px; align-self: flex-start; }
.typing-indicator span { width: 7px; height: 7px; border-radius: 50%; background: var(--emerald); opacity: 0.4; animation: typingDot 1.2s ease-in-out infinite; }
.typing-indicator span:nth-child(2) { animation-delay: 0.15s; }
.typing-indicator span:nth-child(3) { animation-delay: 0.3s; }
@keyframes typingDot { 0%, 60%, 100% { transform: translateY(0); opacity: 0.4; } 30% { transform: translateY(-6px); opacity: 1; } }
@keyframes typingDot {
0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }
30% { transform: translateY(-6px); opacity: 1; }
}
/* ── Quick Reply Buttons ────────────────────────────────── */
.quick-replies {
display: flex;
flex-direction: column;
gap: 8px;
margin-top: 6px;
}
.quick-replies { display: flex; flex-direction: column; gap: 8px; margin-top: 6px; }
.quick-reply-btn {
background: #fff;
border: 1.5px solid var(--blue);
color: var(--blue);
padding: 9px 14px;
border-radius: var(--radius-sm);
font-size: 13px;
font-weight: 500;
cursor: pointer;
text-align: left;
transition: all 0.2s ease;
font-family: inherit;
display: flex;
align-items: center;
gap: 8px;
}
.quick-reply-btn:hover {
background: var(--blue);
color: #fff;
transform: translateX(4px);
box-shadow: 0 2px 8px rgba(0, 119, 200, 0.2);
}
.quick-reply-btn .qr-icon {
font-size: 16px;
flex-shrink: 0;
background: #fff; border: 1.5px solid var(--border); color: var(--ink);
padding: 11px 15px; border-radius: var(--radius-sm); font-size: 13.5px; font-weight: 500;
cursor: pointer; text-align: left; transition: all 0.25s cubic-bezier(0.4,0,0.2,1);
font-family: inherit; display: flex; align-items: center; gap: 12px; box-shadow: var(--shadow-xs);
}
.quick-reply-btn:hover { background: var(--emerald-light); border-color: var(--emerald); color: var(--emerald-dark); transform: translateY(-1px); }
.quick-reply-btn .qr-icon { font-size: 16px; flex-shrink: 0; }
/* ── Doc Status Cards ───────────────────────────────────── */
.doc-status-card {
background: #fff;
border: 1px solid var(--border);
border-radius: var(--radius-xs);
padding: 10px 12px;
margin-top: 6px;
font-size: 12px;
}
.doc-status-card .doc-name {
font-weight: 600;
color: var(--navy);
margin-bottom: 4px;
font-size: 13px;
}
.doc-status-card .doc-year {
color: var(--muted);
font-size: 11px;
}
.doc-status-card .doc-badge {
display: inline-block;
padding: 2px 8px;
border-radius: var(--radius-pill);
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.3px;
}
.doc-badge.pending { background: var(--warn-bg); color: var(--warn); }
.doc-status-card { background: #fff; border: 1px solid var(--border); border-radius: var(--radius-xs); padding: 10px 12px; margin-top: 6px; font-size: 12px; }
.doc-status-card .doc-name { font-weight: 600; color: var(--ink); margin-bottom: 4px; font-size: 13px; }
.doc-status-card .doc-year { color: var(--muted); font-size: 11px; }
.doc-status-card .doc-badge { display: inline-block; padding: 2px 8px; border-radius: var(--radius-xs); font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.3px; font-family: var(--font-mono); }
.doc-badge.pending { background: var(--warn-bg); color: var(--brass-dark); }
.doc-badge.approved { background: var(--success-bg); color: var(--success); }
.doc-badge.rejected { background: var(--error-bg); color: var(--error); }
.doc-status-card .doc-note { margin-top: 4px; color: var(--muted); font-style: italic; font-size: 11px; }
.doc-status-card .doc-note {
margin-top: 4px;
color: var(--muted);
font-style: italic;
font-size: 11px;
}
/* ── Summary Banner ─────────────────────────────────────── */
.status-summary {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin-top: 8px;
}
.summary-item {
text-align: center;
padding: 8px 4px;
border-radius: var(--radius-xs);
background: #f1f7fb;
}
.summary-item .count {
font-size: 20px;
font-weight: 700;
display: block;
}
.summary-item .label {
font-size: 10px;
text-transform: uppercase;
color: var(--muted);
letter-spacing: 0.5px;
}
.summary-item.pending .count { color: var(--warn); }
.status-summary { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin-top: 8px; }
.summary-item { text-align: center; padding: 8px 4px; border-radius: var(--radius-xs); background: var(--paper); }
.summary-item .count { font-family: var(--font-mono); font-size: 19px; font-weight: 600; display: block; }
.summary-item .label { font-size: 10px; text-transform: uppercase; color: var(--muted); letter-spacing: 0.5px; }
.summary-item.pending .count { color: var(--brass-dark); }
.summary-item.approved .count { color: var(--success); }
.summary-item.rejected .count { color: var(--error); }
/* ── FAQ List ───────────────────────────────────────────── */
.faq-question {
background: #fff;
border: 1px solid var(--border);
border-radius: var(--radius-xs);
padding: 9px 12px;
font-size: 12.5px;
cursor: pointer;
transition: all 0.2s ease;
text-align: left;
color: var(--navy);
width: 100%;
font-family: inherit;
display: block;
margin-top: 4px;
}
.faq-question:hover {
border-color: var(--blue);
color: var(--blue);
background: var(--blue-light);
background: #fff; border: 1px solid var(--border); border-radius: var(--radius-xs);
padding: 9px 12px; font-size: 12.5px; cursor: pointer; transition: all 0.2s ease;
text-align: left; color: var(--ink); width: 100%; font-family: inherit; display: block; margin-top: 4px;
}
.faq-question:hover { border-color: var(--emerald); color: var(--emerald); background: var(--emerald-light); }
/* ── Back Button ────────────────────────────────────────── */
.back-btn {
background: none;
border: none;
color: var(--blue);
cursor: pointer;
font-size: 12px;
padding: 4px 0;
font-family: inherit;
font-weight: 500;
margin-top: 6px;
display: inline-flex;
align-items: center;
gap: 4px;
background: none; border: none; color: var(--emerald); cursor: pointer; font-size: 12px;
padding: 4px 0; font-family: inherit; font-weight: 500; margin-top: 6px;
display: inline-flex; align-items: center; gap: 4px;
}
.back-btn:hover { text-decoration: underline; }
/* ── Mobile Responsive ──────────────────────────────────── */
@media (max-width: 480px) {
.chatbot-window {
bottom: 0;
right: 0;
left: 0;
width: 100%;
max-height: 75vh;
border-radius: var(--radius-md) var(--radius-md) 0 0;
}
.chatbot-fab {
bottom: 16px;
right: 16px;
width: 52px;
height: 52px;
font-size: 24px;
}
.chatbot-window { bottom: 0; right: 0; left: 0; width: 100%; max-height: 75vh; border-radius: var(--radius-md) var(--radius-md) 0 0; }
.chatbot-fab { bottom: 16px; right: 16px; width: 50px; height: 50px; font-size: 22px; }
}
/* ── Dark Mode Support ──────────────────────────────────── */
[data-theme="dark"] .chatbot-window { background: #1a2332; }
[data-theme="dark"] .chatbot-messages { background: #0f1923; }
[data-theme="dark"] .chat-msg.bot {
background: #1e2d3d;
border-color: #2a3f54;
color: #d4dde6;
}
[data-theme="dark"] .quick-reply-btn {
background: #1e2d3d;
border-color: var(--blue);
color: var(--accent);
}
[data-theme="dark"] .quick-reply-btn:hover {
background: var(--blue);
color: #fff;
}
[data-theme="dark"] .doc-status-card {
background: #1e2d3d;
border-color: #2a3f54;
}
[data-theme="dark"] .doc-status-card .doc-name { color: #d4dde6; }
[data-theme="dark"] .faq-question {
background: #1e2d3d;
border-color: #2a3f54;
color: #d4dde6;
}
[data-theme="dark"] .faq-question:hover {
background: #253648;
border-color: var(--blue);
}
[data-theme="dark"] .summary-item { background: #1e2d3d; }
.dark-theme .chatbot-window { background: var(--card); }
.dark-theme .chatbot-messages { background: var(--bg); }
.dark-theme .chat-msg.bot { background: var(--card); border-color: var(--border); color: var(--navy); }
.dark-theme .quick-reply-btn { background: var(--card); border-color: var(--border); color: var(--navy); }
.dark-theme .quick-reply-btn:hover { background: var(--blue-light); border-color: var(--blue); }
.dark-theme .doc-status-card { background: var(--card); border-color: var(--border); }
.dark-theme .doc-status-card .doc-name { color: var(--navy); }
.dark-theme .faq-question { background: var(--card); border-color: var(--border); color: var(--navy); }
.dark-theme .faq-question:hover { background: var(--blue-light); border-color: var(--blue); }
.dark-theme .summary-item { background: var(--card); }
+569 -196
View File
@@ -1,30 +1,32 @@
/* ============================================================
components.css — Reusable UI components
components.css — Reusable UI components (Ledger system)
Load after base.css
============================================================ */
/* ── App Header ──────────────────────────────────────────── */
/* ── App Header (dashboard/admin) ───────────────────────── */
.app-header {
position: sticky;
top: 0;
z-index: 200;
background: var(--header-bg);
backdrop-filter: var(--glass-blur);
-webkit-backdrop-filter: var(--glass-blur);
border-bottom: 1px solid var(--border);
padding: 0 clamp(16px, 4vw, 32px);
height: 62px;
height: 66px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
position: sticky;
top: 0;
z-index: 200;
box-shadow: 0 2px 12px rgba(0,80,140,0.10);
}
.app-header .logo { height: 38px; cursor: pointer; transition: opacity var(--transition); }
.app-header .logo { height: 34px; cursor: pointer; transition: opacity var(--transition); }
.app-header .logo:hover { opacity: 0.85; }
.app-header .header-actions { display: flex; gap: 10px; align-items: center; }
.header-actions { display: flex; align-items: center; gap: 10px; }
/* ── App Footer ──────────────────────────────────────────── */
.app-footer {
background: var(--header-bg);
border-top: 1px solid rgba(0,80,140,0.10);
border-top: 1px solid var(--border);
padding: 18px clamp(16px, 4vw, 32px);
display: flex;
align-items: center;
@@ -33,7 +35,7 @@
gap: 12px;
margin-top: auto;
}
.app-footer img { height: 30px; }
.app-footer img { height: 28px; }
.app-footer small { color: var(--muted); font-size: 12px; }
/* ── Auth Layout — Split Card ────────────────────────────── */
@@ -46,19 +48,22 @@
.auth-brand {
width: 42%;
min-width: 280px;
background: linear-gradient(145deg, var(--navy) 0%, var(--blue) 100%);
position: relative;
background: #17211D;
background-image: var(--ruled), linear-gradient(155deg, #17211D 0%, var(--emerald-dark) 130%);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 48px 40px;
color: #fff;
gap: 24px;
gap: 22px;
overflow: hidden;
}
.auth-brand .brand-logo { height: 56px; }
.auth-brand h2 { color: #fff; font-size: clamp(20px,2.5vw,26px); text-align: center; margin: 0; }
.auth-brand p { color: rgba(255,255,255,0.75); font-size: 14px; text-align: center; line-height: 1.8; margin: 0; }
.auth-brand .brand-divider { width: 40px; height: 3px; background: var(--orange); border-radius: 2px; }
.auth-brand .brand-logo { height: 48px; opacity: 0.95; }
.auth-brand h2 { font-family: var(--font-display); color: #fff; font-size: clamp(20px,2.5vw,27px); text-align: center; margin: 0; font-weight: 500; }
.auth-brand p { color: rgba(255,255,255,0.68); font-size: 14px; text-align: center; line-height: 1.8; margin: 0; max-width: 320px; }
.auth-brand .brand-divider { width: 40px; height: 2px; background: var(--brass); border-radius: 2px; }
.auth-form-side {
flex: 1;
@@ -70,11 +75,10 @@
overflow-y: auto;
}
.auth-box { width: 100%; max-width: 420px; }
.auth-box h1 { font-size: clamp(20px,2.5vw,26px); margin-bottom: 6px; }
.auth-box h1 { font-size: clamp(21px,2.5vw,27px); margin-bottom: 6px; }
.auth-box .auth-subtitle { color: var(--muted); font-size: 14px; margin-bottom: 32px; }
.auth-links { margin-top: 20px; font-size: 13px; color: var(--muted); text-align: center; line-height: 2; }
/* Dark Theme Overrides for Auth Pages */
body.dark-theme .auth-shell { background: var(--bg); }
body.dark-theme .auth-form-side { background: var(--bg); }
body.dark-theme .auth-box h1 { color: var(--navy); }
@@ -89,13 +93,13 @@ body.dark-theme .auth-links a { color: var(--blue); }
width: 100%;
min-width: unset;
min-height: unset;
padding: 24px 20px;
padding: 26px 20px;
flex-direction: row;
justify-content: center;
gap: 16px;
}
.auth-brand p, .auth-brand .brand-divider { display: none; }
.auth-brand .brand-logo { height: 32px; }
.auth-brand .brand-logo { height: 30px; }
.auth-brand h2 { font-size: 15px; margin: 0; }
.auth-form-side { padding: 28px 20px; }
}
@@ -110,10 +114,10 @@ body.dark-theme .auth-links a { color: var(--blue); }
margin-bottom: 28px;
}
.page-heading h1, .page-heading h2 { margin: 0; }
.page-heading .page-meta { font-size: 13px; color: var(--muted); margin-top: 4px; }
.page-heading .page-meta { font-size: 13px; color: var(--muted); margin-top: 4px; font-family: var(--font-mono); }
/* ── Stat Cards Row ──────────────────────────────────────── */
.stat-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 16px; margin-bottom: 28px; }
.stat-row, .admin-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 16px; margin-bottom: 28px; }
.stat-card {
background: var(--card);
border: 1px solid var(--border);
@@ -125,12 +129,12 @@ body.dark-theme .auth-links a { color: var(--blue); }
transition: box-shadow var(--transition), transform var(--transition);
}
.stat-card:hover { box-shadow: var(--shadow-md); transform: translateY(-2px); }
.stat-card .stat-icon { font-size: 24px; margin-bottom: 4px; }
.stat-card .stat-value { font-size: 26px; font-weight: 700; color: var(--navy); line-height: 1; }
.stat-card .stat-label { font-size: 12px; color: var(--muted); font-weight: 500; text-transform: uppercase; letter-spacing: 0.4px; }
.stat-card.accent-blue { border-left: 4px solid var(--blue); }
.stat-card.accent-orange{ border-left: 4px solid var(--orange); }
.stat-card.accent-green { border-left: 4px solid var(--success); }
.stat-card .stat-icon { font-size: 22px; margin-bottom: 4px; color: var(--muted); }
.stat-card .stat-value, .stat-card .stat-val { font-family: var(--font-mono); font-size: 27px; font-weight: 600; color: var(--ink); line-height: 1; font-variant-numeric: tabular-nums; }
.stat-card .stat-label, .stat-card .stat-title { font-size: 11.5px; color: var(--muted); font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }
.stat-card.accent-blue { border-left: 3px solid var(--emerald); }
.stat-card.accent-orange{ border-left: 3px solid var(--brass); }
.stat-card.accent-green { border-left: 3px solid var(--success); }
/* ── Tab Bar ─────────────────────────────────────────────── */
.tab-bar {
@@ -144,7 +148,7 @@ body.dark-theme .auth-links a { color: var(--blue); }
.tab-bar::-webkit-scrollbar { display: none; }
.tab-btn {
padding: 12px 22px;
font-family: inherit;
font-family: var(--font-body);
font-size: 14px;
font-weight: 500;
color: var(--muted);
@@ -157,8 +161,8 @@ body.dark-theme .auth-links a { color: var(--blue); }
white-space: nowrap;
flex-shrink: 0;
}
.tab-btn:hover { color: var(--navy); }
.tab-btn.active { color: var(--blue); border-bottom-color: var(--blue); font-weight: 600; }
.tab-btn:hover { color: var(--ink); }
.tab-btn.active { color: var(--emerald); border-bottom-color: var(--brass); font-weight: 600; }
.tab-panel { display: none; }
.tab-panel.active{ display: block; animation: fadeIn 0.25s ease; }
@@ -175,34 +179,34 @@ body.dark-theme .auth-links a { color: var(--blue); }
transition: transform var(--transition), box-shadow var(--transition), border-color var(--transition);
position: relative;
}
.user-card:hover { transform: translateY(-3px); box-shadow: var(--shadow-md); border-color: #c5d9ee; }
.user-card:hover { transform: translateY(-3px); box-shadow: var(--shadow-md); border-color: #cfc7ad; }
.click-layer { position: absolute; inset: 0; z-index: 0; }
.user-top { display: flex; align-items: center; gap: 14px; min-width: 0; }
.user-avatar {
width: 46px; height: 46px; border-radius: 50%;
background: linear-gradient(135deg, var(--header-bg), var(--blue-light));
width: 44px; height: 44px; border-radius: 50%;
background: var(--emerald);
display: flex; align-items: center; justify-content: center;
font-weight: 700; font-size: 17px; color: var(--navy);
flex-shrink: 0; border: 2px solid rgba(0,119,200,0.15);
font-weight: 700; font-size: 16px; color: #fff;
flex-shrink: 0; font-family: var(--font-display);
}
.user-info { min-width: 0; flex: 1; }
.user-info .u-name { font-weight: 600; color: var(--navy); font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.user-info .u-name { font-weight: 600; color: var(--ink); font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.user-info .u-email { font-size: 12px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-top: 2px; }
.user-bottom { display: flex; align-items: center; justify-content: space-between; gap: 8px; position: relative; z-index: 10; flex-wrap: wrap; }
/* ── Role Controls ───────────────────────────────────────── */
.role-controls { display: flex; align-items: center; gap: 8px; position: relative; z-index: 10; }
.role-select { padding: 6px 10px; border: 1.5px solid var(--border); border-radius: var(--radius-sm); font-size: 13px; font-family: inherit; cursor: pointer; background: #fff; flex: 1; transition: border-color var(--transition); }
.role-select:focus { outline: none; border-color: var(--blue); }
.role-save-btn { padding: 6px 14px; background: var(--blue); color: #fff; border: none; border-radius: var(--radius-sm); font-size: 12px; font-weight: 600; cursor: pointer; transition: background var(--transition); white-space: nowrap; }
.role-save-btn:hover { background: var(--blue-dark); }
.role-select { padding: 6px 10px; border: 1.5px solid var(--border); border-radius: var(--radius-sm); font-size: 13px; font-family: var(--font-body); cursor: pointer; background: #fff; flex: 1; transition: border-color var(--transition); }
.role-select:focus { outline: none; border-color: var(--emerald); }
.role-save-btn { padding: 6px 14px; background: var(--emerald); color: #fff; border: none; border-radius: var(--radius-sm); font-size: 12px; font-weight: 600; cursor: pointer; transition: background var(--transition); white-space: nowrap; }
.role-save-btn:hover { background: var(--emerald-dark); }
/* ── Info Card (User Detail) ─────────────────────────────── */
.info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 24px; }
@media (max-width: 640px) { .info-grid { grid-template-columns: 1fr; } }
.info-item { display: flex; flex-direction: column; gap: 3px; }
.info-item .info-label { font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; color: var(--muted); font-weight: 600; }
.info-item .info-value { font-size: 15px; font-weight: 500; color: var(--navy); }
.info-item .info-value { font-size: 15px; font-weight: 500; color: var(--ink); }
/* ── Document Row ────────────────────────────────────────── */
.doc-row {
@@ -212,19 +216,19 @@ body.dark-theme .auth-links a { color: var(--blue); }
padding: 14px 16px;
border-radius: var(--radius-sm);
border: 1px solid var(--border);
background: #fafcff;
transition: border-color var(--transition), background var(--transition);
background: var(--paper);
transition: border-color var(--transition), background var(--transition), transform var(--transition), box-shadow var(--transition);
margin-bottom: 10px;
}
.doc-row:hover { border-color: #c5d9ee; background: var(--blue-light); }
.doc-row:hover { border-color: #cfc7ad; background: #fff; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(23,33,29,0.06); }
.doc-row-left { display: flex; flex-direction: column; gap: 4px; flex: 1; min-width: 0; }
.doc-row-name { font-weight: 600; font-size: 13px; color: var(--navy); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.doc-row-name { font-weight: 600; font-size: 13px; color: var(--ink); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.doc-row-type { font-size: 12px; color: var(--muted); }
.doc-row-actions { display: flex; gap: 8px; align-items: center; flex-shrink: 0; }
/* ── Drop Zone ───────────────────────────────────────────── */
.drop-zone {
border: 2px dashed #b8cfdf;
border: 2px dashed #cfc7ad;
border-radius: var(--radius-md);
padding: 36px 24px;
text-align: center;
@@ -233,12 +237,12 @@ body.dark-theme .auth-links a { color: var(--blue); }
cursor: pointer;
}
.drop-zone:hover, .drop-zone.drag-over {
border-color: var(--blue);
background: var(--blue-light);
color: var(--blue);
border-color: var(--emerald);
background: var(--emerald-light);
color: var(--emerald);
}
.drop-zone .drop-icon { font-size: 36px; margin-bottom: 10px; }
.drop-zone .drop-title { font-weight: 600; font-size: 15px; color: var(--navy); }
.drop-zone .drop-icon { font-size: 34px; margin-bottom: 10px; }
.drop-zone .drop-title { font-weight: 600; font-size: 15px; color: var(--ink); }
.drop-zone .drop-hint { font-size: 13px; margin-top: 4px; }
/* ── Search Bar ──────────────────────────────────────────── */
@@ -253,7 +257,7 @@ body.dark-theme .auth-links a { color: var(--blue); }
transition: border-color var(--transition), box-shadow var(--transition);
max-width: 360px;
}
.search-bar:focus-within { border-color: var(--blue); box-shadow: 0 0 0 3px rgba(0,119,200,0.10); }
.search-bar:focus-within { border-color: var(--emerald); box-shadow: 0 0 0 3px rgba(31,93,70,0.10); }
.search-bar input { border: none; outline: none; font-family: inherit; font-size: 14px; width: 100%; background: transparent; }
.search-bar .search-icon { color: var(--muted); font-size: 16px; flex-shrink: 0; }
@@ -262,7 +266,7 @@ body.dark-theme .auth-links a { color: var(--blue); }
display: flex;
align-items: center;
gap: 12px;
background: var(--bg);
background: var(--paper);
border-radius: var(--radius-sm);
padding: 10px 16px;
width: fit-content;
@@ -278,32 +282,24 @@ body.dark-theme .auth-links a { color: var(--blue); }
display: flex; align-items: center; justify-content: center;
transition: border-color var(--transition), background var(--transition);
}
.timeline-control .tl-btn:hover { border-color: var(--blue); background: var(--blue-light); color: var(--blue); }
.timeline-control .tl-value { font-size: 20px; font-weight: 700; color: var(--navy); min-width: 32px; text-align: center; }
.timeline-control .tl-btn:hover { border-color: var(--emerald); background: var(--emerald-light); color: var(--emerald); }
.timeline-control .tl-value { font-family: var(--font-mono); font-size: 20px; font-weight: 600; color: var(--ink); min-width: 32px; text-align: center; }
.timeline-control .tl-label { font-size: 12px; color: var(--muted); }
/* ── Approval Table ──────────────────────────────────────── */
.approval-table { width: 100%; border-collapse: collapse; }
.approval-table th, .approval-table td { padding: 12px 14px; border-bottom: 1px solid var(--border); font-size: 13px; }
.approval-table th { background: #f5f8fb; font-weight: 600; color: var(--muted); text-align: left; font-size: 12px; text-transform: uppercase; letter-spacing: 0.4px; }
.approval-table th { background: var(--paper); font-weight: 600; color: var(--muted); text-align: left; font-size: 11.5px; text-transform: uppercase; letter-spacing: 0.4px; }
.approval-table tr:last-child td { border-bottom: none; }
.approval-table tr:hover td { background: #fafcff; }
.approval-table tr:hover td { background: var(--paper); }
/* ── Toggle Switch (approve/reject) ─────────────────────── */
.review-toggle {
display: flex;
gap: 6px;
}
.review-toggle { display: flex; gap: 6px; }
.review-toggle label {
display: flex;
align-items: center;
gap: 5px;
padding: 5px 12px;
border-radius: var(--radius-pill);
display: flex; align-items: center; gap: 5px;
padding: 5px 12px; border-radius: var(--radius-pill);
border: 1.5px solid var(--border);
font-size: 12px;
font-weight: 600;
cursor: pointer;
font-size: 12px; font-weight: 600; cursor: pointer;
transition: all var(--transition);
}
.review-toggle input[type=checkbox] { display: none; }
@@ -319,166 +315,543 @@ body.dark-theme .auth-links a { color: var(--blue); }
gap: 16px;
padding: 16px 20px;
border-radius: var(--radius-md);
background: linear-gradient(90deg, #e3f2fd, #f0f9ff);
border: 1px solid #b3d9f5;
background: var(--emerald-light);
border: 1px solid rgba(31,93,70,0.2);
margin-bottom: 24px;
}
.engagement-banner .banner-icon { font-size: 28px; flex-shrink: 0; }
.engagement-banner .banner-icon { font-size: 26px; flex-shrink: 0; color: var(--emerald); }
.engagement-banner .banner-text { flex: 1; }
.engagement-banner .banner-text strong { display: block; font-size: 14px; color: var(--navy); }
.engagement-banner .banner-text strong { display: block; font-size: 14px; color: var(--ink); }
.engagement-banner .banner-text span { font-size: 13px; color: var(--muted); }
.engagement-banner.acknowledged { background: var(--success-bg); border-color: #a5d6a7; }
.engagement-banner.acknowledged { background: var(--success-bg); border-color: rgba(31,93,70,0.25); }
/* ── Empty State ─────────────────────────────────────────── */
.empty-state {
padding: 48px 24px;
text-align: center;
color: var(--muted);
background: var(--paper);
border: 1px dashed var(--border);
border-radius: var(--radius-md);
}
.empty-state .empty-icon { font-size: 42px; margin-bottom: 12px; opacity: 0.6; }
.empty-state .empty-title { font-size: 15px; font-weight: 600; color: var(--navy); margin-bottom: 6px; }
.empty-state .empty-icon { font-size: 40px; margin-bottom: 12px; opacity: 0.5; color: var(--muted); }
.empty-state .empty-title { font-size: 15px; font-weight: 600; color: var(--ink); margin-bottom: 6px; }
.empty-state .empty-hint { font-size: 13px; }
/* ── Marketing Navbar ────────────────────────────────────── */
.mkt-navbar {
position: absolute;
top: 0; left: 0;
width: 100%;
z-index: 20;
}
.mkt-nav-inner {
width: min(1200px, 96%);
margin: auto;
padding: 18px 12px;
display: flex;
align-items: center;
justify-content: space-between;
}
.mkt-nav-logo { height: clamp(38px,5vw,54px); object-fit: contain; }
.mkt-nav-menu { display: flex; gap: 32px; align-items: center; }
.mkt-nav-menu a { color: #fff; font-size: 15px; font-weight: 500; text-decoration: none; transition: color var(--transition); }
.mkt-nav-menu a:hover { color: #FFD28C; }
.mkt-hamburger { display: none; flex-direction: column; gap: 5px; cursor: pointer; }
.mkt-hamburger span { width: 26px; height: 2.5px; background: #fff; border-radius: 2px; }
.table-responsive { overflow-x: auto; }
.admin-table { width: 100%; border-collapse: collapse; }
.admin-table th, .admin-table td { padding: 12px 16px; text-align: left; border-bottom: 1px solid var(--border); font-size: 13px; }
.admin-table th { background: var(--paper); font-weight: 600; color: var(--muted); text-transform: uppercase; font-size: 11.5px; letter-spacing: 0.5px; }
.admin-table tr:last-child td { border-bottom: none; }
.admin-table tr:hover td { background: var(--paper); }
/* ── Chatbot Footer ─────────────────────────────────────── */
.chatbot-footer {
padding: 16px;
border-top: 1px solid var(--border);
background: var(--paper);
text-align: center;
font-size: 13px;
color: var(--muted);
border-radius: 0 0 var(--radius-md) var(--radius-md);
}
.search-wrap { position: relative; display: flex; align-items: center; }
/* ── JS-extracted components (upload/review) ─────────────── */
.doc-row-wrapper { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
.btn-approve { background: var(--success-bg); color: var(--success); border: 1px solid rgba(31,93,70,0.3); border-radius: var(--radius-sm); }
.btn-reject { background: var(--error-bg); color: var(--error); border: 1px solid rgba(166,58,58,0.3); border-radius: var(--radius-sm); }
.reject-box { display: none; margin-top: 10px; }
.reject-textarea { width: 100%; padding: 10px; border-radius: var(--radius-sm); border: 1.5px solid var(--border); font-family: inherit; font-size: 13px; resize: vertical; }
.admin-doc-actions { display: flex; gap: 8px; flex-shrink: 0; }
.admin-docs-table { width: 100%; border-collapse: collapse; font-size: 13px; }
.admin-docs-td { padding: 10px 12px; color: #3E463F; }
.admin-docs-th { padding: 10px 12px; color: var(--muted); font-weight: 600; text-align: left; border-bottom: 2px solid var(--border); }
.btn-download-pill { background: var(--emerald); color: #fff; border: none; border-radius: var(--radius-sm); font-weight: 500; }
.btn-download-pill:hover { opacity: 0.9; }
.btn-upload-pill { background: var(--brass); color: #fff; border: none; border-radius: var(--radius-sm); font-weight: 500; cursor: pointer; padding: 8px 16px; display: inline-flex; align-items: center; gap: 8px; }
.btn-upload-pill:hover { opacity: 0.9; }
/* ── Dark theme overrides for the above ─────────────────── */
body.dark-theme .app-header { background: var(--header-bg); border-color: var(--border); }
body.dark-theme .admin-table th { background: var(--card); }
body.dark-theme .chatbot-footer { background: var(--card); border-color: var(--border); }
body.dark-theme .doc-row, body.dark-theme .stat-card, body.dark-theme .user-card { background: var(--card); }
body.dark-theme .search-bar, body.dark-theme .role-select { background: var(--card); color: var(--navy); }
body.dark-theme .search-bar input { color: var(--navy); }
/* ============================================================
RESPONSIVE IMPROVEMENTS — Multi-screen support
Breakpoints: 480px (xs), 640px (sm), 768px (md), 1024px (lg)
============================================================ */
/* ── Admin Dashboard — users grid ───────────────────────── */
.users-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
gap: 16px;
margin-top: 4px;
}
@media (max-width: 640px) {
.users-grid {
grid-template-columns: 1fr;
gap: 12px;
}
}
/* ── Admin Stats — 4 cards on desktop, 2x2 on tablet, 1 col on mobile ── */
@media (max-width: 900px) {
.mkt-nav-menu {
display: none;
position: absolute;
top: 72px; left: 0;
.admin-stats {
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 480px) {
.admin-stats {
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.stat-card {
padding: 14px 16px;
}
.stat-card .stat-value,
.stat-card .stat-val {
font-size: 22px;
}
}
/* ── App Header — collapse actions on small screens ─────── */
@media (max-width: 480px) {
.app-header {
padding: 0 14px;
height: 58px;
gap: 10px;
}
.app-header .logo {
height: 28px;
}
.header-actions {
gap: 6px;
}
.header-actions .btn {
padding: 6px 10px;
font-size: 12px;
}
.header-actions .btn-sm {
padding: 5px 8px;
font-size: 11px;
}
}
/* ── Page Heading — stack on mobile ─────────────────────── */
@media (max-width: 640px) {
.page-heading {
flex-direction: column;
align-items: flex-start;
gap: 10px;
margin-bottom: 20px;
}
.page-heading h1 {
font-size: clamp(20px, 5vw, 26px);
}
}
/* ── Tab Bar — tighten padding on small screens ──────────── */
@media (max-width: 640px) {
.tab-btn {
padding: 10px 14px;
font-size: 13px;
}
}
@media (max-width: 400px) {
.tab-btn {
padding: 8px 10px;
font-size: 12px;
}
}
/* ── User Card bottom badges — wrap cleanly ─────────────── */
.user-bottom {
flex-wrap: wrap;
gap: 6px;
}
/* ── Document slots — reflow on mobile ──────────────────── */
@media (max-width: 640px) {
.doc-slot {
flex-direction: column;
align-items: flex-start;
gap: 10px;
padding: 12px 14px;
}
.doc-slot-actions {
width: 100%;
background: var(--navy);
display: flex;
flex-wrap: wrap;
gap: 8px;
}
}
/* ── Admin Table — readable on small screens ─────────────── */
@media (max-width: 768px) {
.admin-table th,
.admin-table td {
padding: 10px 10px;
font-size: 12px;
}
}
@media (max-width: 480px) {
.admin-table th,
.admin-table td {
padding: 8px 8px;
font-size: 11px;
}
/* Hide less-important columns on very small screens */
.admin-table .col-hide-xs {
display: none;
}
}
/* ── Card & Card-flat — reduce padding on mobile ────────── */
@media (max-width: 480px) {
.card {
padding: 16px;
}
.card-flat {
padding: 14px;
}
}
/* ── Page main widths — full bleed on small screens ──────── */
@media (max-width: 640px) {
.page-main,
.page-main-wide {
padding: 0 12px;
margin-top: 20px;
margin-bottom: 20px;
}
}
/* ── Admin User Detail — user info bar ──────────────────── */
@media (max-width: 768px) {
/* the user info bar flex row */
.card > div[style*="justify-content:space-between"] {
flex-direction: column;
align-items: flex-start !important;
}
}
/* ── Upload pages — tax year selector row ────────────────── */
@media (max-width: 640px) {
/* page-heading flex row with year selector */
.page-heading > div:last-child {
align-self: flex-start;
}
}
/* ── Timeline control — center on mobile ────────────────── */
@media (max-width: 640px) {
.timeline-control {
width: 100%;
justify-content: center;
}
}
/* ── Toast — full width on mobile ───────────────────────── */
@media (max-width: 480px) {
.toast-container {
left: 12px;
right: 12px;
transform: none;
bottom: 16px;
}
.toast {
min-width: unset;
width: 100%;
}
}
/* ── Chatbot FAB — smaller on mobile ────────────────────── */
@media (max-width: 480px) {
.chatbot-fab {
width: 50px;
height: 50px;
bottom: 16px;
right: 16px;
font-size: 20px;
}
.chatbot-window {
width: calc(100vw - 24px);
right: 12px;
bottom: 76px;
}
}
/* ── Auth shell — improve narrow portrait phones ────────── */
@media (max-width: 400px) {
.auth-form-side {
padding: 20px 16px;
}
.auth-box {
max-width: 100%;
}
}
/* ── Marketing Navbar — tighter on 768px tablets ────────── */
@media (max-width: 768px) {
.nav-container {
padding: 14px 12px;
}
}
/* ── Services / About page blocks — better mobile spacing ── */
@media (max-width: 640px) {
.about-wrapper,
.services-wrapper {
margin: 48px auto;
gap: 28px;
}
.about-block,
.service-block {
padding: 18px;
}
}
/* ── Contact page — full-width form on mobile ───────────── */
@media (max-width: 640px) {
.contact-container {
flex-direction: column;
}
.contact-info,
.contact-form {
flex: 1 1 100%;
width: 100%;
}
.form-row {
flex-direction: column;
gap: 0;
padding: 8px 0 20px;
}
.mkt-nav-menu a { padding: 12px 28px; width: 100%; }
.mkt-nav-menu.open { display: flex; }
.mkt-hamburger { display: flex; }
}
/* ── Marketing Footer ────────────────────────────────────── */
.mkt-footer { background: var(--header-bg); border-top: 4px solid var(--blue); margin-top: auto; }
.mkt-footer-top {
width: min(1200px, 92%);
margin: auto;
padding: 40px 0;
display: flex;
justify-content: space-between;
gap: 40px;
flex-wrap: wrap;
/* ── Footer — stack on mobile ───────────────────────────── */
@media (max-width: 640px) {
.footer-top,
.mkt-footer-top {
flex-direction: column;
gap: 28px;
padding: 36px 0 28px;
}
}
.mkt-footer-logo { width: clamp(120px,20vw,160px); }
.mkt-footer-links { display: flex; flex-direction: column; gap: 8px; }
.mkt-footer-links h4 { color: var(--blue); margin-bottom: 4px; font-size: 14px; }
.mkt-footer-links a { color: var(--navy); font-size: 14px; font-weight: 500; transition: color var(--transition); }
.mkt-footer-links a:hover { color: var(--blue); }
.mkt-footer-bottom { background: var(--footer-bot); text-align: center; padding: 12px; font-size: 13px; color: #555; }
/* --- JS Extracted Components --- */
/* ── Expandable summary block (AI summaries) ─────────────── */
@media (max-width: 640px) {
/* give AI summary blocks full width */
div[style*="blue-light"] {
padding: 10px !important;
}
}
.doc-row-wrapper {
/* ── Global touch targets — ensure 44px min on mobile ───── */
@media (max-width: 768px) {
.btn-sm {
min-height: 36px;
}
.tab-btn {
min-height: 42px;
}
select,
.select-input,
.input {
min-height: 42px;
}
}
/* ============================================================
ADMIN USER DETAIL — Responsive layout classes
Replaces all inline flex styles that couldn't be overridden
============================================================ */
/* ── User info bar ───────────────────────────────────────── */
.aud-bar-inner {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
gap: 16px;
}
.aud-bar-left {
display: flex;
align-items: center;
gap: 16px;
flex: 1;
min-width: 0;
}
.aud-bar-actions {
display: flex;
gap: 10px;
align-items: center;
flex-wrap: wrap;
}
.aud-year-picker {
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 4px;
padding-left: 16px;
border-left: 1px solid var(--border);
}
@media (max-width: 640px) {
.aud-bar-inner {
flex-direction: column;
align-items: flex-start;
}
.aud-bar-left {
width: 100%;
}
.aud-bar-actions {
width: 100%;
flex-wrap: wrap;
gap: 8px;
}
.aud-year-picker {
align-items: flex-start;
border-left: none;
border-top: 1px solid var(--border);
padding-left: 0;
padding-top: 10px;
width: 100%;
flex-direction: row;
align-items: center;
gap: 8px;
}
.aud-year-picker label {
white-space: nowrap;
}
.aud-year-picker select {
flex: 1;
}
}
/* ── Doc review layout (main + sidebar) ─────────────────── */
.doc-review-layout {
display: flex;
gap: 20px;
align-items: flex-start;
}
.doc-review-main {
flex: 2;
min-width: 0; /* prevents flex child from overflowing */
}
.doc-review-sidebar {
flex: 0 0 240px; /* fixed 240px sidebar, doesn't shrink */
width: 240px;
}
@media (max-width: 768px) {
.doc-review-layout {
flex-direction: column;
}
.doc-review-sidebar {
flex: unset;
width: 100%;
order: -1; /* show Filing Timeline ABOVE the doc list on mobile */
}
.doc-review-sidebar .card-flat {
flex-direction: row !important;
align-items: center;
flex-wrap: wrap;
gap: 12px;
}
.doc-review-sidebar h3 {
width: 100%;
margin-bottom: 0 !important;
}
.doc-review-sidebar .timeline-control {
flex: 1;
}
.doc-review-sidebar .btn {
flex: 1;
min-width: 180px;
}
}
/* ── Individual doc review row ──────────────────────────── */
.doc-review-row {
display: flex;
flex-direction: column;
gap: 8px;
padding: 14px 0;
border-bottom: 1px solid var(--border);
}
.doc-review-row:last-child {
border-bottom: none;
}
.doc-review-row-top {
display: flex;
align-items: flex-start;
gap: 16px;
}
.doc-review-info {
flex: 1;
min-width: 0;
}
.doc-review-actions {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
flex-wrap: wrap;
}
.btn-approve {
background: var(--success-bg);
color: var(--success);
border: 1px solid #a5d6a7;
border-radius: var(--radius-pill);
@media (max-width: 520px) {
.doc-review-row-top {
flex-direction: column;
gap: 10px;
}
.doc-review-actions {
width: 100%;
justify-content: flex-start;
}
.doc-review-actions .btn {
flex: 1;
min-width: 70px;
justify-content: center;
}
}
.btn-reject {
background: var(--error-bg);
color: var(--error);
border: 1px solid #ef9a9a;
border-radius: var(--radius-pill);
}
.reject-box {
display: none;
margin-top: 10px;
}
.reject-textarea {
width: 100%;
padding: 10px;
/* ── AI Summary block ────────────────────────────────────── */
.ai-summary-block {
padding: 12px;
background-color: var(--blue-light);
border-radius: var(--radius-sm);
border: 1.5px solid var(--border);
font-family: inherit;
font-size: 13px;
resize: vertical;
border: 1px solid var(--border);
width: 100%;
margin-top: 4px;
}
.admin-doc-actions {
.ai-summary-label {
font-size: 11px;
font-weight: 700;
color: var(--emerald);
margin-bottom: 8px;
text-transform: uppercase;
letter-spacing: 0.5px;
display: flex;
gap: 8px;
flex-shrink: 0;
align-items: center;
}
.admin-docs-table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
}
.admin-docs-td {
padding: 10px 12px;
color: #444;
}
.admin-docs-th {
padding: 10px 12px;
color: #555;
font-weight: 500;
text-align: left;
border-bottom: 2px solid var(--border);
}
/* -- Pill Buttons for Document Actions ----------------------- */
.btn-download-pill {
background: var(--blue);
color: #fff;
border: none;
border-radius: var(--radius-sm);
font-weight: 500;
}
.btn-download-pill:hover {
opacity: 0.9;
}
.btn-upload-pill {
background: var(--orange);
color: #fff;
border: none;
border-radius: var(--radius-sm);
font-weight: 500;
cursor: pointer;
}
.btn-upload-pill:hover {
opacity: 0.9;
/* ── Doc count chips — user info bar ────────────────────── */
.doc-count-chip {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 12px;
font-family: var(--font-mono);
background: var(--paper);
border: 1px solid var(--border);
border-radius: var(--radius-xs);
padding: 3px 8px;
white-space: nowrap;
}
File diff suppressed because it is too large Load Diff
+126 -101
View File
@@ -6,77 +6,113 @@ 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. These will be visible to the user." }
{ 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." }
],
"User Management": [
{ q: "How do I see user details?", a: "Simply click on any user in the Admin Dashboard table. This will take you to their detailed view where you can see their info and all their documents." },
{ q: "Can I add another admin?", a: "Currently, 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 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." }
],
"Notifications": [
{ q: "How are users notified?", a: "Users receive automated emails when they sign up, when their documents are ready for review, and when you approve or reject their documents." }
{ q: "How are users notified?", a: "Users receive automated emails on signup, document submission, and when you approve or reject their documents." }
]
};
const CATEGORY_ICONS = {
"Document Review": "📑",
"User Management": "👥",
"Notifications": "🔔"
"Notifications": "🔔",
};
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" target="_blank" rel="noopener noreferrer" style="color:var(--blue);text-decoration:underline">$1</a>')
.replace(/\n/g, '<br/>');
};
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');
const [isOpen, setIsOpen] = useState(false);
const [messages, setMessages] = useState([]);
const [view, setView] = useState('menu'); // menu | category | chat
const [activeCategory, setActiveCategory] = useState(null);
const [inputText, setInputText] = useState("");
const [isTyping, setIsTyping] = useState(false);
const [inputText, setInputText] = useState("");
const [menuInput, setMenuInput] = useState(""); // free-text from menu
const [isTyping, setIsTyping] = useState(false);
const chatEndRef = useRef(null);
// Close chatbot when navigating
useEffect(() => { setIsOpen(false); }, [location.pathname]);
useEffect(() => {
setIsOpen(false);
}, [location.pathname]);
useEffect(() => {
if (chatEndRef.current) {
chatEndRef.current.scrollIntoView({ behavior: 'smooth' });
}
chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages, view]);
const toggleChat = () => setIsOpen(!isOpen);
const toggleChat = () => setIsOpen(o => !o);
/* ── quick-action: system overview ── */
const handleAdminStatusCheck = async () => {
setMessages([...messages, { type: 'user', text: 'Give me a system overview.' }]);
setMessages(prev => [...prev, { type: '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 }]);
} else {
setMessages(prev => [...prev, { type: 'bot', text: 'Sorry, I could not fetch the system status right now.' }]);
setMessages(prev => [...prev, { type: 'bot', text: 'Could not fetch system status right now.' }]);
}
} catch (err) {
setMessages(prev => [...prev, { type: 'bot', text: 'Network error occurred.' }]);
} catch {
setMessages(prev => [...prev, { type: 'bot', text: 'Network error.' }]);
}
};
const selectCategory = (cat) => {
setActiveCategory(cat);
setView('category');
/* ── send a message to /ask ── */
const sendMessage = async (text, existingMessages) => {
const userMsg = { type: 'user', role: 'user', text };
const allMessages = [...(existingMessages ?? messages), userMsg];
setMessages(allMessages);
setInputText("");
setMenuInput("");
setView('chat');
setIsTyping(true);
try {
const res = await authFetch('/api/chatbot/ask', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
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);
}
};
const handleSendMessage = async (e) => {
e.preventDefault();
if (!inputText.trim()) return;
await sendMessage(inputText.trim());
};
const handleMenuAsk = async (e) => {
e.preventDefault();
if (!menuInput.trim()) return;
await sendMessage(menuInput.trim(), []);
};
const askFaq = (faq) => {
@@ -84,139 +120,128 @@ export default function AdminChatbot() {
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 {
// Convert messages to format expected by backend
const backendMessages = currentMessages.map(m => ({
role: m.role || (m.type === 'bot' ? 'assistant' : 'user'),
content: m.text,
reasoning_details: m.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();
const contentText = data.content || "Sorry, I couldn't understand that.";
const reasoning = data.reasoning_details;
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: contentText, reasoning_details: reasoning }]);
} else {
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Sorry, I am having trouble connecting to the server.' }]);
}
} catch (err) {
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Network error occurred. Please try again.' }]);
} finally {
setIsTyping(false);
}
};
if (!user || (user.role !== 'admin' && user.role !== 'super_admin') || !location.pathname.startsWith('/admin')) {
return null;
return null;
}
return (
<>
<button className={`chatbot-fab ${isOpen ? 'open' : ''}`} onClick={toggleChat} aria-label="Open admin assistant" style={{background: 'linear-gradient(135deg, var(--navy) 0%, var(--blue) 100%)'}}>
<button
className={`chatbot-fab ${isOpen ? 'open' : ''}`}
onClick={toggleChat}
aria-label="Open admin assistant"
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">
<div className="chatbot-header" style={{background: 'linear-gradient(135deg, var(--navy) 0%, #005fa3 100%)'}}>
{/* header */}
<div className="chatbot-header" style={{ background: 'var(--ink)' }}>
<div className="bot-avatar">🤖</div>
<div className="bot-info">
<h4>Admin Assistant</h4>
<span>System Insights & Help</span>
<span>Live system insights</span>
</div>
<button className="close-chat" onClick={toggleChat}>✕</button>
</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>How can we help you today?</p>
<p>What do you need today?</p>
</div>
<button className="quick-reply-btn" style={{display: 'flex', width: '100%', marginBottom: '8px'}} onClick={handleAdminStatusCheck}>
<span className="qr-icon">📊</span>
Check System Status
{/* 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)}
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>
</form>
<button className="quick-reply-btn" style={{ display: 'flex', width: '100%', marginBottom: '8px' }} onClick={handleAdminStatusCheck}>
<span className="qr-icon">📊</span> System Overview
</button>
{Object.keys(FAQ_DATA).map(cat => (
<button key={cat} className="quick-reply-btn" style={{display: 'flex', width: '100%', marginBottom: '8px'}} onClick={() => selectCategory(cat)}>
<span className="qr-icon">{CATEGORY_ICONS[cat]}</span> {cat} FAQ
<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={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 to menu
</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)}>
<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={resetToMenu} style={{display: 'flex', width: '100%', marginBottom: '16px', background: 'transparent', border: 'none'}}>
<button className="quick-reply-btn" onClick={() => setView('menu')} style={{ display: 'flex', width: '100%', marginBottom: '16px', background: 'transparent', border: 'none' }}>
← Back to menu
</button>
{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...
Admin Assistant is typing…
</div>
)}
<div ref={chatEndRef} />
</>
)}
</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"
<input
type="text"
value={inputText}
onChange={(e) => setInputText(e.target.value)}
placeholder="Ask a question..."
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(--blue)', color: '#fff', border: 'none', borderRadius: 'var(--radius-pill)', padding: '8px 16px', cursor: 'pointer' }}>
<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 }}>Admin tools & shortcuts</p>
<p style={{ margin: 0, fontSize: '13px', color: 'var(--muted)' }}>Admin tools &amp; shortcuts</p>
)}
</div>
</div>
+50 -13
View File
@@ -48,6 +48,7 @@ export default function Chatbot() {
const [view, setView] = useState('menu'); // menu, category, chat
const [activeCategory, setActiveCategory] = useState(null);
const [inputText, setInputText] = useState("");
const [menuInput, setMenuInput] = useState(""); // free-text from menu
const [isTyping, setIsTyping] = useState(false);
const chatEndRef = useRef(null);
@@ -113,30 +114,51 @@ export default function Chatbot() {
setIsTyping(true);
try {
// Convert messages to format expected by backend
const backendMessages = currentMessages.map(m => ({
role: m.role || (m.type === 'bot' ? 'assistant' : 'user'),
content: m.text,
reasoning_details: m.reasoning_details || null
reasoning_details: null,
}));
const res = await authFetch('/api/chatbot/ask', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ messages: backendMessages })
body: JSON.stringify({ messages: backendMessages }),
});
if (res.ok) {
const data = await res.json();
// Extract content and optional reasoning details
const contentText = data.content || "Sorry, I couldn't understand that.";
const reasoning = data.reasoning_details;
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: contentText, reasoning_details: reasoning }]);
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: 'Sorry, I am having trouble connecting to the server.' }]);
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Having trouble connecting. Please try again.' }]);
}
} catch (err) {
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Network error occurred. 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);
}
@@ -171,6 +193,21 @@ 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)}
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>
</form>
{user && (
<button className="quick-reply-btn" style={{display: 'flex', width: '100%', marginBottom: '8px'}} onClick={handleDocStatusCheck}>
<span className="qr-icon">📋</span>
@@ -227,7 +264,7 @@ export default function Chatbot() {
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(--navy)', color: '#fff', border: 'none', borderRadius: 'var(--radius-pill)', padding: '8px 16px', cursor: 'pointer' }}>
<button type="submit" style={{ background: 'var(--emerald)', color: '#fff', border: 'none', borderRadius: 'var(--radius-pill)', padding: '8px 16px', cursor: 'pointer' }}>
Send
</button>
</form>
@@ -0,0 +1,63 @@
import { useState } from 'react';
import ExpandableValue from './ExpandableValue';
export default function ExpandableSummaryBlock({ extractedData }) {
const [expanded, setExpanded] = useState(false);
const entries = Object.entries(extractedData);
if (entries.length === 0) {
return (
<div style={{ fontSize: '12px', color: 'var(--muted)', fontStyle: 'italic' }}>
Blank form / No user data found.
</div>
);
}
const showToggle = entries.length > 3;
const entriesToShow = expanded ? entries : entries.slice(0, 3);
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
{entriesToShow.map(([key, value]) => (
<div key={key}>
{/* Field label — uppercase, bold, navy */}
<div style={{
fontSize: '11px',
color: 'var(--navy)',
fontWeight: 700,
textTransform: 'uppercase',
letterSpacing: '0.6px',
marginBottom: '2px',
}}>
{key}
</div>
{/* Field value — bold navy */}
<div style={{ fontSize: '13px', fontWeight: 600, color: 'var(--navy)' }}>
<ExpandableValue value={value} isArray={Array.isArray(value)} />
</div>
</div>
))}
{showToggle && (
<button
type="button"
onClick={() => setExpanded(!expanded)}
style={{
background: 'var(--paper)',
border: '1px solid var(--border)',
color: 'var(--emerald)',
fontSize: '12px',
fontWeight: 600,
padding: '5px 12px',
borderRadius: 'var(--radius-sm)',
cursor: 'pointer',
alignSelf: 'flex-start',
marginTop: '4px',
}}
>
{expanded ? '− Show Less' : `+ Show ${entries.length - 3} More Fields`}
</button>
)}
</div>
);
}
@@ -0,0 +1,75 @@
import { useState } from 'react';
export default function ExpandableValue({ value, isArray }) {
const [expanded, setExpanded] = useState(false);
if (isArray) {
if (!value || value.length === 0) return <span>—</span>;
const showToggle = value.length > 3;
const itemsToShow = expanded ? value : value.slice(0, 3);
return (
<div style={{ display: 'flex', flexDirection: 'column', width: '100%' }}>
<ul style={{ margin: '4px 0 0 16px', padding: 0, fontWeight: 600, color: 'var(--navy)' }}>
{itemsToShow.map((item, idx) => (
<li key={idx} style={{ marginBottom: '4px', lineHeight: '1.4' }}>{item}</li>
))}
</ul>
{showToggle && (
<button
type="button"
onClick={() => setExpanded(!expanded)}
style={{
background: 'none',
border: 'none',
color: 'var(--primary)',
fontSize: '12px',
fontWeight: 600,
padding: '4px 0',
marginTop: '4px',
cursor: 'pointer',
display: 'inline-flex',
alignSelf: 'flex-start',
gap: '4px'
}}
>
{expanded ? 'Show Less' : `+ ${value.length - 3} More`}
</button>
)}
</div>
);
}
const text = value !== null && value !== undefined ? String(value) : "—";
const maxLength = 400;
const isLong = text.length > maxLength;
if (!isLong) {
return <span style={{ color: 'var(--navy)', fontWeight: 600, lineHeight: '1.4', display: 'block', marginTop: '2px' }}>{text}</span>;
}
return (
<div style={{ display: 'flex', flexDirection: 'column', marginTop: '2px', width: '100%' }}>
<span style={{ color: 'var(--navy)', fontWeight: 600, lineHeight: '1.4' }}>
{expanded ? text : `${text.slice(0, maxLength)}...`}
</span>
<button
type="button"
onClick={() => setExpanded(!expanded)}
style={{
background: 'none',
border: 'none',
color: 'var(--primary)',
fontSize: '12px',
fontWeight: 600,
padding: '4px 0',
cursor: 'pointer',
marginTop: '2px'
}}
>
{expanded ? 'Read Less' : 'Read More'}
</button>
</div>
);
}
+8 -8
View File
@@ -5,12 +5,12 @@ export default function Footer() {
<footer className="footer">
<div className="footer-top">
<div className="footer-left">
<img src="/images/bookkeeppro-logo.webp" className="footer-logo" alt="Bookkeepro" />
<p>Your Globally Trusted Bookkeeping Partner.</p>
<img src="/images/bookkeeppro-logo.webp" className="footer-logo" alt="BookKeepPro" />
<p>Bookkeeping, payroll and tax preparation for growing businesses — kept precise, kept compliant.</p>
</div>
<div className="footer-links">
<h4>Quick Links</h4>
<h4>Navigate</h4>
<Link to="/">Home</Link>
<Link to="/about-us">About Us</Link>
<Link to="/services">Services</Link>
@@ -18,11 +18,11 @@ export default function Footer() {
</div>
<div className="footer-contact">
<h4>Contact</h4>
<p>📍 USA: McKinney, TX</p>
<p>📍 India: Pune, Maharashtra</p>
<p>📧 vedant.aiindia@gmail.com</p>
<p>📞 +918275367267</p>
<h4>Reach us</h4>
<p>USA · 2520 Indigo Dr, McKinney, TX 75072</p>
<p>India · 508 White Square, Hinjewadi Road, Pune 411057</p>
<p>atharvg.aiindia@gmail.com</p>
<p>+91 8275367267</p>
</div>
</div>
+13 -14
View File
@@ -1,32 +1,32 @@
import { Link, useNavigate } from 'react-router-dom';
import { useState, useEffect } from 'react';
import { useState } from 'react';
import { useTheme } from '../context/ThemeContext';
export default function Navbar({ transparent = false }) {
export default function Navbar({ solid = false }) {
const [isOpen, setIsOpen] = useState(false);
const navigate = useNavigate();
const { theme, toggleTheme } = useTheme();
return (
<div className={`navbar ${transparent ? 'navbar-transparent' : ''}`}>
<div className={`navbar ${solid ? 'navbar-solid' : ''}`}>
<div className="nav-container">
<Link to="/">
<img id="logos" src="/images/bookkeeppro-logo.webp" alt="Bookkeeping Logo" />
<img id="logos" src="/images/bookkeeppro-logo.webp" alt="BookKeepPro" />
</Link>
<nav id="navMenu" className={`nav-menu ${isOpen ? 'active' : ''}`}>
<Link to="/">Home</Link>
<Link to="/about-us">About Us</Link>
<Link to="/services">Services</Link>
<Link to="/contact">Contact Us</Link>
<Link to="/" onClick={() => setIsOpen(false)}>Home</Link>
<Link to="/about-us" onClick={() => setIsOpen(false)}>About Us</Link>
<Link to="/services" onClick={() => setIsOpen(false)}>Services</Link>
<Link to="/contact" onClick={() => setIsOpen(false)}>Contact Us</Link>
<button
className="theme-toggle"
onClick={toggleTheme}
style={{background:'none', border:'none', color:'inherit', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', padding:'8px'}}
<button
className="theme-toggle"
onClick={toggleTheme}
style={{ background: 'none', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '8px' }}
aria-label="Toggle Theme"
>
<span className="material-symbols-outlined theme-toggle-icon" style={{fontSize: '24px'}}>
<span className="material-symbols-outlined" style={{ fontSize: '22px' }}>
{theme === 'dark' ? 'light_mode' : 'dark_mode'}
</span>
</button>
@@ -34,7 +34,6 @@ export default function Navbar({ transparent = false }) {
<button className="login-btn desktop-login" onClick={() => navigate('/login')}>
Sign in
</button>
<button className="login-btn mobile-login" onClick={() => navigate('/login')}>
Sign in
</button>
+14 -14
View File
@@ -1,4 +1,4 @@
import { createContext, useContext, useState, useEffect } from 'react';
import { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
const AuthContext = createContext();
@@ -9,18 +9,7 @@ export function AuthProvider({ children }) {
const [loading, setLoading] = useState(true);
const navigate = useNavigate();
useEffect(() => {
if (token) {
localStorage.setItem('token', token);
fetchUser();
} else {
localStorage.removeItem('token');
setUser(null);
setLoading(false);
}
}, [token]);
const fetchUser = async () => {
const fetchUser = useCallback(async () => {
try {
const res = await fetch('/api/auth/me', {
headers: {
@@ -39,7 +28,18 @@ export function AuthProvider({ children }) {
} finally {
setLoading(false);
}
};
}, [token]);
useEffect(() => {
if (token) {
localStorage.setItem('token', token);
fetchUser();
} else {
localStorage.removeItem('token');
setUser(null);
setLoading(false);
}
}, [token, fetchUser]);
const login = (newToken) => {
setLoading(true);
+1 -1
View File
@@ -21,7 +21,7 @@ export function ToastProvider({ children }) {
}, []);
return (
<ToastContext.Provider value={{ addToast }}>
<ToastContext.Provider value={{ addToast, showToast: addToast }}>
{children}
<div className="toast-container">
{toasts.map(toast => (
+300 -2676
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -10,7 +10,7 @@ export default function DashboardLayout() {
return (
<div className="app-body">
<header className="app-header">
<Link to="/dashboard">
<Link to={(user?.role === 'admin' || user?.role === 'super_admin') ? '/admin-dashboard' : '/dashboard'}>
<img className="logo" src="/images/bookkeeppro-logo.webp" alt="BookKeepPro" />
</Link>
<div className="header-actions">
+3
View File
@@ -2,9 +2,12 @@ import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.jsx'
import { initScrollReveal } from './utils/scrollReveal.js'
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>,
)
initScrollReveal()
+40 -41
View File
@@ -1,29 +1,19 @@
export default function AboutUs() {
return (
<>
{/* HERO */}
<div className="page-hero" style={{
backgroundImage: 'linear-gradient(rgba(0,0,0,0.6), rgba(0,0,0,0.6)), url("/images/About-us-background-image.webp")',
backgroundSize: 'cover',
backgroundPosition: 'center',
minHeight: '400px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
textAlign: 'center',
color: '#fff'
}}>
<div>
<h1>About Us</h1>
<p>Our People Are Passionate About What We Do</p>
<div className="page-hero" style={{ '--hero-img': 'url("/images/About-us-background-image.webp")' }}>
<div className="page-hero-inner">
<span className="eyebrow">About BookKeepPro</span>
<h1>Our people are passionate about what we do</h1>
<p>Twenty-seven years of accounting, compliance and long-term client relationships.</p>
</div>
</div>
{/* CONTENT */}
<div className="about-wrapper">
<div className="about-block">
<div className="about-block reveal">
<div className="about-text">
<h2>Who We Are</h2>
<span className="eyebrow">1998 — where it started</span>
<h2 style={{ margin: '14px 0' }}>Who we are</h2>
<p>
Our journey began in 1998 as a Chartered Accountant firm in India,
built on strong fundamentals of accounting, compliance, integrity,
@@ -31,48 +21,57 @@ export default function AboutUs() {
</p>
<br />
<p>
In 2018, we strengthened our presence in Pune & Mumbai — transitioning
from a traditional CA practice into a scalable financial services
organization.
In 2018, we strengthened our presence in Pune and Mumbai —
transitioning from a traditional CA practice into a scalable
financial services organization.
</p>
</div>
<img className="about-img" src="/images/about-us-block-1.webp" alt="Bookkeepro Team" style={{ objectFit: 'cover' }} />
<img className="about-img" src="/images/about-us-block-1.webp" alt="BookKeepPro Team" />
</div>
<div className="about-block reverse">
<div className="about-block reverse reveal">
<div className="about-text">
<h2>About Bookkeepro</h2>
<span className="eyebrow">2023 — going global</span>
<h2 style={{ margin: '14px 0' }}>About BookKeepPro</h2>
<p>
As our client base expanded globally — especially across the US — we aligned
our operating model to support international growth.
As our client base expanded globally — especially across the US —
we aligned our operating model to support international growth.
</p>
<br />
<p>
In 2023, we launched:<br /><br />
<b>• Bookkeeping Business Solutions Pvt Ltd (India)</b><br />
<b>• Bookkeeping Business Solutions LLC (USA)</b>
<b>Bookkeeping Business Solutions Pvt Ltd</b> (India)<br />
<b>Bookkeeping Business Solutions LLC</b> (USA)
</p>
<br />
<p>
Today, Bookkeepro serves global businesses, startups & enterprises with
scalable, compliant bookkeeping and financial operations support.
Today, BookKeepPro serves global businesses, startups and
enterprises with scalable, compliant bookkeeping and financial
operations support.
</p>
</div>
<img className="about-img" src="/images/young-business-people-using-computer-in-office.jpg" alt="About Bookkeepro" style={{ objectFit: 'cover' }} />
<img className="about-img" src="/images/young-business-people-using-computer-in-office.jpg" alt="About BookKeepPro" />
</div>
</div>
<div className="about-block" style={{ width: 'min(1200px, 92%)', margin: 'auto', marginBottom: '80px', padding: '40px', justifyContent: 'center', textAlign: 'center', flexWrap: 'wrap' }}>
<div className="about-text" style={{ flex: '1 1 100%' }}>
<h2 style={{ marginBottom: '24px' }}>Who We Are Today</h2>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '20px', justifyContent: 'center' }}>
<p style={{ background: 'var(--blue-light)', color: 'var(--navy)', padding: '12px 24px', borderRadius: '30px', fontWeight: '500' }}>✔️ 25+ years of accounting & compliance expertise</p>
<p style={{ background: 'var(--blue-light)', color: 'var(--navy)', padding: '12px 24px', borderRadius: '30px', fontWeight: '500' }}>✔️ Operations across India & USA</p>
<p style={{ background: 'var(--blue-light)', color: 'var(--navy)', padding: '12px 24px', borderRadius: '30px', fontWeight: '500' }}>✔️ Secure, process-driven financial workflows</p>
<p style={{ background: 'var(--blue-light)', color: 'var(--navy)', padding: '12px 24px', borderRadius: '30px', fontWeight: '500' }}>✔️ Strong confidentiality & data protection practices</p>
</div>
<section className="section reveal" style={{ marginTop: 0, marginBottom: '90px' }}>
<div className="section-head" style={{ textAlign: 'center', margin: '0 auto 32px', maxWidth: '640px' }}>
<span className="eyebrow" style={{ justifyContent: 'center' }}>Where we stand today</span>
<h2>Who we are today</h2>
</div>
</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '16px', justifyContent: 'center' }}>
{[
'27+ years of accounting & compliance expertise',
'Operations across India and the USA',
'Secure, process-driven financial workflows',
'Strong confidentiality & data protection practices',
].map((item) => (
<p key={item} className="badge badge-blue" style={{ padding: '12px 22px', fontSize: '13.5px', fontWeight: 500, letterSpacing: 0 }}>
{item}
</p>
))}
</div>
</section>
</>
);
}
+42 -27
View File
@@ -1,10 +1,10 @@
import { useState, useEffect } from 'react';
import { useState, useEffect, useCallback } from 'react';
import { useAuth } from '../context/AuthContext';
import { useNavigate } from 'react-router-dom';
export default function AdminDashboard() {
const { user, authFetch } = useAuth();
const [stats, setStats] = useState({ total_users: 0, pending_docs: 0, admins: 0 });
const { authFetch } = useAuth();
const [stats, setStats] = useState({ total_users: 0, pending_personal: 0, pending_business: 0, admins: 0 });
const [users, setUsers] = useState([]);
const [search, setSearch] = useState("");
const [tab, setTab] = useState("users");
@@ -19,17 +19,7 @@ export default function AdminDashboard() {
const [tplFile, setTplFile] = useState(null);
const [tplLoading, setTplLoading] = useState(false);
useEffect(() => {
fetchAdminData();
}, [authFetch]);
useEffect(() => {
if (tab === "templates") {
loadTemplates();
}
}, [tab, tplCategory, tplYear]);
const fetchAdminData = async () => {
const fetchAdminData = useCallback(async () => {
setLoading(true);
try {
const res = await authFetch("/api/auth/admin/users");
@@ -39,21 +29,22 @@ export default function AdminDashboard() {
const usersArray = Array.isArray(payload) ? payload : (payload.users || []);
setUsers(usersArray);
// Compute stats locally like legacy frontend
const total = usersArray.length;
const pending = usersArray.reduce((s, u) => s + (u.pending_docs || 0), 0);
const admins = usersArray.filter(u => u.role === "admin" || u.role === "super_admin").length;
// Compute stats locally
const total = usersArray.length;
const pendingP = usersArray.reduce((s, u) => s + (u.pending_personal || 0), 0);
const pendingB = usersArray.reduce((s, u) => s + (u.pending_business || 0), 0);
const admins = usersArray.filter(u => u.role === "admin" || u.role === "super_admin").length;
setStats({ total_users: total, pending_docs: pending, admins: admins });
setStats({ total_users: total, pending_personal: pendingP, pending_business: pendingB, admins: admins });
}
} catch (err) {
console.error(err);
} finally {
setLoading(false);
}
};
}, [authFetch]);
const loadTemplates = async () => {
const loadTemplates = useCallback(async () => {
setTplLoading(true);
try {
const res = await authFetch(`/api/upload/templates?category=${tplCategory}&tax_year=${tplYear}`);
@@ -68,7 +59,17 @@ export default function AdminDashboard() {
} finally {
setTplLoading(false);
}
};
}, [authFetch, tplCategory, tplYear]);
useEffect(() => {
fetchAdminData();
}, [authFetch, fetchAdminData]);
useEffect(() => {
if (tab === "templates") {
loadTemplates();
}
}, [tab, tplCategory, tplYear, loadTemplates]);
const handleTplUpload = async (e) => {
e.preventDefault();
@@ -168,9 +169,14 @@ export default function AdminDashboard() {
<div className="stat-label">Admin Accounts</div>
</div>
<div className="stat-card accent-orange">
<div className="stat-icon"><span className="material-symbols-outlined">pending</span></div>
<div className="stat-value">{stats.pending_docs}</div>
<div className="stat-label">Pending Docs</div>
<div className="stat-icon"><span className="material-symbols-outlined">description</span></div>
<div className="stat-value">{stats.pending_personal}</div>
<div className="stat-label">Pending Personal</div>
</div>
<div className="stat-card accent-orange">
<div className="stat-icon"><span className="material-symbols-outlined">business</span></div>
<div className="stat-value">{stats.pending_business}</div>
<div className="stat-label">Pending Business</div>
</div>
</div>
@@ -199,8 +205,17 @@ export default function AdminDashboard() {
<span className={`badge role-badge ${u.role === 'super_admin' ? 'badge-red' : u.role === 'admin' ? 'badge-orange' : 'badge-blue'}`}>
{u.role}
</span>
{u.pending_docs > 0 && (
<span className="badge badge-orange pulse" style={{ cursor: 'default' }}>{u.pending_docs} pending</span>
{u.pending_personal > 0 && (
<span className="badge badge-orange pulse" style={{ cursor: 'default' }}>
<span className="material-symbols-outlined" style={{fontSize:'12px', verticalAlign:'middle'}}>description</span>
{' '}{u.pending_personal} personal
</span>
)}
{u.pending_business > 0 && (
<span className="badge badge-orange pulse" style={{ cursor: 'default' }}>
<span className="material-symbols-outlined" style={{fontSize:'12px', verticalAlign:'middle'}}>business</span>
{' '}{u.pending_business} business
</span>
)}
</div>
<div className="click-layer"></div>
+159 -60
View File
@@ -1,7 +1,8 @@
import { useState, useEffect, useRef } from 'react';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { useToast } from '../context/ToastContext';
import ExpandableSummaryBlock from '../components/ExpandableSummaryBlock';
export default function AdminUserDetail() {
const [searchParams] = useSearchParams();
@@ -13,7 +14,7 @@ export default function AdminUserDetail() {
const [userDetail, setUserDetail] = useState(null);
const [documents, setDocuments] = useState([]);
const [activeTab, setActiveTab] = useState('personal');
const [taxYear, setTaxYear] = useState(new Date().getFullYear().toString());
const [taxYear, setTaxYear] = useState("");
const [loading, setLoading] = useState(true);
// States for Review Emails
@@ -26,15 +27,7 @@ export default function AdminUserDetail() {
const adminDocInputRef = useRef(null);
useEffect(() => {
if (!userId) {
navigate('/admin-dashboard');
return;
}
fetchUserDetails();
}, [userId, taxYear]);
const fetchUserDetails = async () => {
const fetchUserDetails = useCallback(async () => {
setLoading(true);
try {
const url = taxYear ? `/api/upload/admin/users/${userId}/documents?tax_year=${taxYear}` : `/api/upload/admin/users/${userId}/documents`;
@@ -47,15 +40,35 @@ export default function AdminUserDetail() {
const payload = await res.json();
setUserDetail(payload.user);
setDocuments(payload.documents || []);
// 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) {
adminDocs = await adminDocsRes.json();
adminDocs = adminDocs.map(d => ({ ...d, type: 'admin', uploaded_at: d.created_at }));
}
setDocuments([...userDocs, ...adminDocs]);
} catch (err) {
console.error(err);
} finally {
setLoading(false);
}
};
}, [authFetch, navigate, taxYear, userId]);
const loadAuditLog = async () => {
useEffect(() => {
if (!userId) {
navigate('/admin-dashboard');
return;
}
fetchUserDetails();
}, [userId, taxYear, navigate, fetchUserDetails]);
const loadAuditLog = useCallback(async () => {
try {
const res = await authFetch(`/api/auth/admin/audit-logs?user_id=${userId}&limit=30`);
if (res.ok) {
@@ -65,13 +78,23 @@ export default function AdminUserDetail() {
} catch (err) {
console.error(err);
}
};
}, [authFetch, userId]);
useEffect(() => {
if (activeTab === 'audit' && !auditLoaded) {
loadAuditLog();
}
}, [activeTab]);
}, [activeTab, auditLoaded, loadAuditLog]);
// Auto-refresh if any doc is still awaiting AI extraction (background task lag)
useEffect(() => {
const hasPending = documents.some(
d => (d.type === 'personal' || d.type === 'business') && d.extracted_data === null
);
if (!hasPending) return;
const timer = setTimeout(() => fetchUserDetails(), 5000);
return () => clearTimeout(timer);
}, [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;
@@ -144,6 +167,10 @@ export default function AdminUserDetail() {
const fd = new FormData();
fd.append("file", file);
fd.append("user_id", userId);
// doc_key and doc_label are required by the backend
const label = file.name.replace(/\.[^.]+$/, ''); // strip extension for a clean label
fd.append("doc_key", `admin_${Date.now()}`);
fd.append("doc_label", label);
try {
const res = await authFetch("/api/upload/admin-documents", {
method: "POST",
@@ -243,9 +270,9 @@ export default function AdminUserDetail() {
return (
<div className="page-main-wide page-enter">
{/* User Info Bar */}
<div className="card" style={{marginBottom: '20px'}}>
<div style={{display:'flex', alignItems:'center', justifyContent:'space-between', flexWrap:'wrap', gap:'16px'}}>
<div style={{display:'flex', alignItems:'center', gap:'16px'}}>
<div className="card aud-user-bar" style={{marginBottom: '20px'}}>
<div className="aud-bar-inner">
<div className="aud-bar-left">
<div style={{width:'52px', height:'52px', borderRadius:'50%', background:'linear-gradient(135deg,var(--header-bg),var(--blue-light))', display:'flex', alignItems:'center', justifyContent:'center', fontWeight:700, fontSize:'20px', color:'var(--navy)', flexShrink:0}}>
{(userDetail.name || "U").charAt(0).toUpperCase()}
</div>
@@ -271,13 +298,38 @@ export default function AdminUserDetail() {
<span className="badge badge-yellow"><span className="material-symbols-outlined" style={{fontSize: '14px'}}>pending</span> Engagement not acknowledged</span>
)}
</div>
{/* Doc count summary */}
<div style={{display:'flex', gap:'12px', marginTop:'10px', flexWrap:'wrap'}}>
<div className="doc-count-chip">
<span className="material-symbols-outlined" style={{fontSize:'14px', color:'var(--emerald)'}}>description</span>
<span style={{fontWeight:600, color:'var(--navy)'}}>{personalDocs.length}</span>
<span style={{color:'var(--muted)'}}>personal</span>
</div>
<div className="doc-count-chip">
<span className="material-symbols-outlined" style={{fontSize:'14px', color:'var(--brass)'}}>business</span>
<span style={{fontWeight:600, color:'var(--navy)'}}>{businessDocs.length}</span>
<span style={{color:'var(--muted)'}}>business</span>
</div>
<div className="doc-count-chip">
<span className="material-symbols-outlined" style={{fontSize:'14px', color:'var(--muted)'}}>upload_file</span>
<span style={{fontWeight:600, color:'var(--navy)'}}>{returnDocs.length}</span>
<span style={{color:'var(--muted)'}}>returns</span>
</div>
<div className="doc-count-chip" style={{borderLeft:'1px solid var(--border)', paddingLeft:'12px'}}>
<span className="material-symbols-outlined" style={{fontSize:'14px', color:'var(--muted)'}}>folder</span>
<span style={{fontWeight:700, color:'var(--navy)'}}>{personalDocs.length + businessDocs.length + returnDocs.length}</span>
<span style={{color:'var(--muted)'}}>total</span>
</div>
</div>
</div>
</div>
<div style={{display:'flex', gap:'10px', alignItems:'center', flexWrap:'wrap'}}>
<div className="aud-bar-actions">
<button className="btn btn-primary btn-sm" onClick={submitAllDocs} style={{borderRadius:'var(--radius-sm)'}}>Trigger Submit Review</button>
<div style={{display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: '4px', marginLeft: '12px', paddingLeft: '16px', borderLeft: '1px solid var(--border)'}}>
<div className="aud-year-picker">
<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)}>
<option value="">All Years</option>
{yearOptions.map(y => <option key={y} value={y}>{y}</option>)}
</select>
</div>
@@ -297,35 +349,59 @@ export default function AdminUserDetail() {
{/* Tab: Personal */}
{activeTab === 'personal' && (
<div className="tab-panel active">
<div style={{display:'flex', gap:'20px', flexWrap:'wrap'}}>
<div style={{flex:2, minWidth:0}}>
<div className="doc-review-layout">
<div className="doc-review-main">
<div className="card-flat">
{personalDocs.length === 0 ? (
<p className="text-muted">No personal documents uploaded for {taxYear}.</p>
<p className="text-muted">No personal documents uploaded{taxYear ? ` for ${taxYear}` : ''}.</p>
) : (
personalDocs.map(doc => (
<div key={doc.id} style={{ display:'flex', alignItems:'flex-start', gap:'16px', padding:'14px 0', borderBottom:'1px solid var(--border)'}}>
<div style={{ flex:1, minWidth:0 }}>
<div style={{ fontWeight:600, fontSize:'13px', color:'var(--navy)' }}>{doc.doc_type}</div>
<div style={{ fontSize:'12px', color:'var(--muted)', marginTop:'2px' }}>Uploaded {new Date(doc.uploaded_at).toLocaleDateString()}</div>
{doc.notes && <div style={{ fontSize:'12px', color:'var(--warn)', marginTop:'3px' }}>Notes: {doc.notes}</div>}
{doc.review_status && (
<div style={{ fontSize:'12px', color: doc.review_status === "approved" ? "var(--success)" : doc.review_status === "rejected" ? "var(--error)" : "var(--yellow)", marginTop:'3px', fontWeight:600, textTransform:'uppercase' }}>
{doc.review_status}
<div key={doc.id} className="doc-review-row">
<div className="doc-review-row-top">
<div className="doc-review-info">
<div style={{ fontWeight:700, fontSize:'15px', color:'var(--navy)', lineHeight:'1.3' }}>{doc.doc_type}</div>
<div style={{ fontSize:'12px', color:'var(--muted)', marginTop:'3px' }}>
<span className="material-symbols-outlined" style={{fontSize:'12px', verticalAlign:'middle', marginRight:'3px'}}>calendar_today</span>
{new Date(doc.uploaded_at).toLocaleDateString('en-US', {year:'numeric', month:'short', day:'numeric'})}
{doc.tax_year && <span style={{marginLeft:'8px', fontWeight:600, color:'var(--brass)'}}>TY {doc.tax_year}</span>}
</div>
)}
</div>
<div style={{ display:'flex', alignItems:'center', gap:'8px', flexShrink:0, flexWrap:'wrap' }}>
<button onClick={() => viewDoc(doc.storage_key)} className="btn btn-secondary btn-sm" style={{borderRadius:'var(--radius-sm)'}}>View</button>
<button className="btn btn-secondary btn-sm" style={{borderRadius:'var(--radius-sm)'}} onClick={() => handleDocApprove(doc.id, doc.type, true)}>Approve</button>
<button className="btn btn-danger btn-sm" style={{borderRadius:'var(--radius-sm)'}} onClick={() => handleDocApprove(doc.id, doc.type, false)}>Reject</button>
{doc.notes && <div style={{ fontSize:'12px', color:'var(--warn)', marginTop:'3px', fontWeight:500 }}>⚠ {doc.notes}</div>}
{doc.review_status && (
<div style={{ marginTop:'5px' }}>
<span className={`badge ${doc.review_status === 'approved' ? 'badge-green' : doc.review_status === 'rejected' ? 'badge-red' : 'badge-yellow'}`} style={{fontWeight:700}}>
{doc.review_status.toUpperCase()}
</span>
</div>
)}
</div>
<div className="doc-review-actions">
<button onClick={() => viewDoc(doc.storage_key)} className="btn btn-secondary btn-sm" style={{borderRadius:'var(--radius-sm)'}}>View</button>
<button className="btn btn-secondary btn-sm" style={{borderRadius:'var(--radius-sm)'}} onClick={() => handleDocApprove(doc.id, doc.type, true)}>Approve</button>
<button className="btn btn-danger btn-sm" style={{borderRadius:'var(--radius-sm)'}} onClick={() => handleDocApprove(doc.id, doc.type, false)}>Reject</button>
</div>
</div>
{doc.extracted_data && Object.keys(doc.extracted_data).length > 0 ? (
<div className="ai-summary-block">
<div className="ai-summary-label">
<span className="material-symbols-outlined" style={{ fontSize: '14px', verticalAlign: 'middle', marginRight: '4px' }}>auto_awesome</span>
AI Summary
</div>
<ExpandableSummaryBlock extractedData={doc.extracted_data} />
</div>
) : doc.extracted_data === null ? (
<div className="ai-summary-block" style={{ opacity: 0.6 }}>
<div className="ai-summary-label">
<span className="material-symbols-outlined" style={{ fontSize: '14px', verticalAlign: 'middle', marginRight: '4px', animation: 'spin 1.2s linear infinite' }}>progress_activity</span>
AI Summary — Processing…
</div>
</div>
) : null}
</div>
))
)}
</div>
</div>
<div style={{flex:1, minWidth:'240px'}}>
<div className="doc-review-sidebar">
<div className="card-flat" style={{display:'flex', flexDirection:'column', gap:'16px'}}>
<h3>Filing Timeline</h3>
<div className="timeline-control">
@@ -348,35 +424,59 @@ export default function AdminUserDetail() {
{/* Tab: Business */}
{activeTab === 'business' && (
<div className="tab-panel active">
<div style={{display:'flex', gap:'20px', flexWrap:'wrap'}}>
<div style={{flex:2, minWidth:0}}>
<div className="doc-review-layout">
<div className="doc-review-main">
<div className="card-flat">
{businessDocs.length === 0 ? (
<p className="text-muted">No business documents uploaded for {taxYear}.</p>
<p className="text-muted">No business documents uploaded{taxYear ? ` for ${taxYear}` : ''}.</p>
) : (
businessDocs.map(doc => (
<div key={doc.id} style={{ display:'flex', alignItems:'flex-start', gap:'16px', padding:'14px 0', borderBottom:'1px solid var(--border)'}}>
<div style={{ flex:1, minWidth:0 }}>
<div style={{ fontWeight:600, fontSize:'13px', color:'var(--navy)' }}>{doc.doc_type}</div>
<div style={{ fontSize:'12px', color:'var(--muted)', marginTop:'2px' }}>Uploaded {new Date(doc.uploaded_at).toLocaleDateString()}</div>
{doc.notes && <div style={{ fontSize:'12px', color:'var(--warn)', marginTop:'3px' }}>Notes: {doc.notes}</div>}
{doc.review_status && (
<div style={{ fontSize:'12px', color: doc.review_status === "approved" ? "var(--success)" : doc.review_status === "rejected" ? "var(--error)" : "var(--yellow)", marginTop:'3px', fontWeight:600, textTransform:'uppercase' }}>
{doc.review_status}
<div key={doc.id} className="doc-review-row">
<div className="doc-review-row-top">
<div className="doc-review-info">
<div style={{ fontWeight:700, fontSize:'15px', color:'var(--navy)', lineHeight:'1.3' }}>{doc.doc_type}</div>
<div style={{ fontSize:'12px', color:'var(--muted)', marginTop:'3px' }}>
<span className="material-symbols-outlined" style={{fontSize:'12px', verticalAlign:'middle', marginRight:'3px'}}>calendar_today</span>
{new Date(doc.uploaded_at).toLocaleDateString('en-US', {year:'numeric', month:'short', day:'numeric'})}
{doc.tax_year && <span style={{marginLeft:'8px', fontWeight:600, color:'var(--brass)'}}>TY {doc.tax_year}</span>}
</div>
)}
</div>
<div style={{ display:'flex', alignItems:'center', gap:'8px', flexShrink:0, flexWrap:'wrap' }}>
<button onClick={() => viewDoc(doc.storage_key)} className="btn btn-secondary btn-sm" style={{borderRadius:'var(--radius-sm)'}}>View</button>
<button className="btn btn-secondary btn-sm" style={{borderRadius:'var(--radius-sm)'}} onClick={() => handleDocApprove(doc.id, doc.type, true)}>Approve</button>
<button className="btn btn-danger btn-sm" style={{borderRadius:'var(--radius-sm)'}} onClick={() => handleDocApprove(doc.id, doc.type, false)}>Reject</button>
{doc.notes && <div style={{ fontSize:'12px', color:'var(--warn)', marginTop:'3px', fontWeight:500 }}>⚠ {doc.notes}</div>}
{doc.review_status && (
<div style={{ marginTop:'5px' }}>
<span className={`badge ${doc.review_status === 'approved' ? 'badge-green' : doc.review_status === 'rejected' ? 'badge-red' : 'badge-yellow'}`} style={{fontWeight:700}}>
{doc.review_status.toUpperCase()}
</span>
</div>
)}
</div>
<div className="doc-review-actions">
<button onClick={() => viewDoc(doc.storage_key)} className="btn btn-secondary btn-sm" style={{borderRadius:'var(--radius-sm)'}}>View</button>
<button className="btn btn-secondary btn-sm" style={{borderRadius:'var(--radius-sm)'}} onClick={() => handleDocApprove(doc.id, doc.type, true)}>Approve</button>
<button className="btn btn-danger btn-sm" style={{borderRadius:'var(--radius-sm)'}} onClick={() => handleDocApprove(doc.id, doc.type, false)}>Reject</button>
</div>
</div>
{doc.extracted_data && Object.keys(doc.extracted_data).length > 0 ? (
<div className="ai-summary-block">
<div className="ai-summary-label">
<span className="material-symbols-outlined" style={{ fontSize: '14px', verticalAlign: 'middle', marginRight: '4px' }}>auto_awesome</span>
AI Summary
</div>
<ExpandableSummaryBlock extractedData={doc.extracted_data} />
</div>
) : doc.extracted_data === null ? (
<div className="ai-summary-block" style={{ opacity: 0.6 }}>
<div className="ai-summary-label">
<span className="material-symbols-outlined" style={{ fontSize: '14px', verticalAlign: 'middle', marginRight: '4px', animation: 'spin 1.2s linear infinite' }}>progress_activity</span>
AI Summary — Processing…
</div>
</div>
) : null}
</div>
))
)}
</div>
</div>
<div style={{flex:1, minWidth:'240px'}}>
<div className="doc-review-sidebar">
<div className="card-flat" style={{display:'flex', flexDirection:'column', gap:'16px'}}>
<h3>Filing Timeline</h3>
<div className="timeline-control">
@@ -465,10 +565,9 @@ export default function AdminUserDetail() {
<tr key={log.id}>
<td style={{whiteSpace:'nowrap', color:'var(--muted)'}}>{new Date(log.created_at).toLocaleString()}</td>
<td><span className="badge badge-blue">{log.action}</span></td>
<td>{log.details}</td>
<td>{log.detail}</td>
<td className="text-sm text-muted">
{log.ip_address}<br/>
<span style={{fontSize:'10px'}}>{log.user_agent?.substring(0, 30)}...</span>
{log.ip_address}
</td>
</tr>
))}
+67 -88
View File
@@ -21,7 +21,7 @@ export default function Contact() {
body: JSON.stringify(formData)
});
if (!res.ok) throw new Error("Failed to send");
alert("Message Sent! Thank you for contacting us.");
alert("Message sent! Thank you for contacting us.");
setFormData({
first_name: '',
last_name: '',
@@ -42,110 +42,89 @@ export default function Contact() {
return (
<>
{/* HERO */}
<div className="page-hero" style={{
backgroundImage: 'linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)), url("/images/home-background.jpg")',
backgroundSize: 'cover',
backgroundPosition: 'center',
minHeight: '350px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
textAlign: 'center',
color: '#fff'
}}>
<div>
<h1>Get In Touch</h1>
<div className="page-hero" style={{ '--hero-img': 'url("/images/home-background.jpg")' }}>
<div className="page-hero-inner">
<span className="eyebrow">Get in touch</span>
<h1>Let's talk about your books</h1>
<p>We'd love to hear from you. Reach out to our global teams.</p>
</div>
</div>
<section className="contact-section" style={{ border: 'none', marginTop: '60px', marginBottom: '80px' }}>
<h2 className="contact-title" style={{ color: 'var(--navy)', marginBottom: '50px' }}>
CONTACT <span style={{ color: 'var(--blue)' }}>BOOK</span><span style={{ color: 'var(--orange)' }}>KEEPRO</span>
</h2>
<section className="contact-section reveal">
<h2 className="contact-title">Contact BookKeepPro</h2>
<p className="contact-sub">Tell us a little about your business and we'll follow up within one business day.</p>
<div className="contact-container" style={{ width: '100%', maxWidth: '1000px', display: 'flex', flexWrap: 'wrap', gap: '40px', justifyContent: 'center' }}>
<div className="contact-info" style={{ flex: '1 1 300px', display: 'flex', flexDirection: 'column', gap: '30px' }}>
<div className="info-box usa" style={{ padding: '30px', borderRadius: '20px', boxShadow: 'var(--shadow-md)' }}>
<h3 style={{ fontSize: '24px', marginBottom: '12px' }}>USA</h3>
<p style={{ lineHeight: '1.6', marginBottom: '16px', opacity: 0.9 }}>2520 Indigo Dr<br />McKinney, TX<br />75072, United States</p>
<p className="phone" style={{ display: 'flex', alignItems: 'center', gap: '10px', fontWeight: '500' }}>
<span className="material-symbols-outlined" style={{ fontSize: '20px' }}>call</span> +1469-796-6151
<div className="contact-container">
<div className="contact-info">
<div className="info-box usa">
<h3>USA</h3>
<p>2520 Indigo Dr<br />McKinney, TX<br />75072, United States</p>
<p className="phone">
<span className="material-symbols-outlined" style={{ fontSize: '18px' }}>call</span> +1 469-796-6151
</p>
</div>
<div className="info-box ind" style={{ padding: '30px', borderRadius: '20px', boxShadow: 'var(--shadow-md)' }}>
<h3 style={{ fontSize: '24px', marginBottom: '12px' }}>IND</h3>
<p style={{ lineHeight: '1.6', marginBottom: '16px', opacity: 0.9 }}>508, White Square,<br />Hinjewadi Road, Pune<br />411057, India</p>
<p className="phone" style={{ display: 'flex', alignItems: 'center', gap: '10px', fontWeight: '500' }}>
<span className="material-symbols-outlined" style={{ fontSize: '20px' }}>call</span> +91 738 793 6020
<div className="info-box ind">
<h3>India</h3>
<p>508, White Square,<br />Hinjewadi Road, Pune<br />411057, India</p>
<p className="phone">
<span className="material-symbols-outlined" style={{ fontSize: '18px' }}>call</span> +91 738 793 6020
</p>
</div>
</div>
<div style={{ flex: '1.5 1 400px' }}>
<form className="contact-form" onSubmit={handleSubmit} style={{ padding: '40px', borderRadius: '20px', boxShadow: 'var(--shadow-lg)' }}>
<h3 style={{ fontSize: '22px', marginBottom: '24px', color: 'var(--navy)' }}>Send us a message</h3>
<div className="form-row" style={{ display: 'flex', gap: '20px', marginBottom: '20px' }}>
<input
type="text"
name="first_name"
placeholder="First Name"
required
value={formData.first_name}
onChange={handleChange}
style={{ flex: 1, padding: '14px', borderRadius: '8px', border: '1px solid var(--border)', outline: 'none' }}
/>
<input
type="text"
name="last_name"
placeholder="Last Name"
required
value={formData.last_name}
onChange={handleChange}
style={{ flex: 1, padding: '14px', borderRadius: '8px', border: '1px solid var(--border)', outline: 'none' }}
/>
</div>
<input
type="email"
name="email"
placeholder="Email Address"
required
value={formData.email}
<form className="contact-form" onSubmit={handleSubmit}>
<h3 style={{ marginBottom: '22px' }}>Send us a message</h3>
<div className="form-row">
<input
type="text"
name="first_name"
placeholder="First name"
required
value={formData.first_name}
onChange={handleChange}
style={{ width: '100%', padding: '14px', borderRadius: '8px', border: '1px solid var(--border)', outline: 'none', marginBottom: '20px' }}
/>
<input
type="text"
name="last_name"
placeholder="Last name"
required
value={formData.last_name}
onChange={handleChange}
/>
</div>
<div className="phone-row" style={{ marginBottom: '20px', border: 'none', padding: 0 }}>
<input
type="text"
name="phone"
placeholder="Mobile Number"
required
value={formData.phone}
onChange={handleChange}
style={{ width: '100%', padding: '14px', borderRadius: '8px', border: '1px solid var(--border)', outline: 'none' }}
/>
</div>
<input
type="email"
name="email"
placeholder="Email address"
required
value={formData.email}
onChange={handleChange}
/>
<div className="message-row">
<textarea
name="message"
placeholder="How can we help you?"
required
style={{ width: '100%', padding: '14px', border: '1px solid var(--border)', borderRadius: '8px', fontFamily: 'inherit', fontSize: '15px', outline: 'none', marginBottom: '24px', resize: 'vertical', minHeight: '120px' }}
value={formData.message}
onChange={handleChange}
></textarea>
</div>
<input
type="text"
name="phone"
placeholder="Mobile number"
required
value={formData.phone}
onChange={handleChange}
/>
<button type="submit" disabled={loading} className="btn btn-primary" style={{ width: '100%', padding: '14px', fontSize: '16px', borderRadius: '30px' }}>
{loading ? 'SENDING...' : 'SEND MESSAGE'}
</button>
</form>
</div>
<textarea
name="message"
placeholder="How can we help you?"
required
style={{ minHeight: '120px' }}
value={formData.message}
onChange={handleChange}
></textarea>
<button type="submit" disabled={loading} className="btn btn-primary w-full">
{loading ? 'Sending…' : 'Send message'}
</button>
</form>
</div>
</section>
</>
+86 -53
View File
@@ -1,76 +1,109 @@
import { Link } from 'react-router-dom';
const SERVICES = [
{
label: 'Bookkeeping',
title: 'Monthly books, closed clean and on time',
img: '/images/services-1.jpg',
},
{
label: 'Payroll',
title: 'Payroll runs your team can set a clock by',
img: '/images/services-2.jpg',
},
{
label: 'Tax',
title: 'Tax planning and prep built around your entity',
img: '/images/services-3.jpg',
},
];
export default function Home() {
return (
<>
{/* ================= HERO ================= */}
<div className="home-hero" style={{
backgroundImage: 'linear-gradient(rgba(0,0,0,0.6), rgba(0,0,0,0.6)), url("/images/home-background.jpg")',
backgroundSize: 'cover',
backgroundPosition: 'center',
minHeight: '600px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
textAlign: 'center',
color: '#fff',
padding: '20px'
}}>
<div style={{ maxWidth: '800px' }}>
<h1 style={{ fontSize: 'clamp(32px, 5vw, 56px)', fontWeight: '700', marginBottom: '20px', color: '#fff' }}>PRECISION | COMPLIANCE | FINANCIAL GROWTH</h1>
<p style={{ fontSize: 'clamp(18px, 2vw, 24px)', marginBottom: '30px', color: '#e2eaf2' }}>Your Trusted Bookkeeping & Financial Operations Partner for Growing Businesses</p>
<Link to="/contact">
<button className="btn btn-primary" style={{ padding: '12px 32px', fontSize: '18px', borderRadius: '30px' }}>Get Started</button>
</Link>
<div className="hero">
<div className="hero-inner reveal in-view">
<span className="hero-eyebrow">Bookkeeping · Payroll · Tax</span>
<h1>Every entry accounted for. <em>Every deadline kept.</em></h1>
<p className="hero-sub">
BookKeepPro handles the books, the payroll and the filings for growing
businesses across the US and India, so nothing slips between the cracks
of a busy quarter.
</p>
<div className="hero-actions">
<Link to="/contact"><button className="btn btn-primary">Get started</button></Link>
<Link to="/services"><button className="btn btn-outline" style={{ borderColor: 'rgba(255,255,255,0.5)', color: '#fff' }}>See our services</button></Link>
</div>
</div>
<div className="hero-stats">
<div className="stat-block">
<div className="stat-figure tnum">27</div>
<div className="stat-caption">Years in accounting</div>
</div>
<div className="stat-block">
<div className="stat-figure tnum">2</div>
<div className="stat-caption">Countries operating</div>
</div>
<div className="stat-block">
<div className="stat-figure tnum">100%</div>
<div className="stat-caption">Filings on schedule</div>
</div>
</div>
</div>
{/* ================= ABOUT ================= */}
<section className="about-section" style={{ display: 'flex', gap: '40px', padding: '80px 20px', maxWidth: '1200px', margin: '0 auto', alignItems: 'center', flexWrap: 'wrap' }}>
<div className="text" style={{ flex: '1 1 500px' }}>
<h2 style={{ fontSize: '36px', marginBottom: '24px' }}>
We are <span style={{ color: '#0077C8' }}>BOOK</span><span style={{ color: '#FF7F11' }}>KEEPRO</span>
</h2>
<p style={{ fontSize: '16px', lineHeight: '1.8', marginBottom: '16px' }}>
Our journey began in 1998 as a Chartered Accountant firm in India, built on strong fundamentals of accounting, compliance, integrity, and long-term client relationships. Over the years, we earned the trust of businesses by delivering accurate, compliant, and dependable financial services.
<section className="section about-grid reveal">
<div className="about-copy">
<span className="eyebrow">Who we are</span>
<h2 style={{ marginTop: '14px', marginBottom: '20px' }}>Twenty-seven years of getting the numbers right</h2>
<p>
Our journey began in 1998 as a Chartered Accountant firm in India, built
on strong fundamentals of accounting, compliance, integrity, and
long-term client relationships.
</p>
<p style={{ fontSize: '16px', lineHeight: '1.8', marginBottom: '24px' }}>
In 2018, responding to growing demand and an expanding client base, we strengthened our presence by establishing operations in Pune and Mumbai, two of India’s major business hubs. This phase marked our evolution from a traditional CA practice into a more structured, process-driven financial services organization.
<p>
In 2018, responding to growing demand, we expanded into Pune and
Mumbai — evolving from a traditional CA practice into a structured,
process-driven financial services organization.
</p>
<p className="note" style={{ fontStyle: 'italic', color: 'var(--muted)', fontWeight: '500' }}>-- Our People Are Passionate About What We Do</p>
<p className="note">— Our people are passionate about what we do</p>
</div>
<div style={{ flex: '1 1 400px' }}>
<img src="/images/home-about.jpg" alt="About BookKeepPro" style={{ width: '100%', borderRadius: '20px', boxShadow: 'var(--shadow-lg)', objectFit: 'cover' }} />
<div className="about-media">
<img src="/images/home-about.jpg" alt="BookKeepPro team at work" />
</div>
</section>
{/* ================= SERVICES ================= */}
<section className="services-section">
<h2>OUR SERVICES</h2>
<div className="services-grid">
<div className="service-card" style={{ flex: '1 1 300px' }}>
<img src="/images/services-1.jpg" alt="Bookkeeping" style={{ width: '100%', height: '220px', objectFit: 'cover', borderTopLeftRadius: '15px', borderTopRightRadius: '15px' }} />
<div style={{ padding: '24px' }}>
<h3 style={{ fontSize: '20px', marginBottom: '16px' }}>Professional Bookkeeping for Firms & Businesses</h3>
<Link to="/contact"><button className="btn btn-outline" style={{ width: '100%' }}>Get Consultation</button></Link>
<section className="section reveal">
<div className="section-head">
<span className="eyebrow">What we handle</span>
<h2>The three ledgers every business runs on</h2>
</div>
<div className="services-grid stagger">
{SERVICES.map((s) => (
<div className="service-card fade-up" key={s.label}>
<div className="service-media">
<img src={s.img} alt={s.title} />
</div>
<div className="service-body">
<span className="service-label">{s.label}</span>
<h3>{s.title}</h3>
<Link to="/contact"><button className="btn btn-outline btn-sm w-full">Get consultation</button></Link>
</div>
</div>
</div>
<div className="service-card" style={{ flex: '1 1 300px' }}>
<img src="/images/services-2.jpg" alt="Payroll" style={{ width: '100%', height: '220px', objectFit: 'cover', borderTopLeftRadius: '15px', borderTopRightRadius: '15px' }} />
<div style={{ padding: '24px' }}>
<h3 style={{ fontSize: '20px', marginBottom: '16px' }}>Professional & Globally Trusted Payroll Solutions</h3>
<Link to="/contact"><button className="btn btn-outline" style={{ width: '100%' }}>Get Consultation</button></Link>
</div>
</div>
<div className="service-card" style={{ flex: '1 1 300px' }}>
<img src="/images/services-3.jpg" alt="Tax Planning" style={{ width: '100%', height: '220px', objectFit: 'cover', borderTopLeftRadius: '15px', borderTopRightRadius: '15px' }} />
<div style={{ padding: '24px' }}>
<h3 style={{ fontSize: '20px', marginBottom: '16px' }}>Professional Tax Planning & Preparation</h3>
<Link to="/contact"><button className="btn btn-outline" style={{ width: '100%' }}>Get Consultation</button></Link>
</div>
</div>
))}
</div>
</section>
{/* ================= CTA ================= */}
<div className="cta-band reveal">
<span className="eyebrow" style={{ justifyContent: 'center', color: '#E4C98A' }}>Ready when you are</span>
<h2 style={{ marginTop: '14px' }}>Hand us the receipts. We'll handle the rest.</h2>
<p>Book a short call and we'll map out exactly what your books need this quarter.</p>
<Link to="/contact"><button className="btn btn-primary">Talk to us</button></Link>
</div>
</>
);
}
+33 -42
View File
@@ -1,67 +1,59 @@
export default function Services() {
return (
<>
{/* HERO */}
<div className="page-hero" style={{
backgroundImage: 'linear-gradient(rgba(0,0,0,0.6), rgba(0,0,0,0.6)), url("/images/Services-background-image.webp")',
backgroundSize: 'cover',
backgroundPosition: 'center',
minHeight: '400px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
textAlign: 'center',
color: '#fff'
}}>
<h1>Professional Services for Firms & Businesses</h1>
<div className="page-hero" style={{ '--hero-img': 'url("/images/Services-background-image.webp")' }}>
<div className="page-hero-inner">
<span className="eyebrow">What we do</span>
<h1>Professional services for firms and businesses</h1>
</div>
</div>
{/* SERVICE CONTENT */}
<div className="services-wrapper">
{/* Block 1 */}
<div className="service-block">
<div className="service-block reveal">
<div className="service-text">
<h2>For Accounting Firms and Businesses</h2>
<span className="eyebrow">Offshore delivery</span>
<h2>For accounting firms and businesses</h2>
<p>
Bookkeepro India specialises in its offshore delivery model and consists of a strong team of qualified
accountants, cost accountants, tax consultants and payroll experts to ease the bookkeeping for Accounting
Firms and Businesses, globally.
BookKeepPro India specialises in its offshore delivery model and
consists of a strong team of qualified accountants, cost
accountants, tax consultants and payroll experts to ease the
bookkeeping for accounting firms and businesses, globally.
</p>
<br />
<p>
Bookkeepro’s India based offshore bookkeeping services offer several benefits
to global accounting firms and businesses.
Our India-based offshore bookkeeping services offer several
benefits to global accounting firms and businesses.
</p>
</div>
<img className="service-img" src="/images/services-3.jpg" alt="Accounting Outsourcing" style={{ borderRadius: '14px', objectFit: 'cover' }} />
<img className="service-img" src="/images/services-3.jpg" alt="Accounting Outsourcing" />
</div>
{/* Block 2 */}
<div className="service-block reverse">
<div className="service-block reverse reveal">
<div className="service-text">
<h2>Scale Your Business with Accounting Outsourcing</h2>
<span className="eyebrow">Accounting outsourcing</span>
<h2>Scale your business with outsourcing</h2>
<p>
Are you ready to supercharge your business and take it to new heights?
We understand that managing finances and accounting can be a complex and
time-consuming task, often diverting your focus away from what truly matters —
growing your business.
Managing finances and accounting can be a complex and
time-consuming task, often diverting your focus away from what
truly matters — growing your business.
</p>
<br />
<p>
That’s where we come in. Allow us to present the game-changing solution:
Accounting Outsourcing.
That's where we come in: a bookkeeping team that runs in the
background so yours doesn't have to.
</p>
</div>
<img className="service-img-bl-3" src="/images/services-2.jpg" alt="Outsourced Accounting Team" style={{ borderRadius: '14px', objectFit: 'cover' }} />
<img className="service-img-bl-3" src="/images/services-2.jpg" alt="Outsourced Accounting Team" />
</div>
{/* Block 3 */}
<div className="service-block">
<div className="service-block reveal">
<div className="service-text">
<h2>Tax Planning And Preparation</h2>
<span className="eyebrow">Tax planning</span>
<h2>Tax planning and preparation</h2>
<p>
We help individuals and businesses optimize tax strategy and get returns prepared right and on time.
Whether your business is an LLC, S-Corp, or C-Corp, we’ll help you:
We help individuals and businesses optimize tax strategy and get
returns prepared right and on time. Whether your business is an
LLC, S-Corp, or C-Corp, we'll help you:
</p>
<ol className="list-items">
<li>Comply with and leverage changing federal tax law</li>
@@ -72,12 +64,11 @@ export default function Services() {
</ol>
<br />
<p>
By minimizing your tax liability, you maximize your after-tax cash flow,
which helps create financial security. We want you confident in knowing you
have the right proactive tax plan in place.
By minimizing your tax liability, you maximize your after-tax
cash flow — the foundation of a proactive, confident tax plan.
</p>
</div>
<img className="service-img" src="/images/services-1.jpg" alt="Tax Services" style={{ borderRadius: '14px', objectFit: 'cover' }} />
<img className="service-img" src="/images/services-1.jpg" alt="Tax Services" />
</div>
</div>
</>
+65 -27
View File
@@ -1,4 +1,4 @@
import { useEffect, useState, useRef } from 'react';
import { useEffect, useState, useRef, useCallback } from 'react';
import { Link } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { useToast } from '../context/ToastContext';
@@ -13,11 +13,7 @@ export default function UploadBusiness() {
const fileInputRefs = useRef({});
const extraFileRef = useRef(null);
useEffect(() => {
fetchTemplatesAndDocs();
}, [taxYear]);
const fetchTemplatesAndDocs = async () => {
const fetchTemplatesAndDocs = useCallback(async () => {
setLoading(true);
try {
const tplRes = await authFetch(`/api/upload/templates?category=business&tax_year=${taxYear}`);
@@ -34,9 +30,13 @@ export default function UploadBusiness() {
} finally {
setLoading(false);
}
};
}, [authFetch, taxYear]);
const uploadFile = async (file, docType) => {
useEffect(() => {
fetchTemplatesAndDocs();
}, [taxYear, fetchTemplatesAndDocs]);
const uploadFile = async (file, docType, skipFetch = false) => {
if (file.size > 10 * 1024 * 1024) {
showToast("File size exceeds 10MB limit", "error");
return;
@@ -52,7 +52,7 @@ export default function UploadBusiness() {
});
if (res.ok) {
showToast("Document uploaded successfully", "success");
fetchTemplatesAndDocs();
if (!skipFetch) fetchTemplatesAndDocs();
} else {
const data = await res.json().catch(() => ({}));
showToast(data.detail || "Upload failed", "error");
@@ -93,12 +93,20 @@ export default function UploadBusiness() {
const handleExtraUpload = async (e) => {
const files = Array.from(e.target.files);
const validFiles = [];
for (let file of files) {
if (file.size > 10 * 1024 * 1024) {
showToast(`File ${file.name} exceeds 10MB limit`, "error");
continue;
}
await uploadFile(file, "other");
validFiles.push(file);
}
if (validFiles.length > 0) {
await Promise.all(validFiles.map((file, idx) =>
uploadFile(file, `other_${Date.now()}_${idx}`, true)
));
fetchTemplatesAndDocs();
}
e.target.value = "";
};
@@ -172,7 +180,12 @@ export default function UploadBusiness() {
hidden
accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx,.xls,.xlsx"
ref={el => fileInputRefs.current[dt.name] = el}
onChange={(e) => e.target.files[0] && uploadFile(e.target.files[0], dt.name)}
onChange={(e) => {
if (e.target.files[0]) {
uploadFile(e.target.files[0], dt.name);
e.target.value = null;
}
}}
/>
<div style={{display: 'flex', gap: '8px', alignItems: 'center'}}>
{dt.download && (
@@ -185,9 +198,11 @@ export default function UploadBusiness() {
)}
</div>
{uploaded.map(doc => (
<div key={doc.id} style={{display:'flex', gap:'8px'}}>
<button className="btn btn-secondary btn-xs" style={{borderRadius:'var(--radius-sm)'}} onClick={() => viewDoc(doc.storage_key)}>View</button>
<button className="btn btn-danger btn-xs" style={{borderRadius:'var(--radius-sm)'}} onClick={() => deleteDoc(doc.id)}>Delete</button>
<div key={doc.id} style={{display:'flex', flexDirection:'column', gap:'8px', alignItems:'flex-end'}}>
<div style={{display:'flex', gap:'8px'}}>
<button className="btn btn-secondary btn-xs" style={{borderRadius:'var(--radius-sm)'}} onClick={() => viewDoc(doc.storage_key)}>View</button>
<button className="btn btn-danger btn-xs" style={{borderRadius:'var(--radius-sm)'}} onClick={() => deleteDoc(doc.id)}>Delete</button>
</div>
</div>
))}
</div>
@@ -203,30 +218,53 @@ export default function UploadBusiness() {
<h3>Additional Documents</h3>
<p className="text-sm" style={{marginTop:'2px'}}>Upload any supplementary business documents</p>
</div>
<label className="btn btn-secondary btn-sm" style={{borderRadius:'var(--radius-sm)', cursor:'pointer'}}>
<label
className="btn btn-secondary btn-sm"
style={{borderRadius:'var(--radius-sm)', cursor:'pointer'}}
tabIndex={0}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
extraFileRef.current?.click();
}
}}
>
+ Choose Files
<input type="file" multiple hidden accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx,.xls,.xlsx" onChange={handleExtraUpload} />
</label>
</div>
<div className="drop-area" style={{ border:'2px dashed #b8cfdf', borderRadius:'var(--radius-md)', padding:'28px 20px', textAlign:'center', cursor:'pointer', background:'var(--card)' }} onClick={() => extraFileRef.current?.click()}>
<div className="da-icon"><span className="material-symbols-outlined" style={{color: '#ffca28', fontSize: '32px'}}>folder</span></div>
<div
className="drop-area"
style={{ border:'2px dashed #cfc7ad', borderRadius:'var(--radius-md)', padding:'28px 20px', textAlign:'center', cursor:'pointer', background:'var(--card)' }}
onClick={() => extraFileRef.current?.click()}
tabIndex={0}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
extraFileRef.current?.click();
}
}}
>
<div className="da-icon"><span className="material-symbols-outlined" style={{color: 'var(--brass)', fontSize: '32px'}}>folder</span></div>
<div className="da-title" style={{fontWeight: 600, color: 'var(--navy)', fontSize: '14px'}}>Drag & drop files here</div>
<div className="da-hint" style={{fontSize: '12px', color: 'var(--muted)'}}>or click to browse · PDF, JPG, PNG, WEBP, DOC, EXCEL · Max 10MB</div>
</div>
<input type="file" multiple hidden ref={extraFileRef} onChange={handleExtraUpload} />
<div className="upload-track mt-12">
{docs.filter(d => d.doc_type === "other").map(doc => (
<div key={doc.id} className="upload-track-item" style={{display:'flex', alignItems:'center', gap:'10px', padding:'8px 12px', borderRadius:'var(--radius-sm)', background:'#f5f8fb', fontSize:'13px', marginBottom:'6px'}}>
<span className="material-symbols-outlined" style={{color:'var(--green)', fontSize:'18px'}}>check_circle</span>
<div className="uti-name" style={{flex:1}}>{doc.filename}</div>
<button className="btn btn-secondary btn-sm" style={{padding:'4px'}} onClick={() => viewDoc(doc.storage_key)}>
<span className="material-symbols-outlined" style={{fontSize:'16px'}}>visibility</span>
</button>
<button className="btn btn-danger btn-sm" style={{padding:'4px'}} onClick={() => deleteDoc(doc.id)}>
<span className="material-symbols-outlined" style={{fontSize:'16px'}}>delete</span>
</button>
{docs.filter(d => d.doc_type.startsWith("other")).map(doc => (
<div key={doc.id} style={{marginBottom:'6px'}}>
<div className="upload-track-item" style={{display:'flex', alignItems:'center', gap:'10px', padding:'8px 12px', borderRadius:'var(--radius-sm)', background:'var(--paper)', fontSize:'13px'}}>
<span className="material-symbols-outlined" style={{color:'var(--green)', fontSize:'18px'}}>check_circle</span>
<div className="uti-name" style={{flex:1}}>{doc.filename}</div>
<button className="btn btn-secondary btn-sm" style={{padding:'4px'}} onClick={() => viewDoc(doc.storage_key)}>
<span className="material-symbols-outlined" style={{fontSize:'16px'}}>visibility</span>
</button>
<button className="btn btn-danger btn-sm" style={{padding:'4px'}} onClick={() => deleteDoc(doc.id)}>
<span className="material-symbols-outlined" style={{fontSize:'16px'}}>delete</span>
</button>
</div>
</div>
))}
</div>
+65 -27
View File
@@ -1,4 +1,4 @@
import { useEffect, useState, useRef } from 'react';
import { useEffect, useState, useRef, useCallback } from 'react';
import { Link } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { useToast } from '../context/ToastContext';
@@ -13,11 +13,7 @@ export default function UploadPersonal() {
const fileInputRefs = useRef({});
const extraFileRef = useRef(null);
useEffect(() => {
fetchTemplatesAndDocs();
}, [taxYear]);
const fetchTemplatesAndDocs = async () => {
const fetchTemplatesAndDocs = useCallback(async () => {
setLoading(true);
try {
// Fetch required templates
@@ -36,9 +32,13 @@ export default function UploadPersonal() {
} finally {
setLoading(false);
}
};
}, [authFetch, taxYear]);
const uploadFile = async (file, docType) => {
useEffect(() => {
fetchTemplatesAndDocs();
}, [taxYear, fetchTemplatesAndDocs]);
const uploadFile = async (file, docType, skipFetch = false) => {
if (file.size > 10 * 1024 * 1024) {
showToast("File size exceeds 10MB limit", "error");
return;
@@ -54,7 +54,7 @@ export default function UploadPersonal() {
});
if (res.ok) {
showToast("Document uploaded successfully", "success");
fetchTemplatesAndDocs();
if (!skipFetch) fetchTemplatesAndDocs();
} else {
const data = await res.json().catch(() => ({}));
showToast(data.detail || "Upload failed", "error");
@@ -95,12 +95,20 @@ export default function UploadPersonal() {
const handleExtraUpload = async (e) => {
const files = Array.from(e.target.files);
const validFiles = [];
for (let file of files) {
if (file.size > 10 * 1024 * 1024) {
showToast(`File ${file.name} exceeds 10MB limit`, "error");
continue;
}
await uploadFile(file, "other");
validFiles.push(file);
}
if (validFiles.length > 0) {
await Promise.all(validFiles.map((file, idx) =>
uploadFile(file, `other_${Date.now()}_${idx}`, true)
));
fetchTemplatesAndDocs();
}
e.target.value = "";
};
@@ -174,7 +182,12 @@ export default function UploadPersonal() {
hidden
accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx"
ref={el => fileInputRefs.current[dt.name] = el}
onChange={(e) => e.target.files[0] && uploadFile(e.target.files[0], dt.name)}
onChange={(e) => {
if (e.target.files[0]) {
uploadFile(e.target.files[0], dt.name);
e.target.value = null;
}
}}
/>
<div style={{display: 'flex', gap: '8px', alignItems: 'center'}}>
{dt.download && (
@@ -187,9 +200,11 @@ export default function UploadPersonal() {
)}
</div>
{uploaded.map(doc => (
<div key={doc.id} style={{display:'flex', gap:'8px'}}>
<button className="btn btn-secondary btn-xs" style={{borderRadius:'var(--radius-sm)'}} onClick={() => viewDoc(doc.storage_key)}>View</button>
<button className="btn btn-danger btn-xs" style={{borderRadius:'var(--radius-sm)'}} onClick={() => deleteDoc(doc.id)}>Delete</button>
<div key={doc.id} style={{display:'flex', flexDirection:'column', gap:'8px', alignItems:'flex-end'}}>
<div style={{display:'flex', gap:'8px'}}>
<button className="btn btn-secondary btn-xs" style={{borderRadius:'var(--radius-sm)'}} onClick={() => viewDoc(doc.storage_key)}>View</button>
<button className="btn btn-danger btn-xs" style={{borderRadius:'var(--radius-sm)'}} onClick={() => deleteDoc(doc.id)}>Delete</button>
</div>
</div>
))}
</div>
@@ -205,30 +220,53 @@ export default function UploadPersonal() {
<h3>Additional Documents</h3>
<p className="text-sm" style={{marginTop:'2px'}}>Upload any supplementary personal documents</p>
</div>
<label className="btn btn-secondary btn-sm" style={{borderRadius:'var(--radius-sm)', cursor:'pointer'}}>
<label
className="btn btn-secondary btn-sm"
style={{borderRadius:'var(--radius-sm)', cursor:'pointer'}}
tabIndex={0}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
extraFileRef.current?.click();
}
}}
>
+ Choose Files
<input type="file" multiple hidden accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx" onChange={handleExtraUpload} />
</label>
</div>
<div className="drop-area" style={{ border:'2px dashed #b8cfdf', borderRadius:'var(--radius-md)', padding:'28px 20px', textAlign:'center', cursor:'pointer', background:'var(--card)' }} onClick={() => extraFileRef.current?.click()}>
<div className="da-icon"><span className="material-symbols-outlined" style={{color: '#ffca28', fontSize: '32px'}}>folder</span></div>
<div
className="drop-area"
style={{ border:'2px dashed #cfc7ad', borderRadius:'var(--radius-md)', padding:'28px 20px', textAlign:'center', cursor:'pointer', background:'var(--card)' }}
onClick={() => extraFileRef.current?.click()}
tabIndex={0}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
extraFileRef.current?.click();
}
}}
>
<div className="da-icon"><span className="material-symbols-outlined" style={{color: 'var(--brass)', fontSize: '32px'}}>folder</span></div>
<div className="da-title" style={{fontWeight: 600, color: 'var(--navy)', fontSize: '14px'}}>Drag & drop files here</div>
<div className="da-hint" style={{fontSize: '12px', color: 'var(--muted)'}}>or click to browse · PDF, JPG, PNG, WEBP, DOC, DOCX · Max 10MB</div>
</div>
<input type="file" multiple hidden ref={extraFileRef} onChange={handleExtraUpload} />
<div className="upload-track mt-12">
{docs.filter(d => d.doc_type === "other").map(doc => (
<div key={doc.id} className="upload-track-item" style={{display:'flex', alignItems:'center', gap:'10px', padding:'8px 12px', borderRadius:'var(--radius-sm)', background:'#f5f8fb', fontSize:'13px', marginBottom:'6px'}}>
<span className="material-symbols-outlined" style={{color:'var(--green)', fontSize:'18px'}}>check_circle</span>
<div className="uti-name" style={{flex:1}}>{doc.filename}</div>
<button className="btn btn-secondary btn-sm" style={{padding:'4px'}} onClick={() => viewDoc(doc.storage_key)}>
<span className="material-symbols-outlined" style={{fontSize:'16px'}}>visibility</span>
</button>
<button className="btn btn-danger btn-sm" style={{padding:'4px'}} onClick={() => deleteDoc(doc.id)}>
<span className="material-symbols-outlined" style={{fontSize:'16px'}}>delete</span>
</button>
{docs.filter(d => d.doc_type.startsWith("other")).map(doc => (
<div key={doc.id} style={{marginBottom:'6px'}}>
<div className="upload-track-item" style={{display:'flex', alignItems:'center', gap:'10px', padding:'8px 12px', borderRadius:'var(--radius-sm)', background:'var(--paper)', fontSize:'13px'}}>
<span className="material-symbols-outlined" style={{color:'var(--green)', fontSize:'18px'}}>check_circle</span>
<div className="uti-name" style={{flex:1}}>{doc.filename}</div>
<button className="btn btn-secondary btn-sm" style={{padding:'4px'}} onClick={() => viewDoc(doc.storage_key)}>
<span className="material-symbols-outlined" style={{fontSize:'16px'}}>visibility</span>
</button>
<button className="btn btn-danger btn-sm" style={{padding:'4px'}} onClick={() => deleteDoc(doc.id)}>
<span className="material-symbols-outlined" style={{fontSize:'16px'}}>delete</span>
</button>
</div>
</div>
))}
</div>
+37 -38
View File
@@ -1,4 +1,4 @@
import { useState, useEffect } from 'react';
import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { useToast } from '../context/ToastContext';
@@ -13,12 +13,9 @@ export default function UserDashboard() {
const [loadingDocs, setLoadingDocs] = useState(false);
const [docLoading, setDocLoading] = useState(false);
useEffect(() => {
checkEngagement();
loadAdminDocs();
}, []);
// ── declare callbacks BEFORE the effects that reference them ──
const checkEngagement = async () => {
const checkEngagement = useCallback(async () => {
try {
const res = await authFetch("/api/auth/me");
if (res.ok) {
@@ -31,16 +28,33 @@ export default function UserDashboard() {
} catch (err) {
console.error(err);
}
};
}, [authFetch]);
const loadAdminDocs = useCallback(async () => {
setLoadingDocs(true);
try {
const res = await authFetch("/api/upload/admin-documents");
if (res.ok) {
setAdminDocs(await res.json());
}
} catch (err) {
console.error(err);
} finally {
setLoadingDocs(false);
}
}, [authFetch]);
useEffect(() => {
checkEngagement();
loadAdminDocs();
}, [checkEngagement, loadAdminDocs]);
const handleEngagementChange = async (e) => {
const isChecked = e.target.checked;
if (!isChecked) {
// Don't allow unchecking
setEngagementChecked(true);
return;
}
try {
setEngagementChecked(true);
const res = await authFetch("/api/auth/acknowledge-engagement", { method: "POST" });
@@ -55,20 +69,6 @@ export default function UserDashboard() {
}
};
const loadAdminDocs = async () => {
setLoadingDocs(true);
try {
const res = await authFetch("/api/upload/admin-documents");
if (res.ok) {
setAdminDocs(await res.json());
}
} catch (err) {
console.error(err);
} finally {
setLoadingDocs(false);
}
};
const viewDoc = async (storageKey) => {
try {
const res = await authFetch(`/api/upload/view-url?key=${encodeURIComponent(storageKey)}`);
@@ -85,13 +85,11 @@ export default function UserDashboard() {
const respondDoc = async (docId, approved) => {
if (docLoading) return;
let reason = "";
if (!approved) {
reason = window.prompt("Reason for rejection:");
if (reason === null) return;
}
setDocLoading(true);
try {
const res = await authFetch("/api/review/admin-doc-response", {
@@ -123,22 +121,23 @@ export default function UserDashboard() {
<div className="card fade-up">
<h3 style={{marginBottom: '16px'}}>Engagement Letter</h3>
<p className="text-sm" style={{marginBottom: '16px'}}>Please acknowledge the engagement letter before uploading documents.</p>
<div style={{
<label style={{
display: 'flex', alignItems: 'center', gap: '12px', padding: '16px',
background: 'var(--bg)', borderRadius: 'var(--radius-sm)', border: '1px solid var(--border)'
background: 'var(--bg)', borderRadius: 'var(--radius-sm)', border: '1px solid var(--border)',
cursor: engagementDisabled ? 'not-allowed' : 'pointer'
}}>
<input
type="checkbox"
<input
type="checkbox"
checked={engagementChecked}
disabled={engagementDisabled}
onChange={handleEngagementChange}
style={{width:'20px', height:'20px', cursor: engagementDisabled ? 'not-allowed' : 'pointer'}}
style={{width:'20px', height:'20px', cursor: engagementDisabled ? 'not-allowed' : 'pointer'}}
/>
<div>
<div style={{fontWeight: 600, color: 'var(--navy)'}}>I acknowledge the Engagement Letter</div>
<div style={{fontSize: '13px', color: 'var(--muted)', marginTop: '2px'}}>By checking this, you agree to our terms of service for the current tax year.</div>
</div>
</div>
</label>
</div>
<div style={{display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: '20px', marginTop: '20px'}}>
@@ -148,23 +147,23 @@ export default function UserDashboard() {
<h3 style={{margin:0}}>Personal Documents</h3>
</div>
<p className="text-sm text-muted" style={{marginBottom: '20px', minHeight: '40px'}}>Upload your W-2s, 1099s, IDs, and other individual tax forms.</p>
<button
className="btn btn-primary w-full"
<button
className="btn btn-primary w-full"
disabled={!engagementChecked}
onClick={() => navigate('/upload-personal')}
>
Go to Personal Upload
</button>
</div>
<div className="card fade-up" style={{animationDelay: '0.2s'}}>
<div style={{display:'flex', alignItems:'center', gap:'12px', marginBottom: '12px'}}>
<span className="material-symbols-outlined" style={{color:'var(--orange)', fontSize:'28px'}}>business</span>
<h3 style={{margin:0}}>Business Documents</h3>
</div>
<p className="text-sm text-muted" style={{marginBottom: '20px', minHeight: '40px'}}>Upload corporate documents, bookkeeping ledgers, and business receipts.</p>
<button
className="btn btn-primary w-full"
<button
className="btn btn-primary w-full"
disabled={!engagementChecked}
onClick={() => navigate('/upload-business')}
>
@@ -176,7 +175,7 @@ export default function UserDashboard() {
<div className="card fade-up" style={{animationDelay: '0.3s', marginTop: '20px'}}>
<h3 style={{marginBottom: '16px'}}>Admin Returns / Documents</h3>
<p className="text-sm" style={{marginBottom: '16px'}}>Documents and tax returns finalized by the admin.</p>
{loadingDocs ? (
<div className="empty-state">Loading documents...</div>
) : adminDocs.length === 0 ? (
@@ -215,4 +214,4 @@ export default function UserDashboard() {
</div>
</div>
);
}
}
+36
View File
@@ -0,0 +1,36 @@
// Lightweight scroll-reveal: watches for elements with the `.reveal` class
// (added throughout the marketing pages) and adds `.in-view` once they enter
// the viewport. Re-scans on DOM mutation so it keeps working across route
// changes in the SPA without needing per-page wiring.
let observer;
function ensureObserver() {
if (observer) return observer;
observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.classList.add('in-view');
observer.unobserve(entry.target);
}
});
},
{ threshold: 0.15, rootMargin: '0px 0px -40px 0px' }
);
return observer;
}
function scan() {
const obs = ensureObserver();
document.querySelectorAll('.reveal:not(.in-view)').forEach((el) => obs.observe(el));
}
export function initScrollReveal() {
if (typeof window === 'undefined') return;
scan();
const mo = new MutationObserver(() => scan());
mo.observe(document.getElementById('root') || document.body, {
childList: true,
subtree: true,
});
}
+8 -8
View File
@@ -479,7 +479,7 @@ def list_users_for_admin(
"""
from sqlalchemy import func as sqlfunc
def _pending_count(uid: int) -> int:
def _pending_count(uid: int) -> dict:
p = db.query(sqlfunc.count(PersonalDocument.id)).filter(
PersonalDocument.user_id == uid,
PersonalDocument.review_status == "pending",
@@ -490,7 +490,7 @@ def list_users_for_admin(
BusinessDocument.review_status == "pending",
BusinessDocument.deleted_at == None,
).scalar() or 0
return p + b
return {"pending_personal": p, "pending_business": b, "pending_docs": p + b}
if current_user.role == UserRole.super_admin:
q = db.query(UserModel)
@@ -503,12 +503,12 @@ def list_users_for_admin(
return {
"users": [
{
"id": u.id,
"name": u.name,
"email": u.email,
"phone": u.phone,
"role": u.role.value if hasattr(u.role, "value") else str(u.role),
"pending_docs": _pending_count(u.id),
"id": u.id,
"name": u.name,
"email": u.email,
"phone": u.phone,
"role": u.role.value if hasattr(u.role, "value") else str(u.role),
**_pending_count(u.id), # inlines pending_personal, pending_business, pending_docs (total)
}
for u in users
],
+31 -74
View File
@@ -1,6 +1,6 @@
import os
import logging
from fastapi import FastAPI, HTTPException, Request
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
@@ -92,9 +92,15 @@ def mount_if_exists(route: str, subdir: str, name: str):
log.debug("Static directory not found, skipping: %s", path)
mount_if_exists("/js", "js", "js")
mount_if_exists("/images", "images", "images")
mount_if_exists("/css", "css", "css")
mount_if_exists("/js", "dist/js", "js")
mount_if_exists("/images", "dist/images", "images")
mount_if_exists("/css", "dist/css", "css")
# Mount Vite build assets (JS bundles, hashed chunks)
DIST_ASSETS = os.path.join(FRONTEND_DIR, "dist", "assets")
if os.path.isdir(DIST_ASSETS):
app.mount("/assets", StaticFiles(directory=DIST_ASSETS), name="assets")
log.info("Mounted Vite assets -> %s", DIST_ASSETS)
UPLOAD_DIR = os.path.abspath(os.path.join(FRONTEND_DIR, "..", "uploads"))
if not os.path.exists(UPLOAD_DIR):
@@ -103,25 +109,14 @@ if not os.path.exists(UPLOAD_DIR):
log.info("FRONTEND_DIR resolved to: %s", FRONTEND_DIR)
log.info("CSS dir exists: %s", os.path.isdir(os.path.join(FRONTEND_DIR, "css")))
DIST_DIR = os.path.join(FRONTEND_DIR, "dist")
SPA_INDEX = os.path.join(DIST_DIR, "index.html")
from fastapi.templating import Jinja2Templates
templates = Jinja2Templates(directory=FRONTEND_DIR)
def serve_frontend_file(request: Request, filename: str):
full = os.path.join(FRONTEND_DIR, filename)
if os.path.isfile(full):
return templates.TemplateResponse(
name=filename,
context={"request": request},
headers={
"Cache-Control": "no-store, no-cache, must-revalidate",
"Pragma": "no-cache",
"Expires": "0",
},
)
log.warning("Frontend file not found: %s", full)
raise HTTPException(status_code=404, detail="Page not found")
# Mount the Vite dist folder for hashed static assets not already mounted above
# (favicon, icons.svg, etc.)
if os.path.isdir(DIST_DIR):
# Serve root-level static assets that Vite places at dist/
app.mount("/dist", StaticFiles(directory=DIST_DIR), name="dist_root")
# ─────────────────────────────────────────────
@@ -141,57 +136,19 @@ def logout():
# ─────────────────────────────────────────────
# Frontend page routes
# SPA catch-all — serve index.html for every non-API GET route
# so React Router handles client-side navigation on direct URL access
# ─────────────────────────────────────────────
@app.get("/", tags=["frontend"])
def home(request: Request): return serve_frontend_file(request, "home.html")
@app.get("/home", tags=["frontend"])#route to home page
def home_page(request: Request): return serve_frontend_file(request, "home.html")
@app.get("/login", tags=["frontend"]) #route to login page
def login_page(request: Request): return serve_frontend_file(request, "login.html")
@app.get("/signup", tags=["frontend"]) #route to signup page
def signup_page(request: Request): return serve_frontend_file(request, "signup.html")
@app.get("/dashboard", tags=["frontend"])
def dashboard_page(request: Request): return serve_frontend_file(request, "dashboard.html") #route to dashboard page
@app.get("/admin-dashboard", tags=["frontend"])
def admin_dashboard_page(request: Request): return serve_frontend_file(request, "admin-dashboard.html") #route to admin dashboard page
@app.get("/admin-user-detail", tags=["frontend"])
def admin_user_detail(request: Request): return serve_frontend_file(request, "admin-user-detail.html") #route to admin-user-detail page
@app.get("/upload-personal", tags=["frontend"])
def upload_personal(request: Request): return serve_frontend_file(request, "upload-personal.html") #route to upload-personal
@app.get("/upload-business", tags=["frontend"])
def upload_business(request: Request): return serve_frontend_file(request, "upload-business.html") #route to upload-business
@app.get("/contact", tags=["frontend"])
def contact_page(request: Request): return serve_frontend_file(request, "contact.html") #route to contact page
@app.get("/services", tags=["frontend"])
def services_page(request: Request): return serve_frontend_file(request, "services.html") #route to service page
@app.get("/about-us", tags=["frontend"])
def about_us_page(request: Request): return serve_frontend_file(request, "about-us.html") # route to about-us page
@app.get("/forgot-password", tags=["frontend"])
def forgot_password_page(request: Request): return serve_frontend_file(request, "forgot-password.html")
@app.get("/profile", tags=["frontend"])
def profile_page(request: Request): return serve_frontend_file(request, "profile.html") #route to forgot-password page
@app.get("/reset-password", tags=["frontend"])
def reset_password_page(request: Request): return serve_frontend_file(request, "reset-password.html") #route to reset-password page
@app.get("/verify-email", tags=["frontend"])
def verify_email_page(request: Request): return serve_frontend_file(request, "verify-email.html")# route to verify-email page
@app.get("/resend-verification", tags=["frontend"]) # route to resend-verification page
def resend_verification_page(request: Request): return serve_frontend_file(request, "resend-verification.html")
@app.get("/{full_path:path}", tags=["frontend"])
def spa_fallback(full_path: str):
if os.path.isfile(SPA_INDEX):
return FileResponse(
SPA_INDEX,
headers={
"Cache-Control": "no-store, no-cache, must-revalidate",
"Pragma": "no-cache",
"Expires": "0",
},
)
raise HTTPException(status_code=404, detail="Frontend not built. Run 'npm run build' in /frontend.")
+3
View File
@@ -7,6 +7,7 @@ from sqlalchemy import (
Index,
Integer,
String,
JSON,
UniqueConstraint,
func,
)
@@ -61,6 +62,7 @@ class PersonalDocument(Base):
review_status = Column(String(20), default="pending", nullable=False)
review_note = Column(String(500), nullable=True)
tax_year = Column(Integer, default=2025, nullable=False)
extracted_data = Column(JSON, nullable=True)
user = relationship("User")
@@ -87,6 +89,7 @@ class BusinessDocument(Base):
review_status = Column(String(20), default="pending", nullable=False)
review_note = Column(String(500), nullable=True)
tax_year = Column(Integer, default=2025, nullable=False)
extracted_data = Column(JSON, nullable=True)
user = relationship("User")
+244 -97
View File
@@ -1,11 +1,14 @@
import logging
from fastapi import APIRouter, Depends
from datetime import datetime, date, timedelta
from fastapi import APIRouter, Depends, Request, Query
from app.limiter import limiter
from sqlalchemy.orm import Session
from sqlalchemy import func, or_
import os
import requests
from pydantic import BaseModel
from fastapi import HTTPException
from app.models import PersonalDocument, BusinessDocument, User
from app.models import PersonalDocument, BusinessDocument, User, AuditLog
from app.db import get_db
from app.auth.security import get_current_user, require_admin
@@ -14,59 +17,43 @@ logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/chatbot", tags=["chatbot"])
# ─────────────────────────────────────────────────────────────────────────────
# User: doc status
# ─────────────────────────────────────────────────────────────────────────────
@router.get("/doc-status")
def get_doc_status(
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
):
"""Return a consolidated summary of the user's document statuses."""
personal = (
db.query(PersonalDocument)
.filter(
PersonalDocument.user_id == current_user.id,
PersonalDocument.deleted_at == None,
)
.filter(PersonalDocument.user_id == current_user.id, PersonalDocument.deleted_at == None)
.order_by(PersonalDocument.tax_year.desc(), PersonalDocument.uploaded_at.desc())
.all()
)
business = (
db.query(BusinessDocument)
.filter(
BusinessDocument.user_id == current_user.id,
BusinessDocument.deleted_at == None,
)
.filter(BusinessDocument.user_id == current_user.id, BusinessDocument.deleted_at == None)
.order_by(BusinessDocument.tax_year.desc(), BusinessDocument.uploaded_at.desc())
.all()
)
personal_list = [
{
"doc_type": d.doc_type,
"status": d.review_status,
"note": d.review_note,
"tax_year": d.tax_year,
"filename": d.filename,
}
{"doc_type": d.doc_type, "status": d.review_status, "note": d.review_note,
"tax_year": d.tax_year, "filename": d.filename}
for d in personal
]
business_list = [
{
"business_type": d.business_type,
"status": d.review_status,
"note": d.review_note,
"tax_year": d.tax_year,
"filename": d.filename,
}
{"business_type": d.business_type, "status": d.review_status, "note": d.review_note,
"tax_year": d.tax_year, "filename": d.filename}
for d in business
]
all_docs = personal_list + business_list
summary = {
"total": len(all_docs),
"pending": sum(1 for d in all_docs if d["status"] == "pending"),
"total": len(all_docs),
"pending": sum(1 for d in all_docs if d["status"] == "pending"),
"approved": sum(1 for d in all_docs if d["status"] == "approved"),
"rejected": sum(1 for d in all_docs if d["status"] == "rejected"),
}
@@ -76,67 +63,163 @@ def get_doc_status(
msg_lines.append("You have not uploaded any documents yet.")
else:
msg_lines.append(f"You have uploaded <b>{summary['total']}</b> documents in total.")
if summary["pending"] > 0:
if summary["pending"]:
msg_lines.append(f"<br>• <b>{summary['pending']}</b> pending review.")
if summary["approved"] > 0:
if summary["approved"]:
msg_lines.append(f"<br>• <span style='color:var(--success)'><b>{summary['approved']}</b> approved.</span>")
if summary["rejected"] > 0:
if summary["rejected"]:
msg_lines.append(f"<br>• <span style='color:var(--error)'><b>{summary['rejected']}</b> rejected.</span> Please check the upload pages for notes.")
return {
"personal": personal_list,
"business": business_list,
"summary": summary,
"message": "".join(msg_lines),
}
return {"personal": personal_list, "business": business_list, "summary": summary,
"message": "".join(msg_lines)}
# ─────────────────────────────────────────────────────────────────────────────
# Admin: system overview stats
# ─────────────────────────────────────────────────────────────────────────────
@router.get("/admin-status")
def get_admin_status(
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
"""Return system-wide stats for the super admin chatbot."""
total_users = db.query(User).count()
"""Return system-wide stats for the admin chatbot."""
today_start = datetime.combine(date.today(), datetime.min.time())
total_users = db.query(User).count()
new_users_today = db.query(User).filter(User.created_at >= today_start).count()
pending_personal = (
db.query(PersonalDocument)
.filter(
PersonalDocument.review_status == "pending",
PersonalDocument.deleted_at == None,
)
.filter(PersonalDocument.review_status == "pending", PersonalDocument.deleted_at == None)
.count()
)
pending_business = (
db.query(BusinessDocument)
.filter(BusinessDocument.review_status == "pending", BusinessDocument.deleted_at == None)
.count()
)
pending_business = (
db.query(BusinessDocument)
.filter(
BusinessDocument.review_status == "pending",
BusinessDocument.deleted_at == None,
)
.count()
# Most recent 10 uploads across both tables
recent_personal = (
db.query(PersonalDocument)
.filter(PersonalDocument.deleted_at == None)
.order_by(PersonalDocument.uploaded_at.desc())
.limit(10).all()
)
recent_business = (
db.query(BusinessDocument)
.filter(BusinessDocument.deleted_at == None)
.order_by(BusinessDocument.uploaded_at.desc())
.limit(10).all()
)
# Merge and sort to get true top-10 latest
recent_uploads = sorted(
[{"user_id": d.user_id, "doc": d.doc_type, "type": "personal",
"uploaded_at": d.uploaded_at, "status": d.review_status} for d in recent_personal] +
[{"user_id": d.user_id, "doc": d.business_type, "type": "business",
"uploaded_at": d.uploaded_at, "status": d.review_status} for d in recent_business],
key=lambda x: x["uploaded_at"], reverse=True
)[:10]
# Enrich with user names
user_map = {u.id: u for u in db.query(User).filter(User.id.in_([r["user_id"] for r in recent_uploads])).all()}
for r in recent_uploads:
u = user_map.get(r["user_id"])
r["user_name"] = u.name if u else "Unknown"
r["user_email"] = u.email if u else "Unknown"
r["uploaded_at"] = r["uploaded_at"].strftime("%Y-%m-%d %H:%M") if r["uploaded_at"] else "N/A"
message = (
f"<b>System Overview:</b><br><br>"
f"• Total Users: <b>{total_users}</b><br>"
f"• Total Users: <b>{total_users}</b> (<b>{new_users_today}</b> joined today)<br>"
f"• Pending Personal Docs: <b>{pending_personal}</b><br>"
f"• Pending Business Docs: <b>{pending_business}</b><br><br>"
)
if pending_personal + pending_business > 0:
message += f"You have <b>{pending_personal + pending_business}</b> documents awaiting review in the Dashboard."
total_pending = pending_personal + pending_business
if total_pending > 0:
message += f"You have <b>{total_pending}</b> documents awaiting review."
else:
message += "All documents have been reviewed!"
return {
"total_users": total_users,
"total_users": total_users,
"new_users_today": new_users_today,
"pending_personal": pending_personal,
"pending_business": pending_business,
"total_pending": pending_personal + pending_business,
"message": message,
"total_pending": total_pending,
"recent_uploads": recent_uploads,
"message": message,
}
# ─────────────────────────────────────────────────────────────────────────────
# Admin: rich context for a specific user (activity + docs)
# ─────────────────────────────────────────────────────────────────────────────
@router.get("/admin-user-context")
def get_admin_user_context(
query: str = Query(..., description="User name or email to search for"),
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
"""Search for a user by name/email and return their full activity context."""
q = f"%{query}%"
user = (
db.query(User)
.filter(or_(User.name.ilike(q), User.email.ilike(q)))
.first()
)
if not user:
return {"found": False, "message": f"No user found matching '{query}'."}
# Docs
personal = db.query(PersonalDocument).filter(
PersonalDocument.user_id == user.id, PersonalDocument.deleted_at == None
).order_by(PersonalDocument.uploaded_at.desc()).all()
business = db.query(BusinessDocument).filter(
BusinessDocument.user_id == user.id, BusinessDocument.deleted_at == None
).order_by(BusinessDocument.uploaded_at.desc()).all()
# Audit log (last 20 actions)
audit = (
db.query(AuditLog)
.filter(AuditLog.user_id == user.id)
.order_by(AuditLog.created_at.desc())
.limit(20).all()
)
return {
"found": True,
"user": {
"id": user.id,
"name": user.name,
"email": user.email,
"role": user.role.value if hasattr(user.role, "value") else str(user.role),
"joined": user.created_at.strftime("%Y-%m-%d") if user.created_at else "N/A",
"engagement_acknowledged": bool(user.engagement_acknowledged_at),
},
"documents": {
"personal": [{"doc_type": d.doc_type, "status": d.review_status,
"tax_year": d.tax_year,
"uploaded_at": d.uploaded_at.strftime("%Y-%m-%d %H:%M") if d.uploaded_at else "N/A"} for d in personal],
"business": [{"business_type": d.business_type, "status": d.review_status,
"tax_year": d.tax_year,
"uploaded_at": d.uploaded_at.strftime("%Y-%m-%d %H:%M") if d.uploaded_at else "N/A"} for d in business],
},
"audit_log": [
{"action": l.action, "detail": l.detail, "ip": l.ip_address,
"at": l.created_at.strftime("%Y-%m-%d %H:%M") if l.created_at else "N/A"}
for l in audit
],
}
# ─────────────────────────────────────────────────────────────────────────────
# Shared chat endpoint
# ─────────────────────────────────────────────────────────────────────────────
class ChatMessage(BaseModel):
role: str
content: str
@@ -145,75 +228,139 @@ class ChatMessage(BaseModel):
class ChatRequest(BaseModel):
messages: list[ChatMessage]
def _build_admin_context(db: Session, current_user) -> str:
"""Build a rich real-time context string for the admin system prompt."""
status = get_admin_status(db=db, current_user=current_user, _=None)
ctx = f"=== LIVE SYSTEM DATA (as of {datetime.now().strftime('%Y-%m-%d %H:%M')}) ===\n"
ctx += f"Total registered users: {status['total_users']}\n"
ctx += f"New users registered TODAY: {status['new_users_today']}\n"
ctx += f"Pending personal docs (system-wide): {status['pending_personal']}\n"
ctx += f"Pending business docs (system-wide): {status['pending_business']}\n"
ctx += f"Total pending docs: {status['total_pending']}\n\n"
if status["recent_uploads"]:
ctx += "=== MOST RECENT DOCUMENT UPLOADS ===\n"
for r in status["recent_uploads"]:
ctx += (f"- {r['user_name']} ({r['user_email']}) uploaded a "
f"{r['type']} doc '{r['doc']}' on {r['uploaded_at']} "
f"[status: {r['status']}]\n")
return ctx
@router.post("/ask")
@limiter.limit("5/minute")
def ask_chatbot(
request: Request,
req: ChatRequest,
current_user=Depends(get_current_user)
current_user=Depends(get_current_user),
db: Session = Depends(get_db),
):
"""Send a message to OpenRouter AI."""
api_key = os.environ.get("OPENROUTER_API_KEY")
if not api_key:
raise HTTPException(status_code=500, detail="OpenRouter API key not configured")
is_admin = current_user.role in ("admin", "super_admin")
system_prompt = ""
if is_admin:
context = _build_admin_context(db, current_user)
# Check if the latest user message references a specific user — if so, fetch their data
last_user_msg = next((m.content for m in reversed(req.messages) if m.role == "user"), "")
user_context_addon = ""
if any(kw in last_user_msg.lower() for kw in ["user", "who", "activity", "uploaded", "registered", "recent"]):
# Try to find a name/email in the message
words = last_user_msg.replace(",", " ").replace("?", " ").split()
for word in words:
if "@" in word or len(word) > 4:
result = get_admin_user_context(query=word, db=db, current_user=current_user, _=None)
if result.get("found"):
u = result["user"]
docs = result["documents"]
audit = result["audit_log"]
user_context_addon = f"\n\n=== USER DETAIL: {u['name']} ({u['email']}) ===\n"
user_context_addon += f"Role: {u['role']} | Joined: {u['joined']} | Engagement acknowledged: {u['engagement_acknowledged']}\n"
if docs["personal"]:
user_context_addon += "Personal docs: " + "; ".join(
f"{d['doc_type']} ({d['tax_year']}) [{d['status']}] uploaded {d['uploaded_at']}"
for d in docs["personal"]) + "\n"
if docs["business"]:
user_context_addon += "Business docs: " + "; ".join(
f"{d['business_type']} ({d['tax_year']}) [{d['status']}] uploaded {d['uploaded_at']}"
for d in docs["business"]) + "\n"
if audit:
user_context_addon += "Recent activity:\n" + "\n".join(
f" [{a['at']}] {a['action']} — {a['detail'] or ''} (IP: {a['ip'] or 'N/A'})"
for a in audit[:10]) + "\n"
break
system_prompt = (
"You are the BookKeepPro Admin Assistant. Your ONLY job is to help admins with this specific application's internal processes. "
"IMPORTANT: Do NOT make up URLs, generic advice, or flows. Answer ONLY based on this application's actual flow:\n"
"- How to view users: On the Admin Dashboard, click any user in the table to go to their Admin User Detail page.\n"
"- How to review/approve docs: On the Admin User Detail page, you will see their uploaded documents. Click a document to download/view it, change its status to 'Approved' or 'Rejected', add an optional review note, and click 'Submit Review'.\n"
"- If a doc is rejected: The user is notified and must re-upload it.\n"
"Rule: You must ONLY answer questions related to system administration, BookKeepPro, accounting, or taxes. If the admin asks about anything else, politely decline."
"You are the BookKeepPro Admin Assistant — a knowledgeable, concise AI that has live access to the system's data.\n\n"
"CAPABILITIES:\n"
"- You can answer questions about which users uploaded documents and when.\n"
"- You can report how many new users registered today or on any date.\n"
"- You can show recent activity and document history for any specific user.\n"
"- You can answer questions about document review status system-wide.\n\n"
"RULES:\n"
"- Only answer questions related to BookKeepPro administration, accounting, or taxes.\n"
"- Use the live data below to answer. Do NOT make up user names, counts, or dates.\n"
"- Be concise and direct. Format answers clearly.\n\n"
f"{context}{user_context_addon}"
)
else:
doc_status = get_doc_status(db=db, current_user=current_user)
summary = doc_status["summary"]
context = f"Total Documents: {summary['total']}\nPending: {summary['pending']}\nApproved: {summary['approved']}\nRejected: {summary['rejected']}\n"
if doc_status["personal"]:
context += "\nPersonal Documents:\n"
for d in doc_status["personal"]:
note = f" — Admin note: {d['note']}" if d['note'] else ""
context += f" • {d['doc_type']} ({d['tax_year']}): {d['status']}{note}\n"
if doc_status["business"]:
context += "\nBusiness Documents:\n"
for d in doc_status["business"]:
note = f" — Admin note: {d['note']}" if d['note'] else ""
context += f" • {d['business_type']} ({d['tax_year']}): {d['status']}{note}\n"
system_prompt = (
"You are the BookKeepPro Assistant. Your ONLY job is to help users navigate this specific application's features and answer basic accounting/tax questions. "
"IMPORTANT: Do NOT make up URLs (like portal.bookkeeppro.com) or generic advice. Answer ONLY based on this application's actual flow:\n"
"- How to upload documents: On your Dashboard, find the 'Required Documents' section. Click on a document slot (e.g., Personal or Business) to go to the Upload page. Drag and drop your file (PDF, JPG, PNG, DOCX) or click to browse, then click 'Upload Document'.\n"
"- How to check doc status: Look at your Dashboard under 'Required Documents'. It will show 'Pending' (waiting for admin), 'Approved', or 'Rejected'.\n"
"- If rejected: Click the rejected document slot again to see the admin's note and upload a new version.\n"
"Rule: You must ONLY answer questions related to BookKeepPro, accounting, or taxes. If the user asks about anything else, politely decline."
"You are the BookKeepPro Assistant. Help users with this application and basic accounting/tax questions.\n\n"
"APPLICATION FLOW:\n"
"- Upload documents: Dashboard → Personal Upload or Business Upload page → drag & drop or click to browse.\n"
"- Check status: Documents show Pending (waiting for admin), Approved, or Rejected.\n"
"- If rejected: see the admin's note on the upload page and re-upload a corrected version.\n"
"- Profile: update your name, phone, or password on the Profile page.\n\n"
"RULES:\n"
"- Only answer questions about BookKeepPro, accounting, or taxes.\n"
"- Use the live data below to answer questions about the user's documents.\n\n"
f"=== LIVE DATA for {current_user.name or current_user.email} ===\n{context}"
)
messages = [{"role": "system", "content": system_prompt}]
for m in req.messages:
msg = {"role": m.role, "content": m.content}
if m.reasoning_details:
msg["reasoning_details"] = m.reasoning_details
messages.append(msg)
messages.append({"role": m.role, "content": m.content})
try:
response = requests.post(
url="https://openrouter.ai/api/v1/chat/completions",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json={
"model": "nvidia/nemotron-3-super-120b-a12b:free",
"messages": messages,
"reasoning": {"enabled": True}
},
timeout=30
headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
json={"model": "meta-llama/llama-3.3-70b-instruct", "messages": messages},
timeout=30,
)
response.raise_for_status()
data = response.json()
if "error" in data:
logger.error(f"OpenRouter returned an error payload: {data['error']}")
raise HTTPException(status_code=502, detail="AI Service is currently overloaded. Please try again.")
logger.error(f"OpenRouter error: {data['error']}")
raise HTTPException(status_code=502, detail="AI service overloaded. Please try again.")
if "choices" not in data:
logger.error(f"OpenRouter returned unexpected payload: {data}")
raise HTTPException(status_code=502, detail="Unexpected response from AI service. Please try again.")
return data['choices'][0]['message']
raise HTTPException(status_code=502, detail="Unexpected AI response. Please try again.")
return data["choices"][0]["message"]
except HTTPException:
raise
except Exception as e:
logger.error(f"OpenRouter API error: {str(e)}")
logger.error(f"OpenRouter API error: {e}")
raise HTTPException(status_code=500, detail="Failed to connect to AI service")
+60 -8
View File
@@ -15,11 +15,14 @@ from jose import jwt, JWTError
from datetime import timedelta
from app.models import AdminDocument, PersonalDocument, BusinessDocument, User, UserRole
from app.db import get_db
from app.db import get_db, SessionLocal
import app.crud as crud
from app.auth.security import get_current_user, require_admin, SECRET_KEY, ALGORITHM
from app.utils.emailer import send_email
from app.utils.ai import extract_document_data
from app.schemas import UploadCompleteNotify, ReviewStatusUpdate
from app.limiter import limiter
from fastapi import Request
logger = logging.getLogger(__name__)
@@ -35,6 +38,26 @@ BASE_DIR = Path(__file__).resolve().parents[4]
UPLOAD_DIR = BASE_DIR / "uploads"
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
def process_ai_extraction(table: str, doc_id: int, file_path: str, doc_type: str):
extracted = extract_document_data(file_path, doc_type)
if extracted is None:
return
db = SessionLocal()
try:
if table == "personal":
doc = db.query(PersonalDocument).filter_by(id=doc_id).first()
else:
doc = db.query(BusinessDocument).filter_by(id=doc_id).first()
if doc:
doc.extracted_data = extracted
db.commit()
except Exception as e:
logger.error(f"Failed to update DB with AI extraction: {e}")
finally:
db.close()
async def upload_to_storage(file: UploadFile) -> str:
"""Upload to local disk. Returns the filename (storage_key)."""
await file.seek(0)
@@ -53,6 +76,8 @@ async def upload_to_storage(file: UploadFile) -> str:
"image/webp",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.ms-excel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
}
kind = filetype.guess(contents)
@@ -60,15 +85,15 @@ async def upload_to_storage(file: UploadFile) -> str:
ext = os.path.splitext(file.filename or "file")[1].lower()
# Fallback for legacy .doc and inconsistent .docx sniffing
# Fallback for legacy .doc, .xls, and inconsistent .docx/.xlsx sniffing (which are just zip files)
if sniffed_mime is None or sniffed_mime == "application/zip":
if ext in [".doc", ".docx"] and file.content_type in ALLOWED_TYPES:
if ext in [".doc", ".docx", ".xls", ".xlsx"] and file.content_type in ALLOWED_TYPES:
sniffed_mime = file.content_type
if sniffed_mime not in ALLOWED_TYPES:
raise HTTPException(
status_code=400,
detail=f"File type not allowed or could not be verified. Allowed: PDF, JPG, PNG, WEBP, DOC, DOCX."
detail=f"File type not allowed or could not be verified. Allowed: PDF, JPG, PNG, WEBP, DOC, DOCX, XLS, XLSX."
)
ext = os.path.splitext(file.filename or "file")[1].lower()
@@ -345,6 +370,9 @@ async def upload_personal_document(
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
):
if not current_user.engagement_acknowledged_at:
raise HTTPException(status_code=403, detail="You must acknowledge the engagement letter before uploading.")
logger.info(f"User {current_user.id} uploading personal document: {file.filename}")
storage_key = await upload_to_storage(file)
@@ -380,6 +408,14 @@ async def upload_personal_document(
body=f"<p><strong>{current_user.email}</strong> uploaded a personal document: <strong>{file.filename}</strong> ({doc_type}).</p>",
)
background.add_task(
process_ai_extraction,
"personal",
record.id,
str(UPLOAD_DIR / storage_key),
doc_type
)
return {
"id": record.id,
"filename": record.filename,
@@ -407,8 +443,8 @@ def delete_personal_document(
if not doc:
raise HTTPException(status_code=404, detail="Document not found")
logger.info(f"User {current_user.id} deleting personal document {doc_id}")
delete_from_storage(doc.storage_key)
logger.info(f"User {current_user.id} deleting personal document {doc_id} (soft delete)")
# Soft delete (Option B): Keep file in storage, only mark as deleted in DB
doc.deleted_at = datetime.utcnow()
db.commit()
crud.log_action(db, "delete_personal", user_id=current_user.id, target=f"personal_doc:{doc_id}")
@@ -437,6 +473,7 @@ def list_business_documents(
return [
{
"id": d.id,
"doc_type": d.business_type,
"business_type": d.business_type,
"filename": d.filename,
"storage_key": d.storage_key,
@@ -458,6 +495,9 @@ async def upload_business_document(
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
):
if not current_user.engagement_acknowledged_at:
raise HTTPException(status_code=403, detail="You must acknowledge the engagement letter before uploading.")
logger.info(f"User {current_user.id} uploading business document: {file.filename}")
storage_key = await upload_to_storage(file)
@@ -491,6 +531,14 @@ async def upload_business_document(
subject="New Business Document Uploaded — BookKeepro",
body=f"<p><strong>{current_user.email}</strong> uploaded a business document: <strong>{file.filename}</strong> ({doc_type}).</p>",
)
background.add_task(
process_ai_extraction,
"business",
record.id,
str(UPLOAD_DIR / storage_key),
doc_type
)
return {
"id": record.id,
@@ -513,8 +561,8 @@ def delete_business_document(
if doc.user_id != current_user.id:
raise HTTPException(status_code=403, detail="Not authorized")
logger.info(f"User {current_user.id} deleting business document {doc_id}")
delete_from_storage(doc.storage_key)
logger.info(f"User {current_user.id} deleting business document {doc_id} (soft delete)")
# Soft delete (Option B): Keep file in storage, only mark as deleted in DB
doc.deleted_at = datetime.utcnow()
db.commit()
crud.log_action(db, "delete_business", user_id=current_user.id, target=f"business_doc:{doc_id}")
@@ -626,6 +674,7 @@ def get_user_all_documents(
"tax_year": d.tax_year,
"review_status": d.review_status,
"review_note": d.review_note,
"extracted_data": d.extracted_data,
}
for d in personal_docs
] + [
@@ -639,6 +688,7 @@ def get_user_all_documents(
"tax_year": d.tax_year,
"review_status": d.review_status,
"review_note": d.review_note,
"extracted_data": d.extracted_data,
}
for d in business_docs
]
@@ -730,7 +780,9 @@ def delete_user_completely(
# ─────────────────────────────────────────────
@router.post("/notify-upload-complete")
@limiter.limit("5/minute")
async def notify_upload_complete(
request: Request,
payload: UploadCompleteNotify,
background: BackgroundTasks,
db: Session = Depends(get_db),
+316
View File
@@ -0,0 +1,316 @@
import os
import json
import logging
import requests
import base64
from io import BytesIO
from pypdf import PdfReader
from PIL import Image
import fitz # PyMuPDF — PDF rendering for scanned docs
logger = logging.getLogger(__name__)
# ─────────────────────────────────────────────────────────────────────────────
# Pipeline thresholds
# ─────────────────────────────────────────────────────────────────────────────
MIN_TEXT_CHARS = 50 # Stage 1: native text must have at least this many chars
MIN_TESS_WORDS = 30 # Stage 2: Tesseract must return at least this many words
RENDER_DPI = 2.5 # PyMuPDF render scale (2.5x ≈ 212 DPI)
# ─────────────────────────────────────────────────────────────────────────────
# Models
# ─────────────────────────────────────────────────────────────────────────────
MODEL_TEXT = "meta-llama/llama-3.3-70b-instruct" # Stage 1 & 2 — FREE tier
MODEL_VISION = "qwen/qwen2.5-vl-72b-instruct" # Stage 3 — best document OCR
# ─────────────────────────────────────────────────────────────────────────────
# Prompts
# ─────────────────────────────────────────────────────────────────────────────
SYSTEM_PROMPT = (
"You are a highly accurate document data extraction AI. "
"Extract only what is explicitly present in the document — never invent, guess, or add placeholder fields. "
"Respond with a raw JSON object only. No markdown, no explanation, no extra keys."
)
BLANK_FORM_PROMPT = (
"This appears to be an unfilled form or template. "
"Return a JSON object with these keys only: "
"form_type (name of the form), "
"tax_year (year if visible, else null), "
"purpose (one sentence describing what this form is for), "
"status (always set to 'blank_template'). "
"Return ONLY valid JSON, no markdown."
)
def _build_user_prompt(doc_type: str) -> str:
return (
f"Document type hint: {doc_type}\n\n"
"You are a precise data extraction AI. Read this document and extract its key information.\n\n"
"STRICT RULES:\n"
"1. Use field names exactly as they appear in the document "
"(e.g. 'PAN Number', 'Date of Birth', 'Employer Name', 'Tax Year').\n"
"2. For LEGAL DOCUMENTS, LETTERS, or CONTRACTS: extract key terms — "
"services included, responsibilities, fees, tax forms mentioned, deadlines, party names.\n"
"3. Extract ONLY fields that have actual content — do NOT add null or empty fields.\n"
"4. Dates: format as DD/MM/YYYY. A run-together date like '27082022' → '27/08/2022'.\n"
"5. For list fields (services, items, fees) use JSON arrays.\n"
"6. Ignore bilingual label noise (Hindi/Devanagari text) — extract English values only.\n"
"7. If the document is truly a blank unfilled form with zero data, return {}.\n"
"8. Return ONLY a valid JSON object — no markdown, no explanation."
)
# ─────────────────────────────────────────────────────────────────────────────
# Helpers
# ─────────────────────────────────────────────────────────────────────────────
def image_to_base64(pil_image: Image.Image, max_size: int = 2048) -> str:
"""Encode a PIL image to a base64 data URI, downscaling if needed."""
w, h = pil_image.size
if w > max_size or h > max_size:
scale = max_size / max(w, h)
pil_image = pil_image.resize((int(w * scale), int(h * scale)), Image.Resampling.LANCZOS)
logger.debug(f"[Vision] Resized {w}x{h} → {pil_image.size}")
if pil_image.mode != "RGB":
pil_image = pil_image.convert("RGB")
buf = BytesIO()
pil_image.save(buf, format="JPEG", quality=92)
return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode()
def _render_pdf_page(file_path: str, scale: float = RENDER_DPI) -> Image.Image | None:
"""Render the first page of a PDF to a PIL Image using PyMuPDF."""
try:
pdf_doc = fitz.open(file_path)
pix = pdf_doc[0].get_pixmap(
matrix=fitz.Matrix(scale, scale),
colorspace=fitz.csRGB
)
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
pdf_doc.close()
return img
except Exception as e:
logger.error(f"[PyMuPDF] Render failed for {file_path}: {e}")
return None
def _tesseract_text(pil_image: Image.Image) -> str:
"""
Run Tesseract OCR on a PIL image.
Uses eng+hin for bilingual Indian documents (Aadhaar, PAN, tax forms).
Falls back to eng-only if Hindi data not installed.
Auto-detects binary on Windows vs Linux/Docker.
"""
try:
import pytesseract
import platform
if platform.system() == "Windows":
win_paths = [
r"C:\Program Files\Tesseract-OCR\tesseract.exe",
r"C:\Users\abhil\AppData\Local\Programs\Tesseract-OCR\tesseract.exe",
]
for p in win_paths:
if os.path.isfile(p):
pytesseract.pytesseract.tesseract_cmd = p
break
config = "--psm 6 --oem 3"
try:
text = pytesseract.image_to_string(pil_image, lang="eng+hin", config=config).strip()
logger.debug(f"[Tesseract] eng+hin produced {len(text.split())} words")
except Exception:
logger.debug("[Tesseract] eng+hin unavailable, using eng only")
text = pytesseract.image_to_string(pil_image, lang="eng", config=config).strip()
return text
except ImportError:
logger.warning("[Tesseract] pytesseract not installed — skipping Stage 2")
return ""
except Exception as e:
logger.warning(f"[Tesseract] OCR failed: {e}")
return ""
def _call_openrouter(
api_key: str,
model: str,
user_content: list,
original_text: str = "",
) -> dict | None:
"""
POST to OpenRouter and return parsed JSON dict, or None on failure.
If the model returns {} (blank/unfilled doc), retries with a metadata
prompt so the admin always sees form_type / purpose / tax_year.
"""
def _post(content):
try:
response = requests.post(
url="https://openrouter.ai/api/v1/chat/completions",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json={
"model": model,
"messages": [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": content},
],
"response_format": {"type": "json_object"},
},
timeout=60,
)
response.raise_for_status()
raw = response.json()["choices"][0]["message"]["content"].strip()
for fence in ("```json", "```"):
if raw.startswith(fence):
raw = raw[len(fence):]
if raw.endswith("```"):
raw = raw[:-3]
return json.loads(raw.strip())
except Exception as e:
logger.error(f"[OpenRouter] {model} call failed: {e}")
return None
result = _post(user_content)
# If model returned {} (blank template), retry with metadata-only prompt
if result == {} and original_text:
logger.info("[AI] Empty result — retrying with blank-form metadata prompt")
fallback_content = [{
"type": "text",
"text": f"{BLANK_FORM_PROMPT}\n\nDocument text:\n{original_text[:3000]}"
}]
result = _post(fallback_content) or {}
return result
# ─────────────────────────────────────────────────────────────────────────────
# Main extraction entry point
# ─────────────────────────────────────────────────────────────────────────────
def extract_document_data(file_path: str, doc_type: str) -> dict | None:
"""
3-stage extraction pipeline:
Stage 1 — Native text (FREE)
pypdf + PyMuPDF pull embedded text from the PDF.
>= MIN_TEXT_CHARS → llama-3.3-70b (free tier)
Stage 2 — Tesseract OCR (FREE, local CPU)
PyMuPDF renders page at 2.5x DPI.
Tesseract reads with eng+hin for bilingual docs.
>= MIN_TESS_WORDS → llama-3.3-70b (free tier)
Stage 3 — Qwen2.5-VL-72B vision (paid, minimal cost)
Sends rendered page image to Qwen via OpenRouter.
Blank template fallback:
If any stage returns {}, a second call extracts
form_type / purpose / tax_year / status metadata.
"""
api_key = os.getenv("OPENROUTER_API_KEY")
if not api_key:
logger.warning("[AI] OPENROUTER_API_KEY not set — skipping extraction")
return None
is_pdf = file_path.lower().endswith(".pdf")
is_image = file_path.lower().endswith((".jpg", ".jpeg", ".png", ".webp"))
if not (is_pdf or is_image):
logger.info(f"[AI] Unsupported file type, skipping: {file_path}")
return None
user_prompt = _build_user_prompt(doc_type)
try:
# ── PDF ───────────────────────────────────────────────────────────────
if is_pdf:
# Stage 1: native text
text = ""
try:
reader = PdfReader(file_path)
for page in reader.pages[:3]:
t = page.extract_text()
if t:
text += t + "\n"
except Exception as e:
logger.warning(f"[Stage1] pypdf failed: {e}")
# PyMuPDF sometimes recovers text pypdf misses
if len(text.strip()) < MIN_TEXT_CHARS:
try:
doc = fitz.open(file_path)
mu = "".join(doc[i].get_text() for i in range(min(3, len(doc))))
doc.close()
if len(mu.strip()) > len(text.strip()):
text = mu
except Exception as e:
logger.warning(f"[Stage1] PyMuPDF text failed: {e}")
if len(text.strip()) >= MIN_TEXT_CHARS:
logger.info(f"[Stage1] Text PDF ({len(text.strip())} chars) → {MODEL_TEXT}")
content = [{"type": "text", "text": f"{user_prompt}\n\nDocument text:\n{text.strip()}"}]
return _call_openrouter(api_key, MODEL_TEXT, content, original_text=text.strip())
# Stage 2 & 3 need rendered image
rendered = _render_pdf_page(file_path)
if rendered is None:
return None
# Stage 2: Tesseract
tess_text = _tesseract_text(rendered)
word_count = len(tess_text.split())
if word_count >= MIN_TESS_WORDS:
logger.info(f"[Stage2] Tesseract {word_count} words → {MODEL_TEXT} (free)")
content = [{"type": "text", "text": f"{user_prompt}\n\nDocument text (OCR):\n{tess_text}"}]
result = _call_openrouter(api_key, MODEL_TEXT, content, original_text=tess_text)
if result is not None:
return result
logger.warning("[Stage2] Text model failed — falling through to Stage 3")
else:
logger.info(f"[Stage2] Tesseract only {word_count} words (threshold {MIN_TESS_WORDS}) → Stage 3")
# Stage 3: vision model
logger.info(f"[Stage3] Vision model: {MODEL_VISION}")
content = [
{"type": "text", "text": user_prompt},
{"type": "image_url", "image_url": {"url": image_to_base64(rendered)}},
]
return _call_openrouter(api_key, MODEL_VISION, content)
# ── Image ─────────────────────────────────────────────────────────────
elif is_image:
img = Image.open(file_path)
tess_text = _tesseract_text(img)
word_count = len(tess_text.split())
if word_count >= MIN_TESS_WORDS:
logger.info(f"[Stage2-img] Tesseract {word_count} words → {MODEL_TEXT} (free)")
content = [{"type": "text", "text": f"{user_prompt}\n\nDocument text (OCR):\n{tess_text}"}]
result = _call_openrouter(api_key, MODEL_TEXT, content, original_text=tess_text)
if result is not None:
return result
logger.warning("[Stage2-img] Text model failed — Stage 3")
else:
logger.info(f"[Stage2-img] Tesseract only {word_count} words → Stage 3")
logger.info(f"[Stage3-img] Vision model: {MODEL_VISION}")
content = [
{"type": "text", "text": user_prompt},
{"type": "image_url", "image_url": {"url": image_to_base64(img)}},
]
return _call_openrouter(api_key, MODEL_VISION, content)
except Exception as e:
logger.error(f"[AI] Extraction pipeline failed for {file_path}: {e}")
return None
+56
View File
@@ -0,0 +1,56 @@
"""
Re-run AI extraction for all documents (or only NULL ones).
Run from: services/api/
python backfill_extraction.py # only missing extractions
python backfill_extraction.py --all # re-extract everything with Qwen
"""
import sys, os, argparse
sys.path.insert(0, os.path.dirname(__file__))
from dotenv import load_dotenv
load_dotenv(os.path.join(os.path.dirname(__file__), '..', '..', '.env'))
from app.db import SessionLocal
from app.models import PersonalDocument, BusinessDocument
from app.utils.ai import extract_document_data
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument("--all", action="store_true", help="Re-extract all docs, not just missing ones")
args = parser.parse_args()
BASE_DIR = Path(__file__).resolve().parents[2]
UPLOAD_DIR = BASE_DIR / "uploads"
db = SessionLocal()
def backfill(model_class, table_name, doc_type_field):
query = db.query(model_class).filter(model_class.deleted_at == None)
if not args.all:
query = query.filter(model_class.extracted_data == None)
docs = query.all()
label = "all" if args.all else "missing"
print(f"\n[{table_name}] Found {len(docs)} {label} docs to process")
for doc in docs:
file_path = str(UPLOAD_DIR / doc.storage_key)
doc_type = getattr(doc, doc_type_field)
print(f" → id={doc.id} type={doc_type[:40]} file={doc.storage_key[:20]}...")
if not os.path.exists(file_path):
print(f" ⚠ File not found on disk, skipping")
continue
result = extract_document_data(file_path, doc_type)
if result is not None:
doc.extracted_data = result # store {} as-is — empty means blank template, not failure
db.commit()
print(f" ✓ Extracted {len(result)} fields: {list(result.keys())}")
else:
print(f" ✗ Extraction failed (unsupported type, blank doc, or API error)")
backfill(PersonalDocument, "personal_documents", "doc_type")
backfill(BusinessDocument, "business_documents", "business_type")
db.close()
print("\nDone.")
+31
View File
@@ -0,0 +1,31 @@
import sys
import os
# Add the root directory to sys.path so we can import app
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
from app.db import engine
from sqlalchemy import text
from sqlalchemy.exc import OperationalError, ProgrammingError
def upgrade():
try:
with engine.begin() as conn:
try:
conn.execute(text("ALTER TABLE personal_documents ADD COLUMN extracted_data JSON"))
print("Added extracted_data to personal_documents")
except (OperationalError, ProgrammingError) as e:
print(f"personal_documents: {e}")
try:
conn.execute(text("ALTER TABLE business_documents ADD COLUMN extracted_data JSON"))
print("Added extracted_data to business_documents")
except (OperationalError, ProgrammingError) as e:
print(f"business_documents: {e}")
print("Migration complete.")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
upgrade()
Binary file not shown.