# GenerateFinancialStatement

## Permission Scope

financialStatement

## Overview

generateFinancialStatement creates a financial statement in DRAFT status from trial balance data. The statement can be a Balance Sheet, Profit & Loss, or Cash Flow Statement, scoped to a single company and structured according to the account group hierarchy from coa-management. Statement generation maps GL accounts to the appropriate report sections based on account type and aggregates balances per account group. A DRAFT statement can be regenerated with updated trial balance data before finalization.

## Business Rules

- Requires a valid `companyId` referencing an ACTIVE company
- Requires a valid `chartOfAccountsId` referencing an ACTIVE CoA
- Statement type must be one of: BALANCE_SHEET, PROFIT_AND_LOSS, or CASH_FLOW
- Balance Sheet requires a single reporting date (as-of date)
- Profit & Loss requires a date range (start date and end date)
- Cash Flow Statement 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
- Balance Sheet includes only ASSET, LIABILITY, and EQUITY accounts
- Profit & Loss includes only REVENUE and EXPENSE accounts
- On a correctly generated Balance Sheet, total assets equal total liabilities plus equity
- Statement line items are structured by the account group hierarchy from coa-management
- Accounts not assigned to any group are reported in an "Unclassified" section with warnings
- Comparative period data, when requested, is aligned to same sections as current period
- If comparative period trial balance data is unavailable, generation fails with an error
- Statement is created in DRAFT status
- A DRAFT statement can be regenerated (replaced) with updated trial balance data
- Generating 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
- All monetary amounts are denominated in the company's base currency
- Each statement records a reference to the trial balance snapshot it was generated from
- Emits an audit event recording the acting user, timestamp, statement type, and parameters

## Process Flow

```mermaid
flowchart TD
    A[Receive generate financial statement request] --> B{Company ACTIVE with ACTIVE CoA?}
    B -->|No| C[Return error: invalid company or CoA]
    B -->|Yes| D{Valid statement type?}
    D -->|No| E[Return error: invalid statement type]
    D -->|Yes| F{Valid reporting parameters?}
    F -->|No| G[Return error: invalid parameters]
    F -->|Yes| H{Trial balance data available?}
    H -->|No| I[Return error: no trial balance data]
    H -->|Yes| J[Retrieve trial balance for period]
    J --> K[Map accounts to statement sections by type]
    K --> L[Aggregate balances per account group]
    L --> M{Comparative period requested?}
    M -->|Yes| N[Retrieve and align prior period data]
    M -->|No| O[Assemble statement line items]
    N --> O
    O --> P[Create FinancialStatement in DRAFT]
    P --> Q[Emit audit event]
    Q --> R[Return DRAFT financial statement]
```

## External Dependencies

- [coa-management::getChartOfAccounts](../../../coa-management/docs/queries/GetChartOfAccounts.md) - Retrieves the active CoA and account group hierarchy for statement structure
- [coa-management::getAccount](../../../coa-management/docs/queries/GetAccount.md) - Retrieves GL accounts for type-based classification
- [organization::getCompany](../../../organization/docs/queries/GetCompany.md) - Validates that the referenced company is ACTIVE and retrieves base currency

## Error Scenarios

- **COMPANY_NOT_FOUND**: Referenced company does not exist or is not in ACTIVE status
- **CHART_OF_ACCOUNTS_NOT_FOUND**: Referenced CoA does not exist or is not ACTIVE
- **INVALID_STATEMENT_TYPE**: Statement type is not BALANCE_SHEET, PROFIT_AND_LOSS, or CASH_FLOW
- **INVALID_REPORTING_PARAMETERS**: Missing or invalid reporting date, date range, or cash flow method
- **NO_TRIAL_BALANCE_DATA**: No trial balance data exists for the requested period
- **COMPARATIVE_DATA_UNAVAILABLE**: Comparative period trial balance data is not available

## Test Cases

- returns error when company does not exist
- returns error when company is not ACTIVE
- returns error when CoA does not exist
- returns error when CoA is not ACTIVE
- returns error for invalid statement type
- returns error when BALANCE_SHEET is missing reportingDate
- returns error when PROFIT_AND_LOSS is missing date range
- returns error when CASH_FLOW is missing cashFlowMethod
- returns error when trial balance does not exist
- returns error when comparative trial balance does not exist
- returns error when trial balance has no lines
- successfully generates a BALANCE_SHEET financial statement
- successfully generates a PROFIT_AND_LOSS financial statement
- generates subtotal lines for each section
- emits audit event recording the generation
