# CancelAccountPayableDocument

## Permission Scope

accountPayableDocument

## Overview

cancelAccountPayableDocument cancels an unposted AP document. DRAFT and REGISTERED documents can be cancelled because they have not created an accounting event. POSTED documents cannot be cancelled; supplier corrections and full offsets are represented by separate AP correction documents.

## Business Rules

- DRAFT AP documents can be cancelled
- REGISTERED AP documents can be cancelled
- POSTED documents cannot be cancelled
- Cancellation sets cancelledAt
- Cancellation does not delete AP lines
- Cancelling a REGISTERED INVOICE feeds purchase-order billing progress back to purchase

## Process Flow

```mermaid
flowchart TD
    A[Receive cancel AP document request] --> B{Document exists?}
    B -->|No| C[Return error: AP document not found]
    B -->|Yes| D{Status is DRAFT or REGISTERED?}
    D -->|No| E[Return error: invalid AP document status]
    D -->|Yes| F[Transition AP document to CANCELLED]
    F --> G[Sync purchase-order billing status when cancelling a registered invoice]
    G --> H[Return cancelled AP document]
```

## External Dependencies

- [recalculatePurchaseOrderBillingStatus](../../../purchase/docs/command/RecalculatePurchaseOrderBillingStatus.md) - Recalculates PO billing progress after registered AP invoice cancellation

## Error Scenarios

- **AP_DOCUMENT_NOT_FOUND**: Referenced AP document does not exist
- **AP_INVALID_DOCUMENT_STATUS**: AP document status does not allow this operation
- **AP_PURCHASE_ORDER_BILLING_SYNC_FAILED**: Purchase-order billing status sync failed for the AP document

## Test Cases

- cancels DRAFT AP document
- cancels REGISTERED AP document
- syncs purchase-order billing status when cancelling REGISTERED AP invoice
- returns error when AP document does not exist
- returns error when AP document is POSTED
- returns error when purchase-order billing sync fails
