# GetPurchaseOrder

## Overview

GetPurchaseOrder retrieves a single purchase order with its lines, frozen commercial snapshots, and fulfillment progress.

## Business Rules

- Accepts lookup by `{ id }` or by `{ companyId, externalSupplierOrderReference }`
- Returns purchase orders in any `orderStatus` so cancelled and closed documents remain auditable
- Response includes `orderStatus`, `receiptStatus`, `billingStatus`, and `revisionNumber` as separate fields
- Response includes line-level remaining quantity to receive and remaining quantity to bill
- Response includes received and billed quantities computed directly per line (sum of posted GoodsReceiptLine and MATCHED PurchaseBillLine records referencing each line)
- Only active lines (lineStatus = ACTIVE) represent current targets; CANCELLED lines are excluded from fulfillment totals
- Response includes payment-term snapshot and matched price-rule references when present
- Returns null when no purchase order matches the lookup

## Process Flow

```mermaid
flowchart TD
    A[Receive lookup input] --> B{Lookup by id or external reference?}
    B -->|id| C[Select PurchaseOrder by id]
    B -->|external reference| D[Select PurchaseOrder by company + external reference]
    C --> E{Order found?}
    D --> E
    E -->|Yes| F[Load lines, snapshots, and fulfillment totals]
    E -->|No| G[Return null]
    F --> H[Compute received and billed quantities per line]
    H --> I[Return purchase order]
```

## External Dependencies

- None

## Error Scenarios

- **PURCHASE_ORDER_NOT_FOUND**: Referenced purchase order does not exist

## Test Cases

- returns purchase order when found by id
- returns purchase order when found by company and external supplier order reference
- returns lines with the order
- returns revisionNumber on the order
- returns null when purchase order is not found
- returns received and billed quantities per line
