# Invoice Tool Implementation Guide
## Overview
The `list_invoices` tool has been successfully implemented for the Updation MCP system. This tool provides comprehensive invoice listing functionality with role-based access control, advanced filtering, pagination, and dashboard filters.
## Implementation Summary
### Files Created
1. **`/src/mcp_server/tools/invoices/__init__.py`**
- Package initialization for invoice tools
- Exports the `register_list_invoices` function
2. **`/src/mcp_server/tools/invoices/list_invoices.py`**
- Main implementation of the `list_invoices` tool
- Handles API calls to Laravel endpoint: `GET /api/v2/invoice-details`
- Implements comprehensive filtering and pagination
3. **`/test_list_invoices.sh`**
- Test script for validating the tool functionality
- Includes 7 different test scenarios
### Files Modified
1. **`/src/core/security.py`**
- Added `list_invoices` to `AUTHENTICATED_TOOLS`
- All authenticated users can now access this tool
2. **`/src/core/domain_policies.py`**
- Policy already existed for `list_invoices`
- Configured for `INVOICE_TABLE` page type
- Read-only operation, no entity required
## Tool Configuration
### Tool Policy
```python
"list_invoices": ToolContextPolicy(
allowed_page_types={PageType.INVOICE_TABLE},
requires_entity=False,
read_only=True
)
```
### RBAC Configuration
- **Access Level**: `AUTHENTICATED_TOOLS`
- **All authenticated users** can access this tool
- Role-based data filtering is handled by Laravel API backend
### Page Context Requirements
- **Allowed Page**: `INVOICE_TABLE` only
- **Entity Required**: No
- **Operation Type**: Read-only
## API Integration
### Laravel Endpoint
- **URL**: `/api/v2/invoice-details`
- **Method**: GET
- **Controller**: `InvoiceDetailController@show`
- **Required Permission**: `invoice.index`
### Authentication
- Uses Bearer token from user context
- Token automatically injected by orchestrator
- Cached for 15 minutes for performance
## Supported Parameters
### Pagination
- `page` (int): Page number (default: 1)
- `page_size` (int|string): Items per page or 'all' (default: 50)
### Sorting
- `sort` (string): Sort direction - 'ascend' or 'descend' (default: 'descend')
- `sort_by` (string): Column to sort by
- Valid values: `due_date`, `invoice_amount`, `created_at`, `invoice_name`, `invoice_no`, `variance`, `rate`
### Status Filters
- `status` (string): Comma-separated invoice statuses
- Valid values: `verification`, `waiting_for_ai`, `pending`, `approved`, `rejected`, `duplicate`, `posted`, `rtp_downloaded`, `paid`
- `invoice_status` (string): Alternative status filter
### Dashboard Filters
- `filter_type` (string): Dashboard filter type
- `total_outstanding`: All outstanding invoices
- `due_today`: Invoices due today or overdue
- `due_30days`: Invoices due within next 30 days
- `total_over_due`: Invoices past due date
### Search/Filter Parameters
- `filter_by_vendor_name` (string): Filter by vendor name
- `invoice_no` (string): Filter by invoice number
- `range_due_date` (string): Date range (format: MM-DD-YYYY,MM-DD-YYYY)
- `department` (string): Filter by department ID or name
- `rate` (string): Filter by rate
- `invoice_amount` (string): Filter by invoice amount
- `filter_by_location` (string): Filter by organization/location
- `document_type_name` (string): Filter by document type
- `assigned_to_me` (boolean): Show only invoices assigned to current user
### Global Admin Filters
- `glo_platform_id` (string): Platform ID filter (e.g., "100" or "all")
- `glo_dealership_id` (string): Dealership ID filter (e.g., "200" or "all")
## Response Structure
### Success Response
```json
{
"success": true,
"message": "Invoices retrieved successfully",
"invoices": [
{
"id": 12345,
"invoice_no": "INV-2024-001",
"invoice_date": "01-15-2024",
"invoice_amount": "5000.00",
"vendor_id": 456,
"vendor_name": "ABC Supplies Inc",
"status": "Approved",
"status_css": {
"color": "#2FBD4E",
"background": "#D5F2DC",
"icon": "CheckOutlined"
},
"due_date": "02-15-2024",
"po_number": "PO-2024-100",
"organization_id": 789,
"invoice_location": "Main Office",
"department_name": "Operations",
"variance": "100.00",
"rate": "4.5",
"contract_linked": true,
"invoice_flag": false,
"document_type_name": "Invoice",
"contract_required": "Y",
"is_checkbox": 1,
"is_paid": 0,
"created_at": "2024-01-15T10:30:00.000000Z"
}
],
"dashboard_data": {
"total_invoice_amount": 0,
"todays_due_invoices_count": 0,
"last30days_invoice_amount": 0,
"total_variance": 0,
"mark_as_paid": 0,
"statuses": ""
},
"pagination": {
"current_page": 1,
"total": 500,
"per_page": 50,
"last_page": 10,
"from": 1,
"to": 50
},
"grid_filters": {
"saved_filters": [],
"default_columns": []
}
}
```
## Role-Based Access Control
### Hierarchy-Based Filtering
The Laravel API automatically filters invoices based on user role:
1. **Global Admin (Role ID: 1)**
- Access: ALL invoices across ALL organizations
- Scope: No restrictions
- Can use `glo_platform_id` and `glo_dealership_id` filters
2. **Organization Admin (Role ID: 2)**
- Access: Own organization + all child platforms + all child dealerships
- Scope: Hierarchical (3 levels)
3. **Platform Admin (Role ID: 3)**
- Access: Own platform(s) + child dealerships
- Scope: Hierarchical (2 levels)
4. **Dealership Admin (Role ID: 4)**
- Access: Only own dealership(s)
- Scope: Self only (leaf node)
5. **Reporting Only (Role ID: 5)**
- Access: Read-only based on assigned organizations
- Scope: Limited to assigned organizations
## Usage Examples
### Example 1: Basic Listing
```
User: "List all invoices"
Context: invoice_table page
Result: First page of invoices (50 items)
```
### Example 2: Filter by Status
```
User: "Show me approved invoices"
Context: invoice_table page
Tool Call: list_invoices(status="approved")
```
### Example 3: Dashboard Filter
```
User: "Show invoices due today"
Context: invoice_table page
Tool Call: list_invoices(filter_type="due_today")
```
### Example 4: Filter by Vendor
```
User: "Show invoices from ABC Supplies"
Context: invoice_table page
Tool Call: list_invoices(filter_by_vendor_name="ABC Supplies")
```
### Example 5: Date Range
```
User: "Show invoices due between 01-01-2024 and 01-31-2024"
Context: invoice_table page
Tool Call: list_invoices(range_due_date="01-01-2024,01-31-2024")
```
### Example 6: Pagination
```
User: "Show me page 2 with 25 items per page"
Context: invoice_table page
Tool Call: list_invoices(page=2, page_size=25)
```
## Testing
### Running Tests
```bash
# Set your bearer token
export BEARER_TOKEN="your_actual_token"
# Run the test script
./test_list_invoices.sh
```
### Test Scenarios Covered
1. Basic invoice listing (first page)
2. Filter by status (approved)
3. Dashboard filter (due today)
4. Filter by vendor name
5. Pagination (page 2, 25 items)
6. Date range filter
7. Wrong page context (should fail)
## Error Handling
### API Errors
- Logs error details with trace ID
- Returns structured error response
- Includes error message and details
### Validation Errors
- Page number validated (minimum 1)
- Page size validated (1-1000 or 'all')
- Sort direction validated (ascend/descend)
- Sort by column validated against allowed list
- Filter type validated against allowed values
### Exception Handling
- All exceptions caught and logged
- User-friendly error messages returned
- Trace ID included for debugging
## Performance Optimizations
1. **Bearer Token Caching**
- 15-minute cache TTL
- 90%+ cache hit rate
- Reduces API calls to Laravel
2. **Selective Field Loading**
- Only essential fields included in response
- Reduces payload size
3. **Pagination Support**
- Prevents loading all invoices at once
- Configurable page size
- Support for 'all' when needed
## Logging
All operations are logged with structured logging:
```python
logger.info(
"list_invoices_started",
user_id=user_context.user_id,
role=user_context.role.name,
page=page,
page_size=page_size,
status=status,
filter_type=filter_type,
trace_id=trace_id
)
```
## Next Steps
### Potential Enhancements
1. **Additional Invoice Tools**
- `get_invoice_details` - Get details for a specific invoice
- `approve_invoice` - Approve an invoice
- `reject_invoice` - Reject an invoice
- `export_invoices` - Export invoices to CSV/Excel
2. **Vendor-Specific Invoice Tools**
- `get_vendor_invoices` - Get all invoices for a specific vendor
- Already documented in the API spec
3. **Bulk Operations**
- `bulk_approve_invoices` - Already in policy, needs implementation
- `bulk_reject_invoices`
- `bulk_export_invoices`
## Troubleshooting
### Tool Not Available
- Check page context is `invoice_table`
- Verify user is authenticated
- Check RBAC configuration
### No Data Returned
- Verify user has access to invoices
- Check filter parameters
- Review Laravel API logs
- Verify bearer token is valid
### Permission Denied
- Check user has `invoice.index` permission in Laravel
- Verify role assignment
- Check organization/platform/dealership assignment
## References
- **API Documentation**: See comprehensive API documentation provided
- **Tool Development Template**: `/TOOL_DEVELOPMENT_TEMPLATE.md`
- **RBAC Guide**: `/RBAC_GUIDE.md`
- **Architecture Flow**: `/ARCHITECTURE_FLOW.md`