# CreateAccountPayableDocument

## Permission Scope

accountPayableDocument

## Overview

createAccountPayableDocument creates a DRAFT AP document with its payable control account, initial commercial lines, line-owned posting distributions, and optional payable due schedule lines. It validates partner, currency, payable control account, total amount, line gross totals, distribution totals, and any provided due schedule, but it does not create journal entries. Accounting event creation starts only when postAccountPayableDocument runs.

## Business Rules

- Creates the document in DRAFT status
- Requires an existing company, supplier account, currency, and ACTIVE payable control account
- Requires at least one line
- Requires at least one distribution under each line, counting the derived distributions of a receipt-required purchase-order line
- Header total amount must be positive
- Every line net and gross amount must be positive
- Every caller-supplied distribution amount must be positive; the derived invoice price variance row is signed
- Sum of line gross amounts must equal totalAmount
- Sum of each line's distribution amounts must equal that line's gross amount
- Sum of all distribution amounts must equal totalAmount
- If due schedule lines are provided, each due amount must be positive and the due schedule total must equal totalAmount
- Due schedule input accepts a positive `amount`
- Every distribution must reference an existing ACTIVE posting account, including the derived one
- For a purchase-order sourced line whose purchase order line requires a physical receipt, the goods-value distributions are derived from the valuation policy governing the ordered item: an ACCRUAL row relieving the accrual account at quantity times the purchase order line's current unit price — the price the goods receipt credited — and, when the invoiced price differs, an invoice price variance row carrying the signed remainder of the net amount. A zero row is not written, so the rows always sum to the line net amount. Derived rows are persisted with their distributionType (caller-supplied distributions are MANUAL), marking them as system-owned so later edits can find and recompute them, and the split is provisional until registration fixes it against the matched price
- Caller-supplied distributions on such a line cover only the difference between the line gross and net amounts, which is tax
- A purchase-order line that cannot be resolved yields no derivation, leaving the line fully caller-distributed; registration's matching surfaces the dangling reference
- The payable control account is stored on the AP document header
- Lines are inserted with the new document
- Distributions are inserted under the new document lines
- Due schedule lines are inserted under the new document
- A 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
- A purchase-order sourced line net amount must equal quantity times unit price

## Process Flow

```mermaid
flowchart TD
    A[Receive create AP document request] --> B{Company exists?}
    B -->|No| C[Return error: company not found]
    B -->|Yes| D{Business partner exists?}
    D -->|No| E[Return error: supplier account not found]
    D -->|Yes| F{Currency exists?}
    F -->|No| G[Return error: currency not found]
    F -->|Yes| H{Amounts and lines valid?}
    H -->|No| I[Return validation error]
    H -->|Yes| N{Payable control account exists?}
    N -->|No| O[Return error: account not found]
    N -->|Yes| Q[Derive the accrual and invoice price variance distributions for receipt-required purchase-order lines]
    Q -->|Unresolved policy| R[Return error: AP_ACCRUAL_ACCOUNT_UNRESOLVED]
    Q -->|Resolved| J[Create AP document in DRAFT]
    J --> K[Create AP document lines]
    K --> L[Create AP distribution lines]
    L --> P[Create AP due schedule lines when provided]
    P --> M[Return created AP document]
```

## External Dependencies

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

## Error Scenarios

- **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

- **COMPANY_NOT_FOUND**: Referenced company does not exist
- **AP_SUPPLIER_ACCOUNT_NOT_FOUND**: Referenced supplier account does not exist
- **AP_CURRENCY_NOT_FOUND**: Referenced currency 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_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
- **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

## Test Cases

- creates DRAFT AP document with lines and distributions
- passes custom header and line fields through to inserts
- returns error when company does not exist
- returns error when supplier account does not exist
- returns error when currency does not exist
- returns error when no lines are provided
- returns error when total amount is not positive
- returns error when line gross total does not match document total
- returns error when distribution total does not match document total
- creates DRAFT AP document with multiple due schedule lines
- returns error when due schedule total does not match document total
- returns error when a purchase-order sourced line omits the purchase order line reference
- returns error when a purchase-order sourced line is missing a unit
- returns error when a purchase-order sourced line net amount does not equal quantity times unit price
- returns error when distribution account does not exist
- returns error when distribution account is inactive
- returns error when payable control account does not exist
- returns error when payable control account is inactive
- derives the accrual distribution account from the item valuation policy for a receipt-required purchase-order line
- derives a signed invoice price variance distribution when the invoiced unit price differs from the purchase order unit price
- derives no distribution for a purchase-order line that does not require a physical receipt
- returns error when no valuation policy resolves the accrual account for a receipt-required purchase-order line
