# GeneratePreliminaryStatements

## Permission Scope

financialStatement

## Overview

generatePreliminaryStatements generates preliminary financial statements (Balance Sheet, Profit & Loss) for the closing period and transitions the PeriodClose from TRIAL_BALANCE_VERIFIED to UNDER_REVIEW status. Preliminary statements can only be generated after the trial balance has been verified, ensuring that all figures are based on a balanced ledger. These statements are generated in DRAFT status for management review and approval.

## Business Rules

- PeriodClose record must exist and be in TRIAL_BALANCE_VERIFIED status
- Only TRIAL_BALANCE_VERIFIED records can transition to UNDER_REVIEW
- Preliminary financial statements can only be generated after the trial balance is verified
- Statements are generated in DRAFT status for review purposes
- The trial balance must still be balanced at time of generation
- Updates completionPercentage to reflect progress
- Records the userId of the operator who generated the preliminary statements
- Emits an audit event recording the acting user, timestamp, generated statement references, and status transition

## Process Flow

```mermaid
flowchart TD
    A[Receive generate preliminary statements request] --> B{PeriodClose record exists?}
    B -->|No| C[Return error: period close not found]
    B -->|Yes| D{PeriodClose in TRIAL_BALANCE_VERIFIED status?}
    D -->|No| E[Return error: invalid status transition]
    D -->|Yes| F[Retrieve verified trial balance for the period]
    F --> G[Generate preliminary Balance Sheet in DRAFT]
    G --> H[Generate preliminary Profit & Loss in DRAFT]
    H --> I[Transition PeriodClose to UNDER_REVIEW]
    I --> J[Update completionPercentage]
    J --> K[Emit audit event]
    K --> L[Return updated PeriodClose with statement references]
```

## External Dependencies

- [coa-management::getChartOfAccounts](../../../coa-management/docs/queries/GetChartOfAccounts.md) - Retrieves the active CoA and account group hierarchy for statement structure
- [organization::getCompany](../../../organization/docs/queries/GetCompany.md) - Retrieves company details and base currency for statement denomination

## 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_NOT_FOUND**: Referenced trial balance does not exist or is invalid

## Test Cases

- returns error when PeriodClose record does not exist
- returns error when PeriodClose is in SOFT_LOCKED status
- returns error when PeriodClose is in IN_PROGRESS status
- returns error when trial balance is not found
- generates both BS and P&L and transitions to UNDER_REVIEW with completionPercentage=75
- emits audit event recording status transition and statement ids
