Vance Finance Wiki

Complete documentation and developer guide

v2.2.1

Project Overview

Vance Finance is a comprehensive personal finance management web application designed to help users track their income, bills, credit cards, loans, subscriptions, and budgets with advanced analytics and insights.

Key Objectives
  • Simplify comprehensive personal finance management
  • Provide clear financial insights and analytics
  • Support multiple income frequencies and expense types
  • Enable flexible budgeting with goal tracking
  • Ensure data security and comprehensive backup capabilities
  • Offer an intuitive, responsive user interface
  • Provide interactive demo mode for testing and showcasing
Technology Stack
Backend
  • Python 3.7+
  • Flask 3.0+ with Flask-WTF for CSRF protection
  • SQLAlchemy ORM with migrations
  • Werkzeug for security and utilities
  • Gunicorn for production deployment
Frontend
  • HTML5/CSS3 with modern features
  • Bootstrap 5 with custom themes
  • JavaScript (ES6+) with dynamic interactions
  • Bootstrap Icons comprehensive icon set
  • Responsive design for all devices
Recent Updates (v1.1.5)
Latest Features
  • Budget Management System: Complete budgeting with categories, periods, transactions, and goals
  • Enhanced Income Tracking: Support for 7 different income frequencies including one-time income
  • Advanced Credit Card Management: Automatic minimum payment calculations and payment calculators
  • Comprehensive Backup System: Automatic backups, JSON exports, and data recovery
  • Demo Mode: Interactive demo with realistic sample data
  • CSRF Protection: Enhanced security for all forms
  • Financial Analytics: Debt-to-income ratios, utilization tracking, and projections

Complete Feature Set

Income Management
  • 7 Payment Frequencies: Weekly, bi-weekly, monthly, bi-monthly, quarterly, annually, one-time
  • Flexible Scheduling: Custom payment days, day-of-week selection
  • Future Projections: 90-day income forecasting
  • Monthly Estimations: Automatic conversion to monthly equivalents
  • Active/Inactive Status: Temporarily disable income sources
  • Income Timeline: Visual timeline of upcoming payments
Bill & Expense Management
  • Recurring Bills: Monthly, bi-monthly tracking
  • One-time Bills: Special event or irregular expenses
  • Categories: Utilities, Housing, Insurance, Medical, Transportation, Other
  • Due Date Tracking: Urgent bill alerts (7-day window)
  • Payment Status: Mark bills as paid/unpaid
  • Include/Exclude: Control which bills affect calculations
Credit Card Management
  • Comprehensive Tracking: Limits, balances, utilization, interest rates
  • Automatic Minimum Payments: Smart calculation with multiple methods
  • Annual Fee Tracking: Monthly or yearly fee calculations
  • Auto-Pay Configuration: Minimum payment or fixed amount options
  • Payment Calculator: Advanced payment strategy calculator
  • Utilization Monitoring: Per-card and overall utilization tracking
  • Payment Strategies: Debt avalanche, snowball, utilization-first options
Subscription Tracking
  • Multiple Billing Cycles: Weekly, monthly, quarterly, yearly
  • Category Organization: Entertainment, Software, News, Music, Gaming, etc.
  • Auto-Renewal Tracking: Monitor which subscriptions auto-renew
  • Active/Inactive Status: Pause tracking without deletion
  • Next Billing Alerts: Upcoming subscription renewals
  • Cost Analysis: Monthly equivalent calculations
Loan Management
  • Multiple Loan Types: Personal, Auto, Mortgage, Student, Business
  • Progress Tracking: Visual progress bars showing payoff status
  • Payment Scheduling: Next payment date tracking
  • Interest Rate Monitoring: Track and compare rates
  • Principal vs Balance: Track original amount vs current balance
  • Term Tracking: Monitor loan terms in months
Budget Management (NEW)
  • Budget Categories: Income and expense categorization with colors and icons
  • Budget Periods: Monthly, quarterly, yearly, or custom periods
  • Budget Items: Planned vs actual amount tracking
  • Transaction Recording: Manual transaction entry with categories
  • Budget Goals: Savings goals with progress tracking
  • Auto-Contributions: Automatic monthly goal contributions
  • Budget Analytics: Performance insights and recommendations
Financial Analytics
  • Debt-to-Income Ratio: Real-time financial health monitoring
  • Credit Utilization Analysis: Individual and overall utilization tracking
  • Cash Flow Projections: 90-day financial timeline
  • Savings Rate Calculation: Monthly savings as percentage of income
  • Payment Strategy Analysis: Compare different debt payoff strategies
  • Budget Performance: Category-wise budget vs actual analysis
Data Management & Security
Backup & Recovery
  • Automatic Backups: Before all data modifications
  • Manual Backups: On-demand database snapshots
  • JSON Export/Import: Portable data format
  • Backup Management: View, download, delete backup files
  • Data Recovery: Multiple restoration options
Security Features
  • CSRF Protection: Cross-site request forgery prevention
  • Password Hashing: Werkzeug PBKDF2 with salt
  • Session Security: Secure session management
  • User Data Isolation: Complete data separation by user
  • Input Validation: Server-side form validation
Demo & User Experience
Interactive Demo
  • Realistic Sample Data: Complete financial scenario
  • Full Functionality: All features available in demo
  • Demo Reset: Restore original demo data
  • Demo Mode Indicators: Clear demo mode identification
User Interface
  • Responsive Design: Mobile-first responsive layout
  • Bootstrap 5: Modern component library
  • Custom Themes: Tailored styling for financial data
  • Interactive Elements: Dynamic forms and calculators

Application Components

Vance Finance is built with a modular component architecture where each financial entity operates independently while contributing to comprehensive financial insights.

Core Components Overview
User Management
Authentication, authorization, data isolation
Financial Entities
Income, bills, cards, loans, subscriptions
Analytics Engine
Calculations, projections, insights
1. User Management Component
Purpose

Handles user authentication, session management, and data isolation. Ensures each user can only access their own financial data.

Key Features:
  • Secure Registration: Username, email, and password with hashing
  • Session Management: Flask session-based authentication
  • Data Isolation: All database queries filtered by user_id
  • Demo Mode: Special demo user with sample data
Database Schema:
User Model:
- id: Primary key
- username: Unique identifier
- email: Contact information
- password_hash: Secure password storage
- Relationships: One-to-many with all financial entities
Component Interactions:
  • Authentication Guard: Protects all financial routes
  • Data Filter: Automatically filters all queries by user
  • Session Context: Provides user context to all components

2. Income Management Component
Purpose

Tracks multiple income sources with flexible payment frequencies and provides monthly income calculations for financial health analysis.

Income Frequencies Supported:
  • Weekly: Every 7 days on specified day of week
  • Bi-weekly: Every 14 days from start date
  • Monthly: Specific day each month
  • Bi-monthly: Two specific days each month
  • Quarterly: Every 3 months
  • Annually: Once per year
  • One-time: Single payment on specific date
Calculation Engine:
Monthly Income Calculation:
- Weekly: amount × 52 ÷ 12
- Bi-weekly: amount × 26 ÷ 12  
- Monthly: amount × 1
- Bi-monthly: amount × 2
- Quarterly: amount ÷ 3
- Annually: amount ÷ 12
- One-time: Excluded from monthly calculations
Component Interactions:
  • Dashboard Integration: Shows next 5 income payments
  • Analytics Feed: Provides monthly income for debt-to-income calculations
  • Timeline Generation: Contributes to 90-day financial projections
  • Budget Integration: Feeds budget planning with income estimates

3. Bill Management Component
Purpose

Manages recurring and one-time bills with due date tracking, categories, and payment status. Provides expense calculations for financial analysis.

Bill Categories:
  • Utilities: Electric, water, gas, internet
  • Housing: Rent, mortgage, HOA fees
  • Insurance: Health, auto, home, life
  • Medical: Healthcare expenses
  • Transportation: Car payments, transit
  • Other: Miscellaneous expenses
Key Features:
  • Due Date Tracking: Automatic urgent bill detection (7-day window)
  • Recurring Flag: Distinguishes monthly recurring vs one-time bills
  • Payment Status: Mark bills as paid/unpaid
  • Include/Exclude Toggle: Control impact on financial calculations
  • Category Organization: Group bills by expense type
Component Interactions:
  • Dashboard Alerts: Urgent bills prominently displayed
  • Expense Calculations: Feeds monthly expense totals
  • Overview Timeline: Shows future bill dates in projections
  • Budget Integration: Bill amounts can feed budget categories

4. Credit Card Management Component
Purpose

Comprehensive credit card tracking with automatic minimum payment calculations, utilization monitoring, and payment strategy optimization.

Advanced Features:
  • Automatic Minimum Payments: Multiple calculation methods with smart defaults
  • Annual Fee Handling: Monthly or yearly fee calculations
  • Auto-Pay Configuration: Minimum payment or fixed amount options
  • Payment Calculator: Advanced debt payoff strategy calculator
  • Utilization Tracking: Per-card and overall utilization monitoring
Minimum Payment Calculation:
Calculation Methods:
1. Standard: 2% of current balance
2. Interest + Principal: Monthly interest + 1% principal
3. Minimum Floor: $25 absolute minimum
4. Annual Fee Addition: Monthly fees added if applicable
5. Balance Cap: Never exceeds current balance + fees

Final Amount: MAX(method1, method2, $25) + monthly_fees
Payment Strategies:
  • High Utilization First: Reduce cards with highest utilization
  • High Interest First (Avalanche): Pay highest interest rate cards
  • High Balance First: Focus on largest balances
  • Low Balance First (Snowball): Pay smallest balances first
  • Even Distribution: Spread payments equally
  • Minimums First: Ensure all minimums are covered
Component Interactions:
  • Dashboard Summary: Total utilization and upcoming payments
  • Debt Calculations: Minimum payments feed into monthly expenses
  • Financial Health: Utilization affects credit score estimates
  • Payment Planning: Integrated with overall debt strategy

5. Subscription Management Component
Purpose

Tracks recurring subscription services with multiple billing cycles, categories, and auto-renewal status. Helps identify subscription spending patterns.

Billing Cycle Support:
  • Weekly: 52 payments per year
  • Monthly: 12 payments per year
  • Quarterly: 4 payments per year
  • Yearly: 1 payment per year
Category Organization:
  • Entertainment: Netflix, Hulu, Spotify
  • Software: Adobe, Microsoft Office
  • News: Newspapers, magazines
  • Gaming: Game subscriptions
  • Productivity: Business tools
  • Other: Miscellaneous services
Component Interactions:
  • Expense Calculations: Monthly equivalent amounts feed total expenses
  • Bills Integration: Can be managed alongside bills
  • Timeline Projections: Shows upcoming renewal dates
  • Spending Analysis: Category-wise subscription spending

6. Loan Management Component
Purpose

Tracks various loan types with progress monitoring, payment scheduling, and payoff visualization. Supports multiple loan categories and terms.

Loan Types Supported:
  • Personal Loans: Unsecured personal debt
  • Auto Loans: Vehicle financing
  • Mortgages: Home financing
  • Student Loans: Education financing
  • Business Loans: Commercial financing
Progress Tracking:
Progress Calculation:
Progress % = (Principal Amount - Current Balance) / Principal Amount × 100

Visual indicators:
- Progress bars showing completion percentage
- Remaining balance vs original amount
- Monthly payment impact on timeline
Component Interactions:
  • Monthly Expenses: Loan payments contribute to debt calculations
  • Debt-to-Income: Loan payments factor into DTI ratio
  • Payment Timeline: Shows upcoming loan payments
  • Financial Health: Loan progress affects net worth calculations

7. Budget Management Component (NEW)
Purpose

Complete budgeting system with categories, periods, transactions, and goals. Provides planned vs actual analysis with intelligent insights.

Budget Structure:
  • Categories: Income and expense categories with colors and icons
  • Periods: Monthly, quarterly, yearly, or custom time periods
  • Items: Planned amounts for each category per period
  • Transactions: Actual spending/income recorded manually
  • Goals: Savings goals with progress tracking and auto-contributions
Default Categories Created:
Income Categories:
  • Salary (Primary employment)
  • Side Income (Freelance, gigs)
  • Investment Income (Dividends, interest)
Expense Categories:
  • Housing, Transportation, Food & Groceries
  • Healthcare, Insurance, Entertainment
  • Shopping, Travel, Personal Care
  • Savings, Investments, Debt Payments
Budget Analytics:
Performance Analysis:
- Planned vs Actual comparison
- Category performance status (Excellent/Good/Warning/Over Budget)
- Percentage completion tracking
- Variance analysis and recommendations
- Savings rate calculation
- Budget insights and strategic recommendations
Component Interactions:
  • Financial Entity Integration: Can import data from bills, income, etc.
  • Goal Tracking: Links savings goals with budget performance
  • Analytics Feed: Provides budgeting data for financial insights
  • Transaction Recording: Manual entry for non-automated expenses

8. Analytics Engine
Purpose

Processes data from all components to generate financial insights, health metrics, and projections. The brain of the financial analysis system.

Key Calculations:
  • Debt-to-Income Ratio: Total monthly debt payments ÷ Total monthly income
  • Credit Utilization: Total balances ÷ Total credit limits
  • Monthly Cash Flow: Total monthly income - Total monthly expenses
  • Savings Rate: Net income ÷ Total income × 100
  • Future Projections: 90-day timeline of income and expenses
Data Flow Architecture:
Component → Analytics Engine → Insights

Income Sources → Monthly Income Calculation
Bills + Subscriptions + Loans + Credit Cards → Monthly Expenses
Budget Transactions → Spending Analysis
All Components → Financial Timeline Generation
Combined Data → Health Metrics & Recommendations
Analytics Outputs:
  • Dashboard Metrics: Key financial health indicators
  • Financial Timeline: 90-day projection of cash flow
  • Debt Analysis: DTI ratios and debt management insights
  • Budget Performance: Category analysis and recommendations
  • Goal Progress: Savings goal achievement tracking
Component Integration Summary
How Components Work Together
  1. User Context: User management provides authentication and data isolation
  2. Data Collection: Financial components collect and store user's financial data
  3. Real-time Analysis: Analytics engine processes all component data for insights
  4. Dashboard Integration: All components contribute to unified dashboard view
  5. Cross-Component Features: Include/exclude toggles, timeline generation, backup system
  6. Budget Integration: Budget system can import and analyze data from all components

Result: A comprehensive financial management system where each component operates independently but contributes to holistic financial insights and recommendations.

Complete User Guide

Getting Started
  1. Create Account: Register with username, email, and password
  2. Explore Demo First: Visit /demo to see the app with sample data
  3. Set Up Income Sources: Add your income with appropriate frequencies
  4. Add Financial Obligations: Enter bills, credit cards, loans, and subscriptions
  5. Configure Budget (Optional): Set up budget categories and tracking
  6. Monitor & Analyze: Use dashboard and analytics for financial insights
Dashboard Overview

Your financial command center provides:

Quick Insights
  • Urgent Bills: Bills due within 7 days
  • Credit Card Summary: Balances and utilization
  • Financial Health Metrics: Debt-to-income ratio
  • Next Income Payments: Upcoming income dates
Financial Analytics
  • Monthly Cash Flow: Income vs expenses
  • Savings Rate: Percentage of income saved
  • Credit Utilization: Overall credit usage
  • Upcoming Obligations: Next 30 days of payments
Financial Overview & Timeline (Dashboard)

The Financial Overview is now part of the main Dashboard. It provides a summary of your total income, total expenses, net income, and savings rate for any date range you select.

  • Date Range Selection: Use the date pickers and "Update" button to view your financial summary and timeline for any custom period. The dashboard will recalculate all totals and the running balance for the selected range.
  • Show Excluded Items: Toggle the "Show Excluded Items" switch to include or hide items (such as bills, loans, or subscriptions) that are marked as excluded from calculations. This helps you compare your finances with or without certain items.
  • Timeline Table: The timeline displays all income and expense events in the selected range, with running balance and status indicators for included/excluded items.
All Upcoming Bills – "View All" Button

In the "All Upcoming Bills" section of the dashboard, a "View All" button is always visible in the card header. Click this button to see the complete list of your upcoming bills.

Income Management Guide
Setting Up Income Sources
Frequency Best For Configuration Example
Bi-weekly Most salary jobs Next payment date Every other Friday
Bi-monthly Salary paid twice monthly Two payment days per month 15th and 30th
Monthly Freelance, contract work Day of month Every 25th
One-time Bonuses, tax refunds Specific date March 15, 2025
Credit Card Management Guide
Understanding Minimum Payments

The system automatically calculates minimum payments using multiple methods:

Calculation Priority:
  1. Interest + Principal Method: Monthly interest + 1% of balance (if interest rate provided)
  2. Percentage Method: 2% of current balance
  3. Minimum Floor: $25 absolute minimum
  4. Annual Fee Addition: Monthly fees added if applicable

The system uses the highest calculated amount but never exceeds your current balance plus fees.

Credit Card Payment Calculator

Use the advanced payment calculator for debt payoff strategies:

  • One-time Payment Mode: Allocate a specific amount across cards
  • Monthly Budget Mode: Plan based on monthly payment capacity
  • Strategy Selection: Choose from 6 different payment strategies
  • Target Utilization: Set desired credit utilization goals
Budget Management Guide
Setting Up Your First Budget
  1. Navigate to Budget: Click "Setup Budget" from the budget dashboard
  2. Choose Period: Select current month or create custom period
  3. Set Category Amounts: Enter planned amounts for each category
  4. Save Setup: Your budget is now active and tracking
  5. Record Transactions: Add actual spending and income
  6. Monitor Performance: Review budget vs actual regularly
Budget Categories Explained
Essential Categories
  • Housing: Rent, mortgage, utilities
  • Transportation: Car payments, gas, insurance
  • Food & Groceries: Essential food expenses
  • Healthcare: Medical expenses and insurance
Discretionary Categories
  • Entertainment: Movies, dining out, hobbies
  • Shopping: Clothing, electronics
  • Travel: Vacations and trips
  • Personal Care: Gym, salon, personal services
Financial Health Indicators
Debt-to-Income Ratio

Calculated as: (Total Monthly Debt Payments / Total Monthly Income) × 100

  • Excellent: Under 20%
  • Good: 20-35%
  • Fair: 36-49%
  • Poor: Over 50%
Credit Utilization

Per-card and overall utilization: (Current Balance / Credit Limit) × 100

  • Excellent: Under 10%
  • Good: 10-30%
  • Fair: 30-50%
  • Poor: Over 50%
Data Management
Backup and Export
  • Automatic Backups: Created before any data changes
  • Manual Backup: Dashboard → Create New Backup
  • JSON Export: Backup → Export Data (portable format)
  • Data Import: Backup → Import Data (restore from JSON)
  • Backup Management: View, download, or delete backup files
Include/Exclude Feature

Control which financial items affect your calculations:

  • Include: Item counts toward debt-to-income and financial health metrics
  • Exclude: Item is tracked but doesn't affect calculations (useful for business expenses, etc.)
  • Toggle: Easily switch inclusion status for any bill, card, loan, or subscription
Pro Tips
Maximize Your Financial Management
  • Start with Demo: Explore all features with sample data first
  • Regular Updates: Update balances and payments monthly for accuracy
  • Use Categories: Organize bills and subscriptions by category for better insights
  • Monitor Trends: Watch your debt-to-income ratio and utilization trends
  • Set Goals: Use budget goals to work toward specific financial targets
  • Backup Regularly: Export your data periodically for safekeeping
  • Payment Strategies: Use the credit card calculator to optimize debt payoff

Self-Host Installation

Complete Self-Hosting Guide: This section covers everything you need to set up, configure, and deploy Vance Finance on your own infrastructure. Use the navigation menu to jump to specific topics.
Prerequisites
  • Python 3.7 or higher
  • pip (Python package manager)
  • Git (for cloning repository)
  • Virtual environment support (recommended)
Quick Start Guide
  1. Clone the Repository
    git clone <repository-url>
    cd vance-finance
  2. Create Virtual Environment
    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
  3. Install Dependencies
    pip install -r requirements.txt
  4. Set Up Static Files
    python static_setup.py
  5. Environment Configuration
    # Copy example environment file
    cp .env.example .env
    
    # Edit .env with your settings
    SECRET_KEY=your-secret-key-here
    DEVELOPMENT_MODE=true
  6. Run the Application
    python Vance_Financial_Assistant.py
  7. Access the Application
Quick Start with Demo
Visit /demo to explore the application with pre-populated sample data including all new features like budget management and advanced credit card tools.
Production Deployment Options
Cloud Deployment

Deploy to Heroku, DigitalOcean, or AWS with pre-configured deployment files.

Deploy Guide →
Docker Deployment

Use included Dockerfile for containerized deployment.

Docker Guide →
Next Steps
Configuration

Set up environment variables, database connections, and application settings.

Configure →
Security

Implement CSRF protection, secure sessions, and production security.

Secure →

Configuration

Environment Variables
Variable Description Default Required
SECRET_KEY Flask session encryption key (CSRF protection) Auto-generated Production
DATABASE_URL Database connection string SQLite local file No
DEVELOPMENT_MODE Enable development features true No
PORT Application port 5000 No
Database Configuration
Development (SQLite)
DATABASE_URL=sqlite:///finance_tracker.db

Automatic setup with safe migrations

Production (PostgreSQL)
DATABASE_URL=postgresql://user:password@host:port/database

Recommended for production deployments

New Configuration Features
  • CSRF Protection: Automatically enabled with Flask-WTF
  • Proxy Support: Nginx proxy headers supported
  • Auto-Migration: Database schema automatically updated
  • Backup Configuration: Automatic backup directory creation

Database Schema

Complete Database Schema

Vance Finance uses a comprehensive database schema with 11 core tables supporting all financial management features. The schema includes automatic migration support and foreign key relationships for data integrity.

Core Financial Tables
1. Users Table
CREATE TABLE user (
    id INTEGER PRIMARY KEY,
    username VARCHAR(80) UNIQUE NOT NULL,
    password_hash VARCHAR(256) NOT NULL,
    email VARCHAR(120) UNIQUE NOT NULL
);
2. Bills Table
CREATE TABLE bill (
    id INTEGER PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    amount FLOAT NOT NULL,
    due_date DATE NOT NULL,
    category VARCHAR(50),
    is_paid BOOLEAN DEFAULT FALSE,
    recurring BOOLEAN DEFAULT FALSE,
    include_in_calculations BOOLEAN DEFAULT TRUE,
    user_id INTEGER NOT NULL,
    FOREIGN KEY (user_id) REFERENCES user(id)
);
3. Credit Cards Table
CREATE TABLE credit_card (
    id INTEGER PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    last_four VARCHAR(4) NOT NULL,
    limit FLOAT,
    current_balance FLOAT DEFAULT 0,
    payment_due_date DATE NOT NULL,
    minimum_payment FLOAT,
    interest_rate FLOAT,
    is_paid BOOLEAN DEFAULT FALSE,
    auto_pay_minimum BOOLEAN DEFAULT FALSE,
    auto_payment_amount FLOAT,
    include_in_calculations BOOLEAN DEFAULT TRUE,
    user_id INTEGER NOT NULL,
    FOREIGN KEY (user_id) REFERENCES user(id)
);
4. Income Sources Table
CREATE TABLE income_source (
    id INTEGER PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    amount FLOAT NOT NULL,
    frequency VARCHAR(20) NOT NULL, -- weekly, biweekly, monthly, etc.
    payment_day_1 INTEGER,
    payment_day_2 INTEGER,
    next_payment_date DATE,
    day_of_week VARCHAR(10),
    one_time_date DATE,
    is_active BOOLEAN DEFAULT TRUE,
    user_id INTEGER NOT NULL,
    FOREIGN KEY (user_id) REFERENCES user(id)
);
5. Subscriptions Table
CREATE TABLE subscription (
    id INTEGER PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    amount FLOAT NOT NULL,
    billing_cycle VARCHAR(20) NOT NULL, -- Monthly, Yearly, Weekly
    next_billing_date DATE NOT NULL,
    category VARCHAR(50),
    is_active BOOLEAN DEFAULT TRUE,
    auto_renew BOOLEAN DEFAULT TRUE,
    include_in_calculations BOOLEAN DEFAULT TRUE,
    user_id INTEGER NOT NULL,
    FOREIGN KEY (user_id) REFERENCES user(id)
);
6. Loans Table
CREATE TABLE loan (
    id INTEGER PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    loan_type VARCHAR(50) NOT NULL, -- Personal, Auto, Mortgage, Student
    principal_amount FLOAT NOT NULL,
    current_balance FLOAT NOT NULL,
    monthly_payment FLOAT NOT NULL,
    interest_rate FLOAT,
    next_payment_date DATE NOT NULL,
    term_months INTEGER,
    is_paid_off BOOLEAN DEFAULT FALSE,
    include_in_calculations BOOLEAN DEFAULT TRUE,
    user_id INTEGER NOT NULL,
    FOREIGN KEY (user_id) REFERENCES user(id)
);
Budget Management Tables (NEW in v1.1.4)
7. Budget Categories Table
CREATE TABLE budget_category (
    id INTEGER PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    description VARCHAR(255),
    color VARCHAR(7) DEFAULT '#667eea', -- Hex color code
    icon VARCHAR(50) DEFAULT 'bi-wallet2', -- Bootstrap icon class
    is_active BOOLEAN DEFAULT TRUE,
    is_income BOOLEAN DEFAULT FALSE, -- True for income, False for expense
    sort_order INTEGER DEFAULT 0,
    user_id INTEGER NOT NULL,
    FOREIGN KEY (user_id) REFERENCES user(id)
);
8. Budget Periods Table
CREATE TABLE budget_period (
    id INTEGER PRIMARY KEY,
    name VARCHAR(100) NOT NULL, -- e.g., "January 2025", "Q1 2025"
    period_type VARCHAR(20) NOT NULL, -- monthly, quarterly, yearly, custom
    start_date DATE NOT NULL,
    end_date DATE NOT NULL,
    is_active BOOLEAN DEFAULT TRUE,
    auto_rollover BOOLEAN DEFAULT FALSE, -- Auto-create next period
    notes TEXT,
    user_id INTEGER NOT NULL,
    FOREIGN KEY (user_id) REFERENCES user(id)
);
9. Budget Items Table
CREATE TABLE budget_item (
    id INTEGER PRIMARY KEY,
    category_id INTEGER NOT NULL,
    period_id INTEGER NOT NULL,
    planned_amount FLOAT NOT NULL DEFAULT 0.0,
    actual_amount FLOAT DEFAULT 0.0, -- Auto-calculated from transactions
    notes TEXT,
    alert_threshold FLOAT, -- Alert when % of budget is reached
    is_rollover BOOLEAN DEFAULT FALSE, -- Unused budget rolls to next period
    user_id INTEGER NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (category_id) REFERENCES budget_category(id),
    FOREIGN KEY (period_id) REFERENCES budget_period(id),
    FOREIGN KEY (user_id) REFERENCES user(id)
);
10. Budget Transactions Table
CREATE TABLE budget_transaction (
    id INTEGER PRIMARY KEY,
    category_id INTEGER NOT NULL,
    period_id INTEGER NOT NULL,
    description VARCHAR(255) NOT NULL,
    amount FLOAT NOT NULL,
    transaction_date DATE NOT NULL,
    transaction_type VARCHAR(20) DEFAULT 'manual', -- manual, bill, subscription, loan
    reference_id INTEGER, -- ID of linked bill/subscription/loan
    receipt_url VARCHAR(255), -- Optional receipt/proof
    tags VARCHAR(255), -- Comma-separated tags
    notes TEXT,
    user_id INTEGER NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (category_id) REFERENCES budget_category(id),
    FOREIGN KEY (period_id) REFERENCES budget_period(id),
    FOREIGN KEY (user_id) REFERENCES user(id)
);
11. Budget Goals Table
CREATE TABLE budget_goal (
    id INTEGER PRIMARY KEY,
    title VARCHAR(150) NOT NULL,
    description TEXT,
    target_amount FLOAT NOT NULL,
    current_amount FLOAT DEFAULT 0.0,
    target_date DATE,
    category VARCHAR(50), -- emergency, vacation, purchase, debt_payoff
    priority VARCHAR(20) DEFAULT 'medium', -- low, medium, high
    is_active BOOLEAN DEFAULT TRUE,
    is_achieved BOOLEAN DEFAULT FALSE,
    auto_contribute FLOAT DEFAULT 0.0, -- Automatic monthly contribution
    user_id INTEGER NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES user(id)
);
Database Relationships
Relationship Overview
  • User → All Entities: One-to-many relationships with complete data isolation
  • Budget Categories → Budget Items: One-to-many (categories can have multiple budget allocations)
  • Budget Periods → Budget Items: One-to-many (periods contain multiple category budgets)
  • Budget Categories → Transactions: One-to-many (categories track multiple transactions)
  • Budget Periods → Transactions: One-to-many (periods contain multiple transactions)
Database Features
Migration Support
  • Safe Migrations: Automatic schema updates with backup
  • Column Additions: Dynamic addition of new features
  • Data Preservation: Existing data maintained during updates
  • Rollback Support: Database backups for recovery
Data Integrity
  • Foreign Key Constraints: Referential integrity maintained
  • Cascade Operations: Related data properly managed
  • User Isolation: Complete data separation by user
  • Validation: Server-side data validation
Database Performance
  • Indexed Queries: Primary keys and foreign keys automatically indexed
  • Query Optimization: SQLAlchemy ORM with optimized queries
  • Connection Pooling: Efficient database connection management
  • Pagination: Large datasets handled efficiently
Migration History
Version Changes Migration
v1.0 Initial schema: User, Bill, CreditCard Create initial tables
v1.1 Added: Subscription, Loan, IncomeSource Add new financial entity tables
v1.1.2 Added: include_in_calculations columns ALTER TABLE add column operations
v1.1.3 Added: auto_pay_minimum, auto_payment_amount Credit card feature enhancements
v1.1.4 Added: Complete budget management schema 5 new budget-related tables
v1.1.5 Added: one_time_date for income sources Enhanced income frequency support

API Reference

Authentication Endpoints
POST /register

Register a new user account with CSRF protection.

Form Data:
username: string (required)
email: string (required)
password: string (required)
csrf_token: string (required)
POST /login

Authenticate user login with session management.

Form Data:
username: string (required)
password: string (required)
csrf_token: string (required)
GET /logout

End user session and redirect to login.

Response: Redirect to login page with flash message.
Dashboard & Overview
GET /dashboard

Main financial dashboard with comprehensive overview.

Response Data:
  • Urgent bills (due within 7 days)
  • Credit card summaries with utilization
  • Financial health metrics (debt-to-income ratio)
  • Next 5 income payment dates
  • Monthly cash flow analysis
GET /overview

Financial timeline with 90-day projections.

Query Parameters:
start_date: YYYY-MM-DD (optional)
end_date: YYYY-MM-DD (optional)
include_excluded: boolean (optional)
Financial Management Endpoints
GET/POST /bills

Manage bills and recurring payments.

POST Form Data:
name: string (required)
amount: float (required)
due_date: YYYY-MM-DD (required)
category: string (optional)
recurring: boolean (optional)
include_in_calculations: boolean (optional)
csrf_token: string (required)
GET/POST /credit-cards

Credit card management with automatic minimum payment calculation.

POST Form Data:
name: string (required)
last_four: string (required)
limit: float (optional)
current_balance: float (required)
interest_rate: float (optional)
due_day: integer (required)
auto_pay_minimum: boolean (optional)
auto_payment_amount: float (optional)
csrf_token: string (required)
GET/POST /income

Income source management with flexible frequencies.

POST Form Data:
name: string (required)
amount: float (required)
frequency: string (required) // weekly, biweekly, monthly, bimonthly, quarterly, annually, onetime
payment_day_1: integer (conditional)
payment_day_2: integer (conditional)
next_payment_date: YYYY-MM-DD (conditional)
day_of_week: string (conditional)
one_time_date: YYYY-MM-DD (conditional)
csrf_token: string (required)
Budget Management Endpoints (NEW)
GET /budget

Budget dashboard with analytics and insights.

Response Data:
  • Budget summary with planned vs actual
  • Category performance analysis
  • Recent transactions
  • Active budget goals
  • Budget insights and recommendations
GET/POST /budget/transactions

Record and manage budget transactions.

POST Form Data:
category_id: integer (required)
description: string (required)
amount: float (required)
transaction_date: YYYY-MM-DD (required)
notes: string (optional)
tags: string (optional)
csrf_token: string (required)
GET/POST /budget/goals

Create and manage financial goals.

POST Form Data:
title: string (required)
description: string (optional)
target_amount: float (required)
target_date: YYYY-MM-DD (optional)
category: string (optional)
priority: string (optional) // low, medium, high
auto_contribute: float (optional)
csrf_token: string (required)
Data Management Endpoints
GET /backup/export

Export all user data to JSON format.

Response: JSON file download with complete user data backup.
GET/POST /backup/import

Import data from JSON backup file.

POST Form Data:
backup_file: file (required) // JSON file
clear_existing: boolean (optional)
csrf_token: string (required)
GET /backup/manual

Create manual database backup.

Response: Flash message with backup status.
Demo Mode Endpoints
GET /demo

Demo landing page with feature showcase.

GET /demo/login

Automatic login as demo user with sample data.

Response: Automatic session creation and redirect to dashboard.
GET /demo/reset

Reset demo data to original state.

Authentication: Demo mode only.
Error Handling
Common HTTP Status Codes
  • 200 OK: Successful request
  • 302 Found: Redirect (after POST operations)
  • 400 Bad Request: CSRF token missing or invalid
  • 403 Forbidden: Unauthorized access to user data
  • 404 Not Found: Resource not found
  • 500 Internal Server Error: Server error with automatic rollback

Development Guide

Development Environment Setup
1. Install Development Dependencies
# Create and activate virtual environment
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt
2. Enable Development Mode
# Set environment variables
export DEVELOPMENT_MODE=true
export SECRET_KEY=your-dev-secret-key

# Or create .env file
echo "DEVELOPMENT_MODE=true" > .env
echo "SECRET_KEY=your-dev-secret-key" >> .env
3. Development Features
  • Debug Mode: Detailed error pages and automatic reloading
  • Debug Routes: Special endpoints for testing and debugging
  • Auto-Migration: Database schema automatically updated
  • Demo Data: Rich sample data for testing
Project Structure
vance-finance/
├── Vance_Financial_Assistant.py  # Main application file
├── requirements.txt               # Python dependencies
├── static_setup.py               # Static file setup script
├── wsgi.py                       # WSGI entry point
├── config.py                     # Configuration management
├── demo.py                       # Demo data generator
├── .env.example                  # Environment template
├── Dockerfile                    # Container configuration
├── templates/                    # Jinja2 templates
│   ├── base.html                # Base template
│   ├── dashboard.html           # Main dashboard
│   ├── bills.html               # Bill management
│   ├── credit_cards.html        # Credit card management
│   ├── income.html              # Income management
│   ├── budget.html              # Budget dashboard
│   ├── budget_transactions.html # Budget transactions
│   ├── budget_goals.html        # Budget goals
│   └── errors/                  # Error pages
├── static/                      # Static assets
│   └── css/                     # Stylesheets
│       ├── style.css           # Main styles
│       ├── budget.css          # Budget-specific styles
│       └── wiki.css            # Documentation styles
└── backups/                     # Database backups (auto-created)
Code Architecture
Models (SQLAlchemy)

All models are defined in the main application file:

  • User: Authentication and profile management
  • Bill: Recurring and one-time bill tracking
  • CreditCard: Credit card management with calculations
  • IncomeSource: Flexible income frequency tracking
  • Subscription: Recurring service subscriptions
  • Loan: Loan and debt management
  • Budget Models: Complete budgeting system (5 tables)
Utility Functions
  • calculate_monthly_income(): Convert various frequencies to monthly
  • calculate_monthly_expenses(): Aggregate monthly expense calculations
  • get_future_income_dates(): Generate income payment schedules
  • calculate_minimum_payment(): Advanced credit card minimum payment calculation
  • backup_database(): Automated backup system
  • safe_migrate_database(): Safe database migration
Development Best Practices
Security Guidelines
  • CSRF Protection: All forms must include CSRF tokens
  • User Validation: Always verify user_id in session
  • Data Isolation: Filter all queries by user_id
  • Input Validation: Validate and sanitize all form inputs
  • Error Handling: Use try/catch blocks with rollback
Database Guidelines
  • Backup First: Call backup_database() before destructive operations
  • Transaction Safety: Use database transactions for related operations
  • Migration Testing: Test migrations on backup data first
  • Foreign Keys: Maintain referential integrity
Frontend Guidelines
  • Responsive Design: Mobile-first approach with Bootstrap 5
  • Accessibility: Proper labels, ARIA attributes, and keyboard navigation
  • Progressive Enhancement: Core functionality works without JavaScript
  • Error Feedback: Clear user feedback for all operations
Testing
Manual Testing Checklist
  • User Registration/Login: Account creation and authentication
  • Data Entry: All form submissions with validation
  • Calculations: Financial calculations and analytics
  • Navigation: All routes and redirects
  • Demo Mode: Demo functionality and data integrity
  • Backup/Restore: Data export/import functionality
  • Mobile Interface: Responsive design testing
  • Error Handling: Invalid inputs and edge cases
Debug Routes (Development Only)
Remove in Production: These routes should not be available in production.
  • /debug/paths - View file system paths and configuration
  • /debug/users - View user database information
  • /test/backup - Test backup functionality
Contributing
Adding New Features
  1. Database Model: Add new SQLAlchemy model if needed
  2. Migration: Update safe_migrate_database() function
  3. Routes: Add Flask routes with proper authentication
  4. Templates: Create responsive HTML templates
  5. Integration: Update analytics and dashboard integration
  6. Demo Data: Add sample data to demo system
  7. Documentation: Update wiki and README
Code Style
  • Python: Follow PEP 8 style guidelines
  • HTML: Proper indentation and semantic markup
  • CSS: Use Bootstrap classes with minimal custom CSS
  • JavaScript: ES6+ features with progressive enhancement
  • Comments: Document complex calculations and business logic

Deployment Options

Production Environment Setup
1. Environment Configuration
# Production environment variables
export DEVELOPMENT_MODE=false
export SECRET_KEY=your-production-secret-key-here
export DATABASE_URL=your-production-database-url
export PORT=5000
2. Security Configuration
  • Secret Key: Generate a secure 32+ character secret key
  • Database Security: Use database authentication and SSL
  • HTTPS: Enable SSL/TLS encryption
  • Firewall: Restrict access to necessary ports only
Docker Deployment
Using the Included Dockerfile
# Build the Docker image
docker build -t vance-finance .

# Run with environment variables
docker run -d \
  --name vance-finance \
  -p 5000:5000 \
  -e SECRET_KEY=your-secret-key \
  -e DATABASE_URL=your-database-url \
  -e DEVELOPMENT_MODE=false \
  vance-finance
Docker Compose
# docker-compose.yml
version: '3.8'
services:
  app:
    build: .
    ports:
      - "5000:5000"
    environment:
      - SECRET_KEY=your-secret-key
      - DATABASE_URL=sqlite:///finance_tracker.db
      - DEVELOPMENT_MODE=false
    volumes:
      - ./backups:/app/backups
      - ./data:/app/data
Heroku Deployment
1. Heroku Setup
# Install Heroku CLI and login
heroku login

# Create Heroku app
heroku create your-app-name

# Add PostgreSQL database
heroku addons:create heroku-postgresql:hobby-dev
2. Environment Configuration
# Set environment variables
heroku config:set SECRET_KEY=your-secret-key
heroku config:set DEVELOPMENT_MODE=false

# Database URL is automatically set by Heroku PostgreSQL addon
3. Deploy Application
# Deploy to Heroku
git push heroku main

# Migrate database (if needed)
heroku run python -c "from Vance_Financial_Assistant import app, db; app.app_context().push(); db.create_all()"
Traditional Server Deployment
Using Gunicorn (Recommended)
# Install Gunicorn
pip install gunicorn

# Run with Gunicorn
gunicorn --bind 0.0.0.0:5000 --workers 4 wsgi:app

# Or with configuration file
gunicorn --config gunicorn.conf.py wsgi:app
Nginx Configuration
# /etc/nginx/sites-available/vance-finance
server {
    listen 80;
    server_name your-domain.com;

    location / {
        proxy_pass http://127.0.0.1:5000;
        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;
    }

    location /static {
        alias /path/to/your/app/static;
        expires 1d;
    }
}
Systemd Service (Linux)
# /etc/systemd/system/vance-finance.service
[Unit]
Description=Vance Finance Application
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/path/to/your/app
Environment=PATH=/path/to/your/app/venv/bin
ExecStart=/path/to/your/app/venv/bin/gunicorn --workers 3 --bind unix:vance-finance.sock -m 007 wsgi:app
Restart=always

[Install]
WantedBy=multi-user.target
DigitalOcean App Platform
App Spec Configuration
# .do/app.yaml
name: vance-finance
services:
- name: web
  source_dir: /
  github:
    repo: your-username/vance-finance
    branch: main
  run_command: gunicorn --worker-tmp-dir /dev/shm --config gunicorn.conf.py wsgi:app
  environment_slug: python
  instance_count: 1
  instance_size_slug: basic-xxs
  envs:
  - key: SECRET_KEY
    value: your-secret-key
  - key: DEVELOPMENT_MODE
    value: "false"
databases:
- name: db
  engine: PG
  version: "13"
AWS Deployment
Elastic Beanstalk
  1. Install EB CLI: pip install awsebcli
  2. Initialize: eb init
  3. Create environment: eb create production
  4. Set environment variables: eb setenv SECRET_KEY=your-key DEVELOPMENT_MODE=false
  5. Deploy: eb deploy
Database Considerations
SQLite (Development/Small Deployments)
  • Pros: No setup required, automatic backups, simple
  • Cons: Single-user, no clustering, limited concurrency
  • Best For: Personal use, small deployments, development
PostgreSQL (Production Recommended)
  • Pros: Multi-user, scalable, ACID compliant, full-featured
  • Cons: Requires setup and maintenance
  • Best For: Production deployments, multi-user environments
Monitoring & Maintenance
Health Checks
  • Health Endpoint: /health returns application status
  • Database Connectivity: Verify database connections
  • Backup Status: Monitor backup creation and storage
  • Error Rates: Track application errors and performance
Backup Strategy
  • Automated Backups: Application creates backups automatically
  • Database Dumps: Regular database exports
  • File System Backups: Backup entire application directory
  • Off-site Storage: Store backups in separate location
Scaling Considerations
  • Horizontal Scaling: Multiple application instances with load balancer
  • Database Scaling: Read replicas, connection pooling
  • Static Assets: CDN for static file delivery
  • Caching: Redis or Memcached for session storage

Security Implementation

Authentication Security
Password Security
  • Hashing Algorithm: Werkzeug PBKDF2 with SHA-256
  • Salt: Unique salt per password
  • Iterations: High iteration count for security
  • No Plain Text: Passwords never stored in plain text
Session Management
  • Flask Sessions: Secure server-side session management
  • Session Expiry: Automatic session timeout
  • Secure Cookies: HTTPOnly and Secure flags in production
  • Session Validation: User ID validation on each request
CSRF Protection
Implementation Details
  • Flask-WTF: CSRF protection enabled globally
  • Token Generation: Unique tokens per session
  • Form Protection: All POST forms include CSRF tokens
  • AJAX Protection: CSRF tokens in AJAX requests
CSRF Token Usage
<form method="POST">
    <input type="hidden" name="csrf_token" value="ImI3MTJlNjg3MDBhZTNjYzE5ZWUyMGE3NDY5OGMwYjdmZDg5MzIxYjgi.aTOnVQ.8u9GSySjIhJW0k5R-i9Y72sTwfI"/>
    <!-- form fields -->
</form>
Data Protection
Input Validation
  • Server-Side Validation: All inputs validated on server
  • Type Checking: Proper data type validation
  • Range Validation: Numeric ranges and string lengths
  • Sanitization: HTML and SQL injection prevention
SQL Injection Prevention
  • SQLAlchemy ORM: Parameterized queries by default
  • No Raw SQL: Avoid raw SQL queries
  • Input Sanitization: All user inputs properly escaped
  • Prepared Statements: Database-level protection
XSS Prevention
  • Jinja2 Auto-Escaping: Template auto-escaping enabled
  • Content Security Policy: CSP headers for additional protection
  • Input Sanitization: User content properly escaped
  • Output Encoding: Context-appropriate encoding
User Data Isolation
Database Security
  • User ID Filtering: All queries filtered by user_id
  • Foreign Key Constraints: Referential integrity enforced
  • Access Control: Users can only access their own data
  • Authorization Checks: Ownership verification on all operations
Route Protection
@app.route('/protected')
def protected_route():
    if 'user_id' not in session:
        return redirect(url_for('login'))
    
    # Verify data ownership
    item = Model.query.get_or_404(item_id)
    if item.user_id != session['user_id']:
        flash('Unauthorized access', 'danger')
        return redirect(url_for('dashboard'))
Production Security Checklist
Application Security
Infrastructure Security
Security Headers
Recommended Headers
# Add to your Flask app or web server configuration
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'
Referrer-Policy: strict-origin-when-cross-origin
Backup Security
  • Backup Encryption: Encrypt sensitive backup data
  • Access Control: Restrict backup file access
  • Secure Storage: Store backups in secure locations
  • Regular Testing: Test backup restoration procedures
Monitoring & Alerting
  • Failed Login Attempts: Monitor and alert on suspicious activity
  • CSRF Violations: Track CSRF token failures
  • Error Monitoring: Monitor application errors and exceptions
  • Access Logs: Log and monitor all access attempts
Security Best Practices
Important Security Guidelines
  • Regular Updates: Keep all dependencies up to date
  • Principle of Least Privilege: Grant minimum necessary permissions
  • Defense in Depth: Multiple layers of security
  • Security Testing: Regular security assessments
  • Incident Response: Have a plan for security incidents

Backup & Recovery

Comprehensive Backup System

Vance Finance includes a multi-layered backup system designed to protect your financial data with multiple recovery options.

Automatic Backup Features
Triggered Backups
  • Before User Registration: Database backed up before new user creation
  • Before Data Modification: All ADD, EDIT, DELETE operations trigger backup
  • Before Data Import: Backup created before importing external data
  • Before Bulk Operations: Mass updates and batch processes
Backup Types
  • SQLite File Copy: Complete database file duplication
  • JSON Export: Structured data export for portability
  • Timestamp Naming: Backups named with creation timestamp
  • Verification: Backup integrity verification
Manual Backup Options
Database Backup
  • One-Click Backup: Create instant database backup from dashboard
  • Route: /backup/manual
  • File Location: backups/finance_tracker_backup_YYYYMMDD_HHMMSS.db
  • Verification: Automatic file size and integrity verification
JSON Data Export
  • Complete Export: All user data in structured JSON format
  • Route: /backup/export
  • Includes: Bills, credit cards, subscriptions, loans, income sources, budget data
  • Portable Format: Cross-platform compatible data format
Backup Management
Backup Browser
  • View All Backups: Complete list with dates and sizes
  • Download: Download any backup file
  • Delete: Remove old or unnecessary backups
  • Storage Info: Total backup count and disk usage
Backup File Naming
Database Backups:
finance_tracker_backup_20250711_143022.db

JSON Exports:
vance_financial_backup_username_20250711_143022.json
Recovery Procedures
Database Recovery (Complete Restoration)
  1. Stop Application: Ensure application is not running
  2. Backup Current: Create backup of current state (if possible)
  3. Replace Database: Replace current database file with backup
  4. Restart Application: Start application with restored database
  5. Verify Data: Confirm data integrity and completeness
JSON Data Import (Selective Restoration)
  1. Navigate to Import: Go to Backup → Import Data
  2. Select File: Choose JSON backup file
  3. Choose Option:
    • Merge: Add backup data to existing data
    • Replace: Clear existing data and import backup
  4. Confirm Import: Review and confirm the import operation
  5. Verify Results: Check that data was imported correctly
Backup Security
Access Control
  • User Authentication: Backup access requires user login
  • File Permissions: Backup files protected by file system permissions
  • Download Verification: Security checks before file downloads
  • Path Protection: Prevents directory traversal attacks
Data Protection
  • User Isolation: JSON exports contain only user's own data
  • Password Hashing: Passwords remain hashed in exports
  • Secure Storage: Backup files stored in protected directory
  • Encryption Recommendation: Encrypt backups for additional security
Disaster Recovery Planning
Recovery Strategy
Recommended Recovery Plan
  1. Regular Testing: Test backup and recovery procedures monthly
  2. Multiple Locations: Store backups in multiple locations
  3. Version Control: Keep multiple backup versions
  4. Documentation: Document recovery procedures
  5. Monitoring: Monitor backup creation and storage
Backup Best Practices
  • 3-2-1 Rule: 3 copies, 2 different media types, 1 offsite
  • Regular Schedule: Automate regular backup creation
  • Test Restoration: Regularly test backup restoration
  • Monitor Storage: Track backup file sizes and storage usage
  • Cleanup Policy: Remove old backups based on retention policy
Advanced Backup Features
Backup Automation
# Cron job for daily backups (Linux/Mac)
0 2 * * * /path/to/your/app/venv/bin/python -c "
from Vance_Financial_Assistant import backup_database, app
with app.app_context():
    backup_database()
"
External Storage Integration
  • Cloud Storage: Integrate with AWS S3, Google Drive, or Dropbox
  • Network Storage: Use network attache
  • Network Storage: Use network attached storage (NAS) for local backups
  • FTP/SFTP: Upload backups to remote servers
  • Version Control: Store backups in Git repositories
Monitoring and Alerts
  • Backup Success Monitoring: Track successful backup creation
  • Storage Space Alerts: Monitor backup directory disk usage
  • Backup Age Monitoring: Alert on old or stale backups
  • Automated Cleanup: Remove backups older than retention period

Troubleshooting Guide

Common Issues & Solutions

Possible causes:
  • Missing Python dependencies
  • Port already in use (5000)
  • Database connection issues
  • Invalid environment variables
  • Permission issues
Solutions:
  1. Check Python version: python --version (requires 3.7+)
  2. Install dependencies: pip install -r requirements.txt
  3. Check port availability: netstat -an | grep 5000
  4. Verify environment variables: Check .env file or export statements
  5. Check file permissions: Ensure read/write access to database directory
  6. Try different port: export PORT=5001

Possible causes:
  • Incorrect username or password
  • Database corruption or migration issues
  • Session management problems
  • CSRF token issues
Solutions:
  1. Clear browser data: Clear cache, cookies, and local storage
  2. Try demo mode: Visit /demo/login to test functionality
  3. Check debug routes: /debug/users (development only)
  4. Register new account: Test with fresh account
  5. Check console errors: Look for JavaScript or network errors
  6. Verify CSRF protection: Ensure forms include csrf_token

Possible causes:
  • Database permission issues
  • Disk space full
  • Form validation errors
  • CSRF token missing or invalid
  • Database locks or corruption
Solutions:
  1. Check file permissions: Ensure database file is writable
  2. Verify disk space: df -h (Linux/Mac) or check disk properties
  3. Check browser console: Look for JavaScript errors
  4. Review application logs: Check terminal output for errors
  5. Test with demo: See if demo mode works correctly
  6. Check CSRF tokens: Verify forms include proper tokens

Possible causes:
  • Items marked as "excluded" from calculations
  • Incorrect income frequency settings
  • Missing or inactive financial items
  • Date-related calculation issues
Solutions:
  1. Check include/exclude status: Verify items are included in calculations
  2. Review income frequencies: Ensure correct payment schedules
  3. Verify active status: Check that items are marked as active
  4. Check dates: Ensure dates are current and correct
  5. Use overview page: Toggle "include excluded" to see differences

Possible causes:
  • Insufficient disk space for backups
  • File permission issues
  • Corrupted backup files
  • JSON format issues in imports
Solutions:
  1. Check disk space: Ensure adequate space in backup directory
  2. Verify permissions: Check backup directory write permissions
  3. Test backup creation: Use manual backup to test functionality
  4. Validate JSON files: Ensure backup files are valid JSON
  5. Try smaller imports: Import data in smaller chunks

Possible causes:
  • Browser compatibility issues
  • CSS loading problems
  • JavaScript errors on mobile
  • Viewport configuration
Solutions:
  1. Update browser: Use latest version of mobile browser
  2. Clear cache: Clear mobile browser cache and data
  3. Check network: Ensure stable internet connection
  4. Test different browsers: Try Chrome, Safari, Firefox mobile
  5. Check console errors: Use browser dev tools on mobile
Debug Tools (Development Only)
Important: These debug routes should only be used in development and must be removed in production.
Route Purpose Information Provided
/debug/paths File system debugging Application paths, working directory, database location
/debug/users User database inspection User count, usernames, email addresses
/test/backup Backup system testing Backup functionality, file permissions, directory access
/health Application health check Application status, timestamp, basic functionality
Log Analysis
Reading Application Logs
  • Console Output: Monitor terminal where application is running
  • Error Messages: Look for Python tracebacks and error messages
  • Database Errors: SQLAlchemy and database-related errors
  • HTTP Status Codes: 400, 403, 404, 500 error responses
Common Error Patterns
# Database connection error
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) database is locked

# CSRF token error
The CSRF token is missing. or Bad Request: The CSRF token is missing.

# Permission error
PermissionError: [Errno 13] Permission denied: '/path/to/database'

# Import error (missing dependency)
ModuleNotFoundError: No module named 'flask'
Performance Issues
Slow Application Response
  • Database Size: Large databases may slow queries
  • Backup Operations: Automatic backups can cause temporary slowness
  • Memory Usage: Check available system memory
  • Disk I/O: Slow disk can affect performance
Optimization Strategies
  • Database Cleanup: Remove old or unnecessary data
  • Backup Management: Delete old backup files
  • Indexing: Database indexes are automatically maintained
  • Production Deployment: Use Gunicorn for better performance
Getting Help
Self-Help Resources
  • Demo Mode: Test expected behavior with sample data
  • Documentation: Review this wiki for detailed information
  • Source Code: Examine the code for implementation details
  • Debug Routes: Use development debug tools
Reporting Issues
  • Error Messages: Include complete error messages
  • Browser Information: Browser version and type
  • Steps to Reproduce: Detailed reproduction steps
  • Environment Details: Operating system, Python version
Recovery Procedures
Emergency Recovery
  1. Stop Application: Safely shut down the application
  2. Backup Current State: Create backup of current (even if problematic) state
  3. Restore from Backup: Use most recent known-good backup
  4. Test Functionality: Verify application works with restored data
  5. Document Issue: Record what went wrong for future prevention
Reset to Demo State

If all else fails, you can reset to demo state for testing:

  1. Visit /demo/login to access demo mode
  2. Test functionality with demo data
  3. Use /demo/reset to restore original demo data
  4. Export demo data as reference
  5. Create new user account and import demo data
Pro Tips for Troubleshooting
  • Start Simple: Test with demo mode first
  • Check Basics: Verify Python version, dependencies, and permissions
  • Use Browser Tools: Browser developer tools can reveal client-side issues
  • Monitor Logs: Keep an eye on console output during operations
  • Test Incrementally: Add data gradually to isolate problematic items
  • Keep Backups: Regular backups make recovery much easier