# Reporting Logic and Aggregation System

This document outlines the hierarchical reporting logic implemented for the BJI OMS system.

## 1. Data Structure
Reports are stored in the `ComprehensiveReport` entity (table `comprehensive_reports`). 
Most data sections are stored as `jsonb` columns to allow for flexible, schema-less report fields across different organizational levels (Unit, Ward, Thana, etc.).

## 2. Hierarchical Aggregation
Reports for higher-level organizations (Ward, Thana, City, Central) are dynamically calculated based on the reports of their descendant Units.

### Calculation Logic:
- **Unit Reports**: The base level where data is manually entered.
- **Ward Reports**: The sum of all reports from Units belonging to that Ward for a given month.
- **Thana Reports**: The sum of all reports from all Units within all Wards belonging to that Thana for a given month.
- **General Principle**: Higher-level reports are an aggregate of all underlying **Unit** reports.

### Implementation Detail:
The `ComprehensiveReportService.findOne` method recursively finds all descendant Units for the requested organization and sums their data.
The aggregation utility (`comprehensive-report.utils.ts`) recursively sums numeric values in the JSON sections while preserving strings (taking the first non-empty value encountered).

## 3. Manual Adjustments & Extra Data
Organizations above the Unit level can also have their own report records. 
- If a Ward/Thana report record exists, its values are **added** to the aggregated sum from its children.
- This allows higher levels to:
    - Add "extra" data that doesn't belong to a specific unit (e.g., Ward-level meetings).
    - "Adjust" totals by adding or subtracting (if negative values are supported) from the aggregate.
    - Note: The preferred way to "correct" unit data is to edit the Unit report directly.

## 4. Role-Based Access & Editing
- **Unit Level**: Editors (President, Secretary, Office) can edit their own Unit's report.
- **Ward Level**: Editors can edit their own Ward's report (adjustments) AND any of their **direct child** Unit reports.
- **Thana Level**: Editors can edit their own Thana's report AND any of their **direct child** Ward reports.
- **General Rule**: A user with an editor role can edit reports for their own organization and any direct child organizations.

## 5. Instructions for AI Agents
- When adding new sections to the `ComprehensiveReport` entity, ensure they are added to the `sections` array in `comprehensive-report.service.ts` and `comprehensive-report.utils.ts` to enable aggregation.
- When updating frontend templates, ensure they use the `compReport` data which now automatically contains aggregated values.
- If a user reports that "totals are wrong", check if the underlying Unit reports are correctly saved and if the hierarchy (parentId) is correctly set in the `organizations` table.
