# Incoming 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

Incoming Payment Management records the operational AR payment document that
settles one or more posted invoice or credit memo due schedules for a single company,
customer, and currency. A `IncomingPayment` begins in `DRAFT`, where its header
and `AccountReceivableSettlement` 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 incoming payment. It
may be a bank, cash, or incoming-payment-clearing account selected by the host
application; it is not a bank-account master or bank-execution record.

The feature deliberately separates AR 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.

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

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

## Business Purpose

- Record which posted invoice and credit memo due schedules an incoming payment settles, including partial applications and net payment across multiple AR 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 receivable 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 AR

## Process Flow

```mermaid
flowchart TD
    A[Create Incoming Payment in DRAFT] --> B[Add or update settlements against posted AR 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, customer, 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 incoming payment**: One payment has multiple settlement rows against posted invoice due schedules belonging to the same company, customer, 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 incoming 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 AR posting**: A posted incoming payment may later be transmitted or matched to a bank transaction by another capability without changing the AR payment lifecycle
- **Payment accounting counterpart**: A payment stores one active company-scoped `paymentAccountId`; posting applies each AR settlement according to its document type and debits this payment account by the net total

## Test Cases

- Creating an incoming payment with a valid active company, active customer CustomerAccount, currency, and payment account should create it in `DRAFT`
- Creating an incoming payment must require `companyId`, `customerAccountId`, `currencyId`, `paymentAccountId`, payment date, and positive total amount
- Creating and posting an incoming payment must require the CustomerAccount to be company-compatible and available for transactions
- Creating, updating, and posting an incoming payment must require `paymentAccountId` to identify an active Account belonging to the payment company
- Posting an incoming 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 AR-increasing INVOICE correction document
- Adding a settlement must reject unsupported AR document types
- Adding a settlement must reject a non-positive settlement amount
- All settlements on one payment must belong to the payment's company, customer, 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 credit AR for invoice settlements, debit AR for credit memo settlements, and debit `paymentAccountId` by the net amount; a reversal journal must produce the opposite accounting direction
- Reprocessing the same posted Incoming 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 incoming payment without the corresponding account-receivable permission must be rejected
- A payment execution failure or bank-statement match must not by itself change `IncomingPayment.status`; an authorized receipt reversal changes it to `REVERSED`
- Version 1 must not support cash discounts, withholding, fees, write-offs, unapplied payments, customer 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
