> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lerian.studio/llms.txt
> Use this file to discover all available pages before exploring further.

# Trial Balance Report with Midaz and Reporter

> Produce a trial balance from your Midaz Ledger using Reporter and export it as XML, TXT, HTML, or PDF — no extra conversion tools needed.

Security, compliance, and clarity in financial reporting start with your ledger. **Midaz** is a financial ledger at its core — meaning it already stores all the data required to produce a trial balance, from account structures to transaction histories.

While Midaz provides the raw data, the **Reporter** product transforms this data into ready-to-share outputs. With Reporter, you can generate trial balances and export them directly in formats such as **XML, TXT, HTML, and PDF** — without needing extra conversion tools.

# Key concepts

***

Before diving into the step-by-step process, it's important to understand how Midaz structures data for regulatory reporting:

## OperationRoute and the code field

***

The **OperationRoute** entity is central to COSIF mapping. Each OperationRoute has a code field (max 100 characters) designed specifically to store external reference codes such as COSIF account codes.

When transactions are processed, each operation is associated with an OperationRoute. By aggregating operations grouped by OperationRoute.code, you can calculate balances per COSIF account — which is exactly what a trial balance requires.

```text theme={null}
OperationRoute
├── code: "1.1.1.10-8"        ← COSIF code for aggregation
├── title: "Checking Account Debit"
├── operationType: "source" | "destination"
└── account: AccountRule      ← Validation rules
```

## TransactionRoute

***

A **TransactionRoute** groups multiple OperationRoutes (sources and destinations) into a reusable template. When creating transactions, you reference a TransactionRoute, and Midaz validates that operations follow the defined rules.

# Step-by-step process

***

## 1. Prepare your Chart of Accounts in Midaz

***

Configure your **Organizations, Ledgers, Assets, Account Types, and Accounts** according to your business needs.

The key entities for trial balance generation are:

* **Account Types** — define the nature of each account (asset, liability, equity, revenue, expense) using the keyValue field.
* **OperationRoutes** — map each type of operation to a COSIF code via the code field.
* **TransactionRoutes** — group OperationRoutes into transaction templates with validation rules.

## 2. Create OperationRoutes with COSIF codes

***

For each COSIF account in your chart of accounts, create corresponding OperationRoutes with the COSIF code in the code field.

Example OperationRoutes for a Brazilian financial institution:

OperationRoute for checking account debits (source):

```json theme={null}
{
  "title": "Checking Account Withdrawal",
  "description": "Debit operations from personal checking accounts",
  "code": "1.1.1.10-8",
  "operationType": "source",
  "account": {
    "ruleType": "account_type",
    "validIf": ["checking_account_pf", "checking_account_pj"]
  }
}
```

OperationRoute for checking account credits (destination):

```json theme={null}
{
  "title": "Checking Account Deposit",
  "description": "Credit operations to personal checking accounts",
  "code": "1.1.1.10-8",
  "operationType": "destination",
  "account": {
    "ruleType": "account_type",
    "validIf": ["checking_account_pf", "checking_account_pj"]
  }
}
```

OperationRoute for investment account:

```json theme={null}
{
  "title": "Investment Account Movement",
  "description": "Operations involving investment accounts",
  "code": "1.2.3.00-0",
  "operationType": "source",
  "account": {
    "ruleType": "account_type",
    "validIf": ["investment_account"]
  }
}
```

Common COSIF mappings:

| COSIF Code | Description                     | Account Types         |
| ---------- | ------------------------------- | --------------------- |
| 1.1.1.10-8 | Checking Accounts - Individuals | checking\_account\_pf |
| 1.1.1.20-5 | Checking Accounts - Companies   | checking\_account\_pj |
| 1.2.3.00-0 | Investment Accounts             | investment\_account   |
| 7.1.1.00-0 | Service Revenue                 | revenue\_services     |
| 8.1.1.00-0 | Administrative Expenses         | expense\_admin        |

## 3. Create TransactionRoutes

***

Group your OperationRoutes into TransactionRoutes that represent common transaction patterns.

<Note>
  When creating a TransactionRoute, you pass an array of OperationRoute UUIDs. When retrieving a TransactionRoute via the API, it returns the full OperationRoute objects with all their details.
</Note>

```json theme={null}
{
  "title": "PIX Transfer Between Accounts",
  "description": "Internal PIX transfer from one checking account to another",
  "operationRoutes": [
    "uuid-of-checking-account-source-route",
    "uuid-of-checking-account-destination-route"
  ]
}
```

## 4. Process transactions with routes

***

When creating transactions, reference the TransactionRoute. Each operation will be associated with its corresponding OperationRoute and COSIF code:

```json theme={null}
{
  "code": "PIX_TRANSFER_001",
  "description": "PIX lunch payment",
  "route": "uuid-of-pix-transfer-route",
  "send": {
    "asset": "BRL",
    "value": 4550,
    "source": {
      "from": [{
        "accountAlias": "@joao_silva_cc"
      }]
    },
    "distribute": {
      "to": [{
        "accountAlias": "@restaurante_abc"
      }]
    }
  },
  "metadata": {
    "pixKey": "12345678901",
    "description": "Lunch"
  }
}
```

<Note>
  The `asset` and `value` are defined at the `send` level. Individual operations in `from` and `to` use `accountAlias` (not `account`). The value is expressed in the smallest unit of the asset (e.g., cents for BRL, so 4550 = R\$ 45.50).
</Note>

The COSIF mapping happens automatically through the route:

```text theme={null}
Transaction uses route → TransactionRoute
                              ↓
                       OperationRoutes[]
                              ↓
            source: code = "1.1.1.10-8" (COSIF)
            destination: code = "1.1.1.20-5" (COSIF)
```

## 5. Understanding the data flow

***

Midaz stores all the financial data needed for trial balance generation:

* **Operations** — each operation includes a `route` field containing the OperationRoute UUID
* **OperationRoutes** — contain the `code` field with COSIF codes for aggregation
* **Account Balances** — current positions per account

**How aggregation works:**

Each Operation stores a `route` field that references the OperationRoute UUID (not the COSIF code directly). To aggregate by COSIF code, Reporter joins operations with their corresponding OperationRoutes to access the `code` field:

```text theme={null}
Operation.route (UUID) → OperationRoute.id → OperationRoute.code (COSIF)
```

**Available Midaz APIs:**

```text theme={null}
GET /v1/organizations/{org_id}/ledgers/{ledger_id}/accounts/{account_id}/operations
```

Query parameters for filtering include `cursor`, `limit`, and `type`. Operations are retrieved per account.

<Note>
  Reporter connects directly to the Midaz database for report generation, enabling efficient batch queries and aggregations. The APIs above are available for custom integrations and ad-hoc queries.
</Note>

## 6. Generate your report with Reporter

***

Reporter uses a template-driven architecture to generate reports. The process involves:

1. **Select or create a template** — templates use Pongo2 syntax (Django-like) with custom aggregation tags
2. **Configure data sources** — Reporter queries Midaz database tables directly
3. **Apply filters** — specify date ranges, account types, or other criteria
4. **Generate the report** — Reporter aggregates data and renders the template
5. **Export** in your chosen format (XML, TXT, HTML, PDF, CSV, JSON)

**How Reporter aggregates data:**

Reporter templates support built-in aggregation tags for calculating balances:

* `{% sum_by collection by "field" %}` — sum values by field
* `{% count_by collection if condition %}` — count records matching condition
* `{% calc expression %}` — arithmetic calculations

**Example template snippet for COSIF aggregation:**

```
{% for route in operation_routes %}
  {{ route.code }} |
  Debits: {% sum_by operations by "amount" if operation.route == route.id and operation.type == "DEBIT" %} |
  Credits: {% sum_by operations by "amount" if operation.route == route.id and operation.type == "CREDIT" %}
{% endfor %}
```

<Tip>
  Reporter includes ready-to-use templates for different reporting needs. Use the [**CADOC 4010**](/en/reporter/cadoc-4010-and-4016) template when generating reports for **BACEN regulatory submission**, as it follows the official required structure.
</Tip>

## 7. Export and integrate

***

You can:

* Export a **ready-to-share PDF** for auditors and regulators
* Generate **XML** files formatted for BACEN submission
* Integrate with your existing reporting workflows or accounting systems

# Practical example — Complete Midaz setup

***

Below is a fictional institution, **DigitalBank**, showing how Midaz entities connect to support a trial balance:

<Accordion title="Organization">
  ```json theme={null}
  {
    "legalName": "DigitalBank S.A.",
    "legalDocument": "12.345.678/0001-90",
    "address": {
      "line1": "Av. Faria Lima, 3064",
      "line2": "12th floor",
      "zipCode": "01451-000",
      "city": "Sao Paulo",
      "state": "SP",
      "country": "Brazil"
    },
    "metadata": {
      "cnae": "6422-1",
      "licenseNumber": "BCB-2024-001",
      "foundedAt": "2024-01-15"
    }
  }
  ```
</Accordion>

<Accordion title="Assets">
  ```json theme={null}
  [
    {
      "name": "Brazilian Real",
      "type": "currency",
      "code": "BRL",
      "status": { "code": "ACTIVE" },
      "metadata": {
        "symbol": "R$",
        "centralBank": "BACEN"
      }
    }
  ]
  ```
</Accordion>

<Accordion title="Account Types">
  ```json theme={null}
  [
    {
      "name": "Personal Checking Account",
      "keyValue": "checking_account_pf",
      "description": "Checking accounts for individual customers"
    },
    {
      "name": "Business Checking Account",
      "keyValue": "checking_account_pj",
      "description": "Checking accounts for business customers"
    },
    {
      "name": "Investment Account",
      "keyValue": "investment_account",
      "description": "Investment and savings accounts"
    }
  ]
  ```

  <Note>
    COSIF codes are defined in OperationRoutes via the `code` field, **not** in Account Types. Account Types define the nature of accounts and are used by OperationRoutes for validation rules.
  </Note>
</Accordion>

<Accordion title="OperationRoutes with COSIF codes">
  ```json theme={null}
  [
    {
      "title": "PF Checking - Debit",
      "code": "1.1.1.10-8",
      "operationType": "source",
      "account": {
        "ruleType": "account_type",
        "validIf": ["checking_account_pf"]
      }
    },
    {
      "title": "PF Checking - Credit",
      "code": "1.1.1.10-8",
      "operationType": "destination",
      "account": {
        "ruleType": "account_type",
        "validIf": ["checking_account_pf"]
      }
    },
    {
      "title": "PJ Checking - Debit",
      "code": "1.1.1.20-5",
      "operationType": "source",
      "account": {
        "ruleType": "account_type",
        "validIf": ["checking_account_pj"]
      }
    },
    {
      "title": "PJ Checking - Credit",
      "code": "1.1.1.20-5",
      "operationType": "destination",
      "account": {
        "ruleType": "account_type",
        "validIf": ["checking_account_pj"]
      }
    }
  ]
  ```
</Accordion>

<Accordion title="TransactionRoute for PIX">
  ```json theme={null}
  {
    "title": "PIX Transfer PF to PJ",
    "description": "PIX transfer from personal to business account",
    "operationRoutes": [
      "uuid-pf-checking-debit",
      "uuid-pj-checking-credit"
    ]
  }
  ```
</Accordion>

<Accordion title="Sample Transaction">
  ```json theme={null}
  {
    "code": "PIX_TRANSFER_001",
    "description": "PIX lunch payment",
    "route": "uuid-pix-transfer-pf-to-pj",
    "send": {
      "asset": "BRL",
      "value": 4550,
      "source": {
        "from": [{
          "accountAlias": "@joao_silva_cc"
        }]
      },
      "distribute": {
        "to": [{
          "accountAlias": "@restaurante_abc"
        }]
      }
    },
    "metadata": {
      "pixKey": "12345678901",
      "purpose": "Lunch payment"
    }
  }
  ```
</Accordion>

# Trial Balance output example

***

After joining operations with their OperationRoutes and aggregating by the `code` field, your trial balance would look like:

| COSIF Code | Description   | Debits (R\$)   | Credits (R\$)  | Balance (R\$) |
| ---------- | ------------- | -------------- | -------------- | ------------- |
| 1.1.1.10-8 | Checking - PF | 150,000.00     | 145,000.00     | 5,000.00      |
| 1.1.1.20-5 | Checking - PJ | 89,000.00      | 92,500.00      | -3,500.00     |
| 1.2.3.00-0 | Investments   | 50,000.00      | 48,000.00      | 2,000.00      |
| **Total**  |               | **289,000.00** | **285,500.00** | **3,500.00**  |

Using Reporter, this data can be formatted into:

* **XML** — structured for BACEN regulatory submission
* **PDF** — professional report for auditors and stakeholders
* **TXT** — flat file for legacy system integration

The report consolidates ledger data by COSIF code, presenting balances grouped by accounting sections (Assets, Liabilities, Equity, Revenues, and Expenses), along with subtotals and a global total. This output reflects the result of automated aggregation and validation performed on top of Midaz data, ready for audit, compliance, and regulatory use.

# Summary

***

The key to generating accurate trial balances with Midaz is proper use of the `code` field in OperationRoutes:

1. **Create OperationRoutes** with COSIF codes in the `code` field
2. **Group into TransactionRoutes** for transaction validation
3. **Process transactions** referencing the appropriate routes
4. **Join operations with OperationRoutes** using the `route` field (UUID) to access COSIF codes
5. **Aggregate by OperationRoute.code** to calculate balances per COSIF account
6. **Generate reports** with Reporter using templates that perform the aggregation automatically

This approach ensures:

* Regulatory compliance with COSIF standards
* Automatic balance aggregation by account code
* Validation of transaction operations
* Flexible reporting in multiple formats

# Related documentation

***

* [OperationRoutes API Reference](/en/reference/midaz/create-an-operation-route)
* [TransactionRoutes API Reference](/en/reference/midaz/create-transaction-route)
* [Account Types API Reference](/en/reference/midaz/create-an-account-type)
* [Operations API Reference](/en/reference/midaz/list-operations-by-account)
* [Reporter Overview](/en/reporter/what-is-reporter)
* [CADOC 4010 and 4016](/en/reporter/cadoc-4010-and-4016)
