# Reports with Drill-Down — Planning & Implementation

QuickBooks-style summary/detail report pairs for the Brix Accounting API.

**Status:** Planning draft  
**Related docs:** [api/reports.md](./api/reports.md), [api/journal-entries.md](./api/journal-entries.md), [api/sales-transactions.md](./api/sales-transactions.md), [api/purchase-transactions.md](./api/purchase-transactions.md)

---

## Goals

1. Add **16 report endpoints** (8 summary + 8 detail pairs) with a consistent drill-down contract.
2. Reuse existing services where possible (`ProfitAndLossService`, `BalanceSheetService`, `StockValuationService`, `BuildsAgingReport`).
3. Keep business rules in `*Service` classes; controllers stay thin.
4. Every new behavior ships with a feature test and an update to `docs/api/reports.md`.
5. **No breaking changes** to existing report routes or response shapes — see [Non-breaking implementation guide](#non-breaking-implementation-guide).

---

## Drill-down model

### Summary → Detail flow

```text
Summary report                    Detail report (or flag)
─────────────────────────────────────────────────────────
Customer Balance Summary    →     Customer Balance Detail
Vendor Balance Summary      →     Vendor Balance Detail
Profit and Loss             →     Profit and Loss Detail
Balance Sheet               →     Balance Sheet Detail
Sales by Customer Summary   →     Sales by Customer Detail
Sales by Product Summary    →     Sales by Product Detail
Expenses by Vendor Summary  →     Expenses by Vendor Detail
Inventory Valuation Summary →     Inventory Valuation Detail
```

### API conventions

| Convention | Rule |
|------------|------|
| Base path | `GET /api/v1/reports/{report-slug}` |
| Auth | `auth:sanctum`, `company` middleware |
| Response envelope | `{ "data": { ... } }` |
| Amounts | Strings, 4 decimal places (`"118.0000"`) |
| Drill-down link | Each summary row includes `detail_url` (relative path with query params) |
| Detail filter | Detail endpoints accept the same date params plus entity filter (`customer_id`, `vendor_id`, `account_id`, `item_id`) |
| Zero rows | Summary supports `include_zero_balances` where applicable |
| Pagination | Detail endpoints paginate when row count can be large (`per_page`, max 100) |

### Alternative: embed detail in one response

AR/AP aging already nests documents in one call. For GL-heavy reports, prefer **separate detail endpoints** to avoid huge payloads. Inventory valuation may use `include_layers=true` on the summary route (existing pattern).

---

## Route map (proposed)

```text
GET /api/v1/reports/customer-balance-summary
GET /api/v1/reports/customer-balance-detail

GET /api/v1/reports/vendor-balance-summary
GET /api/v1/reports/vendor-balance-detail

GET /api/v1/reports/profit-and-loss              ← exists; add detail_url per account
GET /api/v1/reports/profit-and-loss-detail       ← new

GET /api/v1/reports/balance-sheet                ← exists; add detail_url per account
GET /api/v1/reports/balance-sheet-detail         ← new

GET /api/v1/reports/sales-by-customer-summary
GET /api/v1/reports/sales-by-customer-detail

GET /api/v1/reports/sales-by-product-summary
GET /api/v1/reports/sales-by-product-detail

GET /api/v1/reports/expenses-by-vendor-summary
GET /api/v1/reports/expenses-by-vendor-detail

GET /api/v1/reports/inventory-valuation-summary  ← alias/wrapper of stock-value
GET /api/v1/reports/inventory-valuation-detail   ← layers + optional movements
```

**Backward compatibility:** Keep `GET /reports/inventory/stock-value` as an alias to `inventory-valuation-summary` (or redirect internally).

---

## Shared infrastructure (build first)

| Component | Location | Purpose |
|-----------|----------|---------|
| `AccountBalanceQuery` | `Financials/Support/` | Single GL aggregation for P&L, balance sheet, detail reports |
| `ReportDrillDown` | `Financials/Support/` | Helper to build `detail_url` strings |
| `BuildsSubLedgerBalanceReport` | `Financials/Concerns/` | Shared customer/vendor balance summary logic |
| `ResolvesJournalSource` | `Financials/Concerns/` | Map `reference_transaction_id` → invoice/bill/payment source (reuse from `JournalEntryResource`) |
| Base `ReportRequest` | `Financials/Requests/` | Shared `as_of` / `start_date` / `end_date` / `include_zero_balances` validation |

### Phase 0 checklist

- [ ] `AccountBalanceQuery` + unit/feature coverage via refactored trial balance / P&L (no behavior change)
- [ ] `ReportDrillDown` helper
- [ ] Extend existing `profit-and-loss` and `balance-sheet` responses with `detail_url` on each account row
- [ ] Register new routes in `routes/api/financials.php` and `routes/api/inventory.php`

---

## Implementation phases

| Phase | Reports | Module | Effort |
|-------|---------|--------|--------|
| **1** | Customer/Vendor balance summary + detail | Sales, Purchasing, Financials | Medium |
| **2** | P&L detail, Balance sheet detail | Financials | Medium |
| **3** | Sales by customer/product summary + detail | Sales | Medium |
| **4** | Expenses by vendor summary + detail | Purchasing | Medium |
| **5** | Inventory valuation summary + detail | Inventory | Low (mostly rename + extend) |

---

## Non-breaking implementation guide

Follow these rules on every phase so existing clients, tests, and integrations keep working.

### Golden rules

| Rule | Why |
|------|-----|
| **Add routes; never remove or rename** | Clients may hard-code paths like `/reports/trial-balance` and `/reports/inventory/stock-value` |
| **Add response fields only** | New keys (`detail_url`, `source_url`) are safe; renaming or removing keys breaks parsers |
| **New query params must be optional** | Existing calls without new params must behave exactly as before |
| **No database migrations for reports** | Reports are read-only aggregations over existing tables |
| **Refactor internals, not contracts** | Extract `AccountBalanceQuery` behind existing services; public JSON shape unchanged until explicitly extended |
| **One PR = one phase** | Easier rollback; existing test suite stays green per merge |

### What is already live (do not break)

These endpoints and shapes are in production docs and feature tests — treat them as frozen unless **adding** optional fields:

```text
GET /api/v1/reports/trial-balance
GET /api/v1/reports/balance-sheet
GET /api/v1/reports/profit-and-loss
GET /api/v1/reports/ar-aging
GET /api/v1/reports/ap-aging
GET /api/v1/reports/gross-profit-summary
GET /api/v1/reports/payment-method-summary
GET /api/v1/reports/inventory/stock-value
GET /api/v1/reports/inventory/low-stock
GET /api/v1/journal-entries
GET /api/v1/journal-entries/{id}
```

**Regression suite to run before every merge:**

```bash
php artisan test --filter=TrialBalanceReportTest
php artisan test --filter=BalanceSheetReportTest
php artisan test --filter=ProfitAndLossReportTest
php artisan test --filter=AgingReportTest
php artisan test --filter=StockValuationReportTest
```

---

### Strategy 1 — New endpoints only (zero risk to existing clients)

All **summary/detail pairs that do not exist yet** are pure additions:

- `customer-balance-summary` / `customer-balance-detail`
- `vendor-balance-summary` / `vendor-balance-detail`
- `profit-and-loss-detail`
- `balance-sheet-detail`
- `sales-by-customer-*`, `sales-by-product-*`
- `expenses-by-vendor-*`
- `inventory-valuation-summary` / `inventory-valuation-detail`

**How to implement:**

1. Add new route in `routes/api/financials.php` or `routes/api/inventory.php` — do not change existing route definitions.
2. Add new `*Service` class; do not alter posting, payment, or ledger write paths.
3. Add new Form Request; do not loosen validation on existing requests.
4. Add new feature test file; leave existing report tests untouched except where asserting new optional fields.

```php
// routes/api/financials.php — ADD only
Route::prefix('reports')->group(function () {
    // existing routes unchanged …
    Route::get('customer-balance-summary', [ReportController::class, 'customerBalanceSummary']);
    Route::get('customer-balance-detail', [ReportController::class, 'customerBalanceDetail']);
});
```

Existing clients that never call the new URLs are unaffected.

---

### Strategy 2 — Extend existing endpoints (additive fields only)

Only these existing reports gain **new optional keys**:

| Endpoint | Additive change | Safe for old clients? |
|----------|-----------------|----------------------|
| `profit-and-loss` | `detail_url` on each account in `income.accounts[]` and `expenses.accounts[]` | Yes — clients ignore unknown JSON keys |
| `balance-sheet` | `detail_url` on each account in `assets`, `liabilities`, `equity` | Yes |
| `inventory/stock-value` | `detail_url` on each item (optional) | Yes |

**Do not:**

- Rename `net_income` → `net_profit`
- Move `accounts` from `income.accounts` to a flat list
- Change amount formatting (must stay 4-decimal strings)
- Change default date behavior for `as_of`, `start_date`, `end_date`
- Remove `is_balanced`, `totals`, or section nesting

**Implementation pattern:**

```php
// ProfitAndLossService — append field; do not restructure
$entry = [
    'account_id'       => (int) $row->id,
    // … existing keys unchanged …
    'amount'           => number_format($amount, 4, '.', ''),
    'detail_url'       => ReportDrillDown::profitAndLossDetail($row->id, $startDate, $endDate),
];
```

**Test both shapes in the same file:**

```php
// Existing assertion still passes
$response->assertJsonPath('data.net_income', '50.0000');

// New assertion documents additive field
$response->assertJsonPath('data.income.accounts.0.detail_url', fn ($url) => str_contains($url, 'profit-and-loss-detail'));
```

---

### Strategy 3 — Alias routes instead of replacing

For inventory valuation, **do not remove** `stock-value`.

```php
// Both routes call the same controller method or shared service
Route::get('inventory/stock-value', [InventoryReportController::class, 'stockValue']);
Route::get('inventory-valuation-summary', [InventoryReportController::class, 'stockValue']);
```

| Approach | Use when |
|----------|----------|
| **Same handler** | Response body must be identical (recommended for `stock-value` alias) |
| **Thin wrapper** | New name adds `detail_url` but old route omits it for strict backward compat |
| **Never redirect 301** | API clients expect 200 + JSON, not redirects |

If the new summary name needs `detail_url` but the old route must stay byte-identical:

```php
public function stockValue(StockValuationRequest $request): JsonResponse
{
    $data = $this->stockValuation->generate(/* … */, includeDetailUrls: false);
    return response()->json(['data' => $data]);
}

public function inventoryValuationSummary(StockValuationRequest $request): JsonResponse
{
    $data = $this->stockValuation->generate(/* … */, includeDetailUrls: true);
    return response()->json(['data' => $data]);
}
```

---

### Strategy 4 — Internal refactors without API changes

When extracting `AccountBalanceQuery` from `ProfitAndLossService` / `TrialBalanceService`:

1. Run existing feature tests **before** refactor (baseline green).
2. Refactor service to delegate to shared query class.
3. Run same tests **after** — JSON output must match exactly (`assertJson` or `assertExactJson` on `data` if stable).
4. Do not change SQL semantics (date filters, account types, rounding).

```text
Before: ProfitAndLossService → inline DB::table(...)
After:  ProfitAndLossService → AccountBalanceQuery → same array shape out
```

If a refactor changes a penny due to rounding order, **stop** and fix — that is a breaking change for reporting clients.

---

### Strategy 5 — Keep overlapping reports separate

New balance reports **complement** aging; they do not replace it.

| Report | Keep | Reason |
|--------|------|--------|
| `ar-aging` | Yes | Clients rely on bucket columns (`days_1_30`, etc.) |
| `customer-balance-summary` | New | Simpler total-only view + different drill-down UX |
| `ap-aging` | Yes | Same for payables |
| `vendor-balance-summary` | New | Same |

Do not fold aging into balance summary or delete aging routes.

---

### Strategy 6 — Detail endpoints and pagination

New detail endpoints may paginate; existing list endpoints keep their defaults.

| Endpoint | Pagination | Breaking if changed? |
|----------|------------|----------------------|
| `journal-entries` | `per_page` default 50 | Yes — do not change default |
| `profit-and-loss-detail` (new) | `per_page` default 50 | N/A — new endpoint |
| `customer-balance-detail` (new) | Optional; nest under customers if small | N/A |

Use the same `per_page` max (100) as journal-entries for consistency.

---

### Strategy 7 — Auth, middleware, and policies

New report routes must use the **same middleware stack** as existing reports:

```php
Route::middleware(['auth:sanctum', 'company'])->group(function () {
    Route::prefix('reports')->group(function () { /* … */ });
});
```

- Do not tighten role middleware on existing report routes.
- New reports: match `ar-aging` / `profit-and-loss` access (all authenticated company users per `features-list.md`).
- Authorize via existing policies where applicable (`viewAny` on `Invoice`, `Bill`, `Item`, `JournalEntry`).

---

### Strategy 8 — Documentation without breaking contracts

1. **Document new endpoints** in `docs/api/reports.md` — append sections, do not rewrite existing endpoint docs in ways that imply removed fields.
2. Mark additive fields with *(added v1.x)* in docs when clients track versions.
3. Update `docs/features-list.md` — add rows, keep existing rows.
4. Cross-link from `sales-transactions.md` — add drill-down table rows, keep `journal-entries` links.

---

### Strategy 9 — Deprecation (future only)

If a route is ever retired (not in this plan):

1. Announce in docs; keep route working for **at least one release**.
2. Add `Deprecation` response header or `meta.deprecated` in JSON — never silent removal.
3. `inventory/stock-value` → prefer alias pattern indefinitely unless product explicitly deprecates.

**This plan does not deprecate any current route.**

---

### Per-phase non-breaking checklist

Copy into each PR description.

#### Phase 0 (shared infrastructure)

- [ ] Existing report tests pass with no assertion changes
- [ ] `AccountBalanceQuery` output matches previous inline queries (spot-check totals)
- [ ] `detail_url` added only where documented; old routes omit it if alias requires identical body

#### Phase 1 (customer/vendor balance)

- [ ] New routes only; `ar-aging` / `ap-aging` tests unchanged
- [ ] `ar-aging` JSON shape untouched

#### Phase 2 (P&L / balance sheet detail)

- [ ] `profit-and-loss` and `balance-sheet` tests still pass
- [ ] New `detail_url` keys are additive assertions only
- [ ] `profit-and-loss-detail` does not alter `ProfitAndLossService` totals

#### Phase 3 (sales reports)

- [ ] Invoice list/show APIs unchanged
- [ ] Sales hub (`/sales-transactions`) unchanged

#### Phase 4 (expense reports)

- [ ] Bill list/show APIs unchanged
- [ ] Purchase hub unchanged

#### Phase 5 (inventory valuation)

- [ ] `stock-value` response identical when called without new params
- [ ] `include_layers` behavior on `stock-value` unchanged
- [ ] `low-stock` endpoint untouched

---

### Client integration notes (share with frontend)

Clients can adopt drill-down incrementally:

1. **No changes required** — existing report screens keep working.
2. **Optional** — read `detail_url` from summary rows and navigate or fetch detail.
3. **Optional** — call new summary/detail pairs for new UI only.
4. **Ignore unknown fields** — all JSON parsers should tolerate extra keys (standard for REST evolution).

Example progressive rollout:

```text
Sprint 1: Ship customer-balance-summary in new UI panel only
Sprint 2: Wire detail_url → customer-balance-detail drawer
Sprint 3: Add detail_url to existing P&L screen (old screen still works without it)
```

---

## Report specifications

---

### 1. Customer Balance Summary

**Purpose:** Total amount each customer owes (open receivables).

**Endpoint:** `GET /api/v1/reports/customer-balance-summary`

**Query parameters**

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `as_of` | date | today | Cutoff date (invoices with `txn_date <= as_of` and open balance) |
| `include_zero_balances` | boolean | false | Include customers with zero balance |
| `customer_id` | integer | — | Optional single-customer filter |

**Data source**

- `invoices` where `status IN (OPEN, PARTIAL)` and `balance > 0`
- Optionally cross-check `customers.balance` (denormalized); report should compute from invoices for accuracy
- Exclude `DRAFT`, `PAID`, `VOIDED`

**Response outline**

```json
{
  "data": {
    "as_of": "2026-06-30",
    "totals": { "balance": "236.0000", "customer_count": 2 },
    "customers": [
      {
        "customer_id": 1,
        "display_name": "John Doe Corp",
        "balance": "236.0000",
        "open_invoice_count": 2,
        "detail_url": "/api/v1/reports/customer-balance-detail?customer_id=1&as_of=2026-06-30"
      }
    ]
  }
}
```

**Service:** `Sales\Services\CustomerBalanceSummaryService`  
**Request:** `Financials\Requests\CustomerBalanceSummaryRequest` (or Sales-owned)  
**Test:** `tests/Feature/CustomerBalanceReportTest.php`

**Drill-down:** `detail_url` → Customer Balance Detail

---

### 2. Customer Balance Detail

**Purpose:** Open invoices (and optional credits) for one or all customers.

**Endpoint:** `GET /api/v1/reports/customer-balance-detail`

**Query parameters**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `as_of` | date | No | Same as summary |
| `customer_id` | integer | No | Filter to one customer; omit for all |
| `per_page` | integer | No | Default 50, max 100 |

**Data source**

- `invoices` + `customers` (eager load)
- Each row: invoice header fields only (not line items)

**Response outline**

```json
{
  "data": {
    "as_of": "2026-06-30",
    "totals": { "balance": "236.0000" },
    "customers": [
      {
        "customer_id": 1,
        "display_name": "John Doe Corp",
        "balance": "236.0000",
        "invoices": [
          {
            "invoice_id": 1,
            "invoice_number": "INV-0001",
            "txn_date": "2026-06-10",
            "due_date": "2026-07-10",
            "total_amount": "118.0000",
            "balance": "118.0000",
            "status": "OPEN",
            "source_url": "/api/v1/invoices/1"
          }
        ]
      }
    ]
  }
}
```

**Further drill-down:** `source_url` → `GET /invoices/{id}` (full document + lines)

**Service:** `Sales\Services\CustomerBalanceDetailService`  
**Reuse:** Similar to `ArAgingService` but without aging buckets; consider shared `BuildsSubLedgerBalanceReport` trait

---

### 3. Vendor Balance Summary

**Purpose:** Total amount owed to each vendor (open payables).

**Endpoint:** `GET /api/v1/reports/vendor-balance-summary`

**Query parameters**

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `as_of` | date | today | Cutoff date |
| `include_zero_balances` | boolean | false | Include vendors with zero balance |
| `vendor_id` | integer | — | Optional single-vendor filter |

**Data source**

- `bills` where `status IN (OPEN, PARTIAL)` and `balance > 0`
- Exclude `DRAFT`, `PAID`, `VOIDED`

**Response outline**

```json
{
  "data": {
    "as_of": "2026-06-30",
    "totals": { "balance": "590.0000", "vendor_count": 1 },
    "vendors": [
      {
        "vendor_id": 1,
        "display_name": "Acme Suppliers",
        "balance": "590.0000",
        "open_bill_count": 1,
        "detail_url": "/api/v1/reports/vendor-balance-detail?vendor_id=1&as_of=2026-06-30"
      }
    ]
  }
}
```

**Service:** `Purchasing\Services\VendorBalanceSummaryService`  
**Test:** `tests/Feature/VendorBalanceReportTest.php`

---

### 4. Vendor Balance Detail

**Purpose:** Open bills per vendor.

**Endpoint:** `GET /api/v1/reports/vendor-balance-detail`

**Query parameters:** `as_of`, `vendor_id`, `per_page` (same pattern as customer detail)

**Data source:** `bills` + `vendors`

**Response outline**

```json
{
  "data": {
    "as_of": "2026-06-30",
    "totals": { "balance": "590.0000" },
    "vendors": [
      {
        "vendor_id": 1,
        "display_name": "Acme Suppliers",
        "balance": "590.0000",
        "bills": [
          {
            "bill_id": 1,
            "bill_number": "BILL-0001",
            "txn_date": "2026-06-11",
            "due_date": "2026-07-11",
            "total_amount": "590.0000",
            "balance": "590.0000",
            "status": "OPEN",
            "source_url": "/api/v1/bills/1"
          }
        ]
      }
    ]
  }
}
```

**Service:** `Purchasing\Services\VendorBalanceDetailService`

---

### 5. Profit and Loss (enhance existing)

**Purpose:** Income and expense by account for a period. **Already implemented.**

**Endpoint:** `GET /api/v1/reports/profit-and-loss`

**Enhancement:** Add `detail_url` on each account row.

**Response addition (per account)**

```json
{
  "account_id": 7,
  "account_number": "4000",
  "name": "Sales Revenue",
  "account_type": "INCOME",
  "account_sub_type": "SALES_REVENUE",
  "amount": "100.0000",
  "detail_url": "/api/v1/reports/profit-and-loss-detail?account_id=7&start_date=2026-06-01&end_date=2026-06-30"
}
```

**No new service** — extend `ProfitAndLossService` only.

---

### 6. Profit and Loss Detail

**Purpose:** Journal entry lines that make up each income/expense account for the period.

**Endpoint:** `GET /api/v1/reports/profit-and-loss-detail`

**Query parameters**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `start_date` | date | No | Defaults to start of month |
| `end_date` | date | No | Defaults to today |
| `account_id` | integer | No | Filter to one account; omit for all P&L accounts |
| `per_page` | integer | No | Paginate transactions when `account_id` omitted |

**Data source**

- `journal_entry_lines` → `journal_entries` → `accounts`
- Filter: `account_type IN (INCOME, EXPENSE)`, `txn_date` in range
- Resolve source document via `journal_entries.reference_transaction_id` and `JournalEntryResource` source logic

**Response outline**

```json
{
  "data": {
    "start_date": "2026-06-01",
    "end_date": "2026-06-30",
    "accounts": [
      {
        "account_id": 7,
        "account_number": "4000",
        "name": "Sales Revenue",
        "account_type": "INCOME",
        "amount": "100.0000",
        "transactions": [
          {
            "journal_entry_id": 1,
            "je_number": "JE-0001",
            "txn_date": "2026-06-10",
            "posting_type": "CREDIT",
            "amount": "100.0000",
            "description": "Invoice INV-0001",
            "source": {
              "type": "INVOICE",
              "id": 1,
              "number": "INV-0001",
              "transaction_id": 5
            },
            "source_url": "/api/v1/invoices/1"
          }
        ]
      }
    ]
  }
}
```

**Service:** `Financials\Services\ProfitAndLossDetailService`  
**Test:** `tests/Feature/ProfitAndLossDetailReportTest.php`

**Drill-down chain:** Account total → JE lines → source document (`/invoices`, `/bills`, `/payments`)

---

### 7. Balance Sheet (enhance existing)

**Purpose:** Assets, liabilities, equity as of a date. **Already implemented.**

**Endpoint:** `GET /api/v1/reports/balance-sheet`

**Enhancement:** Add `detail_url` on each account row (including synthetic Current Period Earnings with `account_id: null` — link to P&L detail for earnings breakdown).

---

### 8. Balance Sheet Detail

**Purpose:** All journal lines contributing to each balance-sheet account through `as_of`.

**Endpoint:** `GET /api/v1/reports/balance-sheet-detail`

**Query parameters**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `as_of` | date | No | Defaults to today |
| `account_id` | integer | No | Filter to one account |
| `per_page` | integer | No | Pagination |

**Data source**

- `journal_entry_lines` for accounts where `account_type IN (ASSET, LIABILITY, EQUITY)`
- `txn_date <= as_of`
- Include **running balance** per line (optional but useful for GL-style drill-down)

**Response outline**

```json
{
  "data": {
    "as_of": "2026-06-30",
    "accounts": [
      {
        "account_id": 3,
        "account_number": "1000",
        "name": "CASH",
        "account_type": "ASSET",
        "amount": "118.0000",
        "transactions": [
          {
            "journal_entry_id": 1,
            "je_number": "JE-0001",
            "txn_date": "2026-06-10",
            "posting_type": "DEBIT",
            "amount": "118.0000",
            "running_balance": "118.0000",
            "source": { "type": "INVOICE", "id": 1, "number": "INV-0001" },
            "source_url": "/api/v1/invoices/1"
          }
        ]
      }
    ]
  }
}
```

**Service:** `Financials\Services\BalanceSheetDetailService`  
**Test:** `tests/Feature/BalanceSheetDetailReportTest.php`

**Note:** Current Period Earnings is not a real account — drill-down should redirect to P&L detail for the same implicit date range or document as-of logic.

---

### 9. Sales by Customer Summary

**Purpose:** Total sales revenue per customer for a period.

**Endpoint:** `GET /api/v1/reports/sales-by-customer-summary`

**Query parameters**

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `start_date` | date | start of month | Period start |
| `end_date` | date | today | Period end |
| `include_zero_balances` | boolean | false | Include customers with no sales in period |

**Data source**

- `invoices` where `status IN (OPEN, PARTIAL, PAID)` and `txn_date` in range
- Sum `total_amount` per `customer_id` (sub-ledger view)
- **Alternative (GL view):** sum credits on `SALES_REVENUE` accounts where `entity_type = CUSTOMER` — prefer invoice-based for operational report consistency with QBO

**Response outline**

```json
{
  "data": {
    "start_date": "2026-06-01",
    "end_date": "2026-06-30",
    "totals": { "sales": "500.0000", "customer_count": 3 },
    "customers": [
      {
        "customer_id": 1,
        "display_name": "John Doe Corp",
        "invoice_count": 2,
        "sales": "300.0000",
        "detail_url": "/api/v1/reports/sales-by-customer-detail?customer_id=1&start_date=2026-06-01&end_date=2026-06-30"
      }
    ]
  }
}
```

**Service:** `Sales\Services\SalesByCustomerSummaryService`  
**Test:** `tests/Feature/SalesByCustomerReportTest.php`

---

### 10. Sales by Customer Detail

**Purpose:** Individual invoices (or invoice lines) per customer in the period.

**Endpoint:** `GET /api/v1/reports/sales-by-customer-detail`

**Query parameters:** `start_date`, `end_date`, `customer_id`, `per_page`

**Data source:** `invoices` filtered by customer and date; optionally include `lines` when `include_lines=true`

**Response outline**

```json
{
  "data": {
    "start_date": "2026-06-01",
    "end_date": "2026-06-30",
    "customers": [
      {
        "customer_id": 1,
        "display_name": "John Doe Corp",
        "sales": "300.0000",
        "invoices": [
          {
            "invoice_id": 1,
            "invoice_number": "INV-0001",
            "txn_date": "2026-06-10",
            "total_amount": "118.0000",
            "source_url": "/api/v1/invoices/1",
            "lines": [
              {
                "line_number": 1,
                "item_id": 1,
                "description": "Widget",
                "qty": "2.0000",
                "unit_price": "50.0000",
                "line_total": "100.0000"
              }
            ]
          }
        ]
      }
    ]
  }
}
```

**Service:** `Sales\Services\SalesByCustomerDetailService`

---

### 11. Sales by Product/Service Summary

**Purpose:** Total sales per item (product/service) for a period.

**Endpoint:** `GET /api/v1/reports/sales-by-product-summary`

**Query parameters**

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `start_date` | date | start of month | Period start |
| `end_date` | date | today | Period end |
| `item_id` | integer | — | Optional filter |
| `include_zero_balances` | boolean | false | Include items with no sales |

**Data source**

- `invoice_lines` joined to `invoices`
- Invoice `status IN (OPEN, PARTIAL, PAID)`, `txn_date` in range
- Group by `item_id`; sum `line_total`, sum `qty`
- Lines with `item_id = null` group as `"Non-item line"` or use `description`

**Response outline**

```json
{
  "data": {
    "start_date": "2026-06-01",
    "end_date": "2026-06-30",
    "totals": { "sales": "450.0000", "qty": "9.0000" },
    "items": [
      {
        "item_id": 1,
        "sku": "WDG-001",
        "name": "Widget",
        "qty_sold": "9.0000",
        "sales": "450.0000",
        "detail_url": "/api/v1/reports/sales-by-product-detail?item_id=1&start_date=2026-06-01&end_date=2026-06-30"
      }
    ]
  }
}
```

**Service:** `Sales\Services\SalesByProductSummaryService`  
**Test:** `tests/Feature/SalesByProductReportTest.php`

---

### 12. Sales by Product/Service Detail

**Purpose:** Each sale line for an item in the period.

**Endpoint:** `GET /api/v1/reports/sales-by-product-detail`

**Query parameters:** `start_date`, `end_date`, `item_id`, `per_page`

**Data source:** `invoice_lines` → `invoices` → `customers`

**Response outline**

```json
{
  "data": {
    "start_date": "2026-06-01",
    "end_date": "2026-06-30",
    "items": [
      {
        "item_id": 1,
        "sku": "WDG-001",
        "name": "Widget",
        "qty_sold": "9.0000",
        "sales": "450.0000",
        "lines": [
          {
            "invoice_id": 1,
            "invoice_number": "INV-0001",
            "txn_date": "2026-06-10",
            "customer_id": 1,
            "customer_name": "John Doe Corp",
            "qty": "2.0000",
            "unit_price": "50.0000",
            "line_total": "100.0000",
            "source_url": "/api/v1/invoices/1"
          }
        ]
      }
    ]
  }
}
```

**Service:** `Sales\Services\SalesByProductDetailService`

---

### 13. Expenses by Vendor Summary

**Purpose:** Total purchases/expenses per vendor for a period.

**Endpoint:** `GET /api/v1/reports/expenses-by-vendor-summary`

**Query parameters**

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `start_date` | date | start of month | Period start |
| `end_date` | date | today | Period end |
| `vendor_id` | integer | — | Optional filter |
| `include_zero_balances` | boolean | false | Include vendors with no bills |

**Data source**

- `bills` where `status IN (OPEN, PARTIAL, PAID)` and `txn_date` in range
- Sum `total_amount` per `vendor_id`
- Exclude `DRAFT`, `VOIDED`

**Response outline**

```json
{
  "data": {
    "start_date": "2026-06-01",
    "end_date": "2026-06-30",
    "totals": { "expenses": "1200.0000", "vendor_count": 2 },
    "vendors": [
      {
        "vendor_id": 1,
        "display_name": "Acme Suppliers",
        "bill_count": 3,
        "expenses": "800.0000",
        "detail_url": "/api/v1/reports/expenses-by-vendor-detail?vendor_id=1&start_date=2026-06-01&end_date=2026-06-30"
      }
    ]
  }
}
```

**Service:** `Purchasing\Services\ExpensesByVendorSummaryService`  
**Test:** `tests/Feature/ExpensesByVendorReportTest.php`

---

### 14. Expenses by Vendor Detail

**Purpose:** Individual bills (and lines) per vendor in the period.

**Endpoint:** `GET /api/v1/reports/expenses-by-vendor-detail`

**Query parameters:** `start_date`, `end_date`, `vendor_id`, `per_page`, optional `include_lines`

**Data source:** `bills` + `bill_lines`

**Response outline**

```json
{
  "data": {
    "start_date": "2026-06-01",
    "end_date": "2026-06-30",
    "vendors": [
      {
        "vendor_id": 1,
        "display_name": "Acme Suppliers",
        "expenses": "800.0000",
        "bills": [
          {
            "bill_id": 1,
            "bill_number": "BILL-0001",
            "txn_date": "2026-06-11",
            "total_amount": "590.0000",
            "source_url": "/api/v1/bills/1",
            "lines": [
              {
                "line_number": 1,
                "item_id": 1,
                "description": "Widget stock",
                "qty": "10.0000",
                "unit_price": "50.0000",
                "line_total": "500.0000"
              }
            ]
          }
        ]
      }
    ]
  }
}
```

**Service:** `Purchasing\Services\ExpensesByVendorDetailService`

---

### 15. Inventory Valuation Summary

**Purpose:** FIFO inventory value per item (company total). **Mostly exists** as `stock-value`.

**Endpoint:** `GET /api/v1/reports/inventory-valuation-summary`  
**Alias:** `GET /api/v1/reports/inventory/stock-value` (keep for backward compatibility)

**Query parameters**

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `item_id` | integer | — | Optional filter |
| `active_only` | boolean | true | Active items only |
| `include_zero_qty` | boolean | false | Include zero-qty items |

**Data source:** `inventory_cost_layers` + `items` (existing `StockValuationService` without layers)

**Response outline**

```json
{
  "data": {
    "valuation_method": "FIFO",
    "totals": { "qty_on_hand": "14.0000", "total_value": "650.0000" },
    "items": [
      {
        "item_id": 1,
        "sku": "WDG-001",
        "name": "Widget",
        "qty_on_hand": "9.0000",
        "average_unit_cost": "50.0000",
        "total_value": "450.0000",
        "detail_url": "/api/v1/reports/inventory-valuation-detail?item_id=1"
      }
    ]
  }
}
```

**Service:** Reuse `Inventory\Services\StockValuationService` (add `detail_url` in controller or service wrapper)

---

### 16. Inventory Valuation Detail

**Purpose:** FIFO cost layers per item (and optional recent movements).

**Endpoint:** `GET /api/v1/reports/inventory-valuation-detail`

**Query parameters**

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `item_id` | integer | — | Required or strongly recommended |
| `include_movements` | boolean | false | Include recent hub rows for the item |

**Data source**

- `inventory_cost_layers` where `qty_remaining > 0`
- Optional: `InventoryTransactionHubService` filtered by `item_id`

**Response outline**

```json
{
  "data": {
    "valuation_method": "FIFO",
    "items": [
      {
        "item_id": 1,
        "sku": "WDG-001",
        "name": "Widget",
        "qty_on_hand": "9.0000",
        "total_value": "450.0000",
        "layers": [
          {
            "layer_id": 1,
            "date_acquired": "2026-06-01",
            "qty_remaining": "9.0000",
            "unit_cost": "50.0000",
            "layer_value": "450.0000",
            "source_type": "BILL",
            "source_id": 1
          }
        ],
        "movements_url": "/api/v1/inventory-transactions?item_id=1"
      }
    ]
  }
}
```

**Service:** Extend `StockValuationService` or new `InventoryValuationDetailService`  
**Test:** Extend `StockValuationReportTest` or add `InventoryValuationDetailReportTest`

---

## File checklist (per report pair)

### Financials module

| File | Reports |
|------|---------|
| `Controllers/Api/ReportController.php` | Wire all Financials endpoints |
| `Services/ProfitAndLossDetailService.php` | P&L detail |
| `Services/BalanceSheetDetailService.php` | Balance sheet detail |
| `Services/CustomerBalanceSummaryService.php` | Could live in Sales — see below |
| `Concerns/BuildsSubLedgerBalanceReport.php` | Customer + vendor balance |
| `Support/AccountBalanceQuery.php` | GL detail reports |
| `Support/ReportDrillDown.php` | URL builder |
| `Requests/*Request.php` | One per endpoint |

### Sales module

| File | Reports |
|------|---------|
| `Services/CustomerBalanceSummaryService.php` | Customer balance |
| `Services/CustomerBalanceDetailService.php` | Customer balance detail |
| `Services/SalesByCustomerSummaryService.php` | Sales by customer |
| `Services/SalesByCustomerDetailService.php` | Sales by customer detail |
| `Services/SalesByProductSummaryService.php` | Sales by product |
| `Services/SalesByProductDetailService.php` | Sales by product detail |

### Purchasing module

| File | Reports |
|------|---------|
| `Services/VendorBalanceSummaryService.php` | Vendor balance |
| `Services/VendorBalanceDetailService.php` | Vendor balance detail |
| `Services/ExpensesByVendorSummaryService.php` | Expenses by vendor |
| `Services/ExpensesByVendorDetailService.php` | Expenses by vendor detail |

### Inventory module

| File | Reports |
|------|---------|
| `Controllers/Api/InventoryReportController.php` | Valuation summary + detail routes |
| `Services/InventoryValuationDetailService.php` | Optional wrapper |

---

## Relationship to existing reports

| Existing | New equivalent | Action |
|----------|----------------|--------|
| `GET /reports/ar-aging` | Customer balance + aging buckets | Keep both; aging adds buckets, balance summary is simpler |
| `GET /reports/ap-aging` | Vendor balance + aging buckets | Keep both |
| `GET /reports/profit-and-loss` | P&L summary | Enhance with `detail_url` |
| `GET /reports/balance-sheet` | Balance sheet summary | Enhance with `detail_url` |
| `GET /reports/inventory/stock-value` | Inventory valuation summary | Alias or deprecate later |
| `GET /journal-entries?account_id=` | P&L / BS detail | Detail reports wrap this with grouping + source resolution |

---

## Testing strategy

Each report test should:

1. Seed company, accounts, customer/vendor, items.
2. Post invoice(s) and bill(s) with known amounts.
3. Call summary endpoint → assert totals and `detail_url` present.
4. Call detail endpoint with filter from summary → assert nested rows match.
5. Assert `company_id` scoping (second company sees nothing).

**Test files to add**

- `CustomerBalanceReportTest.php`
- `VendorBalanceReportTest.php`
- `ProfitAndLossDetailReportTest.php`
- `BalanceSheetDetailReportTest.php`
- `SalesByCustomerReportTest.php`
- `SalesByProductReportTest.php`
- `ExpensesByVendorReportTest.php`
- `InventoryValuationDetailReportTest.php`

---

## Documentation updates

After each phase:

- [ ] Add section to `docs/api/reports.md` (or split into `docs/api/reports/` per category if file grows too large)
- [ ] Update `docs/features-list.md` Financial Reports table
- [ ] Cross-link from `sales-transactions.md` and `purchase-transactions.md` drill-down tables

---

## Open decisions

| # | Question | Recommendation |
|---|----------|----------------|
| 1 | Invoice-based vs GL-based sales/expense reports? | **Invoice/bill sub-ledger** for operational reports; GL detail for accountant reports |
| 2 | Separate detail routes vs `?include_detail=true` on summary? | **Separate routes** for GL and sales reports; optional `include_lines` on detail only |
| 3 | Paginate summary endpoints? | No — paginate detail only when unfiltered |
| 4 | Include unapplied payment credits in customer balance? | Phase 2 — start with open invoice balances only |
| 5 | Controller: one `ReportController` vs module controllers? | **Financials `ReportController`** for cross-cutting GL; module controllers for sales/purchasing/inventory reports registered in same route group |

---

## Suggested first PR (Phase 1)

1. `BuildsSubLedgerBalanceReport` trait
2. Customer balance summary + detail
3. Vendor balance summary + detail
4. Tests + `reports.md` sections
5. Complete [Phase 1 non-breaking checklist](#per-phase-non-breaking-checklist); run existing `AgingReportTest` before merge

This delivers immediate QBO parity for receivables/payables drill-down with low risk and no migrations.
