# Brix Accounting API — Bills

API reference for vendor bills (accounts payable documents with line items, inventory receipt, and voiding).

**Attachments:** Upload vendor PDFs before save using [staged-attachments.md](./staged-attachments.md), or attach after create via [attachments.md](./attachments.md).

---

## Base URL

```
{BASE_URL}/api/v1/bills
```

| Environment | Example |
|-------------|---------|
| Local | `http://127.0.0.1:8000/api/v1/bills` |

---

## Authentication

All endpoints require:

| Header | Value |
|--------|-------|
| `Authorization` | `Bearer {token}` |
| `Accept` | `application/json` |
| `Content-Type` | `application/json` | On `POST`, `PUT`, `PATCH` |

Obtain a token via `POST /api/v1/login`. See [auth-and-users.md](./auth-and-users.md).

**Middleware:** `auth:sanctum`, `company` — the user must belong to a company. Records are automatically scoped to that company.

---

## Role permissions

| Action | ADMIN | ACCOUNTANT | MANAGER | CASHIER |
|--------|-------|------------|---------|---------|
| List bills | ✓ | ✓ | ✓ | ✓ |
| View bill | ✓ | ✓ | ✓ | ✓ |
| Create bill | ✓ | ✓ | ✗ | ✗ |
| Update bill | ✓ | ✓* | ✗ | ✗ |
| Cost correction preview | ✓ | ✗ | ✗ | ✗ |
| Receive bill | ✓ | ✓** | ✗ | ✗ |
| Void bill | ✓ | ✗ | ✗ | ✗ |
| Delete bill | ✓ | ✗ | ✗ | ✗ |

\* **Update:** allowed when `status` = `DRAFT`, or when `status` = `OPEN`, `received_into_inventory` = `true`, with no payments applied (`balance` = `total_amount` and no linked bill payment allocations). For **unconsumed** stock, open edits reverse and repost GL/inventory automatically (amend). For **consumed** stock, only **ADMIN** may update via **cost correction** (delta GL + FIFO + invoice COGS); see [Cost correction](#cost-correction-consumed-inventory) below.

\** Receive is only allowed when `received_into_inventory` = `false`.

---

## Bill lifecycle

```
DRAFT  ──RECEIVE──▶  OPEN  ──bill payments──▶  PARTIAL / PAID
  │                    │
  │                    ├──PATCH (unpaid, no consumption)──▶ OPEN (amended)
  │                    ├──PATCH (unpaid, consumed, ADMIN)──▶ OPEN (cost corrected)
  │                    └──VOID (ADMIN)──▶  VOIDED
  │
  └──DELETE (ADMIN)──▶ removed
```

| Status | Description |
|--------|-------------|
| `DRAFT` | Editable; no GL or inventory impact; `balance` = `0` |
| `OPEN` | Received; A/P balance set; FIFO cost layers created for inventory lines; editable while unpaid (amend) |
| `PARTIAL` | Partially paid via vendor bill payments; not editable |
| `PAID` | Fully paid; not editable |
| `VOIDED` | Reversed; inventory and GL restored (if stock not yet consumed) |

---

## Bill object

| Field | Type | Read-only | Description |
|-------|------|-----------|-------------|
| `id` | integer | Yes | Primary key |
| `vendor_id` | integer | Yes* | Linked vendor |
| `bill_number` | string | **Yes** | Auto-generated (`BILL-0001`, `BILL-0002`, …) |
| `vendor_bill_number` | string \| null | No** | Vendor's invoice/reference number (QuickBooks Bill No.) |
| `vendor_snapshot` | object | **Yes** | Frozen vendor details at create time |
| `txn_date` | date | No** | Bill date |
| `due_date` | date | No** | Payment due date |
| `sub_total` | decimal string | **Yes** | Sum of line nets (after discounts, before tax) |
| `discount_total` | decimal string | **Yes** | Sum of line discounts |
| `tax_total` | decimal string | **Yes** | Sum of line taxes |
| `total_amount` | decimal string | **Yes** | `sub_total` + `tax_total` |
| `balance` | decimal string | **Yes** | `0` while draft; `total_amount` after receive; reduced by payments |
| `status` | string | **Yes** | `DRAFT`, `OPEN`, `PARTIAL`, `PAID`, `VOIDED` |
| `received_into_inventory` | boolean | **Yes** | `true` after receive; inventory + GL posted |
| `memo` | string \| null | No** | Printed on bill |
| `vendor` | object | Yes | Nested vendor when loaded |
| `lines` | array | No** | Line items (replaced entirely on update when sent) |
| `cogs_true_ups` | array | Yes | Backorder COGS adjustments from receive (when oversold stock was cleared) |
| `created_at` | datetime | Yes | — |
| `updated_at` | datetime | Yes | — |

\* `vendor_id` is set on create and cannot be changed via update.

\** Editable only while `status` = `DRAFT`.

**Defaults on create:** `status` = `DRAFT`, `balance` = `0`, `received_into_inventory` = `false`, `bill_number` auto-assigned per company.

### Bill line object

| Field | Type | Read-only | Description |
|-------|------|-----------|-------------|
| `id` | integer | Yes | Primary key |
| `item_id` | integer \| null | No* | Catalog item (optional for non-inventory expenses) |
| `item_snapshot` | object \| null | **Yes** | Frozen item name/sku/price at bill time |
| `qty` | decimal string | No* | Quantity purchased |
| `unit_price` | decimal string | No* | Cost per unit |
| `discount_percent` | decimal string | No* | Line discount % (0–100) |
| `tax_code_id` | integer \| null | No* | Tax code applied |
| `tax_amount` | decimal string | **Yes** | Calculated tax |
| `line_total` | decimal string | **Yes** | Net + tax for the line |
| `description` | string \| null | No* | Optional line detail for display on bill |
| `notes` | string \| null | No* | Line-level notes (max 500) |
| `item` | object | Yes | Nested item when loaded (on show/receive/void) |

\* Set via `lines` array on create/update (draft only).

### Tax calculation

Totals are calculated server-side:

1. `gross` = `qty` × `unit_price`
2. `net` = `gross` − (`gross` × `discount_percent` / 100)
3. If a taxable tax code applies (and item is taxable or absent): `tax_amount` = `net` × `rate_percent` / 100
4. `line_total` = `net` + `tax_amount`

On **receive**, inventory FIFO cost and `standard_cost` use net unit cost (`unit_price` after `discount_percent`), not the pre-discount list price. See [Receive side effects](#receive-side-effects).

**Tax code resolution per line:**

- Tax is calculated only when the company has `tax_enabled` = `true` (see [company.md](./company.md)). When `false`, all line tax is zero, `tax_code_id` is cleared, and sending `lines.*.tax_code_id` returns `422`.
- Use `lines.*.tax_code_id` when provided (must exist in the same company — see [tax-codes.md](./tax-codes.md)).
- Otherwise, if the item is `taxable`, the first active taxable tax code for the company is used.
- Lines without an item can still have tax if `tax_code_id` is explicitly set.

### Bill number generation

`bill_number` is assigned automatically on create (not sent in the request):

- Format: `BILL-` + 4-digit sequence → `BILL-0001`, `BILL-0002`, …
- Scoped per company (tenant isolation).
- Unique per company via database constraint.

### Vendor bill number

`vendor_bill_number` is optional and user-supplied — the reference printed on the vendor's invoice (QuickBooks **Bill No.** / `DocNumber`):

- Max 50 characters; blank strings are stored as `null`.
- Unique per `(company_id, vendor_id)` when set (including voided bills).
- Editable only while `status` = `DRAFT`; frozen after receive.

### Receive side effects

`POST /bills/{id}/receive` (when `received_into_inventory` = `false`):

- Clears open **backorders** for each inventory line first (QBO-style COGS true-up when actual cost differs from the estimate used at oversell).
- Creates FIFO inventory cost layers for any **remaining** quantity after backorder clearance (increases `qty_on_hand`).
- FIFO layer `unit_cost`, backorder clearance actual cost, and item `standard_cost` use the line’s **net unit cost** after `discount_percent`: `unit_price × (1 − discount_percent / 100)`. The stored `unit_price` / `discount_percent` on the bill line stay as entered (vendor document).
- Posts GL: Inventory Dr, Input VAT Dr (if tax), Accounts Payable Cr; plus a separate COGS true-up JE when needed.
- **Rounds header `total_amount` to currency precision (2 decimal places)** before GL posting. Sub-cent line sums are absorbed into `tax_total` (or `sub_total` when there is no tax) so debits equal credits. Line `line_total` values remain at 4 decimal places; draft preview may differ from the received header by up to 1¢ until receive.
- Sets `received_into_inventory` = `true`.
- If `status` was `DRAFT`, sets `status` = `OPEN`, `balance` = `total_amount`, and increases the vendor's running `balance` by `total_amount`. 

`POST /bills/{id}/void` (ADMIN, `OPEN` + received only):

- Restores backorder clearances and reverses COGS true-up journal entries when applicable.
- Removes FIFO cost layers and decrements `qty_on_hand` (fails if any layer was partially consumed).
- Reverses all auto-generated journal entries linked to the bill transaction.
- Each reversal JE is dated per **that entry's** `txn_date` when the entry falls in an open period; **today** when the entry's `txn_date` is on or before [company `books_closed_through`](./company.md). See [GL reversal dating](#gl-reversal-dating-void-and-amend) below.
- Sets `status` = `VOIDED`, `balance` = `0`, `received_into_inventory` = `false`, and decreases the vendor's running `balance` by the bill's remaining balance.

**Open unpaid amend** (`PATCH` while `OPEN`, no payments):

- Unreceives (reverses all auto-generated JEs + inventory), applies changes, re-receives at the (possibly updated) `bill.txn_date`.
- Each reversed JE uses **per-entry** dating (main receive JE and any COGS true-up JEs keep their original period when open).
- `txn_date` cannot be moved into a closed period (`422`).

### GL reversal dating (void and amend)

Company setting [`books_closed_through`](./company.md) marks the last day of the closed fiscal year (`NULL` = no close).

| Entry `txn_date` vs close | Reversal JE `txn_date` | Amend re-receive JE `txn_date` |
|---------------------------|------------------------|--------------------------------|
| After `books_closed_through` (open year) | Same as that entry's `txn_date` | `bill.txn_date` after edit |
| On or before `books_closed_through` (closed year) | Today (correction in current period) | `bill.txn_date` after edit |

Received bills store `active_journal_entry_id` pointing at the main receive posting JE. Void and amend still reverse **all** auto-generated JEs on the bill transaction (including COGS true-ups); per-entry dating ensures true-up reversals land in their original period when open.

---

# Endpoints

## List bills

```
GET /bills
```

Returns bills for the authenticated user's company. Default sort is `txn_date` descending. By default, each bill includes `lines` and `vendor`. Results are paginated.

### Query parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `vendor_id` | integer | — | Limit to one vendor (must belong to the same company) |
| `status` | string | — | Comma-separated statuses: `DRAFT`, `OPEN`, `PARTIAL`, `PAID`, `VOIDED` |
| `balance_min` | decimal | — | Minimum outstanding `balance` (inclusive) |
| `start_date` | date | — | Minimum `txn_date` (inclusive) |
| `end_date` | date | — | Maximum `txn_date` (inclusive); must be on or after `start_date` |
| `search` | string | — | Matches `bill_number`, `vendor_bill_number`, or vendor `display_name` (max 100 chars) |
| `is_overdue` | boolean | — | When `true`, only `OPEN`/`PARTIAL` bills with `balance > 0` and `due_date` before today |
| `include_lines` | boolean | `true` | When `false`, omits `lines` from each bill |
| `include_vendor` | boolean | `true` | When `false`, omits nested `vendor` object |
| `sort` | string | `-txn_date` | Sort field. Prefix with `-` for descending. Allowed: `txn_date`, `due_date`, `bill_number`, `vendor_bill_number`, `total_amount`, `balance`, `status`, `created_at`, `vendor_name` |
| `per_page` | integer | `25` | Page size (1–100) |
| `page` | integer | `1` | Page number |

Filters are combined with **AND** logic. `is_overdue` can be used together with `status` and other filters.

### Example request

```http
GET /api/v1/bills?vendor_id=2&status=OPEN,PARTIAL&balance_min=0.01&start_date=2026-01-01&end_date=2026-06-30&search=BILL-00&is_overdue=1&include_lines=0&include_vendor=1&sort=due_date&per_page=100&page=1
Authorization: Bearer {token}
Accept: application/json
```

### Success response — `200 OK`

```json
{
  "data": [
    {
      "id": 1,
      "vendor_id": 2,
      "bill_number": "BILL-0001",
      "vendor_bill_number": "INV-8842",
      "vendor_snapshot": {
        "name": "Acme Suppliers",
        "email": null,
        "phone": null,
        "address": null
      },
      "txn_date": "2026-06-11T00:00:00.000000Z",
      "due_date": "2026-07-11T00:00:00.000000Z",
      "sub_total": "500.0000",
      "discount_total": "0.0000",
      "tax_total": "90.0000",
      "total_amount": "590.0000",
      "balance": "0.0000",
      "status": "DRAFT",
      "received_into_inventory": false,
      "memo": "PO #123",
      "created_at": "2026-06-11T10:00:00.000000Z",
      "updated_at": "2026-06-11T10:00:00.000000Z",
      "vendor": {
        "id": 2,
        "display_name": "Acme Suppliers"
      },
      "lines": [
        {
          "id": 1,
          "item_id": 5,
          "item_snapshot": {
            "name": "Test Widget",
            "sku": "WDG-001",
            "unit_price": "100.0000"
          },
          "qty": "10.0000",
          "unit_price": "50.0000",
          "discount_percent": "0.00",
          "tax_code_id": 1,
          "tax_amount": "90.0000",
          "line_total": "590.0000",
          "description": null,
          "notes": null
        }
      ]
    }
  ],
  "links": {
    "first": "http://127.0.0.1:8000/api/v1/bills?page=1",
    "last": "http://127.0.0.1:8000/api/v1/bills?page=1",
    "prev": null,
    "next": null
  },
  "meta": {
    "current_page": 1,
    "per_page": 25,
    "total": 1,
    "last_page": 1
  }
}
```

---

## Create bill

```
POST /bills
```

Creates a **draft** bill with line items. Totals are calculated automatically.

### Request body

| Field | Type | Required | Rules |
|-------|------|----------|-------|
| `vendor_id` | integer | **Yes** | Must exist in the same company |
| `vendor_bill_number` | string | No | Max 50; unique per vendor within the company |
| `txn_date` | date | **Yes** | Bill date |
| `due_date` | date | **Yes** | Must be ≥ `txn_date` |
| `memo` | string | No | Printed on bill |
| `lines` | array | **Yes** | Min 1 line |
| `lines.*.item_id` | integer | No | Must exist in the same company if provided |
| `lines.*.qty` | number | **Yes** | Min `0.0001` |
| `lines.*.unit_price` | number | **Yes** | Min `0` |
| `lines.*.discount_percent` | number | No | 0–100; default `0` |
| `lines.*.tax_code_id` | integer | No | Must exist in the same company |
| `lines.*.description` | string | No | Max 1000 chars; informational only |
| `lines.*.notes` | string | No | Max 500 characters |
| `staged_attachment_ids` | integer[] | No | Link staged uploads atomically on create; see [staged-attachments.md](./staged-attachments.md) |
| `include_on_send_by_id` | object | No | Invoice only — ignored on bills |

### Example request

```http
POST /api/v1/bills
Authorization: Bearer {token}
Content-Type: application/json

{
  "vendor_id": 2,
  "vendor_bill_number": "INV-8842",
  "txn_date": "2026-06-11",
  "due_date": "2026-07-11",
  "memo": "PO #123",
  "lines": [
    {
      "item_id": 5,
      "qty": 10,
      "unit_price": 50
    }
  ]
}
```

### Example with discount

```json
{
  "vendor_id": 2,
  "txn_date": "2026-06-11",
  "due_date": "2026-07-11",
  "lines": [
    {
      "item_id": 5,
      "qty": 5,
      "unit_price": 50,
      "discount_percent": 10,
      "tax_code_id": 1
    }
  ]
}
```

### Success response — `201 Created`

Draft bill in `data` (same shape as list item).

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User is not ADMIN or ACCOUNTANT |
| `422` | Validation failed |

---

## Get bill

```
GET /bills/{id}
```

Returns the bill with `lines.item` and `vendor` loaded.

### Example request

```http
GET /api/v1/bills/1
Authorization: Bearer {token}
Accept: application/json
```

### Success response — `200 OK`

Single bill object wrapped in `data`.

### Error responses

| Status | Condition |
|--------|-----------|
| `404` | Bill not found or belongs to another company |

---

## Update bill

```
PUT /bills/{id}
PATCH /bills/{id}
```

Updates a **draft** bill, or an **open unpaid received** bill. All body fields are optional.

**Draft (`DRAFT`):** line and total changes only — no GL or inventory impact until receive.

**Open unpaid, stock not sold (`OPEN`, no consumption on FIFO layers):** ACCOUNTANT or ADMIN — the API reverses FIFO layers and the journal entry, applies your changes, then receives again (full amend).

**Open unpaid, stock sold (`OPEN`, FIFO layers partially consumed):** **ADMIN only** — cost correction applies delta updates to bill lines in place, FIFO layers, sold invoice COGS (when unit price changes), and posts adjustment journal entries. Per-line **qty may decrease** when `new_qty >= sold_qty` for that line; **unsold lines may be removed** via `_remove: true` or `qty: 0`. Qty increases and `item_id` changes are blocked. See [Cost correction](#cost-correction-consumed-inventory).

**Open unpaid, stock sold, adding items (`OPEN`, consumed, payload contains new id-less lines):** **ADMIN only** — line append. New lines (rows **without** an `id`) are inserted and receipted into inventory on their own FIFO layers at the bill's original `txn_date`; a single balanced delta journal entry posts Inventory Dr, Input VAT Dr (if tax), Accounts Payable Cr for the appended amount. Existing lines and their sold invoices/COGS are **not** touched. In the same request every existing line must be sent by `id` **unchanged**; changing an existing line while appending returns `422` (do cost correction as a separate request). Blocked when the bill's `txn_date` is in a closed period. See [Appending lines](#appending-lines-consumed-inventory).

When `lines` is sent on **draft** or **full amend**, existing lines are **replaced entirely**. On **cost correction**, lines are updated in place by **bill line `id`** (order-independent); eligible unsold lines may be removed. On **line append**, existing lines are matched by `id` and left unchanged while id-less rows are added.

### Request body

| Field | Type | Required | Rules |
|-------|------|----------|-------|
| `txn_date` | date | No | — |
| `due_date` | date | No | Must be ≥ `txn_date` |
| `vendor_bill_number` | string \| null | No | Max 50; unique per vendor within the company |
| `memo` | string | No | — |
| `lines` | array | No | Min 1 line when provided; same line rules as create |
| `staged_attachment_ids` | integer[] | No | Link staged uploads atomically on update; see [staged-attachments.md](./staged-attachments.md) |

### Example request

```http
PATCH /api/v1/bills/1
Authorization: Bearer {token}
Content-Type: application/json

{
  "memo": "Updated memo",
  "lines": [
    {
      "item_id": 5,
      "qty": 5,
      "unit_price": 50,
      "discount_percent": 10
    }
  ]
}
```

### Success response — `200 OK`

Updated bill in `data` with recalculated totals. After **cost correction**, `correction_summary` is included:

| Field | Description |
|-------|-------------|
| `affected_invoice_count` | Posted invoices with COGS adjustments |
| `cogs_delta` | Total COGS change on sold qty |
| `inventory_delta` | Inventory asset change on on-hand qty and qty returns |
| `ap_delta` | Change to bill `total_amount` / vendor A/P |
| `qty_returned` | `true` when any line qty was reduced or lines were removed |
| `lines_removed` | `true` when one or more bill lines were deleted |
| `removed_line_ids` | IDs of deleted bill lines |
| `journal_entry_ids` | Auto-generated adjustment entry IDs |

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User lacks permission; bill is `PARTIAL`, `PAID`, or `VOIDED`; open bill has payments applied; ACCOUNTANT attempted cost correction on consumed stock |
| `404` | Bill not found |
| `422` | Validation failed; missing/invalid `lines[].id` on cost correction; line structure change on consumed bill; closed-period `txn_date` |

---

## Cost correction preview

```
POST /bills/{id}/correction-preview
```

Read-only impact analysis before saving a cost correction. **ADMIN only.** Same request body as [Update bill](#update-bill).

### Success response — `200 OK`

```json
{
  "data": {
    "blockers": [],
    "warnings": ["1 invoice(s) will have COGS adjusted."],
    "old_total_amount": "590.0000",
    "new_total_amount": "708.0000",
    "cogs_delta": "30.0000",
    "inventory_delta": "70.0000",
    "ap_delta": "118.0000",
    "affected_invoice_count": 1,
    "affected_invoices": [
      {
        "invoice_id": 42,
        "invoice_number": "INV-0001",
        "cogs_delta": "30.0000"
      }
    ],
    "line_impacts": [
      {
        "bill_line_id": 12,
        "old_qty": "10.0000",
        "new_qty": "6.0000",
        "sold_qty": "5.0000",
        "qty_returned": "4.0000",
        "inventory_delta": "-200.0000"
      },
      {
        "bill_line_id": 14,
        "action": "removed",
        "old_qty": "10.0000",
        "new_qty": "0.0000",
        "sold_qty": "0.0000",
        "qty_returned": "10.0000",
        "inventory_delta": "-500.0000",
        "ap_delta": "-590.0000"
      }
    ]
  }
}
```

| Field | Description |
|-------|-------------|
| `blockers` | Reasons correction cannot proceed (e.g. payment allocations linked) |
| `warnings` | Non-blocking notices (invoice count, closed-period COGS dating) |
| `line_impacts` | Per-line qty/price change preview (`sold_qty`, `qty_returned`, `inventory_delta`) |
| `line_errors` | Per-line validation errors keyed by line index (when invalid) |

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User is not ADMIN |
| `404` | Bill not found |

---

## Cost correction (consumed inventory)

When FIFO layers from a received bill have been **partially or fully sold**, `PATCH` routes to **cost correction** instead of full amend.

### Preconditions

- `status` = `OPEN`, `received_into_inventory` = `true`
- `balance` = `total_amount` (no bill payments applied)
- User is **ADMIN**
- Every `lines[]` entry **must** include `id` (bill line id from `GET /bills/{id}` → `lines[].id`); array **order does not matter**
- Payload must include **exactly one row per existing bill line** (same count, no unknown ids, no duplicate ids)
- Same `item_id` per line as stored on the bill (defense in depth)
- Send `_remove: true` or `qty: 0` on eligible unsold lines to delete them
- **Qty rules (per line):** may decrease if `new_qty >= sold_qty` from that line's FIFO layers; cannot increase; cannot change qty on lines that cleared a backorder
- **Removal rules (per line):** may remove when `sold_qty = 0` and the line did not clear a backorder; at least one line must remain on the bill

Bill line responses on consumed bills include `sold_qty`, `min_allowed_qty`, and `can_remove` to drive the UI.

### Line removal example

Bill: Item A ×10, Item B ×10, Item C ×10 → receive → invoice Item A ×5 → remove Item C (unsold):

```json
{
  "lines": [
    { "id": 42, "_remove": true, "item_id": 3 },
    { "id": 40, "item_id": 1, "qty": 10, "unit_price": 50 },
    { "id": 41, "item_id": 2, "qty": 10, "unit_price": 50 }
  ]
}
```

Line order in the array may differ from the bill display order; matching is by `id` only.

- Item A line stays at qty 10 (5 sold)
- Item C line deleted — FIFO layer removed, `qty_on_hand` for Item C returns to 0, bill total and vendor A/P decrease
- Setting `qty: 0` on an unsold line is equivalent to `_remove: true`

### Quantity return example

Bill line received 10, invoice sold 5, return 4 units to vendor by setting line qty to 6:

- Sold floor = 5 — qty 4 is rejected (`422`)
- qty 6 is allowed — layer becomes `qty_purchased` 6, `qty_remaining` 1
- Bill total and vendor A/P decrease; sold invoice COGS unchanged (unless unit price also changes)

See also [partialbilledit.md](../partialbilledit.md).

### Paid bills workflow

1. **ADMIN** unlinks payment: `PUT /bill-payments/{id}/allocations` with allocations excluding this bill (or `[]` if only bill). See [bill-payments.md](./bill-payments.md).
2. Optional: `POST /bills/{id}/correction-preview`
3. `PATCH /bills/{id}` with corrected costs
4. **ADMIN** reapplies payment via `PUT /bill-payments/{id}/allocations`

Cash GL is unchanged during unlink/relink; only sub-ledger balances move.

### Side effects

| Area | Effect |
|------|--------|
| Bill lines | Updated in place; eligible unsold lines deleted; totals recalculated |
| FIFO layers | Deleted for removed lines; `unit_cost` updated; `qty_purchased` / `qty_remaining` shrunk when qty decreases on survivors |
| Sold qty | `invoice_line_layers` + `invoice_lines.cogs_amount` updated when **unit price** changes |
| Bill GL | Delta JE on bill transaction (inventory, input VAT, A/P) — original receive JE kept |
| Invoice GL | Per-invoice COGS adjustment JE on invoice transaction |
| COGS JE date | Invoice `txn_date` when period open; **today** when invoice falls in a closed period |
| Backorder clearances | True-up amounts recalculated; prior true-up JE reversed |
| Repeated corrections | Each correction deltas from the **current** layer/consumption cost to the new bill line `unit_price` (including fully sold layers) |

### Error responses

| Status | Condition |
|--------|-----------|
| `422` | Line structure change; `blockers` from preview |

---

## Appending lines (consumed inventory)

When a received bill has stock already sold and you need to add the items that were left off the original bill, send a `PATCH /bills/{id}` whose `lines` array mixes the existing lines (each with its `id`, unchanged) and one or more **new rows without an `id`**. This routes to **line append** instead of cost correction.

### Preconditions

- `status` = `OPEN`, `received_into_inventory` = `true`
- `balance` = `total_amount` (no bill payments applied and no linked bill payment allocations)
- User is **ADMIN**
- The bill's `txn_date` is **not** in a closed period (`books_closed_through`)
- Every existing bill line is present by `id` and **unchanged** (qty, `unit_price`, `discount_percent`, `item_id`, `tax_code_id`)
- At least one new row without an `id`

### Behavior

- New lines are inserted and receipted into inventory: FIFO cost layers are created at each new line's net unit cost, `qty_on_hand` increases, open **backorders** for those items are cleared first (with COGS true-up when applicable), and `standard_cost` refreshes.
- A single balanced delta journal entry posts on the bill transaction at the bill's `txn_date`: **Inventory Dr**, **Input VAT Dr** (if tax), **Accounts Payable Cr** for the appended amount. The original receive journal entry is left intact.
- Header totals (`sub_total`, `tax_total`, `total_amount`), `balance`, and the vendor's running balance increase by the appended amount.
- **Existing lines, their FIFO layers, and sold invoice COGS are not modified.**

### FIFO ordering note

Appended layers are added at the receipt date (bill `txn_date`); they are **not** retroactively inserted ahead of sales that were already costed against earlier layers. This is intended for the "forgot to add lines from the same delivery" case. To restate cost ordering across already-sold stock, void and re-enter the documents instead.

### Example request

```http
PATCH /api/v1/bills/1
Authorization: Bearer {token}
Content-Type: application/json

{
  "lines": [
    { "id": 40, "item_id": 5, "qty": 10, "unit_price": 50 },
    { "item_id": 6, "qty": 5, "unit_price": 20 },
    { "item_id": 7, "qty": 3, "unit_price": 15 }
  ]
}
```

Line `40` is the existing (sold) line, sent unchanged. Items 6 and 7 are appended. Use [correction preview](#cost-correction-preview) to see appended-line impact before saving; appended rows appear in `line_impacts` with `action: added`.

### Success response — `200 OK`

Updated bill in `data` with recalculated totals, plus an `append_summary`:

| Field | Description |
|-------|-------------|
| `appended_line_ids` | IDs of the newly created bill lines |
| `ap_delta` | Increase to bill `total_amount` / vendor A/P |
| `inventory_delta` | Inventory asset increase (net of tax) |
| `tax_delta` | Input VAT increase |
| `journal_entry_ids` | Auto-generated append delta entry IDs |

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User is not ADMIN; bill is `PARTIAL`/`PAID` or has payments applied |
| `422` | Existing line changed while appending; closed-period `txn_date`; invalid new line |

---

## Receive bill

```
POST /bills/{id}/receive
```

Receives inventory and posts journal entries. Sets `status` = `OPEN` and `balance` = `total_amount` when receiving from draft. For each inventory line, creates a FIFO cost layer at the line `unit_price`, updates `qty_on_hand`, and refreshes the item’s `standard_cost` to that same `unit_price` (last line wins if the same item appears more than once).

### Example request

```http
POST /api/v1/bills/1/receive
Authorization: Bearer {token}
Accept: application/json
```

### Success response — `200 OK`

Received bill in `data` with `status` = `OPEN`, `received_into_inventory` = `true`, and `balance` = `total_amount`.

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User is not ADMIN/ACCOUNTANT, or bill already received |
| `404` | Bill not found |

---

## Void bill

```
POST /bills/{id}/void
```

Reverses a received bill. **ADMIN only.** Bill must be `OPEN` and `received_into_inventory` = `true`.

### Example request

```http
POST /api/v1/bills/1/void
Authorization: Bearer {token}
Accept: application/json
```

### Success response — `200 OK`

Voided bill in `data` with `status` = `VOIDED`, `balance` = `0`, `received_into_inventory` = `false`.

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User is not ADMIN, or bill is not received/open |
| `404` | Bill not found |
| `500` | Inventory from this bill has already been sold/consumed |

---

## Delete bill

```
DELETE /bills/{id}
```

Permanently removes a **draft** bill, its lines, and spine transaction. **ADMIN only.**

### Example request

```http
DELETE /api/v1/bills/1
Authorization: Bearer {token}
Accept: application/json
```

### Success response — `204 No Content`

Empty body.

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User is not ADMIN, or bill is not `DRAFT` |
| `404` | Bill not found |

---

## Validation error format — `422`

```json
{
  "message": "The vendor id field is required.",
  "errors": {
    "vendor_id": ["The vendor id field is required."]
  }
}
```

---

## Endpoint summary

| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/bills` | List all bills |
| `POST` | `/bills` | Create draft bill |
| `GET` | `/bills/{id}` | Get bill |
| `PUT`/`PATCH` | `/bills/{id}` | Update draft, amend (unconsumed), or cost-correct (consumed, ADMIN) |
| `POST` | `/bills/{id}/correction-preview` | Preview cost correction impact (ADMIN) |
| `DELETE` | `/bills/{id}` | Delete draft bill |
| `POST` | `/bills/{id}/receive` | Receive into inventory & post GL |
| `POST` | `/bills/{id}/void` | Void received bill |

---

## Frontend notes

- Workflow: **create draft → edit if needed → receive**. After receive, you may **amend** (unconsumed stock) or **cost-correct** (consumed stock, ADMIN) while `status` = `OPEN`, `received_into_inventory` = `true`, and no bill payments are linked.
- Show **Edit** when the purchase hub returns `edit` in `actions`. Show **unlink_payment** when hub returns it (ADMIN, allocations exist).
- To edit a **paid** bill: ADMIN unlinks payment → preview (optional) → `PATCH` → reallocate payment. See [Cost correction](#cost-correction-consumed-inventory).
- **Cost correction** updates sold invoice COGS and posts delta JEs; warn users about affected invoices before confirm.
- Unconsumed open amend reverses GL, FIFO layers, and vendor A/P internally — warn users that totals, inventory, and `standard_cost` change immediately.
- `bill_number`, totals, `balance`, `status`, and `received_into_inventory` are system-managed — do not send on create/update.
- `item_id` is optional on lines (e.g. freight or services without a catalog item); inventory layers are only created when `item_id` is set.
- Pre-fill `unit_price` from the item catalog but allow override per line.
- `vendor_snapshot` and `item_snapshot` preserve historical data — display these on printed/PDF bills.
- `lines.*.description` is optional free text per line; re-send when replacing `lines` on draft update.
- Record vendor payments separately via the bill payments API; allocations reduce `balance` and update status to `PARTIAL` / `PAID`. See [bill-payments.md](./bill-payments.md).
- Void will fail if any received stock has been consumed by sales (FIFO). Check inventory before voiding.
- Related docs: [vendors.md](./vendors.md), [items.md](./items.md), [accounts.md](./accounts.md), [invoices.md](./invoices.md).
