# CancelAccountReceivableDocument

## Permission Scope

accountReceivableDocumentOperation

## Overview

cancelAccountReceivableDocument cancels a DRAFT or REGISTERED AR document. POSTED documents are immutable and require a correction document.

## Business Rules

- DRAFT cancellation creates no accounting or sales effects
- REGISTERED cancellation removes the document from sales billing progress
- POSTED documents cannot be cancelled
- Cancellation and projection rebuilding run in one transaction

## Process Flow

```mermaid
flowchart TD
    A[Lock document] --> B{DRAFT or REGISTERED?}
    B -->|No| C[Return invalid status]
    B -->|Yes| D[Mark CANCELLED]
    D --> E[Rebuild sales billing when previously REGISTERED]
```

## External Dependencies

- sales [RecalculateSalesOrderBillingStatus](../../../sales/docs/command/RecalculateSalesOrderBillingStatus.md)

## Error Scenarios

- **DOCUMENT_NOT_FOUND**: Referenced AR document does not exist
- **INVALID_DOCUMENT_STATUS**: AR document status does not allow this operation
- **SALES_ORDER_BILLING_SYNC_FAILED**: Sales-order billing projection could not be synchronized

## Test Cases

- cancels a draft invoice without updating sales billing quantity
- cancels a registered invoice and removes its sales billing quantity
- rejects cancellation of a posted invoice
