commit 611d00bda18bfaf4de5f1a76b6c55f37913d9c04 Author: Atharv1705 Date: Wed Jul 15 12:30:28 2026 +0530 Initial commit diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..a990c4d --- /dev/null +++ b/.dockerignore @@ -0,0 +1,16 @@ +.git +.github +__pycache__ +*.pyc +*.pyo +*.pyd +*.log +.env* +.venv +venv +node_modules +.pytest_cache +.mypy_cache +.ruff_cache +services/api/temp +uploads \ No newline at end of file diff --git a/.env.docker.example b/.env.docker.example new file mode 100644 index 0000000..a711266 --- /dev/null +++ b/.env.docker.example @@ -0,0 +1,35 @@ +# Docker / Contabo runtime settings +MYSQL_ROOT_PASSWORD=rootpassword +MYSQL_USER=bookkeep +MYSQL_PASSWORD=bookkeepro_pass +MYSQL_HOST=db +MYSQL_PORT=3306 +MYSQL_DATABASE=bookkeepprodb +DATABASE_URL=mysql+pymysql://bookkeep:bookkeepro_pass@db:3306/bookkeepprodb + +# Security & Authentication +SECRET_KEY=change_me_to_a_long_random_secret +ALGORITHM=HS256 +ACCESS_TOKEN_EXPIRE_MINUTES=1440 +FRONTEND_URL=http://localhost:8000 + +# Contabo / S3-compatible storage +CONTABO_ENDPOINT=https://eu2.contabostorage.com +CONTABO_REGION=eu2 +CONTABO_ACCESS_KEY=your_contabo_access_key +CONTABO_SECRET_KEY=your_contabo_secret_key +CONTABO_BUCKET=bookkeepro-docs +PRESIGNED_URL_EXPIRY=3600 + +# Email Configuration (SMTP) +SMTP_USER=your_smtp_user +SMTP_PASSWORD=your_smtp_password +MAIL_FROM=noreply@bookkeepro.net +SMTP_HOST=smtp.yourprovider.com +SMTP_PORT=587 +SMTP_TLS=True +MAIL_SSL_TLS=False +MAIL_FROM_NAME=BookKeepro + +# Application Settings +ADMIN_EMAIL=admin@bookkeepro.net \ No newline at end of file diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..a307dd1 --- /dev/null +++ b/.env.example @@ -0,0 +1,34 @@ +# Database Configuration +MYSQL_USER=root +MYSQL_PASSWORD= +MYSQL_HOST=localhost +MYSQL_PORT=3306 +MYSQL_DATABASE=bookkeepprodb +DATABASE_URL=mysql+pymysql://root:@localhost:3306/bookkeepprodb + +# Security & Authentication +SECRET_KEY=your_super_secret_key_here +ALGORITHM=HS256 +ACCESS_TOKEN_EXPIRE_MINUTES=1440 +FRONTEND_URL=https://bookkeepro.net + +# Contabo / S3-compatible storage +CONTABO_ENDPOINT=https://eu2.contabostorage.com +CONTABO_REGION=eu2 +CONTABO_ACCESS_KEY=your_contabo_access_key +CONTABO_SECRET_KEY=your_contabo_secret_key +CONTABO_BUCKET=bookkeepro-docs +PRESIGNED_URL_EXPIRY=3600 + +# Email Configuration (SMTP) +SMTP_USER=your_smtp_user +SMTP_PASSWORD=your_smtp_password +MAIL_FROM=noreply@bookkeepro.net +SMTP_HOST=smtp.yourprovider.com +SMTP_PORT=587 +SMTP_TLS=True +MAIL_SSL_TLS=False +MAIL_FROM_NAME=BookKeepro + +# Application Settings +ADMIN_EMAIL=admin@bookkeepro.net diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..eeace45 --- /dev/null +++ b/.gitignore @@ -0,0 +1,19 @@ +.venv/ +venv/ +__pycache__/ +*.pyc +.env +.env.* +!.env.example +!.env.docker.example +credentials.json +oauth_token.json + +# IDEs and OS +.vscode/ +.idea/ +.DS_Store + +# User Uploads & Temp Data +uploads/ +services/temp/ \ No newline at end of file diff --git a/AI_ENGINEERING_ONE_PAGER.md b/AI_ENGINEERING_ONE_PAGER.md new file mode 100644 index 0000000..1e532aa --- /dev/null +++ b/AI_ENGINEERING_ONE_PAGER.md @@ -0,0 +1,147 @@ +# AI Engineering One-Pager Template + +My Name - Team No + +Employee ID: + +Designation: AI Developer + +Month: JUNE 2026 + +Sprint: _____________ Project: BookKeepPro + +Owner: _____________ + +1. Work Snapshot + +BookKeepPro is a FastAPI-based bookkeeping platform for CPA workflows, enabling clients to upload personal and business documents, review admin documents, and interact with a web-based dashboard. The project combines a Python backend, MySQL database, vanilla HTML frontend, and object storage integration to support document handling, admin review, email notifications, and authentication flows. The current focus is on stabilizing the storage migration, strengthening security, and improving production readiness for real-world deployment. + +2. Key Deliverables + +- Reviewed the end-to-end architecture of authentication, RBAC, uploads, reviews, and storage integration. +- Audited the project for critical issues affecting upload/delete workflows, document ownership, and security. +- Documented the current state of the app through a detailed project audit and technical review. +- Identified remediation priorities for storage migration, JWT security, validation, and admin workflow resilience. + +3. Progress + +- Done — Architecture and security review completed; critical issues documented; upload workflow analysis completed; storage migration gaps identified. +- In Progress — Remediation planning for upload endpoints, storage integration, and auth hardening. +- Not Started — Full production hardening tasks such as tests, deployment automation, monitoring, and audit trail implementation. + +Overall completion: approximately 45% of the planned stabilization scope is completed, with the highest-risk issues now clearly identified. + +4. Next Sprint Priorities + +- Priority 1 — Fix the broken upload and delete endpoints by replacing legacy Drive-based calls with the new storage implementation. +- Priority 2 — Harden authentication and authorization by tightening JWT secret handling, improving admin role checks, and enforcing ownership validation. +- Priority 3 — Add server-side validation for uploads, generate presigned document URLs, and improve security around document access. + +5. Status + +🟡 At Risk + +The project is functionally promising, but several critical issues remain unresolved, particularly around upload/storage stability and security hardening, which could affect reliability and production readiness. + +6. Major Wins + +- Win 1 — Identified and documented the critical storage migration gap that was breaking document upload and delete flows. +- Win 2 — Confirmed that backend RBAC patterns are largely sound, creating a strong base for secure access control improvements. +- Win 3 — Produced a structured audit that clearly prioritizes technical and security remediation work for the next sprint. + +7. Risks & Blockers + +- Risk/Blocker 1 — Upload and delete endpoints are currently broken due to incomplete migration from legacy Drive logic to object storage; mitigation: replace legacy function calls and validate the full workflow end to end. +- Risk/Blocker 2 — Security weaknesses such as weak secrets, permissive CORS, and missing validation could expose the platform to unauthorized access or misuse; mitigation: implement hardening measures and remove insecure defaults. + +8. Decisions Required + +- Decision 1 — Confirm the production storage strategy and credentials for object storage; owner: Project Lead; deadline: next sprint kickoff. +- Decision 2 — Approve the security hardening scope for JWT, file validation, and access control; owner: Project Lead / Tech Lead; deadline: before deployment planning. + +9. Biggest Opportunity + +The highest-leverage opportunity is to complete the storage and security stabilization work in one pass. If the upload pipeline, document access model, and auth hardening are finalized together, the application will move from a working prototype to a much more reliable production-ready platform. + +10. What’s Keeping Me Awake + +- Concern 1 — Critical upload flows remain unstable until the migration is completed end to end. +- Concern 2 — Production readiness is still limited by missing validation, weak secret handling, and incomplete operational safeguards. + +11. Major Misses + +- Miss 1 — The storage migration was started but not completed, leaving upload and delete APIs broken; root cause: legacy Drive references remained in the code after the storage transition. +- Miss 2 — Security and validation safeguards were not fully implemented before broader rollout planning; root cause: the project is still in an early-stage prototype phase with incomplete hardening. + +12. Key Observations + +- Observation 1 — The core workflow architecture is solid, but operational resilience is still weak. +- Observation 2 — The frontend and backend are closely coupled, which increases the need for careful API and security discipline. + +13. Key Learnings + +- Learning 1 — Migration work must be verified end to end rather than assumed complete after partial implementation. +- Learning 2 — Security hardening should be treated as a core delivery requirement, not a later-phase improvement. + +14. Customer Feedback for Me + +Customer-facing feedback is limited at this stage, but the main expectation is clear: the platform should be dependable for document uploads, secure for sensitive financial data, and simple for users to navigate without friction. + +15. HR Team Feedback (Filled by Myself) + +The sprint reflected strong ownership, structured analysis, and a focus on building a reliable technical foundation. Continued emphasis on delivery discipline, communication, and proactive issue resolution will help improve execution quality further. + +16. Personal Reflection + +What went well?: I maintained a strong focus on identifying high-impact technical issues and translating them into actionable remediation priorities. + +What could I improve?: I can improve by moving from analysis to implementation faster, especially on the highest-risk fixes that affect user-facing functionality. + +Am I spending time on the right things?: Yes, the work has centered on the most important risks to the project’s stability and credibility. + +17. My One Big Bet + +If I could improve only one thing next sprint, I would prioritize completing the storage and security remediation path in a single focused effort. Success would mean that document upload, review, and access flows work reliably and securely without regressions. + +18. Next Month Top 5 Commitments + +1. Complete the storage migration fixes and restore document upload/delete flows. +2. Harden authentication, authorization, and document access controls. +3. Add backend validation for file type, file size, and input safety. +4. Improve production readiness with deployment and monitoring considerations. +5. Build a stronger review and audit trail foundation for CPA workflow reliability. + +19. Confidence Score (1-10) + +| Area | My Score | Lead Score | +|---|---:|---:| +| Delivery (Project Execution & Timely Completion) | 6 | | +| Overall ROI (Business Impact & Value Created) | 7 | | +| Performance (Quality & Productivity) | 7 | | +| Ownership & Accountability | 8 | | +| Code Quality & Engineering Standards | 6 | | +| Problem Solving | 8 | | +| Decision Making | 7 | | +| Technical Growth & Skill Development | 8 | | +| System Stability & Reliability | 5 | | +| Technical Growth | 8 | | +| Skill Development | 8 | | +| Innovative Approach | 7 | | +| Technical Leadership | 6 | | +| Team Collaboration | 7 | | +| Communication | 7 | | +| Time Utilization & Productivity | 7 | | +| Commitment | 8 | | +| Dedication | 8 | | +| Learnings & Continuous Improvement | 8 | | +| Punctuality & Professional Discipline | 7 | | + +My Overall Performance (Self-Assessment): 7/10 + +My Signature: ___________________________ Date: __________ + +Lead Sign-off: ___________________________ Date: __________ + +Overall Performance Status (keep one) + +🟡 Good diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md new file mode 100644 index 0000000..d8e00e3 --- /dev/null +++ b/DEPLOYMENT.md @@ -0,0 +1,24 @@ +# Contabo Docker Deployment + +This project runs as a single FastAPI container that also serves the frontend files from `frontend/`. + +## Files used for deployment + +- `Dockerfile` builds the API image. +- `docker-compose.yml` runs the API, MySQL, and Nginx proxy. +- `.dockerignore` keeps the image build context small. +- `.env.docker.example` shows the runtime variables needed on Contabo. +- `nginx/default.conf` proxies public traffic to the app container. + +## Deployment flow + +1. Copy `.env.docker.example` to `.env` and fill in your real values. +2. Point `FRONTEND_URL` to your domain once it is live. +3. Run `docker compose up -d --build` on the Contabo VPS. +4. Open port 80 in the Contabo firewall and VPS firewall. + +## Notes + +- The database runs in a separate MySQL container by default. +- Uploaded files are stored in a named Docker volume. +- If you want HTTPS, add TLS termination to Nginx or put a separate certbot setup in front of it. \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..48c6a13 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,26 @@ +FROM python:3.12-slim + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PIP_NO_CACHE_DIR=1 + +WORKDIR /app + +COPY services/api/requirements.txt /tmp/requirements.txt +RUN python - <<'PY' +from pathlib import Path + +src = Path('/tmp/requirements.txt') +text = src.read_text(encoding='utf-16') +Path('/tmp/requirements-utf8.txt').write_text(text, encoding='utf-8') +PY + +RUN pip install --upgrade pip && pip install -r /tmp/requirements-utf8.txt + +COPY . /app + +WORKDIR /app/services/api + +EXPOSE 8000 + +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4", "--proxy-headers"] \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..e2e3c38 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,55 @@ +services: + app: + build: + context: . + dockerfile: Dockerfile + env_file: + - .env + environment: + MYSQL_HOST: db + MYSQL_PORT: 3306 + MYSQL_DATABASE: ${MYSQL_DATABASE:-bookkeepprodb} + MYSQL_USER: ${MYSQL_USER:-bookkeep} + MYSQL_PASSWORD: ${MYSQL_PASSWORD:-bookkeepro_pass} + DATABASE_URL: mysql+pymysql://${MYSQL_USER:-bookkeep}:${MYSQL_PASSWORD:-bookkeepro_pass}@db:3306/${MYSQL_DATABASE:-bookkeepprodb} + ports: + - "8000:8000" + depends_on: + db: + condition: service_healthy + restart: unless-stopped + volumes: + - uploads_data:/app/uploads + + nginx: + image: nginx:1.27-alpine + depends_on: + - app + ports: + - "80:80" + volumes: + - ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro + - ./frontend:/usr/share/nginx/html:ro + restart: unless-stopped + + db: + image: mysql:8.4 + command: --default-authentication-plugin=mysql_native_password + environment: + MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-rootpassword} + MYSQL_DATABASE: ${MYSQL_DATABASE:-bookkeepprodb} + MYSQL_USER: ${MYSQL_USER:-bookkeep} + MYSQL_PASSWORD: ${MYSQL_PASSWORD:-bookkeepro_pass} + volumes: + - mysql_data:/var/lib/mysql + healthcheck: + test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-p$${MYSQL_ROOT_PASSWORD}"] + interval: 10s + timeout: 5s + retries: 10 + start_period: 20s + restart: unless-stopped + +volumes: + mysql_data: + uploads_data: \ No newline at end of file diff --git a/frontend/about-us.html b/frontend/about-us.html new file mode 100644 index 0000000..2e56c62 --- /dev/null +++ b/frontend/about-us.html @@ -0,0 +1,123 @@ + + + + + +About Us — BookKeepro + + + + + + + + + + + + +{% include 'partials/navbar.html' %} + + +
+
+

About Us

+

Our People Are Passionate About What We Do

+
+
+ + +
+ +
+
+

Who We Are

+ +

+ 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. +

+ +
+ +

+ In 2018, we strengthened our presence in Pune & Mumbai — transitioning + from a traditional CA practice into a scalable financial services + organization. +

+
+ + Bookkeepro Team +
+ +
+
+

About Bookkeepro

+ +

+ As our client base expanded globally — especially across the US — we aligned + our operating model to support international growth. +

+ +
+ +

+ In 2023, we launched: +

+ • Bookkeeping Business Solutions Pvt Ltd (India)
+ • Bookkeeping Business Solutions LLC (USA) +

+ +
+ +

+ Today, Bookkeepro serves global businesses, startups & enterprises with + scalable, compliant bookkeeping and financial operations support. +

+
+ + About Bookkeepro +
+ +
+ +
+
+

Who We Are Today

+ +

+ ✔️ 25+ years of accounting & compliance expertise
+ ✔️ Operations across India & USA
+ ✔️ Secure, process-driven financial workflows
+ ✔️ Strong confidentiality & data protection practices +

+ +
+ +

+ We help businesses build financial clarity, compliance confidence, + and operational efficiency. +

+
+ + Global Bookkeepro Team +
+ + +{% include 'partials/footer.html' %} + + + + + diff --git a/frontend/admin-dashboard.html b/frontend/admin-dashboard.html new file mode 100644 index 0000000..3c037b1 --- /dev/null +++ b/frontend/admin-dashboard.html @@ -0,0 +1,348 @@ + + + + + + + BookKeepPro | Admin Dashboard + + + + + + + + + + + + +
+ +
+ + + + + +
+
+ +
+ + +
+ + +
+
+
+

Users

+

Templates

+
+

+
+ +
+ +
+
+
+
pending
+
Loading users…
+
+
+
+ + + +
+ + + + + + + + + + diff --git a/frontend/admin-user-detail.html b/frontend/admin-user-detail.html new file mode 100644 index 0000000..c8129e6 --- /dev/null +++ b/frontend/admin-user-detail.html @@ -0,0 +1,454 @@ + + + + + +BookKeepPro | User Detail + + + + + + + + + + +
+ +
+ + + + + + +
+
+ +
+ + +
+
+
+
?
+
+
—
+
—
+
+ user + pending Engagement not acknowledged +
+
+
+
+
+ + +
+ + +
+
+
+ + + + + +
+ + + + +
+ + + +
+
+
+
+
+
+
+
+
+

Filing Timeline

+
+ +
+
0
+
days
+
+ +
+ +
+
+
+
+ + +
+
+
+
+
+
+
+
+
+

Filing Timeline

+
+ +
+
0
+
days
+
+ +
+ +
+
+
+
+ + +
+
+
+

Admin-Uploaded Returns

+
+ + +
+
+
+
+
+ + +
+
+

Audit Trail

+
+
history
Loading audit log…
+
+
+
+ +
+ + + + + + + + + + + + + diff --git a/frontend/contact.html b/frontend/contact.html new file mode 100644 index 0000000..fcdc6e4 --- /dev/null +++ b/frontend/contact.html @@ -0,0 +1,117 @@ + + + + + +Contact — BookKeepro + + + + + + + + + + + +{% set navbar_class = 'navbar-solid' %} +{% include 'partials/navbar.html' %} + + + +
+ +

+ CONTACT BOOKKEEPRO +

+ +
+ +
+ +
+

USA

+

2520 Indigo Dr
McKinney, TX
75072, United States

+

+1469-796-6151

+
+ +
+

IND

+

508, White Square,
Hinjewadi Road, Pune
411057, India

+

+91 738 793 6020

+
+ +
+ +
+
+ +
+ + +
+ + + +
+ +
+ +
+ +
+ + + +
+
+ +
+
+ +{% include 'partials/footer.html' %} + + + + + + + diff --git a/frontend/css/animations.css b/frontend/css/animations.css new file mode 100644 index 0000000..0f95826 --- /dev/null +++ b/frontend/css/animations.css @@ -0,0 +1,91 @@ +/* ============================================================ + animations.css — Micro-interactions & transitions + ============================================================ */ + +/* ── Page transition ─────────────────────────────────────── */ +.page-enter { + animation: fadeIn 0.3s 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); +} + +/* ── 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); } +} +.pulse { animation: pulse-orange 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; +} + +/* ── 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; } + +/* ── Checkbox animate ────────────────────────────────────── */ +input[type=checkbox] { + accent-color: var(--blue); + width: 16px; + height: 16px; + cursor: pointer; +} + +/* ── Focus ring ──────────────────────────────────────────── */ +:focus-visible { + outline: 2px solid var(--blue); + outline-offset: 2px; +} + +/* ── Smooth link underline ───────────────────────────────── */ +.fancy-link { + position: relative; + text-decoration: none; + color: var(--blue); +} +.fancy-link::after { + content: ''; + position: absolute; + bottom: -1px; left: 0; + width: 0; height: 1.5px; + background: var(--blue); + transition: width 0.2s ease; +} +.fancy-link:hover::after { width: 100%; } diff --git a/frontend/css/base.css b/frontend/css/base.css new file mode 100644 index 0000000..178c7ae --- /dev/null +++ b/frontend/css/base.css @@ -0,0 +1,282 @@ +/* ============================================================ + 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'); + +/* ── 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; + + --radius-xs: 6px; + --radius-sm: 10px; + --radius-md: 14px; + --radius-lg: 20px; + --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); + + --transition: 0.2s ease; +} + +/* ── Reset ───────────────────────────────────────────────── */ +*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } +html { font-size: 16px; scroll-behavior: smooth; } +body { + font-family: "Poppins", system-ui, sans-serif; + background: var(--bg); + color: #222; + 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); } +.material-symbols-outlined { font-size: inherit; vertical-align: middle; line-height: 1; font-variation-settings: 'FILL' 1, 'wght' 400, 'GRAD' 0, 'opsz' 24; } + +/* ── 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; } +small, .text-sm { font-size: 13px; color: var(--muted); } +.text-muted { color: var(--muted); } + +/* ── Card ────────────────────────────────────────────────── */ +.card { + background: var(--card); + border-radius: var(--radius-md); + box-shadow: var(--shadow-sm); + border: 1px solid var(--border); + padding: clamp(20px, 4vw, 32px); + transition: box-shadow var(--transition); +} +.card:hover { box-shadow: var(--shadow-md); } +.card-flat { background: var(--card); border-radius: var(--radius-md); border: 1px solid var(--border); padding: clamp(16px, 3vw, 24px); } + +/* ── Buttons ─────────────────────────────────────────────── */ +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + padding: 11px 22px; + font-family: inherit; + font-size: 14px; + font-weight: 600; + border: none; + border-radius: var(--radius-pill); + cursor: pointer; + transition: background var(--transition), transform var(--transition), box-shadow var(--transition); + white-space: nowrap; +} +.btn:active { transform: translateY(1px) scale(0.97); } +.btn:disabled { opacity: 0.55; 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-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-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-danger { background: #ff4d4d; color: #fff; } +.btn-danger:hover:not(:disabled) { background: #e03c3c; box-shadow: 0 4px 12px rgba(255,77,77,0.3); } + +.btn-sm { padding: 7px 16px; font-size: 13px; } +.btn-xs { padding: 5px 12px; font-size: 12px; } +.btn-icon { padding: 9px; border-radius: var(--radius-sm); } + +/* ── Form Inputs ─────────────────────────────────────────── */ +.input, .select-input { + width: 100%; + padding: 12px 16px; + border: 1.5px solid var(--border); + border-radius: var(--radius-sm); + font-family: inherit; + font-size: 14px; + color: #222; + 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); +} +.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; } +.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; +} + +/* ── Badges ──────────────────────────────────────────────── */ +.badge { + display: inline-flex; align-items: center; gap: 4px; + padding: 3px 10px; border-radius: var(--radius-pill); + font-size: 11px; font-weight: 700; letter-spacing: 0.3px; + white-space: nowrap; +} +.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-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); } + +/* ── 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; } + +/* ── Divider ─────────────────────────────────────────────── */ +.divider { border: none; border-top: 1px solid var(--border); margin: 20px 0; } + +/* ── App Layout Scaffold ─────────────────────────────────── */ +.app-body { + display: flex; + flex-direction: column; + min-height: 100vh; +} +.page-main { + flex: 1; + width: min(100%, 1100px); + margin: clamp(24px, 4vw, 40px) auto; + padding: 0 clamp(16px, 3vw, 24px); +} +.page-main-wide { + flex: 1; + width: min(100%, 1300px); + margin: clamp(24px, 4vw, 40px) auto; + padding: 0 clamp(16px, 3vw, 24px); +} + +/* ── 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; } + +/* ── Skeleton loading ────────────────────────────────────── */ +@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); +} + +/* ── Utility ─────────────────────────────────────────────── */ +.flex { display: flex; } +.flex-center { display: flex; align-items: center; justify-content: center; } +.flex-between{ display: flex; align-items: center; justify-content: space-between; } +.flex-gap-sm { gap: 8px; } +.flex-gap-md { gap: 16px; } +.gap-8 { gap: 8px; } +.gap-12 { gap: 12px; } +.gap-16 { gap: 16px; } +.gap-24 { gap: 24px; } +.mt-8 { margin-top: 8px; } +.mt-16 { margin-top: 16px; } +.mt-24 { margin-top: 24px; } +.mb-8 { margin-bottom: 8px; } +.mb-16 { margin-bottom: 16px; } +.mb-24 { margin-bottom: 24px; } +.w-full { width: 100%; } +.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 States for Accessibility */ +.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; + 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-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); + --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); +} diff --git a/frontend/css/components.css b/frontend/css/components.css new file mode 100644 index 0000000..cbb80ae --- /dev/null +++ b/frontend/css/components.css @@ -0,0 +1,484 @@ +/* ============================================================ + components.css — Reusable UI components + Load after base.css + ============================================================ */ + +/* ── App Header ──────────────────────────────────────────── */ +.app-header { + background: var(--header-bg); + padding: 0 clamp(16px, 4vw, 32px); + height: 62px; + 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:hover { opacity: 0.85; } +.app-header .header-actions { display: flex; gap: 10px; align-items: center; } + +/* ── App Footer ──────────────────────────────────────────── */ +.app-footer { + background: var(--header-bg); + border-top: 1px solid rgba(0,80,140,0.10); + padding: 18px clamp(16px, 4vw, 32px); + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 12px; + margin-top: auto; +} +.app-footer img { height: 30px; } +.app-footer small { color: var(--muted); font-size: 12px; } + +/* ── Auth Layout — Split Card ────────────────────────────── */ +.auth-shell { + min-height: 100vh; + display: flex; + align-items: stretch; + background: #fff; +} +.auth-brand { + width: 42%; + min-width: 280px; + background: linear-gradient(145deg, var(--navy) 0%, var(--blue) 100%); + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 48px 40px; + color: #fff; + gap: 24px; +} +.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-form-side { + flex: 1; + display: flex; + align-items: center; + justify-content: center; + padding: clamp(32px, 5vw, 64px) clamp(24px, 6vw, 80px); + background: #fff; + 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 .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); } +body.dark-theme .auth-box .auth-subtitle { color: var(--muted); } +body.dark-theme .auth-box .form-label { color: var(--muted); } +body.dark-theme .auth-box .input { background: var(--card); color: var(--navy); border-color: var(--border); } +body.dark-theme .auth-links a { color: var(--blue); } + +@media (max-width: 768px) { + .auth-shell { flex-direction: column; } + .auth-brand { + width: 100%; + min-width: unset; + min-height: unset; + padding: 24px 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 h2 { font-size: 15px; margin: 0; } + .auth-form-side { padding: 28px 20px; } +} + +/* ── Page Header Row ─────────────────────────────────────── */ +.page-heading { + display: flex; + align-items: flex-end; + justify-content: space-between; + flex-wrap: wrap; + gap: 16px; + margin-bottom: 28px; +} +.page-heading h1, .page-heading h2 { margin: 0; } +.page-heading .page-meta { font-size: 13px; color: var(--muted); margin-top: 4px; } + +/* ── Stat Cards Row ──────────────────────────────────────── */ +.stat-row { 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); + border-radius: var(--radius-md); + padding: 20px 22px; + display: flex; + flex-direction: column; + gap: 6px; + 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); } + +/* ── Tab Bar ─────────────────────────────────────────────── */ +.tab-bar { + display: flex; + gap: 0; + border-bottom: 2px solid var(--border); + margin-bottom: 24px; + overflow-x: auto; + scrollbar-width: none; +} +.tab-bar::-webkit-scrollbar { display: none; } +.tab-btn { + padding: 12px 22px; + font-family: inherit; + font-size: 14px; + font-weight: 500; + color: var(--muted); + background: none; + border: none; + border-bottom: 3px solid transparent; + margin-bottom: -2px; + cursor: pointer; + transition: color var(--transition), border-color var(--transition); + 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-panel { display: none; } +.tab-panel.active{ display: block; animation: fadeIn 0.25s ease; } + +/* ── User Card (Admin Dashboard) ─────────────────────────── */ +.user-card { + background: var(--card); + border: 1px solid var(--border); + border-radius: var(--radius-md); + padding: 18px 20px; + display: flex; + flex-direction: column; + gap: 14px; + cursor: pointer; + 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; } +.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)); + 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); +} +.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-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); } + +/* ── 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); } + +/* ── Document Row ────────────────────────────────────────── */ +.doc-row { + display: flex; + align-items: center; + gap: 14px; + padding: 14px 16px; + border-radius: var(--radius-sm); + border: 1px solid var(--border); + background: #fafcff; + transition: border-color var(--transition), background var(--transition); + margin-bottom: 10px; +} +.doc-row:hover { border-color: #c5d9ee; background: var(--blue-light); } +.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-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-radius: var(--radius-md); + padding: 36px 24px; + text-align: center; + color: var(--muted); + transition: border-color var(--transition), background var(--transition); + cursor: pointer; +} +.drop-zone:hover, .drop-zone.drag-over { + border-color: var(--blue); + background: var(--blue-light); + color: var(--blue); +} +.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-hint { font-size: 13px; margin-top: 4px; } + +/* ── Search Bar ──────────────────────────────────────────── */ +.search-bar { + display: flex; + align-items: center; + gap: 10px; + background: #fff; + border: 1.5px solid var(--border); + border-radius: var(--radius-pill); + padding: 9px 18px; + 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 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; } + +/* ── Timeline Stepper ────────────────────────────────────── */ +.timeline-control { + display: flex; + align-items: center; + gap: 12px; + background: var(--bg); + border-radius: var(--radius-sm); + padding: 10px 16px; + width: fit-content; +} +.timeline-control .tl-btn { + width: 32px; height: 32px; + border-radius: 50%; + border: 1.5px solid var(--border); + background: #fff; + font-size: 18px; + font-weight: 600; + cursor: pointer; + 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-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 tr:last-child td { border-bottom: none; } +.approval-table tr:hover td { background: #fafcff; } + +/* ── Toggle Switch (approve/reject) ─────────────────────── */ +.review-toggle { + display: flex; + gap: 6px; +} +.review-toggle label { + 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; + transition: all var(--transition); +} +.review-toggle input[type=checkbox] { display: none; } +.review-toggle .approve-lbl { color: var(--success); } +.review-toggle .approve-lbl:has(input:checked), +.review-toggle input.approve:checked + label { background: var(--success-bg); border-color: var(--success); } +.review-toggle .reject-lbl { color: var(--error); } + +/* ── Engagement Banner ───────────────────────────────────── */ +.engagement-banner { + display: flex; + align-items: center; + gap: 16px; + padding: 16px 20px; + border-radius: var(--radius-md); + background: linear-gradient(90deg, #e3f2fd, #f0f9ff); + border: 1px solid #b3d9f5; + margin-bottom: 24px; +} +.engagement-banner .banner-icon { font-size: 28px; flex-shrink: 0; } +.engagement-banner .banner-text { flex: 1; } +.engagement-banner .banner-text strong { display: block; font-size: 14px; color: var(--navy); } +.engagement-banner .banner-text span { font-size: 13px; color: var(--muted); } +.engagement-banner.acknowledged { background: var(--success-bg); border-color: #a5d6a7; } + +/* ── Empty State ─────────────────────────────────────────── */ +.empty-state { + padding: 48px 24px; + text-align: center; + color: var(--muted); +} +.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-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; } + +@media (max-width: 900px) { + .mkt-nav-menu { + display: none; + position: absolute; + top: 72px; left: 0; + width: 100%; + background: var(--navy); + 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; +} +.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 --- */ + +.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 #a5d6a7; + border-radius: var(--radius-pill); +} + +.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; + 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: #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; +} diff --git a/frontend/css/marketing.css b/frontend/css/marketing.css new file mode 100644 index 0000000..8679f39 --- /dev/null +++ b/frontend/css/marketing.css @@ -0,0 +1,1199 @@ +*{ + + margin:0; + + padding:0; + + box-sizing:border-box; + + font-family:"Poppins",sans-serif; + +} + + + +body{ + + background:#f5f5f5; + + overflow-x:hidden; + +} + + + +img{max-width:100%;display:block} + + + +/* ================= NAVBAR ================= */ + + + +.navbar{ + width:100%; + position:absolute; + top:0; + left:0; + z-index:20; + backdrop-filter: blur(8px); + -webkit-backdrop-filter: blur(8px); + background: rgba(11, 37, 64, 0.15); + border-bottom: 1px solid rgba(255, 255, 255, 0.08); + transition: background 0.3s ease; +} + + + +.nav-container{ + + width:min(1200px,96%); + + margin:auto; + + padding:18px 12px; + + display:flex; + + align-items:center; + + justify-content:space-between; + +} + + + +#logos{ + + height:clamp(42px,5vw,64px); + + object-fit:contain; + +} + + + +/* NAV MENU */ + + + +.nav-menu{ + + display:flex; + + gap:32px; + + align-items:center; + +} + + + +.nav-menu a{ + + text-decoration:none; + + color:white; + + font-size:15px; + + font-weight:500; + +} + + + +.nav-menu a:hover{color:#FFD28C} + + + +/* login buttons */ + + + +.login-btn{ + + padding:10px 14px; + + background:var(--orange); + + color:#fff; + + border-radius:25px; + + border:none; + + font-weight:600; + + cursor:pointer; + +} + + + +.login-btn:hover{background:var(--orange-dark)} + + + +.login-btn:active{ + + transform:translateY(1px) scale(.94); + + box-shadow:0 2px 6px rgba(0,0,0,.12); + +} + + + +/* desktop vs mobile login visibility */ + + + +.desktop-login{display:inline-block;} + +.mobile-login{display:none;} + + + +.hamburger{ + + display:none; + + flex-direction:column; + + gap:4px; + + cursor:pointer; + +} + + + +.hamburger span{ + + width:26px; + + height:3px; + + background:white; + + border-radius:2px; + +} + + + +/* ================= HERO ================= */ + + + +.hero{ + + width:100%; + + min-height:580px; + + height:clamp(420px,60vh,620px); + + background: + + linear-gradient(rgba(0,0,0,.45),rgba(0,0,0,.45)), + + url("../images/home-background.jpg"); + + background-size:cover; + + background-position:center; + +} + + + +/* ================= BOTTOM BLOCK ================= */ + + + +.bottom-block{ + + width:min(900px,92%); + + margin:-360px auto 300px; + + background:#fff; + + padding:18px; + + border-radius:12px; + + display:flex; + + gap:22px; + + align-items:center; + + box-shadow:0 3px 12px rgba(0,0,0,.15); + +} + + + +.block-img{ + + width:120px; + + height:120px; + + border-radius:12px; + + background:url("/images/small.webp") center/cover; + +} + + + +.block-text h1{ + + font-size:clamp(18px,3vw,26px); + + font-weight:700; + +} + + + +.block-text p{color:#555} + + + +/* ================= ABOUT ================= */ + + + +.about-section{ + + width:min(1200px,92%); + + margin:60px auto; + + display:flex; + + gap:32px; + +} + + + +.about-section h2{ + + font-size:clamp(22px,3vw,30px); + + font-weight:700; + +} + + + +.about-section .text p{ + + line-height:1.8; + + font-size:15px; + + color:#333; + +} + + + +.about-section .note{ + + margin-top:12px; + + color:var(--orange); + + font-style:italic; + +} + + + +.about-section img{ + + width:100%; + + height:300px; + + border-radius:10px; + + object-fit:cover; + +} + + + +/* ================= SERVICES ================= */ + + + +.services-section{ + + width:min(1200px,92%); + + margin:50px auto; + + margin-bottom: 30px; + +} + + + +.services-section h2{ + + font-size:26px; + + font-weight:700; + + margin-bottom:22px; + + margin-top: 90px; + +} + + + +.services-grid{ + + display:flex; + + gap:22px; + + flex-wrap:wrap; + + justify-content:space-between; + + margin-bottom: 90px; + +} + + + +.service-card{ + + flex:1; + + min-width:260px; + + background:var(--accent); + + padding:22px; + + border-radius:20px; + + color:#fff; + + text-align:center; + + box-shadow:0 4px 12px rgba(0,0,0,.15); + + transition:.25s; + +} + + + +.service-card:hover{transform:translateY(-4px)} + + + +/* .service-card img{ + + align-items: center; + + width:110px; + + height:110px; + + border-radius:50%; + + object-fit:cover; + +} */ + + + +.service-card img{ + + display: block; + + margin: 0 auto; + + width:110px; + + height:110px; + + border-radius:50%; + + object-fit:cover; + +} + + + + + +.service-card h3{ + + margin-top:12px; + + font-size:15px; + + font-weight:600; + +} + + + +.service-card button{ + + margin-top:12px; + + padding:10px 18px; + + background:var(--orange); + + border:none; + + border-radius:20px; + + color:#fff; + + cursor:pointer; + +} + + + +.service-card button:active{ + + transform:translateY(1px) scale(.94); + + box-shadow:0 2px 6px rgba(0,0,0,.12); + +} + + + +/* ================= FOOTER ================= */ + + + +.footer{ + + background:var(--header-bg); + + margin-top:60px; + + border-top:4px solid var(--blue); + +} + + + +.footer-top{ + + width:min(1200px,92%); + + margin:auto; + + display:flex; + + justify-content:space-between; + + gap:40px; + + padding:40px 0; + + flex-wrap:wrap; + +} + + + +.footer-logo{width:220px} + + + +.footer-links{ + + display:flex; + + flex-direction:column; + + gap:10px; + +} + + + +.footer-links a{ + + text-decoration:none; + + color:var(--navy); + + font-size:16px; + + font-weight:500; + +} + + + +.footer-bottom{ + + text-align:center; + + padding:15px 0; + + background:var(--footer-bot); + +} + + + +/* ======================================================= + + RESPONSIVE BREAKPOINTS + + ======================================================= */ + + + +@media (max-width:992px){ + + + + .about-section{flex-direction:column;} + + + + .bottom-block{ + + width:96%; + + flex-direction:column; + + text-align:center; + + margin-top:-300px; + + } + + + + /* mobile nav dropdown */ + + + + .nav-menu{ + + display:none; + + position:absolute; + + top:76px; + + left:0; + + width:100%; + + background:var(--navy); + + padding:20px 0; + + flex-direction:column; + + gap:18px; + + align-items:center; + + } + + + + .nav-menu.active{display:flex;} + + + + /* desktop login hidden */ + + .desktop-login{display:none;} + + + + /* mobile login visible */ + + .mobile-login{ + + display:block; + + margin-top:6px; + + padding:10px 18px; + + border-radius:20px; + + background:var(--orange); + + color:#fff; + + font-weight:600; + + width:140px; + + text-align:center; + + } + + + + .hamburger{display:flex;} + +} + + + +@media (max-width:576px){ + + + + .service-card{min-width:100%} + + + + .service-card h3{font-size:14px;} + + + + .bottom-block{margin-bottom:240px;} + +} + + + +/* --- Page Specific Styles --- */ + + + +.page-hero h1, body.dark-theme .page-hero h1 { + font-size:clamp(22px, 4vw, 38px); + font-weight:700; + color: #ffffff !important; +} + +.page-hero p, body.dark-theme .page-hero p { + color: #ffffff !important; +} + + + +.about-wrapper{ + + width:min(1200px, 92%); + + margin:70px auto; + + display:flex; + + flex-direction:column; + + gap:40px; + +} + + + +.page-hero{ + + width:100%; + + min-height:580px; + + height:clamp(420px,60vh,620px); + + color:white; + + display:flex; + + align-items:center; + + justify-content:center; + + text-align:center; + + + + background: + + linear-gradient(rgba(56,54,54,.55),rgba(0,0,0,.55)), + + url("../images/Services-background-image.webp"); + + + + background-size:cover; + + background-position:center; + +} + + + +.about-block{ + + display:flex; + + gap:28px; + + background:#fff; + + padding:clamp(18px, 3vw, 32px); + + border-radius:14px; + + box-shadow:0 6px 16px rgba(0,0,0,.08); + + align-items:center; + +} + + + +.about-img{ + + width:380px; + + max-width:100%; + + height:260px; + + border-radius:14px; + + object-fit:cover; + +} + + + +.reverse{ + + flex-direction:row-reverse; + +} + + + +.page-hero{ + + width:100%; + + min-height:580px; + + height:clamp(420px, 60vh, 620px); + + color:white; + + display:flex; + + align-items:center; + + justify-content:center; + + text-align:center; + + + + background: + + linear-gradient(rgba(0,0,0,.55),rgba(0,0,0,.55)), + + url("../images/About-us-background-image.webp"); + + + + background-size:cover; + + background-position:center; + +} + + + +.page-hero h1{ + + font-size:clamp(22px,4vw,34px); + + font-weight:700; + +} + +.services-wrapper { + + width:min(1200px,92%); + + margin:70px auto; + + display:flex; + + flex-direction:column; + + gap:50px; + +} + + + +.service-block { + + display:flex; + + align-items:center; + + gap:32px; + + background:#fff; + + padding:clamp(20px,3vw,35px); + + border-radius:15px; + + box-shadow:0 4px 12px rgba(0,0,0,.12); + +} + + + +.service-block.reverse { + + flex-direction:row-reverse; + +} + + + +.service-text h2 { + + font-size:clamp(18px,2.6vw,22px); + + font-weight:700; + + margin-bottom:10px; + + color:var(--navy); + +} + + + +.service-text p { + + line-height:1.8; + + font-size:15px; + + color:#333; + +} + + + +.list-items li { + + margin-left:28px; + + color:#333; + +} + + + +.service-img, + +.service-img-bl-3 { + + width:380px; + + max-width:100%; + + height:260px; + + border-radius:14px; + + object-fit:cover; + +} + + +@media (max-width: 992px) { + .service-block, + .service-block.reverse { + flex-direction: column; + } + + .service-img, + .service-img-bl-3 { + width: 100%; + height: 240px; + } +} + + +.contact-section { + + width:min(1200px,92%); + + margin:70px auto; + + border:2px solid rgb(131,124,124); + + border-radius:15px; + + padding-top: 20px; + + padding-bottom: 20px; + +} + + + +.contact-title { + + font-size:28px; + + font-weight:700; + + margin-bottom:30px; + + text-align:center; + +} + + + +.contact-container { + + display:flex; + + padding:20px; + + width:70%; + + gap:35px; + + margin:auto; + +} + + + +.contact-info { + + flex:1; + + display:flex; + + flex-direction:column; + + gap:25px; + +} + + + +.info-box { + + padding:20px; + + border-radius:15px; + + color:white; + +} + + + +.usa { + + background:var(--accent); + +} + + + +.ind { + + background:var(--orange); + +} + + + +.contact-form { + + flex:1.3; + + background:white; + + padding:50px; + + border-radius:15px; + + box-shadow:0 3px 10px rgba(0,0,0,.15); + +} + + + +.form-row { + + display:flex; + gap:15px; +} + +.contact-form input, +.contact-form textarea { + width:100%; + padding:12px 15px; + border-radius:10px; + border:1px solid #ddd; + margin-bottom:15px; + font-family: inherit; +} + +.phone-row { + display:flex; + gap:10px; + border:1px solid #ddd; + padding:10px; + border-radius:10px; +} + +.contact-form button { + margin-top:20px; + padding:10px 25px; + background:var(--accent); + color:#fff; + border-radius:20px; + border:none; +} + +.email-box { + display:flex; + align-items:center; + margin-top:20px; + gap:10px; + font-size:14px; + color:#333; +} + +.email-box img { + width:20px; +} + +.phone img { + width:16px; +} + +/* --- Solid Navbar Modifier (for pages without hero images) --- */ +.navbar-solid { + position: relative !important; + background: var(--footer-bot) !important; + backdrop-filter: none !important; + -webkit-backdrop-filter: none !important; + border-bottom: none !important; +} +.navbar-solid .nav-menu a { + color: var(--navy) !important; +} +.navbar-solid .hamburger span { + background: var(--navy) !important; +} + +/* Micro-animations */ +.nav-menu a { + position: relative; +} +.nav-menu a::after { + content: ''; + position: absolute; + width: 0; + height: 2px; + bottom: -4px; + left: 0; + background-color: currentColor; + transition: width 0.3s ease; +} +.nav-menu a:hover::after { + width: 100%; +} + +.service-block { + transition: transform 0.3s ease, box-shadow 0.3s ease; +} +.service-block:hover { + transform: translateY(-6px); + box-shadow: 0 10px 25px rgba(0,0,0,0.12); +} + +/* --- Dark Theme Overrides for Marketing Pages --- */ +body.dark-theme .bottom-block, +body.dark-theme .about-block, +body.dark-theme .service-block, +body.dark-theme .contact-form, +body.dark-theme .service-card { + background: var(--card); +} +/* Text colors */ +body.dark-theme .service-text p, +body.dark-theme .list-items li, +body.dark-theme .email-box, +body.dark-theme p, +body.dark-theme .block-text p, +body.dark-theme .about-section .text p, +body.dark-theme .about-text p, +body.dark-theme .footer-bottom, +body.dark-theme .footer-links a { + color: var(--muted) !important; +} +/* Headers */ +body.dark-theme h1, +body.dark-theme h2, +body.dark-theme h3, +body.dark-theme h4, +body.dark-theme .block-text h1, +body.dark-theme .about-section h2, +body.dark-theme .services-section h2, +body.dark-theme .contact-title, +body.dark-theme .service-card h3 { + color: var(--navy) !important; +} +body.dark-theme .contact-form input, +body.dark-theme .contact-form textarea, +body.dark-theme .phone-row { + background: var(--bg); + color: var(--navy); + border-color: var(--border); +} +body.dark-theme .contact-section { + border-color: var(--border); +} +body.dark-theme .navbar-solid { + background: var(--card) !important; +} +@media (max-width:992px) { + body.dark-theme #navMenu, + body.dark-theme .nav-menu { + background-color: #262a34 !important; + } +} + diff --git a/frontend/dashboard.html b/frontend/dashboard.html new file mode 100644 index 0000000..58bf147 --- /dev/null +++ b/frontend/dashboard.html @@ -0,0 +1,327 @@ + + + + + + + BookKeepPro | Dashboard + + + + + + + + + + + + +
+ +
+ + + + + +
+
+ +
+ + + + + + +
+
+

Welcome back!

+

Manage your tax documents and review filings below.

+
+
+ + +
+

Upload Documents

+
+
+
+
Personal Documents
+
W-2, 1099, tax organizer and more
+
+
+
+
Business Documents
+
S-Corp, LLC, partnership organizers
+
+
+
+ + +
+
+

Returns for Review

+ +
+
+
+
inbox
+
No returns yet
+
When your accountant uploads your tax returns, they'll appear here.
+
+
+
+ +
+ + + + + + + + + + + diff --git a/frontend/forgot-password.html b/frontend/forgot-password.html new file mode 100644 index 0000000..fabf26b --- /dev/null +++ b/frontend/forgot-password.html @@ -0,0 +1,66 @@ + + + + + + BookKeepPro | Forgot Password + + + + + + + + + +
+ +
+ +
+

Reset Your Password

+

We'll send a secure link to your registered email address.

+
+ +
+
+
🔑
+

Forgot Password?

+

Enter your email and we'll send a reset link

+ +
+ + +
+ + + + +
+
+ +
+ + + + + diff --git a/frontend/home.html b/frontend/home.html new file mode 100644 index 0000000..f3af92f --- /dev/null +++ b/frontend/home.html @@ -0,0 +1,86 @@ + + + + + +Bookkeeping Landing Page + + + + + + + + + + + +{% include 'partials/navbar.html' %} + + + +
+ + + +
+
+ +
+

PRECISION | COMPLIANCE | FINANCIAL GROWTH

+

Your Trusted Bookkeeping & Financial Operations Partner for Growing Businesses

+
+
+ + + +
+
+ +

+ We are BOOKKEEPRO +

+ +

+ 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. + 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. +

+ +

-- Our People Are Passionate About What We Do

+
+ + +
+ + + +
+

OUR SERVICES

+ +
+ +
+ +

Professional Bookkeeping for Firms & Businesses

+ +
+ +
+ +

Professional & Globally Trusted Payroll Solutions

+ +
+ +
+ +

Professional Tax Planning &
Preparation

+ +
+ +
+
+ +{% include 'partials/footer.html' %} + + + diff --git a/frontend/images/About-us-background-image.webp b/frontend/images/About-us-background-image.webp new file mode 100644 index 0000000..88b1995 Binary files /dev/null and b/frontend/images/About-us-background-image.webp differ diff --git a/frontend/images/Background-image.jpg b/frontend/images/Background-image.jpg new file mode 100644 index 0000000..12f1b87 Binary files /dev/null and b/frontend/images/Background-image.jpg differ diff --git a/frontend/images/Background-image.png b/frontend/images/Background-image.png new file mode 100644 index 0000000..aa1f271 Binary files /dev/null and b/frontend/images/Background-image.png differ diff --git a/frontend/images/Background-image.webp b/frontend/images/Background-image.webp new file mode 100644 index 0000000..34412b5 Binary files /dev/null and b/frontend/images/Background-image.webp differ diff --git a/frontend/images/Gemini_Generated_Image_5pqvpl5pqvpl5pqv.jpg b/frontend/images/Gemini_Generated_Image_5pqvpl5pqvpl5pqv.jpg new file mode 100644 index 0000000..b3c402e Binary files /dev/null and b/frontend/images/Gemini_Generated_Image_5pqvpl5pqvpl5pqv.jpg differ diff --git a/frontend/images/Gemini_Generated_Image_5pqvpl5pqvpl5pqv.png b/frontend/images/Gemini_Generated_Image_5pqvpl5pqvpl5pqv.png new file mode 100644 index 0000000..85ce4a2 Binary files /dev/null and b/frontend/images/Gemini_Generated_Image_5pqvpl5pqvpl5pqv.png differ diff --git a/frontend/images/Gemini_Generated_Image_5pqvpl5pqvpl5pqv.webp b/frontend/images/Gemini_Generated_Image_5pqvpl5pqvpl5pqv.webp new file mode 100644 index 0000000..6b9d7fa Binary files /dev/null and b/frontend/images/Gemini_Generated_Image_5pqvpl5pqvpl5pqv.webp differ diff --git a/frontend/images/Gemini_Generated_Image_qacxnoqacxnoqacx.jpg b/frontend/images/Gemini_Generated_Image_qacxnoqacxnoqacx.jpg new file mode 100644 index 0000000..25b7cba Binary files /dev/null and b/frontend/images/Gemini_Generated_Image_qacxnoqacxnoqacx.jpg differ diff --git a/frontend/images/Gemini_Generated_Image_qacxnoqacxnoqacx.png b/frontend/images/Gemini_Generated_Image_qacxnoqacxnoqacx.png new file mode 100644 index 0000000..bec1f87 Binary files /dev/null and b/frontend/images/Gemini_Generated_Image_qacxnoqacxnoqacx.png differ diff --git a/frontend/images/Gemini_Generated_Image_qacxnoqacxnoqacx.webp b/frontend/images/Gemini_Generated_Image_qacxnoqacxnoqacx.webp new file mode 100644 index 0000000..a782161 Binary files /dev/null and b/frontend/images/Gemini_Generated_Image_qacxnoqacxnoqacx.webp differ diff --git a/frontend/images/Services-background-image.webp b/frontend/images/Services-background-image.webp new file mode 100644 index 0000000..3dfc38b Binary files /dev/null and b/frontend/images/Services-background-image.webp differ diff --git a/frontend/images/about-us-block-1.webp b/frontend/images/about-us-block-1.webp new file mode 100644 index 0000000..5fb7fc6 Binary files /dev/null and b/frontend/images/about-us-block-1.webp differ diff --git a/frontend/images/about-us-block-2.webp b/frontend/images/about-us-block-2.webp new file mode 100644 index 0000000..6807c56 Binary files /dev/null and b/frontend/images/about-us-block-2.webp differ diff --git a/frontend/images/bookkeeppro-logo.jpg b/frontend/images/bookkeeppro-logo.jpg new file mode 100644 index 0000000..7fb778e Binary files /dev/null and b/frontend/images/bookkeeppro-logo.jpg differ diff --git a/frontend/images/bookkeeppro-logo.png b/frontend/images/bookkeeppro-logo.png new file mode 100644 index 0000000..df9eed6 Binary files /dev/null and b/frontend/images/bookkeeppro-logo.png differ diff --git a/frontend/images/bookkeeppro-logo.webp b/frontend/images/bookkeeppro-logo.webp new file mode 100644 index 0000000..efab1fa Binary files /dev/null and b/frontend/images/bookkeeppro-logo.webp differ diff --git a/frontend/images/business-meeting-long-table-with-chart.jpg b/frontend/images/business-meeting-long-table-with-chart.jpg new file mode 100644 index 0000000..98895b4 Binary files /dev/null and b/frontend/images/business-meeting-long-table-with-chart.jpg differ diff --git a/frontend/images/call.webp b/frontend/images/call.webp new file mode 100644 index 0000000..06d0d24 Binary files /dev/null and b/frontend/images/call.webp differ diff --git a/frontend/images/facebook.webp b/frontend/images/facebook.webp new file mode 100644 index 0000000..8de813b Binary files /dev/null and b/frontend/images/facebook.webp differ diff --git a/frontend/images/general_engagement_letter_2025-1 - common.pdf b/frontend/images/general_engagement_letter_2025-1 - common.pdf new file mode 100644 index 0000000..4ddd56d Binary files /dev/null and b/frontend/images/general_engagement_letter_2025-1 - common.pdf differ diff --git a/frontend/images/home-about.jpg b/frontend/images/home-about.jpg new file mode 100644 index 0000000..0473118 Binary files /dev/null and b/frontend/images/home-about.jpg differ diff --git a/frontend/images/home-background.jpg b/frontend/images/home-background.jpg new file mode 100644 index 0000000..4f3ce85 Binary files /dev/null and b/frontend/images/home-background.jpg differ diff --git a/frontend/images/home-card.jpg b/frontend/images/home-card.jpg new file mode 100644 index 0000000..9d4ed09 Binary files /dev/null and b/frontend/images/home-card.jpg differ diff --git a/frontend/images/individual_taxpayer_organizer_2024.pdf b/frontend/images/individual_taxpayer_organizer_2024.pdf new file mode 100644 index 0000000..191dc06 Binary files /dev/null and b/frontend/images/individual_taxpayer_organizer_2024.pdf differ diff --git a/frontend/images/individual_taxpayer_organizer_sole_proprietorship_rental_2025-doc-1.pdf b/frontend/images/individual_taxpayer_organizer_sole_proprietorship_rental_2025-doc-1.pdf new file mode 100644 index 0000000..18c5438 Binary files /dev/null and b/frontend/images/individual_taxpayer_organizer_sole_proprietorship_rental_2025-doc-1.pdf differ diff --git a/frontend/images/instagram.webp b/frontend/images/instagram.webp new file mode 100644 index 0000000..e45aeae Binary files /dev/null and b/frontend/images/instagram.webp differ diff --git a/frontend/images/linkedin.webp b/frontend/images/linkedin.webp new file mode 100644 index 0000000..0ab0de5 Binary files /dev/null and b/frontend/images/linkedin.webp differ diff --git a/frontend/images/llc_tax_organizer_2025-personal-doc-2.pdf b/frontend/images/llc_tax_organizer_2025-personal-doc-2.pdf new file mode 100644 index 0000000..ad2b191 Binary files /dev/null and b/frontend/images/llc_tax_organizer_2025-personal-doc-2.pdf differ diff --git a/frontend/images/mail.webp b/frontend/images/mail.webp new file mode 100644 index 0000000..5182b5e Binary files /dev/null and b/frontend/images/mail.webp differ diff --git a/frontend/images/partnership_tax_organizer_2025-persoal-doc-3.pdf b/frontend/images/partnership_tax_organizer_2025-persoal-doc-3.pdf new file mode 100644 index 0000000..8b39346 Binary files /dev/null and b/frontend/images/partnership_tax_organizer_2025-persoal-doc-3.pdf differ diff --git a/frontend/images/s_corporation_organizer_2025-business-doc-1.pdf b/frontend/images/s_corporation_organizer_2025-business-doc-1.pdf new file mode 100644 index 0000000..613dd0a Binary files /dev/null and b/frontend/images/s_corporation_organizer_2025-business-doc-1.pdf differ diff --git a/frontend/images/services-1.jpg b/frontend/images/services-1.jpg new file mode 100644 index 0000000..766822d Binary files /dev/null and b/frontend/images/services-1.jpg differ diff --git a/frontend/images/services-2.jpg b/frontend/images/services-2.jpg new file mode 100644 index 0000000..0c4fff3 Binary files /dev/null and b/frontend/images/services-2.jpg differ diff --git a/frontend/images/services-3.jpg b/frontend/images/services-3.jpg new file mode 100644 index 0000000..262ef17 Binary files /dev/null and b/frontend/images/services-3.jpg differ diff --git a/frontend/images/services-block-3.webp b/frontend/images/services-block-3.webp new file mode 100644 index 0000000..5233355 Binary files /dev/null and b/frontend/images/services-block-3.webp differ diff --git a/frontend/images/small.jpg b/frontend/images/small.jpg new file mode 100644 index 0000000..f5c6ade Binary files /dev/null and b/frontend/images/small.jpg differ diff --git a/frontend/images/small.png b/frontend/images/small.png new file mode 100644 index 0000000..aa44135 Binary files /dev/null and b/frontend/images/small.png differ diff --git a/frontend/images/small.webp b/frontend/images/small.webp new file mode 100644 index 0000000..9b6bce6 Binary files /dev/null and b/frontend/images/small.webp differ diff --git a/frontend/images/trash.png b/frontend/images/trash.png new file mode 100644 index 0000000..8bb661e Binary files /dev/null and b/frontend/images/trash.png differ diff --git a/frontend/images/young-business-people-using-computer-in-office.jpg b/frontend/images/young-business-people-using-computer-in-office.jpg new file mode 100644 index 0000000..fcfcb7b Binary files /dev/null and b/frontend/images/young-business-people-using-computer-in-office.jpg differ diff --git a/frontend/images/young-business-people-using-computer-in-office.webp b/frontend/images/young-business-people-using-computer-in-office.webp new file mode 100644 index 0000000..6518c98 Binary files /dev/null and b/frontend/images/young-business-people-using-computer-in-office.webp differ diff --git a/frontend/js/admin.js b/frontend/js/admin.js new file mode 100644 index 0000000..c35d3c1 --- /dev/null +++ b/frontend/js/admin.js @@ -0,0 +1,6 @@ +// admin.js — legacy reference file, not imported by any HTML page. +// admin-dashboard.html uses auth.js + inline scripts exclusively. +// Kept here as a reference stub; safe to delete if no longer needed. + +// All shared utilities (authFetch, logoutUser, guardAuth, escapeHtml, +// reviewBadge, buildYearOptions) are now in /js/auth.js. diff --git a/frontend/js/auth.js b/frontend/js/auth.js new file mode 100644 index 0000000..f50e0cf --- /dev/null +++ b/frontend/js/auth.js @@ -0,0 +1,154 @@ +/** + * auth.js — shared utilities loaded by every protected page. + * + * Provides: + * authFetch(url, options) — fetch with Bearer token + auto-redirect on 401 + * logoutUser() — clear storage and redirect to /login + * guardAuth(requiredRoles) — redirect if token missing or role not in list + * escapeHtml(str) — XSS-safe string for innerHTML insertion + * reviewBadge(status) — returns safe HTML badge string + * buildYearOptions(selectId, def) — populate a + + +
+ +
+ + +
+
+ + + + + + + + + + + + + + diff --git a/frontend/partials/footer.html b/frontend/partials/footer.html new file mode 100644 index 0000000..70cf7c8 --- /dev/null +++ b/frontend/partials/footer.html @@ -0,0 +1,38 @@ + + + diff --git a/frontend/partials/navbar.html b/frontend/partials/navbar.html new file mode 100644 index 0000000..e627846 --- /dev/null +++ b/frontend/partials/navbar.html @@ -0,0 +1,37 @@ + diff --git a/frontend/profile.html b/frontend/profile.html new file mode 100644 index 0000000..ad9b549 --- /dev/null +++ b/frontend/profile.html @@ -0,0 +1,163 @@ + + + + + + BookKeepPro | My Profile + + + + + + + + + +
+ +
+ + + + + +
+
+ +
+
+
+

My Profile

+

Update your name, phone number, or password

+
+
+ +
+

Account Info

+ +
+ + +
+
+
+ + +
+
+ + +
+
+
+ +
+
+

Change Password

+ ▶ +
+

Click to expand and update your password

+ + +
+ + +
+ + + + + + + + + diff --git a/frontend/resend-verification.html b/frontend/resend-verification.html new file mode 100644 index 0000000..aace764 --- /dev/null +++ b/frontend/resend-verification.html @@ -0,0 +1,66 @@ + + + + + + BookKeepPro | Resend Verification + + + + + + + + + +
+ +
+ +
+

Verify Your Email

+

Check your inbox for the verification link. It expires in 24 hours.

+
+ +
+
+
📧
+

Resend Verification

+

We'll send a new link to your registered email

+ +
+ + +
+ + + + +
+
+ +
+ + + + + diff --git a/frontend/reset-password.html b/frontend/reset-password.html new file mode 100644 index 0000000..2593a39 --- /dev/null +++ b/frontend/reset-password.html @@ -0,0 +1,87 @@ + + + + + + BookKeepPro | Reset Password + + + + + + + + + +
+ +
+ +
+

Choose a New Password

+

Pick something strong — at least 8 characters with a mix of letters, numbers, and symbols.

+
+ +
+
+
🔒
+

Reset Password

+

Enter your new password below

+ +
+ +
+ + +
+
+ + + + +
+
+ +
+ + + + + + diff --git a/frontend/services.html b/frontend/services.html new file mode 100644 index 0000000..f1a3bb2 --- /dev/null +++ b/frontend/services.html @@ -0,0 +1,117 @@ + + + + + +Services — BookKeepro + + + + + + + + + + + +{% include 'partials/navbar.html' %} + + + +
+

Professional Services for Firms & Businesses

+
+ + + +
+ + +
+
+ +

For Accounting Firms and Businesses

+ +

+ 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. +

+ +
+ +

+ Bookkeepro’s India based offshore bookkeeping services offer several benefits + to global accounting firms and businesses. +

+
+ + Accounting Outsourcing +
+ + +
+
+ +

Scale Your Business with Accounting Outsourcing

+ +

+ 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. +

+ +
+ +

+ That’s where we come in. Allow us to present the game-changing solution: + Accounting Outsourcing. +

+
+ + Outsourced Accounting Team +
+ + +
+
+ +

Tax Planning And Preparation

+ +

+ 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: +

+ +
    +
  1. Comply with and leverage changing federal tax law
  2. +
  3. Minimize overall tax liability through strategic planning
  4. +
  5. Determine taxation of owner-provided benefits
  6. +
  7. Leverage year-end tax opportunities
  8. +
  9. Manage multi-state tax exposure based on nexus
  10. +
+ +
+ +

+ Our proactive approach goes beyond traditional filing to deliver long-term value. +

+
+ + Tax Strategy Services +
+ +
+ +{% include 'partials/footer.html' %} + + + diff --git a/frontend/signup.html b/frontend/signup.html new file mode 100644 index 0000000..2322fb5 --- /dev/null +++ b/frontend/signup.html @@ -0,0 +1,87 @@ + + + + + + BookKeepPro | Sign Up + + + + + + + + + +
+ +
+ +
+

Join BookKeepPro

+

Create your account to securely upload documents, track reviews, and stay on top of your filings.

+
+ +
+
+ ← Back to Home +

Create Account

+

It only takes a minute

+ +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+ + +
+
+ + + +
+
+
+ +
+ + + + + + + + + diff --git a/frontend/upload-business.html b/frontend/upload-business.html new file mode 100644 index 0000000..0bda903 --- /dev/null +++ b/frontend/upload-business.html @@ -0,0 +1,268 @@ + + + + + + BookKeepPro | Business Documents + + + + + + + + + + +
+ +
+ + + + + +
+
+ +
+
+
+

Business Documents

+

Upload your business tax documents securely

+
+
+ + +
+
+ +
+

Required Documents

+
+
+ +
+
+
+

Additional Documents

+

Upload any supplementary business documents

+
+ +
+ +
+
folder
+
Drag & drop files here
+
or click to browse · PDF, JPG, PNG, WEBP, DOC, DOCX · Max 10MB
+
+ +
+

+
+
+ + + + + + + + + + diff --git a/frontend/upload-personal.html b/frontend/upload-personal.html new file mode 100644 index 0000000..179f076 --- /dev/null +++ b/frontend/upload-personal.html @@ -0,0 +1,329 @@ + + + + + + BookKeepPro | Personal Documents + + + + + + + + + + +
+ +
+ + + + + +
+
+ +
+
+
+

Personal Documents

+

Upload your personal tax documents securely

+
+
+ + +
+
+ + +
+

Required Documents

+
+
+ + +
+
+
+

Additional Documents

+

Upload any supplementary personal documents

+
+ +
+ +
+
folder
+
Drag & drop files here
+
or click to browse · PDF, JPG, PNG, WEBP, DOC, DOCX · Max 10MB
+
+ +
+

+
+
+ + + + + + + + + + diff --git a/frontend/verify-email.html b/frontend/verify-email.html new file mode 100644 index 0000000..794f732 --- /dev/null +++ b/frontend/verify-email.html @@ -0,0 +1,78 @@ + + + + + + BookKeepPro | Verify Email + + + + + + + + + +
+ +
+ +
+

Almost There

+

We're verifying your email address right now.

+
+ +
+
+
pending
+

Verifying your email…

+

Please wait a moment.

+
+
+ +
+ + + + diff --git a/nginx/default.conf b/nginx/default.conf new file mode 100644 index 0000000..6e6381c --- /dev/null +++ b/nginx/default.conf @@ -0,0 +1,23 @@ +server { + listen 80; + server_name _; + + client_max_body_size 25m; + + location ~ ^/(css|js|images)/ { + root /usr/share/nginx/html; + expires 30d; + add_header Cache-Control "public, no-transform"; + } + + location / { + proxy_pass http://app:8000; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + } +} \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..c6b5964 Binary files /dev/null and b/requirements.txt differ diff --git a/services/api/app/__init__.py b/services/api/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/services/api/app/auth/__init__.py b/services/api/app/auth/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/services/api/app/auth/security.py b/services/api/app/auth/security.py new file mode 100644 index 0000000..6e88f46 --- /dev/null +++ b/services/api/app/auth/security.py @@ -0,0 +1,675 @@ +import os +import logging +from datetime import datetime, timedelta + +from jose import jwt, JWTError +from fastapi import APIRouter, Depends, HTTPException, status, Request, Query, BackgroundTasks +from fastapi.security import OAuth2PasswordBearer +from sqlalchemy.orm import Session + +from app.db import get_db +import app.crud as crud +from app.schemas import SignupRequest, LoginRequest, TokenResponse, ForgotPasswordRequest, ResetPasswordRequest, ResendVerificationRequest, RoleChangeRequest +from app.models import UserRole, User as UserModel, PersonalDocument, BusinessDocument + +logger = logging.getLogger(__name__) + +# ========================= +# Router +# ========================= +router = APIRouter(prefix="/api/auth", tags=["auth"]) + + +# ========================= +# Config +# ========================= +SECRET_KEY = os.getenv("SECRET_KEY") +if not SECRET_KEY: + raise RuntimeError( + "SECRET_KEY environment variable is not set. " + "Generate one with: openssl rand -hex 32" + ) +ALGORITHM = os.getenv("ALGORITHM", "HS256") +ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "1440")) + +oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login") +# ========================= +# JWT helpers +# ========================= +def create_access_token( + subject: str, + role: str = "user", + expires_minutes: int | None = None, +) -> str: + expire = datetime.utcnow() + timedelta( + minutes=expires_minutes or ACCESS_TOKEN_EXPIRE_MINUTES + ) + payload = { + "sub": subject, + "role": role.lower(), + "exp": expire, + } + return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM) + + +RESET_TOKEN_EXPIRE_MINUTES = 15 + +def create_password_reset_token(email: str) -> str: + expire = datetime.utcnow() + timedelta(minutes=RESET_TOKEN_EXPIRE_MINUTES) + payload = { + "sub": email, + "type": "password_reset", + "exp": expire, + } + return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM) + + +VERIFY_TOKEN_EXPIRE_MINUTES = 60 * 24 # 24 hours + +def create_email_verification_token(email: str) -> str: + expire = datetime.utcnow() + timedelta(minutes=VERIFY_TOKEN_EXPIRE_MINUTES) + payload = { + "sub": email, + "type": "email_verification", + "exp": expire, + } + return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM) + + +from app.utils.emailer import send_email +from app.limiter import limiter + +@router.post("/forgot-password") +@limiter.limit("3/hour") +async def forgot_password( + request: Request, + payload: ForgotPasswordRequest, + background: BackgroundTasks, + db: Session = Depends(get_db), +): + user = crud.get_user_by_email(db, payload.email) + + # Anti-enumeration + if not user: + return {"message": "If the email exists, a reset link has been sent"} + + reset_token = create_password_reset_token(user.email) + + frontend_url = os.getenv("FRONTEND_URL", "https://bookkeepro.net") + reset_link = f"{frontend_url}/reset-password?token={reset_token}" + + # Add email task with error handling + async def send_reset_email_safely(): + try: + await send_email( + to=user.email, + subject="Reset your BookKeepro password", + body=f""" + Hi {user.name},

+ Click the button below to reset your password:

+ + + Reset Password + +

+ This link expires in 15 minutes.

+ BookKeepro Team + """ + ) + except Exception as e: + import logging + logger = logging.getLogger(__name__) + logger.error(f"Failed to send reset email to {user.email}: {e}") + + background.add_task(send_reset_email_safely) + + return {"message": "If the email exists, a reset link has been sent"} + + +@router.post("/reset-password") +def reset_password( + payload: ResetPasswordRequest, + db: Session = Depends(get_db), +): + try: + decoded = jwt.decode(payload.token, SECRET_KEY, algorithms=[ALGORITHM]) + email = decoded.get("sub") + token_type = decoded.get("type") + + if token_type != "password_reset": + logger.warning(f"Invalid password reset token type for email: {email}") + raise HTTPException(status_code=400, detail="Invalid token") + + except JWTError: + logger.warning(f"Invalid or expired password reset token") + raise HTTPException(status_code=400, detail="Invalid or expired token") + + user = crud.get_user_by_email(db, email) + if not user: + logger.warning(f"Password reset attempt for non-existent user: {email}") + raise HTTPException(status_code=404, detail="User not found") + + hashed_password = crud.hash_password(payload.new_password) + crud.update_user_password(db, user, hashed_password) + + logger.info(f"Password reset successful for user: {email}") + + return {"message": "Password reset successful"} + + + + +def get_current_user( + token: str = Depends(oauth2_scheme), + db: Session = Depends(get_db), +): + """Get current user from JWT token and verify role from database (not JWT). + + CRITICAL: Role is always read from database, not from JWT token. + This prevents JWT role spoofing attacks. + """ + credentials_exception = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate credentials", + headers={"WWW-Authenticate": "Bearer"}, + ) + + try: + payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + email: str | None = payload.get("sub") + + if not email: + raise credentials_exception + + except JWTError: + raise credentials_exception + + user = crud.get_user_by_email(db, email) + if not user: + raise credentials_exception + + # CRITICAL: Always use role from database, never trust JWT role + # This prevents attackers from forging JWT with elevated privileges + return user + + +def require_admin(current_user=Depends(get_current_user)): + if current_user.role not in [UserRole.admin, UserRole.super_admin]: + logger.warning(f"Unauthorized admin access attempt by user {current_user.id} ({current_user.email})") + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Admin access required" + ) + logger.info(f"Admin action by user {current_user.id} ({current_user.email})") + return current_user + + +def require_super_admin(current_user=Depends(get_current_user)): + """Dependency to enforce super_admin-only access (role management, etc.).""" + if current_user.role != UserRole.super_admin: + logger.warning(f"Unauthorized super_admin access attempt by user {current_user.id} ({current_user.email})") + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Super admin access required" + ) + return current_user + + +# ========================= +# Auth Routes +# ========================= + +@router.post("/signup", response_model=TokenResponse) +@limiter.limit("10/hour") +async def signup(request: Request, payload: SignupRequest, background: BackgroundTasks, db: Session = Depends(get_db)): + if crud.get_user_by_email(db, payload.email): + logger.warning(f"Signup attempt with already registered email: {payload.email}") + raise HTTPException(status_code=400, detail="Email already registered") + + role_value = "user" # all public signups are always regular users + + # Admins created via DB are pre-verified; new signups are always "user" and unverified + is_admin = False + + user = crud.create_user( + db=db, + name=payload.name, + email=payload.email, + phone=payload.phone or "", + password=payload.password, + role=role_value, + is_verified=1 if is_admin else 0, + ) + + logger.info(f"New user registered: {user.email} with role {user.role}") + + crud.log_action(db, "signup", user_id=user.id, ip_address=request.client.host if hasattr(request, 'client') and request.client else None) + + # Send verification email in background (non-blocking) + if not is_admin: + verify_token = create_email_verification_token(user.email) + frontend_url = os.getenv("FRONTEND_URL", "https://bookkeepro.net") + verify_link = f"{frontend_url}/verify-email?token={verify_token}" + + async def send_verify_email(): + try: + await send_email( + to=user.email, + subject="Verify your BookKeepro email", + body=f""" + Hi {user.name},

+ Welcome to BookKeepro! Please verify your email address to activate your account.

+ + Verify My Email + +

+ This link expires in 24 hours. If you did not sign up, ignore this email.

+ BookKeepro Team + """ + ) + except Exception as e: + logger.error(f"Verification email failed for {user.email}: {e}") + + background.add_task(send_verify_email) + + return { + "access_token": "", # no token until verified + "token_type": "bearer", + "role": role_value, + "user_id": user.id, + "email_verification_required": not is_admin, + } + + + +@router.post("/login", response_model=TokenResponse) +@limiter.limit("5/minute") +def login(request: Request, payload: LoginRequest, db: Session = Depends(get_db)): + user = crud.get_user_by_email(db, payload.email) + + if not user or not crud.verify_password(payload.password, user.hashed_password): + logger.warning(f"Failed login attempt for email: {payload.email}") + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid credentials", + ) + + # Block unverified users + if not user.is_verified: + logger.warning(f"Login attempt by unverified user: {user.email}") + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="EMAIL_NOT_VERIFIED", + ) + + user_role = ( + user.role.value if hasattr(user.role, "value") else str(user.role) + ).lower() + + logger.info(f"User logged in: {user.email} with role {user_role}") + + crud.log_action(db, "login", user_id=user.id, ip_address=request.client.host if request.client else None) + + token = create_access_token(subject=user.email, role=user_role) + + return { + "access_token": token, + "token_type": "bearer", + "role": user_role, + "user_id": user.id, + } + + +@router.get("/verify-email") +def verify_email(token: str, db: Session = Depends(get_db)): + """Verify a user's email using the token sent during signup.""" + try: + decoded = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + email = decoded.get("sub") + token_type = decoded.get("type") + + if token_type != "email_verification": + raise HTTPException(status_code=400, detail="Invalid token") + + except JWTError: + raise HTTPException(status_code=400, detail="Invalid or expired verification link") + + user = crud.get_user_by_email(db, email) + if not user: + raise HTTPException(status_code=404, detail="User not found") + + if user.is_verified: + return {"message": "already_verified"} + + user.is_verified = 1 + db.commit() + logger.info(f"Email verified for user: {email}") + return {"message": "verified"} + + +@router.post("/resend-verification") +async def resend_verification( + payload: ResendVerificationRequest, + background: BackgroundTasks, + db: Session = Depends(get_db), +): + """Resend the email verification link.""" + user = crud.get_user_by_email(db, payload.email) + + if not user or user.is_verified: + return {"message": "If the email exists and is unverified, a new link has been sent"} + + verify_token = create_email_verification_token(user.email) + frontend_url = os.getenv("FRONTEND_URL", "https://bookkeepro.net") + verify_link = f"{frontend_url}/verify-email?token={verify_token}" + + async def send_resend_email(): + try: + await send_email( + to=user.email, + subject="Verify your BookKeepro email", + body=f""" + Hi {user.name},

+ Here is your new verification link:

+ + Verify My Email + +

+ This link expires in 24 hours.

+ BookKeepro Team + """ + ) + except Exception as e: + logger.error(f"Resend verification email failed for {user.email}: {e}") + + background.add_task(send_resend_email) + return {"message": "If the email exists and is unverified, a new link has been sent"} + + +@router.get("/me") +def me(current_user=Depends(get_current_user)): + role = ( + current_user.role.value + if hasattr(current_user.role, "value") + else str(current_user.role) + ) + return { + "id": current_user.id, + "name": current_user.name, + "email": current_user.email, + "phone": current_user.phone, + "role": role, + "engagement_acknowledged_at": ( + current_user.engagement_acknowledged_at.isoformat() + if current_user.engagement_acknowledged_at else None + ), + } + + +# ───────────────────────────────────────────── +# Engagement letter acknowledgement +# ───────────────────────────────────────────── + +@router.post("/acknowledge-engagement") +def acknowledge_engagement( + db: Session = Depends(get_db), + current_user=Depends(get_current_user), +): + """User confirms they have read the engagement letter. Idempotent.""" + if not current_user.engagement_acknowledged_at: + current_user.engagement_acknowledged_at = datetime.utcnow() + db.commit() + crud.log_action(db, "engagement_acknowledged", user_id=current_user.id) + return { + "acknowledged": True, + "acknowledged_at": current_user.engagement_acknowledged_at.isoformat(), + } + + +@router.patch("/me") +def update_me( + payload: dict, + request: Request, + db: Session = Depends(get_db), + current_user=Depends(get_current_user), +): + """Update own profile (name, phone, password). Any authenticated user.""" + name = payload.get("name", "").strip() + phone = payload.get("phone", "").strip() + current_pw = payload.get("current_password", "") + new_pw = payload.get("new_password", "") + + changed = [] + + if name and name != current_user.name: + current_user.name = name + changed.append("name") + + if phone != current_user.phone: + current_user.phone = phone + changed.append("phone") + + if new_pw: + if len(new_pw) < 8: + raise HTTPException(status_code=400, detail="New password must be at least 8 characters") + if not current_pw: + raise HTTPException(status_code=400, detail="Current password is required to set a new password") + if not crud.verify_password(current_pw, current_user.hashed_password): + raise HTTPException(status_code=400, detail="Current password is incorrect") + current_user.hashed_password = crud.hash_password(new_pw) + changed.append("password") + + if changed: + db.commit() + crud.log_action( + db, "profile_update", + user_id=current_user.id, + detail=", ".join(changed), + ip_address=request.client.host if request.client else None, + ) + + return { + "id": current_user.id, + "name": current_user.name, + "email": current_user.email, + "phone": current_user.phone, + "updated": changed, + } + + +# ========================= +# Admin Routes +# ========================= +@router.get("/admin/users") +def list_users_for_admin( + skip: int = Query(0, ge=0), + limit: int = Query(100, ge=1, le=500), + db: Session = Depends(get_db), + current_user=Depends(get_current_user), + _=Depends(require_admin), +): + """ + List users: + - super_admin → sees all users (user + admin + super_admin) + - admin → sees only role=user accounts + Supports skip/limit pagination. Returns pending_docs count per user. + """ + from sqlalchemy import func as sqlfunc + + def _pending_count(uid: int) -> int: + p = db.query(sqlfunc.count(PersonalDocument.id)).filter( + PersonalDocument.user_id == uid, + PersonalDocument.review_status == "pending", + PersonalDocument.deleted_at == None, + ).scalar() or 0 + b = db.query(sqlfunc.count(BusinessDocument.id)).filter( + BusinessDocument.user_id == uid, + BusinessDocument.review_status == "pending", + BusinessDocument.deleted_at == None, + ).scalar() or 0 + return p + b + + if current_user.role == UserRole.super_admin: + q = db.query(UserModel) + else: + q = db.query(UserModel).filter(UserModel.role == UserRole.user) + + total = q.count() + users = q.offset(skip).limit(limit).all() + + 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), + } + for u in users + ], + "total": total, + "skip": skip, + "limit": limit, + } + + +@router.get("/admin/audit-logs") +def get_audit_logs( + user_id: int | None = None, + limit: int = 50, + db: Session = Depends(get_db), + current_user=Depends(get_current_user), + _=Depends(require_admin), +): + from app.models import AuditLog + query = db.query(AuditLog).order_by(AuditLog.created_at.desc()) + if user_id: + query = query.filter(AuditLog.user_id == user_id) + logs = query.limit(min(limit, 200)).all() + return [ + { + "id": l.id, + "user_id": l.user_id, + "action": l.action, + "target": l.target, + "detail": l.detail, + "ip_address": l.ip_address, + "created_at": l.created_at.isoformat() if l.created_at else None, + } + for l in logs + ] + + +@router.get("/admin/users/{user_id}/documents") +def get_user_documents( + user_id: int, + current_user=Depends(get_current_user), + _=Depends(require_admin), +): + """ + Removed: this endpoint queried the legacy uploaded_files table which is empty. + All document data is now at GET /api/upload/admin/users/{user_id}/documents. + Returns 410 Gone so callers know to update their URLs. + """ + raise HTTPException( + status_code=410, + detail=f"This endpoint is removed. Use /api/upload/admin/users/{user_id}/documents instead.", + ) + + +# ───────────────────────────────────────────── +# Role management — super_admin only +# ───────────────────────────────────────────── + +@router.patch("/admin/users/{user_id}/role") +def change_user_role( + user_id: int, + payload: RoleChangeRequest, + request: Request, + db: Session = Depends(get_db), + current_user=Depends(get_current_user), + _=Depends(require_super_admin), +): + """ + Change a user's role. Super admin only. + + Rules: + - Cannot change your own role (prevents self-demotion) + - Cannot assign super_admin via API (super_admin is DB-only) + - Cannot demote the last remaining super_admin + """ + # Rule 1 — no self-modification + if user_id == current_user.id: + raise HTTPException( + status_code=400, + detail="You cannot change your own role" + ) + + target = crud.get_user_by_id(db, user_id) + if not target: + raise HTTPException(status_code=404, detail="User not found") + + old_role = target.role.value if hasattr(target.role, "value") else str(target.role) + new_role = payload.role # already validated as "user" or "admin" by schema + + # Rule 2 — no change if already same role + if old_role == new_role: + return { + "id": target.id, + "email": target.email, + "role": old_role, + "message": "Role unchanged (already set to this value)" + } + + # Rule 3 — cannot demote the last remaining super_admin + if old_role == "super_admin": + from app.models import User as UserModel + super_admin_count = ( + db.query(UserModel) + .filter(UserModel.role == UserRole.super_admin) + .count() + ) + if super_admin_count <= 1: + raise HTTPException( + status_code=400, + detail="Cannot demote the last super admin. Promote another user first." + ) + + # Apply the role change + target.role = UserRole(new_role) + db.commit() + + # Audit log with full context + crud.log_action( + db, + action="role_change", + user_id=current_user.id, + target=f"user:{user_id}", + detail=f"{target.email}: {old_role} → {new_role}", + ip_address=request.client.host if request.client else None, + ) + + logger.info( + f"Super admin {current_user.email} changed user {target.email} role: {old_role} → {new_role}" + ) + + return { + "id": target.id, + "email": target.email, + "old_role": old_role, + "new_role": new_role, + "message": f"Role updated from {old_role} to {new_role}" + } + + diff --git a/services/api/app/crud.py b/services/api/app/crud.py new file mode 100644 index 0000000..c0cad95 --- /dev/null +++ b/services/api/app/crud.py @@ -0,0 +1,92 @@ +from sqlalchemy.orm import Session +from passlib.context import CryptContext +from app.models import User, AuditLog + +# Single shared password hashing context +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") + + +# ───────────────────────────────────────────── +# User queries +# ───────────────────────────────────────────── + +def get_user_by_email(db: Session, email: str) -> User | None: + return db.query(User).filter(User.email == email).first() + + +def get_user_by_id(db: Session, user_id: int) -> User | None: + return db.query(User).filter(User.id == user_id).first() + + +def create_user( + db: Session, + name: str, + email: str, + phone: str, + password: str, + role: str = "user", + is_verified: int = 0, +) -> User: + user = User( + name=name, + email=email, + phone=phone, + hashed_password=pwd_context.hash(password), + role=role, + is_verified=is_verified, + ) + db.add(user) + db.commit() + db.refresh(user) + return user + + +def update_user_password(db: Session, user: User, hashed_password: str) -> None: + user.hashed_password = hashed_password + db.add(user) + db.commit() + db.refresh(user) + + +# ───────────────────────────────────────────── +# Password helpers +# ───────────────────────────────────────────── + +def verify_password(plain_password: str, hashed_password: str) -> bool: + return pwd_context.verify(plain_password, hashed_password) + + +def hash_password(plain_password: str) -> str: + return pwd_context.hash(plain_password) + + +def authenticate_user(db: Session, email: str, password: str) -> User | None: + user = get_user_by_email(db, email) + if not user: + return None + if not verify_password(password, user.hashed_password): + return None + return user + + +# ───────────────────────────────────────────── +# Audit logging +# ───────────────────────────────────────────── + +def log_action( + db: Session, + action: str, + user_id: int | None = None, + target: str | None = None, + detail: str | None = None, + ip_address: str | None = None, +) -> None: + entry = AuditLog( + user_id=user_id, + action=action, + target=target, + detail=detail, + ip_address=ip_address, + ) + db.add(entry) + db.commit() diff --git a/services/api/app/db.py b/services/api/app/db.py new file mode 100644 index 0000000..836d0e9 --- /dev/null +++ b/services/api/app/db.py @@ -0,0 +1,39 @@ +import os +from urllib.parse import quote_plus +from dotenv import load_dotenv +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker, declarative_base +from typing import Generator + +# load .env located at myapp/.env (three levels up from this file) +env_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", ".env")) +load_dotenv(env_path) + +DB_USER = os.getenv("MYSQL_USER", "root") +DB_PASS = os.getenv("MYSQL_PASSWORD", "") +DB_HOST = os.getenv("MYSQL_HOST", "localhost") +DB_PORT = os.getenv("MYSQL_PORT", "3306") +DB_NAME = os.getenv("MYSQL_DATABASE", "bookkeepprodb") + +# URL-encode password to handle special characters like @ +DB_PASS_ENCODED = quote_plus(DB_PASS) +DATABASE_URL = os.getenv("DATABASE_URL") or f"mysql+pymysql://{DB_USER}:{DB_PASS_ENCODED}@{DB_HOST}:{DB_PORT}/{DB_NAME}" + +# Engine and session — explicit pool config for production stability +engine = create_engine( + DATABASE_URL, + pool_pre_ping=True, # detect stale connections before use + pool_size=10, # persistent connections in pool + max_overflow=20, # extra connections allowed under peak load + pool_recycle=3600, # recycle connections after 1 hour (avoids MySQL wait_timeout drops) +) +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) + +Base = declarative_base() + +def get_db() -> Generator: + db = SessionLocal() + try: + yield db + finally: + db.close() diff --git a/services/api/app/limiter.py b/services/api/app/limiter.py new file mode 100644 index 0000000..43a2265 --- /dev/null +++ b/services/api/app/limiter.py @@ -0,0 +1,8 @@ +""" +Centralised rate-limiter instance. +Lives in its own module to avoid circular imports between main.py and security.py. +""" +from slowapi import Limiter +from slowapi.util import get_remote_address + +limiter = Limiter(key_func=get_remote_address) diff --git a/services/api/app/main.py b/services/api/app/main.py new file mode 100644 index 0000000..ceb75cc --- /dev/null +++ b/services/api/app/main.py @@ -0,0 +1,191 @@ +import os +import logging +from fastapi import FastAPI, HTTPException, Request +from fastapi.middleware.cors import CORSMiddleware +from fastapi.staticfiles import StaticFiles +from fastapi.responses import FileResponse +from slowapi import Limiter, _rate_limit_exceeded_handler +from slowapi.util import get_remote_address +from slowapi.errors import RateLimitExceeded +from app.limiter import limiter +from app import models +from app.db import engine + +log = logging.getLogger("uvicorn.error") + +app = FastAPI(title="BookKeepPro API") + +# Rate limiter — import from limiter.py to avoid circular imports +app.state.limiter = limiter +app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) + +# Create DB tables on startup (new tables only — does not alter existing) +models.Base.metadata.create_all(bind=engine) + +# ───────────────────────────────────────────── +# Routers — each isolated so one failure never kills the others +# ───────────────────────────────────────────── +try: + from app.routers import auth # type: ignore + app.include_router(auth.router) +except Exception as exc: + log.exception("Failed to load auth router: %s", exc) + +try: + from app.routers import upload # type: ignore + app.include_router(upload.router) +except Exception as exc: + log.exception("Failed to load upload router: %s", exc) + +try: + from app.routers import contact # type: ignore + app.include_router(contact.router) +except Exception as exc: + log.exception("Failed to load contact router: %s", exc) + +try: + from app.routers import review # type: ignore + app.include_router(review.router) +except Exception as exc: + log.exception("Failed to load review router: %s", exc) + +# ───────────────────────────────────────────── +# CORS +# ───────────────────────────────────────────── +_ALLOWED_ORIGINS = [ + o.strip() + for o in os.getenv( + "ALLOWED_ORIGINS", + "https://bookkeepro.net,http://localhost:8000", + ).split(",") + if o.strip() +] + +app.add_middleware( + CORSMiddleware, + allow_origins=_ALLOWED_ORIGINS, + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# ───────────────────────────────────────────── +# Static file mounts +# ───────────────────────────────────────────── +FRONTEND_DIR = os.path.abspath( + os.path.join(os.path.dirname(__file__), "..", "..", "..", "frontend") +) + + +def mount_if_exists(route: str, subdir: str, name: str): + path = os.path.join(FRONTEND_DIR, subdir) + if os.path.isdir(path): + app.mount(route, StaticFiles(directory=path), name=name) + log.info("Mounted static %s -> %s", route, path) + else: + 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") + +UPLOAD_DIR = os.path.abspath(os.path.join(FRONTEND_DIR, "..", "uploads")) +if not os.path.exists(UPLOAD_DIR): + os.makedirs(UPLOAD_DIR, exist_ok=True) + +log.info("FRONTEND_DIR resolved to: %s", FRONTEND_DIR) +log.info("CSS dir exists: %s", os.path.isdir(os.path.join(FRONTEND_DIR, "css"))) + + +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") + + +# ───────────────────────────────────────────── +# Ops endpoints +# ───────────────────────────────────────────── + +@app.get("/health", tags=["ops"]) +def health(): + """Health check for monitoring and load balancers.""" + return {"status": "ok"} + + +@app.post("/logout", tags=["auth"]) +def logout(): + # JWT is stateless — token is invalidated client-side by clearing localStorage + return {"message": "Logged out"} + + +# ───────────────────────────────────────────── +# Frontend page routes +# ───────────────────────────────────────────── + +@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") diff --git a/services/api/app/models.py b/services/api/app/models.py new file mode 100644 index 0000000..84163dd --- /dev/null +++ b/services/api/app/models.py @@ -0,0 +1,180 @@ +from sqlalchemy import ( + Boolean, + Column, + DateTime, + Enum, + ForeignKey, + Index, + Integer, + String, + UniqueConstraint, + func, +) +from sqlalchemy.orm import relationship +from app.db import Base +import enum + + +# ───────────────────────────────────────────── +# Enums +# ───────────────────────────────────────────── + +class UserRole(str, enum.Enum): + user = "user" + admin = "admin" + super_admin = "super_admin" + + +# ───────────────────────────────────────────── +# Users +# ───────────────────────────────────────────── + +class User(Base): + __tablename__ = "users" + + id = Column(Integer, primary_key=True, index=True) + name = Column(String(150), nullable=True) + email = Column(String(200), unique=True, index=True, nullable=False) + phone = Column(String(50), default="") + hashed_password = Column(String(300), nullable=False) + role = Column(Enum(UserRole), default=UserRole.user, nullable=False) + is_verified = Column(Integer, default=0, nullable=False) # 0 = unverified, 1 = verified + created_at = Column(DateTime(timezone=True), server_default=func.now()) + engagement_acknowledged_at = Column(DateTime(timezone=True), nullable=True, default=None) + + +# ───────────────────────────────────────────── +# Documents — user-uploaded +# ───────────────────────────────────────────── + +class PersonalDocument(Base): + __tablename__ = "personal_documents" + + id = Column(Integer, primary_key=True, index=True) + user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False) + doc_type = Column(String(200), nullable=False) + filename = Column(String(512), nullable=False) + storage_key = Column(String(500), nullable=False) + content_type = Column(String(100)) + uploaded_at = Column(DateTime(timezone=True), server_default=func.now()) + deleted_at = Column(DateTime(timezone=True), nullable=True, default=None) + review_status = Column(String(20), default="pending", nullable=False) + review_note = Column(String(500), nullable=True) + tax_year = Column(Integer, default=2025, nullable=False) + + user = relationship("User") + + __table_args__ = ( + Index("ix_personal_documents_user_id", "user_id"), + UniqueConstraint( + "user_id", "doc_type", "tax_year", + name="uq_personal_doc_user_type_year" + ), + ) + + +class BusinessDocument(Base): + __tablename__ = "business_documents" + + id = Column(Integer, primary_key=True, index=True) + user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False) + business_type = Column(String(200), nullable=False) + filename = Column(String(512), nullable=False) + storage_key = Column(String(500), nullable=False) + content_type = Column(String(100)) + uploaded_at = Column(DateTime(timezone=True), server_default=func.now()) + deleted_at = Column(DateTime(timezone=True), nullable=True, default=None) + review_status = Column(String(20), default="pending", nullable=False) + review_note = Column(String(500), nullable=True) + tax_year = Column(Integer, default=2025, nullable=False) + + user = relationship("User") + + __table_args__ = ( + Index("ix_business_documents_user_id", "user_id"), + UniqueConstraint( + "user_id", "business_type", "tax_year", + name="uq_business_doc_user_type_year" + ), + ) + + +# ───────────────────────────────────────────── +# Documents — admin-uploaded (tax returns for client review) +# ───────────────────────────────────────────── + +class AdminDocument(Base): + __tablename__ = "admin_documents" + + id = Column(Integer, primary_key=True, index=True) + doc_key = Column(String(100), nullable=False, index=True) # machine-readable slug + doc_label = Column(String(150), nullable=False) # display name + filename = Column(String(512), nullable=False) + storage_key = Column(String(500), nullable=False) # S3 object key + content_type = Column(String(100)) + uploaded_at = Column(DateTime(timezone=True), server_default=func.now()) + uploaded_by = Column(Integer, ForeignKey("users.id"), nullable=False) # admin user + user_id = Column(Integer, ForeignKey("users.id"), nullable=False) # target client + deleted_at = Column(DateTime(timezone=True), nullable=True, default=None) + + admin = relationship("User", foreign_keys=[uploaded_by]) + user = relationship("User", foreign_keys=[user_id]) + + __table_args__ = ( + Index("ix_admin_documents_user_id", "user_id"), + Index("ix_admin_documents_uploaded_by", "uploaded_by"), + ) + + +# ───────────────────────────────────────────── +# Legacy table — kept to avoid breaking existing DB +# Nothing writes here anymore; safe to drop after verifying +# uploaded_files has zero rows in production. +# ───────────────────────────────────────────── + +class UploadedFile(Base): + __tablename__ = "uploaded_files" + + id = Column(Integer, primary_key=True, index=True) + filename = Column(String(512), nullable=False) + drive_file_id = Column(String(200), nullable=False) # legacy column name + content_type = Column(String(100)) + doc_type = Column(String(150)) + uploaded_at = Column(DateTime(timezone=True), server_default=func.now()) + owner_id = Column(Integer, ForeignKey("users.id"), nullable=False) + + owner = relationship("User") + + +# ───────────────────────────────────────────── +# Audit Log +# ───────────────────────────────────────────── + +class AuditLog(Base): + __tablename__ = "audit_logs" + + id = Column(Integer, primary_key=True, index=True) + user_id = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True) + action = Column(String(100), nullable=False) # e.g. "upload", "delete", "login", "approve" + target = Column(String(200), nullable=True) # e.g. "personal_doc:42", "user:7" + detail = Column(String(500), nullable=True) # extra context + ip_address = Column(String(45), nullable=True) + created_at = Column(DateTime(timezone=True), server_default=func.now()) + + __table_args__ = ( + Index("ix_audit_logs_user_id", "user_id"), + Index("ix_audit_logs_created_at", "created_at"), + ) +class RequiredDocumentTemplate(Base): + __tablename__ = "required_document_templates" + + id = Column(Integer, primary_key=True, index=True) + category = Column(String(50), nullable=False) # 'personal' or 'business' + tax_year = Column(Integer, nullable=False) + name = Column(String(200), nullable=False) + file_url = Column(String(500), nullable=True) # Null if there is no template file to download + created_at = Column(DateTime(timezone=True), server_default=func.now()) + + __table_args__ = ( + UniqueConstraint("category", "tax_year", "name", name="uq_template_cat_year_name"), + ) diff --git a/services/api/app/routers/__init__.py b/services/api/app/routers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/services/api/app/routers/auth.py b/services/api/app/routers/auth.py new file mode 100644 index 0000000..f39eebc --- /dev/null +++ b/services/api/app/routers/auth.py @@ -0,0 +1,12 @@ +# This module re-exports everything from app.auth.security. +# All routes and auth dependencies live there. +from app.auth.security import ( + router, + get_current_user, + require_admin, + require_super_admin, + create_access_token, +) + +# Alias kept for any legacy internal references +get_current_user_real = get_current_user diff --git a/services/api/app/routers/contact.py b/services/api/app/routers/contact.py new file mode 100644 index 0000000..0de97a5 --- /dev/null +++ b/services/api/app/routers/contact.py @@ -0,0 +1,58 @@ +import os +from fastapi import APIRouter, BackgroundTasks, HTTPException, Request +from app.limiter import limiter +from pydantic import BaseModel, EmailStr +from app.utils.emailer import send_email + +router = APIRouter(prefix="/api", tags=["contact"]) + +# Get admin email from environment, with fallback +ADMIN_EMAIL = os.getenv("ADMIN_EMAIL", "admin@bookkeepro.net") + +class ContactForm(BaseModel): + first_name: str + last_name: str + email: EmailStr + phone: str + message: str = "" + +@router.post("/contact") +@limiter.limit("5/minute") +async def contact_message(request: Request, form: ContactForm, background: BackgroundTasks): + if not ADMIN_EMAIL or "@" not in ADMIN_EMAIL: + raise HTTPException(status_code=500, detail="Admin email not configured") + background.add_task( + send_email, + to=ADMIN_EMAIL, + subject="New Contact Enquiry Received — Follow-Up Required - BookKeepro", + body=f""" + Dear Team, +

+ A new contact enquiry has been received. Please find the details below: +

+ Name: {form.first_name} {form.last_name}
+ Email: {form.email}
+ Phone: {form.phone}
+ Message: {form.message or '(none)'}

+ Kindly follow up with the user at the earliest convenience. +

+ Thank you,
+ BookKeepro Support Team + """ + ) + + # auto-reply to user + background.add_task( + send_email, + to=form.email, + subject="Thanks for contacting BookKeepro", + body=f""" + Hi {form.first_name},

+ Thank you for reaching out to BookKeepro.
+ We’ve received your enquiry, and our team will get back to you shortly.

+ Best Regards,
+ BookKeepro Team + """ + ) + + return {"status": "sent"} diff --git a/services/api/app/routers/review.py b/services/api/app/routers/review.py new file mode 100644 index 0000000..4026495 --- /dev/null +++ b/services/api/app/routers/review.py @@ -0,0 +1,144 @@ +import logging +from fastapi import APIRouter, Depends, HTTPException +from sqlalchemy.orm import Session +from app.models import AdminDocument, User, UserRole +from app.db import get_db +from app.utils.emailer import send_email +from app import crud +from app.auth.security import get_current_user, require_admin +from app.schemas import SubmitReviewRequest, NotifyUserRequest, AdminDocResponseRequest + +logger = logging.getLogger(__name__) + +router = APIRouter(prefix="/api/review", tags=["review"]) + +DASHBOARD_LINK = "https://bookkeepro.net/dashboard" + + +# ───────────────────────────────────────────── +# Admin submits user documents for review +# ───────────────────────────────────────────── + +@router.post("/submit") +async def submit_review( + payload: SubmitReviewRequest, + db: Session = Depends(get_db), + current_user=Depends(get_current_user), + _=Depends(require_admin), +): + """Notify the user their documents have been submitted for review. Admin only.""" + user = crud.get_user_by_id(db, payload.user_id) + if not user: + raise HTTPException(status_code=404, detail="User not found") + + email_sent = await send_email( + to=user.email, + subject="Documents Ready for Review — BookKeepro", + body=f""" +

Dear {user.name or "Sir/Ma'am"},

+

Your documents have been successfully submitted and are pending review.

+

+ + 👉 Go to Dashboard + +

+

Kind regards,
BookKeepro Team

+ """ + ) + + logger.info(f"Admin {current_user.id} submitted review for user {payload.user_id}") + return {"status": "submitted", "email_sent": email_sent} + + +# ───────────────────────────────────────────── +# Admin sends approval / rejection notification +# ───────────────────────────────────────────── + +@router.post("/notify-user") +async def notify_user_review( + payload: NotifyUserRequest, + db: Session = Depends(get_db), + current_user=Depends(get_current_user), + _=Depends(require_admin), +): + """Send document review result (approved/rejected + timeline) to the user. Admin only.""" + user = crud.get_user_by_id(db, payload.user_id) + if not user: + raise HTTPException(status_code=404, detail="User not found") + + approved_html = "".join(f"
  • {item}
  • " for item in payload.approved) or "
  • None
  • " + rejected_html = "".join(f"
  • {item}
  • " for item in payload.rejected) or "
  • None
  • " + + body = f""" +

    Dear {user.name or "Sir/Ma'am"},

    +

    Your uploaded documents have been reviewed.

    + +

    Approved Documents

    + + +

    Rejected Documents

    + + +

    Estimated Filing Timeline:

    + + +

    Kind regards,
    BookKeepro Team

    + """ + + await send_email(to=user.email, subject="Document Review Update — BookKeepro", body=body) + logger.info(f"Admin {current_user.id} sent review notification to user {payload.user_id}") + return {"status": "notified"} + + +# ───────────────────────────────────────────── +# User responds to an admin-uploaded return +# ───────────────────────────────────────────── + +@router.post("/admin-doc-response") +async def admin_doc_response( + payload: AdminDocResponseRequest, + db: Session = Depends(get_db), + current_user=Depends(get_current_user), +): + """User approves or rejects an admin-uploaded document. Users only.""" + if current_user.role != UserRole.user: + raise HTTPException(status_code=403, detail="Users only") + + doc = db.query(AdminDocument).filter_by(id=payload.doc_id).first() + if not doc: + raise HTTPException(status_code=404, detail="Document not found") + + # Verify this doc belongs to the current user + if doc.user_id != current_user.id: + logger.warning( + f"User {current_user.id} tried to respond to doc {payload.doc_id} " + f"belonging to user {doc.user_id}" + ) + raise HTTPException(status_code=403, detail="Not authorized") + + admin = db.query(User).filter_by(id=doc.uploaded_by).first() + if not admin: + raise HTTPException(status_code=404, detail="Admin not found") + + body = f""" +

    Dear Admin,

    +

    User {current_user.email} has {payload.status.upper()} the document:

    +

    {doc.doc_label}

    + """ + if payload.status == "rejected" and payload.reason: + body += f"

    Reason:

    {payload.reason}

    " + + body += "

    BookKeepro System

    " + + await send_email( + to=admin.email, + subject=f"Admin Return Status {payload.status.capitalize()} — BookKeepro", + body=body, + ) + + logger.info(f"User {current_user.id} {payload.status} admin doc {payload.doc_id}") + return {"status": "notified"} diff --git a/services/api/app/routers/upload.py b/services/api/app/routers/upload.py new file mode 100644 index 0000000..fc3d82f --- /dev/null +++ b/services/api/app/routers/upload.py @@ -0,0 +1,910 @@ +import os +import io +import uuid +import logging +from datetime import datetime +import filetype +from fastapi import APIRouter, BackgroundTasks, UploadFile, File, HTTPException, Depends, Form, Query +from fastapi.responses import FileResponse +from sqlalchemy.orm import Session +from sqlalchemy.exc import IntegrityError +import boto3 +from botocore.client import Config +from botocore.exceptions import ClientError +from jose import jwt, JWTError +from datetime import timedelta + +from app.models import AdminDocument, PersonalDocument, BusinessDocument, User, UserRole +from app.db import get_db +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.schemas import UploadCompleteNotify, ReviewStatusUpdate + +logger = logging.getLogger(__name__) + +router = APIRouter(prefix="/api/upload", tags=["upload"]) + +from pathlib import Path + +# ───────────────────────────────────────────── +# Local File Storage (Contabo VPS Disk) +# ───────────────────────────────────────────── + +BASE_DIR = Path(__file__).resolve().parents[4] +UPLOAD_DIR = BASE_DIR / "uploads" +UPLOAD_DIR.mkdir(parents=True, exist_ok=True) + +async def upload_to_storage(file: UploadFile) -> str: + """Upload to local disk. Returns the filename (storage_key).""" + await file.seek(0) + contents = await file.read() + + # File size validation + MAX_SIZE = 10 * 1024 * 1024 # 10 MB + if len(contents) > MAX_SIZE: + raise HTTPException(status_code=413, detail="File too large. Maximum size is 10MB.") + + # Content type validation + ALLOWED_TYPES = { + "application/pdf", + "image/jpeg", + "image/png", + "image/webp", + "application/msword", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + } + + kind = filetype.guess(contents) + sniffed_mime = kind.mime if kind else None + + ext = os.path.splitext(file.filename or "file")[1].lower() + + # Fallback for legacy .doc and inconsistent .docx sniffing + if sniffed_mime is None or sniffed_mime == "application/zip": + if ext in [".doc", ".docx"] 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." + ) + + ext = os.path.splitext(file.filename or "file")[1].lower() + object_key = f"{uuid.uuid4().hex}{ext}" + file_path = UPLOAD_DIR / object_key + + try: + with open(file_path, "wb") as f: + f.write(contents) + logger.info(f"Uploaded {object_key} locally") + return object_key + except Exception as e: + logger.error(f"Local upload failed: {e}") + raise HTTPException(status_code=500, detail="File upload failed") + +def delete_from_storage(storage_key: str): + """Delete from local disk.""" + try: + if storage_key.startswith("uploads/"): + storage_key = storage_key.split("uploads/")[1] + file_path = UPLOAD_DIR / storage_key + if file_path.exists(): + file_path.unlink() + logger.info(f"Deleted {storage_key} locally") + except Exception as e: + logger.warning(f"Storage delete failed for {storage_key}: {e}") + +def get_presigned_url(storage_key: str) -> str: + """Return an authenticated URL containing a short-lived JWT for viewing the file.""" + if storage_key.startswith("uploads/"): + storage_key = storage_key.split("uploads/")[1] + + expire = datetime.utcnow() + timedelta(minutes=5) + payload = { + "sub": storage_key, + "type": "file_access", + "exp": expire, + } + token = jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM) + return f"/api/upload/file/{storage_key}?token={token}" + +@router.get("/file/{storage_key}") +def stream_file(storage_key: str, token: str = Query(...)): + """Stream file securely using short-lived JWT token.""" + try: + payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + token_key = payload.get("sub") + if token_key != storage_key or payload.get("type") != "file_access": + raise HTTPException(status_code=403, detail="Token mismatch or invalid type") + except JWTError: + raise HTTPException(status_code=401, detail="Invalid or expired token") + + file_path = (UPLOAD_DIR / storage_key).resolve() + + # Path traversal protection + if not str(file_path).startswith(str(UPLOAD_DIR.resolve()) + os.sep): + raise HTTPException(status_code=400, detail="Invalid file key") + + if not file_path.exists(): + raise HTTPException(status_code=404, detail="File not found") + + return FileResponse(file_path) + + +# ───────────────────────────────────────────── +# Presigned URL — frontend "View" button +# ───────────────────────────────────────────── + +@router.get("/view-url") +def get_view_url( + key: str, + current_user=Depends(get_current_user), + db: Session = Depends(get_db), +): + """Return a presigned URL. Verifies the requesting user owns the document.""" + if not key: + raise HTTPException(status_code=400, detail="key is required") + + # Existence check — ensure the document actually exists in the DB first + doc = ( + db.query(PersonalDocument).filter(PersonalDocument.storage_key == key).first() or + db.query(BusinessDocument).filter(BusinessDocument.storage_key == key).first() or + db.query(AdminDocument).filter(AdminDocument.storage_key == key).first() + ) + + if not doc: + raise HTTPException(status_code=404, detail="Document not found") + + # Ownership check — ensure this key belongs to the requesting user or user is admin + if current_user.role not in [UserRole.admin, UserRole.super_admin] and doc.user_id != current_user.id: + logger.warning( + f"User {current_user.id} attempted to access storage key {key} — not owned" + ) + raise HTTPException(status_code=403, detail="Access denied") + + url = get_presigned_url(key) + if not url: + raise HTTPException(status_code=500, detail="Could not generate view URL") + return {"url": url} + + +# ───────────────────────────────────────────── +# Admin Documents +# ───────────────────────────────────────────── + +@router.post("/admin-documents") +async def upload_admin_document( + file: UploadFile = File(...), + doc_key: str = Form(...), + doc_label: str = Form(...), + user_id: int = Form(...), + background: BackgroundTasks = BackgroundTasks(), + db: Session = Depends(get_db), + current_user=Depends(get_current_user), + _=Depends(require_admin), +): + target_user = crud.get_user_by_id(db, user_id) + if not target_user: + raise HTTPException(status_code=404, detail="Target user not found") + + # Regular admins can only upload documents for user-role accounts + if current_user.role == UserRole.admin and target_user.role != UserRole.user: + raise HTTPException( + status_code=403, + detail="Admins can only upload documents for regular user accounts" + ) + + logger.info(f"Admin {current_user.id} uploading document for user {user_id}") + storage_key = await upload_to_storage(file) + + record = AdminDocument( + doc_key=doc_key, + doc_label=doc_label, + filename=file.filename, + storage_key=storage_key, + content_type=file.content_type, + uploaded_by=current_user.id, + user_id=user_id, + ) + db.add(record) + db.commit() + db.refresh(record) + + crud.log_action(db, "upload_admin_doc", user_id=current_user.id, target=f"admin_doc:{record.id}", detail=f"for user {user_id}") + + background.add_task( + send_email, + to=target_user.email, + subject="New Document Uploaded — BookKeepro", + body=f""" +

    Dear {target_user.name or "Sir/Ma'am"},

    +

    An admin has securely uploaded a new document ({doc_label}) to your account.

    +

    You can view this document by logging into your BookKeepro portal.

    +
    BookKeepro Team + """, + ) + + return { + "id": record.id, + "doc_label": record.doc_label, + "filename": record.filename, + "storage_key": record.storage_key, + } + + +@router.get("/admin-documents") +def list_admin_documents( + user_id: int | None = None, + db: Session = Depends(get_db), + current_user=Depends(get_current_user), +): + if current_user.role in [UserRole.admin, UserRole.super_admin]: + if not user_id: + raise HTTPException(status_code=400, detail="user_id is required for admin") + docs = ( + db.query(AdminDocument) + .filter(AdminDocument.user_id == user_id, AdminDocument.deleted_at == None) + .order_by(AdminDocument.uploaded_at.desc()) + .all() + ) + elif current_user.role == UserRole.user: + docs = ( + db.query(AdminDocument) + .filter(AdminDocument.user_id == current_user.id, AdminDocument.deleted_at == None) + .order_by(AdminDocument.uploaded_at.desc()) + .all() + ) + else: + raise HTTPException(status_code=403, detail="Unauthorized") + + return [ + { + "id": d.id, + "doc_key": d.doc_key, + "doc_label": d.doc_label, + "filename": d.filename, + "storage_key": d.storage_key, + } + for d in docs + ] + + +@router.delete("/admin-documents/{doc_id}") +def delete_admin_document( + doc_id: int, + db: Session = Depends(get_db), + current_user=Depends(get_current_user), + _=Depends(require_admin), +): + doc = db.query(AdminDocument).filter_by(id=doc_id).first() + if not doc: + raise HTTPException(status_code=404, detail="Document not found") + + target_user = db.query(User).filter(User.id == doc.user_id).first() + if not target_user: + raise HTTPException(status_code=404, detail="Target user not found") + + # Scope restriction: standard admins can only delete documents for base users + if current_user.role == UserRole.admin and target_user.role != UserRole.user: + raise HTTPException( + status_code=403, + detail="Standard admins can only manage documents for standard users" + ) + + logger.info(f"Admin {current_user.id} deleting admin document {doc_id}") + delete_from_storage(doc.storage_key) + doc.deleted_at = datetime.utcnow() + db.commit() + crud.log_action(db, "delete_admin_doc", user_id=current_user.id, target=f"admin_doc:{doc_id}") + return {"deleted": True} + + +# ───────────────────────────────────────────── +# Personal Documents +# ───────────────────────────────────────────── + +@router.get("/personal-documents") +def list_personal_documents( + tax_year: int | None = None, + skip: int = Query(0, ge=0), + limit: int = Query(200, ge=1, le=500), + db: Session = Depends(get_db), + current_user=Depends(get_current_user), +): + q = db.query(PersonalDocument).filter( + PersonalDocument.user_id == current_user.id, + PersonalDocument.deleted_at == None, + ) + if tax_year: + q = q.filter(PersonalDocument.tax_year == tax_year) + docs = q.order_by(PersonalDocument.uploaded_at.desc()).offset(skip).limit(limit).all() + return [ + { + "id": d.id, + "doc_type": d.doc_type, + "filename": d.filename, + "storage_key": d.storage_key, + "uploaded_at": d.uploaded_at, + "tax_year": d.tax_year, + "review_status": d.review_status, + "review_note": d.review_note, + } + for d in docs + ] + + +@router.post("/personal-documents") +async def upload_personal_document( + background: BackgroundTasks, + file: UploadFile = File(...), + doc_type: str = Form(...), + tax_year: int = Form(2025), + db: Session = Depends(get_db), + current_user=Depends(get_current_user), +): + logger.info(f"User {current_user.id} uploading personal document: {file.filename}") + storage_key = await upload_to_storage(file) + + record = PersonalDocument( + user_id=current_user.id, + doc_type=doc_type, + filename=file.filename, + storage_key=storage_key, + content_type=file.content_type, + tax_year=tax_year, + ) + db.add(record) + try: + db.commit() + except IntegrityError: + db.rollback() + # Clean up the already-uploaded S3 object + delete_from_storage(storage_key) + raise HTTPException( + status_code=409, + detail="You have already uploaded this document for this tax year. " + "Delete the existing one to replace it." + ) + db.refresh(record) + crud.log_action(db, "upload_personal", user_id=current_user.id, target=f"personal_doc:{record.id}", detail=file.filename) + + admins = db.query(User).filter(User.role.in_([UserRole.admin, UserRole.super_admin])).all() + for admin in admins: + background.add_task( + send_email, + to=admin.email, + subject="New Personal Document Uploaded — BookKeepro", + body=f"

    {current_user.email} uploaded a personal document: {file.filename} ({doc_type}).

    ", + ) + + return { + "id": record.id, + "filename": record.filename, + "doc_type": record.doc_type, + "storage_key": record.storage_key, + "uploaded_at": record.uploaded_at, + "tax_year": record.tax_year, + } + + +@router.delete("/personal-documents/{doc_id}") +def delete_personal_document( + doc_id: int, + db: Session = Depends(get_db), + current_user=Depends(get_current_user), +): + doc = ( + db.query(PersonalDocument) + .filter( + PersonalDocument.id == doc_id, + PersonalDocument.user_id == current_user.id, + ) + .first() + ) + 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) + doc.deleted_at = datetime.utcnow() + db.commit() + crud.log_action(db, "delete_personal", user_id=current_user.id, target=f"personal_doc:{doc_id}") + return {"deleted": True} + + +# ───────────────────────────────────────────── +# Business Documents +# ───────────────────────────────────────────── + +@router.get("/business-documents") +def list_business_documents( + tax_year: int | None = None, + skip: int = Query(0, ge=0), + limit: int = Query(200, ge=1, le=500), + db: Session = Depends(get_db), + current_user=Depends(get_current_user), +): + q = db.query(BusinessDocument).filter( + BusinessDocument.user_id == current_user.id, + BusinessDocument.deleted_at == None, + ) + if tax_year: + q = q.filter(BusinessDocument.tax_year == tax_year) + docs = q.order_by(BusinessDocument.uploaded_at.desc()).offset(skip).limit(limit).all() + return [ + { + "id": d.id, + "business_type": d.business_type, + "filename": d.filename, + "storage_key": d.storage_key, + "uploaded_at": d.uploaded_at, + "tax_year": d.tax_year, + "review_status": d.review_status, + "review_note": d.review_note, + } + for d in docs + ] + + +@router.post("/business-documents") +async def upload_business_document( + background: BackgroundTasks, + file: UploadFile = File(...), + doc_type: str = Form(...), + tax_year: int = Form(2025), + db: Session = Depends(get_db), + current_user=Depends(get_current_user), +): + logger.info(f"User {current_user.id} uploading business document: {file.filename}") + storage_key = await upload_to_storage(file) + + record = BusinessDocument( + user_id=current_user.id, + business_type=doc_type, + filename=file.filename, + storage_key=storage_key, + content_type=file.content_type, + tax_year=tax_year, + ) + db.add(record) + try: + db.commit() + except IntegrityError: + db.rollback() + delete_from_storage(storage_key) + raise HTTPException( + status_code=409, + detail="You have already uploaded this document for this tax year. " + "Delete the existing one to replace it." + ) + db.refresh(record) + crud.log_action(db, "upload_business", user_id=current_user.id, target=f"business_doc:{record.id}", detail=file.filename) + + admins = db.query(User).filter(User.role.in_([UserRole.admin, UserRole.super_admin])).all() + for admin in admins: + background.add_task( + send_email, + to=admin.email, + subject="New Business Document Uploaded — BookKeepro", + body=f"

    {current_user.email} uploaded a business document: {file.filename} ({doc_type}).

    ", + ) + + return { + "id": record.id, + "filename": record.filename, + "business_type": record.business_type, + "storage_key": record.storage_key, + "tax_year": record.tax_year, + } + + +@router.delete("/business-documents/{doc_id}") +def delete_business_document( + doc_id: int, + db: Session = Depends(get_db), + current_user=Depends(get_current_user), +): + doc = db.query(BusinessDocument).filter_by(id=doc_id).first() + if not doc: + raise HTTPException(status_code=404, detail="Document not found") + 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) + doc.deleted_at = datetime.utcnow() + db.commit() + crud.log_action(db, "delete_business", user_id=current_user.id, target=f"business_doc:{doc_id}") + return {"deleted": True} + + +# ───────────────────────────────────────────── +# Review status — admin persists approve/reject decisions +# ───────────────────────────────────────────── + +@router.patch("/personal-documents/{doc_id}/review-status") +def set_personal_review_status( + doc_id: int, + payload: ReviewStatusUpdate, + db: Session = Depends(get_db), + current_user=Depends(get_current_user), + _=Depends(require_admin), +): + """Admin sets approve/reject/pending on a personal document.""" + doc = db.query(PersonalDocument).filter_by(id=doc_id).first() + if not doc: + raise HTTPException(status_code=404, detail="Document not found") + + doc.review_status = payload.status + doc.review_note = payload.note + db.commit() + + crud.log_action( + db, f"review_{payload.status}", + user_id=current_user.id, + target=f"personal_doc:{doc_id}", + detail=f"owner:{doc.user_id}" + (f" note:{payload.note}" if payload.note else ""), + ) + return {"id": doc_id, "review_status": payload.status} + + +@router.patch("/business-documents/{doc_id}/review-status") +def set_business_review_status( + doc_id: int, + payload: ReviewStatusUpdate, + db: Session = Depends(get_db), + current_user=Depends(get_current_user), + _=Depends(require_admin), +): + """Admin sets approve/reject/pending on a business document.""" + doc = db.query(BusinessDocument).filter_by(id=doc_id).first() + if not doc: + raise HTTPException(status_code=404, detail="Document not found") + + doc.review_status = payload.status + doc.review_note = payload.note + db.commit() + + crud.log_action( + db, f"review_{payload.status}", + user_id=current_user.id, + target=f"business_doc:{doc_id}", + detail=f"owner:{doc.user_id}" + (f" note:{payload.note}" if payload.note else ""), + ) + return {"id": doc_id, "review_status": payload.status} + + +# ───────────────────────────────────────────── +# Admin — all documents for one user +# ───────────────────────────────────────────── + +@router.get("/admin/users/{user_id}/documents") +def get_user_all_documents( + user_id: int, + tax_year: int | None = None, + db: Session = Depends(get_db), + current_user=Depends(get_current_user), + _=Depends(require_admin), +): + user = db.query(User).filter(User.id == user_id).first() + if not user: + raise HTTPException(status_code=404, detail="User not found") + + # Regular admins can only view documents for user-role accounts + if current_user.role == UserRole.admin and user.role != UserRole.user: + raise HTTPException( + status_code=403, + detail="Admins can only view documents for regular user accounts" + ) + + logger.info(f"Admin {current_user.id} retrieving all documents for user {user_id}") + + pq = db.query(PersonalDocument).filter( + PersonalDocument.user_id == user_id, PersonalDocument.deleted_at == None + ) + bq = db.query(BusinessDocument).filter( + BusinessDocument.user_id == user_id, BusinessDocument.deleted_at == None + ) + if tax_year: + pq = pq.filter(PersonalDocument.tax_year == tax_year) + bq = bq.filter(BusinessDocument.tax_year == tax_year) + + personal_docs = pq.order_by(PersonalDocument.uploaded_at.desc()).all() + business_docs = bq.order_by(BusinessDocument.uploaded_at.desc()).all() + + documents = [ + { + "id": d.id, + "table": "personal", + "doc_type": d.doc_type, + "filename": d.filename, + "storage_key": d.storage_key, + "uploaded_at": d.uploaded_at.isoformat() if d.uploaded_at else None, + "tax_year": d.tax_year, + "review_status": d.review_status, + "review_note": d.review_note, + } + for d in personal_docs + ] + [ + { + "id": d.id, + "table": "business", + "doc_type": d.business_type, + "filename": d.filename, + "storage_key": d.storage_key, + "uploaded_at": d.uploaded_at.isoformat() if d.uploaded_at else None, + "tax_year": d.tax_year, + "review_status": d.review_status, + "review_note": d.review_note, + } + for d in business_docs + ] + + return { + "user": { + "id": user.id, + "name": user.name, + "email": user.email, + "role": user.role.value if hasattr(user.role, "value") else str(user.role), + "engagement_acknowledged_at": ( + user.engagement_acknowledged_at.isoformat() + if user.engagement_acknowledged_at else None + ), + }, + "documents": documents, + } + + +# ───────────────────────────────────────────── +# Admin — delete a user and all documents +# ───────────────────────────────────────────── + +@router.delete("/admin/users/{user_id}") +def delete_user_completely( + user_id: int, + db: Session = Depends(get_db), + current_user=Depends(get_current_user), + _=Depends(require_admin), +): + if user_id == current_user.id: + raise HTTPException(status_code=400, detail="Cannot delete your own account") + + user = db.query(User).filter(User.id == user_id).first() + if not user: + raise HTTPException(status_code=404, detail="User not found") + + # Regular admins can only delete user-role accounts + # Super_admin can delete admin or user accounts (but not other super_admins) + if current_user.role == UserRole.admin and user.role != UserRole.user: + raise HTTPException( + status_code=403, + detail="Admins can only delete regular user accounts" + ) + if current_user.role == UserRole.super_admin and user.role == UserRole.super_admin: + raise HTTPException( + status_code=403, + detail="Super admin accounts cannot be deleted through the dashboard" + ) + + logger.info(f"Admin {current_user.id} deleting user {user_id}") + + try: + for doc in db.query(AdminDocument).filter(AdminDocument.user_id == user_id).all(): + delete_from_storage(doc.storage_key) + db.delete(doc) + + for doc in db.query(AdminDocument).filter(AdminDocument.uploaded_by == user_id).all(): + delete_from_storage(doc.storage_key) + db.delete(doc) + + for doc in db.query(PersonalDocument).filter(PersonalDocument.user_id == user_id).all(): + delete_from_storage(doc.storage_key) + db.delete(doc) + + for doc in db.query(BusinessDocument).filter(BusinessDocument.user_id == user_id).all(): + delete_from_storage(doc.storage_key) + db.delete(doc) + + # Clean up legacy uploaded_files rows and audit logs to avoid FK constraint errors on db.delete(user) + from app.models import UploadedFile, AuditLog + db.query(UploadedFile).filter(UploadedFile.owner_id == user_id).delete() + db.query(AuditLog).filter(AuditLog.user_id == user_id).delete() + + db.commit() + crud.log_action(db, "delete_user", user_id=current_user.id, target=f"user:{user_id}") + db.delete(user) + db.commit() + except Exception as e: + db.rollback() + logger.error(f"User deletion failed for {user_id}: {e}") + raise HTTPException(status_code=500, detail="Deletion failed. No changes were made.") + + return {"deleted": True, "user_id": user_id} + + +# ───────────────────────────────────────────── +# Batch upload notification — call once after all files uploaded (#11) +# ───────────────────────────────────────────── + +@router.post("/notify-upload-complete") +async def notify_upload_complete( + payload: UploadCompleteNotify, + background: BackgroundTasks, + db: Session = Depends(get_db), + current_user=Depends(get_current_user), +): + """ + Send one summary email after a user finishes uploading all documents. + Call this once from the frontend after the upload session is complete. + Replaces the old per-file email approach. + """ + admin_email = os.getenv("ADMIN_EMAIL") + count = payload.file_count + category = payload.doc_category + + background.add_task( + send_email, + to=current_user.email, + subject=f"{category} Documents Uploaded — BookKeepro", + body=f""" +

    Dear {current_user.name or "Sir/Ma'am"},

    +

    We received {count} {category.lower()} + document{"s" if count != 1 else ""} from you.

    +

    Our team will review {"them" if count != 1 else "it"} and update you shortly.

    +
    BookKeepro Team + """, + ) + admins = db.query(User).filter(User.role.in_([UserRole.admin, UserRole.super_admin])).all() + for admin in admins: + background.add_task( + send_email, + to=admin.email, + subject=f"New {category} Upload — BookKeepro", + body=f"

    {current_user.email} uploaded " + f"{count} {category.lower()} document{'s' if count != 1 else ''}.

    ", + ) + return {"status": "notified"} + + +from pydantic import BaseModel + +class NotifyApprovalRequest(BaseModel): + user_id: int + +@router.post("/notify/personal") +async def notify_personal_approval( + payload: NotifyApprovalRequest, + background: BackgroundTasks, + db: Session = Depends(get_db), + _=Depends(require_admin), +): + user = db.query(User).filter(User.id == payload.user_id).first() + if not user: + raise HTTPException(status_code=404, detail="User not found") + + background.add_task( + send_email, + to=user.email, + subject="Personal Documents Approved — BookKeepro", + body=f""" +

    Dear {user.name or "Sir/Ma'am"},

    +

    Your personal documents have been successfully reviewed and approved.

    +
    BookKeepro Team + """, + ) + return {"status": "email_sent"} + +@router.post("/notify/business") +async def notify_business_approval( + payload: NotifyApprovalRequest, + background: BackgroundTasks, + db: Session = Depends(get_db), + _=Depends(require_admin), +): + user = db.query(User).filter(User.id == payload.user_id).first() + if not user: + raise HTTPException(status_code=404, detail="User not found") + + background.add_task( + send_email, + to=user.email, + subject="Business Documents Approved — BookKeepro", + body=f""" +

    Dear {user.name or "Sir/Ma'am"},

    +

    Your business documents have been successfully reviewed and approved.

    +
    BookKeepro Team + """, + ) + return {"status": "email_sent"} + +# ───────────────────────────────────────────── +# Required Document Templates +# ───────────────────────────────────────────── + +from app.models import RequiredDocumentTemplate + +@router.get("/templates") +def list_templates( + category: str, + tax_year: int, + db: Session = Depends(get_db), + current_user=Depends(get_current_user), +): + templates = ( + db.query(RequiredDocumentTemplate) + .filter_by(category=category, tax_year=tax_year) + .order_by(RequiredDocumentTemplate.id.asc()) + .all() + ) + return [ + { + "id": t.id, + "name": t.name, + "download": t.file_url, + } + for t in templates + ] + +@router.post("/admin/templates") +async def upload_template( + file: UploadFile = File(None), + category: str = Form(...), + tax_year: int = Form(...), + name: str = Form(...), + db: Session = Depends(get_db), + current_user=Depends(get_current_user), + _=Depends(require_admin), +): + # Only super admin can manage templates + if current_user.role != UserRole.super_admin: + raise HTTPException(status_code=403, detail="Only super admins can manage templates") + + file_url = None + if file and file.filename: + storage_key = await upload_to_storage(file) + file_url = get_presigned_url(storage_key) + + record = RequiredDocumentTemplate( + category=category, + tax_year=tax_year, + name=name, + file_url=file_url, + ) + + try: + db.add(record) + db.commit() + db.refresh(record) + except IntegrityError: + db.rollback() + raise HTTPException(status_code=400, detail="A template with this name already exists for the given year.") + + return { + "id": record.id, + "name": record.name, + "download": record.file_url, + } + +@router.delete("/admin/templates/{template_id}") +def delete_template( + template_id: int, + db: Session = Depends(get_db), + current_user=Depends(get_current_user), + _=Depends(require_admin), +): + if current_user.role != UserRole.super_admin: + raise HTTPException(status_code=403, detail="Only super admins can manage templates") + + record = db.query(RequiredDocumentTemplate).filter_by(id=template_id).first() + if not record: + raise HTTPException(status_code=404, detail="Template not found") + + if record.file_url and record.file_url.startswith("/uploads/"): + storage_key = record.file_url.split("/uploads/")[1] + delete_from_storage(storage_key) + + db.delete(record) + db.commit() + return {"deleted": True} diff --git a/services/api/app/schemas.py b/services/api/app/schemas.py new file mode 100644 index 0000000..ed25adf --- /dev/null +++ b/services/api/app/schemas.py @@ -0,0 +1,202 @@ +from pydantic import BaseModel, EmailStr, field_validator +from typing import Optional, List +from datetime import datetime + + +# ───────────────────────────────────────────── +# Auth +# ───────────────────────────────────────────── + +class SignupRequest(BaseModel): + name: str + email: EmailStr # validates format, not just a plain str + phone: Optional[str] = None + password: str + + @field_validator("password") + @classmethod + def password_min_length(cls, v: str) -> str: + if len(v) < 8: + raise ValueError("Password must be at least 8 characters") + return v + + @field_validator("name") + @classmethod + def name_not_empty(cls, v: str) -> str: + if not v.strip(): + raise ValueError("Name cannot be blank") + return v.strip() + + +class LoginRequest(BaseModel): + email: EmailStr + password: str + + +class TokenResponse(BaseModel): + access_token: str + token_type: str + role: Optional[str] = None + user_id: Optional[int] = None + email_verification_required: Optional[bool] = None + + +class ForgotPasswordRequest(BaseModel): + email: EmailStr + + +class ResendVerificationRequest(BaseModel): + """Dedicated schema so resend-verification isn't sharing ForgotPasswordRequest.""" + email: EmailStr + + +class ResetPasswordRequest(BaseModel): + token: str + new_password: str + + @field_validator("new_password") + @classmethod + def password_min_length(cls, v: str) -> str: + if len(v) < 8: + raise ValueError("Password must be at least 8 characters") + return v + + +class RoleChangeRequest(BaseModel): + """Body for PATCH /api/auth/admin/users/{id}/role — super_admin only.""" + role: str + + @field_validator("role") + @classmethod + def role_must_be_valid(cls, v: str) -> str: + allowed = {"user", "admin"} # super_admin is DB-only, never assignable via API + if v.lower() not in allowed: + raise ValueError(f"Role must be one of: {', '.join(sorted(allowed))}") + return v.lower() + + +# ───────────────────────────────────────────── +# Review schemas +# ───────────────────────────────────────────── + +class SubmitReviewRequest(BaseModel): + user_id: int + + +class NotifyUserRequest(BaseModel): + user_id: int + type: str = "personal" + approved: List[str] = [] + rejected: List[str] = [] + personal_timeline: int = 0 + business_timeline: int = 0 + + @field_validator("approved", "rejected") + @classmethod + def cap_list_length(cls, v: List[str]) -> List[str]: + if len(v) > 100: + raise ValueError("List may not contain more than 100 items") + return v + + @field_validator("type") + @classmethod + def valid_type(cls, v: str) -> str: + if v not in ("personal", "business"): + raise ValueError("type must be 'personal' or 'business'") + return v + + +class AdminDocResponseRequest(BaseModel): + doc_id: int + status: str + reason: str = "" + + @field_validator("status") + @classmethod + def valid_status(cls, v: str) -> str: + if v not in ("approved", "rejected"): + raise ValueError("status must be 'approved' or 'rejected'") + return v + + @field_validator("reason") + @classmethod + def cap_reason(cls, v: str) -> str: + if len(v) > 1000: + raise ValueError("Reason must be 1000 characters or fewer") + return v + + +class ReviewStatusUpdate(BaseModel): + """Body for PATCH /api/upload/{personal,business}-documents/{id}/review-status""" + status: str + note: str = "" + + @field_validator("status") + @classmethod + def valid_status(cls, v: str) -> str: + if v not in ("approved", "rejected", "pending"): + raise ValueError("status must be 'approved', 'rejected', or 'pending'") + return v + + @field_validator("note") + @classmethod + def cap_note(cls, v: str) -> str: + if len(v) > 500: + raise ValueError("Note must be 500 characters or fewer") + return v + + + + +class PersonalDocumentOut(BaseModel): + id: int + doc_type: str + filename: str + storage_key: str + uploaded_at: Optional[datetime] = None + + model_config = {"from_attributes": True} + + +class BusinessDocumentOut(BaseModel): + id: int + business_type: str + filename: str + storage_key: str + uploaded_at: Optional[datetime] = None + + model_config = {"from_attributes": True} + + +class AdminDocumentOut(BaseModel): + id: int + doc_key: str + doc_label: str + filename: str + storage_key: str + uploaded_at: Optional[datetime] = None + + model_config = {"from_attributes": True} + + +# ───────────────────────────────────────────── +# Upload notification schema +# ───────────────────────────────────────────── + +class UploadCompleteNotify(BaseModel): + doc_category: str # "Personal" | "Business" + file_count: int + + @field_validator("doc_category") + @classmethod + def valid_category(cls, v: str) -> str: + if v not in ("Personal", "Business"): + raise ValueError("doc_category must be 'Personal' or 'Business'") + return v + + @field_validator("file_count") + @classmethod + def positive_count(cls, v: int) -> int: + if v < 1: + raise ValueError("file_count must be at least 1") + return v diff --git a/services/api/app/utils/emailer.py b/services/api/app/utils/emailer.py new file mode 100644 index 0000000..a3b3521 --- /dev/null +++ b/services/api/app/utils/emailer.py @@ -0,0 +1,85 @@ +import os +import logging +from pathlib import Path +from dotenv import load_dotenv + +logger = logging.getLogger(__name__) + +# Load .env from project root +BASE_DIR = Path(__file__).resolve().parents[3] +load_dotenv(BASE_DIR / ".env") + + +def _build_mail_client(): + """Build FastMail client lazily so a bad SMTP config never crashes the app on startup.""" + try: + from fastapi_mail import FastMail, ConnectionConfig + + smtp_user = os.getenv("SMTP_USER") + smtp_password = os.getenv("SMTP_PASSWORD") + mail_from = os.getenv("MAIL_FROM") + smtp_host = os.getenv("SMTP_HOST") + + # Refuse to build a broken config — missing critical values + if not all([smtp_user, smtp_password, mail_from, smtp_host]): + logger.warning( + "Email not configured: one or more SMTP env vars are missing. " + "Set SMTP_USER, SMTP_PASSWORD, MAIL_FROM, SMTP_HOST in .env" + ) + return None + + # Guard against placeholder value + if "PASTE" in (smtp_password or "").upper(): + logger.warning( + "SMTP_PASSWORD looks like a placeholder. " + "Set a real Gmail App Password in .env" + ) + return None + + conf = ConnectionConfig( + MAIL_USERNAME=smtp_user, + MAIL_PASSWORD=smtp_password, + MAIL_FROM=mail_from, + MAIL_PORT=int(os.getenv("SMTP_PORT", "587")), + MAIL_SERVER=smtp_host, + MAIL_STARTTLS=os.getenv("SMTP_TLS", "True").strip().lower() == "true", + MAIL_SSL_TLS=os.getenv("MAIL_SSL_TLS", "False").strip().lower() == "true", + MAIL_FROM_NAME=os.getenv("MAIL_FROM_NAME", "BookKeepro"), + ) + return FastMail(conf) + + except Exception as e: + logger.error(f"Failed to initialise email client: {e}") + return None + + +async def send_email(to: str, subject: str, body: str) -> bool: + """ + Send an HTML email. Returns True on success, False on any failure. + Errors are logged but never crash the caller. + """ + try: + if not to or "@" not in to: + logger.warning(f"Invalid recipient email: {to}") + return False + + fm = _build_mail_client() + if fm is None: + logger.warning(f"Email skipped (client not configured) — would have sent to {to}: {subject}") + return False + + from fastapi_mail import MessageSchema + message = MessageSchema( + subject=subject, + recipients=[to], + body=body, + subtype="html", + ) + + await fm.send_message(message) + logger.info(f"Email sent to {to}: {subject}") + return True + + except Exception as e: + logger.error(f"Failed to send email to {to}: {e}") + return False diff --git a/services/api/app/utils/login_email.py b/services/api/app/utils/login_email.py new file mode 100644 index 0000000..510d912 --- /dev/null +++ b/services/api/app/utils/login_email.py @@ -0,0 +1,91 @@ +from app.utils.emailer import send_email + + +# async def send_login_welcome_email(to: str, name: str | None = None): +# display_name = name or "Valued Customer" + +# body = f""" +#

    Dear {display_name},

    + +#

    +# Welcome to BookKeepro +#

    + +#

    +# You have successfully logged in to your account. +# We’re excited to support you with your compliance and bookkeeping needs. +#

    + +#

    +# You can access your dashboard anytime using the link below: +#

    + +#

    +# +# 👉 Go to Dashboard +# +#

    + +#

    +# If this login was not initiated by you, please contact our support team immediately. +#

    + +#

    +# Kind regards,
    +# BookKeepro Team +#

    +# """ + +# await send_email( +# to=to, +# subject="Welcome to BookKeepro", +# body=body +# ) + + + + +# app/utils/emailer.py + +async def send_signup_welcome_email(to: str, name: str | None = None): + display_name = name or "Valued Customer" + + body = f""" +

    Dear {display_name},

    + +

    + Welcome to BookKeepro 🎉 +

    + +

    + Your account has been successfully created. + We’re excited to support you with your compliance and bookkeeping needs. +

    + +

    + You can log in to your dashboard using the link below: +

    + +

    + + 👉 Login to BookKeepro + +

    + +

    + If you did not create this account, please contact our support team immediately. +

    + +

    + Kind regards,
    + BookKeepro Team +

    + """ + + await send_email( + to=to, + subject="Welcome to BookKeepro 🎉", + body=body + ) diff --git a/services/api/migrations/v003_p3_p4_changes.sql b/services/api/migrations/v003_p3_p4_changes.sql new file mode 100644 index 0000000..d6af18d --- /dev/null +++ b/services/api/migrations/v003_p3_p4_changes.sql @@ -0,0 +1,26 @@ +-- ============================================================ +-- Migration v003 — P3/P4 changes +-- Compatible with MySQL 5.7+ / 8.0 (no IF NOT EXISTS syntax) +-- Run each block separately if re-running after a partial apply. +-- ============================================================ + +-- #16 — Engagement letter acknowledgement timestamp +-- Safe to re-run: ADD COLUMN fails silently if column already exists +-- (just ignore "Duplicate column name" error on re-run) +ALTER TABLE users + ADD COLUMN engagement_acknowledged_at DATETIME NULL DEFAULT NULL; + +-- #10 — Prevent duplicate document uploads (same user / type / year) +-- Drop first in case of partial previous run, then re-add. +-- Ignore "Can't DROP ... check that it exists" errors on first run. +ALTER TABLE personal_documents + DROP INDEX uq_personal_doc_user_type_year; + +ALTER TABLE personal_documents + ADD UNIQUE INDEX uq_personal_doc_user_type_year (user_id, doc_type, tax_year); + +ALTER TABLE business_documents + DROP INDEX uq_business_doc_user_type_year; + +ALTER TABLE business_documents + ADD UNIQUE INDEX uq_business_doc_user_type_year (user_id, business_type, tax_year); diff --git a/services/api/migrations/v004_required_document_templates.sql b/services/api/migrations/v004_required_document_templates.sql new file mode 100644 index 0000000..91c3a01 --- /dev/null +++ b/services/api/migrations/v004_required_document_templates.sql @@ -0,0 +1,41 @@ +CREATE TABLE required_document_templates ( + id INTEGER PRIMARY KEY AUTO_INCREMENT, + category VARCHAR(50) NOT NULL, + tax_year INTEGER NOT NULL, + name VARCHAR(200) NOT NULL, + file_url VARCHAR(500), + created_at DATETIME DEFAULT CURRENT_TIMESTAMP +); + +CREATE UNIQUE INDEX uq_template_cat_year_name ON required_document_templates (category, tax_year, name); + +-- Seed with initial hardcoded data +INSERT INTO required_document_templates (category, tax_year, name, file_url) VALUES +('personal', 2026, 'Individual taxpayer organizer sole proprietorship rental 2026', '/images/individual_taxpayer_organizer_sole_proprietorship_rental_2025-doc-1.pdf'), +('personal', 2025, 'Individual taxpayer organizer sole proprietorship rental 2025', '/images/individual_taxpayer_organizer_sole_proprietorship_rental_2025-doc-1.pdf'), +('personal', 2024, 'Individual taxpayer organizer 2024', '/images/individual_taxpayer_organizer_2024.pdf'), +('personal', 2023, 'Individual taxpayer organizer 2023', NULL), +('business', 2026, 's_corporation organizer 2026', '/images/s_corporation_organizer_2025-business-doc-1.pdf'), +('business', 2026, 'llc tax organizer 2026', '/images/llc_tax_organizer_2025-personal-doc-2.pdf'), +('business', 2026, 'Partnership tax organizer 2026', '/images/partnership_tax_organizer_2025-persoal-doc-3.pdf'), +('business', 2026, 'Certificate of Formation', NULL), +('business', 2026, 'Employer Identification Number (EIN)', NULL), +('business', 2026, 'Annual Financial Statements', NULL), +('business', 2025, 's_corporation organizer 2025', '/images/s_corporation_organizer_2025-business-doc-1.pdf'), +('business', 2025, 'llc tax organizer 2025', '/images/llc_tax_organizer_2025-personal-doc-2.pdf'), +('business', 2025, 'Partnership tax organizer 2025', '/images/partnership_tax_organizer_2025-persoal-doc-3.pdf'), +('business', 2025, 'Certificate of Formation', NULL), +('business', 2025, 'Employer Identification Number (EIN)', NULL), +('business', 2025, 'Annual Financial Statements', NULL), +('business', 2024, 'S Corporation organizer 2024', NULL), +('business', 2024, 'LLC tax organizer 2024', NULL), +('business', 2024, 'Partnership tax organizer 2024', NULL), +('business', 2024, 'Certificate of Formation', NULL), +('business', 2024, 'Employer Identification Number (EIN)', NULL), +('business', 2024, 'Annual Financial Statements', NULL), +('business', 2023, 'S Corporation organizer 2023', NULL), +('business', 2023, 'LLC tax organizer 2023', NULL), +('business', 2023, 'Partnership tax organizer 2023', NULL), +('business', 2023, 'Certificate of Formation', NULL), +('business', 2023, 'Employer Identification Number (EIN)', NULL), +('business', 2023, 'Annual Financial Statements', NULL); diff --git a/services/api/requirements.txt b/services/api/requirements.txt new file mode 100644 index 0000000..6bb9172 Binary files /dev/null and b/services/api/requirements.txt differ