# Reports Implementation Logic

This note documents how reporting works in the app, with a focus on the cashbook report and the data flows that support it.

## Overview
Reports are generated from persisted operational data (cashbook entries, invoices, receipts, etc.). The report layer:
1. Validates input (date ranges, cashbook selection).
2. Queries the transactional tables for a defined period.
3. Computes opening balances, running balances, and totals.
4. Renders results in HTML and PDF variants.

## Cashbook Report Logic
The cashbook report is driven by `cashbook_entries` and uses:
- A pre-period aggregation to compute the opening balance.
- A period query to fetch transactions and compute running balance.

High-level steps:
1. Resolve the selected cashbook and its currency.
2. Calculate opening balance:
   - Sum receipts before `date_from`.
   - Sum payments/transfers before `date_from`.
   - Opening balance = receipts - payments.
3. Fetch in-period entries ordered by date and id.
4. Build running balance:
   - For each entry, inflow = receipt amount, outflow = payment/transfer amount.
   - running += inflow - outflow.
5. Compute totals:
   - Total receipts, total payments, closing balance.
6. Render in the report view and PDF template.

## Data Dependencies
The report logic depends on these tables:
- `cashbook_entries` (primary data source)
- `cashbooks` (context for selected cashbook)
- `clients` (optional, for labeling)
- `matters` (optional, for labeling)
- `currencies` (optional, for display)

If any optional relations are missing, the report should degrade gracefully (e.g., show "N/A").

## Key Inputs
Cashbook report expects:
- `cashbook_account` (cashbook id)
- `date_from`
- `date_to`

These inputs are validated before report generation.

## Output Variants
- HTML report view for in-app rendering.
- PDF view for download with the same data payload.

## Notes and Assumptions
- Transaction types are treated as:
  - `receipt` => inflow
  - `payment` / `transfer` => outflow
- Data integrity relies on foreign keys in `cashbook_entries`.
- Running balance is computed in-memory from ordered entries.
