# Report Builder

Create and update custom reports via the REST API. Use an existing report as a template for field format and structure.

For listing and executing reports, see the **Reports Overview** doc in `Mirasvit_Reports`.

## Creating a New Report

Use `POST /V1/report-builder/report` to create a custom report. The easiest approach is to use an existing report as a template.

### Workflow

1. Get the configuration of a report to use as template:

```json
{
  "endpoint": "/V1/reports/report/order_overview",
  "method": "GET"
}
```

2. Create the new report — copy the desired fields from the template but **omit** read-only fields (`identifier`, `id`, `user_id`, `is_edit_disabled`, `share_identifier`, `report_identifier`):

```json
{
  "endpoint": "/V1/report-builder/report",
  "method": "POST",
  "body": {
    "report": {
      "name": "My Custom Sales Report",
      "table": "sales_order",
      "columns": ["sales_order|entity_id__cnt", "sales_order|grand_total__sum"],
      "dimensions": ["sales_order|created_at__day"],
      "internal_columns": [],
      "internal_filters": [],
      "primary_dimensions": ["sales_order|created_at__day", "sales_order|created_at__week", "sales_order|created_at__month"],
      "filters": [],
      "primary_filters": ["sales_order|created_at", "sales_order|store_id", "sales_order|status"],
      "sort_orders": [],
      "is_sharing_enabled": false,
      "is_customized": false,
      "time_range": "month",
      "page_size": 20
    }
  }
}
```

3. The response returns the created report with its assigned numeric identifier

### Pitfalls

- **Never** include these read-only fields when creating or updating a report — they are auto-generated and have no setter: `identifier`, `id`, `user_id`, `is_edit_disabled`, `share_identifier`. Including any of them causes `"X is not supported"` error
- `is_sharing_enabled` is applied only when the caller is allowed `Mirasvit_ReportBuilder::share`; otherwise the stored value is kept.
- **Never** include `report_identifier` when creating a new report. If set to an existing predefined report identifier (e.g., `catalog_product`), the custom report merges with the predefined one instead of being created separately
- The schema endpoint shows these read-only fields because they have getters (used in responses), but the input processor rejects them because there are no corresponding setters
- Always use an existing report as a reference/template for the column and filter format to avoid configuration errors
- Use the schema discovery endpoint (`GET /V1/report-builder/schema`) to find available tables and columns when building a report from scratch. Use `fields=items[name,label,group],total_count` to list tables only, or filter by table name to get columns for a specific table

## Report Structure: Dimensions vs Columns

A report has two distinct field lists that serve different purposes:

### `dimensions` — Row Grouping (GROUP BY)

Dimensions define **how rows are grouped**. Each unique combination of dimension values produces one row in the output.

- Use dimensions for the field(s) that identify each row (e.g., SKU, date, customer email)
- **Do NOT put display-only fields in dimensions** — it changes the grouping and creates extra rows
- A product report grouped by `catalog_product_entity|sku` produces one row per product

### `columns` — Displayed Values

Columns define **what data is shown** in each row. These are either:
- **Aggregated metrics** with suffixes: `__sum`, `__avg`, `__cnt` (e.g., `sales_order_item|qty_ordered__sum`)
- **Concatenated text** with `__concat` suffix: joins multiple values into one cell (e.g., `catalog_category_entity|name__concat` → "Gear, Bags, Sale")
- **Dimension-level attributes** without suffix: displayed as-is for the grouped row (e.g., `catalog_product_entity|name`)

### Key Rule: `__concat` for Multi-Value Attributes

When a product (or any entity) has multiple related values (e.g., multiple categories), use the `__concat` variant in **columns** to display them as a comma-separated list in a single cell.

**Wrong:** `catalog_category_entity|name` in `dimensions` → creates one row per product-category pair, splitting metrics across rows.

**Correct:** `catalog_category_entity|name__concat` in `columns` → shows "Category1, Category2" in one cell, one row per product.

### `primary_dimensions` — Dimension Switcher

The `primary_dimensions` array defines which dimensions appear in the UI dimension switcher (e.g., toggle between daily/weekly/monthly view). Keep the same values as the template report unless you have a reason to change them.

### Example: Product Report with Categories

Based on the predefined `catalog_product` report (table: `catalog_product_entity`, dimension: `catalog_product_entity|sku`):

```json
{
  "name": "Product Performance (with Categories)",
  "table": "catalog_product_entity",
  "dimensions": ["catalog_product_entity|sku"],
  "columns": [
    "catalog_product_entity|name",
    "catalog_category_entity|name__concat",
    "sales_order|entity_id__cnt",
    "sales_order_item|qty_ordered__sum",
    "sales_order_item|row_total__sum"
  ]
}
```

This produces one row per SKU with a "Categories" column showing all assigned category names.



The schema endpoint (`GET /V1/report-builder/schema`) returns all registered tables and their columns. Use it to understand what data is available **before** creating reports or configs.

### Column Identifier Format

Columns follow the pattern `table|column` with optional suffixes:
- **Aggregation suffixes:** `__sum`, `__avg`, `__cnt`, `__concat` — pre-defined aggregated variants
- **Date granularity suffixes:** `__hour`, `__day`, `__day_of_week`, `__week`, `__month`, `__quarter`, `__year`

### Column Types and What They Mean

| Type | Meaning |
|------|---------|
| `pk` | Primary key. Identifies rows in this table. `__cnt` variant counts rows. |
| `fk` | **Foreign key — the table is already linked to another table.** The report builder automatically joins through this column. No config relation needed. |
| `str` | String value (text, EAV attributes) |
| `select` | Dropdown/option value (EAV select attributes, enum columns) |
| `money` | Currency amount |
| `number` | Numeric value |
| `date` | Date/datetime value |
| `image` | Image path |

### Key Rule: `fk` Columns = Existing Relations

When the schema shows a column with `type: "fk"`, it means the report builder **already knows how to join** that table to the referenced table. You can use columns from the related table directly in reports — no config or relation definition is needed.

**Example:** `catalog_category_product` has `fk` columns `category_id` and `product_id`. This means a report based on `catalog_product_entity` can use `catalog_category_entity|name` directly — the report builder resolves the join path through `catalog_category_product` automatically.

### When You DO Need a Config

Only create a config (see `Mirasvit_ReportBuilder/config-builder`) when:
1. **Synthetic/calculated column** — you need a column computed from an SQL expression (e.g., gross profit = revenue - cost)
2. **Missing relation** — two tables have no `fk` connection in the schema and you need to join them
3. **New table** — a DB table is not registered in the schema at all

**Always check the schema first.** If the column or relation already exists, use it directly.

## Duplicating a Report

Use `POST /V1/report-builder/report/:identifier/duplicate` to create a copy of an existing report. Works with both predefined identifiers (e.g., `catalog_product`) and custom numeric IDs (e.g., `9`).

### Workflow

1. Duplicate with default name ("{original name} (Copy)"):

```json
{
  "endpoint": "/V1/report-builder/report/catalog_product/duplicate",
  "method": "POST",
  "body": {}
}
```

2. Duplicate with a custom name:

```json
{
  "endpoint": "/V1/report-builder/report/catalog_product/duplicate",
  "method": "POST",
  "body": {
    "name": "My Product Report Copy"
  }
}
```

3. The response returns the new report with its assigned numeric identifier. All configuration fields (columns, dimensions, filters, sort orders, etc.) are copied from the source report.

## Updating a Report

Use `PUT /V1/report-builder/report/:reportId` to update an existing report. The `:reportId` can be a numeric ID (e.g., `9`) or a predefined report identifier (e.g., `catalog_product`).

### Workflow

1. Get the current report configuration:

```json
{
  "endpoint": "/V1/reports/report/9",
  "method": "GET"
}
```

2. Update with modified fields:

```json
{
  "endpoint": "/V1/report-builder/report/9",
  "method": "PUT",
  "body": {
    "report": {
      "name": "Updated Report Name",
      "columns": ["sales_order|entity_id__cnt", "sales_order|grand_total__sum", "sales_order|tax_amount__sum"],
      "dimensions": ["sales_order|created_at__week"],
      "page_size": 50
    }
  }
}
```

### Pitfalls

- Updates always use `PUT` with the report ID in the URL — do not use `POST` for updates
- Both custom reports (numeric ID) and predefined reports (string identifier like `catalog_product`) can be updated
