# CompleteWorkOrder

## Permission Scope

workOrder

## Overview

CompleteWorkOrder finishes an operation after final execution evidence is recorded. The command may trigger manual-issue reconciliation, backflush issue intent, and intermediate or finished receipt handoff to inventory.

## Business Rules

- Target work order must exist and be in `IN_PROGRESS`.
- The work order must have started before completion.
- Completion transaction must report positive completed quantity or valid zero-quantity completion under an explicit bypass policy.
- Backflush consumption must not duplicate quantities already issued manually.
- Required receipt-handoff payload fields must be present when output receipt is required.
- Completing the work order updates parent production-order progress.

## Process Flow

```mermaid
flowchart TD
    A[Receive complete request] --> B{Work order exists and is IN_PROGRESS?}
    B -->|No| C[Return WORK_ORDER_NOT_COMPLETABLE]
    B -->|Yes| D[Validate completion quantities]
    D --> E{Backflush required?}
    E -->|Yes| F[Emit material issue intent]
    E -->|No| G[Skip issue intent]
    F --> H{Receipt handoff required?}
    G --> H
    H -->|Yes| J[Emit ManufacturingReceiptHandoff]
    H -->|No| K[Skip receipt handoff]
    J --> L[Set status to COMPLETE]
    K --> L
    L --> M[Roll up parent progress]
    M --> N[Return completed work order]
```

## External Dependencies

- [ProductionOrder](../model/ProductionOrder.md) - Completion rolls up into parent order progress and completion gating.

## Error Scenarios

- **WORK_ORDER_NOT_FOUND**: Referenced work order does not exist
- **WORK_ORDER_NOT_COMPLETABLE**: Work order is not in `IN_PROGRESS`.
- **WORK_ORDER_NOT_STARTED**: No actual start evidence exists.
- **INVALID_COMPLETION_QUANTITY**: Completion quantity is invalid for the transaction.
- **DUPLICATE_BACKFLUSH_RISK**: Requested backflush would duplicate manual issue quantity.
- **RECEIPT_HANDOFF_REQUIRED**: Required receipt-handoff data is incomplete.

## Test Cases

- completes an in-progress work order with final quantity reporting
- returns error when the work order does not exist
- returns error when the work order is not in progress
- returns error when the work order was never started
- returns error when completion quantity is invalid
- returns error when backflush would duplicate manual issue
- emits receipt handoff when output receipt is required
- returns error when receipt is required but receipt data is missing
- rolls up completion to the parent order
- allows zero-quantity completion only under an explicit bypass policy
- emits a backflush handoff when completion requires backflush consumption
