# UpdateAccountPayableDocument

## Permission Scope

accountPayableDocument

## Overview

updateAccountPayableDocument updates a DRAFT AP document. Header changes are supplied under `headerPatch`. Commercial line changes are incremental through `addLines`, `updateLines`, and `removeLineIds`; distributions are changed inside their owning line edit through `addDistributions`, `updateDistributions`, and `removeDistributionLineIds`. Due schedule changes are supplied as a full replacement because the schedule is document-level DRAFT data.

## Business Rules

- Added lines follow the same account determination as creation
- Distributions added to an existing line need no derivation: that line already balances to its gross amount
- A derived distribution belongs to the system: it cannot be updated or removed through a line edit
- When a line patch touches a derivation input (net amount, quantity, unit price, source type, or purchase order line reference), the line's derived accrual and invoice price variance distributions are recomputed from the patched line and replace the stored ones
- Only DRAFT AP documents can be updated
- Header patch may update document type, dates, amounts, description, currency, and payable control account
- Line additions, updates, and removals are applied to the effective line set
- Distribution additions under new lines and distribution additions, updates, and removals under existing line edits are applied to the effective distribution set
- Effective line set must contain at least one line
- Effective line gross amounts must sum to the effective header total
- Effective distribution amounts under each line must sum to that line's gross amount
- Effective distribution amounts must sum to the effective header total
- When `dueSchedule` is supplied, it replaces the document's due schedule; each due amount must be positive and the due schedule total must equal the effective header total
- Lines removed or updated by id must exist under the AP document
- The same line id cannot appear in both `updateLines` and `removeLineIds`
- Existing distribution ids updated or removed under a line edit must belong to that line
- Each effective line is either purchase-order sourced (sourceType PURCHASE_ORDER) carrying a purchase order line reference, positive quantity, positive unit price, and a unit of measure, or amount-only carrying none of them
- Each effective purchase-order sourced line net amount must equal quantity times unit price
- Existing and new distribution accounts must exist and be ACTIVE
- Updated payable control account must exist and be ACTIVE

## Process Flow

```mermaid
flowchart TD
    A[Receive update AP document request] --> B{Document exists?}
    B -->|No| C[Return error: AP document not found]
    B -->|Yes| D{Status is DRAFT?}
    D -->|No| E[Return error: invalid AP document status]
    D -->|Yes| M{Updated payable control account exists?}
    M -->|No| N[Return account error]
    M -->|Yes| F[Load existing lines]
    F --> G{Line-owned distribution references valid?}
    G -->|No| H[Return line not found error]
    G -->|Yes| I{Effective amounts valid?}
    I -->|No| J[Return validation error]
    I -->|Yes| K[Update header and mutate lines, distributions, and due schedule]
    K --> L[Return updated AP document]
```

## External Dependencies

- [coa-management::GetAccount](../../../coa-management/docs/query/GetAccount.md) - Validates an updated payable control GL account exists and is ACTIVE
- [coa-management::ListAccounts](../../../coa-management/docs/query/ListAccounts.md) - Validates distribution GL accounts exist and are ACTIVE
- [purchase::ListPurchaseOrderLinesForMatching](../../../purchase/docs/query/ListPurchaseOrderLinesForMatching.md) - Resolves the ordered item and whether an added line requires a physical receipt
- [inventory::ResolveItemValuationPolicies](../../../inventory/docs/query/ResolveItemValuationPolicies.md) - Resolves the valuation policy governing the ordered item

## Error Scenarios

- **AP_SUPPLIER_ACCOUNT_NOT_FOUND**: Referenced supplier account does not exist

- **AP_INVALID_SUPPLIER_ACCOUNT**: Business partner is unavailable for transactions or belongs to another company

- **AP_PURCHASE_ORDER_ACCOUNT_MISMATCH**: Referenced purchase order belongs to a different company or supplier account

- **AP_ACCRUAL_ACCOUNT_UNRESOLVED**: Neither the ordered item's valuation policy nor a company default policy resolves the posting accounts for a receipt-required purchase order line
- **AP_DOCUMENT_NOT_FOUND**: Referenced AP document does not exist
- **AP_INVALID_DOCUMENT_STATUS**: AP document status does not allow this operation
- **AP_DOCUMENT_LINE_NOT_FOUND**: Referenced AP document line does not exist
- **AP_MINIMUM_LINES_NOT_MET**: AP document must have at least one line and one distribution
- **AP_INVALID_AMOUNT**: AP document, line, quantity, unit price, or distribution amount is not positive
- **AP_LINE_TOTAL_MISMATCH**: AP line gross total or distribution total does not match the document total
- **AP_LINE_SOURCE_INCONSISTENT**: AP line source fields, correction target, or values are inconsistent
- **AP_LINE_EDIT_CONFLICT**: AP document line cannot be updated and removed in the same command
- **AP_DERIVED_DISTRIBUTION_IMMUTABLE**: Derived distribution cannot be updated or removed directly; it is recomputed when its line changes
- **AP_LINE_AMOUNT_MISMATCH**: AP line net amount does not equal quantity times unit price
- **AP_DUE_SCHEDULE_INVALID**: AP due schedule must have positive amounts and sum to the document total
- **ACCOUNT_NOT_FOUND**: Referenced GL account does not exist
- **ACCOUNT_INACTIVE**: Referenced GL account is not ACTIVE
- **ACCOUNT_COMPANY_MISMATCH**: Referenced account belongs to a different company
- **AP_CURRENCY_NOT_FOUND**: Referenced currency does not exist

## Test Cases

- derives the accrual distribution account for an added receipt-required purchase-order line
- updates DRAFT AP document header, lines, and distributions
- passes custom header and line fields through to writes
- adds distributions under an existing line without changing the line patch
- returns error when AP document does not exist
- returns error when AP document is not DRAFT
- returns error when removing an unknown line
- returns error when updating a distribution outside the edited line
- returns error when updating and removing the same line
- returns error when updating a derived distribution
- returns error when removing a derived distribution
- re-derives the accrual distribution when a patch changes the net amount
- re-derives the accrual distribution when a patch repoints the purchase order line
- drops the derived distribution when a patch clears the line source
- returns error when effective lines are empty
- returns error when effective line gross total does not match document total
- returns error when effective distribution total does not match document total
- replaces due schedule with multiple due schedule lines
- returns error when effective due schedule total does not match document total
- returns error when an added purchase-order sourced line omits the purchase order line reference
- returns error when an added purchase-order sourced line net amount does not equal quantity times unit price
- returns error when added distribution account does not exist
- returns error when added distribution account is inactive
- returns error when payable control account does not exist
- returns error when payable control account belongs to another company
- returns error when payable control account is inactive
