# 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 affected purchase orders from the referenced lines, rolls line quantities up with `deriveBillingStatus`, 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 updated purchase orders]
    B -->|Yes| D{All billed quantities valid?}
    D -->|No| E[Return NEGATIVE_BILLED_QUANTITY]
    D -->|Yes| F{All purchase-order lines exist?}
    F -->|No| G[Return PURCHASE_ORDER_LINE_NOT_FOUND]
    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 orders]
```

## 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 updated purchase orders when no line progress is supplied
- returns error when billed quantity is negative
- returns error when a purchase-order line does not exist
