# AccountPayableDocument

## Description

AccountPayableDocument is the AP document root for vendor and payable-side obligations. It captures invoice and credit memo documents before they become posted accounting entries, and owns its AccountPayableDocumentLine, AccountPayableDistributionLine, and AccountPayableDueScheduleLine records. AccountPayableDocument can optionally reference a posted AP document through `correctionOfId` when it is created as a correction document; an INVOICE with `correctionOfId` is an AP-increasing correction, and a CREDIT_MEMO with `correctionOfId` is an AP-reducing correction or full offset. AccountPayableDocumentLine records one commercial line that preserves supplier-facing invoice detail such as description, net amount, optional tax amount, and gross amount; a line is either purchase-order sourced (`sourceType = PURCHASE_ORDER`, carrying a typed `purchaseOrderLineId` reference together with the invoiced `quantity`, `unitPrice`, and `unitId` that drive purchase-order and goods-receipt matching) or amount-only (no source, quantity, unit price, or unit, representing charges, adjustments, or direct GL entries). Correction lines reference the corrected AP line through `correctionOfLineId` and classify the correction as PRICE, QUANTITY, or AMOUNT through `correctionType`. Purchase-order sourced correction lines keep the same purchase order line context as the corrected AP line while bypassing standard invoice matching holds. AccountPayableDistributionLine records one posting distribution under a commercial line, carrying a posting account and positive amount; it can optionally reference a corrected distribution through `correctionOfDistributionLineId` when the correction targets a specific accounting or cost allocation. AccountPayableDistributionLine is the AP-owned source used by postAccountPayableDocument to build accounting event distribution payloads. AccountPayableDueScheduleLine records one due-date installment for the AP document, carrying only dueDate and amount so AP can model multiple payable due dates independently from later payment execution or bank transfer grouping. Draft documents are editable. Registered documents are accepted as AP documents but have not yet created an accounting event. Posting emits an ACCOUNT_PAYABLE_RECOGNIZED accounting event, then moves the AP document to POSTED. Posted documents are immutable and are corrected or fully offset by creating separate AP correction documents through correctAccountPayableDocument; the corrected document remains POSTED. AccountPayableDocumentHold records one payment block against an AP document, optionally scoped to a single AccountPayableDocumentLine; it carries a reason code and a source (SYSTEM holds are produced by purchase-order and goods-receipt matching, MANUAL holds are placed by users), and an active hold (releasedAt is null) prevents posting until it is released.

## Domain Model Definitions

### Model type

Stateful

#### State Transitions

```mermaid
stateDiagram-v2
    [*] --> Draft: createAccountPayableDocument
    [*] --> Draft: correctAccountPayableDocument
    Draft --> Draft: updateAccountPayableDocument
    Draft --> Registered: registerAccountPayableDocument
    Draft --> Cancelled: cancelAccountPayableDocument
    Registered --> Posted: postAccountPayableDocument
    Registered --> Cancelled: cancelAccountPayableDocument
```

| Operation | From | To | Command |
|-----------|------|----|---------|
| register | DRAFT | REGISTERED | [registerAccountPayableDocument](../command/RegisterAccountPayableDocument.md) |
| cancelDraft | DRAFT | CANCELLED | [cancelAccountPayableDocument](../command/CancelAccountPayableDocument.md) |
| post | REGISTERED | POSTED | [postAccountPayableDocument](../command/PostAccountPayableDocument.md) |
| cancelRegistered | REGISTERED | CANCELLED | [cancelAccountPayableDocument](../command/CancelAccountPayableDocument.md) |

### Command Definitions

- [createAccountPayableDocument](../command/CreateAccountPayableDocument.md) - Create a DRAFT AP document with initial lines
- [correctAccountPayableDocument](../command/CorrectAccountPayableDocument.md) - Create a DRAFT AP correction document for a POSTED AP document
- [updateAccountPayableDocument](../command/UpdateAccountPayableDocument.md) - Update a DRAFT AP document and its lines
- [registerAccountPayableDocument](../command/RegisterAccountPayableDocument.md) - Accept a DRAFT AP document for posting
- [postAccountPayableDocument](../command/PostAccountPayableDocument.md) - Emit an account payable recognized accounting event for a REGISTERED AP document
- [cancelAccountPayableDocument](../command/CancelAccountPayableDocument.md) - Cancel an unposted AP document
- [releaseAccountPayableDocumentHold](../command/ReleaseAccountPayableDocumentHold.md) - Release an active payment hold on an AP document

### Query Definitions

- None

### Models

- AccountPayableDocument
- AccountPayableDocumentLine
- AccountPayableDistributionLine
- AccountPayableDueScheduleLine
- AccountPayableDocumentHold

### Invariants

- AP documents are created in DRAFT status
- DRAFT documents can be updated and cancelled
- REGISTERED documents are immutable except for cancellation or posting
- POSTED documents are immutable and cannot be cancelled
- POSTED documents can be corrected or fully offset by creating separate correction AP documents
- Posting emits an ACCOUNT_PAYABLE_RECOGNIZED accounting event with source document type ACCOUNT_PAYABLE_DOCUMENT and source document id equal to the AP document id
- Posting is the point where accounting event is created
- The AP payable control account is stored on the AP document header and reused by posting
- Commercial line gross amounts must sum to the header total amount before registration or posting
- Distribution amounts across all AP document lines must sum to the header total amount before registration or posting
- INVOICE creates a debit to distribution accounts and credit to the payable control account
- CREDIT_MEMO creates a debit to the payable control account and credits distribution accounts
- Correction document amounts remain positive; documentType determines AP direction and accounting direction
- A full offset of a posted AP invoice is represented by a CREDIT_MEMO correction document for the full invoice amount
- A correction document references the corrected posted AP document through `correctionOfId`
- Correction lines reference corrected AP lines through `correctionOfLineId`
- Correction line `correctionType` is PRICE, QUANTITY, or AMOUNT
- PRICE and QUANTITY corrections require the corrected AP line to be purchase-order sourced
- AMOUNT corrections can target purchase-order sourced or amount-only AP lines
- Correction distributions can reference corrected distributions through `correctionOfDistributionLineId`
- Correction links provide provenance and validation; tax, expense, and posting allocations are supplied by the correction document's own lines and distributions
- Manual AP entry uses one of the concrete AP document types; pure accounting adjustments belong to JournalEntry
- Each AccountPayableDocumentLine belongs to one AccountPayableDocument
- Each AccountPayableDocumentLine must have positive net and gross amounts
- `sourceType` is nullable; `PURCHASE_ORDER` identifies a purchase-order sourced AP line
- `purchaseOrderLineId` is required when `sourceType = PURCHASE_ORDER` and must be null otherwise
- `quantity`, `unitPrice`, and `unitId` are required when `sourceType = PURCHASE_ORDER` (with `quantity` and `unitPrice` positive), and must be null otherwise
- When `sourceType = PURCHASE_ORDER`, `netAmount` must equal `quantity * unitPrice`
- Quantity, unit price, and unit of measure are line-level commercial detail and are not duplicated for amount-only lines
- AP document lines are mutable only while the parent AP document is DRAFT
- Posting accounts are held by child AccountPayableDistributionLine records, not directly by AccountPayableDocumentLine
- Each AccountPayableDistributionLine belongs to one AccountPayableDocumentLine
- Each AccountPayableDistributionLine must have a positive amount and reference a posting account
- Distribution amounts under each AccountPayableDocumentLine must sum to that line's gross amount before registration or posting
- Distribution lines are mutable only while the parent AP document is DRAFT
- Posting includes distribution lines in the accounting event payload, plus the AP control account from the AP document header
- Each AccountPayableDueScheduleLine belongs to one AccountPayableDocument
- Each AccountPayableDueScheduleLine must have a due date and positive amount
- Due schedule line amounts must sum to the AP document total amount before registration
- Due schedule lines are document-level obligations and do not represent individual payments, payment methods, or bank transfers
- Due schedule lines are mutable only while the parent AP document is DRAFT
- Posting includes due schedule lines in the accounting event payload as dueDate and amount rows
- Each AccountPayableDocumentHold belongs to one AccountPayableDocument and is optionally scoped to one AccountPayableDocumentLine
- A hold carries a reason code and a source; SYSTEM holds are produced by purchase-order and goods-receipt matching, MANUAL holds are placed by users
- A hold is active while releasedAt is null and released once releasedAt is set
- Registration reconciles SYSTEM holds from purchase-order matching: INVOICE_UNIT_DIFFERS_FROM_PURCHASE_ORDER_UNIT when the invoiced unit differs from the purchase order line unit, INVOICE_UNIT_PRICE_DIFFERS_FROM_PURCHASE_ORDER_UNIT_PRICE when an invoiced unit price differs from the purchase order line, INVOICE_QUANTITY_EXCEEDS_ORDERED_QUANTITY when invoiced quantity exceeds the remaining ordered quantity, and INVOICE_QUANTITY_EXCEEDS_RECEIVED_QUANTITY when invoiced quantity exceeds the remaining received quantity for receipt-required lines
- Invoice tolerance is resolved from InvoiceToleranceConfig by the AP document companyId and businessPartnerId; missing rows or null fields fall back to strict matching for that tolerance field
- Each InvoiceToleranceConfig row belongs to one company and one supplier; there can be at most one row for each company and supplier pair
- Remaining ordered and received quantities are net of quantities already invoiced by other REGISTERED or POSTED INVOICE documents that reference the same purchase order line
- Reconciliation only applies to purchase-order sourced lines, so SYSTEM holds arise only for documents carrying such lines
- Reconciliation creates missing SYSTEM holds and releases SYSTEM holds that no longer apply, but never recreates a SYSTEM hold that was already released, so a released variance stays accepted
- Registration does not fail when holds are present; an AP document with any active hold cannot be posted until the hold is released

### Relationships

- **References Company**: Each AP document is scoped to a Company via companyId
- **References BusinessPartner**: Each AP document references the payable business partner via businessPartnerId
- **References Currency**: Each AP document records the transaction currency via currencyId
- **References Account**: Each AP document references the payable control account via payableControlAccountId
- **AccountPayableDocument References AccountPayableDocument (correction)**: A correction document references the corrected posted AP document through correctionOfId
- **Has Many AccountPayableDocumentLine**: AP document lines belong to the document via accountPayableDocumentId
- **AccountPayableDocumentLine References AccountPayableDocumentLine (correction)**: A correction line references the corrected AP document line through correctionOfLineId
- **AccountPayableDocumentLine References PurchaseOrderLine**: Purchase-order sourced AP lines reference the originating purchase order line through `purchaseOrderLineId`
- **AccountPayableDocumentLine References Unit**: Purchase-order sourced AP lines reference the invoiced unit of measure through `unitId`
- **AccountPayableDocumentLine Has Many AccountPayableDistributionLine**: Distribution lines belong to the commercial line they allocate
- **AccountPayableDistributionLine References Account**: Each distribution references a GL account from coa-management
- **AccountPayableDistributionLine References AccountPayableDistributionLine (correction)**: A correction distribution can reference the corrected distribution through correctionOfDistributionLineId
- **Has Many AccountPayableDueScheduleLine**: Due schedule lines belong to the document via accountPayableDocumentId
- **Has Many AccountPayableDocumentHold**: Payment holds belong to the document via accountPayableDocumentId
- **AccountPayableDocumentHold References AccountPayableDocumentLine**: A line-scoped hold references the held line via accountPayableDocumentLineId
- **InvoiceToleranceConfig References Company and BusinessPartner**: Invoice tolerance overrides are scoped by company and supplier
