A modern full-stack financial tracking application that combines automated email processing with manual expense management. Built with FastAPI backend and React frontend, featuring Gmail integration for automatic transaction processing, intelligent document parsing, and a credit-based subscription system.
app/
βββ main.py # FastAPI application entry point with lifespan management
βββ db_config.py # Database configuration and session management
βββ alembic.ini # Alembic configuration for database migrations
β
βββ controller/ # Request handling and business logic coordination
β βββ controller.py # Main controller with endpoint logic
β
βββ middleware/ # Custom middleware for request processing
β βββ auth_middleware.py # JWT authentication middleware
β βββ request_id_middleware.py # Request ID tracking for logging
β
βββ models/ # SQLAlchemy database models
β βββ models.py # Complete database schema definitions
β βββ User, UserToken # User management and authentication
β βββ Source, Email # Email processing and source tracking
β βββ Attachment # File storage and metadata
β βββ ProcessedEmailData, ProcessedItem # Extracted financial data
β βββ Expense # Manual expense management
β βββ Plan, Feature, Subscription # Subscription and billing
β βββ Integration* # Integration framework tables
β βββ CreditHistory # Credit usage tracking
β
βββ routes/ # API endpoint definitions
β βββ routes.py # All REST API routes and FastAPI router
β
βββ services/ # Business logic and external integrations
β βββ subscription_service.py # Credit management and billing logic
β βββ gmail_service.py # Gmail API integration and email processing
β βββ user_service.py # User management and profile operations
β βββ db_service.py # Database operations and queries
β βββ integration_service.py # Integration framework management
β βββ email_attachment_service.py # Email attachment processing
β βββ llm_service.py # AI/LLM document processing
β βββ s3_service.py # AWS S3 file storage operations
β βββ file_service.py # File handling and processing
β βββ jwt_service.py # JWT token management
β βββ token_service.py # OAuth token operations
β βββ cron_service.py # Scheduled background jobs
β βββ Every24HoursCronJob # Gmail sync automation
β βββ Every1HourTokenRefreshCronJob # Token refresh
β βββ IsEmailProcessedCheckCRON # Email processing check
β
βββ utils/ # Utility functions and helpers
β βββ exception_handlers.py # Centralized error handling
β βββ exceptions.py # Custom exception definitions
β βββ oauth_utils.py # OAuth flow utilities
β βββ utils.py # General utility functions
β
βββ migrations/ # Database migration files (Alembic)
βββ env.py # Alembic environment configuration
βββ script.py.mako # Migration template
βββ versions/ # Individual migration files
Root Level Files:
βββ docker-compose.yml # Multi-container Docker setup
βββ Dockerfile # Backend container definition
βββ nginx.conf # Nginx reverse proxy configuration
βββ credentials.json # Google OAuth credentials
βββ requirements.txt # Python dependencies
- FastAPI application initialization with lifespan management
- CORS middleware configuration
- APScheduler setup for background jobs
- Centralized exception handler registration
- Health check endpoints
- Request/response handling and validation
- Business logic coordination between services
- Input sanitization and output formatting
- Error handling and HTTP status management
-
Core Services:
subscription_service.py: Credit-based billing, plan management, feature validationgmail_service.py: Gmail API integration, email fetching, OAuth handlinguser_service.py: User profile management, authentication logicdb_service.py: Database operations, query optimization, transaction management
-
Integration Services:
integration_service.py: Multi-provider integration frameworkemail_attachment_service.py: Email attachment processing and extractionllm_service.py: AI-powered document analysis and data extractions3_service.py: AWS S3 file storage and retrieval
-
Utility Services:
jwt_service.py: JWT token creation and validationtoken_service.py: OAuth token refresh and managementfile_service.py: File processing and metadata extractioncron_service.py: Scheduled job definitions and execution
- SQLAlchemy ORM models with relationships
- Enum definitions for status and types
- Database indexes and constraints
- Mixins for common functionality (timestamps, soft delete)
- RESTful API endpoint definitions
- Request/response models with Pydantic
- Authentication and authorization decorators
- API documentation with FastAPI automatic schema generation
- JWT authentication validation
- Request ID generation for tracing
- Cross-cutting concerns like logging and monitoring
- Custom exception classes and handlers
- OAuth flow utilities
- Common helper functions
- Configuration management
HTTP Request
β
Middleware (Auth, Request ID)
β
Routes (FastAPI Router)
β
Controller (Request Validation)
β
Services (Business Logic)
β
Models (Database Operations)
β
Response (JSON/HTTP)
APScheduler
βββ Gmail Sync Job (Every 6 Hours)
β βββ Credit Validation β Gmail Service
β βββ Email Fetching β Attachment Service
β βββ Data Processing β LLM Service
β
βββ Token Refresh (Every 1 Hour)
β βββ OAuth Token Management
β
βββ Email Processing (Every 6 Hours)
βββ Unprocessed Email Detection
βββ AI Document Analysis
βββ Structured Data Extraction
- Expense Management: Create, read, update, and delete personal expenses
- Gmail Integration: Automatic processing of financial emails (invoices, bills, receipts)
- Document Processing: AI-powered extraction of financial data from PDF attachments
- Import System: Review and import automatically processed transactions
- User Dashboard: Analytics and insights with expense categorization
- Real-time Sync: Scheduled background jobs for email synchronization
- Credit-Based Billing: Subscription plans with credit allocation for feature usage
- Multi-Integration Support: Extensible integration framework for Gmail, WhatsApp, and more
- Flexible Plans: Trial, active, and custom subscription plans with credit allocation
- Feature-Based Billing: Different features consume different amounts of credits
- Credit Tracking: Real-time credit balance monitoring and usage history
- Auto Credit Validation: Automatic credit validation before feature execution
- Subscription Management: Trial periods, renewals, and plan upgrades
- JWT Authentication: Secure user authentication with Google OAuth2
- RESTful API: Well-structured API endpoints with proper validation
- Database Management: PostgreSQL with Alembic migrations
- File Storage: AWS S3 integration for document storage
- Background Tasks: APScheduler for automated email processing and token refresh
- Credit Management: Comprehensive subscription and billing system
- Integration Framework: Modular integration system with status tracking
- Responsive UI: Modern React frontend with TypeScript
- State Management: Redux Toolkit for client-side state
- Docker Support: Containerized deployment
- FastAPI - High-performance Python web framework
- PostgreSQL - Primary database
- SQLAlchemy - ORM and database toolkit
- Alembic - Database migration tool
- APScheduler - Background job scheduling
- JWT - Authentication tokens
- Google APIs - Gmail integration and OAuth
- AWS S3 - File storage
- LLM Integration - Document processing and data extraction
- React 18 - UI framework
- TypeScript - Type safety
- Vite - Build tool and dev server
- Redux Toolkit - State management
- React Query - Server state management
- React Router - Client-side routing
- Tailwind CSS - Styling framework
- Shadcn/ui - UI component library
- Recharts - Data visualization
- Python 3.11+
- Node.js 18+
- PostgreSQL 13+
- Docker & Docker Compose (optional)
- AWS Account (for S3 storage)
- Google Cloud Project (for Gmail API)
-
Clone the repository
git clone <repository-url> cd finTrack-public
-
Backend Setup
# Install Python dependencies pip install -r requirements.txt # Set up environment variables cp .env.example .env # Edit .env with your configuration
-
Frontend Setup
cd frontend npm install -
Google API Configuration
- Create a project in Google Cloud Console
- Enable Gmail API and Google+ API
- Create OAuth2 credentials
- Download
credentials.jsonto project root
docker-compose up db -d# Create PostgreSQL database
createdb fintrack
# Run migrations
cd app
alembic upgrade head# Terminal 1: Start backend
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
# Terminal 2: Start frontend
cd frontend
npm run devdocker-compose up -dThe application will be available at:
- Frontend: http://localhost:8080
- Backend API: http://localhost:8000
- API Documentation: http://localhost:8000/docs
GET /api/login- Initiate Google OAuth flowGET /api/emails/oauth2callback- OAuth callback handler
GET /api/user- Get user profileGET /api/user/settings- Get user integration settingsGET /api/user/subscription- Get user subscription details and credit balance
POST /api/subscription/create- Create starter subscription for new usersGET /api/subscription/features- Get available features and credit costsGET /api/subscription/usage- Get credit usage history and statisticsPOST /api/subscription/validate- Validate credits for specific feature usage
POST /api/expense- Create new expenseGET /api/expense- List user expenses (paginated)GET /api/expense/{id}- Get specific expensePUT /api/expense/{id}- Update expenseDELETE /api/expense/{id}- Delete expense
POST /api/emails- Trigger email processing (consumes credits)GET /api/payment/info- Get processed email data (importable transactions)
GET /api/integrations- List available integrationsPOST /api/integrations/{type}/connect- Connect new integrationGET /api/integrations/status- Get user's integration statusPUT /api/integrations/{id}/sync- Trigger manual sync
GET /api/attachment/view- Get signed URL for PDF viewingPOST /api/upload-pdf- Upload PDF to S3
GET /- API statusGET /health- Health check with scheduler status and active jobs
- users - User profiles and authentication
- expenses - Manual expense entries
- sources - Source tracking for data lineage
- emails - Processed Gmail messages
- processed_email_data - Extracted financial data from emails
- processed_items - Individual line items from invoices
- attachments - File metadata and S3 references
- plans - Available subscription plans with credit allocation
- features - System features with credit costs
- plan_features - Junction table for plan-feature relationships
- subscriptions - User subscriptions with credit tracking
- credit_history - Transaction log for credit usage
- integrations - Master table for available integrations
- integration_status - User-specific integration status and sync tracking
- integration_features - Junction table for integration-feature relationships
- email_config - Gmail integration configuration
- whatsapp_config - WhatsApp integration configuration (future)
- user_tokens - OAuth tokens for various providers
Navigate to the /app directory:
# Create new migration
alembic revision --autogenerate -m "migration description"
# Apply migrations
alembic upgrade head
# Check migration status
alembic currentCreate a .env file in the project root:
# Database
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/fintrack
# JWT
JWT_SECRET=your-secret-key
JWT_ALGORITHM=HS256
JWT_EXPIRY_MINUTES=60
# Google OAuth
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
# AWS S3
AWS_ACCESS_KEY_ID=your-aws-access-key
AWS_SECRET_ACCESS_KEY=your-aws-secret-key
S3_BUCKET_NAME=your-s3-bucket
AWS_REGION=us-east-1
# LLM Service (if using OpenAI for document processing)
OPENAI_API_KEY=your-openai-api-keyThe application runs scheduled cron jobs using APScheduler:
- Purpose: Fetches new emails from connected Gmail accounts
- Credit Validation: Validates user credits before processing
- Features:
- Credit-based processing (1 credit per Gmail sync operation)
- Automatic email content extraction
- PDF attachment processing
- Batch processing for multiple users
- Error handling and logging
- Purpose: Refreshes expired OAuth tokens
- Features:
- Automatic token renewal for Google OAuth
- Prevents integration disconnection
- Handles token expiration gracefully
- Purpose: Processes unprocessed emails and extracts financial data
- Features:
- LLM-powered document analysis
- Attachment text extraction
- Structured data extraction for invoices and bills
- Item-level detail extraction
The application uses a credit-based system where different features consume different amounts of credits:
- Gmail Sync: 1 credit per sync operation
- Email Processing: 1 credit per email processed
- PDF Extraction: 2 credits per PDF processed
- LLM Processing: 3 credits per AI analysis
- Starter Plan: 100 credits, 30-day trial
- Custom Plans: Configurable credit allocation and pricing
- Auto-renewal: Configurable subscription renewal
- Real-time credit balance tracking
- Usage history and analytics
- Credit validation before feature execution
- Automatic credit deduction after successful operations
- Gmail: Full email sync and processing with OAuth2
- WhatsApp (Coming Soon): Message and media processing
- Google Drive (Planned): Document sync and processing
- Status Tracking: Real-time integration health monitoring
- Sync Management: Configurable sync intervals and scheduling
- Error Handling: Comprehensive error logging and recovery
- Configuration Management: Per-integration settings and credentials
# Build and run all services
docker-compose up -d
# View logs
docker-compose logs -f
# Stop services
docker-compose down- Set up proper SSL certificates
- Configure environment-specific variables
- Set up monitoring and logging
- Configure backup strategies for PostgreSQL
- Set up CDN for static assets
- Monitor credit usage and subscription renewals
- Set up alerts for integration failures
- Connects to Gmail via OAuth2
- Filters emails for financial keywords
- Downloads and processes PDF attachments
- Extracts structured data using LLM services
- Stores processed data for user review
- Credit-based processing with validation
- Trial subscriptions for new users
- Credit allocation and tracking
- Feature-based billing
- Usage analytics and reporting
- Flexible plan configuration
- Modular integration framework
- Status monitoring and health checks
- Configurable sync schedules
- Error handling and recovery
- Multi-provider support
- PDF text extraction with credit tracking
- LLM-powered financial data extraction
- Support for invoices, bills, receipts, and tax documents
- Item-level detail extraction for invoices
- Structured data output with validation
This project is licensed under the MIT License - see the LICENSE file for details.