# ReverseJournalEntry

## Permission Scope

journalEntry

## Overview

reverseJournalEntry creates a mirror journal entry with all debit and credit amounts inverted from the original posted entry. The reversal entry is automatically POSTED, so its JournalLine rows become ledger lines. The original entry remains POSTED so the original ledger effect stays traceable and nets against the reversal entry. This is the only way to correct a posted journal entry, as posted entries cannot be modified or deleted. The reversal entry must target a period that is in OPEN status.

## Business Rules

- Original journal entry must exist and be in POSTED status
- DRAFT and CANCELLED entries cannot be reversed
- Entries that already have a reversal entry cannot be reversed again
- A new mirror journal entry is created with all debit amounts swapped to credits and vice versa
- The reversal entry references the original entry
- The reversal entry is automatically posted upon creation
- The reversal entry creates inverted JournalLine rows
- The original entry remains POSTED
- The reversal entry must target an accounting period in OPEN status

## Process Flow

```mermaid
flowchart TD
    A[Receive reverse journal entry request] --> B{Original entry exists?}
    B -->|No| C[Return error: journal entry not found]
    B -->|Yes| D{Original entry status is POSTED?}
    D -->|No| E[Return error: invalid status for reversal]
    D -->|Yes| F{Reversal period OPEN?}
    F -->|No| G[Return error: invalid period status]
    F -->|Yes| H[Create mirror entry with inverted debits/credits]
    H --> I[Create inverted JournalLine rows]
    I --> M[Return reversal entry and original entry]
```

## External Dependencies

- None

## Error Scenarios

- **JOURNAL_ENTRY_NOT_FOUND**: Referenced journal entry does not exist
- **INVALID_STATUS_FOR_REVERSAL**: Journal entry is not in POSTED status; only POSTED entries can be reversed
- **ALREADY_REVERSED**: Journal entry has already been reversed
- **INVALID_PERIOD_STATUS**: Target accounting period is not in OPEN status

## Test Cases

- returns error when journal entry does not exist
- returns error when journal entry is in DRAFT status
- returns error when journal entry is in CANCELLED status
- returns error when journal entry already has a reversal entry
- returns error when reversal period is in NEVER_OPENED status
- returns error when reversal period is in CLOSED status
- returns error when reversal period is in PERMANENTLY_CLOSED status
- creates mirror entry with all debit/credit amounts inverted
- does not create separate ledger rows for the reversal entry
- reversal entry references the original entry
- reversal entry is automatically posted
- original entry remains POSTED after reversal
- reversal entry targets the specified accounting period
