# RecordChannelOrder

## Permission Scope

marketplace

## Overview

RecordChannelOrder creates or refreshes the normalized representation of an external order payload. It is the idempotent write path that stores source identity, normalized commercial fields, raw troubleshooting context, and the initial PENDING_CONVERSION lifecycle state.

## Business Rules

- Channel-order identity must be unique by company, channel, and external order identity.
- The command must be idempotent across duplicate deliveries of the same external event.
- A newly created channel order always starts in PENDING_CONVERSION status.
- Raw payload reference or normalized troubleshooting context must be preserved.

## Process Flow

```mermaid
flowchart TD
    A[Receive inbound payload] --> B[Resolve channel and external identity]
    B --> C{Channel order already exists?}
    C -->|No| D[Create ChannelOrder in PENDING_CONVERSION]
    C -->|Yes| E[Update existing ChannelOrder idempotently]
    D --> F[Persist normalized payload context]
    E --> F
    F --> G[Return recorded channel order]
```

## External Dependencies

- [getChannel](../queries/GetChannel.md) - Validate channel scope for the inbound order.
- [getListingByExternalIdentifier](../queries/GetListingByExternalIdentifier.md) - Resolve listing mapping from external identifiers when available.

## Error Scenarios

- **CHANNEL_NOT_FOUND**: Referenced channel does not exist
- **EXTERNAL_ORDER_ID_REQUIRED**: External order identity is required.
- **CROSS_COMPANY_REFERENCE**: One or more referenced records belong to a different company

## Test Cases

- creates a new pending channel order from inbound payload
- updates an existing channel order idempotently on duplicate delivery
- preserves raw troubleshooting context
- throws when external order identity is missing
- throws when the channel does not exist
- throws on cross-company reference
