# Inventory Starting Value API

Set opening quantity and unit cost for inventory items when migrating into Brix or at go-live.

Each starting value automatically:

- Creates a FIFO cost layer (`inventory_cost_layers`, `bill_line_id = null`)
- Updates `items.qty_on_hand`
- Posts a balanced GL journal entry: **Dr Inventory Asset / Cr Owner Equity**

Use this **before** posting sales or receiving bills for the item.

For many SKUs, use **`POST /inventory-starting-values/bulk`** (up to 50 lines per request) or call the single-item endpoint in a script.

---

## Base URL

```
/api/v1/items/{item_id}/starting-value
/api/v1/inventory-starting-values/bulk
```

All endpoints require `Authorization: Bearer {token}` and the `company` middleware.

---

## Role Permissions

| Action | ADMIN | ACCOUNTANT | MANAGER | CASHIER |
|--------|-------|------------|---------|---------|
| View (`GET`) | ✓ | ✓ | ✓ | ✓ |
| Set (`PUT`) | ✓ | ✓ | ✗ | ✗ |
| Bulk set (`POST .../bulk`) | ✓ | ✓ | ✗ | ✗ |
| Edit unsold (`PATCH`) | ✓ | ✗ | ✗ | ✗ |
| Void (`POST .../void`) | ✓ | ✗ | ✗ | ✗ |
| Cost correction preview (`POST .../correction-preview`) | ✓ | ✗ | ✗ | ✗ |
| Cost correction (`PATCH .../correct`) | ✓ | ✗ | ✗ | ✗ |

---

## Endpoints

### `GET /items/{item}/starting-value`

Returns the current starting value record for the item.

#### Response `200 OK`

```json
{
  "data": {
    "id": 1,
    "item_id": 42,
    "item": { "id": 42, "sku": "WDG-001", "name": "Widget A" },
    "status": "OPEN",
    "as_of_date": "2026-06-01",
    "qty": "150.0000",
    "unit_cost": "42.5000",
    "total_value": "6375.0000",
    "cost_layer_id": 88,
    "equity_account": {
      "id": 9,
      "account_number": "3000",
      "name": "Owner Equity"
    },
    "memo": "Opening stock migration",
    "transaction_id": 501,
    "available_actions": ["view_journal", "void", "edit"],
    "created_at": "2026-06-01T10:00:00.000000Z",
    "updated_at": "2026-06-01T10:00:00.000000Z"
  }
}
```

#### Response `404 Not Found`

No starting value has been set for this item.

---

### `PUT /items/{item}/starting-value`

Set opening stock for an inventory item with **zero** quantity and **no existing cost layers**.

**Create-only** — if an open starting value already exists, use [`PATCH`](#patch-itemsitemstarting-value-edit-unsold) (unsold) or void first.

#### Request Body

```json
{
  "as_of_date": "2026-06-01",
  "qty": 150,
  "unit_cost": 42.50,
  "equity_account_id": 9,
  "memo": "Opening stock migration"
}
```

| Field | Required | Description |
|-------|----------|-------------|
| `as_of_date` | Yes | Opening balance date (cut-over date) |
| `qty` | Yes | Opening quantity (> 0) |
| `unit_cost` | Yes | FIFO unit cost (≥ 0) |
| `equity_account_id` | No | Equity GL account. Defaults to account `3000` (Owner Equity) |
| `memo` | No | Optional note (max 500 chars) |

#### GL Impact

| Debit | Credit |
|-------|--------|
| Inventory Asset (item or company default) | Owner Equity |

#### Response `200 OK`

Same shape as `GET`.

#### Business rules

- Item must be `INVENTORY` type
- Item must have `qty_on_hand = 0` and no `inventory_cost_layers` rows
- Only one **OPEN** starting value per item — for unsold stock use `PATCH` to edit; void only to remove entirely
- After void, you may set starting value again

---

### `PATCH /items/{item}/starting-value` (edit unsold)

Edit an **OPEN** starting value when the opening FIFO layer has **not** been consumed. **ADMIN only.**

#### When to use

| Situation | Action |
|-----------|--------|
| Opening stock **not sold** — change qty / cost / date / equity / memo | `PATCH /items/{id}/starting-value` |
| Opening stock **sold** (fully or partly) | `PATCH .../correct` (cost only) |
| Remove opening stock entirely | `POST .../void` |
| First-time setup | `PUT .../starting-value` |

#### Request Body

Same fields as `PUT`:

```json
{
  "as_of_date": "2026-06-01",
  "qty": 100,
  "unit_cost": 40.00,
  "equity_account_id": 9,
  "memo": "Corrected opening qty"
}
```

| Field | Required | Description |
|-------|----------|-------------|
| `as_of_date` | Yes | Opening balance date |
| `qty` | Yes | Opening quantity (> 0) |
| `unit_cost` | Yes | FIFO unit cost (≥ 0) |
| `equity_account_id` | No | Defaults to current equity account on the record |
| `memo` | No | Optional note (max 500 chars) |

#### GL Impact

When any of `qty`, `unit_cost`, `as_of_date`, or `equity_account_id` change:

1. Reverse the active opening journal (same date as that entry, or **today** if the period is closed)
2. Update the existing FIFO layer in place
3. Post a new opening JE: **Dr Inventory Asset / Cr Owner Equity** on the new `as_of_date`

**Memo-only** changes skip journal activity.

Keeps the same `transaction_id` and starting-value record `id`.

#### Response `200 OK`

Returns the updated starting value plus `edit_summary`:

```json
{
  "data": {
    "qty": "100.0000",
    "unit_cost": "40.0000",
    "total_value": "4000.0000"
  },
  "edit_summary": {
    "gl_touched": true,
    "old_total_value": "6375.0000",
    "new_total_value": "4000.0000",
    "journal_entry_ids": [701, 702]
  }
}
```

#### Business rules

- Starting value must be `OPEN` with a linked unconsumed cost layer
- Payload must differ from current values
- Layer consumed → use cost correction instead (edit is not permitted)

---

### `POST /inventory-starting-values/bulk`

Set opening stock for up to **50 inventory items** in one atomic request. If any line fails, the entire batch rolls back.

#### Request Body

```json
{
  "as_of_date": "2026-06-01",
  "equity_account_id": 9,
  "memo": "June 2026 opening import batch 1",
  "lines": [
    { "item_id": 42, "qty": 150, "unit_cost": 42.50 },
    { "sku": "WDG-002", "qty": 80, "unit_cost": 12.00, "memo": "Shelf B stock" }
  ]
}
```

| Field | Required | Description |
|-------|----------|-------------|
| `as_of_date` | Yes | Applied to every line |
| `equity_account_id` | No | Defaults to account `3000` for all lines |
| `memo` | No | Default memo when a line has no `memo` |
| `lines` | Yes | 1–50 rows |
| `lines[].item_id` | One of | Inventory item in your company |
| `lines[].sku` | One of | Alternative to `item_id` |
| `lines[].qty` | Yes | Opening quantity (> 0) |
| `lines[].unit_cost` | Yes | FIFO unit cost (≥ 0) |
| `lines[].memo` | No | Overrides batch `memo` for that line |

Each line must include **`item_id` or `sku`** (not both required, but at least one). Duplicate items in the same request are rejected.

#### Response `201 Created`

```json
{
  "data": [
    {
      "id": 1,
      "item_id": 42,
      "item": { "id": 42, "sku": "WDG-001", "name": "Widget A" },
      "status": "OPEN",
      "as_of_date": "2026-06-01",
      "qty": "150.0000",
      "unit_cost": "42.5000",
      "total_value": "6375.0000"
    }
  ],
  "meta": {
    "count": 2,
    "total_value": "7335.0000"
  }
}
```

Same per-item rules and GL impact as `PUT /items/{item}/starting-value`. Each line creates its own FIFO layer, spine transaction, and journal entry.

---

### `POST /items/{item}/starting-value/void`

Void an open starting value. **ADMIN only.**

Reverses the GL entry, deletes the opening FIFO layer, and resets quantity on hand (if the layer has not been consumed by sales).

The reversal journal uses the **same date as the original starting-value entry** (`as_of_date`). If that date falls in a closed accounting period (`books_closed_through`), the reversal posts on **today** instead.

#### Request Body (optional)

```json
{
  "void_reason": "Wrong quantity entered"
}
```

#### Response `200 OK`

Returns the starting value with `status: VOIDED`.

---

## Cost correction preview

```
POST /items/{item}/starting-value/correction-preview
```

Read-only impact analysis before correcting opening unit cost after stock has been sold. **ADMIN only.**

### Request Body

```json
{
  "unit_cost": 8.00
}
```

| Field | Required | Description |
|-------|----------|-------------|
| `unit_cost` | Yes | Corrected FIFO unit cost (≥ 0, must differ from current) |
| `qty` | No | **Prohibited** in MVP — opening quantity cannot be changed via correction |

### Response `200 OK`

```json
{
  "data": {
    "blockers": [],
    "warnings": ["1 invoice(s) will have COGS adjusted."],
    "old_unit_cost": "10.0000",
    "new_unit_cost": "8.0000",
    "sold_qty": "30.0000",
    "qty_on_hand": "70.0000",
    "cogs_delta": "-60.0000",
    "equity_delta": "-200.0000",
    "inventory_delta": "-140.0000",
    "affected_invoice_count": 1,
    "affected_invoices": [
      {
        "invoice_id": 201,
        "invoice_number": "INV-001",
        "cogs_delta": -60
      }
    ]
  }
}
```

If an affected invoice falls in a **closed** accounting period (`books_closed_through`), `warnings` includes a note that the COGS adjustment will post in the **current** period.

---

## Cost correction (consumed opening stock)

```
PATCH /items/{item}/starting-value/correct
```

Corrects opening `unit_cost` when the starting-value FIFO layer has been **partially or fully sold**. **ADMIN only.**

### When to use

| Situation | Action |
|-----------|--------|
| Opening stock **not sold** | `PATCH /items/{id}/starting-value` (edit) — or void + re-set |
| Opening stock **sold** (fully or partly) | `PATCH .../correct` |

### Request Body

Same as [Cost correction preview](#cost-correction-preview).

### GL Impact

Two adjustment paths (same pattern as bill cost correction):

| Delta | Journal entry |
|-------|---------------|
| Total opening value change (`qty × (new − old)`) | Dr/Cr **Inventory Asset** vs **Owner Equity** (from `equity_account_id`) |
| Sold portion COGS change | Per affected invoice: Dr/Cr **COGS** vs **Inventory Asset** (COGS true-up) |

Updates:

- `inventory_starting_values` (`unit_cost`, `total_value`)
- `inventory_cost_layers` (`unit_cost`, `total_cost`)
- `invoice_line_layers` and `invoice_lines.cogs_amount` for each sale from that layer

### Response `200 OK`

Returns the updated starting value in `data` plus `correction_summary`:

```json
{
  "data": {
    "unit_cost": "8.0000",
    "total_value": "800.0000"
  },
  "correction_summary": {
    "affected_invoice_count": 1,
    "cogs_delta": "-60.0000",
    "equity_delta": "-200.0000",
    "inventory_delta": "-140.0000",
    "journal_entry_ids": [701, 702]
  }
}
```

### Business rules

- Starting value must be `OPEN` with a linked cost layer
- Layer must be **consumed** (`qty_remaining < qty_purchased`); otherwise use void + re-set
- `unit_cost` must differ from the current layer cost
- Revenue on affected invoices is unchanged; **Income by Customer** COGS/income and **P&L** COGS are updated

### Workflow

1. Optional: `POST /items/{id}/starting-value/correction-preview`
2. `PATCH /items/{id}/starting-value/correct`
3. Reconcile with Income by Customer and P&L for the invoice period

---

## Inventory Transaction Hub

Starting values appear in `GET /inventory-transactions` as:

- `movement_type`: **`STARTING_VALUE`**
- Filter: `?type=starting_value`

Voided starting values are excluded from the hub (same as voided adjustments).

---

## Error Responses

| Status | Scenario |
|--------|----------|
| 401 | Missing or invalid token |
| 403 | Role not permitted |
| 404 | Item not found, or starting value not set (GET/void) |
| 422 | Validation failure, item not inventory, stock already exists, duplicate open starting value, void blocked (layer consumed), cost correction blocked (layer not consumed, unchanged cost), edit blocked (unchanged payload) |

---

## Migration workflow (many SKUs)

1. Bulk-create items via `POST /items` (script)
2. Import opening stock in batches of up to 50:
   - `POST /inventory-starting-values/bulk` with `item_id` or `sku` per line
   - Or `PUT /items/{id}/starting-value` one item at a time
3. Reconcile with `GET /reports/inventory/stock-value`

Example: 1,500 SKUs → ~30 bulk requests (50 lines each).
