# Custom Reports

The Report Builder module lets each tenant define ad-hoc reports without modifying code. Reports are stored in two metadata tables that mirror the pattern used by the Form Builder.

## Tables

```sql
CREATE TABLE report_definitions (
  id SERIAL,
  tenant_id INTEGER DEFAULT NULL,
  branch_id INTEGER DEFAULT NULL,
  name varchar(100) NOT NULL,
  description text DEFAULT NULL,
  table_name varchar(100) NOT NULL,
  selected_fields json DEFAULT NULL,
  isDeleted BOOLEAN NOT NULL DEFAULT FALSE,
  updatedAt timestamp NOT NULL DEFAULT current_timestamp,
  PRIMARY KEY (id)
);
```

```sql
CREATE TABLE report_filters (
  id SERIAL,
  report_id INTEGER NOT NULL,
  tenant_id INTEGER DEFAULT NULL,
  branch_id INTEGER DEFAULT NULL,
  field_name varchar(100) NOT NULL,
  operator varchar(10) NOT NULL,
  value varchar(255) DEFAULT NULL,
  order_index INTEGER DEFAULT NULL,
  isDeleted BOOLEAN NOT NULL DEFAULT FALSE,
  updatedAt timestamp NOT NULL DEFAULT current_timestamp,
  PRIMARY KEY (id)
);
```

Each record includes `tenant_id` and `branch_id` so reports can be scoped to a specific counsel or department.

## Configuration

1. Add report definitions from **Dashboard → Report Builder**.
2. Select the database table, choose output columns and define any filters.
3. Use `/api/reportBuilder/generate/{id}?format=csv` to create the file. Supported formats are `csv`, `pdf` and `xlsx`.
4. Generated files are stored in the Document Management System under the `reports` folder. A new document record is created and versioned automatically.

After adding or modifying tables run `test_setup.sh` and then execute the PHP and JS test suites. The IndexedDB schema is now generated dynamically by `api/schema.php` so no manual version bump is required.
