# RecalculatePurchaseOrderBillingStatus

## Permission Scope

purchaseOrder

## Overview

RecalculatePurchaseOrderBillingStatus updates purchase-order billing progress from an external billing source such as account payable. The caller provides current billed quantity per purchase-order line. The command owns the purchase-order read and write: it resolves and locks each affected purchase order from the referenced lines, replaces each referenced line's billed quantity, derives the billing status from the order's lines, and updates each affected purchase-order header.

## Business Rules

- Each referenced purchase-order line must exist
- Billed quantity must be zero or positive
- The command does not read account-payable or supplier-bill tables
- The caller is responsible for passing the current source-of-truth billed quantity for each affected purchase-order line
- Purchase orders with no affected lines are not updated

## Process Flow

```mermaid
flowchart TD
    A[Receive billing 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 billed quantities valid?}
    F -->|No| G[Return NEGATIVE_BILLED_QUANTITY]
    F -->|Yes| H[Group affected lines by purchase order]
    H --> I[Load all lines for each affected purchase order]
    I --> J[Apply provided billed quantities and default other lines to zero]
    J --> K[Derive and update billingStatus]
    K --> L[Return updated purchase order ids]
```

## External Dependencies

- None

## Error Scenarios

- **NEGATIVE_BILLED_QUANTITY**: Supplied billed quantity is negative
- **PURCHASE_ORDER_LINE_NOT_FOUND**: Referenced purchase-order line does not exist

## Test Cases

- updates billingStatus to partially billed from supplied line quantities
- updates billingStatus to billed when supplied quantities cover the order
- resets billingStatus to not billed when supplied quantities are zero
- returns no purchase order ids when no line progress is supplied
- returns error when billed quantity is negative
- returns error when a purchase-order line does not exist
- returns error when a referenced line disappears between resolution and locking
