# CorrectAccountPayableDocument

## Permission Scope

accountPayableDocument

## Overview

correctAccountPayableDocument atomically creates and posts an AP correction document for a POSTED AP document. It does not mutate the corrected AP document or its lines. The correction document records a header-level `correctionOfId`, each correction line records `correctionOfLineId` and `correctionType`, and each correction distribution can record `correctionOfDistributionLineId` when the correction targets a specific accounting or cost allocation. The command posts the correction journal entry, declares any PRICE or QUANTITY correction's price variance to inventory, and synchronizes purchase-order billing status in the same transaction.

## Business Rules

- Correction lines are new lines, so the goods-value distributions of a receipt-required purchase-order correction line are derived the same way creation derives them, routed by the correction type: a PRICE correction's whole net amount is a derived invoice price variance row (it reprices already-billed units and relieves no accrual), an AMOUNT correction derives a single ACCRUAL row at the net amount (it declares nothing to inventory, so nothing may land in invoice price variance), and a QUANTITY correction splits like a regular line — ACCRUAL at quantity times the order price plus the signed invoice price variance remainder
- Only POSTED AP documents can be corrected
- A correction document is created directly in POSTED status
- A non-empty due schedule is required because the correction bypasses the normal DRAFT-to-REGISTERED validation flow
- Due schedule amounts must be positive and sum to the correction total
- The corrected document is locked while the correction is validated and created
- The correction document inherits company, supplier, and currency from the corrected AP document
- The correction currency must equal the company's base currency
- The posting date must belong to an accounting period
- The correction document stores `correctionOfId` on its AccountPayableDocument header
- Each correction line must reference a line on the corrected AP document through `correctionOfLineId`
- Each correction line must declare `correctionType` as PRICE, QUANTITY, or AMOUNT
- PRICE and QUANTITY corrections can only target purchase-order sourced AP lines
- AMOUNT corrections can target purchase-order sourced or amount-only AP lines
- Purchase-order sourced correction lines keep the same purchase order line context as the corrected AP line; supplied source fields must match the corrected line
- A correction distribution may reference a distribution on the corrected line through `correctionOfDistributionLineId`
- Distribution correction references must belong to the corrected line referenced by the correction line
- Amounts remain positive; documentType determines whether the correction increases or decreases AP exposure
- Due schedule input accepts positive amounts; the command generates positive signed amounts for INVOICE corrections and negative signed amounts for CREDIT_MEMO corrections
- CREDIT_MEMO correction documents reduce AP exposure
- INVOICE correction documents increase AP exposure when `correctionOfId` marks them as correction documents rather than normal invoices
- A full offset of a posted AP invoice is represented as a CREDIT_MEMO correction document for the full invoice amount; it does not change the corrected document's lifecycle status
- Tax, expense, and other posting distributions are supplied by the correction document itself; correction links provide provenance and validation, not posting accounts. The derived distributions are the exception, and carry no correction link
- A balanced source-referenced journal entry is created and posted for the correction
- PRICE and QUANTITY corrections declare their price variance to inventory, which adjusts the acquisition cost of the received stock; AMOUNT corrections never do
- Each purchase-order sourced correction line snapshots the current order unit price as its `matchedPurchaseOrderUnitPrice`, fixing the base price its variance is measured from
- Purchase-order billing status is synchronized after posting the correction

## Process Flow

```mermaid
flowchart TD
    A[Receive correct AP document request] --> B{Corrected document exists?}
    B -->|No| C[Return error: AP document not found]
    B -->|Yes| D{Corrected document is POSTED?}
    D -->|No| E[Return error: invalid AP document status]
    D -->|Yes| F{Corrected lines belong to document?}
    F -->|No| G[Return error: AP document line not found]
    F -->|Yes| H{Correction types valid for source lines?}
    H -->|No| I[Return error: line source inconsistent]
    H -->|Yes| J{Distribution correction refs valid?}
    J -->|No| K[Return error: AP distribution line not found]
    J -->|Yes| L[Resolve accounting period]
    L --> M[Create POSTED AP correction document]
    M --> N[Create and post journal entry]
    N --> Q{PRICE or QUANTITY correction on a PO line?}
    Q -->|Yes| R[Declare the price variance to inventory]
    Q -->|No| O[Synchronize purchase-order billing]
    R --> O
    O --> P[Return correction document and journal entry]
```

## External Dependencies

- [listAccounts](../../../coa-management/docs/query/ListAccounts.md) - Validates payable control and distribution accounts
- [getPeriodByDate](../../../financial-accounting/docs/query/GetPeriodByDate.md) - Resolves the accounting period for the posting date
- [createJournalEntry](../../../financial-accounting/docs/command/CreateJournalEntry.md) - Creates the correction journal entry
- [postJournalEntry](../../../financial-accounting/docs/command/PostJournalEntry.md) - Posts the correction journal entry
- [listPurchaseOrderLinesForMatching](../../../purchase/docs/query/ListPurchaseOrderLinesForMatching.md) - Supplies the order unit price snapshotted onto the correction lines and used to resolve the order reference, plus the ordered item and whether the line requires a physical receipt
- [resolveItemValuationPolicies](../../../inventory/docs/query/ResolveItemValuationPolicies.md) - Resolves the valuation policy governing the ordered item
- [postAcquisitionCostAdjustment](../../../inventory/docs/command/PostAcquisitionCostAdjustment.md) - Adjusts the acquisition cost of received stock for the correction's price variance
- [recalculatePurchaseOrderBillingStatus](../../../purchase/docs/command/RecalculatePurchaseOrderBillingStatus.md) - Synchronizes purchase-order billing status

## 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_DISTRIBUTION_LINE_NOT_FOUND**: Referenced AP distribution line does not exist
- **AP_LINE_SOURCE_INCONSISTENT**: AP line source fields, correction target, or values are inconsistent
- **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_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_POSTING_CURRENCY_MISMATCH**: AP document currency does not match the company base currency
- **AP_ACCOUNTING_PERIOD_NOT_FOUND**: No accounting period covers the AP document posting date
- **AP_JOURNAL_ENTRY_CREATE_FAILED**: Journal entry creation failed for the AP document
- **AP_JOURNAL_ENTRY_POST_FAILED**: Journal entry posting failed for the AP document
- **AP_ACQUISITION_COST_ADJUSTMENT_FAILED**: Inventory acquisition cost adjustment failed for a purchase-order sourced line
- **AP_PURCHASE_ORDER_BILLING_SYNC_FAILED**: Purchase-order billing status sync failed for the AP document

## Test Cases

- derives the invoice price variance distribution for a receipt-required PRICE correction line
- returns error when no valuation policy resolves the accrual account for a receipt-required correction line
- creates and posts a correction document with line and distribution correction links
- locks the corrected document before creating the correction
- returns error when the correction due schedule is omitted
- posts the correction journal entry and synchronizes purchase billing
- declares the correction's price variance to inventory
- skips the inventory adjustment for an AMOUNT correction
- returns an error when the correction's inventory adjustment fails
- returns an error when the correction currency is not the company base currency
- returns an error when no accounting period contains the posting date
- returns an error when correction journal entry creation fails
- returns an error when correction journal entry posting fails
- returns an error when purchase-order billing synchronization fails
- creates an INVOICE correction for an AP-increasing correction
- returns error when the corrected document is not POSTED
- returns error when a correction line references a line outside the corrected document
- returns error when a correction distribution references another line
- returns error when a price correction targets a non-PO source line
- returns error when a correction line changes the original purchase order source
- returns missing account errors through the shared AP document validation
- returns inactive account errors through the shared AP document validation
