# Saving and loading reports

> Save and load Pivot Studio reports as plain JSON, store them per user, and understand every key of the report format.

Everything a user builds, from the fields in each zone to filters, sorting, number formats, conditional formats, layout options and which members are expanded, is described by a report: a plain JSON object. Store it wherever you keep user settings and load it again later.

## Saving and loading

```ts title="saved-reports.ts"
import { createPivotStudio, type PivotReport } from '@birchui/pivot-studio';

async function loadSavedReport(userId: string): Promise<PivotReport | undefined> {
  const response = await fetch(`/api/users/${userId}/pivots/store-sales`);
  return response.ok ? response.json() : undefined;
}

const studio = createPivotStudio<Sale>(document.querySelector<HTMLElement>('#sales-report')!, {
  data: sales,
  report: await loadSavedReport(currentUser.id),
  fileName: 'store-sales',
});

let saveTimer = 0;
studio.on('reportChange', ({ report }) => {
  window.clearTimeout(saveTimer);
  saveTimer = window.setTimeout(() => {
    void fetch(`/api/users/${currentUser.id}/pivots/store-sales`, {
      method: 'PUT',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify(report),
    });
  }, 500);
});
```

- `getReport()` returns the current report.
- `setReport(report)` replaces it and recomputes the table.
- `reportChange` fires after every change, whether it came from the user, from an API call such as `addField()`, or from `setReport()`.

Debounce saving as above: dragging a chip across the field list can produce several changes in a second.

### Save and open from the toolbar

The toolbar's **Save report** button downloads the current report as `<fileName>.json`, formatted for reading, and **Open report** loads one from a JSON file. If the file is not valid JSON or does not contain an object, the report stays as it was and the `error` event fires with "The report file could not be read".

### Several reports for one dataset

Keep a list of named reports and switch between them with `setReport()`; the data stays loaded:

```ts
const savedViews: Record<string, PivotReport> = {
  'Revenue by store': revenueByStore,
  'Margin by category': marginByCategory,
  'Units by month': unitsByMonth,
};

viewPicker.addEventListener('change', () => studio.setReport(savedViews[viewPicker.value]));
```

## The report format

**`PivotReport`** (interface from `@birchui/pivot-studio`, full reference: https://docs.birchui.com/api/pivot-studio.md)

```ts
interface PivotReport
```

| Property | Type | Description |
| --- | --- | --- |
| `version?` | `1` |  |
| `dataSource?` | `PivotDataSourceRef` |  |
| `slice` | `PivotSlice` |  |
| `filters?` | `Record<string, FieldFilter>` |  |
| `formats?` | `Record<string, PivotNumberFormat>` |  |
| `conditionalFormats?` | `ConditionalFormatRule[]` |  |
| `options?` | `PivotReportOptions` |  |
| `expansion?` | `{ rows?: ExpansionSpec; columns?: ExpansionSpec }` |  |

| Key | Contents |
| --- | --- |
| `version` | `1` |
| `slice` | The fields in each zone. `rows`, `columns` and `filters` hold `{ field, sort?, sortBy? }`; `values` holds `{ field, aggregation?, showAs?, along?, caption?, format?, id? }`. |
| `filters` | Filters by field name: `include`, `exclude`, `label`, `value`, `top`. See [Filtering & sorting](https://docs.birchui.com/pivot-studio/filtering-and-sorting.md). |
| `formats` | Number formats by field name. See [Number formats](https://docs.birchui.com/pivot-studio/totals-and-formatting.md#number-formats). |
| `conditionalFormats` | Color scale, data bar and threshold rules. See [Conditional formatting](https://docs.birchui.com/pivot-studio/totals-and-formatting.md#conditional-formatting). |
| `options` | Layout and totals: `layout`, `grandTotalRow`, `grandTotalColumn`, `rowSubtotals`, `columnSubtotals`, `grandTotalPosition`, `subtotalPosition`, `stackedHeaders`, `repeatRowLabels`, `emptyCellText` |
| `expansion` | Which members are expanded: `{ rows, columns }`, each `{ all, except }` |
| `dataSource` | A reference to the data: `type`, `ref`, `delimiter` and field definitions |

A complete example:

```json title="store-sales.json"
{
  "version": 1,
  "dataSource": { "type": "array", "ref": "sales-2026" },
  "slice": {
    "rows": [{ "field": "region", "sortBy": { "measure": "sum(revenue)", "dir": "desc" } }, { "field": "store" }],
    "columns": [{ "field": "orderDate.quarter" }],
    "values": [
      { "field": "revenue", "format": { "style": "currency", "currency": "GBP", "decimals": 0 } },
      { "field": "margin", "showAs": "percentOfColumnTotal", "caption": "Margin share" }
    ],
    "filters": [{ "field": "channel" }]
  },
  "filters": { "channel": { "exclude": ["Marketplace"] } },
  "conditionalFormats": [{ "type": "dataBar", "measure": "sum(revenue)" }],
  "options": { "layout": "compact", "subtotalPosition": "top", "grandTotalPosition": "bottom" },
  "expansion": { "rows": { "all": true, "except": [["South"]] } }
}
```

### Measures and members

- **Measures** are referred to by ID, such as `sum(revenue)` or `sum(revenue):percentOfGrandTotal`, or by the `id` you set on a value field. See [Measure IDs](https://docs.birchui.com/pivot-studio/calculations.md#measure-ids).
- **Members** are referred to by key: the raw value as text, an empty string for blanks, and numbers for date parts (`"1"` to `"4"` for quarters, `"1"` to `"12"` for months).
- **Expansion** paths are lists of member keys from the top level down. `{ "all": true, "except": [["South"]] }` means "everything expanded except the South region"; `{ "all": false, "except": [["North"], ["North", "Leeds Trinity"]] }` means "everything collapsed except North and its Leeds Trinity store".

### Options and defaults

Options you leave out take their defaults, which are also exported as `DEFAULT_REPORT_OPTIONS`:

| Option | Default |
| --- | --- |
| `layout` | `'compact'` |
| `grandTotalRow`, `grandTotalColumn` | `true` |
| `rowSubtotals`, `columnSubtotals` | `true` |
| `grandTotalPosition` | `'bottom'` |
| `subtotalPosition` | `'top'` |
| `stackedHeaders` | `true` |
| `repeatRowLabels` | `false` |
| `emptyCellText` | `''` |

## The data source reference

Pivot Studio never fetches data. `dataSource.ref` is a string for your own code, such as a dataset ID or a URL, so you can find the right data before loading a saved report:

```ts
const saved = await loadSavedReport(currentUser.id);
const datasetId = saved?.dataSource?.ref ?? 'sales-2026';
studio.setData(await fetchDataset(datasetId));
if (saved) studio.setReport(saved);
```

## Robust loading

Reports are validated when they are loaded, so a report saved by an older version of your app or edited by hand cannot break the widget:

- Unknown keys and values of the wrong type are dropped.
- Fields that no longer exist in the data are ignored, with a console warning naming the field.
- Filters and sorts that refer to unknown measures are ignored, with a warning.
- A value that is not an object loads an empty report.

`normalizeReport(input, warn?)` is exported and applies the same validation, so you can clean reports on a server before storing them:

```ts
import { normalizeReport } from '@birchui/pivot-studio';

const clean = normalizeReport(JSON.parse(requestBody), (message) => logger.warn(message));
```

> **Tip**
>
> Saved reports refer to field names and member keys. When you rename a column in your data, migrate stored reports (for example by rewriting `"field": "shop"` to `"field": "store"`) or keep the old field name as an alias column in the data.
