# Financial Statement Generation

## Overview

Financial statement generation produces the three core financial reports — Balance Sheet (statement of financial position), Profit & Loss (income statement), and Cash Flow Statement — from the finance-ledger module's trial balance data. Each statement is scoped to a single company, denominated in the company's base currency, and structured according to the account group hierarchy defined in the coa-management module. The Balance Sheet reports asset, liability, and equity positions as of a specific date. The Profit & Loss statement aggregates revenue and expense activity over a date range (typically a fiscal period or year-to-date). The Cash Flow Statement derives cash movements over a period using either the direct or indirect method, reconciling operating, investing, and financing activities to the net change in cash.

A `FinancialStatement` entity represents a generated report. It stores the statement type, the generation parameters (reporting date or date range, method for cash flow), a lifecycle status, and the generated output comprising line items organized by account group sections. Statement generation consumes trial balance data — specifically the period-end balances and movements for each GL account — and maps each account to the appropriate report section based on the account's type (ASSET, LIABILITY, EQUITY, REVENUE, EXPENSE) and its position within the coa-management account group hierarchy. This feature covers standard fixed-format statement generation; configurable report builders and custom financial statement versions (FSV) are out of scope and belong to a future reporting module.

## Business Purpose

Organizations need accurate, standards-compliant financial statements for external reporting, internal decision-making, and regulatory compliance:

- **Regulatory compliance**: IAS 1 (IFRS) and local GAAP frameworks require entities to produce a complete set of financial statements including a statement of financial position, income statement, and cash flow statement. This feature satisfies the core statement production requirement
- **Period-end reporting**: After trial balance generation and period-end close, financial statements are the primary deliverable that summarizes the company's financial position and performance for stakeholders including management, auditors, tax authorities, and investors
- **Account type-driven placement**: Each GL account's type (ASSET, LIABILITY, EQUITY, REVENUE, EXPENSE) determines which statement and section it appears in. This automatic classification eliminates manual mapping errors and ensures consistency between the ledger and the reports
- **Hierarchy-based structure**: The account group hierarchy from coa-management defines the presentation structure of each statement. Groups such as "Current Assets", "Non-Current Liabilities", or "Operating Expenses" provide the section headings and subtotals that give statements their standard shape
- **Comparative periods**: IAS 1 requires comparative information for the preceding period. Statement generation supports including prior-period balances alongside the current period, enabling period-over-period analysis on a single report
- **Cash flow method selection**: The Cash Flow Statement can be generated using the direct method (classifying actual cash receipts and payments) or the indirect method (adjusting net income for non-cash items and working capital changes). Both are permitted under IFRS and US GAAP; the indirect method is more commonly used in practice
- **Company scoping and currency**: Each statement is scoped to a single legal entity and denominated in the company's base currency (inherited via the CoA from the organization module), ensuring that statement figures are consistent with the underlying ledger
- **Audit trail**: Every statement generation event is recorded, preserving a traceable link between the report output, the trial balance data it consumed, and the parameters used to produce it

## Process Flow

The following diagram shows the end-to-end flow for generating a financial statement from trial balance data.

```mermaid
flowchart TD
    A[Request statement generation] --> B{Statement type?}
    B -- Balance Sheet --> C[Retrieve trial balance as-of date]
    B -- Profit & Loss --> D[Retrieve trial balance for date range]
    B -- Cash Flow --> E[Retrieve trial balance for date range]
    C --> F[Load account group hierarchy from coa-management]
    D --> F
    E --> F
    F --> G[Map accounts to statement sections by account type]
    G --> H[Aggregate balances per account group]
    H --> I{Include comparative period?}
    I -- Yes --> J[Retrieve prior period trial balance]
    J --> K[Align prior period to same sections]
    K --> L[Assemble statement line items]
    I -- No --> L
    L --> M{Validation passed?}
    M -- Yes --> N[Create FinancialStatement entity in DRAFT]
    M -- No --> O[Return validation errors]
    N --> P[Review and finalize]
    P --> Q[Finalize statement]
    Q --> R[Statement FINALIZED — immutable]
```

The following diagram shows the Cash Flow Statement generation sub-process, which differs depending on the selected method.

```mermaid
flowchart TD
    A[Cash Flow generation requested] --> B{Method?}
    B -- Direct --> C[Classify cash receipts and payments from ledger entries]
    C --> D[Group into Operating / Investing / Financing]
    B -- Indirect --> E[Start with net income from P&L]
    E --> F[Adjust for non-cash items: depreciation, amortization]
    F --> G[Adjust for working capital changes]
    G --> D
    D --> H[Calculate net change in cash]
    H --> I[Reconcile to opening and closing cash balances]
    I --> J[Return cash flow line items]
```

## Scenario Patterns

- **Monthly Balance Sheet**: At month-end close, a controller generates a Balance Sheet as of the last day of the month. The system retrieves the trial balance closing balances for all ASSET, LIABILITY, and EQUITY accounts, structures them according to the account group hierarchy (Current Assets, Non-Current Assets, Current Liabilities, Long-Term Liabilities, Equity), and produces a report where total assets equal total liabilities plus equity
- **Year-End Income Statement**: At fiscal year-end, a Profit & Loss statement is generated for the full year date range. REVENUE accounts appear as income sections and EXPENSE accounts as cost/expense sections, with subtotals for gross profit, operating profit, and net income derived from the group hierarchy
- **Quarterly Comparative P&L**: A finance manager generates a Q3 income statement with comparative data from Q3 of the prior year. Both periods' figures appear side-by-side, enabling variance analysis of revenue growth and cost changes
- **Cash Flow Statement (Indirect Method)**: An auditor requests a cash flow statement for the fiscal year. The system starts with net income from the P&L, adjusts for non-cash charges (depreciation, amortization, provisions), accounts for changes in working capital (receivables, payables, inventory), and classifies investing and financing activities to arrive at the net cash movement reconciled to the opening and closing cash balances
- **Cash Flow Statement (Direct Method)**: A company required by its regulator to use the direct method generates a cash flow statement that classifies actual cash inflows (customer receipts, interest received) and outflows (supplier payments, wages, taxes) into operating, investing, and financing categories
- **Multi-Entity Consolidation Preparation**: Each subsidiary generates its own set of financial statements in its base currency. These entity-level statements serve as inputs for a future consolidation process (out of scope for this feature)
- **Draft Review and Correction**: A statement is generated in DRAFT status. During review, the controller identifies a missing accrual entry, posts a correcting journal entry, regenerates the trial balance, and regenerates the statement before finalizing

## Test Cases

- FinancialStatement entity requires a valid companyId referencing an ACTIVE company
- FinancialStatement entity requires a valid chartOfAccountsId referencing an ACTIVE CoA
- Statement type must be one of: BALANCE_SHEET, PROFIT_AND_LOSS, CASH_FLOW
- Balance Sheet generation requires a single reporting date (as-of date)
- Profit & Loss generation requires a date range (start date and end date)
- Cash Flow Statement generation requires a date range and a method (DIRECT or INDIRECT)
- The reporting date or date range must fall within a closed or active accounting period
- A Balance Sheet includes only accounts of type ASSET, LIABILITY, and EQUITY
- A Profit & Loss includes only accounts of type REVENUE and EXPENSE
- A Cash Flow Statement derives from ledger data covering all account types relevant to cash movements
- On a correctly generated Balance Sheet, total assets equal total liabilities plus total equity (the accounting equation holds)
- Statement line items are structured according to the account group hierarchy from coa-management
- Accounts not assigned to any account group are reported in an "Unclassified" section and flagged as warnings
- Comparative period data, when requested, is aligned to the same account group sections as the current period
- If comparative period trial balance data is unavailable, generation fails with a descriptive error
- FinancialStatement is created in DRAFT status
- A DRAFT statement can be regenerated (replaced) with updated trial balance data
- Finalizing a DRAFT statement transitions it to FINALIZED status
- A FINALIZED statement is immutable — its line items, parameters, and output cannot be modified
- Finalizing an already FINALIZED statement fails with an invalid status transition error
- Generating a statement for a period with no posted journal entries fails with a validation error
- Statement output includes subtotals at each level of the account group hierarchy
- Cash Flow Statement (indirect method) starts with net income and adjusts for non-cash items and working capital changes
- Cash Flow Statement reconciles to the net change between opening and closing cash balances
- Statement generation emits an audit event via the audit module recording the acting user, timestamp, statement type, and parameters
- Finalizing a statement emits an audit event recording the status transition from DRAFT to FINALIZED
- All monetary amounts in the statement are denominated in the company's base currency
- Statement generation for a company with no trial balance data for the requested period returns a validation error
- Each statement records a reference to the trial balance snapshot it was generated from, ensuring traceability

## Reference Links

- [IAS 1 Presentation of Financial Statements (IFRS)](https://www.ifrs.org/issued-standards/list-of-standards/ias-1-presentation-of-financial-statements/)
- [IAS 7 Statement of Cash Flows (IFRS)](https://www.ifrs.org/issued-standards/list-of-standards/ias-7-statement-of-cash-flows/)
- [SAP Financial Statement Versions (FSV)](https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/ee5c9e37ff4f4e33a6c7e2c32f8fc3b5/577f8c2a397b4ce589e1ad03a64eb1ae.html)
- [Oracle Financial Statement Generator (FSG)](https://docs.oracle.com/en/cloud/saas/financials/24d/oaglg/financial-reporting.html)
- [Odoo Financial Reporting](https://www.odoo.com/documentation/19.0/applications/finance/accounting/reporting.html)
- [NetSuite Financial Statements](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1583498.html)
