# ReconcileBankTransactions

## Permission Scope

reconciliation

## Overview

reconcileBankTransactions confirms one immutable set-to-set match between bank statement lines and posted incoming or outgoing payments.

## Business Rules

- At least one statement item and one payment item are required
- Incoming and outgoing payments cannot be mixed
- Source references must exist and be eligible
- All sources belong to the bank account company and currency
- Statement direction agrees with payment type
- Every statement item uses the statement line's full amount
- Each statement line must be UNRECONCILED with no current reconciliation
- Payment effective cleared amount may not exceed its original amount
- Statement-line `currentBankReconciliationId` and `reconciliationStatus` are updated as current-state projections
- Statement-side and payment-side totals are equal
- Direct payments create no journal
- Clearing-account payments create and post a bank-to-clearing journal atomically

## Process Flow

```mermaid
flowchart LR
    A[Receive source items] --> B[Lock BankAccount]
    B --> C[Resolve and validate sources]
    C --> D[Validate remaining amounts and equal totals]
    D --> E[Create reconciliation and items]
    E --> F{Indirect amount exists?}
    F -->|No| G[Return confirmed group]
    F -->|Yes| H[Post bank-to-clearing journal]
    H --> G
```

## External Dependencies

- account-receivable::GetIncomingPayment
- account-payable::GetOutgoingPayment
- financial-accounting::GetPeriodByDate
- financial-accounting::CreateJournalEntry
- financial-accounting::PostJournalEntry

## Error Scenarios

- **CASH_BANK_ACCOUNT_NOT_FOUND**: Bank account does not exist
- **CASH_BANK_ACCOUNT_INACTIVE**: Bank account is inactive
- **CASH_BANK_RECONCILIATION_INVALID**: Group shape or totals are invalid
- **CASH_BANK_RECONCILIATION_SOURCE_NOT_FOUND**: A source does not exist
- **CASH_BANK_RECONCILIATION_SOURCE_INELIGIBLE**: Source status, scope, direction, or account is invalid
- **CASH_BANK_RECONCILIATION_OVER_CLEARED**: Cleared amount exceeds remaining amount
- **CASH_BANK_RECONCILIATION_ACCOUNTING_PERIOD_NOT_FOUND**: Indirect journal period does not exist
- **CASH_BANK_RECONCILIATION_JOURNAL_FAILED**: Journal creation or posting failed

## Test Cases

- records one statement line against multiple incoming payments as one group
- rejects mixing incoming and outgoing payments in one reconciliation
- rejects partial reconciliation of a statement line
- rejects a statement line that already belongs to an effective reconciliation
- posts bank-to-clearing accounting for an indirect incoming payment
