# CloseSalesOrder

## Permission Scope

salesOrder

## Overview

CloseSalesOrder marks the commercial commitment as complete once no meaningful open balance remains. It is used when all obligations are fulfilled or the residual balance has been cancelled or written off according to policy.

## Business Rules

- Only executable or post-execution orders may be closed.
- All remaining open quantities must be fulfilled, cancelled, or written off before closure.
- Closing the order must preserve line-level shipped and invoiced history.

## Process Flow

```mermaid
flowchart TD
    A[Receive close request] --> B[Load sales order]
    B --> C[Calculate remaining open balance]
    C --> D{Open balance cleared?}
    D -->|No| E[Return ORDER_NOT_CLOSABLE]
    D -->|Yes| F[Set status to CLOSED]
    F --> G[Return closed order]
```

## External Dependencies

- None

## Error Scenarios

- **SALES_ORDER_NOT_FOUND**: Referenced sales order does not exist.
- **INVALID_ORDER_STATUS**: Sales order status does not allow this operation
- **ORDER_NOT_CLOSABLE**: Remaining open balance still exists.

## Test Cases

- closes an order with no remaining open balance
- throws when remaining quantity is still open
- throws when order status does not allow closure
