# Expenses Management System - Complete Documentation

## Overview
The Expenses Management System is a comprehensive module integrated into HAVEN GRAZURI INVESTMENT LIMITEDthat allows staff to track, manage, and approve business expenses across all branches.

## Features Implemented

### 1. Database Integration
- **Table Name**: `expenses`
- **Relationships**:
  - Links to existing `branches` table via `branch_id`
  - Links to existing `users` table via `staff_id` (creator)
  - Links to existing `users` table via `approved_by` (approver)
  - Optional link to `loans` table via `loan_id` (for loan-related expenses)

### 2. Expense Categories
- Operational
- Staff
- Marketing
- Loan-Related
- Utilities
- Office
- Transport
- Maintenance
- Other

### 3. Payment Methods
- Cash
- M-Pesa
- Bank Transfer
- Cheque

### 4. Approval Workflow
- **Pending**: Initial status when expense is created
- **Approved**: Approved by manager/admin
- **Rejected**: Rejected with reason by manager/admin

### 5. Pages & Features

#### A. Expenses List Page (`/expenses/`)
- **Summary Widgets**:
  - Total Expenses Today
  - Total Expenses This Month
  - Total Expenses This Year
  - Pending Approvals Count
  - Top Spending Category

- **Advanced Filters**:
  - Search (title, paid to, reference number)
  - Category filter
  - Payment method filter
  - Status filter
  - Branch filter
  - Date range (from/to)
  - Amount range (min/max)
  - Loan-related filter

- **Table Columns**:
  - Date
  - Title (with loan indicator badge)
  - Category
  - Amount
  - Branch
  - Staff
  - Payment Method
  - Status (with color-coded badges)
  - Receipt (with view link)
  - Actions (View, Edit)

- **Features**:
  - Pagination (25 items per page)
  - Sorting
  - Live search
  - Export to Excel/CSV
  - Branch-based filtering (respects user permissions)

#### B. Add/Edit Expense Page (`/expenses/add/`, `/expenses/<id>/edit/`)
- **Form Sections**:
  1. Basic Information
     - Title (required)
     - Description
     - Category (required)
     - Expense Date (required)

  2. Financial Details
     - Amount (required, minimum 0.01)
     - Payment Method (required)
     - Paid To (required)
     - Reference Number (optional)

  3. Relationships
     - Branch (required, auto-filled from user's branch)
     - Related Loan (optional dropdown)

  4. Documentation
     - Receipt Upload (PDF/Image)
     - Additional Notes

- **Validation**:
  - All required fields validated
  - Amount must be positive
  - Date validation
  - File type validation for receipts

- **Permissions**:
  - Only pending expenses can be edited
  - Staff can only edit their own expenses (unless admin/team leader)

#### C. Expense Detail Page (`/expenses/<id>/`)
- **Information Displayed**:
  - Basic Information (title, category, date, description)
  - Financial Details (amount, payment method, paid to, reference)
  - Relationships (branch, staff, related loan)
  - Approval Information (status, approved by, approved at, rejection reason)
  - Receipt (with view link)
  - Additional Notes

- **Actions Available**:
  - Approve (for managers/admins on pending expenses)
  - Reject (for managers/admins on pending expenses)
  - Edit (for pending expenses)
  - Delete (for managers/admins)

#### D. Pending Approvals Page (`/expenses/approvals/pending/`)
- **Access**: Admin and Team Leader only
- **Features**:
  - List of all pending expenses
  - Quick approve/reject actions
  - Branch filtering (respects user permissions)
  - Pagination

#### E. Expense Analytics Page (`/expenses/analytics/`)
- **Access**: Admin and Team Leader only
- **Reports**:
  1. **Expenses by Category**
     - Count, Total Amount, Average per category
     - Sortable table

  2. **Expenses by Branch**
     - Count, Total Amount, Average per branch
     - Sortable table

  3. **Monthly Trend (Last 6 Months)**
     - Month-by-month breakdown
     - Visual trend bars
     - Total amounts

### 6. Export Functionality
- **Excel/CSV Export** (`/expenses/export/excel/`)
  - Exports filtered expenses
  - Includes all relevant columns
  - Filename with timestamp
  - Respects current filters

### 7. Permission System
- **Staff (loan_officer, secretary)**:
  - Can view expenses
  - Can add expenses
  - Can edit their own pending expenses

- **Manager (team_leader)**:
  - All staff permissions
  - Can approve/reject expenses
  - Can view analytics
  - Can delete expenses

- **Admin**:
  - Full access to all features
  - Can manage all expenses
  - Can view all analytics

- **Auditor**:
  - Read-only access to all expenses
  - Can view analytics
  - Cannot create, edit, or approve

### 8. Branch Filtering
- Automatically filters expenses based on user's accessible branches
- Respects branch hierarchy and permissions
- Admins can see all branches

### 9. UI/UX Features
- **Consistent Design**: Matches existing HAVEN GRAZURI VESTMENT LIMITEDstyling
- **Color Scheme**: Uses primary (#00308a) and secondary (#86c662) colors
- **Responsive**: Works on desktop, tablet, and mobile
- **Icons**: Font Awesome icons throughout
- **Status Badges**: Color-coded (yellow=pending, green=approved, red=rejected)
- **Hover Effects**: Interactive table rows and buttons
- **Loading States**: Proper feedback for user actions
- **Error Handling**: Clear error messages and validation

### 10. Sample Data
- 15 sample expenses created with realistic data
- Mix of categories, payment methods, and statuses
- Distributed across different dates
- Some linked to loans
- 11 approved, 4 pending

## Technical Implementation

### Models
```python
class Expense(models.Model):
    - id (UUID, primary key)
    - title (CharField)
    - description (TextField)
    - category (CharField with choices)
    - amount (DecimalField)
    - payment_method (CharField with choices)
    - paid_to (CharField)
    - receipt_path (FileField)
    - branch (ForeignKey to Branch)
    - staff (ForeignKey to User)
    - loan (ForeignKey to Loan, nullable)
    - status (CharField with choices)
    - approved_by (ForeignKey to User, nullable)
    - approved_at (DateTimeField, nullable)
    - rejection_reason (TextField, nullable)
    - expense_date (DateField)
    - created_at (DateTimeField)
    - updated_at (DateTimeField)
    - reference_number (CharField, nullable)
    - notes (TextField, nullable)
```

### Views
- `expenses_list`: List all expenses with filtering
- `add_expense`: Create new expense
- `edit_expense`: Edit existing expense
- `expense_detail`: View expense details
- `delete_expense`: Delete expense
- `approve_expense`: Approve pending expense
- `reject_expense`: Reject pending expense
- `pending_approvals`: List pending approvals
- `export_expenses_excel`: Export to Excel/CSV
- `expense_analytics`: View analytics and reports

### URLs
```
/expenses/ - List all expenses
/expenses/add/ - Add new expense
/expenses/<id>/ - View expense detail
/expenses/<id>/edit/ - Edit expense
/expenses/<id>/delete/ - Delete expense
/expenses/<id>/approve/ - Approve expense
/expenses/<id>/reject/ - Reject expense
/expenses/approvals/pending/ - Pending approvals
/expenses/export/excel/ - Export to Excel
/expenses/analytics/ - Analytics dashboard
```

### Forms
- `ExpenseForm`: Main form for creating/editing expenses
- `ExpenseFilterForm`: Filter form for expense list

### Templates
- `expenses_list.html`: Main list view
- `expense_form.html`: Add/Edit form
- `expense_detail.html`: Detail view
- `expense_approve.html`: Approval confirmation
- `expense_reject.html`: Rejection form
- `expense_confirm_delete.html`: Delete confirmation
- `pending_approvals.html`: Pending approvals list
- `expense_analytics.html`: Analytics dashboard

## Navigation Integration
The Expenses menu has been added to the main navigation with the following structure:

**Expenses** (Main Menu)
- All Expenses
- Add Expense
- Pending Approvals (Admin/Team Leader only)
- Analytics (Admin/Team Leader only)

## Database Indexes
For optimal performance, the following indexes have been created:
- `(branch_id, expense_date)`
- `(status, expense_date)`
- `(category, expense_date)`
- `(staff_id, expense_date)`

## File Uploads
- Receipts are stored in: `media/expenses/receipts/YYYY/MM/`
- Supported formats: PDF, Images (JPG, PNG, etc.)
- Files are organized by year and month

## Future Enhancements (Optional)
1. **Recurring Expenses**: Support for monthly recurring expenses
2. **Budget Management**: Set and track budgets by category/branch
3. **Expense Policies**: Define approval policies based on amount thresholds
4. **Multi-level Approvals**: Require multiple approvals for large expenses
5. **Expense Categories Customization**: Allow admins to add custom categories
6. **Advanced Analytics**: More detailed charts and visualizations
7. **Email Notifications**: Notify approvers of pending expenses
8. **Expense Reimbursement**: Track staff reimbursements
9. **Vendor Management**: Maintain vendor database
10. **PDF Export**: Generate PDF reports of expenses

## Testing
To test the expenses feature:

1. **Create Sample Data**:
   ```bash
   python create_sample_expenses.py
   ```

2. **Access the Feature**:
   - Login as staff user
   - Navigate to "Expenses" in the main menu
   - View the list of expenses

3. **Test Workflows**:
   - Add a new expense
   - Edit a pending expense
   - Approve/reject as manager
   - Filter and search expenses
   - Export to Excel
   - View analytics

## Deployment Notes
1. Run migrations: `python manage.py migrate expenses`
2. Create sample data (optional): `python create_sample_expenses.py`
3. Ensure media directory is writable
4. Configure web server to serve media files
5. Update navigation cache if applicable

## Support
For issues or questions about the Expenses feature, contact the development team.

---
**Version**: 1.0
**Last Updated**: November 29, 2024
**Author**: HAVEN GRAZURI VESTMENT LIMITEDDevelopment Team
