diff --git a/PROJECT_WORKFLOW_ANALYSIS.md b/PROJECT_WORKFLOW_ANALYSIS.md new file mode 100644 index 0000000..ba72b6c --- /dev/null +++ b/PROJECT_WORKFLOW_ANALYSIS.md @@ -0,0 +1,284 @@ +# Bookkeepro Project Analysis & Workflow +` +This document provides a comprehensive technical analysis of the **Bookkeepro** platform, including its system architecture, technology stack, and diagrammatic representations of its core workflows. +` +## 1. System Architecture & Tech Stack +` +Bookkeepro is structured as a modern, containerized web application using a decoupled Frontend/Backend architecture. +` +### Technology Stack +* **Frontend:** React (Vite), React Router, Context API for state management, pure CSS for styling. +* **Backend:** Python 3.12, FastAPI, SQLAlchemy (ORM), JWT for authentication. +* **Database:** MySQL (MariaDB). +* **Infrastructure:** Docker & Docker Compose, Nginx (Reverse Proxy & Static File Serving). +* **AI Integration:** LLM integration (OpenRouter/Gemini) for the intelligent chatbot assistant. +` +### High-Level Architecture Diagram +` +```mermaid +graph TD + Client[Web Browser / Client] -->|HTTPS Requests| Nginx[Nginx Reverse Proxy] + + subgraph bookkeepro_network[Docker Network: bookkeepro_default] + Nginx -->|/api/*| FastAPI[FastAPI Backend Container] + Nginx -->|Static Assets| React[React Frontend Container] + + FastAPI <-->|SQL Queries| MySQL[(MySQL Database Container)] + FastAPI <-->|API Calls| LLM((OpenRouter / LLM API)) + end + + classDef client fill:#f9f,stroke:#333,stroke-width:2px; + classDef proxy fill:#fcc,stroke:#333,stroke-width:2px; + classDef app fill:#ccf,stroke:#333,stroke-width:2px; + classDef db fill:#ff9,stroke:#333,stroke-width:2px; + classDef external fill:#eee,stroke:#333,stroke-width:2px,stroke-dasharray: 5 5; + + class Client client; + class Nginx proxy; + class FastAPI,React app; + class MySQL db; + class LLM external; +` +` +--- +` +## 2. Core Workflows +` +### A. Authentication & Authorization Workflow +The system uses stateless JSON Web Tokens (JWT) for authentication. Roles (\user\, \dmin\, \super_admin\) dictate access levels across the platform. +` +```mermaid +sequenceDiagram + participant User as User/Client + participant Frontend as React UI + participant Backend as FastAPI + participant DB as MySQL +` + User->>Frontend: Enters Email & Password + Frontend->>Backend: POST /api/auth/login + Backend->>DB: Query User by Email + DB-->>Backend: Returns User Record & Hashed Password + + alt Invalid Credentials + Backend-->>Frontend: 401 Unauthorized + Frontend-->>User: Show Error Message + else Valid Credentials + Backend->>Backend: Generate JWT (Access Token) + Backend-->>Frontend: 200 OK + JWT Token + Frontend->>Frontend: Store Token (LocalStorage) + Frontend->>User: Redirect to Dashboard + end +` +` +### B. Document Management & Review Workflow +This is the core operational flow where users submit personal (W-2s, 1099s) or business documents, and admins review them. +` +```mermaid +stateDiagram-v2 + [*] --> Uploaded + + state Uploaded { + [*] --> PendingReview + note right of PendingReview + User uploads file. + Stored on disk, record in DB. + end note + } + + PendingReview --> Approved: Admin approves + PendingReview --> Rejected: Admin rejects (with reason) + + Approved --> [*] + + Rejected --> ActionRequired + note left of ActionRequired + User notified. + Must upload replacement. + end note + + ActionRequired --> PendingReview: User re-uploads +` +` +### C. AI Chatbot Workflow +The platform features an AI assistant that can query database context (like user stats and pending documents) to provide intelligent answers to both users and admins. +` +```mermaid +sequenceDiagram + participant Admin as Admin User + participant Chat UI as Frontend Chat + participant ChatAPI as FastAPI (/api/chatbot) + participant DB as MySQL DB + participant LLM as OpenRouter LLM +` + Admin->>Chat UI: "How many pending documents do we have?" + Chat UI->>ChatAPI: POST /api/chatbot/ask (Auth Token) + ChatAPI->>ChatAPI: Validate Token & Role + + ChatAPI->>DB: Query system stats (get_admin_status) + DB-->>ChatAPI: Returns {total_users, pending_docs, etc.} + + ChatAPI->>ChatAPI: Build Context Prompt (System Prompt + DB Stats + User Query) + + ChatAPI->>LLM: POST Prompt for Completion + LLM-->>ChatAPI: Returns AI Response + + ChatAPI->>DB: Log ChatMessage (History) + ChatAPI-->>Chat UI: Returns formatted Markdown response + Chat UI-->>Admin: Displays answer +` +` +`### D. Detailed User (Client) Workflow +```mermaid +flowchart TD + A[Landing Site: Home, About, Services] --> B{Has Account?} + B -- No --> C[Sign Up] + B -- Yes --> D[Login] + C --> D + + D -->|JWT Token Granted| E[Client Dashboard] + + E --> F{Upload Documents?} + F -->|Yes| G[Select Year & Type] + G --> H[Upload Personal Docs
e.g., W-2, 1040] + G --> I[Upload Business Docs
e.g., 1099, Receipts] + + H --> J[Status: Pending Review] + I --> J + + J --> K{Admin Review} + K -- Approved --> L[Status: Approved] + K -- Rejected --> M[Status: Action Required] + + M --> N[View Rejection Reason] + N -->|Re-upload file| G + + E --> O[View Completed Files] + O --> P[Download Tax Returns / Reports
uploaded by Admin] + + classDef public fill:#f9f,stroke:#333,stroke-width:2px; + classDef auth fill:#fcc,stroke:#333,stroke-width:2px; + classDef dash fill:#ccf,stroke:#333,stroke-width:2px; + classDef action fill:#ff9,stroke:#333,stroke-width:2px; + classDef pending fill:#e6e6e6,stroke:#333,stroke-width:2px; + classDef success fill:#b3ffb3,stroke:#009933,stroke-width:2px; + classDef danger fill:#ffb3b3,stroke:#cc0000,stroke-width:2px; + + class A public; + class C,D auth; + class E dash; + class H,I,O,P,G,N action; + class J pending; + class L success; + class M danger; +` +``n### E. Detailed Admin (Accountant) Workflow +```mermaid +flowchart TD + A[Login Portal] -->|JWT Role = Admin| B[Admin Dashboard] + + B --> C[View AI Daily Digest] + C -->|Ask Questions| D[Chatbot Queries DB
e.g. 'Show pending docs'] + + B --> E[View All Clients List] + E -->|Click on Client| F[Client Detail View] + + F --> G{Review Client Docs} + + G --> H[View Pending Personal Docs] + G --> I[View Pending Business Docs] + + H --> J{Quality Control} + I --> J + + J -- Looks Good --> K[Click Approve] + J -- Blurry/Incorrect --> L[Click Reject & Add Reason] + + K --> M[Process Taxes/Bookkeeping Offline] + + M --> N[Upload Finalized Work] + N --> O[Saved as Admin Document] + O -->|Client sees it on their end| F + + classDef auth fill:#fcc,stroke:#333,stroke-width:2px; + classDef dash fill:#ccf,stroke:#333,stroke-width:2px; + classDef ai fill:#f9f,stroke:#333,stroke-width:2px; + classDef view fill:#ff9,stroke:#333,stroke-width:2px; + classDef success fill:#b3ffb3,stroke:#009933,stroke-width:2px; + classDef danger fill:#ffb3b3,stroke:#cc0000,stroke-width:2px; + classDef db fill:#eee,stroke:#333,stroke-width:2px,stroke-dasharray: 5 5; + + class A auth; + class B dash; + class C,D ai; + class E,F,H,I view; + class K success; + class L danger; + class M,N,O db; +` +``n--- +``n## 3. Directory Structure Map +` +` ext +Bookkeepro/ +├── docker-compose.yml # Orchestrates the containers (App, DB, Nginx) +├── Makefile # Automation scripts (make deploy, make logs) +├── .env # Environment variables (DB credentials, API keys) +├── frontend/ # React Application +│ ├── index.html # Entry point +│ ├── package.json +│ ├── vite.config.js # Bundler configuration +│ ├── src/ # React components, pages, and contexts +│ └── public/ # CSS, Images, Static assets +├── services/api/ # FastAPI Backend Application +│ ├── main.py # Application factory and router inclusion +│ ├── requirements.txt +│ ├── app/ +│ │ ├── auth/ # JWT logic, Security dependencies +│ │ ├── routers/ # API Endpoints (auth.py, users.py, docs.py, chatbot.py) +│ │ ├── models.py # SQLAlchemy ORM Models +│ │ ├── schemas.py # Pydantic validation models +│ │ ├── crud.py # Database operations +│ │ └── db.py # Database connection pool setup +│ └── uploads/ # Mounted volume for physical document storage +└── nginx/ # Reverse Proxy Configuration + └── conf.d/default.conf # Routing rules for /api and static files +` +` +## 4. Key Technical Decisions & Security +` +1. **Reverse Proxy (Nginx):** Handles SSL termination (if applied) and efficiently serves the built React static files from /usr/share/nginx/html. It forwards any request starting with /api/ directly to the FastAPI container on port 8000. +2. **Containerized Database:** Uses a dedicated MySQL volume to ensure data persistence across container restarts. The entrypoint.sh script handles internal permission alignments (gosu) to prevent permission denied errors on Linux hosts. +3. **Stateless API:** The backend uses JWTs instead of session cookies, making the API easily scalable and preventing CSRF vulnerabilities naturally. +4. **Role-Based Access Control (RBAC):** Middleware in FastAPI explicitly checks user roles. A user trying to hit an admin endpoint receives an automatic 403 Forbidden without executing the route logic. +` + +` +### Security & Routing Architecture Diagram +```mermaid +flowchart TD + Client[Client Browser] -->|HTTP/HTTPS Request| Nginx[Nginx Reverse Proxy] + + Nginx -->|Route: /api/*| Backend[FastAPI Backend] + Nginx -->|Route: /| Frontend[Static React Files] + + subgraph FastAPI_Security_Layer[FastAPI Security Middleware] + Backend --> JWTCheck{Valid JWT Token?} + JWTCheck -- No --> Reject401[401 Unauthorized] + JWTCheck -- Yes --> RoleCheck{Role Check} + + RoleCheck -- Admin Endpoint + User Role --> Reject403[403 Forbidden] + RoleCheck -- Admin Endpoint + Admin Role --> Route[Execute Route Logic] + RoleCheck -- User Endpoint --> Route + end + + Route --> DB[(MySQL Database)] + + classDef reject fill:#ffb3b3,stroke:#cc0000; + classDef success fill:#b3ffb3,stroke:#009933; + classDef proxy fill:#e6f2ff,stroke:#0066cc; + + class Reject401,Reject403 reject; + class Route success; + class Nginx proxy; +` +` diff --git a/USER_ADMIN_WORKFLOWS.md b/USER_ADMIN_WORKFLOWS.md new file mode 100644 index 0000000..602ba1f --- /dev/null +++ b/USER_ADMIN_WORKFLOWS.md @@ -0,0 +1,132 @@ +# Bookkeepro Workflows + +This document visualizes the step-by-step journeys for Users, Admins, and Super Admins based on the core system logic. + +## 1. User Workflow + +```mermaid +flowchart TD + A[Landing: Home, About, Services, Contact] --> B{Has account?} + B -- No --> C[Signup page] + B -- Yes --> D[Login page] + C --> D + + D --> E[Forgot password page] + E -->|Email link| F[Reset password page] + + D -->|Login success| G[User dashboard] + + G --> H[Acknowledge engagement letter] + H --> I{Document type} + + I -- Personal --> J[Upload personal docs] + I -- Business --> K[Upload business docs] + + J --> L[Saved, sent for review] + K --> L + + L --> M{Admin decision} + M -- Approved --> N[Filed] + M -- Changes requested --> O[Notified] + O -- resubmit --> I + + G --> P[Chatbot, deadlines, bookmarks] + G --> Q[Logout] + + classDef public fill:#f9f,stroke:#333,stroke-width:2px; + classDef auth fill:#fcc,stroke:#333,stroke-width:2px; + classDef dash fill:#ccf,stroke:#333,stroke-width:2px; + classDef action fill:#ff9,stroke:#333,stroke-width:2px; + classDef pending fill:#e6e6e6,stroke:#333,stroke-width:2px; + classDef success fill:#b3ffb3,stroke:#009933,stroke-width:2px; + classDef danger fill:#ffb3b3,stroke:#cc0000,stroke-width:2px; + + class A public; + class C,D,E,F auth; + class G dash; + class H,I,J,K,P,O action; + class L pending; + class N success; + class M danger; +``` + +--- + +## 2. Admin Workflow + +```mermaid +flowchart TD + A[Login as admin] --> B[Admin dashboard] + + B --> C[Users tab] + B --> D[Templates tab] + B --> E[Bulk actions via AI chatbot] + + C --> F[Open user detail] + F --> G[Personal / business docs] + F --> H[Returns for review] + F --> I[Audit trail] + F --> J[Export user docs as zip] + + G --> K{Review document} + K -- Approve --> L[Mark filed, notify user] + K -- Request changes --> M[Notify user] + + L --> N[Audit trail logged] + M --> N + + B --> O[Logout] + + classDef auth fill:#fcc,stroke:#333,stroke-width:2px; + classDef dash fill:#ccf,stroke:#333,stroke-width:2px; + classDef view fill:#ff9,stroke:#333,stroke-width:2px; + classDef success fill:#b3ffb3,stroke:#009933,stroke-width:2px; + classDef danger fill:#ffb3b3,stroke:#cc0000,stroke-width:2px; + classDef db fill:#eee,stroke:#333,stroke-width:2px,stroke-dasharray: 5 5; + + class A auth; + class B dash; + class C,D,E,F,G,H,I,J view; + class L success; + class M danger; + class N db; +``` + +--- + +## 3. Super Admin Workflow + +```mermaid +flowchart TD + A[Login as super admin] --> B[Admin dashboard] + B --> C[All admin capabilities] + + B --> D[Open user detail] + D --> E{Viewing own account?} + + E -- Yes --> F[Role dropdown hidden] + E -- No --> G[Role dropdown visible] + + G --> H[Select new role] + H --> I{Validate rules} + + I -- Rule violated
Not self, not super admin via API
Keep 1+ super admin --> J[Rejected] + I -- Valid --> K[Role updated] + + J --> L[Audit trail logged] + K --> L + + classDef auth fill:#fcc,stroke:#333,stroke-width:2px; + classDef dash fill:#ccf,stroke:#333,stroke-width:2px; + classDef view fill:#ff9,stroke:#333,stroke-width:2px; + classDef success fill:#b3ffb3,stroke:#009933,stroke-width:2px; + classDef danger fill:#ffb3b3,stroke:#cc0000,stroke-width:2px; + classDef db fill:#eee,stroke:#333,stroke-width:2px,stroke-dasharray: 5 5; + + class A auth; + class B dash; + class C,D,F,G,H view; + class K success; + class J danger; + class L db; +``` diff --git a/fix_templates.py b/fix_templates.py deleted file mode 100644 index 319375b..0000000 --- a/fix_templates.py +++ /dev/null @@ -1,34 +0,0 @@ -import sys -import datetime -sys.path.append('.') -from sqlalchemy import text -from app.db import SessionLocal - -db = SessionLocal() -# Delete old templates -db.execute(text("DELETE FROM required_document_templates;")) -db.commit() - -# Insert new ones -current_year = datetime.date.today().year -personal_docs = [ - "W-2 Form", "1099-NEC / 1099-MISC", "SSA-1099 (Social Security Benefits)", - "Mortgage Interest Statement (1098)", "Charitable Donation Receipts", - "Medical & Dental Expense Receipts", "Student Loan Interest (1098-E)", - "State & Local Tax Payment Records", "Investment Income (1099-B / 1099-DIV)", - "Prior Year Tax Return", -] -business_docs = [ - "Profit & Loss Statement", "Balance Sheet", - "Bank Statements (All Accounts)", "Business Expense Receipts", - "Payroll Records / W-3", "1099s Issued to Contractors", - "Vehicle Mileage Log", "Home Office Documentation", - "Business Asset Purchase Invoices", "Prior Year Business Tax Return", -] -for name in personal_docs: - db.execute(text("INSERT IGNORE INTO required_document_templates (category, tax_year, name) VALUES ('personal', :yr, :name)"), {"yr": current_year, "name": name}) -for name in business_docs: - db.execute(text("INSERT IGNORE INTO required_document_templates (category, tax_year, name) VALUES ('business', :yr, :name)"), {"yr": current_year, "name": name}) - -db.commit() -print("Templates fixed!") diff --git a/frontend/src/pages/AdminUserDetail.jsx b/frontend/src/pages/AdminUserDetail.jsx index d629a55..af11368 100644 --- a/frontend/src/pages/AdminUserDetail.jsx +++ b/frontend/src/pages/AdminUserDetail.jsx @@ -345,6 +345,31 @@ export default function AdminUserDetail() { } }; + + const downloadDoc = async (storageKey, originalFilename) => { + try { + const res = await authFetch(`/api/upload/view-url?key=${encodeURIComponent(storageKey)}`); + if (res.ok) { + const data = await res.json(); + const fileRes = await fetch(data.url); + const blob = await fileRes.blob(); + const url = window.URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = originalFilename || storageKey.split('/').pop() || 'document'; + document.body.appendChild(a); + a.click(); + a.remove(); + window.URL.revokeObjectURL(url); + } else { + showToast("Could not generate download link", "error"); + } + } catch (err) { + console.error(err); + showToast("Error downloading document", "error"); + } + }; + const handleUpdateExtractedData = async (docId, type, newData) => { try { const res = await authFetch(`/api/upload/${type}-documents/${docId}/extracted-data`, { @@ -592,7 +617,7 @@ export default function AdminUserDetail() {
-
{doc.doc_type}
+
{doc.filename || doc.doc_type}
calendar_today {new Date(doc.uploaded_at).toLocaleDateString('en-US', {year:'numeric', month:'short', day:'numeric'})} @@ -612,6 +637,7 @@ export default function AdminUserDetail() {
+ + + {doc.review_status !== 'filed' && doc.review_status !== 'approved' && ( +
diff --git a/services/api/app/routers/chatbot.py b/services/api/app/routers/chatbot.py index 8ac89af..60994a6 100644 --- a/services/api/app/routers/chatbot.py +++ b/services/api/app/routers/chatbot.py @@ -11,7 +11,7 @@ import os import requests from pydantic import BaseModel, field_validator from fastapi import HTTPException -from app.models import PersonalDocument, BusinessDocument, User, AuditLog, ChatSession, ChatMessage as DBChatMessage +from app.models import PersonalDocument, BusinessDocument, AdminDocument, User, AuditLog, ChatSession, ChatMessage as DBChatMessage from app.db import get_db from app.auth.security import get_current_user, require_admin @@ -119,6 +119,11 @@ def get_admin_status( if tax_year: bq = bq.filter(BusinessDocument.tax_year == tax_year) pending_business = bq.count() + + admin_docs = db.query(AdminDocument).filter(AdminDocument.deleted_at == None) + if tax_year: + admin_docs = admin_docs.filter(AdminDocument.tax_year == tax_year) + pending_admin_returns = admin_docs.filter(AdminDocument.review_status == "pending").count() recent_personal = ( db.query(PersonalDocument).filter(PersonalDocument.deleted_at == None) @@ -128,13 +133,19 @@ def get_admin_status( db.query(BusinessDocument).filter(BusinessDocument.deleted_at == None) .order_by(BusinessDocument.uploaded_at.desc()).limit(10).all() ) + recent_admin = ( + db.query(AdminDocument).filter(AdminDocument.deleted_at == None) + .order_by(AdminDocument.uploaded_at.desc()).limit(10).all() + ) 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], + "uploaded_at": d.uploaded_at, "status": d.review_status} for d in recent_business] + + [{"user_id": d.user_id, "doc": d.doc_label, "type": "admin_return", + "uploaded_at": d.uploaded_at, "status": d.review_status} for d in recent_admin], key=lambda x: x["uploaded_at"].isoformat() if x["uploaded_at"] else "", reverse=True - )[:10] + )[:15] 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: @@ -143,28 +154,18 @@ def get_admin_status( 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" - total_pending = pending_personal + pending_business - message = ( - f"**System Overview:**\n\n" - f"- Total Users: **{total_users}** (**{new_users_today}** joined today)\n" - f"- Pending Personal Docs: **{pending_personal}**\n" - f"- Pending Business Docs: **{pending_business}**\n\n" - + (f"You have **{total_pending}** documents awaiting review." if total_pending > 0 - else "All documents have been reviewed!") - ) + total_pending = pending_personal + pending_business + pending_admin_returns return { "total_users": total_users, "new_users_today": new_users_today, "pending_personal": pending_personal, "pending_business": pending_business, - "total_pending": total_pending, - "recent_uploads": recent_uploads, - "message": message, - "admin_accounts": admin_accounts, + "pending_admin_returns": pending_admin_returns, + "total_pending": total_pending, + "recent_uploads": recent_uploads } - @router.get("/daily-digest") def get_daily_digest( db: Session = Depends(get_db), diff --git a/services/api/app/utils/doc_intelligence.py b/services/api/app/utils/doc_intelligence.py index e098b28..de433d7 100644 --- a/services/api/app/utils/doc_intelligence.py +++ b/services/api/app/utils/doc_intelligence.py @@ -172,16 +172,20 @@ def build_daily_digest(db_stats: dict) -> str: f"Date: {today}\n" f"New users registered today: {db_stats.get('new_users_today', 0)}\n" f"Total users: {db_stats.get('total_users', 0)}\n" - f"Pending personal docs: {db_stats.get('pending_personal', 0)}\n" - f"Pending business docs: {db_stats.get('pending_business', 0)}\n" - f"Total pending docs: {db_stats.get('total_pending', 0)}\n" + f"Pending user-uploaded personal docs: {db_stats.get('pending_personal', 0)}\n" + f"Pending user-uploaded business docs: {db_stats.get('pending_business', 0)}\n" + f"Pending admin-uploaded returns (awaiting user review): {db_stats.get('pending_admin_returns', 0)}\n" + f"Total pending actionable docs: {db_stats.get('total_pending', 0)}\n" ) recent = db_stats.get("recent_uploads", []) if recent: - stats_text += "\nRecent uploads today:\n" - for r in recent[:5]: - stats_text += f"- {r['user_name']} uploaded {r['doc']} ({r['type']}) at {r['uploaded_at']}\n" + stats_text += "\nRecent Document Activity:\n" + for r in recent[:10]: + if r['type'] == 'admin_return': + stats_text += f"- Admin-uploaded return for {r['user_name']} '{r['doc']}' (Status: {r['status']}) at {r['uploaded_at']}\n" + else: + stats_text += f"- {r['user_name']} uploaded {r['doc']} ({r['type']}) (Status: {r['status']}) at {r['uploaded_at']}\n" prompt = ( "You are an accounting firm assistant. Write a brief, friendly, plain-English daily digest " diff --git a/services/api/check_2026.py b/services/api/check_2026.py deleted file mode 100644 index 0c7e3cb..0000000 --- a/services/api/check_2026.py +++ /dev/null @@ -1,10 +0,0 @@ -import sys -sys.path.append('.') -from app.db import SessionLocal -from app.models import PersonalDocument - -db = SessionLocal() -docs = db.query(PersonalDocument).filter(PersonalDocument.tax_year == 2026, PersonalDocument.review_status == 'pending').all() -print("2026 pending docs:") -for d in docs: - print(f"ID {d.id} deleted_at: {d.deleted_at}") diff --git a/services/api/check_db.py b/services/api/check_db.py deleted file mode 100644 index 28a6ab9..0000000 --- a/services/api/check_db.py +++ /dev/null @@ -1,23 +0,0 @@ -import sys -import json -sys.path.append('.') -from app.db import SessionLocal -from app.models import RequiredDocumentTemplate, PersonalDocument, BusinessDocument - -db = SessionLocal() -templates = db.query(RequiredDocumentTemplate).all() -pdocs = db.query(PersonalDocument).all() -bdocs = db.query(BusinessDocument).all() - -print("--- TEMPLATES ---") -for t in templates: - print(f"[{t.category.upper()}] TY {t.tax_year} | {t.name}") - -print("\n--- PERSONAL DOCS ---") -for d in pdocs: - print(f"ID {d.id} | User {d.user_id} | TY {d.tax_year} | {d.doc_type} | {d.review_status}") - -print("\n--- BUSINESS DOCS ---") -for d in bdocs: - print(f"ID {d.id} | User {d.user_id} | TY {d.tax_year} | {d.business_type} | {d.review_status}") - diff --git a/services/api/check_mismatch.py b/services/api/check_mismatch.py deleted file mode 100644 index ce25ec1..0000000 --- a/services/api/check_mismatch.py +++ /dev/null @@ -1,25 +0,0 @@ -import sys -sys.path.append('.') -from app.db import SessionLocal -from app.models import PersonalDocument, BusinessDocument - -db = SessionLocal() - -# Global count (like admin-status) -global_p = db.query(PersonalDocument).filter( - PersonalDocument.review_status == "pending", - PersonalDocument.deleted_at.is_(None), - PersonalDocument.tax_year == 2026 -).count() - -# User-level count (like security.py) -from sqlalchemy import func as sqlfunc -users_p_q = db.query(PersonalDocument.user_id, sqlfunc.count(PersonalDocument.id)).filter( - PersonalDocument.review_status == "pending", - PersonalDocument.deleted_at.is_(None), - PersonalDocument.tax_year == 2026 -).group_by(PersonalDocument.user_id).all() - -sum_user_p = sum(count for _, count in users_p_q) - -print(f"Global: {global_p}, Sum of users: {sum_user_p}") diff --git a/services/api/check_none.py b/services/api/check_none.py deleted file mode 100644 index fc1ba53..0000000 --- a/services/api/check_none.py +++ /dev/null @@ -1,16 +0,0 @@ -import sys -sys.path.append('.') -from app.db import SessionLocal -from app.models import PersonalDocument - -db = SessionLocal() -pq_none = db.query(PersonalDocument).filter(PersonalDocument.review_status == "pending", PersonalDocument.deleted_at == None).filter(PersonalDocument.tax_year == 2025) -pq_is_none = db.query(PersonalDocument).filter(PersonalDocument.review_status == "pending", PersonalDocument.deleted_at.is_(None)).filter(PersonalDocument.tax_year == 2025) - -print("With == None:", pq_none.count()) -print("With is_(None):", pq_is_none.count()) - -docs = db.query(PersonalDocument).filter(PersonalDocument.tax_year == 2025).all() -print("All 2025 docs count:", len(docs)) -for d in docs: - print(f"ID {d.id} deleted_at: {d.deleted_at}") diff --git a/services/api/check_stats.py b/services/api/check_stats.py deleted file mode 100644 index 60a745f..0000000 --- a/services/api/check_stats.py +++ /dev/null @@ -1,14 +0,0 @@ -import sys -sys.path.append('.') -from app.db import SessionLocal -from app.models import PersonalDocument, BusinessDocument - -db = SessionLocal() -pq = db.query(PersonalDocument).filter(PersonalDocument.review_status == "pending", PersonalDocument.deleted_at == None).filter(PersonalDocument.tax_year == 2025) -print("Pending personal docs for 2025:", pq.count()) - -bq = db.query(BusinessDocument).filter(BusinessDocument.review_status == "pending", BusinessDocument.deleted_at == None).filter(BusinessDocument.tax_year == 2025) -print("Pending business docs for 2025:", bq.count()) - -p26 = db.query(PersonalDocument).filter(PersonalDocument.review_status == "pending", PersonalDocument.deleted_at == None).filter(PersonalDocument.tax_year == 2026) -print("Pending personal docs for 2026:", p26.count()) diff --git a/services/api/test_upload.py b/services/api/test_upload.py deleted file mode 100644 index 4f10347..0000000 --- a/services/api/test_upload.py +++ /dev/null @@ -1,30 +0,0 @@ -import requests - -# 1. Login as User 2 -res = requests.post("http://localhost:8000/api/auth/login", data={"username": "user@example.com", "password": "password"}) -user_token = res.json()["access_token"] -print("User token:", user_token[:10]) - -# 2. Upload a personal document for TY 2026 -files = {'file': ('test.pdf', b'fake pdf content', 'application/pdf')} -data = {'doc_type': 'test_doc', 'tax_year': 2026} -res = requests.post( - "http://localhost:8000/api/upload/personal-documents", - headers={"Authorization": f"Bearer {user_token}"}, - files=files, - data=data -) -print("Upload status:", res.status_code) - -# 3. Login as Admin -res = requests.post("http://localhost:8000/api/auth/login", data={"username": "admin@example.com", "password": "password"}) -admin_token = res.json()["access_token"] - -# 4. Check admin status for TY 2026 -res = requests.get("http://localhost:8000/api/chatbot/admin-status?tax_year=2026", headers={"Authorization": f"Bearer {admin_token}"}) -print("Admin status 2026:", res.json().get("pending_personal")) - -# 5. Check admin status for TY 2025 -res = requests.get("http://localhost:8000/api/chatbot/admin-status?tax_year=2025", headers={"Authorization": f"Bearer {admin_token}"}) -print("Admin status 2025:", res.json().get("pending_personal")) - diff --git a/update_drafts.py b/update_drafts.py deleted file mode 100644 index 5aabf12..0000000 --- a/update_drafts.py +++ /dev/null @@ -1,23 +0,0 @@ -import sys -sys.path.append(r'c:\Users\abhil\Desktop\Bookkeepro-redesigned\Bookkeep\services\api') -from app.db import SessionLocal -from sqlalchemy import text - -db = SessionLocal() -db.execute(text("UPDATE personal_documents SET review_status = 'pending' WHERE review_status = 'draft'")) -db.execute(text("UPDATE business_documents SET review_status = 'pending' WHERE review_status = 'draft'")) -db.commit() - -from app.models import DocumentReviewEvent, PersonalDocument, BusinessDocument - -# Also append uploaded events -for doc in db.query(PersonalDocument).all(): - if not db.query(DocumentReviewEvent).filter_by(doc_kind='personal', doc_id=doc.id, action='uploaded').first(): - db.add(DocumentReviewEvent(doc_kind='personal', doc_id=doc.id, owner_user_id=doc.user_id, actor_id=doc.user_id, actor_role='user', action='uploaded', to_status='pending', tax_year=doc.tax_year, created_at=doc.uploaded_at)) - -for doc in db.query(BusinessDocument).all(): - if not db.query(DocumentReviewEvent).filter_by(doc_kind='business', doc_id=doc.id, action='uploaded').first(): - db.add(DocumentReviewEvent(doc_kind='business', doc_id=doc.id, owner_user_id=doc.user_id, actor_id=doc.user_id, actor_role='user', action='uploaded', to_status='pending', tax_year=doc.tax_year, created_at=doc.uploaded_at)) - -db.commit() -print('Done updating db')