# useReport

Groupings, filters, chart formatting, tabular formatting of a Quill Report exposed as a simple form interface.

Use cases with `useReport`: [Dashboard](https://quill.co/docs/use-cases/dashboard.md),
[Chat](https://quill.co/docs/use-cases/chat.md), [Reporting](https://quill.co/docs/use-cases/reporting.md),
[Insight](https://quill.co/docs/use-cases/insight.md),
[Drilldowns](https://quill.co/docs/use-cases/drilldowns.md) and [Alerts](https://quill.co/docs/use-cases/alerts.md).

```tsx
import { Chart, useReport, type ChartType } from "@quillsql/react";

function ReportPage({ reportId }: { reportId: string }) {
  const { name, chart, chartLoading, chartType, chartTypeOptions, setReport } = useReport(reportId);
  return (
    <>
      <h1>{name}</h1>
      <select value={chartType} onChange={(e) => setReport({ chartType: e.target.value as ChartType })}>
        {chartTypeOptions.map((option) => (
          <option key={option.value} value={option.value}>
            {option.label}
          </option>
        ))}
      </select>
      <Chart chart={chart} chartLoading={chartLoading} />
    </>
  );
}
```

## Chart

You can use any charting library. See all examples [here](https://quill.co/docs/react/custom-charts.md).

### Quill

```tsx
const { chart, chartLoading } = useReport(reportId);

<Chart chart={chart} chartLoading={chartLoading} />;
```

### shadcn

```tsx
import { Bar, BarChart, XAxis } from "recharts";
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart";

const { chart } = useReport(reportId);
const ys = chart?.yAxisFields ?? [];
const config = Object.fromEntries(ys.map((y, i) => [y.field, { label: y.label, color: `var(--chart-${i + 1})` }]));
const rows = (chart?.rows ?? []).map((row) => ({ ...row, ...Object.fromEntries(ys.map((y) => [y.field, Number(row[y.field])])) }));

<ChartContainer config={config}>
  <BarChart data={rows}>
    <XAxis dataKey={chart?.xAxisField} tickLine={false} axisLine={false} />
    <ChartTooltip content={<ChartTooltipContent />} />
    {ys.map((y) => (
      <Bar key={y.field} dataKey={y.field} fill={`var(--color-${y.field})`} radius={4} />
    ))}
  </BarChart>
</ChartContainer>;
```

## Table

```tsx
const { table, tableLoading } = useReport(reportId);

<table>
  <thead>
    <tr>
      {table.columns.map((column) => (
        <th key={column.field}>{column.label}</th>
      ))}
    </tr>
  </thead>
  <tbody>
    {table.rows.map((row, i) => (
      <tr key={i}>
        {table.columns.map((column) => (
          <td key={column.field}>{table.getFormattedCellValue(row, column.field)}</td>
        ))}
      </tr>
    ))}
  </tbody>
</table>;
```

## Pagination

```tsx
const { table } = useReport(reportId, {
  initialPagination: { pageIndex: 0, pageSize: 10 },
});

<button onClick={() => table.firstPage()} disabled={!table.getCanPreviousPage()}>{"<<"}</button>
<button onClick={() => table.previousPage()} disabled={!table.getCanPreviousPage()}>{"<"}</button>
<span>
  Page {table.pagination.pageIndex + 1} of {table.getPageCount()}, {table.getRowCount()} rows
</span>
<button onClick={() => table.nextPage()} disabled={!table.getCanNextPage()}>{">"}</button>
<button onClick={() => table.lastPage()} disabled={!table.getCanLastPage()}>{">>"}</button>
<select
  value={table.pagination.pageSize}
  onChange={(e) => table.setPageSize(Number(e.target.value))}
>
  {[10, 25, 50].map((size) => (
    <option key={size} value={size}>
      {size}
    </option>
  ))}
</select>
```

## Form UI

```tsx
import { Chart, useReport, useReportQueryBuilder, type ChartType } from "@quillsql/react";
import { QueryBuilder } from "react-querybuilder";

function ReportForm({ reportId }: { reportId: string }) {
  const report = useReport(reportId);
  const { setReport } = report;
  const queryBuilder = useReportQueryBuilder({
    reportId,
    filters: report.filters,
    queryBuilderProps: report.filterQueryBuilderProps,
    onApply: report.setFilters,
  });
  return (
    <div>
      <label>
        Group rows by
        <select value={report.groupRowsBy} onChange={(e) => setReport({ groupRowsBy: e.target.value })}>
          <option value="">None</option>
          {report.groupRowsByOptions.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
        </select>
      </label>
      <label>
        Aggregations
        <select
          multiple
          value={report.aggregations}
          onChange={(e) => setReport({ aggregations: Array.from(e.target.selectedOptions, (o) => o.value) })}
        >
          {report.aggregationOptions.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
        </select>
      </label>
      <label>
        Chart type
        <select value={report.chartType} onChange={(e) => setReport({ chartType: e.target.value as ChartType })}>
          {report.chartTypeOptions.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
        </select>
      </label>
      <QueryBuilder key={queryBuilder.key} {...queryBuilder.props} />
      <button onClick={queryBuilder.apply} disabled={!queryBuilder.hasUnappliedChanges}>
        Apply filters
      </button>
      <Chart chart={report.chart} chartLoading={report.chartLoading} />
    </div>
  );
}
```

## The query

```tsx
setReport({
  groupRowsBy: "orders::created_at",
  dateBucket: "month",
  aggregations: ["sum:orders::total"],
  chartType: "line",
});
```

| Value            | Options                              |                                                                                                       |
| ---------------- | ------------------------------------ | ----------------------------------------------------------------------------------------------------- |
| `datasources`    | `datasourceOptions`                  | the tables the report queries, by name                                                                |
| `columns`        | `columnOptions`                      | the columns of the table, in order, each `{ value, label, format }`                                   |
| `groupRowsBy`    | `groupRowsByOptions`                 | the column whose values become rows, `"table::field"`; `""` for none                                  |
| `groupColumnsBy` | `groupColumnsByOptions`              | the column whose values become columns, under `groupRowsBy`                                           |
| `dateBucket`     | `dateBucketOptions`                  | `"day"`, `"week"`, `"month"` or `"year"` for a date `groupRowsBy`; `""` picks one from the date range |
| `aggregations`   | `aggregationOptions`                 | what each row computes: `"sum:orders::total"`, `"count:orders"`; `""` is one not chosen yet           |
| `sort`           | `sortOptions`                        | the order of the rows, as `"total descending"`                                                        |
| `limit`          |                                      | `{ value: number }`, the most rows, or `null`                                                         |
| `chartType`      | `chartTypeOptions`                   | `"column"`, `"line"`, `"bar"`, `"pie"`, `"table"`, `"metric"` and others                              |
| `chartSort`      | `chartSortOptions`                   | an order of the chart alone, after the query                                                          |
| `xAxis`          | `xAxisOptions`, `xAxisFormatOptions` | `{ field, label, format }`                                                                            |
| `yAxis`          | `yAxisOptions`, `yAxisFormatOptions` | `{ fields: { field, label, format }[] }`                                                              |
| `showLegend`     |                                      | whether the chart shows its legend                                                                    |

## Filters

```tsx
setFilters({
  combinator: "and",
  rules: [
    { field: "orders.status", operator: "in", value: ["paid", "shipped"] },
    { field: "orders.total", operator: ">", value: 100 },
  ],
});
```

## Saving

```tsx
await saveChanges({ section: "Revenue" });
```

## Reference

```ts
useReport(reportId?: string, options?: UseReportOptions)
```

| Option                      | Default                          |                                                                                                                                                                                              |
| --------------------------- | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `initialPagination`         | `{ pageIndex: 0, pageSize: 10 }` | the pagination to start from                                                                                                                                                                 |
| `rowsPerRequest`            | 10                               | the rows each request fetches; never fewer than a page                                                                                                                                       |
| `destinationDashboardName`  |                                  | the dashboard of a report created without an id                                                                                                                                              |
| `dateBucketMode`            | `"dynamic"`                      | `"standard"` leaves `""` out of `dateBucketOptions`, and `dateBucket` is the one in use                                                                                                      |
| `reportOverride`            |                                  | a report to show instead of loading one                                                                                                                                                      |
| `showTableNames`            | `true`                           | puts the table's name in the labels useReport builds: filter fields, group-by, aggregation and sort options, axis series and pivot table columns ("Account Days Plan", "Count Account Days") |
| `initialReportBuilderState` |                                  | a query to start from instead of the report's                                                                                                                                                |

| Returns                                                                                                                                                            |                                                                                                                                                                                                                                                                   |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`, `reportId`                                                                                                                                                 | the report's name and id                                                                                                                                                                                                                                          |
| `chart`, `chartLoading`                                                                                                                                            | the report to draw with `Chart`, and whether it loads                                                                                                                                                                                                             |
| `table`, `tableLoading`                                                                                                                                            | the rows, columns and pagination of the table, and whether it loads                                                                                                                                                                                               |
| `loading`                                                                                                                                                          | whether the chart or the table loads                                                                                                                                                                                                                              |
| `error`                                                                                                                                                            | `string \| undefined`: why the report could not load                                                                                                                                                                                                              |
| `datasources`, `columns`, `groupRowsBy`, `groupColumnsBy`, `dateBucket`, `aggregations`, `sort`, `limit`, `chartType`, `chartSort`, `xAxis`, `yAxis`, `showLegend` | the parts of the query, and their options, see [the query](#the-query)                                                                                                                                                                                            |
| `setReport`                                                                                                                                                        | `(input: SetReportBuilderInput) => void`: changes any of them                                                                                                                                                                                                     |
| `columnActions`                                                                                                                                                    | changes one column of the table                                                                                                                                                                                                                                   |
| `filters`, `setFilters`                                                                                                                                            | the filters as a group of rules, and a function that replaces them                                                                                                                                                                                                |
| `filterQueryBuilderProps`, `filterOptions`                                                                                                                         | the fields, operators and values of filters, for react-querybuilder or your own builder                                                                                                                                                                           |
| `saveChanges`                                                                                                                                                      | `(overrides?: { name?, section? }) => Promise<unknown>`: saves the report                                                                                                                                                                                         |
| `reload`                                                                                                                                                           | `(refreshServerCache = false) => void`: loads the report again, dropping changes not saved and skipping the browser's copies of it; with `refreshServerCache`, your server SDK also runs each query again and rewrites its Redis or DuckDB cache with the results |
| `reportBuilderState`                                                                                                                                               | the query as one object, for `Chat`'s `reportBuilderState`                                                                                                                                                                                                        |
