# RecalculatePurchaseOrderReceiptStatus

## Permission Scope

purchaseOrder

## Overview

RecalculatePurchaseOrderReceiptStatus updates purchase-order receipt progress from an external receipt source such as inbound shipment. The caller provides a received-quantity delta per purchase-order line. The command owns the purchase-order read and write: it resolves and locks each affected purchase order, adds the delta to each referenced line's current received quantity, derives the receipt status from the order's lines, and updates each affected purchase-order header.

## Business Rules

- Each referenced purchase-order line must exist
- Each received-quantity delta must be zero or positive
- The command does not read inbound-shipment tables
- The caller passes only the quantity received in this event; the command adds it to the stored value under a row lock so concurrent posts cannot lost-update
- Purchase orders with no affected lines are not updated

## Process Flow

```mermaid
flowchart TD
    A[Receive receipt progress] --> B{Any line progress?}
    B -->|No| C[Return no purchase order ids]
    B -->|Yes| D{All purchase-order lines exist?}
    D -->|No| E[Return PURCHASE_ORDER_LINE_NOT_FOUND]
    D -->|Yes| F{All received-quantity deltas valid?}
    F -->|No| G[Return NEGATIVE_RECEIVED_QUANTITY]
    F -->|Yes| H[Lock affected purchase orders and add deltas to current received quantities]
    H --> I[Group affected lines by purchase order]
    I --> J[Load all lines for each affected purchase order]
    J --> K[Derive and update receiptStatus]
    K --> L[Return updated purchase order ids]
```

## External Dependencies

- None

## Error Scenarios

- **NEGATIVE_RECEIVED_QUANTITY**: Supplied received-quantity delta is negative
- **PURCHASE_ORDER_LINE_NOT_FOUND**: Referenced purchase-order line does not exist

## Test Cases

- updates receiptStatus to partially received from supplied line quantities
- adds the delta onto the existing received quantity
- updates receiptStatus to received when supplied quantities cover the order
- resets receiptStatus to not received when supplied quantities are zero
- returns the updated purchase order ids
- returns no purchase order ids when no line progress is supplied
- returns error when received quantity is negative
- returns error when a purchase-order line does not exist
- returns error when a referenced line disappears between resolution and locking
