# Plan: Ledger Kernel Extensions

This document outlines the phases of extending the lightweight, accounting-agnostic ledger web application.

## Phase 1: Exploration, Migrations, and Schema Versioning
- Define dynamic, thread-local DB connections in `ledger_core.py`.
- Implement robust database migrations in `init_db()` (using schema version `PRAGMA user_version` and guards).
- Add new columns to `uploads` (`created_by`, `source_type`) and `company` (`lock_date`).
- Implement database indices on `entry_rows(account_no, date)` and `entry_rows(date)`.

## Phase 2: Login and Engagement Doorway
- Create a registry database `workspace.db` in the application directory.
- Define schemas for `users` and `engagements`.
- Implement security helpers (password hashing via `hashlib.scrypt` and comparison via `hmac.compare_digest`).
- Implement a launch doorway screen (`/login`) in Flask. Add user and engagement creation workflows.
- Restrict all existing web pages using a login session check and request wrapper.

## Phase 3: Backup and Restore
- Implement Backup endpoints using SQLite's online backup API.
- Back up engagement files into zip files with a JSON manifest (`manifest.json` with metadata, schema version, and row counts).
- Implement Auto-backup on application shutdown and immediately prior to a database restore.
- Implement backup validation (verifying user_version and table schemas) before overwriting the database.

## Phase 4: Date-Normalised Period Trial Balance
- Implement robust date parsing and ISO format normalisation (`YYYY-MM-DD`) on entry upload. Reject unparseable dates.
- Update `get_trial_balance` with inclusive date-range filters over posted entries.
- Add preset duration buttons (Day, Week, Month, Quarter, Year, Custom) using an anchor date picker.
- Use `company.year_end` to compute the correct fiscal year range for the Year preset.

## Phase 5: General Ledger Excel Export
- Create `exports.py` for exporting trial balance and transaction detail sheets via `openpyxl`.
- Handle the missing `openpyxl` fallback by exporting zip files with equivalent CSV files and flashing a warning.

## Phase 6: Period Locking, Rollover, and Comparatives
- Block postings, unpostings, and deletions on entry rows containing dates `<= lock_date`.
- Introduce a Year-End Rollover Generator:
  - Query COA metadata to classify accounts (Permanent vs Temporary/P&L).
  - Net out P&L accounts into the Retained Earnings account.
  - Generate a new opening balance batch (`source_type='OPENING'`) for the next fiscal year.
- Add warnings if temporary accounts have non-zero opening balances.
- Implement comparative columns (prior period, variance amount, variance percentage) on the Trial Balance layout.
