# VerifyTrialBalance

## Permission Scope

financialStatement

## Overview

verifyTrialBalance checks that the period's trial balance is balanced (total debits equal total credits across all accounts) and transitions the PeriodClose from ADJUSTMENTS_POSTED to TRIAL_BALANCE_VERIFIED status. This step ensures the integrity of double-entry bookkeeping before financial statements can be generated. If the trial balance has a non-zero discrepancy, the verification fails.

## Business Rules

- PeriodClose record must exist and be in ADJUSTMENTS_POSTED status
- Only ADJUSTMENTS_POSTED records can transition to TRIAL_BALANCE_VERIFIED
- Verification generates or retrieves the trial balance for the period
- Verification fails if the trial balance has a non-zero difference between total debits and total credits
- Verification succeeds when debits equal credits across all accounts for the period
- Updates completionPercentage to reflect progress
- Records the userId of the operator who performed the verification
- Emits an audit event recording the acting user, timestamp, trial balance result, and status transition

## Process Flow

```mermaid
flowchart TD
    A[Receive verify trial balance request] --> B{PeriodClose record exists?}
    B -->|No| C[Return error: period close not found]
    B -->|Yes| D{PeriodClose in ADJUSTMENTS_POSTED status?}
    D -->|No| E[Return error: invalid status transition]
    D -->|Yes| F[Generate or retrieve trial balance for the period]
    F --> G{Total debits equal total credits?}
    G -->|No| H[Return error: trial balance imbalanced with discrepancy amount]
    G -->|Yes| I[Transition PeriodClose to TRIAL_BALANCE_VERIFIED]
    I --> J[Update completionPercentage]
    J --> K[Emit audit event]
    K --> L[Return updated PeriodClose]
```

## External Dependencies

- [coa-management::getChartOfAccounts](../../../coa-management/docs/queries/GetChartOfAccounts.md) - Retrieves the active CoA for trial balance generation

## Error Scenarios

- **PERIOD_CLOSE_NOT_FOUND**: Referenced period close does not exist
- **INVALID_STATUS_TRANSITION**: Requested status transition is not allowed from the current status
- **TRIAL_BALANCE_IMBALANCED**: Total debits do not equal total credits

## Test Cases

- returns error when PeriodClose record does not exist
- returns error when PeriodClose is in SUBLEDGERS_VERIFIED status
- returns error when PeriodClose is already in TRIAL_BALANCE_VERIFIED status
- returns error when trial balance has a non-zero debit-credit discrepancy
- transitions ADJUSTMENTS_POSTED to TRIAL_BALANCE_VERIFIED when trial balance is balanced
- updates completionPercentage after successful verification
- emits audit event recording trial balance result and status transition
