# Brix Accounting API — Negative stock (frontend guide)

Dedicated reference for building **QBO-style negative inventory** in the UI: sell below on-hand qty, track backorders, and show COGS true-up when stock is received.

This feature is **opt-in** at two levels. When disabled, existing invoice/bill flows behave exactly as before.

**Related endpoint docs:** [company](./company.md) · [invoices](./invoices.md) · [items](./items.md) · [bills](./bills.md) · [inventory-adjustments](./inventory-adjustments.md) · [inventory-transactions](./inventory-transactions.md) · [gross-profit-summary](./gross-profit-summary.md)

---

## Base URL

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

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

All endpoints require `Authorization: Bearer {token}`, `Accept: application/json`, and the `company` middleware (tenant scoping).

---

## Feature overview

| Concept | Meaning |
|---------|---------|
| **Oversell** | Invoice line qty exceeds `qty_on_hand` at post time |
| **Backorder** | Outstanding qty committed by a posted oversell invoice, not yet covered by a receipt |
| **Estimated COGS** | Cost booked at **invoice post** for the backorder portion (FIFO avg → `standard_cost` → `0`) |
| **COGS true-up** | Additional JE when a bill or positive adjustment receives stock at a **different** unit cost than the estimate |
| **`qty_on_hand`** | Physical layers minus open backorders — **can be negative** while backorders exist |
| **`backorder_qty`** | Open backorder units for an item (always ≥ 0) |

```mermaid
sequenceDiagram
    participant UI
    participant API
    participant Inv as Inventory

    Note over UI,Inv: 1. Enable (once per company)
    UI->>API: PATCH /company { allow_negative_inventory: true }

    Note over UI,Inv: 2. Oversell invoice (ADMIN)
    UI->>API: POST /invoices { allow_negative_stock: true, lines... }
    UI->>API: POST /invoices/{id}/post
    API->>Inv: FIFO consume + backorder rows
    Inv-->>UI: qty_on_hand negative, backorder_qty positive

    Note over UI,Inv: 3. Receive stock
    UI->>API: POST /bills + POST /bills/{id}/receive
    API->>Inv: Clear backorders, optional COGS true-up JE
    Inv-->>UI: qty_on_hand restored, cogs_amount updated on invoice line

    Note over UI,Inv: 4. Reports
    UI->>API: GET /reports/gross-profit-summary
    API-->>UI: GP includes true-up on bill/adjustment date
```

---

## Activation (two-level opt-in)

Both flags must be true for oversell to work end-to-end.

| Level | Field | Where set | Who | Default |
|-------|-------|-----------|-----|---------|
| Company | `allow_negative_inventory` | `PATCH /company` | ADMIN | `false` |
| Invoice | `allow_negative_stock` | `POST` / `PATCH /invoices` | ADMIN | `false` |

### Company setting

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

{
  "allow_negative_inventory": true
}
```

**Response field:** `data.allow_negative_inventory` (boolean) on `GET /company`, `GET /me`, and login payload (subset).

**UI guidance:** Show a company settings toggle labeled e.g. *Allow selling below on-hand quantity (admin invoices only)*. Hide or disable the invoice-level option when this is `false`.

### Invoice flag

Send on **create** or **update** (draft or amend):

```json
{
  "customer_id": 3,
  "txn_date": "2026-06-22",
  "due_date": "2026-07-22",
  "allow_negative_stock": true,
  "lines": [
    { "item_id": 12, "qty": 5, "unit_price": 100 }
  ]
}
```

**Rules:**

- Only **ADMIN** may set `allow_negative_stock: true` (non-admin → `403`).
- Company must have `allow_negative_inventory: true` (otherwise `422` on `allow_negative_stock`).
- Once set on a posted invoice, the flag is persisted — amend stock checks respect it even if omitted in the PATCH body.

**UI guidance:** Checkbox on invoice form — visible to ADMIN only when company setting is on. Label e.g. *Allow negative stock (oversell)*. Show a warning that COGS is estimated until stock is received.

---

## Affected endpoints (quick reference)

| Action | Method | Path | Notes |
|--------|--------|------|-------|
| Read company flag | `GET` | `/company` | `allow_negative_inventory` |
| Enable feature | `PATCH` | `/company` | ADMIN |
| Create oversell draft | `POST` | `/invoices` | `allow_negative_stock: true` |
| Update draft / amend | `PATCH` | `/invoices/{id}` | Same flag; amend blocked after clearance |
| Post oversell | `POST` | `/invoices/{id}/post` | Creates backorders |
| Void invoice | `POST` | `/invoices/{id}/void` | Blocked if backorders cleared |
| Item stock view | `GET` | `/items`, `/items/{id}` | `qty_on_hand`, `backorder_qty` |
| Delete item | `DELETE` | `/items/{id}` | Blocked if open backorders |
| Receive stock | `POST` | `/bills/{id}/receive` | Clears backorders, COGS true-up |
| Bill detail | `GET` | `/bills/{id}` | `cogs_true_ups[]` after receive |
| Void bill | `POST` | `/bills/{id}/void` | Restores backorders |
| Positive adjustment | `POST` | `/inventory-adjustments` | Increase qty clears backorders |
| Void adjustment | `POST` | `/inventory-adjustments/{id}/void` | Restores backorders |
| Inventory hub | `GET` | `/inventory-transactions` | `type=backorder_sale,cogs_true_up` |
| Gross profit | `GET` | `/reports/gross-profit-summary` | True-up hits on receive date |

---

## Response fields

### Company (`GET /company`)

| Field | Type | Description |
|-------|------|-------------|
| `allow_negative_inventory` | boolean | Master switch for oversell |

### Item (`GET /items`, `GET /items/{id}`)

| Field | Type | Description |
|-------|------|-------------|
| `qty_on_hand` | decimal string | `sum(FIFO layers) − open backorders`. May be **negative**. |
| `backorder_qty` | decimal string | Open backorder units (4 decimal places, e.g. `"5.0000"`) |

**UI guidance:**

- Show both columns on item list/detail when company flag is on.
- Negative `qty_on_hand` with positive `backorder_qty` = oversold, awaiting receipt.
- When `backorder_qty` > 0, disable item delete (API returns `422`).

### Invoice header (`GET /invoices/{id}`)

| Field | Type | Description |
|-------|------|-------------|
| `allow_negative_stock` | boolean | Persisted oversell flag |

### Invoice line (after post)

| Field | Type | Description |
|-------|------|-------------|
| `cogs_amount` | decimal string | Total COGS (FIFO + estimated backorder; updated after true-up) |
| `backorder_qty` | decimal string | Units sold on backorder for this line (`"0.0000"` if none) |
| `estimated_cogs_amount` | decimal string | COGS portion from backorder qty at sale-time estimate |

**Example posted oversell line (5 units, estimate $40/unit, no on-hand):**

```json
{
  "id": 44,
  "item_id": 12,
  "qty": "5.0000",
  "unit_price": "100.0000",
  "cogs_amount": "200.0000",
  "backorder_qty": "5.0000",
  "estimated_cogs_amount": "200.0000"
}
```

After a bill receive at $55/unit (true-up +$75):

```json
{
  "cogs_amount": "275.0000",
  "backorder_qty": "5.0000",
  "estimated_cogs_amount": "200.0000"
}
```

> `estimated_cogs_amount` stays at the sale-time snapshot; `cogs_amount` reflects true-up.

### Bill (`GET /bills/{id}` after receive)

When backorders were cleared on receive, the bill includes:

| Field | Type | Description |
|-------|------|-------------|
| `cogs_true_ups` | array | One entry per clearance row on bill lines |

**`cogs_true_ups[]` object:**

| Field | Type | Description |
|-------|------|-------------|
| `bill_line_id` | integer | Source bill line |
| `invoice_line_id` | integer | Invoice line whose backorder was cleared |
| `invoice_number` | string | Linked oversell invoice |
| `item_sku` | string | Item SKU |
| `qty_cleared` | decimal string | Units applied |
| `estimated_unit_cost` | decimal string | Cost at sale |
| `actual_unit_cost` | decimal string | Cost on this bill line |
| `cogs_adjustment_amount` | decimal string | `(actual − estimated) × qty`; positive = COGS increase |

**Example:**

```json
{
  "id": 8,
  "bill_number": "BILL-0003",
  "received_into_inventory": true,
  "cogs_true_ups": [
    {
      "bill_line_id": 15,
      "invoice_line_id": 44,
      "invoice_number": "INV-0012",
      "item_sku": "ZSW-001",
      "qty_cleared": "5.0000",
      "estimated_unit_cost": "40.0000",
      "actual_unit_cost": "55.0000",
      "cogs_adjustment_amount": "75.0000"
    }
  ]
}
```

**UI guidance:** After bill receive, show a *COGS true-up* panel when `cogs_true_ups.length > 0`, with links to the related invoice(s).

---

## Inventory transactions hub

Use for an **Inventory Valuation Detail** / activity view that includes oversell and true-up rows.

```http
GET /api/v1/inventory-transactions?type=backorder_sale,cogs_true_up&item_id=12
```

| Filter `type` | Response `movement_type` | `qty_change` | `value_change` |
|---------------|--------------------------|----------------|------------------|
| `backorder_sale` | `BACKORDER_SALE` | Negative (oversell qty) | Negative (estimated COGS) |
| `cogs_true_up` | `COGS_TRUE_UP` | `"0.0000"` | COGS adjustment (+/−) |

**`BACKORDER_SALE` row:**

```json
{
  "movement_type": "BACKORDER_SALE",
  "item_sku": "ZSW-001",
  "txn_date": "2026-06-22",
  "qty_change": "-5.0000",
  "unit_cost": "40.0000",
  "value_change": "-200.0000",
  "reference_type": "INVOICE",
  "reference_number": "INV-0012",
  "memo": "Oversold (backorder)",
  "available_actions": ["view_invoice", "view_journal"]
}
```

**`COGS_TRUE_UP` row:**

```json
{
  "movement_type": "COGS_TRUE_UP",
  "txn_date": "2026-06-20",
  "qty_change": "0.0000",
  "value_change": "75.0000",
  "reference_type": "BILL",
  "reference_number": "BILL-0003",
  "memo": "COGS true-up — INV-0012",
  "available_actions": ["view_bill", "view_journal", "view_invoice"]
}
```

Default hub types (`receipt`, `sale`, etc.) are unchanged — backorder types are **additive** and must be requested explicitly.

---

## User flows

### 1. Settings page (ADMIN)

1. `GET /company` → read `allow_negative_inventory`.
2. `PATCH /company` with `{ "allow_negative_inventory": true }`.
3. Optionally refresh `GET /me` if the app caches company flags from login.

### 2. Invoice create / edit (ADMIN)

1. Confirm `company.allow_negative_inventory === true`.
2. Show *Allow negative stock* checkbox; default off.
3. When checked, skip client-side “insufficient stock” blocking (server still validates if flag not sent).
4. On line items, optionally show `qty_on_hand` and warn when `line.qty > qty_on_hand` (informational).
5. `POST /invoices` or `PATCH /invoices/{id}` with `allow_negative_stock: true`.
6. `POST /invoices/{id}/post`.

**After post:** Refresh invoice — show `backorder_qty` / `estimated_cogs_amount` on inventory lines. Refresh item — expect negative `qty_on_hand`.

### 3. Restock via bill

1. Create and receive bill as usual: `POST /bills`, then `POST /bills/{id}/receive`.
2. System clears backorders FIFO by invoice `sold_at` before creating new FIFO layers.
3. `GET /bills/{id}` → display `cogs_true_ups` if present.
4. `GET /invoices/{linked}` → `cogs_amount` may have changed.

### 4. Restock via positive inventory adjustment

Same backorder-clearing behavior as a bill when `change_in_qty > 0`:

```http
POST /api/v1/inventory-adjustments
Content-Type: application/json

{
  "adjustment_date": "2026-06-20",
  "adjustment_account_id": 8,
  "memo": "Found stock — clear backorder",
  "lines": [
    { "item_id": 12, "change_in_qty": 5 }
  ]
}
```

No dedicated `cogs_true_ups` block on adjustments today — use inventory hub `type=cogs_true_up` or journal entries for audit.

### 5. Gross profit report

`GET /reports/gross-profit-summary` includes COGS true-up on the **bill/adjustment date**, not the original invoice date. Warn users that GP for a period can change after posting oversell invoices when bills arrive later.

---

## Blocked actions (v1)

The API enforces these rules after a backorder has been **cleared** by a bill or adjustment:

| Action | Condition | HTTP | Message |
|--------|-----------|------|---------|
| Amend invoice | Backorder cleared | `422` | `Cannot change an invoice whose backorders were cleared by a bill or adjustment. Reverse the receipt first.` |
| Void invoice | Backorder cleared | `422` | Same as above |
| Delete item | Open backorders | `422` | `Cannot delete an item with open backorders.` |

**UI guidance:**

- Before showing **Void** or **Amend** on an oversell invoice, consider fetching bill/adjustment history or catching `422` with the message above.
- To undo: void the receiving bill (`POST /bills/{id}/void`) or void the inventory adjustment first — that restores backorders and reverses true-up JEs.
- Disable **Delete item** when `backorder_qty !== "0.0000"`.

**Still allowed before clearance:**

- Void oversell invoice (`POST /invoices/{id}/void`) — voids open backorders and restores estimated COGS reversal.
- Amend oversell invoice while unpaid and no clearances exist.

---

## Validation and error catalog

Use these for form validation and toast messages.

| HTTP | Field / context | Message |
|------|-----------------|---------|
| `403` | `allow_negative_stock` | Non-admin attempted to set flag |
| `422` | `allow_negative_stock` | `Negative inventory is not enabled for this company.` |
| `422` | `lines.{n}.qty` | `Insufficient stock for item '{sku}'. Available: {qty_on_hand}.` (when flag off) |
| `422` | void / amend | `Cannot change an invoice whose backorders were cleared by a bill or adjustment. Reverse the receipt first.` |
| `422` | delete item | `Cannot delete an item with open backorders.` |

Insufficient-stock errors occur on **draft create/update** and on **amend** (unless invoice has `allow_negative_stock`).

---

## Frontend checklist

### Company settings

- [ ] Toggle `allow_negative_inventory` (ADMIN only)
- [ ] Persist and expose flag to invoice module

### Invoice form

- [ ] Show `allow_negative_stock` checkbox (ADMIN + company flag)
- [ ] Do not block submit on insufficient stock when checkbox on
- [ ] Show post-posting fields: `backorder_qty`, `estimated_cogs_amount`, `cogs_amount`
- [ ] Disable void/amend with tooltip when clearance exists (or handle `422`)

### Item catalog

- [ ] Display `qty_on_hand` (allow negative formatting)
- [ ] Display `backorder_qty` when company flag on
- [ ] Block delete when `backorder_qty` > 0

### Bills

- [ ] After receive, render `cogs_true_ups` with invoice links
- [ ] Explain true-up in bill detail help text

### Inventory activity

- [ ] Optional filter: include `backorder_sale` and `cogs_true_up` in hub
- [ ] Link rows to invoice / bill / journal

### Reports

- [ ] Footnote on gross profit: COGS may update when bills receive oversold items

---

## COGS estimate priority (display / help text)

At invoice post, estimated unit cost for the backorder portion is:

1. Weighted average of remaining FIFO layers
2. Else item `standard_cost`
3. Else `0`

True-up posts only when **actual receive cost ≠ estimated** (bill line unit price or adjustment average cost).

---

## Example: full oversell scenario

**Setup:** Item `ZSW-001`, `qty_on_hand = 0`, `standard_cost = 40`, company flag on.

```http
# 1. Enable company
PATCH /api/v1/company
{ "allow_negative_inventory": true }

# 2. Create & post oversell invoice (5 × $100)
POST /api/v1/invoices
{
  "customer_id": 3,
  "txn_date": "2026-06-22",
  "due_date": "2026-07-22",
  "allow_negative_stock": true,
  "lines": [{ "item_id": 12, "qty": 5, "unit_price": 100 }]
}
POST /api/v1/invoices/42/post

# 3. Check item
GET /api/v1/items/12
# qty_on_hand: "-5.0000", backorder_qty: "5.0000"

# 4. Receive bill @ $55
POST /api/v1/bills
{
  "vendor_id": 2,
  "txn_date": "2026-06-20",
  "due_date": "2026-07-20",
  "lines": [{ "item_id": 12, "qty": 5, "unit_price": 55 }]
}
POST /api/v1/bills/8/receive

# 5. Verify
GET /api/v1/items/12          → qty_on_hand: "0.0000", backorder_qty: "0.0000"
GET /api/v1/invoices/42       → lines[0].cogs_amount: "275.0000"
GET /api/v1/bills/8           → cogs_true_ups[0].cogs_adjustment_amount: "75.0000"
GET /api/v1/inventory-transactions?type=backorder_sale,cogs_true_up&item_id=12
```

---

## TypeScript shapes (optional)

```typescript
interface CompanyNegativeStockFlags {
  allow_negative_inventory: boolean;
}

interface InvoiceNegativeStockFields {
  allow_negative_stock: boolean;
}

interface InvoiceLineNegativeStockFields {
  cogs_amount: string;
  backorder_qty: string;
  estimated_cogs_amount: string;
}

interface ItemNegativeStockFields {
  qty_on_hand: string;   // may be negative
  backorder_qty: string;
}

interface BillCogsTrueUp {
  bill_line_id: number;
  invoice_line_id: number;
  invoice_number: string;
  item_sku: string;
  qty_cleared: string;
  estimated_unit_cost: string;
  actual_unit_cost: string;
  cogs_adjustment_amount: string;
}

type InventoryMovementType =
  | 'RECEIPT'
  | 'SALE'
  | 'ADJUSTMENT_IN'
  | 'ADJUSTMENT_OUT'
  | 'BACKORDER_SALE'
  | 'COGS_TRUE_UP'
  | 'STARTING_VALUE';
```

---

## Changelog

| Date | Notes |
|------|-------|
| 2026-06-22 | Initial frontend guide — Phases 1–4 complete |
