# GenerateTrialBalance

## Overview

generateTrialBalance creates a point-in-time snapshot report summarizing the balances of all GL accounts for a specific accounting period within a company. The report includes opening balance, period debits, period credits, and closing balance for each account, organized by the account group hierarchy from coa-management. The trial balance supports two variants: PRE_CLOSE (before closing entries) and POST_CLOSE (after closing entries have zeroed temporary accounts). It serves as the fundamental verification mechanism for double-entry bookkeeping and is a prerequisite for financial statement generation.

## Business Rules

- Requires a valid `companyId` referencing a company with an ACTIVE Chart of Accounts
- Requires a valid `accountingPeriodId` referencing an existing accounting period
- Requires a variant: PRE_CLOSE or POST_CLOSE
- Must include all GL accounts from the active CoA, including those with zero balances
- Opening balance per account equals the closing balance from the immediately preceding period
- Opening balance for the first period of a new CoA defaults to zero for all accounts
- Period debits per account equal the sum of all debit amounts from posted journal lines for the period
- Period credits per account equal the sum of all credit amounts from posted journal lines for the period
- Closing balance per account equals opening balance plus period debits minus period credits
- Total debits across all accounts must equal total credits (fundamental equilibrium check)
- If totals do not balance, an imbalance error is produced with the discrepancy amount
- Pre-close variant excludes closing entries; post-close variant includes closing entries
- Post-close variant shows zero balances for all temporary accounts (revenue, expense)
- Only posted journal entries are included; draft or voided entries are excluded
- Accounts are ordered by account code in ascending order within each group
- Balances are organized by account group hierarchy with subtotals at each level
- Snapshot includes a generation timestamp
- Regenerating for the same period and variant produces an updated snapshot
- Generating for a period with no posted entries produces a valid report with zero debits/credits and carried-forward opening balances
- Emits an audit event recording the acting user, company, period, variant, and timestamp

## Process Flow

```mermaid
flowchart TD
    A[Receive generate trial balance request] --> B{Company has ACTIVE CoA?}
    B -->|No| C[Return error: no active CoA]
    B -->|Yes| D{Accounting period exists?}
    D -->|No| E[Return error: period not found]
    D -->|Yes| F[Retrieve all GL accounts from active CoA]
    F --> G[Calculate opening balances from prior period]
    G --> H[Aggregate period debits and credits from posted journal lines]
    H --> I[Compute closing balance per account]
    I --> J{Total debits equal total credits?}
    J -->|No| K[Return imbalance error with discrepancy amount]
    J -->|Yes| L[Group balances by account group hierarchy]
    L --> M[Generate snapshot with timestamp]
    M --> N[Emit audit event]
    N --> O[Return trial balance snapshot]
```

## External Dependencies

- [coa-management::getChartOfAccounts](../../../coa-management/docs/queries/GetChartOfAccounts.md) - Retrieves the active CoA and account group hierarchy
- [coa-management::getAccount](../../../coa-management/docs/queries/GetAccount.md) - Retrieves GL accounts for balance aggregation
- [organization::getCompany](../../../organization/docs/queries/GetCompany.md) - Validates the referenced company

## Error Scenarios

- **NO_ACTIVE_CHART_OF_ACCOUNTS**: Company does not have an ACTIVE Chart of Accounts
- **ACCOUNTING_PERIOD_NOT_FOUND**: Referenced accounting period does not exist
- **TRIAL_BALANCE_IMBALANCED**: Total debits do not equal total credits; includes discrepancy amount
- **INVALID_VARIANT**: Variant is not PRE_CLOSE or POST_CLOSE

## Test Cases

- returns error when company has no active CoA
- returns error when accounting period not found
- returns error when variant is invalid
- generates trial balance with correct balances for PRE_CLOSE
- includes zero-balance accounts from active CoA
- returns error when trial balance is imbalanced
- emits audit event with correct actor and trial balance details
- uses accountGroupId from Account record when available
- zeros closing balances for revenue and expense accounts in POST_CLOSE variant
- deletes existing TrialBalance before inserting when regenerating for same period and variant
- sorts trial balance lines by account code ascending
