# 💰 Expenses Management System

## Overview
A comprehensive expense tracking and approval system fully integrated into HAVEN GRAZURI INVESTMENT LIMITEDmicrofinance platform.

## 🎯 Quick Links
- **Technical Documentation**: [EXPENSES_FEATURE_DOCUMENTATION.md](EXPENSES_FEATURE_DOCUMENTATION.md)
- **User Guide**: [EXPENSES_USER_GUIDE.md](EXPENSES_USER_GUIDE.md)
- **Implementation Summary**: [EXPENSES_IMPLEMENTATION_SUMMARY.md](EXPENSES_IMPLEMENTATION_SUMMARY.md)

## 🚀 Quick Start

### For Users
1. Login to HAVEN GRAZURI Advance
2. Click **"Expenses"** in the main menu
3. Click **"Add Expense"** to create a new expense
4. Fill in the details and submit
5. Wait for manager approval

### For Managers
1. Go to **Expenses** → **Pending Approvals**
2. Review pending expenses
3. Click **Approve** or **Reject**

### For Admins
1. Access all expense features
2. View analytics at **Expenses** → **Analytics**
3. Export data using **Export Excel** button

## ✨ Key Features

### 📝 Expense Management
- Create, edit, view, and delete expenses
- Upload receipts (PDF/Images)
- Link expenses to loans
- Track by branch and staff

### ✅ Approval Workflow
- 3-stage workflow: Pending → Approved/Rejected
- Manager/Admin approval required
- Rejection with reasons
- Approval tracking

### 📊 Analytics & Reports
- Expenses by category
- Expenses by branch
- Monthly trends (6 months)
- Export to Excel/CSV

### 🔍 Advanced Filtering
- Search by title, vendor, reference
- Filter by category, status, payment method
- Date range filtering
- Amount range filtering
- Branch filtering

### 🎨 Beautiful UI
- Responsive design (mobile-friendly)
- Color-coded status badges
- Interactive tables
- Summary widgets
- Consistent with existing system

## 📋 Expense Categories

1. **Operational** - Rent, general operations
2. **Staff** - Salaries, training, benefits
3. **Marketing** - Advertising, promotions
4. **Loan-Related** - Loan processing costs
5. **Utilities** - Electricity, water, internet
6. **Office** - Furniture, equipment, supplies
7. **Transport** - Fuel, vehicle costs
8. **Maintenance** - Repairs, servicing
9. **Other** - Miscellaneous

## 💳 Payment Methods

- **Cash** - Physical cash payments
- **M-Pesa** - Mobile money transfers
- **Bank Transfer** - Bank-to-bank transfers
- **Cheque** - Cheque payments

## 👥 User Roles & Permissions

| Role | Create | Edit Own | Approve | Delete | Analytics |
|------|--------|----------|---------|--------|-----------|
| **Staff** | ✅ | ✅ | ❌ | ❌ | ❌ |
| **Manager** | ✅ | ✅ | ✅ | ✅ | ✅ |
| **Admin** | ✅ | ✅ | ✅ | ✅ | ✅ |
| **Auditor** | ❌ | ❌ | ❌ | ❌ | ✅ (Read-only) |

## 📱 Access Points

### Main Navigation
```
Expenses
├── All Expenses
├── Add Expense
├── Pending Approvals (Manager/Admin)
└── Analytics (Manager/Admin)
```

### URLs
```
/expenses/                    - List all expenses
/expenses/add/                - Add new expense
/expenses/<id>/               - View expense detail
/expenses/<id>/edit/          - Edit 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
```

## 🗄️ Database Schema

### Expenses Table
```sql
CREATE TABLE expenses (
    id UUID PRIMARY KEY,
    title VARCHAR(200) NOT NULL,
    description TEXT,
    category VARCHAR(20) NOT NULL,
    amount DECIMAL(12,2) NOT NULL,
    payment_method VARCHAR(20) NOT NULL,
    paid_to VARCHAR(200) NOT NULL,
    receipt_path VARCHAR(255),
    branch_id UUID NOT NULL,
    staff_id UUID,
    loan_id UUID,
    status VARCHAR(20) DEFAULT 'pending',
    approved_by_id UUID,
    approved_at DATETIME,
    rejection_reason TEXT,
    expense_date DATE NOT NULL,
    created_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL,
    reference_number VARCHAR(50),
    notes TEXT,
    FOREIGN KEY (branch_id) REFERENCES branches(id),
    FOREIGN KEY (staff_id) REFERENCES users(id),
    FOREIGN KEY (loan_id) REFERENCES loans(id),
    FOREIGN KEY (approved_by_id) REFERENCES users(id)
);
```

## 📊 Sample Data

15 realistic sample expenses included:
- **Total Amount**: KES 358,500
- **Approved**: 11 expenses
- **Pending**: 4 expenses
- **Categories**: All 9 categories represented
- **Payment Methods**: All 4 methods used
- **Branches**: Distributed across all branches

## 🛠️ Installation & Setup

### 1. Database Migration
```bash
python manage.py migrate expenses
```

### 2. Create Sample Data (Optional)
```bash
python create_sample_expenses.py
```

### 3. Verify Installation
```bash
python verify_expenses.py
```

### 4. Access the System
- Navigate to: `http://your-domain/expenses/`
- Login with staff credentials
- Start managing expenses!

## 📖 Documentation Files

| File | Purpose |
|------|---------|
| `EXPENSES_README.md` | This file - Quick overview |
| `EXPENSES_FEATURE_DOCUMENTATION.md` | Complete technical documentation |
| `EXPENSES_USER_GUIDE.md` | Step-by-step user instructions |
| `EXPENSES_IMPLEMENTATION_SUMMARY.md` | Implementation details & statistics |

## 🧪 Testing

### Manual Testing
1. Create a new expense
2. Edit the expense
3. Submit for approval
4. Login as manager
5. Approve/reject the expense
6. View analytics
7. Export to Excel
8. Test all filters

### Verification Script
```bash
python verify_expenses.py
```

## 🎨 UI Screenshots

### Expenses List
- Summary widgets showing totals
- Advanced filters
- Sortable table
- Pagination
- Export button

### Add/Edit Form
- Clean, organized form
- File upload for receipts
- Branch and loan selection
- Validation messages

### Expense Detail
- Complete expense information
- Approval status
- Receipt viewer
- Action buttons

### Analytics Dashboard
- Category breakdown
- Branch breakdown
- Monthly trends
- Visual representations

## 🔒 Security Features

- ✅ CSRF protection
- ✅ Permission-based access
- ✅ Branch-level filtering
- ✅ File upload validation
- ✅ SQL injection prevention
- ✅ XSS protection

## 📈 Performance

- Database indexes on key fields
- Optimized queries with select_related
- Pagination for large datasets
- Efficient filtering
- Fast page loads

## 🌐 Browser Support

- ✅ Chrome (latest)
- ✅ Firefox (latest)
- ✅ Safari (latest)
- ✅ Edge (latest)
- ✅ Mobile browsers

## 📱 Mobile Support

Fully responsive design works on:
- 📱 Smartphones
- 📱 Tablets
- 💻 Laptops
- 🖥️ Desktops

## 🔮 Future Enhancements

Potential features for future versions:
1. Budget management
2. Recurring expenses
3. Multi-level approvals
4. Email notifications
5. Advanced charts
6. Expense policies
7. Vendor management
8. Reimbursements
9. PDF reports
10. Mobile app

## 🐛 Troubleshooting

### Issue: Can't see Expenses menu
**Solution**: Check your user role. Only staff and above can access.

### Issue: Can't approve expenses
**Solution**: Only managers and admins can approve. Check your role.

### Issue: Receipt upload fails
**Solution**: Check file size and format. Use PDF or images only.

### Issue: Can't edit expense
**Solution**: Only pending expenses can be edited.

## 📞 Support

For help:
1. Check the [User Guide](EXPENSES_USER_GUIDE.md)
2. Review [Technical Documentation](EXPENSES_FEATURE_DOCUMENTATION.md)
3. Contact your system administrator
4. Email: support@branchbusinessadvance.co.ke

## 📝 Changelog

### Version 1.0 (November 29, 2024)
- ✅ Initial release
- ✅ Complete expense management
- ✅ Approval workflow
- ✅ Analytics dashboard
- ✅ Export functionality
- ✅ 15 sample expenses
- ✅ Full documentation

## 👨‍💻 Development

### Tech Stack
- **Backend**: Django 4.x
- **Database**: MySQL/MariaDB
- **Frontend**: HTML5, TailwindCSS, Bootstrap 5
- **Icons**: Font Awesome 6

### Code Structure
```
expenses/
├── models.py          # Expense model
├── views.py           # 9 views
├── forms.py           # 2 forms
├── urls.py            # URL patterns
├── admin.py           # Admin config
└── migrations/        # Database migrations

templates/expenses/
├── expenses_list.html
├── expense_form.html
├── expense_detail.html
├── expense_approve.html
├── expense_reject.html
├── expense_confirm_delete.html
├── pending_approvals.html
└── expense_analytics.html
```

## 🎓 Learning Resources

- Django Documentation: https://docs.djangoproject.com/
- TailwindCSS: https://tailwindcss.com/
- Bootstrap 5: https://getbootstrap.com/
- Font Awesome: https://fontawesome.com/

## 📄 License

Part of HAVEN GRAZURI VESTMENT LIMITEDsystem.
© 2024 HAVEN GRAZURI Advance. All rights reserved.

## ✅ Status

**Status**: ✅ Production Ready
**Version**: 1.0
**Last Updated**: November 29, 2024
**Tested**: ✅ Yes
**Documented**: ✅ Yes

---

## 🎉 Get Started Now!

1. Read the [User Guide](EXPENSES_USER_GUIDE.md)
2. Login to the system
3. Navigate to **Expenses**
4. Start tracking your expenses!

**Happy Expense Tracking! 💰**
