# Config Builder

Define synthetic columns and table relations via XML configuration. Allows creating calculated fields and connecting any database tables for use in reports.

## Before Creating a Config — Check the Schema

**Always** query the schema endpoint first to understand what already exists:

```
GET /V1/report-builder/schema
  query: { "fields": "items[name,label,group,columns[identifier,label,type,is_dimension]],total_count" }
```

Filter by table name to inspect a specific table's columns:
```
  query: { "searchCriteria[filter_groups][0][filters][0][field]": "name",
           "searchCriteria[filter_groups][0][filters][0][value]": "catalog_product_entity",
           "fields": "items[name,columns[identifier,label,type,is_dimension]]" }
```

**Interpret the results:**
- Columns with `type: "fk"` mean the relation to the referenced table **already exists**. The report builder joins automatically. **Do NOT create a `<relation>` for tables already connected via fk columns.**
- If the column you need already appears in the schema, no config is needed — just use it in the report.
- Only create a config when you need a **synthetic column** (calculated via SQL expression) or a **relation between tables that have no `fk` connection** in the schema.

## Creating or Updating a Config

A config is an XML document that registers tables, defines synthetic columns with SQL expressions, and establishes relations between tables. Multiple configs can coexist — each is stored as a separate entity with its own ID.

### Workflow

1. List existing configs via the config REST API
2. Check if any existing config already references the target table(s):
   - **No existing config** for the table → create a new config
   - **One existing config** references the table → update that config by adding the new column/relation to its XML
   - **Multiple configs** reference the same table → ask the user whether to add to an existing config (and which one) or create a separate one
3. Save the config via the REST API — the save endpoint validates XML against the XSD schema automatically. If the XML is invalid, the API returns an error and the config is not saved
4. After a successful save, verify by retrieving the config by ID to confirm it was persisted correctly
5. New columns become available in Report Builder column chooser

### Pitfalls

- Table names must be specified **without** the database prefix (e.g., `sales_order` not `mage_sales_order`)
- When updating an existing config, always preserve all existing XML content — do not remove columns or relations that are already defined
- A single config can define multiple tables, columns, and relations — grouping related elements in one config is preferred over many small configs

## Troubleshooting Config Errors

If the user reports an error like `The XML in file "mst_report_2" is invalid`, the number after `mst_report_` is the config ID. To identify the broken config:

1. Extract the ID from the error message (e.g., `mst_report_2` → config ID `2`)
2. Retrieve the config via `GET /V1/report-builder/config/2`
3. Report the config title and its XML content to the user
4. Fix the XML and update via the REST API

## XML Structure

Root element is `<config>` with three possible child elements: `<table>`, `<eavTable>`, `<relation>`.

### table

Registers a table or adds synthetic columns to an already registered table.

| Attribute | Required | Description |
|-----------|----------|-------------|
| `name` | yes | Table name without DB prefix |
| `group` | no | Group in Report Builder: `Sales`, `Products`, `Customers`, `Categories`, `Other` (default) |
| `label` | no | Display label (defaults to `name`) |
| `connection` | no | DB connection: `sales` or `checkout` (for split-database setups) |

Child elements: `<pk>`, `<fk>`, `<column>`.

### eavTable

Registers an EAV entity table. Automatically adds columns for all EAV attributes. Do NOT use for native EAV tables (`catalog_product_entity`, `customer_entity`, etc.) — they are already registered.

| Attribute | Required | Description |
|-----------|----------|-------------|
| `name` | yes | Table name without DB prefix |
| `type` | yes | EAV entity type code (from `eav_entity_type.entity_type_code`) |
| `group` | no | Group in Report Builder |
| `label` | no | Display label |

Child elements: `<pk>`, `<fk>`, `<column>`.

### pk

Primary key of the table. Only needed for tables not already registered by the extension.

| Attribute | Required | Description |
|-----------|----------|-------------|
| `name` | yes | Primary key column name |
| `label` | no | Display label |

### fk

Foreign key. Defines a link to another table. Only needed for tables not already registered.

| Attribute | Required | Description |
|-----------|----------|-------------|
| `name` | yes | Foreign key column name |
| `table` | yes | Related table name without prefix |
| `label` | no | Display label |
| `uniq` | no | Set to `1` if this is a one-to-one relationship |

### column

Defines a column — either mapping an existing DB column or creating a synthetic calculated column.

| Attribute | Required | Description |
|-----------|----------|-------------|
| `name` | yes | Column identifier (use existing DB column name or a new name for synthetic columns) |
| `label` | yes | Display label |
| `type` | no | Data type (see Column Types below). Defaults to `html` |
| `fields` | no | Comma-separated list of DB fields used in calculation. Defaults to `name` value |
| `expr` | no | MySQL expression. `%1`, `%2`, etc. map to fields in order. Defaults to `%1` |
| `store_expr` | no | Expression used when report is filtered by a single store (avoids currency conversion) |
| `tables` | no | Comma-separated table names whose columns are referenced in `expr` (for cross-table expressions) |
| `options` | no | Full class name implementing `toOptionArray()` — used with `select` and `country` types |
| `uniq` | no | Set to `1` for unique identifier columns (shown as-is, not aggregated) |

### relation

Defines how to join two tables.

**Before adding a relation:** check existing configs for a relation between the same two tables. If one already exists, warn the user that changing or overriding it may affect data accuracy in all reports where these tables are used.

| Attribute | Required | Description |
|-----------|----------|-------------|
| `name` | yes | Relation identifier (convention: `leftTable-rightTable`) |
| `type` | yes | `11` (one-to-one) or `1n` (one-to-many) |

Required child elements:
- `<leftTable>` — table name without prefix
- `<rightTable>` — table name without prefix
- `<condition>` — MySQL JOIN condition. `%1` = leftTable, `%2` = rightTable

## Column Types

The type determines display formatting and available aggregations in Report Builder.

| Type | Display | Aggregators |
|------|---------|-------------|
| `html` | Raw string value | `JOIN` |
| `number` | Number, 2 decimal places | `SUM`, `AVG` |
| `qty` | Integer | `COUNT` |
| `percent` | Value with `%` symbol, 2 decimal places | `AVG` |
| `money` | Currency symbol, 2 decimal places. Uses store currency when filtered by store | `SUM`, `AVG` |
| `date` | Date value | `HOUR`, `DAY`, `DAY OF WEEK`, `MONTH`, `QUARTER`, `YEAR` |
| `select` | Predefined options (requires `options` attribute) | `JOIN` |
| `country` | Country name from ISO 3166-1 alpha-2 code | `JOIN` |
| `store` | Store label (no `options` needed) | — |

## Currency Conversion Pattern

For money columns in multi-currency stores, use `base_*` fields with the conversion rate:

```xml
<column name="grand_total"
        label="Grand Total"
        fields="base_grand_total,base_to_global_rate"
        type="money"
        expr="%1 * IF(%2 > 0, %2, 1)"
        store_expr="%1"/>
```

- `expr` — converts base currency to global currency for cross-store reports
- `store_expr` — uses base value as-is when report is filtered by a single store
- `IF(%2 > 0, %2, 1)` — safety check for missing conversion rate

## Cross-Table Expressions

To reference columns from other tables in an expression, list them in the `tables` attribute:

```xml
<column name="cost"
        label="Cost"
        fields="base_cost,qty_ordered"
        type="money"
        expr="(%1 * %2) * IF(sales_order.base_to_global_rate > 0, sales_order.base_to_global_rate, 1)"
        store_expr="(%1 * %2)"
        tables="sales_order"/>
```

The `tables="sales_order"` allows using `sales_order.base_to_global_rate` directly in the expression.

## Examples

### Gross Profit (synthetic column on existing table)

```xml
<config>
    <table name="sales_order">
        <column name="custom_gross_profit"
                label="Gross Profit"
                fields="base_subtotal_invoiced,base_total_invoiced_cost,base_total_refunded,base_to_global_rate"
                type="money"
                expr="(%1 - IFNULL(%2, 0) - IFNULL(%3, 0)) * %4"/>
    </table>
</config>
```

### Register a New Table with Relations

Register `sales_shipment_item`, connect it to order items and shipments, add a shipment date column:

```xml
<config>
    <table name="sales_shipment_item" group="Sales" label="Shipment Item">
        <pk name="entity_id"/>
        <column name="parent_id" label="Shipment Id"/>
        <column name="order_item_id" label="Order Item Id"/>
    </table>

    <relation name="sales_order_item-sales_shipment_item" type="11">
        <leftTable>sales_order_item</leftTable>
        <rightTable>sales_shipment_item</rightTable>
        <condition>%1.item_id=%2.order_item_id</condition>
    </relation>

    <relation name="sales_shipment-sales_shipment_item" type="11">
        <leftTable>sales_shipment</leftTable>
        <rightTable>sales_shipment_item</rightTable>
        <condition>%1.entity_id=%2.parent_id</condition>
    </relation>

    <table name="sales_shipment" group="Sales" label="Shipment">
        <column name="shipped_at" label="Shipment Date" fields="created_at" type="date"/>
    </table>
</config>
```

### Salable Quantity (complex cross-table calculation)

```xml
<config>
    <table name="inventory_source_item" group="Products" label="Inventory Source Items">
        <pk name="source_item_id"/>
        <column name="sku" label="SKU"/>
        <column name="quantity" label="Source Qty" type="number"/>
    </table>

    <table name="inventory_reservation" group="Products" label="Inventory Reservations">
        <pk name="reservation_id"/>
        <column name="sku" label="SKU"/>
        <column name="quantity" label="Reserved Qty" type="number"/>
    </table>

    <relation name="catalog_product_entity-inventory_source_item" type="1n">
        <leftTable>catalog_product_entity</leftTable>
        <rightTable>inventory_source_item</rightTable>
        <condition>%1.sku = %2.sku</condition>
    </relation>

    <relation name="catalog_product_entity-inventory_reservation" type="1n">
        <leftTable>catalog_product_entity</leftTable>
        <rightTable>inventory_reservation</rightTable>
        <condition>%1.sku = %2.sku AND %2.stock_id = 1</condition>
    </relation>

    <table name="catalog_product_entity">
        <column name="salable_qty_calculated"
                label="Salable Qty"
                fields="inventory_source_item.quantity,inventory_reservation.quantity"
                type="number"
                expr="IF(IF(%2 &lt; 0,%1+SUM(%2), %1) &lt; 0, 0, IF(%2 &lt; 0,%1+SUM(%2), %1))"
                tables="inventory_source_item,inventory_reservation"/>
    </table>
</config>
```

### Conditional Column (active special prices)

```xml
<config>
    <table name="catalog_product_entity">
        <column name="active_special_price"
                label="Active Special Price"
                fields="special_price,special_from_date,special_to_date"
                type="money"
                expr="IF(DATE(IFNULL(%2, 0)) &lt; DATE(NOW()) AND DATE(IFNULL(%3, NOW())) &gt;= DATE(NOW()), IFNULL(%1, 0), 0)"/>
    </table>
</config>
```

### EAV Table Registration

```xml
<config>
    <eavTable name="customer_entity" label="Customers" group="Customers" type="customer">
        <pk name="entity_id" label="Customer ID"/>
        <fk name="default_billing" table="customer_address_entity"/>
        <column name="group_id"
                label="Group"
                type="select"
                options="Mirasvit\Report\Config\Source\Customer\Group"/>
    </eavTable>
</config>
```
