| 1 | **SQL Views** |
| 2 | |
| 3 | The application uses SQL VIEWs to simplify common queries and improve maintainability: |
| 4 | |
| 5 | #### `invoice_summary` |
| 6 | |
| 7 | - **Purpose**: Shows invoice info with client and company names |
| 8 | - **What it does**: Joins Invoice, Client, and Tenant tables to display invoice details with client name and company name |
| 9 | - **Usage**: Makes it easier to see which client each invoice belongs to without writing complex JOINs |
| 10 | |
| 11 | ```sql |
| 12 | SELECT * FROM invoice_summary WHERE invoice_status = 'PENDING'; |
| 13 | ``` |
| 14 | |
| 15 | #### `client_totals` |
| 16 | |
| 17 | - **Purpose**: Shows total amounts for each client |
| 18 | - **What it does**: Groups invoices by client and calculates total paid, pending, overdue amounts |
| 19 | - **Usage**: Provides a quick overview of each client's financial status |
| 20 | |
| 21 | ```sql |
| 22 | SELECT * FROM client_totals ORDER BY total_invoiced DESC; |
| 23 | ``` |
| 24 | |
| 25 | #### API Integration |
| 26 | |
| 27 | The views are used in API endpoints to provide simplified data access: |
| 28 | |
| 29 | - `src/app/api/clients/summary/route.ts`: Uses `client_totals` view for client financial summaries |
| 30 | - `src/app/api/invoices/totals/route.ts`: Uses `invoice_summary` view for invoice analytics |
| 31 | |
| 32 | #### Benefits |
| 33 | |
| 34 | - **Simpler queries**: No need to write complex JOINs every time |
| 35 | - **Consistent data**: Same calculation logic everywhere |
| 36 | - **Easier to maintain**: Change the view, all queries get updated |
| 37 | - **Better performance**: Database can optimize the view |
| 38 | |
| 39 | The views are implemented in `sql/03_business_views.sql`. |
| 40 | |
| 41 | |