# InitiatePeriodClose

## Permission Scope

periodManagement

## Overview

initiatePeriodClose creates a new PeriodClose record in NOT_STARTED status for a given accounting period. This establishes the close checklist that will track the period through the structured close workflow. Only periods in OPEN status can have a close initiated, and each period can have at most one active PeriodClose record.

## Business Rules

- Requires a valid `accountingPeriodId` referencing an existing accounting period
- The accounting period must be in OPEN status
- A PeriodClose cannot be initiated for a period that is already CLOSED or PERMANENTLY_CLOSED
- A PeriodClose cannot be initiated if the period already has an active close record in progress
- Concurrent close attempts for the same period are rejected with a conflict error
- The PeriodClose record is created in NOT_STARTED status
- Records the userId of the operator who initiated the close
- Sets completionPercentage to 0
- PeriodClose is scoped to a single AccountingPeriod; each period has at most one active PeriodClose record
- Emits an audit event via the audit module recording the acting user, timestamp, and period reference

## Process Flow

```mermaid
flowchart TD
    A[Receive initiate period close request] --> B{Accounting period exists?}
    B -->|No| C[Return error: period not found]
    B -->|Yes| D{Period in OPEN status?}
    D -->|No| E[Return error: invalid period status]
    D -->|Yes| F{Active PeriodClose already exists?}
    F -->|Yes| G[Return error: close already in progress]
    F -->|No| H[Create PeriodClose in NOT_STARTED status]
    H --> I[Record initiating user and set completion to 0%]
    I --> J[Emit audit event]
    J --> K[Return PeriodClose record]
```

## External Dependencies

- None (same-module read for accounting period and period close lookup)

## Error Scenarios

- **ACCOUNTING_PERIOD_NOT_FOUND**: Referenced accounting period does not exist
- **INVALID_PERIOD_STATUS**: Target accounting period is not in OPEN or FUTURE_ENTERABLE status
- **CLOSE_ALREADY_IN_PROGRESS**: An active PeriodClose record already exists for this period
- **CONCURRENT_CLOSE_CONFLICT**: A concurrent close attempt for the same period was detected

## Test Cases

- returns error when accounting period does not exist
- returns error when accounting period is in NEVER_OPENED status
- returns error when accounting period is in CLOSED status
- returns error when accounting period is in PERMANENTLY_CLOSED status
- returns error when period already has an active close in progress
- returns error on concurrent close attempt for the same period
- creates PeriodClose in NOT_STARTED status for an OPEN period
- records the initiating user's userId
- sets completionPercentage to 0
- emits audit event recording acting user, timestamp, and period reference
