# Spoonity Insights API

Insights is Spoonity's analytics layer: a curated set of BI **dashboards** (fixed tiles a
merchant's team looks at every day) plus an ad-hoc **Explore** query engine (`GET /views`,
`POST /query`, `POST /drill`) over BigQuery-backed "views" of a vendor's loyalty-program data:
sales, customers, points, fraud, messaging, feedback. Every read is scoped to exactly one vendor
and gated by that vendor's entitlements.

This page documents the Insights API's own endpoint surface, the service Prism's dashboard talks
to, not Prism itself. For Prism's own BFF routes (saved tiles, saved dashboards, goals, the digest
opt-in, the audit log), see [`prism.md`](./prism.md).

## Read this before anything else: there is no vendor API key for Insights

Every other Spoonity service in this reference (CMS, Links, Wallet) is a self-serve integration
surface: a vendor holds an API key and calls it directly. **Insights is not that.** The service is
a private Cloud Run deployment with no API-key path at all. Cloud Run IAM (`roles/run.invoker`)
rejects any caller without a Google-signed ID token before the service runs, and the service then
recognizes two kinds of caller:

- A caller whose verified email is on the deployment's allow-list (the `spoonity.com` domain plus
  a short list of named exceptions) is accepted, but reads **only the one vendor the deployment is
  pinned to**, the Breakfast Bonanza demo brand. Any other verified identity gets a `403`.
- A **broker** is an allow-listed service account that may also send `X-Spoonity-Vendor: <id>` to
  read that vendor instead. Three brokers are configured today: Prism's BFF
  (`prism.spoonity.com`), the standalone Insights app's BFF (`insights.spoonity.com`), and the
  Spoonity MCP server (`mcp.spoonity.com`, its `insights_*` tools). The deployment lets a broker
  name any vendor id; the entitlement files described below decide what that vendor can see. A
  non-broker that sends the header gets a `403`, not a silent fallback.

Each broker authenticates the person itself and forwards only a vendor that person is signed in
to. Concretely, **the ways anyone reaches this API today** are a signed-in session on one of
those three front doors: the Prism dashboard, the Insights app (open to merchants since
2026-09-23), or an MCP client signed in with a Spoonity account. This page's examples use Prism:
its browser client never holds an Insights credential of any kind. It calls same-origin
`/api/insights/*` on Prism's own backend, which mints the ID token and attaches
`X-Spoonity-Vendor` from the signed-in session.

The endpoint catalog below is real reference material: it is exactly what Prism's Explore page and
dashboards call, with the request and response shapes the service returns. It is **not**
something a vendor integrator can wire up with an API key the way they can CMS or Links. Read it
to understand what the product does, or if you are writing code that runs as a trusted Spoonity
backend service and can be made a broker. If you are an outside integrator looking for a way to
pull a merchant's analytics programmatically, this is not it today. There is no OpenAPI file for
this service.

## Where the query and view logic actually lives

Neither BFF that fronts this API (Prism's own, or the `insights-app` deployment behind
`insights.spoonity.com`) carries **any SQL, view definitions, or query-compiler logic of its own**:
every route in the catalog below forwards to the Insights API and relays its response unchanged.
If a dashboard's number looks wrong, or a view is missing a field it should have, the fix does not
belong in either BFF codebase:

- **`Spoonity/insights-api`** is the service live behind every front door. It is a Python
  service with a spec-to-SQL compiler (`builder.py`), one `model/*.json` file per view (48 today)
  and one `dashboards/*.json` file per dashboard (41 today, 21 of them a merchant-specific suite
  visible to one vendor only). Its `entitlements.json` and `view_entitlements.json` are the
  access gates.
- **`Spoonity/microservice-reporting`**, PR #14 (closed without merging on 2026-08-19), is a PHP
  implementation of the same compiler that covered the original 19 views. The Python service's
  model has grown well past it, so treat it as history, not as the path to production.

## The trap: every endpoint here that answers to `POST` is a read

`GET` only carries a URL, and several of these queries (an ad-hoc field list, a set of filters, a
chart datum to drill into) do not fit in one. **`POST` in this API means "this request has a JSON
body," never "this request changes anything."** Nothing under this API ever mutates a vendor's
loyalty data:

| Endpoint | Verb | What it actually does |
|---|---|---|
| `POST /query` | read | runs an ad-hoc query and returns rows |
| `POST /query/export` | read | same query, returned as a CSV file |
| `POST /drill` | read | expands one chart datum into its detail rows |
| `POST /dashboards/:id/data` | read | runs every tile on a dashboard |
| `POST /dashboards/:id/tiles/:key` | read | runs one dashboard tile |
| `POST /dashboards/:id/tiles/:key/export` | read | same tile, returned as a CSV file |

Nothing in this table is unsafe to retry, nothing needs a confirmation dialog, and nothing should
ever be treated as a mutation by a script or an agent working against this API. The two `/export`
routes are the only ones Prism's own audit log records (as `query.export` and `tile.export`), not
because they write anything, but because a CSV is a real extract of vendor data, which is worth a
trail. See [`prism.md`'s audit event section](./prism.md#the-audit-event-shape) for that record's
shape.

**One genuine write exists, but it isn't in this API.** The `insights-app` BFF behind
`insights.spoonity.com` also mounts `POST /api/segments`: it re-runs an Insights query and turns
the result into a real, static Spoonity customer segment. It's authenticated as the signed-in
operator's own Spoonity identity (not the broker credential this page describes), and it lives on
that BFF, next to its own saved tiles and dashboards routes, not on the Insights API cataloged
below. **Prism's own BFF does not mount this route today.**

## Vendor scoping and entitlements

Every view's SQL binds the vendor server side (`@vendor` in the view's base query), from the
caller's resolved vendor (see above), never from anything in the request body. A vendor sees its
own numbers or an empty result set, never another merchant's; no field or parameter anywhere in
this API can name a different vendor's data (a `params` entry called `vendor` is dropped).

Two independent entitlement gates sit in front of that binding. Both use a `"*"` baseline row that
every vendor inherits when it has no row of its own, and a vendor's own row **replaces** the
baseline rather than adding to it.

**Dashboards** (`entitlements.json`): a per-vendor list of dashboard keys, or the literal string
`"all"`. The shipped baseline is `"all"`, so every vendor sees every shared dashboard without a
config change. Granting a vendor a different set means listing every key that vendor should see.
A dashboard can also declare its own vendor allowlist (used for merchant-specific dashboard
suites); when present, the dashboard is invisible to every vendor outside that list, a `404`
indistinguishable from an unallocated id, regardless of the baseline. A dashboard marked unlisted
is left out of `GET /dashboards` but still served by id to anyone entitled to it (it is reached
through a drill-through link on its parent).

**Explore** (`view_entitlements.json`): a per-vendor row of
`{"explore": bool, "explore_pii": bool, "views": [...]}`. The shipped baseline is
`{"explore": true}`. `explore` gates the whole ad-hoc surface (`GET /views`, `GET /views/:name`,
`GET /views/:name/param-options`, `POST /query[/export]`, `POST /drill`); without it every one of
those routes answers `403`. `explore_pii` lifts PII redaction and is **absent from the shipped
baseline on purpose**: PII fields (an email address, a phone number) are excluded from every field
list, every query, every drill and every options response, for every vendor, until a vendor's own
row grants it. `views` widens which views a vendor may explore beyond the ones its entitled
dashboards are built on. `POST /drill` is slightly wider still: it may also target any view that a
tile on one of the vendor's entitled dashboards reads.

A field, filter key, drill `row` key, or query `params` entry that names a PII field answers
`403 {"error": "Not entitled to PII fields", "pii_fields": [...]}` for a vendor without
`explore_pii`. Filtering on a hidden field is treated the same as selecting it, since either one
lets a caller infer something about it.

Cost guards apply to every query: each BigQuery job has a per-query byte cap (a `413` when a
query's dry-run estimate exceeds it), and ad-hoc queries, drills and options lookups also count
against a per-vendor daily scan budget (a `429` once spent, reset at UTC midnight). The daily
counter lives in process memory, so treat it as a guard rail, not an accounting figure.

## Errors common to every endpoint

| Status | Body | Meaning |
|---|---|---|
| `401` | `{"error": "unauthorized", "detail": "Not signed in"}` | through Prism: no valid Prism session |
| `403` | `{"error": "Access is restricted to internal Spoonity accounts", "allowed_domains": [...]}` | direct call with an identity that is not on the allow-list |
| `403` | `{"error": "This caller cannot choose a vendor", "vendor": ...}` | direct call by a non-broker that sent `X-Spoonity-Vendor` |
| `400` | `{"error": "X-Spoonity-Vendor must be a numeric vendor id"}` | a broker sent a non-numeric vendor |
| `404` | `{"error": "not found"}` | no such route |

## Endpoint catalog

All paths below are shown as they appear through Prism's proxy: `/api/insights/<path>` on
`prism.spoonity.com`, same origin, session cookie attached automatically by the browser. The
Insights service itself serves the same paths under an `/insights` prefix on its private Cloud
Run URL, reachable only with a Google-signed ID token as described above.

---

### GET /views

The views this vendor may run an ad-hoc Explore query against: the entry point for building a
`POST /query`.

**Auth:** Prism session cookie (browser) or a broker's ID token (service to service). `403` when
the vendor is not Explore-entitled.

**Params:** none.

**Request example:**

```bash
curl -sS 'https://prism.spoonity.com/api/insights/views' \
  -H 'Cookie: prism_session=<session-cookie>'
```

**Response example** (`200`, sorted by `name`, trimmed to one entry):

```json
[
  {
    "name": "sales",
    "label": "Sales",
    "description": "Transaction-level sales with customer, store, staff and payment detail, current period against previous.",
    "category": "Sales & revenue",
    "field_count": 38,
    "groups": [
      { "name": "Comparison", "count": 19 },
      { "name": "Orders", "count": 5 },
      { "name": "Time", "count": 5 },
      { "name": "Customer", "count": 3 },
      { "name": "Location", "count": 3 }
    ],
    "params": ["trxtype"],
    "param_labels": { "trxtype": "Transaction type" },
    "param_kinds": { "trxtype": "enum" }
  }
]
```

`field_count` and `groups` (the five largest field groups) count only fields this vendor can see;
PII fields are left out without `explore_pii`. `params` omits the four period params, which are
set through `period` and `previous_period` instead.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `403` | `{"error": "Vendor is not entitled to the explore surface"}` | this vendor's Explore row (or the baseline) does not grant `explore` |

---

### GET /views/:name

Full field-level description of one view: every selectable dimension and measure, its declared
joins ("relationships"), and its drill-down defaults.

**Auth:** same as `GET /views`.

**Path params:**

| Name | Type | Notes |
|---|---|---|
| `name` | string | the view's `name`, from `GET /views` |

**Request example:**

```bash
curl -sS 'https://prism.spoonity.com/api/insights/views/sales' \
  -H 'Cookie: prism_session=<session-cookie>'
```

**Response example** (`200`, trimmed):

```json
{
  "name": "sales",
  "label": "Sales",
  "description": "Transaction-level sales with customer, store, staff and payment detail, current period against previous.",
  "category": "Sales & revenue",
  "field_count": 38,
  "groups": [{ "name": "Comparison", "count": 19 }],
  "params": ["trxtype"],
  "param_labels": { "trxtype": "Transaction type" },
  "param_kinds": { "trxtype": "enum" },
  "fields": [
    {
      "name": "location",
      "label": "Location",
      "group": "Location",
      "kind": "dimension",
      "format": "string",
      "datatype": "string"
    },
    {
      "name": "revenue",
      "label": "Revenue",
      "group": "Revenue",
      "kind": "measure",
      "format": "currency",
      "datatype": "number"
    }
  ],
  "drill": {
    "fields": ["id_sales", "id_customer", "location", "staff_name", "payment_method", "trxtype", "tier", "purchase_date"],
    "limit": 200
  },
  "relationships": [
    {
      "name": "customer",
      "label": "Customer",
      "view": "metrics_advanced_matrix_report",
      "on": { "id_customer": "customer_id" },
      "fields": [
        {
          "name": "customer.city",
          "label": "Customer: City",
          "group": "Customer",
          "kind": "dimension",
          "format": "string",
          "datatype": "string"
        }
      ]
    }
  ]
}
```

`fields` is sorted by name. `drill` appears only on a view that declares drill defaults, and
`relationships` only on a view that declares joins. A PII field (an email address, say) is
silently absent from `fields` and from every relationship's `fields` for a vendor without
`explore_pii`; it never shows up as "present but forbidden."

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `403` | `{"error": "Vendor is not entitled to the explore surface"}` | Explore not entitled |
| `403` | `{"error": "Not entitled to this view"}` | no such view, or it is outside this vendor's entitled dashboards and its Explore `views` grant |

---

### GET /views/:name/param-options

Distinct values for one **view param** (an `enum`-kind param, for example `trxtype`'s `Invoice`
and `Online Order`), for a dropdown.

**Auth:** same as `GET /views`.

**Path params:** `name`, the view's name.

**Query params:**

| Name | Type | Required | Notes |
|---|---|---|---|
| `param` | string | yes | one of the view's declared `params` |

**Request example:**

```bash
curl -sS 'https://prism.spoonity.com/api/insights/views/sales/param-options?param=trxtype' \
  -H 'Cookie: prism_session=<session-cookie>'
```

**Response example** (`200`):

```json
{ "options": ["Invoice", "Online Order"] }
```

At most 200 values, sorted, nulls excluded. Values that could not be sent back as a filter
(containing `,` or `%`, starting with `-`, or the literal `NULL`) are left out. A selection goes
back to `POST /query` as a comma-joined string in `params`.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `403` | `{"error": "Vendor is not entitled to the explore surface"}` | Explore not entitled |
| `403` | `{"error": "Not entitled to this view"}` | as above |
| `404` | `{"error": "Unknown param"}` | `param` is missing, a period param, or not declared by the view |
| `400` | `{"error": "This param has no enumerable values"}` | the param has no field to enumerate |
| `413` / `429` / `502` | same shapes as `POST /query` | byte cap, daily budget, execution failure |

---

### POST /query

**This is a read, not a write**; see the callout above. Run an ad-hoc query against one view:
pick fields, filter, sort, page. This is the single endpoint the Explore builder assembles.

**Auth:** same as `GET /views`. `403` when the vendor is not Explore-entitled, or names a view or
field it cannot see.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `view` | string | yes | a view name from `GET /views` |
| `fields` | string[] | yes | dimension and measure names, or `"rel.field"` for a declared join |
| `filters` | object of `{field: expression}` | no | **one object, keyed by field name**, not an array. Expressions use the filter grammar below. A measure filter requires the measure to also be in `fields`. |
| `sorts` | string[] | no | `"field"` (ascending) or `"field desc"`, not `{field, direction}` objects. A sort on a joined `"rel.field"` must also be selected in `fields`; an unknown sort field is a `400`. |
| `limit` | number | no | default 500, clamped to 1 to 5000 |
| `params` | object | no | values for the view's own declared params (for example `{"trxtype": "Invoice"}`); a multi-value param takes a comma-joined string. Anything the view does not declare is dropped. A view's `trxtype` param defaults to `Invoice,Online Order` when not sent. |
| `pivot` | string | no | the name of **one** selected dimension to pivot into per-value measure columns (at most 25 distinct values; overflow sets `pivot_truncated` on the response) |
| `period` | string | no | current-period token, default `"this month"` (see the period tokens under `GET /dashboards/:id`) |
| `previous_period` | string | no | compare-to token, default `"last month"`; `"same period last year"` is also accepted, for windows of a year or less |

Raw SQL is refused: a body carrying `sql` or `query` is a `400`.

**Filter grammar.** Each value in `filters` is a string expression: `a,b` (in list), `NULL` and
`-NULL` (is null, is not null), `-Foo` (not equal), `%Foo%` and `-%Foo%` (like, not like), `>5`,
`<5`, `>=5`, `<=5`, and `Yes` or `No` for yes/no fields. A date field also accepts
`YYYY-MM-DD`, `YYYY-MM-DD to YYYY-MM-DD`, a comparison such as `>=YYYY-MM-DD`, or a period token.
An expression a date field cannot parse is a `400` rather than a silent string comparison.

**Request example:**

```bash
curl -sS 'https://prism.spoonity.com/api/insights/query' \
  -H 'Cookie: prism_session=<session-cookie>' \
  -H 'Content-Type: application/json' \
  -d '{
        "view": "sales",
        "fields": ["location", "revenue"],
        "filters": { "revenue": ">100" },
        "sorts": ["revenue desc"],
        "params": { "trxtype": "Invoice" },
        "limit": 100,
        "period": "this month"
      }'
```

**Response example** (`200`):

```json
{
  "view": "sales",
  "columns": [
    { "name": "location", "label": "Location", "kind": "dimension", "format": "string" },
    { "name": "revenue", "label": "Revenue", "kind": "measure", "format": "currency" }
  ],
  "rows": [
    { "location": "Downtown", "revenue": 18420.55 },
    { "location": "Airport", "revenue": 9110.02 }
  ],
  "truncated": false
}
```

`truncated` is `true` when the result reached `limit`. A pivoted response keeps the same keys,
with the pivot dimension's values spread into extra measure columns, plus `pivot_truncated`.

**Errors:**

| Status | Body shape | Meaning |
|---|---|---|
| `400` | `{"error": "raw SQL is not accepted; name a view and fields instead"}` | body carried `sql` or `query` |
| `400` | `{"error": "Unknown field(s) requested", "unknown_fields": [...]}` | a `fields` entry the view doesn't have |
| `400` | `{"error": "Undeclared relationship", "unknown_fields": [...]}` | a dotted field name whose prefix names no declared join |
| `400` | `{"error": "Unknown filter field(s)", "unknown_fields": [...]}` | a `filters` key the view doesn't have |
| `400` | `{"error": "A measure filter applies via HAVING, so the measure must also be selected in 'fields'", "unselected_measures": [...]}` | filtering on a measure not also selected |
| `400` | `{"error": "sort field <name> must also be selected in 'fields'"}` or `{"error": "unknown sort field <view>.<name>"}` | a bad `sorts` entry |
| `400` | `{"error": "pivot field '<name>' is not a selected dimension"}` | `pivot` names something other than a selected dimension |
| `400` | `{"error": "<compiler message>"}` | the compiler rejected the spec, for example an unparseable date filter |
| `403` | `{"error": "Vendor is not entitled to the explore surface"}` | Explore not entitled |
| `403` | `{"error": "Not entitled to this view"}` | view outside this vendor's Explore scope |
| `403` | `{"error": "Not entitled to joined view(s)", "views": [...]}` | a joined field reaches a view this vendor cannot explore |
| `403` | `{"error": "Not entitled to PII fields", "pii_fields": [...]}` | a field, filter or param names a redacted PII field |
| `413` | `{"error": "This query would scan too much data ... narrow the date range and try again", "bytes": ..., "limit": ...}` | per-query byte cap |
| `429` | `{"error": "Daily data scan budget exceeded for this vendor; resets at <ISO time>", "budget_bytes": ..., "used_bytes": ...}` | per-vendor daily byte budget |
| `502` | `{"error": "query execution failed"}` | the underlying query failed to execute |

---

### POST /query/export

**This is a read**, but one of the two in this API that Prism's audit log records anyway, since it
produces a real CSV extract of vendor data; see the callout above. Same request as `POST /query`;
the response is a CSV file rather than JSON.

**Auth:** identical to `POST /query`.

**Body:** identical to `POST /query`, including `limit` (default 500, at most 5000).

**Request example:**

```bash
curl -sS 'https://prism.spoonity.com/api/insights/query/export' \
  -H 'Cookie: prism_session=<session-cookie>' \
  -H 'Content-Type: application/json' \
  -o sales-export.csv \
  -d '{ "view": "sales", "fields": ["location", "revenue"], "limit": 5000 }'
```

**Response:** `200`, `Content-Type: text/csv; charset=utf-8`, a raw CSV body: a header row of
column labels, then one row per result row. A failed export answers the same JSON error body as
`POST /query` instead of a CSV.

**Errors:** identical to `POST /query`.

---

### POST /drill

Expand one chart datum (a bar, a pie slice, a table row) into its underlying detail rows.

**Auth:** same as `POST /query`, except that the view may be any view Explore allows **or** any
view a tile on one of the vendor's entitled dashboards reads.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `view` | string | yes | the view the chart's own tile reads (or a tile's cross-view `drill.view` target) |
| `row` | object of `{dimension: value}` | yes | the clicked datum's dimension values, bound as an exact-match filter; every key must be a dimension of `view` |
| `fields` | string[] | no | defaults to the view's declared `drill.fields` |
| `limit` | number | no | defaults to the view's declared `drill.limit` (typically 200), clamped to 1 to 1000 |
| `period` / `previous_period` | string | no | same tokens and defaults as `POST /query`, so a drill from a "this year" chart reads the same window |

**Request example:**

```bash
curl -sS 'https://prism.spoonity.com/api/insights/drill' \
  -H 'Cookie: prism_session=<session-cookie>' \
  -H 'Content-Type: application/json' \
  -d '{
        "view": "sales",
        "row": { "location": "Downtown" },
        "fields": ["id_sales", "location", "purchase_date"],
        "period": "this month"
      }'
```

**Response example** (`200`):

```json
{
  "columns": [
    { "name": "id_sales", "label": "Sale Id", "kind": "dimension", "format": "string" },
    { "name": "location", "label": "Location", "kind": "dimension", "format": "string" },
    { "name": "purchase_date", "label": "Purchase Date", "kind": "dimension", "format": "string" }
  ],
  "rows": [{ "id_sales": "48213", "location": "Downtown", "purchase_date": "2026-09-14" }],
  "truncated": false
}
```

**Errors:**

| Status | Body shape | Meaning |
|---|---|---|
| `400` | `{"error": "Unknown dimension(s) in row", "unknown_fields": [...]}` | a `row` key isn't a dimension of `view` |
| `400` | `{"error": "Unknown field(s) requested", "unknown_fields": [...]}` | a requested field doesn't exist on the view |
| `403` | `{"error": "Vendor is not entitled to the explore surface"}` | Explore not entitled |
| `403` | `{"error": "Not entitled to this view"}` | as above |
| `403` | `{"error": "Not entitled to PII fields", "pii_fields": [...]}` | drilling by or selecting a redacted field |
| `413` / `429` / `502` | same as `POST /query` | byte cap, daily budget, execution failure |

---

### GET /dashboards

The curated dashboards this vendor is entitled to see, sorted by name.

**Auth:** Prism session cookie or broker ID token. Always scoped to the resolved vendor; there is
no Explore gate on this list (a vendor can have dashboards without Explore, or the reverse).

**Params:** none.

**Request example:**

```bash
curl -sS 'https://prism.spoonity.com/api/insights/dashboards' \
  -H 'Cookie: prism_session=<session-cookie>'
```

**Response example** (`200`, trimmed):

```json
[
  { "id": 52, "key": "customer analytics", "name": "Customer Analytics", "group": "Customers" },
  { "id": 12, "key": "locations", "name": "Location Analytics", "group": "Sales & Locations" },
  { "id": 83, "key": "loyalty program analysis", "name": "Loyalty Program Analysis", "group": "Loyalty" }
]
```

Unlisted dashboards (drill-through children) and dashboards restricted to other vendors are not
included.

**Errors:** none beyond the common errors above. An unentitled vendor simply gets `[]`.

---

### GET /dashboards/:id

One dashboard's full spec: its filters and every tile's metadata (title, chart type, span, its
own `view`, conditional formatting, tab assignment), which is everything the client needs to lay
the dashboard out before any tile's data has been fetched.

**Auth:** same as `GET /dashboards`. A dashboard restricted to a different vendor is a `404`,
indistinguishable from an id that was never allocated.

**Path params:** `id`, the numeric dashboard id from `GET /dashboards`.

**Request example:**

```bash
curl -sS 'https://prism.spoonity.com/api/insights/dashboards/83' \
  -H 'Cookie: prism_session=<session-cookie>'
```

**Response example** (`200`, trimmed to one tile):

```json
{
  "id": 83,
  "key": "loyalty program analysis",
  "name": "Loyalty Program Analysis",
  "group": "Loyalty",
  "filters": [
    { "name": "current_period", "type": "daterange", "label": "Transaction date", "default": "this month" },
    {
      "name": "currency",
      "type": "select",
      "label": "Currency",
      "default": "Saldo",
      "field": "currency",
      "optionsFrom": { "view": "loyalty_program_analysis", "field": "currency", "period": "this year" }
    }
  ],
  "tiles": [
    {
      "key": "store_redemption",
      "title": "Store Redemption Behaviour",
      "viz": "donut",
      "span": 6,
      "argument": "favorite_store_redemption_behaviour",
      "value": "count",
      "series": null,
      "view": "metrics_advanced_matrix_report",
      "exportable": false
    }
  ]
}
```

**Dashboard fields:**

| Field | Type | Meaning |
|---|---|---|
| `id` / `key` / `name` | number / string / string | identity; `key` is the stable slug used by entitlements, `name` is display copy |
| `group` | string or null | nav grouping; dashboards without one list under "Other" |
| `filters` | DashboardFilter[] | the dashboard's declared filters, passed through as authored (see below) |
| `tiles` | TileSpec[] | every tile's metadata; fields below |
| `tabs` | `{key, label}[]` | optional tab declarations; tiles opt in via their own `tab` |
| `parent` | number | optional: this dashboard is a drill-through child of that dashboard id. Set on an unlisted dashboard, one `GET /dashboards` never returns, which is reached through a `linkTo` button on the parent; it tells the client where to nest it once a viewer has been there |

**Filter fields** (`filters[]`):

| Field | Type | Meaning |
|---|---|---|
| `name` | string | the filter's wire key: what `filters` in a tile or data request uses, and what a `f_<name>` drill-through URL param uses |
| `type` | string | `daterange`, `select`, `multi`, or `text` |
| `label` | string | display copy; the server fills in a humanized `name` when the spec leaves it blank |
| `default` | string | the value applied when the request does not send this filter |
| `field` | string | optional: the view field or param the value is also bound to |
| `options` | string[] | optional: a fixed choice list, in place of `GET /dashboards/:id/filter-options` |
| `optionsFrom` | object | optional: `{view, field, period?}`, the view field whose distinct values fill this filter's list (fetch them with `GET /dashboards/:id/filter-options`) |
| `required` | boolean | optional: the filter cannot be cleared past its own default; a tile that needs it is blocked while it is blank |
| `mode` | `"before"` | optional, `daterange` only: restrict the control to an absolute cutoff with an hour and minute, no relative presets and no start/end range |

**Period tokens.** A `daterange` filter's value, and `period` / `previous_period` on `POST /query`
and `POST /drill`, is one of: `today`, `yesterday`, `last N days`, `year to date`, `this month`,
`last month`, `this quarter`, `last quarter`, `this year`, the older `N day`, or an explicit
`YYYY-MM-DD to YYYY-MM-DD` range. A cutoff filter instead sends `before YYYY-MM-DD` or
`before YYYY-MM-DDTHH:MM`, read as an unbounded start through that instant. A `previous_period`
filter takes any of those tokens too, plus `same period last year`. Omitting a filter applies its
`default`; when a dashboard declares no period filter, the current period is `this month` and the
previous period `last month`.

**Tile fields** (`tiles[]`; `key` through `exportable` are always present, the rest only when the
tile declares them):

| Field | Type | Meaning |
|---|---|---|
| `key` / `title` | string | tile identity and its displayed heading |
| `viz` | string | the chart type. Values used by the shipped dashboards: `stat`, `stat-single`, `stat-compare`, `bar-h`, `pie`, `donut`, `trend`, `line-multi`, `wordcloud`, `pyramid`, `funnel`, `table` |
| `span` | number | width in the 12-column grid |
| `argument` / `value` / `series` | string or null | the dimension, measure and series column names the chart reads |
| `view` | string | the tile's own view, so any tile with a dimension argument can drill into its detail rows |
| `exportable` | boolean | the tile offers a CSV export |
| `rowSpan` | number | how many grid rows the tile occupies; default 1 |
| `drill.view` | string | cross-view drill target, winning over `view` |
| `drill.map` | object | renames the tile's dimension(s) into the target view's spelling |
| `drill.fields` | string[] | field list for the drill request, overriding the target view's declared `drill.fields` |
| `drill.extra` | object | fixed row-filter values merged into every drill request from this tile (a drill inherits none of the dashboard's other filters) |
| `tab` | string | which declared tab the tile belongs to; absent means the first |
| `category` | string | groups the tile into a named horizontal row instead of the standard grid |
| `format_rules` | FormatRule[] | conditional formatting: `{field, op, value, style}` with `op` one of `gt`, `gte`, `lt`, `lte`, `eq` and `style` one of `positive`, `negative`, `warning`, `scale`, `diverging` |
| `color` | string | one hex fill overriding every other rule for this tile's chart |
| `categoryOrder` | string | fixed category order, for example `band` or `age` |
| `categoryColors` | string[] | ordered palette assigned by `categoryOrder`'s rank, not by row order |
| `matrixColorRules` | string | names a two-axis cell-coloring rule set for a table tile |
| `stageColors` | object | funnel tiles: an explicit hex per named stage, replacing the depth ramp |
| `wordCloudMaxRem` | number | word-cloud tiles: per-tile override of the shared max font size |
| `wordCloudHeightRem` | number | word-cloud tiles: per-tile override of the shared canvas height |
| `linkTo` | `{dashboard, filter, column, label?}` | table tiles: a per-row button navigating to `dashboard` with its `filter` preset from that row's `column`; `label` defaults to "Details" |
| `kpiColor` | boolean | `stat-single` tiles: color the whole card off the value's sign |
| `kpiInverted` | boolean | flips `kpiColor` so a rise reads red and a fall green |

A `table` tile that declares `drill` also makes every non-totals row clickable: the drill's `row`
is built from every dimension column the tile's own query selected, renamed through `drill.map`
and merged with `drill.extra`.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `404` | `{"error": "Unknown dashboard"}` | no such id, or restricted to a different vendor |
| `403` | `{"error": "Not entitled to this dashboard"}` | the id exists and is visible, but this vendor's entitlement row doesn't include its key |

---

### GET /dashboards/:id/filter-options

Distinct values for one **dashboard filter** whose options come from a live query
(`optionsFrom`), rather than a static list.

**Auth:** same as `GET /dashboards/:id`.

**Path params:** `id`, the dashboard id.

**Query params:**

| Name | Type | Required | Notes |
|---|---|---|---|
| `name` | string | yes | a filter name from the dashboard's `filters` |

**Request example:**

```bash
curl -sS 'https://prism.spoonity.com/api/insights/dashboards/83/filter-options?name=currency' \
  -H 'Cookie: prism_session=<session-cookie>'
```

**Response example** (`200`):

```json
{ "options": ["Puntos", "Saldo"] }
```

At most 200 values, sorted, with the same exclusions as `GET /views/:name/param-options`. A PII
field is never enumerated this way, regardless of entitlements.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `404` | `{"error": "Unknown dashboard"}` / `{"error": "Unknown filter"}` / `{"error": "Unknown options source"}` | the dashboard, the filter name, or its `optionsFrom` target doesn't resolve |
| `403` | `{"error": "Not entitled to this dashboard"}` | as `GET /dashboards/:id` |
| `400` | `{"error": "This filter has no optionsFrom source"}` | the filter uses static options or free text, not a live query |
| `403` | `{"error": "Not entitled to enumerate this field", "pii_fields": [...]}` | the source field is PII |
| `413` / `429` / `502` | `{"error": "This query would scan too much data", ...}` / budget / `{"error": "query execution failed"}` | byte cap, daily budget, execution failure |

---

### POST /dashboards/:id/data

**This is a read**; see the callout above. Run every tile on a dashboard in one call, applying
the dashboard's filter values. Prism's own dashboard pages fetch tiles individually instead (see
`POST /dashboards/:id/tiles/:key`) so slow tiles never block fast ones, but this endpoint returns
the same per-tile shape as a batch.

**Auth:** same as `GET /dashboards/:id`.

**Path params:** `id`, the dashboard id.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `filters` | object of `{filterName: value}` | no | only names the dashboard declares are read; a declared filter that is missing gets its `default`. A list value is joined with commas. |

**Request example:**

```bash
curl -sS 'https://prism.spoonity.com/api/insights/dashboards/83/data' \
  -H 'Cookie: prism_session=<session-cookie>' \
  -H 'Content-Type: application/json' \
  -d '{ "filters": { "current_period": "2026-08-01 to 2026-08-31" } }'
```

**Response example** (`200`, one entry per tile, in tile order):

```json
[
  {
    "key": "store_redemption",
    "columns": [
      { "name": "favorite_store_redemption_behaviour", "label": "Favourite Redemption Store Behaviour", "kind": "dimension", "format": "string" },
      { "name": "count", "label": "Customer Count", "kind": "measure", "format": "integer" }
    ],
    "rows": [{ "favorite_store_redemption_behaviour": "Single store", "count": 1284 }],
    "truncated": false
  }
]
```

On screen a tile returns at most 500 rows (or its own smaller declared limit). A tile that
declares totals gets an extra `"Total"` row at the end, and a pivoted tile carries
`pivot_truncated` as on `POST /query`. A tile whose own query fails does **not** fail the whole
response: it comes back as
`{"key": "...", "columns": [], "rows": [], "error": true, "detail": "tile query failed"}` alongside
every tile that succeeded.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `404` / `403` | same as `GET /dashboards/:id` | dashboard resolution |

---

### POST /dashboards/:id/tiles/:key

**This is a read**; see the callout above. Run one dashboard tile. This is what Prism's dashboard
pages call, once per visible tile, in parallel.

**Auth:** same as `GET /dashboards/:id`.

**Path params:** `id`, the dashboard id; `key`, the tile's `key` from `GET /dashboards/:id`.

**Body:** same `filters` shape as `POST /dashboards/:id/data`.

**Request example:**

```bash
curl -sS 'https://prism.spoonity.com/api/insights/dashboards/83/tiles/store_redemption' \
  -H 'Cookie: prism_session=<session-cookie>' \
  -H 'Content-Type: application/json' \
  -d '{ "filters": {} }'
```

**Response example** (`200`): the single-tile payload shown above (one entry from the `/data`
array), including the same in-body `error: true` shape when the tile's query fails.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `404` | `{"error": "Unknown dashboard"}` / `{"error": "Unknown tile"}` | bad dashboard id or tile key |
| `403` | `{"error": "Not entitled to this dashboard"}` | as above |

---

### POST /dashboards/:id/tiles/:key/export

**This is a read**, but the other of the two in this API that Prism's audit log records (as
`tile.export`, keyed by the tile's `key`, not the dashboard id); see the callout above. Same
request as `POST /dashboards/:id/tiles/:key`; the response is a CSV file.

**Auth:** identical to `POST /dashboards/:id/tiles/:key`.

**Path params / Body:** identical to `POST /dashboards/:id/tiles/:key`.

**Request example:**

```bash
curl -sS 'https://prism.spoonity.com/api/insights/dashboards/83/tiles/store_redemption/export' \
  -H 'Cookie: prism_session=<session-cookie>' \
  -H 'Content-Type: application/json' \
  -o store-redemption.csv \
  -d '{ "filters": {} }'
```

**Response:** `200`, `Content-Type: text/csv; charset=utf-8`, a raw CSV body. An export is not
held to the 500-row screen cap: a tile whose declared limit is the screen ceiling exports the full
result, up to 500,000 rows or 3,000,000 cells, whichever is smaller; a tile with a deliberately
smaller limit (a "Top 10", say) exports only that many. A tile whose query fails answers `200`
with an empty CSV rather than a JSON error, since tile failures are reported in the body on this
route family; a failed dashboard or tile lookup answers the same JSON error as the non-export route.

**Errors:** identical to `POST /dashboards/:id/tiles/:key`.

---

## What is deliberately not documented here

These bullets are true of **Prism's own backend**, the deployment [`prism.md`](./prism.md)
describes and the one every example on this page talks to. The `insights-app` deployment behind
`insights.spoonity.com` is a different codebase with a wider route table; where the two diverge,
that's called out below.

- **Schedules and alerts** (recurring emailed tile deliveries and threshold alerts) exist in
  Prism's backend data model but have **no HTTP route** on Prism's BFF; they are internal,
  job-runner-only concepts there. `insights-app` does mount `/api/schedules` and `/api/alerts`.
- **`/api/ask` and `/api/ask/query`** (a natural-language-to-query assistant) are **not mounted**
  on Prism's backend and 404 there. `insights-app` mounts them for Spoonity staff only, backed by
  its own Gemini credential.
- **`GET`/`PUT /api/welcome`**, the customizable welcome page built from an operator's own saved
  tiles, **is** mounted on Prism's BFF now, next to its saved tiles and dashboards routes, but is
  not yet written up in [`prism.md`](./prism.md). `insights-app` has its own copy.
- **`GET /health`** (served by the Insights service as `/insights/health`, and also answering on
  bare `/insights`) is an internal liveness and entitlement-debugging check. It reports the
  resolved vendor, whether the caller is a broker, whether the vendor has its own entitlement row
  or rides the baseline, and how many dashboards it can see. It is not a documented integration
  point.
