# Trial Balance

## Overview

The Trial Balance is a point-in-time snapshot report that summarizes the balances of all GL accounts for a specific accounting period within a company. For each account, the report presents the opening balance, total period debits, total period credits, and the resulting closing balance. The trial balance serves as the fundamental verification mechanism in double-entry bookkeeping: total debits across all accounts must equal total credits. Any imbalance indicates a posting error that must be resolved before financial statements can be generated. The report is scoped to a single company (via `companyId` from the organization module) and a single accounting period, and it derives its account structure from the active Chart of Accounts managed by coa-management.

The trial balance supports two variants: **pre-close** and **post-close**. A pre-close trial balance is generated during or before the period-end close process, reflecting all standard and adjusting journal entries posted up to that point. A post-close trial balance is generated after all closing entries have been applied, verifying that temporary accounts (revenue, expense) have been zeroed out and their balances transferred to retained earnings. Both variants aggregate data from posted journal lines in the general ledger, grouping results by the account group hierarchy defined in coa-management. The trial balance is the foundational input for financial statement generation (income statement, balance sheet) and is a required artifact in every period-end close workflow.

## Business Purpose

Organizations rely on the trial balance as a core financial control and reporting mechanism:

- **Debit-credit equilibrium verification**: The trial balance confirms that total debits equal total credits across all accounts, validating the integrity of double-entry bookkeeping for the period. Any discrepancy signals a posting error that must be investigated before proceeding with financial close
- **Period-end close prerequisite**: Generating a balanced trial balance is a mandatory step in the period-end close workflow. Auditors and controllers use it to confirm that all journal entries for the period have been posted correctly before producing financial statements
- **Pre-close visibility**: The pre-close trial balance gives accountants a working view of account balances before adjusting and closing entries are applied, enabling them to identify missing accruals, misclassifications, or unposted transactions
- **Post-close validation**: The post-close trial balance verifies that all temporary accounts (revenue, expense, gains, losses) have been closed to retained earnings, ensuring only permanent accounts (assets, liabilities, equity) carry forward balances into the next period
- **Account group aggregation**: Balances are organized according to the account group hierarchy from coa-management, providing subtotals at each level (e.g., Current Assets, Fixed Assets, Total Assets) that align with the company's reporting structure
- **Financial statement foundation**: The trial balance provides the verified, balanced dataset from which the income statement, balance sheet, and other financial statements are generated. Without a balanced trial balance, downstream statement generation is blocked
- **Multi-period comparison**: By generating trial balances for consecutive periods, organizations can perform trend analysis and variance detection, identifying unusual fluctuations in account balances that may require investigation
- **Audit trail support**: Each generated trial balance is a timestamped snapshot, providing auditors with evidence of account balances at a specific point in time and supporting regulatory compliance requirements

## Process Flow

The following diagram shows the end-to-end workflow for generating a trial balance:

```mermaid
flowchart TD
    A[Select company and accounting period] --> B[Determine trial balance variant]
    B --> C{Pre-close or post-close?}
    C -- Pre-close --> D[Retrieve all posted journal lines for the period]
    C -- Post-close --> E[Retrieve all posted journal lines including closing entries]
    D --> F[Fetch GL accounts from active CoA via coa-management]
    E --> F
    F --> G[Calculate opening balance per account from prior period closing balances]
    G --> H[Aggregate period debits and credits per account from journal lines]
    H --> I[Compute closing balance per account: opening + debits - credits]
    I --> J{Total debits == total credits?}
    J -- Yes --> K[Group balances by account group hierarchy]
    K --> L[Generate trial balance snapshot with timestamp]
    L --> M[Trial balance available for financial statement generation]
    J -- No --> N[Report imbalance error with discrepancy amount]
    N --> O[Investigate and correct journal entries]
    O --> D
```

The following state diagram shows the lifecycle of a trial balance snapshot:

```mermaid
stateDiagram-v2
    [*] --> Generating: generateTrialBalance
    Generating --> Balanced: debit-credit totals match
    Generating --> Imbalanced: debit-credit totals do not match
    Balanced --> [*]: snapshot stored
    Imbalanced --> [*]: error reported
```

## Scenario Patterns

- **Standard Month-End Pre-Close**: An accountant generates a pre-close trial balance at the end of January to review all account balances before adjusting entries. The report reveals that total debits equal total credits, confirming posting integrity. The accountant identifies a missing accrual by reviewing individual account balances and posts an adjusting entry before regenerating the trial balance
- **Post-Close Verification After Period End**: After all closing entries have been posted for Q4, the controller generates a post-close trial balance. Revenue and expense accounts show zero balances, confirming that income summary entries correctly transferred net income to retained earnings. Only balance sheet accounts carry forward into the new fiscal year
- **Imbalance Detection and Resolution**: A trial balance generated mid-period reveals a 500 USD discrepancy between total debits and total credits. The accounting team traces the imbalance to a one-sided journal entry that was incorrectly posted. After correcting the entry, a regenerated trial balance confirms equilibrium
- **Multi-Entity Consolidated Review**: A parent company generates trial balances for each of its three subsidiaries for the same period. Each trial balance is scoped to its respective company and CoA. The finance team uses the individual trial balances as inputs for intercompany elimination and consolidated financial statement preparation
- **Year-End Audit Preparation**: External auditors request pre-close and post-close trial balances for all twelve months of the fiscal year. The accounting team generates each snapshot, providing auditors with a complete trail of account balances throughout the year, organized by the company's account group hierarchy
- **New Account Verification**: After adding a new GL account for a recently launched product line, the accountant generates a trial balance to confirm that postings to the new account are correctly reflected and that overall debit-credit equilibrium is maintained
- **Account Group Subtotal Analysis**: A CFO reviews the trial balance grouped by account hierarchy to analyze subtotals at the department level (e.g., Sales Expenses, R&D Expenses). The grouping follows the account group hierarchy defined in coa-management, enabling drill-down from summary to detail

## Test Cases

- Trial balance can only be generated for a company with an ACTIVE Chart of Accounts
- Trial balance can only be generated for a valid accounting period that exists in the system
- Trial balance must include all GL accounts from the active CoA, even those with zero balances
- Opening balance for each 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 that account in the period
- Period credits per account equal the sum of all credit amounts from posted journal lines for that account in the period
- Closing balance per account equals opening balance plus period debits minus period credits
- Total debits across all accounts must equal total credits across all accounts (fundamental equilibrium check)
- Generating a trial balance when total debits do not equal total credits produces an imbalance error with the discrepancy amount
- Pre-close trial balance excludes closing entries (entries that zero out temporary accounts)
- Post-close trial balance includes all closing entries and shows zero balances for all temporary accounts (revenue, expense)
- Post-close trial balance shows non-zero balances only for permanent accounts (assets, liabilities, equity)
- Trial balance is scoped to a single company; accounts from other companies are never included
- Trial balance respects the account group hierarchy from coa-management, providing subtotals at each group level
- Only posted journal entries are included; draft or voided journal entries are excluded from aggregation
- Trial balance snapshot includes a generation timestamp recording when the report was produced
- Trial balance snapshot records the variant type (pre-close or post-close)
- Generating a trial balance for a period with no posted journal entries produces a valid report with zero debits, zero credits, and opening balances carried forward
- Trial balance correctly handles accounts with only debit postings (no credits) and vice versa
- Trial balance generation emits an audit event recording the acting user, company, period, variant, and timestamp
- Regenerating a trial balance for the same period and variant produces an updated snapshot reflecting any new postings since the last generation
- Trial balance accounts are ordered by account code in ascending order within each account group

## Reference Links

- [SAP Trial Balance Report](https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/ee3509643e954b3da2e0ebfa846c02e1/4006d63d7e167014e10000000a42189c.html)
- [Oracle Fusion Trial Balance](https://docs.oracle.com/en/cloud/saas/financials/24d/oafcf/trial-balance.html)
- [NetSuite Trial Balance Report](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1584498.html)
- [Odoo Trial Balance and Financial Reports](https://www.odoo.com/documentation/19.0/applications/finance/accounting/reporting.html)
- [QuickBooks Trial Balance Overview](https://quickbooks.intuit.com/learn-support/en-us/help-article/report-management/trial-balance-report/L0t0FuAGH_US_en_US)
