# CancelProductionOrder

## Permission Scope

productionOrder

## Overview

CancelProductionOrder abandons a draft or not-yet-started released order. It preserves audit history while blocking further execution updates and cascading cancellation to pending work orders.

## Business Rules

- Target order must exist.
- Only `DRAFT` or `RELEASED` orders may be cancelled.
- Released orders cannot be cancelled once meaningful execution or inventory evidence exists.
- Cancelling a released order cascades cancellation to pending work orders.
- Cancelled orders reject all further execution, completion, and closeout commands.

## Process Flow

```mermaid
flowchart TD
    A[Receive cancel request] --> B{Order exists?}
    B -->|No| C[Return PRODUCTION_ORDER_NOT_FOUND]
    B -->|Yes| D{Status cancellable?}
    D -->|No| E[Return PRODUCTION_ORDER_NOT_CANCELLABLE]
    D -->|Yes| F{Execution or inventory evidence exists?}
    F -->|Yes| G[Return EXECUTION_ALREADY_STARTED]
    F -->|No| H[Cancel order and pending work orders]
    H --> I[Return cancelled order]
```

## External Dependencies

- [WorkOrder](../model/WorkOrder.md) - Pending child work orders are cancelled with the parent order.

## Error Scenarios

- **PRODUCTION_ORDER_NOT_FOUND**: Referenced production order does not exist
- **PRODUCTION_ORDER_NOT_CANCELLABLE**: The current status does not allow cancellation.
- **EXECUTION_ALREADY_STARTED**: Work-order execution evidence already exists for this production order
- **INVENTORY_HANDOFF_EXISTS**: Inventory issue or receipt evidence already exists for this production order

## Test Cases

- cancels a draft production order
- cancels a released order before execution starts
- returns error when the order does not exist
- returns error when the status does not allow cancellation
- returns error when execution evidence already exists
- returns error when inventory handoff evidence already exists
- cascades cancellation to pending work orders
