# Expense Management System

## Overview
The expense management system allows users to track and manage expenses related to legal matters. It includes automatic tax calculations, file attachments, and comprehensive reporting.

## Features

### Core Features
- ✅ Add new expenses with dropdown type selection
- ✅ Automatic tax calculation based on expense type
- ✅ Date recording for each expense
- ✅ Invoice attachment upload (10MB max)
- ✅ Search and filter functionality
- ✅ Edit and delete expenses
- ✅ Pagination for large expense lists

### Expense Type Management
- ✅ Create and manage expense types
- ✅ Configurable tax rates (0%, 6%, 13%, 23%)
- ✅ Enable/disable expense types
- ✅ Edit type details

### User Interface
- ✅ Modern, responsive design with Tailwind CSS
- ✅ Summary cards showing totals
- ✅ Filter and search capabilities
- ✅ Modal forms for adding/editing
- ✅ File upload for invoices
- ✅ Download functionality for attachments

## Quick Start Guide

### Adding Expenses from Matter Detail View
The easiest way to add expenses is directly from the matter detail page:

1. **Navigate to a Matter**: Go to any matter detail page
2. **Find the Expenses Section**: Located after the tasks section
3. **Click "Add Expense"**: This opens a modal form
4. **Fill in the Details**:
   - **Name**: Enter a descriptive name for the expense
   - **Type**: Select from dropdown (Office Supplies, Travel, etc.)
   - **Description**: Optional detailed description
   - **Amount**: Enter the amount in euros
   - **Date**: Select the expense date
   - **Invoice**: Upload invoice file (optional)
   - **Notes**: Additional notes (optional)
5. **Save**: Click "Add Expense" to save

### Using the Full Expense Manager
For more advanced features, use the dedicated expense manager:

1. **Access**: Click "View all expenses →" from matter detail
2. **Full Management**: Complete CRUD operations
3. **Advanced Filtering**: Filter by type, date range, search
4. **Type Management**: Create and manage expense types

### Global Expense Manager (Admin Only)
For comprehensive expense management across all matters and proposals:

1. **Access**: Go to Admin menu → Expense Manager
2. **Global View**: See all expenses across all matters
3. **Advanced Filtering**: Filter by user, proposal, matter, date range, type
4. **Summary Statistics**: View total expenses, tax, and counts
5. **Bulk Operations**: Manage expenses from a central location

## Database Structure

### Expense Types Table
```sql
expense_types
├── id (Primary Key)
├── uuid (Unique Identifier)
├── name (Expense Category Name)
├── description (Optional Description)
├── tax_rate (Tax Rate as Decimal)
├── is_active (Boolean)
└── timestamps
```

### Expenses Table
```sql
expenses
├── id (Primary Key)
├── uuid (Unique Identifier)
├── matter_id (Foreign Key to matters)
├── expense_type_id (Foreign Key to expense_types)
├── name (Expense Name)
├── description (Optional Description)
├── amount (Base Amount)
├── tax_amount (Calculated Tax Amount)
├── total_amount (Calculated Total Amount)
├── expense_date (Date of Expense)
├── invoice_attachment (File Path)
├── notes (Optional Notes)
├── created_by (Foreign Key to users)
└── timestamps
```

## Usage Instructions

### Adding an Expense

#### Method 1: Quick Add from Matter Detail
1. Go to any matter detail page
2. Scroll to the "Expenses" section (after tasks)
3. Click "Add Expense" button
4. Fill in the modal form
5. Click "Add Expense" to save

#### Method 2: Full Expense Manager
1. Navigate to `/matters/{matter}/expenses`
2. Click "Add New Expense" button
3. Fill in the form with all details
4. Upload invoice if needed
5. Click "Save Expense"

### Managing Expense Types
1. Access the expense manager page
2. Click "Manage Types" button
3. Add new types with appropriate tax rates
4. Edit existing types as needed
5. Toggle active/inactive status

### Filtering and Searching

#### Matter-Specific Expense Manager
- **Search**: Use the search box to find expenses by name or description
- **Type Filter**: Filter by expense type
- **Date Range**: Filter by expense date range
- **Clear Filters**: Reset all filters

#### Global Expense Manager (Admin)
- **Search**: Search across expense names, descriptions, matter subjects, and types
- **User Filter**: Filter by who created the expense
- **Matter Filter**: Filter by specific matter
- **Proposal Filter**: Filter by proposal (shows expenses for matters linked to proposals)
- **Type Filter**: Filter by expense type
- **Date Range**: Filter by expense date range
- **Clear Filters**: Reset all filters

## Tax Rates

The system supports Portuguese VAT rates:
- **0%**: Exempt items
- **6%**: Reduced rate items
- **13%**: Intermediate rate items
- **23%**: Standard rate items (default)

Tax calculations are automatic:
- **Tax Amount** = Base Amount × Tax Rate
- **Total Amount** = Base Amount + Tax Amount

## File Management

### Uploading Invoices
- **Supported Formats**: PDF, JPG, PNG, DOC, DOCX
- **Maximum Size**: 10MB per file
- **Storage**: Files stored in `storage/app/public/expenses/{matter_id}/`
- **Naming**: Files renamed with timestamp prefix

### Downloading Invoices
- Click the download icon next to any expense
- Files are served securely through Laravel's storage system

## API Endpoints

### RESTful Endpoints
```
GET    /matters/{matter}/expenses          # List expenses for specific matter
POST   /matters/{matter}/expenses          # Create expense for matter
GET    /matters/{matter}/expenses/{id}     # Show expense
PUT    /matters/{matter}/expenses/{id}     # Update expense
DELETE /matters/{matter}/expenses/{id}     # Delete expense
GET    /expenses                           # Global expense manager (admin)
```

### Livewire Components
- `ExpenseManager`: Full expense management interface for specific matters
- `GlobalExpenseManager`: Global expense management across all matters
- `MatterDetail`: Integrated expense modal for quick adds

## Models

### Expense Model
```php
class Expense extends Model
{
    // Relationships
    public function matter(): BelongsTo
    public function expenseType(): BelongsTo
    public function createdBy(): BelongsTo
    
    // Scopes
    public function scopeByMatter($query, $matterId)
    public function scopeByDateRange($query, $startDate, $endDate)
    public function scopeByType($query, $typeId)
    
    // Accessors
    public function getFormattedAmountAttribute(): string
    public function getFormattedTaxAmountAttribute(): string
    public function getFormattedTotalAmountAttribute(): string
    public function getFormattedDateAttribute(): string
    
    // Calculations
    public function calculateTaxAmount(): float
    public function calculateTotalAmount(): float
}
```

### ExpenseType Model
```php
class ExpenseType extends Model
{
    // Relationships
    public function expenses(): HasMany
    
    // Scopes
    public function scopeActive($query)
    
    // Accessors
    public function getTaxRateLabelAttribute(): string
    public function getFormattedTaxRateAttribute(): string
}
```

## Calculations

### Automatic Calculations
The system automatically calculates:
- **Tax Amount**: `amount × tax_rate / 100`
- **Total Amount**: `amount + tax_amount`

### Example
```
Base Amount: €100.00
Tax Rate: 23%
Tax Amount: €23.00
Total Amount: €123.00
```

## Security

### Authentication
- All expense operations require authentication
- Users can only access expenses for matters they have permission to view

### File Security
- Files are stored outside the web root
- Access controlled through Laravel's storage system
- File type validation prevents malicious uploads

### Data Validation
- All inputs validated on both client and server side
- SQL injection protection through Eloquent ORM
- XSS protection through proper escaping

## Testing

### Running Tests
```bash
# Run all expense tests
php artisan test tests/Feature/ExpenseManagementTest.php

# Run modal tests
php artisan test tests/Feature/MatterExpenseModalTest.php

# Run specific test
php artisan test --filter="it_can_create_an_expense"
```

### Test Coverage
- ✅ Expense creation and validation
- ✅ Tax calculation accuracy
- ✅ File upload and download
- ✅ Expense type management
- ✅ Modal functionality
- ✅ CRUD operations
- ✅ Authorization checks

## Seeding

### Initial Data
The system comes with pre-seeded expense types:
- Office Supplies (23%)
- Travel Expenses (23%)
- Legal Fees (23%)
- Court Costs (0%)
- Document Processing (6%)
- Translation Services (13%)

### Running Seeders
```bash
# Run all seeders
php artisan db:seed

# Run only expense seeder
php artisan db:seed --class=ExpenseTypeSeeder
```

## Troubleshooting

### Common Issues

#### "Cannot add expense" error
- **Cause**: Not authenticated or missing permissions
- **Solution**: Log in with appropriate user account

#### File upload fails
- **Cause**: File too large or wrong format
- **Solution**: Check file size (max 10MB) and format

#### Tax calculation incorrect
- **Cause**: Expense type not selected or tax rate not set
- **Solution**: Ensure expense type is selected with correct tax rate

#### Modal not opening
- **Cause**: JavaScript errors or Livewire issues
- **Solution**: Check browser console for errors, refresh page

### Debug Mode
Enable debug mode to see detailed error messages:
```php
// In .env file
APP_DEBUG=true
```

### Logs
Check Laravel logs for detailed error information:
```bash
tail -f storage/logs/laravel.log
```

## Performance

### Optimization Tips
- Use pagination for large expense lists
- Implement caching for frequently accessed data
- Optimize database queries with proper indexing
- Use file compression for large attachments

### Database Indexes
The system includes optimized indexes:
- `expenses.matter_id` + `expenses.expense_date`
- `expenses.expense_type_id`
- `expenses.expense_date`
- `expenses.created_by`

## Future Enhancements

### Planned Features
- Export expenses to Excel/PDF
- Bulk expense import
- Expense approval workflow
- Integration with accounting systems
- Advanced reporting and analytics
- Mobile app support

### Customization
The system is designed for easy customization:
- Add new expense types
- Modify tax rates
- Customize validation rules
- Extend with additional fields 