# CreateStockReservation

## Permission Scope

stockReservation

## Overview

createStockReservation records a new OPEN stock reservation slice for a source document line at a site. Reserved stock remains in the AVAILABLE StockLevel stock type because it is still physically present, but OPEN reservation quantity is subtracted from site-level availability.

## Business Rules

- A source line may have multiple StockReservation rows when demand is split by site, storage location, date, lot, or future supply source
- Create is append-only for reservation rows; duplicate source and inventory dimensions are allowed and contribute additively to reserved quantity
- Reserved quantity must be greater than zero
- Item must exist
- Site must exist
- Storage location must exist under the site when `storageLocationId` is provided
- Reserved quantity must not exceed site-level available-to-promise: sum of active-location `StockLevel(AVAILABLE).quantity` minus other OPEN reservation quantity for the item and site
- Creates StockReservation with `consumedQuantity = 0` and `status = OPEN`
- Does not create InventoryLedger entries or mutate StockLevel

## Process Flow

```mermaid
flowchart TD
    A[Receive create request] --> D{Item and site valid?}
    D -->|No| E[Return not found error]
    D -->|Yes| F{Optional location valid?}
    F -->|No| G[Return error: STORAGE_LOCATION_NOT_FOUND]
    F -->|Yes| H{Site ATP >= reservedQuantity?}
    H -->|No| I[Return error: INSUFFICIENT_AVAILABLE_STOCK]
    H -->|Yes| J[Insert OPEN StockReservation]
    J --> K[Return reservation balance]
```

## External Dependencies

- [item-management::Item](../../../item-management/docs/model/Item.md) - Validates that the referenced item exists
- [organization::Site](../../../organization/docs/model/Site.md) - Validates that the referenced site exists

## Error Scenarios

- **INVALID_RESERVATION_QUANTITIES**: Quantity values are invalid for a stock reservation
- **ITEM_NOT_FOUND**: Referenced item does not exist
- **SITE_NOT_FOUND**: Referenced site does not exist
- **STORAGE_LOCATION_NOT_FOUND**: Referenced storage location does not exist
- **INSUFFICIENT_AVAILABLE_STOCK**: Available stock is less than the requested quantity

## Test Cases

- creates reservation successfully
- appends another reservation row for the same source line
- returns error when reserved quantity is zero or negative
- returns error when item not found
- returns error when site not found
- returns error when optional location not found
- returns error when insufficient available stock
