# Negative stock (QBO-style) — Non-breaking implementation checklist

Admin oversell with estimated COGS at sale and COGS true-up when bills are received.  
**Default: feature OFF** — existing companies and flows must behave exactly as today.

Related design: conversation outline (company flag + per-invoice flag + `BackorderService` + `CogsTrueUpService`).

**Phase 1 status: DONE** (foundation — flags, schema, draft bypass; post still uses existing FIFO strict check).

**Phase 2 status: DONE** (oversell post, estimated COGS, backorders, void restore; bill true-up not yet).

**Phase 3 status: DONE** (QBO-style COGS true-up on bill receive + void reversal).

---

## Golden rules (every PR)

- [ ] **Opt-in only** — `companies.allow_negative_inventory` defaults `false`; `invoices.allow_negative_stock` defaults `false`
- [ ] **Early exit** — if company flag off OR invoice flag false OR no open backorders → run **existing** code path unchanged
- [ ] **No signature breakage** — new params on shared methods must default to current behavior (`$allowNegative = false`)
- [ ] **Additive schema** — new tables/columns nullable or defaulted; no NOT NULL on existing rows without default
- [ ] **Additive API** — new JSON fields only; do not rename/remove existing fields
- [ ] **Separate tests** — new `NegativeStockInvoiceApiTest.php`; do not weaken existing `InvoiceApiTest` assertions
- [ ] **Full suite green** — `php artisan test` passes before merge (every phase)

---

## Pre-implementation (before Phase 1)

| Task | Status |
|------|--------|
| Confirm accounting decisions: true-up JE date = **bill date** (QBO default) | Done |
| Confirm v1 void rule: **block** void/amend on invoice lines with cleared backorders | Done |
| Confirm COGS estimate order: layer avg → `standard_cost` → `0` | Done |
| Snapshot baseline: run full test suite + note passing count | Pending |

---

## Phase 1 — Foundation (flags + schema, no COGS changes)

Company + invoice flags, backorder tables, guard bypass. **No bill or FIFO behavior change when flags off.**

### Migrations

| Task | Status |
|------|--------|
| Add `companies.allow_negative_inventory` BOOLEAN NOT NULL DEFAULT `false` | Pending |
| Add `invoices.allow_negative_stock` BOOLEAN NOT NULL DEFAULT `false` | Pending |
| Create `inventory_backorders` table | Pending |
| Create `inventory_backorder_clearances` table | Pending |
| Create `invoice_line_backorder_allocations` (or extend layers with nullable FKs) | Pending |

### Models & config

| Task | Status |
|------|--------|
| `InventoryBackorder` model + relations | Pending |
| `InventoryBackorderClearance` model | Pending |
| `Invoice` — cast/fill `allow_negative_stock` | Pending |
| `Company` — cast/fill `allow_negative_inventory` | Pending |

### API (company)

| Task | Status |
|------|--------|
| `UpdateCompanyRequest` — `allow_negative_inventory` (ADMIN only) | Pending |
| `CompanyResource` — expose field | Pending |
| `docs/api/company.md` | Pending |

### API (invoice — draft only, no oversell post yet)

| Task | Status |
|------|--------|
| `StoreInvoiceRequest` / `UpdateInvoiceRequest` — accept `allow_negative_stock` | Pending |
| Authorize: ADMIN only + company flag on | Pending |
| `InvoiceDraftService` — persist flag on invoice | Pending |
| `InvoiceResource` — expose `allow_negative_stock` | Pending |

### Stock guard (gated bypass)

| Task | Status |
|------|--------|
| `ItemGuardService::validateDocumentLines` — add `$allowNegativeStock` param (default `false`) | Pending |
| Invoice requests pass `allowNegativeStock` only when ADMIN + company flag + request flag | Pending |
| **Verify:** flag off → identical 422 insufficient-stock errors as today | Pending |

### Phase 1 non-breaking gates

- [ ] `ItemGuardService` default `$allowNegativeStock = false` — existing callers unchanged
- [ ] `FifoInventoryService` — **not modified** in Phase 1
- [ ] `InvoicePostingService` — **not modified** in Phase 1 (or post still fails on shortfall)
- [ ] `BillProcessingService` — **not modified** in Phase 1
- [ ] `reconcileQtyOnHand` — **not modified** in Phase 1
- [ ] All existing `InvoiceApiTest` tests pass unchanged

### Phase 1 tests

| Task | Status |
|------|--------|
| `test_accountant_cannot_set_allow_negative_stock` | Pending |
| `test_admin_cannot_oversell_when_company_flag_off` | Pending |
| `test_admin_can_create_draft_with_allow_negative_stock_when_company_on` (post may still fail until Phase 2) | Pending |
| `test_existing_insufficient_stock_error_unchanged_when_flag_false` | Pending |

---

## Phase 2 — Oversell post + estimated COGS

Admin can post oversold invoices; provisional COGS at sale. **Bill path still unchanged.**

### Services

| Task | Status |
|------|--------|
| `BackorderService::estimateUnitCost(Item)` | Pending |
| `BackorderService::createFromInvoiceLine(...)` | Pending |
| `FifoInventoryService` — new method `consumeLayersAllowingBackorder()` OR optional `$allowNegative = false` on existing method | Pending |
| **Gate:** `$allowNegative === false` → throw on shortfall (current behavior byte-for-byte) | Pending |
| `InvoicePostingService::publish` — backorder branch only when `$invoice->allow_negative_stock` | Pending |
| `InvoicePostingService::unpublish` — reverse backorders only when allocations exist | Pending |
| `InvoicePostingService::assertSufficientStockForLines` — respect invoice flag on amend | Pending |

### `qty_on_hand` (gated)

| Task | Status |
|------|--------|
| Update `reconcileQtyOnHand` to subtract open backorders **only when** item has open backorders | Pending |
| **Verify:** item with zero backorders → `qty_on_hand` = sum(layers) exactly as today | Pending |

### API response

| Task | Status |
|------|--------|
| `InvoiceLineResource` — `backorder_qty`, optional `estimated_cogs_amount` | Pending |
| `ItemResource` — `backorder_qty` (0 when none) | Pending |
| `docs/api/invoices.md` — oversell section | Pending |
| `docs/api/items.md` — backorder fields | Pending |

### Phase 2 non-breaking gates

- [ ] Invoice with `allow_negative_stock = false` uses **identical** publish path (no new branches entered)
- [ ] `consumeLayers` throw message unchanged for normal failures
- [ ] No COGS true-up on bills yet
- [ ] `GrossProfitSummaryService` — no code changes; GP unchanged for non-oversell
- [ ] Full regression: `InvoiceApiTest`, `BillApiTest`, `GrossProfitSummaryTest`

### Phase 2 tests

| Task | Status |
|------|--------|
| `test_admin_can_post_oversold_invoice` — backorder row, negative `qty_on_hand` | Pending |
| `test_oversell_cogs_uses_fifo_then_estimate` | Pending |
| `test_estimate_falls_back_to_standard_cost` | Pending |
| `test_void_oversold_invoice_before_true_up` — restores stock + COGS | Pending |
| `test_normal_invoice_post_unchanged` (regression) | Pending |

---

## Phase 3 — QBO COGS true-up on bill receive

Bill receive clears backorders and posts COGS adjustment JE. **Only runs when open backorders exist.**

### Services

| Task | Status |
|------|--------|
| `BackorderService::allocateReceipt(Item, qty, source, ...)` — FIFO by `sold_at` | Pending |
| `CogsTrueUpService::applyAdjustment(...)` — post JE, update `invoice_lines.cogs_amount` | Pending |
| `BillProcessingService::receiveIntoBooks` — **before** `receiveLayers`: | Pending |
| &nbsp;&nbsp;→ if `openQtyForItem($item) <= 0` → skip, existing path only | Pending |
| &nbsp;&nbsp;→ else allocate + true-up, then `receiveLayers` on remainder | Pending |
| `BillProcessingService::unreceive` — reverse true-up JEs + restore backorders | Pending |

### GL

| Task | Status |
|------|--------|
| True-up JE: `reference_transaction_id` = bill transaction | Pending |
| `is_auto_generated = true` | Pending |
| Link JE in `inventory_backorder_clearances.journal_entry_id` | Pending |
| Adjustment date = bill `txn_date` | Pending |

### API / docs

| Task | Status |
|------|--------|
| Bill show — optional `cogs_true_ups` metadata | Pending |
| `docs/api/bills.md` — true-up side effect | Pending |
| `docs/api/gross-profit-summary.md` — note GP may shift on bill date | Pending |
| `docs/features-list.md` — negative stock capability | Pending |

### Phase 3 non-breaking gates

- [ ] Bill for item **without** backorders → `receiveIntoBooks` identical to today (no extra JEs)
- [ ] Bill GL lines (Inventory Dr, AP Cr) unchanged in amount for non-backorder qty
- [ ] No true-up when `actual_unit_cost === estimated_unit_cost` (no spurious JE)
- [ ] Full regression: `BillApiTest`, `GrossProfitSummaryTest`, `InventoryTransactionApiTest`

### Phase 3 tests

| Task | Status |
|------|--------|
| `test_bill_true_up_increases_cogs_when_actual_higher` | Pending |
| `test_bill_true_up_decreases_cogs_when_actual_lower` | Pending |
| `test_bill_excess_qty_creates_fifo_layer_after_backorder_cleared` | Pending |
| `test_gross_profit_includes_true_up_on_bill_date` | Pending |
| `test_bill_without_backorders_unchanged` (regression) | Pending |
| `test_bill_void_reverses_true_up` | Pending |

---

## Phase 4 — Hub, amend hardening, polish

| Task | Status |
|------|--------|
| `InventoryTransactionHubService` — `BACKORDER_SALE`, `COGS_TRUE_UP` movement types | DONE |
| `docs/api/inventory-transactions.md` | DONE |
| Block void/amend when backorder has clearances (v1 rule) | DONE |
| Positive inventory adjustment can clear backorders (same as bill) | DONE |
| `ItemGuardService::assertDeletable` — block if open backorders | DONE |

**Frontend API guide:** [docs/api/negative-stock.md](./api/negative-stock.md)

### Phase 4 non-breaking gates

- [ ] Hub additive types only; existing movement types unchanged
- [ ] Amend on normal (non-oversell) invoices unchanged

---

## Per-file review checklist

Use before merging any PR that touches these files.

### `FifoInventoryService.php`

- [ ] Default param / separate method preserves throw-on-shortfall for normal calls
- [ ] `reconcileQtyOnHand` only subtracts backorders when rows exist
- [ ] No change to `receiveLayers` behavior for bills without backorders

### `ItemGuardService.php`

- [ ] `$allowNegativeStock` defaults `false`
- [ ] All non-invoice callers unchanged (bills already use `checkStock: false`)

### `InvoicePostingService.php`

- [ ] Backorder branch gated on `$invoice->allow_negative_stock`
- [ ] Normal publish COGS + JE structure unchanged when no backorder qty
- [ ] `unpublish` does not touch invoices without backorder allocations

### `BillProcessingService.php`

- [ ] `allocateReceipt` called only when `openQtyForItem > 0`
- [ ] `receiveLayers` qty = bill qty minus qty used for backorder clearance
- [ ] `standard_cost` update unchanged

### `InvoiceAmendmentService.php`

- [ ] Stock assert respects persisted `allow_negative_stock` on invoice
- [ ] Normal amend path unchanged for standard invoices

### `GrossProfitSummaryService.php`

- [ ] Prefer **no edits** — true-up flows through COGS account via GL
- [ ] If edited, verify non-oversell periods unchanged

---

## Regression suite (run every phase)

```bash
php artisan test --filter=InvoiceApiTest
php artisan test --filter=BillApiTest
php artisan test --filter=GrossProfitSummaryTest
php artisan test --filter=InventoryAdjustmentApiTest
php artisan test --filter=InventoryTransactionApiTest
php artisan test --filter=SalesTransactionApiTest
php artisan test
```

| Suite | Must pass |
|-------|-----------|
| `InvoiceApiTest` | All existing cases without modification |
| `BillApiTest` | All existing cases |
| `GrossProfitSummaryTest` | All existing cases (until oversell tests added separately) |
| Full `php artisan test` | Green |

---

## Manual smoke test (staging)

### With feature OFF (default company)

- [ ] Create invoice qty > on hand → 422 insufficient stock
- [ ] Post normal invoice → COGS + `qty_on_hand` as before
- [ ] Receive bill → inventory + AP only, no COGS line
- [ ] GP summary matches pre-deploy baseline for same period

### With feature ON

- [ ] ADMIN + `allow_negative_stock: true` → draft + post succeeds
- [ ] ACCOUNTANT same request → 403
- [ ] Receive bill → `cogs_amount` on invoice line updates; GP shifts on bill date
- [ ] Void oversold invoice (no true-up yet) → backorder cleared, COGS reversed

---

## Definition of done (feature complete)

- [ ] All phases 1–3 checklist items complete
- [ ] Full test suite green
- [ ] API docs updated (`invoices`, `company`, `bills`, `items`)
- [ ] No behavior change for companies with `allow_negative_inventory = false`
- [ ] Code review sign-off on per-file checklist above
- [ ] Staging smoke test passed (feature off + feature on)

---

## Files expected to change (summary)

### New

- `database/migrations/*_negative_stock_*.php`
- `app/Modules/Inventory/Models/InventoryBackorder.php`
- `app/Modules/Inventory/Models/InventoryBackorderClearance.php`
- `app/Modules/Inventory/Services/BackorderService.php`
- `app/Modules/Inventory/Services/CogsTrueUpService.php` (or `Financials`)
- `tests/Feature/NegativeStockInvoiceApiTest.php`
- `docs/negative-stock-checklist.md` (this file)

### Edited (gated branches only)

- `ItemGuardService.php`
- `FifoInventoryService.php`
- `InvoicePostingService.php`
- `BillProcessingService.php`
- `InvoiceAmendmentService.php`
- `StoreInvoiceRequest.php`, `UpdateInvoiceRequest.php`
- `UpdateCompanyRequest.php`, `CompanyResource.php`, `InvoiceResource.php`
- `ItemResource.php`
- `docs/api/*.md`

### Must stay behavior-identical when feature off

- `GrossProfitSummaryService.php` (ideal: no edits)
- `InventoryAdjustmentService.php` (until Phase 4)
- `PaymentAllocationService.php`
- All Payment / Bill Payment tests
