# CreateAccountGroup

## Overview

createAccountGroup establishes a new account group within a Chart of Accounts. Groups organize GL accounts into logical categories and can be nested to form a multi-level tree hierarchy. Each group has a code, name, optional parent reference, sort order, and optional account number range.

## Business Rules

- Parent CoA must exist and be in DRAFT or ACTIVE status; creating a group under an ARCHIVED CoA is rejected
- Group code is required and must be unique within the CoA
- Group name is required and must be non-empty
- Parent group, when provided, must exist within the same CoA
- Account number range, when defined, requires both start and end to be provided together, must be a valid interval (start < end), and must not overlap with other groups' ranges within the CoA
- Sort order controls display sequence among sibling groups

## Process Flow

```mermaid
flowchart TD
    A[Receive create request] --> B{CoA exists?}
    B -->|No| C[Return error: CoA not found]
    B -->|Yes| B2{CoA is DRAFT or ACTIVE?}
    B2 -->|No| B3[Return error: CoA is ARCHIVED]
    B2 -->|Yes| C2{Code non-empty?}
    C2 -->|No| C3[Return error: code required]
    C2 -->|Yes| D{Code unique within CoA?}
    D -->|No| E[Return error: duplicate code]
    D -->|Yes| F{Parent group valid if provided?}
    F -->|No| G[Return error: parent not found]
    F -->|Yes| H{Number range valid and non-overlapping?}
    H -->|No| I[Return error: invalid or overlapping range]
    H -->|Yes| J[Create account group]
    J --> K[Return created group]
```

## External Dependencies

- None

## Error Scenarios

- **CHART_OF_ACCOUNTS_NOT_FOUND**: Referenced CoA does not exist
- **CHART_OF_ACCOUNTS_ARCHIVED**: Parent CoA is in ARCHIVED status; no modifications are permitted
- **CODE_REQUIRED**: Group code is empty or not provided
- **DUPLICATE_GROUP_CODE**: A group with the same code already exists in the CoA
- **NAME_REQUIRED**: Group name is empty or not provided
- **PARENT_GROUP_NOT_FOUND**: Specified parent group does not exist or belongs to a different CoA
- **INVALID_NUMBER_RANGE**: Number range is invalid (start >= end) or overlaps with another group's range

## Test Cases

- returns error when CoA does not exist
- returns error when parent CoA is ARCHIVED
- returns error when group code is empty
- returns error when group code already exists in CoA
- returns error when name is empty
- returns error when parent group does not exist
- returns error when parent group belongs to different CoA
- returns error when number range is invalid
- returns error when number range overlaps with existing group
- returns error when only numberRangeStart is provided
- returns error when only numberRangeEnd is provided
- creates a root group with no parent
- creates a child group with valid parent
- creates a group with account number range
- creates a group with sort order
- passes custom fields through to insert
