# CreatePurchaseChangeOrder

## Permission Scope

purchaseOrder

## Overview

CreatePurchaseChangeOrder creates a new change order in `DRAFT` status against an existing `ORDERED` purchase order, proposing line-level additions, modifications, or removals subject to approval before taking effect.

## Business Rules

- Target purchase order must exist
- Only purchase orders with `orderStatus` = `ORDERED` can have change orders created against them
- No other open change order (`DRAFT`, `SUBMITTED`, or `APPROVED`) may exist for the same purchase order
- `fromRevisionNumber` is automatically set from the purchase order's `currentRevisionNumber`
- Input includes `purchaseOrderId`, `reason`, and one or more lines each specifying an `action` (ADD, MODIFY, or REMOVE)
- MODIFY and REMOVE lines must reference an `originalPurchaseOrderLineId`
- ADD lines must specify `itemId`, `quantity`, and `unitPrice`
- Change order is always created with status `DRAFT`

## Process Flow

```mermaid
flowchart TD
    A[Receive create request] --> B{Purchase order exists?}
    B -->|No| C[Return PO_NOT_FOUND]
    B -->|Yes| D{Status is ORDERED?}
    D -->|No| E[Return PO_NOT_ORDERED]
    D -->|Yes| F{Open change order already exists?}
    F -->|Yes| G[Return OPEN_CHANGE_ORDER_EXISTS]
    F -->|No| H[Set fromRevisionNumber from PO currentRevisionNumber]
    H --> I[Insert change order and lines in DRAFT]
    I --> J[Return created change order]
```

## External Dependencies

- None

## Error Scenarios

- **PO_NOT_FOUND**: Target purchase order does not exist
- **PO_NOT_ORDERED**: Purchase order is not in `ORDERED` status
- **OPEN_CHANGE_ORDER_EXISTS**: Another open change order (`DRAFT`, `SUBMITTED`, or `APPROVED`) already exists for this purchase order

## Test Cases

- creates a draft change order against a valid ordered purchase order
- auto-sets fromRevisionNumber from the PO's currentRevisionNumber
- creates change order lines with ADD, MODIFY, and REMOVE actions
- returns error when purchase order does not exist
- returns error when purchase order is not in ORDERED status
- returns error when an open change order already exists for the purchase order
- returns error when creating against a DRAFT purchase order
- returns error when creating against a CANCELLED purchase order
- returns error when creating against a CLOSED purchase order
- defaults fromRevisionNumber to 1 when currentRevisionNumber is null
