# Brix Accounting API — Invoices

API reference for sales invoices (accounts receivable documents with line items, posting, and voiding).

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

---

## Base URL

```
{BASE_URL}/api/v1/invoices
```

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

---

## 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 invoices | ✓ | ✓ | ✓ | ✓ |
| View invoice | ✓ | ✓ | ✓ | ✓ |
| Download PDF | ✓ | ✓ | ✓ | ✓ |
| Send PDF email | ✓ | ✓ | ✗ | ✗ |
| Create invoice | ✓ | ✓ | ✗ | ✓ |
| Update invoice | ✓ | ✓* | ✗ | ✗ |
| Post invoice | ✓ | ✓* | ✗ | ✓ |
| Void invoice | ✓ | ✗ | ✗ | ✗ |
| Delete invoice | ✓ | ✗ | ✗ | ✗ |
| Copy invoice | ✓ | ✓ | ✗ | ✓ |

\* **Update:** allowed when `status` = `DRAFT`, or when `status` = `OPEN` with no payments applied (`balance` = `total_amount` and no linked customer payment allocations). Open edits reverse and repost GL/inventory automatically.

\* **Post:** only allowed when `status` = `DRAFT`.

---

## Invoice lifecycle

```
DRAFT  ──POST──▶  OPEN  ──payments──▶  PARTIAL / PAID
  │                 │
  │                 ├──PATCH (unpaid)──▶ OPEN (amended)
  │                 └──VOID (ADMIN)──▶  VOIDED
  │
  └──DELETE (ADMIN)──▶ removed
```

| Status | Description |
|--------|-------------|
| `DRAFT` | Editable; no GL or inventory impact; `balance` = `0` |
| `OPEN` | Posted; A/R balance set; inventory consumed for stock items; editable while unpaid (amend) |
| `PARTIAL` | Partially paid via customer payments; not editable |
| `PAID` | Fully paid; not editable |
| `VOIDED` | Reversed; inventory and GL restored |

---

## Invoice object

| Field | Type | Read-only | Description |
|-------|------|-----------|-------------|
| `id` | integer | Yes | Primary key |
| `customer_id` | integer | Yes* | Linked customer |
| `invoice_number` | string | **Yes** | Auto-generated (`INV-0001`, `INV-0002`, …) |
| `customer_snapshot` | object | **Yes*** | Bill-to details for print/PDF; frozen per document |
| `txn_date` | date | No** | Invoice date |
| `due_date` | date | No** | Payment due date |
| `payment_terms` | string | No** | `NET_30`, `NET_60`, `NET_90`, `IMMEDIATE` |
| `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 post; reduced by payments |
| `status` | string | **Yes** | `DRAFT`, `OPEN`, `PARTIAL`, `PAID`, `VOIDED` |
| `allow_negative_stock` | boolean | No** | When `true`, stock validation is bypassed on draft create/update (ADMIN only; requires company `allow_negative_inventory`). See [negative-stock.md](./negative-stock.md). |
| `memo` | string \| null | No** | Printed on invoice |
| `notes` | string \| null | No** | Internal notes only |
| `customer` | object | Yes | Nested customer when loaded |
| `lines` | array | No** | Line items (replaced entirely on update when sent) |
| `created_at` | datetime | Yes | — |
| `updated_at` | datetime | Yes | — |

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

\* `customer_snapshot` is returned on read only. On **create**, **draft update**, and **open unpaid amend**, send optional `customer_snapshot` overrides (see below). Omitted keys keep the existing or default value; explicit `null` clears nullable fields. Does **not** update the customer master record.

\** Editable while `status` = `DRAFT`, or while `status` = `OPEN` with no payments applied.

### Customer snapshot (Bill to)

| Field | Type | Writable | Description |
|-------|------|----------|-------------|
| `name` | string | Yes | Printed customer/company name (defaults from `customer.display_name`) |
| `email` | string \| null | Yes | Printed email |
| `phone` | string \| null | Yes | Printed phone |
| `address` | string \| null | Yes | Printed billing address (multiline) |

On create, defaults are copied from the linked customer. Send only fields you want to override; the API merges into the stored snapshot.

**Defaults on create:** `status` = `DRAFT`, `balance` = `0`, `payment_terms` from customer (or `IMMEDIATE`), `invoice_number` auto-assigned per company.

### Invoice line object

| Field | Type | Read-only | Description |
|-------|------|-----------|-------------|
| `id` | integer | Yes | Primary key |
| `item_id` | integer | No* | Catalog item |
| `item_snapshot` | object | **Yes** | Frozen item name/sku/price at invoice time |
| `line_number` | integer | **Yes** | 1-based position |
| `qty` | decimal string | No* | Quantity sold |
| `unit_price` | decimal string | No* | Selling price per unit (**7 decimal places**, QBO rate precision) |
| `discount_percent` | decimal string | No* | Line discount % (0–100); back-calculated when `discount_amount` is the input |
| `discount_amount` | decimal string | No* | Flat discount in currency units; back-calculates `discount_percent` when used as input |
| `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 |
| `cogs_amount` | decimal string | **Yes** | FIFO + estimated backorder cost (set on post for inventory items) |
| `backorder_qty` | decimal string | **Yes** | Units sold on backorder (posted oversell invoices only) |
| `estimated_cogs_amount` | decimal string | **Yes** | COGS portion from backorder qty at estimated unit cost |
| `description` | string \| null | No* | Optional line detail for display on invoice |
| `item` | object | Yes | Nested item when loaded (on show/post/void) |

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

### Tax calculation

Totals are calculated server-side (QuickBooks-style):

1. `unit_price` is normalized to **7 decimal places** before calculation.
2. `gross` = `round(qty × unit_price, 2)` — line amount at **cent precision**.
3. Discount — **two mutually exclusive input paths** (send one or neither, never both):
   - `discount_percent` provided → `discount_amount` = `round(gross × discount_percent / 100, 2)`
   - `discount_amount` provided → used directly (rounded to 2 dp); `discount_percent` is back-calculated as `discount_amount / gross × 100`
   - Neither provided → both default to `0`
4. `net` = `round(gross − discount_amount, 2)`
5. If the item is `taxable` and a tax code applies: `tax_amount` = `round(net × rate_percent / 100, 2)` **per line**
6. `line_total` = `round(net + tax_amount, 2)`
7. Header `sub_total`, `tax_total`, and `total_amount` are sums of 2-dp line values.

**Rate vs catalog:** `items.unit_price` remains 4 dp for catalog defaults. Send a precise 7-dp rate on the invoice line when needed (e.g. `total ÷ qty` → `221.3114754` so `305 × rate = 67500.00`). `item_snapshot.unit_price` copies the 4-dp catalog price at save time; the line’s own `unit_price` is authoritative for totals.

> `discount_amount` cannot exceed the line `gross` (`qty × unit_price`, rounded to 2 dp). Sending both `discount_percent` and `discount_amount` on the same line returns `422`.

**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.
- Non-taxable items get `tax_amount` = `0`.

### Posting side effects

`POST /invoices/{id}/post` (draft only):

- Consumes FIFO inventory layers for `INVENTORY` items (fails if insufficient stock unless `allow_negative_stock` is set on the invoice).
- When overselling, records backorder rows and books estimated COGS (layer average → `standard_cost` → `0`).
- Posts GL: A/R Dr, Sales Revenue Cr, VAT Payable Cr (if tax), COGS Dr / Inventory Cr (if inventory).
- **Line amounts are cent-aligned at save** (2 dp). `DocumentHeaderRoundingService` on post is a safety net for float epsilon only; draft and posted `total_amount` normally match.
- Sets `status` = `OPEN`, `balance` = `total_amount`, and increases the customer's running `balance` by `total_amount`.

`POST /invoices/{id}/void` (open only, ADMIN):

- Restores inventory layers and `qty_on_hand`.
- Reverses the **current** auto-generated journal entry (tracked via `active_journal_entry_id`).
- Reversal JE date: **invoice `txn_date`** when the invoice falls in an open period; **today** when `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`, and decreases the customer's running `balance` by the invoice's remaining balance.

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

- Unpublishes (reversal + inventory restore), applies changes, reposts GL at the (possibly updated) `invoice.txn_date`.
- Reversal uses the **pre-amend** `txn_date` for dating when the period is 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).

| Invoice `txn_date` vs close | Reversal JE `txn_date` | Amend repost JE `txn_date` |
|-----------------------------|------------------------|------------------------------|
| After `books_closed_through` (open year) | Same as invoice `txn_date` | `invoice.txn_date` after edit |
| On or before `books_closed_through` (closed year) | Today (correction in current period) | `invoice.txn_date` after edit |

Posted invoices store `active_journal_entry_id` pointing at the current posting JE so repeated amends do not leave orphan GL entries.

---

# Endpoints

## List invoices

```
GET /invoices
```

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

### Query parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `customer_id` | integer | — | Limit to one customer (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 `invoice_number` or customer `display_name` (max 100 chars) |
| `is_overdue` | boolean | — | When `true`, only `OPEN`/`PARTIAL` invoices with `balance > 0` and `due_date` before today |
| `include_lines` | boolean | `true` | When `false`, omits `lines` from each invoice |
| `include_customer` | boolean | `true` | When `false`, omits nested `customer` object |
| `sort` | string | `-txn_date` | Sort field. Prefix with `-` for descending. Allowed: `txn_date`, `due_date`, `invoice_number`, `total_amount`, `balance`, `status`, `created_at`, `customer_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/invoices?customer_id=3&status=OPEN,PARTIAL&balance_min=0.01&start_date=2026-01-01&end_date=2026-06-30&search=INV-00&is_overdue=1&include_lines=0&include_customer=1&sort=due_date&per_page=100&page=1
Authorization: Bearer {token}
Accept: application/json
```

### Success response — `200 OK`

```json
{
  "data": [
    {
      "id": 1,
      "customer_id": 3,
      "invoice_number": "INV-0001",
      "customer_snapshot": {
        "name": "John Doe Corp",
        "email": null,
        "phone": null,
        "address": null
      },
      "txn_date": "2026-06-11T00:00:00.000000Z",
      "due_date": "2026-07-11T00:00:00.000000Z",
      "payment_terms": "NET_30",
      "sub_total": "200.0000",
      "discount_total": "0.0000",
      "tax_total": "36.0000",
      "total_amount": "236.0000",
      "balance": "0.0000",
      "status": "DRAFT",
      "memo": null,
      "notes": "Rush order",
      "created_at": "2026-06-11T10:00:00.000000Z",
      "updated_at": "2026-06-11T10:00:00.000000Z",
      "customer": {
        "id": 3,
        "display_name": "John Doe Corp"
      },
      "lines": [
        {
          "id": 1,
          "item_id": 5,
          "item_snapshot": {
            "name": "Test Widget",
            "sku": "WDG-001",
            "unit_price": "100.0000"
          },
          "line_number": 1,
          "qty": "2.0000",
          "unit_price": "100.0000",
          "discount_percent": "0.00",
          "discount_amount": "0.0000",
          "tax_code_id": 1,
          "tax_amount": "36.0000",
          "line_total": "236.0000",
          "cogs_amount": "0.0000",
          "description": null
        }
      ]
    }
  ],
  "links": {
    "first": "http://127.0.0.1:8000/api/v1/invoices?page=1",
    "last": "http://127.0.0.1:8000/api/v1/invoices?page=1",
    "prev": null,
    "next": null
  },
  "meta": {
    "current_page": 1,
    "per_page": 25,
    "total": 1,
    "last_page": 1
  }
}
```

---

## Create invoice

```
POST /invoices
```

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

### Request body

| Field | Type | Required | Rules |
|-------|------|----------|-------|
| `customer_id` | integer | **Yes** | Must exist in the same company |
| `txn_date` | date | **Yes** | Invoice date |
| `due_date` | date | **Yes** | Must be ≥ `txn_date` |
| `payment_terms` | string | No | `NET_30`, `NET_60`, `NET_90`, `IMMEDIATE`; defaults from customer |
| `customer_snapshot` | object | No | Optional Bill-to overrides; merged with customer defaults (see [Customer snapshot](#customer-snapshot-bill-to)) |
| `customer_snapshot.name` | string | No | Max 255 |
| `customer_snapshot.email` | string \| null | No | Email format |
| `customer_snapshot.phone` | string \| null | No | Max 50 |
| `customer_snapshot.address` | string \| null | No | Max 2000 |
| `memo` | string | No | Printed on invoice |
| `notes` | string | No | Internal notes |
| `allow_negative_stock` | boolean | No | ADMIN only. Requires company `allow_negative_inventory`. Bypasses insufficient-stock validation on draft create. |
| `lines` | array | **Yes** | Min 1 line |
| `lines.*.item_id` | integer | **Yes** | Must exist in the same company |
| `lines.*.qty` | number | **Yes** | Min `0.0001` |
| `lines.*.unit_price` | number | **Yes** | Min `0` |
| `lines.*.discount_percent` | number | No | 0–100; default `0`. Mutually exclusive with `discount_amount`. |
| `lines.*.discount_amount`  | number | No | Flat discount ≥ 0, must not exceed `qty × unit_price`. Mutually exclusive with `discount_percent`. |
| `lines.*.tax_code_id` | integer | No | Must exist in the same company |
| `lines.*.description` | string | No | Max 1000 chars; informational only |
| `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 | Map of attachment id → boolean for invoice email |

### Example request

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

{
  "customer_id": 3,
  "txn_date": "2026-06-11",
  "due_date": "2026-07-11",
  "notes": "Rush order",
  "lines": [
    {
      "item_id": 5,
      "qty": 2,
      "unit_price": 100
    }
  ]
}
```

### Example with Bill-to override

```json
{
  "customer_id": 3,
  "txn_date": "2026-06-11",
  "due_date": "2026-07-11",
  "customer_snapshot": {
    "name": "Acme Corp — Warehouse Receiving",
    "address": "456 Dock Rd"
  },
  "lines": [
    {
      "item_id": 5,
      "qty": 2,
      "unit_price": 100
    }
  ]
}
```

### Example with discount

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

### Success response — `201 Created`

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

### Error responses

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

---

## Get invoice

```
GET /invoices/{id}
```

Returns the invoice with `lines.item` and `customer` loaded.

### Example request

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

### Success response — `200 OK`

Single invoice object wrapped in `data`.

### Error responses

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

---

## Update invoice

```
PUT /invoices/{id}
PATCH /invoices/{id}
```

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

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

**Open unpaid (`OPEN`, `balance` = `total_amount`, no payment allocations):** the API reverses the existing journal entry, restores FIFO inventory, applies your changes, then reposts. `invoice_number`, `customer_id`, and `transaction_id` stay the same; `balance` is set to the new `total_amount`.

When `lines` is sent, existing lines are **replaced entirely** with the new array.

### Request body

| Field | Type | Required | Rules |
|-------|------|----------|-------|
| `txn_date` | date | No | — |
| `due_date` | date | No | Must be ≥ `txn_date` |
| `payment_terms` | string | No | `NET_30`, `NET_60`, `NET_90`, `IMMEDIATE` |
| `customer_snapshot` | object | No | Bill-to overrides; merged into existing snapshot (see [Customer snapshot](#customer-snapshot-bill-to)) |
| `customer_snapshot.name` | string | No | Max 255 |
| `customer_snapshot.email` | string \| null | No | Email format |
| `customer_snapshot.phone` | string \| null | No | Max 50 |
| `customer_snapshot.address` | string \| null | No | Max 2000 |
| `memo` | string | No | — |
| `notes` | 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) |
| `include_on_send_by_id` | object | No | Map of attachment id → boolean for invoice email |

### Example request

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

{
  "notes": "Updated note",
  "lines": [
    {
      "item_id": 5,
      "qty": 3,
      "unit_price": 100,
      "discount_percent": 10,
      "description": "Updated line note"
    }
  ]
}
```

### Success response — `200 OK`

Updated invoice in `data` with recalculated totals.

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User is not ADMIN/ACCOUNTANT; invoice is `PARTIAL`, `PAID`, or `VOIDED`; or open invoice has payments applied |
| `404` | Invoice not found |
| `422` | Validation failed; insufficient stock after amend; amend preconditions failed |

---

## Post invoice

```
POST /invoices/{id}/post
```

Finalizes a draft invoice: consumes inventory, posts journal entries, sets `status` = `OPEN`.

### Example request

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

### Success response — `200 OK`

Posted invoice in `data` with `status` = `OPEN` and `balance` = `total_amount`.

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User is not ADMIN/ACCOUNTANT, or invoice is not `DRAFT` |
| `404` | Invoice not found |
| `422` | Posting failed (e.g. insufficient inventory, missing GL account) |

On any posting failure the draft invoice is **automatically deleted** (invoice, lines, spine transaction, and attachments). Fix the underlying issue and create a new draft before retrying.

---

## Download invoice PDF

```
GET /invoices/{id}/pdf
```

Streams a generated PDF of the invoice. Uses company letterhead and **`customer_snapshot`** / line data (not live customer master records). Internal `notes` and invoice `status` are omitted. Shows `txn_date`, `due_date`, `payment_terms`, totals, and **amount due** (`balance`).

**Roles:** any authenticated tenant user who can view the invoice. Allowed for any status (`DRAFT`, `OPEN`, `PARTIAL`, `PAID`, `VOIDED`).

### Example request

```http
GET /api/v1/invoices/1/pdf
Authorization: Bearer {token}
```

### Success response — `200 OK`

| Header | Value |
|--------|-------|
| `Content-Type` | `application/pdf` |
| `Content-Disposition` | `attachment; filename="INV-0001.pdf"` |

Body: PDF binary.

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User cannot view the invoice |
| `404` | Invoice not found or wrong company |

---

## Send invoice PDF by email

```
POST /invoices/{id}/send
```

Generates the same PDF as download and emails it to the customer. **Does not change invoice status.** Also attaches any invoice files with `include_on_send: true` (see [attachments.md](./attachments.md)).

**Roles:** ADMIN, ACCOUNTANT.

### Request body

All fields optional.

| Field | Type | Description |
|-------|------|-------------|
| `to` | email | Recipient; defaults to `customer_snapshot.email` |
| `cc` | email or email[] | Optional CC recipients |
| `subject` | string | Defaults to `Invoice {number} from {company name}` |
| `message` | string | Optional plain-text body above the default notice |

```json
{
  "to": "buyer@example.com",
  "cc": ["ops@example.com"],
  "subject": "Your invoice INV-0001",
  "message": "Please find your invoice attached."
}
```

### Success response — `200 OK`

Returns the invoice object (status unchanged).

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User cannot send invoices |
| `404` | Invoice not found or wrong company |
| `422` | No recipient (`to` omitted and snapshot email empty) |

---

## Void invoice

```
POST /invoices/{id}/void
```

Reverses a posted invoice. **ADMIN only.** Invoice must be `OPEN`.

### Example request

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

### Success response — `200 OK`

Voided invoice in `data` with `status` = `VOIDED`, `balance` = `0`.

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User is not ADMIN, or invoice is not `OPEN` |
| `404` | Invoice not found |

---

## Copy invoice

```
POST /invoices/{id}/copy
```

Creates a new **DRAFT** invoice from any source invoice (any status). Copies customer, lines, memo, notes, payment terms, and `allow_negative_stock`. Assigns a new invoice number and transaction; does not copy payments, journal entries, or attachments.

**Roles:** same as create invoice (ADMIN, ACCOUNTANT, CASHIER).

### Optional request body

| Field | Type | Description |
|-------|------|-------------|
| `txn_date` | date | Invoice date (default: today) |
| `due_date` | date | Due date (default: computed from `payment_terms`) |
| `memo` | string \| null | Override memo |

### Example request

```http
POST /api/v1/invoices/12/copy
Authorization: Bearer {token}
Accept: application/json
Content-Type: application/json

{}
```

### Success response — `201 Created`

Same shape as [Create invoice](#create-invoice) (`Invoice` object with `status` = `DRAFT`).

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User cannot create invoices |
| `404` | Invoice not found |
| `422` | Source has no lines, inactive item, insufficient stock, or validation failed |

---

## Delete invoice

```
DELETE /invoices/{id}
```

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

### Example request

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

### Success response — `204 No Content`

Empty body.

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User is not ADMIN, or invoice is not `DRAFT` |
| `404` | Invoice not found |

---

## Validation error format — `422`

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

---

## Endpoint summary

| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/invoices` | List all invoices |
| `POST` | `/invoices` | Create draft invoice |
| `GET` | `/invoices/{id}` | Get invoice |
| `PUT`/`PATCH` | `/invoices/{id}` | Update draft invoice, or amend open unpaid invoice |
| `DELETE` | `/invoices/{id}` | Delete draft invoice |
| `POST` | `/invoices/{id}/post` | Post draft to GL & inventory |
| `POST` | `/invoices/{id}/void` | Void posted invoice |
| `POST` | `/invoices/{id}/copy` | Copy invoice to new draft |

---

## Frontend notes

- Workflow: **create draft → edit if needed → post**. After post, you may **amend** while `status` = `OPEN` and no payments are linked (same `PATCH` endpoint).
- Show **Edit** when the sales hub returns `edit` in `actions`, or when `status` = `DRAFT`, or when `status` = `OPEN` and `balance` equals `total_amount` with no payments.
- To edit a **partially paid** or **paid** invoice (QuickBooks-style), remove payment allocations first via [customer-payments.md](./customer-payments.md), then amend.
- Open amend reverses GL and FIFO internally — warn users that totals and inventory impact change immediately; this is not a cosmetic-only edit.
- For `INVENTORY` items on **draft** create/update, validate stock against current `qty_on_hand`. On **open amend**, stock is checked after this invoice’s qty is restored to on-hand.
- `customer_snapshot` and `item_snapshot` preserve historical Bill-to / line data — **always render print/PDF from snapshots**, not live customer/item records. Override Bill to on create or edit via `customer_snapshot` in the request body; updating the customer master is a separate `PATCH /customers/{id}`.
- `lines.*.description` is optional free text per line; re-send when replacing `lines` on draft update.
- Record customer payments separately via the customer payments API; allocations reduce `balance` and update status to `PARTIAL` / `PAID`. See [customer-payments.md](./customer-payments.md).
- Related docs: [customers.md](./customers.md), [items.md](./items.md), [accounts.md](./accounts.md).
