# UpdateStockReservation

## Permission Scope

stockReservation

## Overview

updateStockReservation updates one existing OPEN stock reservation row by `id`. It sets the current reservation row state, such as `reservedQuantity`, `requiredDate`, source references, and optional location, instead of applying a release delta.

## Business Rules

- An OPEN reservation must exist for the provided `id`
- Provided fields are partially updated while omitted fields are preserved
- `reservedQuantity` cannot be negative and cannot be less than `consumedQuantity`
- Updated open reservation quantity is derived as `max(reservedQuantity - consumedQuantity, 0)`
- Updated open reservation quantity must not exceed site-level available-to-promise after excluding the reservation's current open quantity
- Storage location must exist under the effective site when the location or site changes
- Does not create InventoryLedger entries or mutate StockLevel

## Process Flow

```mermaid
flowchart TD
    A[Receive update request] --> B{OPEN reservation exists?}
    B -->|No| C[Return reservation error]
    B -->|Yes| D{Updated quantities valid?}
    D -->|No| E[Return error: INVALID_RESERVATION_QUANTITIES]
    D -->|Yes| F{Delta-aware ATP sufficient?}
    F -->|No| G[Return error: INSUFFICIENT_AVAILABLE_STOCK]
    F -->|Yes| H[Update StockReservation fields]
    H --> I[Return updated reservation balance]
```

## External Dependencies

- [item-management::Item](../../../item-management/docs/model/Item.md) - Validates updated item when provided
- [organization::Site](../../../organization/docs/model/Site.md) - Validates updated site when provided

## Error Scenarios

- **STOCK_RESERVATION_NOT_FOUND**: Referenced stock reservation does not exist
- **STOCK_RESERVATION_NOT_OPEN**: Stock reservation is not OPEN
- **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

- updates reserved quantity successfully
- partially updates required date without rewriting omitted fields
- updates source document id for a reservation slice
- returns error when changing site would leave the existing location outside the site
- allows changing site when clearing the location
- returns error when reservation not found
- returns error when reservation is not open
- returns error when reserved quantity is less than consumed quantity
- returns error when updated open quantity exceeds available stock
