# Outgoing Payment Management

<!-- This section should contain the following subsections in order: -->
<!-- 1. ## Overview (required) -->
<!-- 2. ## Business Purpose (required) -->
<!-- 3. ## Process Flow (required) -->
<!-- 4. ## Scenario Patterns (required) -->
<!-- 5. ## Test Cases (required) -->
<!-- 6. ## Reference Links (required) -->

## Overview

Outgoing Payment Management records the operational AP payment document that
settles one or more posted invoice or credit memo due schedules for a single company,
supplier, and currency. A `OutgoingPayment` begins in `DRAFT`, where its header
and `AccountPayableSettlement` rows remain editable. Posting validates the
payment and every settlement as one atomic operation, freezes them, creates and
posts a balanced journal entry directly in `financial-accounting`, and changes
the payment to `POSTED`.

Each payment stores `paymentAccountId`, an active company-scoped Account that
represents the immutable accounting counterpart for the outgoing payment. It
may be a bank, cash, or outgoing-payment-clearing account selected by the host
application; it is not a bank-account master or bank-execution record.

The feature deliberately separates AP settlement from bank execution. A
payment can be cancelled only before posting. Once posted, its accounting identity
and original settlements remain immutable; correction changes the same payment
header to `REVERSED` and appends settlements linked through
`reversalOfSettlementId`. Payment approval, payment files,
bank connectivity, execution attempts, bank-statement matching, and general
ledger clearing are outside this feature.

`postOutgoingPayment` and `reverseOutgoingPayment` post balanced journal entries
directly in `financial-accounting`. Each journal uses source type
`OUTGOING_PAYMENT` and the posted payment ID. Normal posting debits payable
control accounts for invoice settlements, credits payable control accounts for
credit memo settlements, and credits the payment account by the signed net;
reversal posting records the exact opposite entry. Journal posting and the AP
payment changes are atomic.

Approval and segregation of duties remain application-composer concerns. A
host application may require an approved `ApprovalRequest` before calling
`postOutgoingPayment`; the base module does not add approval states to
`OutgoingPayment.status`.

## Business Purpose

- Record which posted invoice and credit memo due schedules an outgoing payment settles, including partial applications and net payment across multiple AP documents
- Preserve a clear operational payment audit trail independently of invoice lifecycle and bank execution state
- Prevent a due schedule from being settled beyond its remaining payable amount
- Freeze posted payment intent while allowing pre-posting mistakes to be cancelled without accounting effect
- Correct posted payment mistakes by marking the original payment REVERSED while preserving its posting facts and appending reversal history
- Post source-referenced journal entries directly to `financial-accounting`
- Preserve the selected payment-side accounting counterpart without bringing bank-account or payment-execution ownership into AP

## Process Flow

```mermaid
flowchart TD
    A[Create Outgoing Payment in DRAFT] --> B[Add or update settlements against posted AP due schedules]
    B --> C{Next action}
    C -->|Continue editing| B
    C -->|Cancel| D[Set payment to CANCELLED with no accounting effect]
    C -->|Post| E[Validate company, supplier, currency, totals, and remaining due amounts]
    E -->|Invalid| B
    E -->|Valid| F[Validate payment account and build immutable settlement snapshot]
    F --> N[Atomically post the journal and freeze payment and settlements]
    N --> G[Set payment to POSTED]
    G --> H{Correction required?}
    H -->|No| I[Keep payment POSTED]
    H -->|Yes| J[Create reversal settlements for the original due schedules]
    J --> K[Post the opposite journal]
    K --> L[Set the same payment to REVERSED]
```

## Scenario Patterns

- **Single-invoice payment**: A payment settles the remaining amount of one posted invoice due schedule in full
- **Partial payment**: A payment settles only part of a posted invoice due schedule, leaving the unapplied amount available for a later payment
- **Combined outgoing payment**: One payment has multiple settlement rows against posted invoice due schedules belonging to the same company, supplier, and currency
- **Invoice net of credit memo**: Settlement magnitudes of 100 for an invoice and 20 for a credit memo use document types to produce an outgoing payment of 80
- **Draft correction**: A user changes the payment date, payment account, amount, or settlement allocation while the payment is still `DRAFT`
- **Draft cancellation**: A payment prepared in error is changed from `DRAFT` to `CANCELLED` without emitting accounting intent or changing due-schedule settlement balances
- **Posted reversal**: A posted payment is corrected by appending linked reversing settlements and an opposite journal, then changing the same header to `REVERSED`; the original payment identity and settlement rows remain preserved
- **Concurrent settlement attempt**: Two draft payments target the same remaining due amount; only the posting operation that can atomically reserve the available amount succeeds
- **Bank processing after AP posting**: A posted outgoing payment may later be transmitted or matched to a bank transaction by another capability without changing the AP payment lifecycle
- **Payment accounting counterpart**: A payment stores one active company-scoped `paymentAccountId`; posting applies each AP settlement according to its document type and credits this payment account by the net total

## Test Cases

- Creating an outgoing payment with a valid active company, active supplier SupplierAccount, currency, and payment account should create it in `DRAFT`
- Creating an outgoing payment must require `companyId`, `supplierAccountId`, `currencyId`, `paymentAccountId`, payment date, and positive total amount
- Creating and posting an outgoing payment must require the SupplierAccount to be company-compatible and available for transactions
- Creating, updating, and posting an outgoing payment must require `paymentAccountId` to identify an active Account belonging to the payment company
- Posting an outgoing payment must require at least one settlement
- Adding a settlement must reference an existing due schedule of a posted invoice or credit memo document
- Adding a settlement may reference a due schedule owned by a posted AP-increasing INVOICE correction document
- Adding a settlement must reject unsupported AP document types
- Adding a settlement must reject a non-positive settlement amount
- All settlements on one payment must belong to the payment's company, supplier, and currency
- Posting a payment must require the due-schedule-directed signed settlement total to equal the payment total amount
- Posting a payment must reject any settlement that exceeds the due schedule's remaining amount after effective posted payments and posted reversals are considered
- Posting concurrent payments against the same remaining due amount must prevent the combined effective settlement from exceeding that amount
- Posting a valid draft payment must freeze its header and settlements, post one journal entry, and change the payment to `POSTED` atomically
- A normal payment journal must debit AP for invoice settlements, credit AP for credit memo settlements, and credit `paymentAccountId` by the net amount; a reversal journal must produce the opposite accounting direction
- Reprocessing the same posted Outgoing Payment must not create a duplicate journal or duplicate accounting effect
- Failing journal creation or posting must leave the payment in `DRAFT` and must not make its settlements effective
- Updating a `POSTED` or `CANCELLED` payment or its settlements must be rejected
- Cancelling a `DRAFT` payment must change it to `CANCELLED` without emitting accounting intent or affecting remaining due amounts
- Cancelling a `POSTED` payment must be rejected
- Reversing a `POSTED` payment must change the same payment header to `REVERSED`, record `reversalDate` and `reversedAt`, and retain the original `postedAt`
- Reversal must restore exactly the payment's settlement effect without changing original settlement rows
- Reversing a `DRAFT`, `CANCELLED`, or `REVERSED` payment must be rejected
- Reversing the same original payment more than once must be rejected
- Creating, updating, posting, cancelling, or reversing an outgoing payment without the corresponding account-payable permission must be rejected
- A payment execution failure, bank rejection, or bank-statement match must not change `OutgoingPayment.status` within this feature
- Version 1 must not support cash discounts, withholding, fees, write-offs, unapplied payments, supplier prepayments, cross-currency settlement, or post-posting payment blocks
- Version 1 must require cash paid to equal the signed net of settled obligation amounts; later payment differences must use a separate adjustment model rather than changing settlement meaning

## Reference Links

- See module README
