# Reports

What a brand's reports count, where the numbers come from, and how to export
them (M8-04, [REQUIREMENTS §4.8](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/docs/planning/REQUIREMENTS.md#48-reports--dashboards)):
the **Reports** screen in the admin, and the api it reads.

## Who may read them

`report:read`: an **Admin**, a **Team Leader** and a **Viewer** (DOMAIN-RULES
§1.2: a Viewer "may read reports"). An **Agent** may not.

A Team Leader or a Viewer restricted to some departments gets those
departments' numbers and no others. The rollup tables are department-scoped
under row-level security like the tickets they summarise, so asking for a
department they cannot see answers zeroes, not another team's figures.

## The Reports screen

`Reports` in the sidebar (artboard `Admin/Reports`), offered to the three roles
that hold `report:read`.

- **Filters:** a date range (the last 7, 30 or 90 days, or any range of up to
  366 days), a department, a channel and an agent. Each change asks the api
  again. The range opens on the last 30 days, ending today. The agents offered
  are the summary's `agentChoices`: everyone with work or assigned tickets in
  the range under the other filters, so a Viewer, who may not list staff, gets
  them too.
- **KPI tiles:** tickets created, median first response, SLA met (response and
  resolution clocks together) and CSAT. Each compares itself in words with the
  same number of days just before the range ("8 % more than the previous 30
  days"), from a second read of the same route.
- **Cards:** Ticket volume (created per day, stacked by Channel, Status or
  Priority, with each series' total beside it; a sixth series and beyond fold
  into "Other"), First response and resolution time, SLA compliance (by
  priority and by clock), Backlog trend, Customer satisfaction, Volume by tag
  (tickets created in the range per tag, the 20 most used), Backlog by status
  (the tickets open now per status, each with how many nobody is assigned, and
  the unassigned share of them all; M14-29), Agent workload
  (per agent: open assigned, solved, replies, median first response, median
  resolution, SLA met and CSAT, then an "Unassigned" row with the open tickets
  nobody has, left out when the report is one agent's), Busiest hours (weekday
  by hour, in the brand's time zone), Help center top searches and Searches with
  no results. AI deflection rate and AI cost come from `ai_calls` and the
  auto-reply timestamps ([AI guide](https://helpdock.oday-bakkour.com/docs/ai/#deflection)).
- **Table and Export CSV**: "Table" on every card swaps the chart for the same
  numbers as a table, and "Export CSV" downloads that report's rows with the
  filters in force, named as below. The two search cards export the same
  `searches` file; Ticket volume exports `volume` for the Channel and Priority
  breakdowns and `volume_by_status` for Status; Volume by tag exports
  `volume_by_tag`. Backlog by status and the two AI cards have no CSV: the
  backlog's Table carries every figure.
- Volume by tag and Backlog by status show a tag's or a status's Arabic name to
  an Arabic reader where the brand wrote one, and its own name otherwise.
- Charts are drawn as plain SVG (no charting library is in the stack). Each is
  one image with its figures in its accessible name, and follows the charting
  rules of [DESIGN §9](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/DESIGN.md#9-charts). In Arabic the page mirrors and
  the plots keep time running left to right, as numerals do.

## What is counted

A ticket counts unless it is **spam**, **merged** into another, or
**soft-deleted**: the statuses marked "excluded from reports" (Spam and Merged,
M1-11) and `deleted_at` keep it out of every number below.

Every number is filed under the ticket's department, channel, priority and
assignee **as they are now**: a ticket moved to Billing last week reports under
Billing, and a reassigned ticket's times, SLA outcomes and rating are its new
assignee's.

| Report | What it is | When it counts |
|---|---|---|
| Volume | Tickets created and resolved, by day, channel and priority, and created per day and channel or priority (the stacked columns) | Created on creation; resolved on `closed_at` |
| By status | Tickets created in the range, by the status they are in now, in total and per day of creation | A current state, read from the tickets themselves |
| Volume by tag | Tickets created in the range, per tag they carry now; a ticket with two tags counts under each, one with none in no row. The 20 most used, ties by name; the CSV has every tag. Only tickets that still exist count: a ticket deleted, or removed by retention, drops out of it while it stays in Ticket volume's rollups, so for an old range the two cards can differ | A current state, read from the tickets themselves |
| Backlog by status | Tickets open now — in a status whose system state is not closed (so Snoozed, once M14-02 adds it, counts) — per status, with how many have no assignee, and the unassigned share of the total | Now, whatever the date range; under the department, channel and agent filters. One agent's report leaves the unassigned figures out |
| First response time | Median and p90 | On the day of the response |
| Resolution time | Median and p90 | On the day of the resolution |
| SLA compliance | Response and resolution clocks met, over met plus breached; per priority, both clocks together | On the day the clock was satisfied or breached |
| Backlog trend | Tickets open at the end of each day | A snapshot at the day's end |
| CSAT | Responses, average, share of 4 and 5, and the 1–5 distribution | On the day of the rating |
| Agent workload | Public replies and resolutions per agent and the open tickets assigned to them at the end of the range; the median first response and resolution, SLA met (both clocks) and CSAT average of the tickets assigned to them; and the open tickets with no assignee | Replies and resolutions on their day; times, SLA and ratings as in the rows above |
| Busiest hours | Tickets created per weekday and hour | On creation |
| Help center searches | Top searches with the share that opened a result, and searches that found nothing | On the day of the search |
| AI deflection and cost | "Not available" until the AI subsystem (M7) records calls | — |

Days are the **brand's** calendar days, in its time zone (Brand settings), so
"yesterday" is the brand's yesterday.

### Response and resolution times

A ticket under an SLA policy is timed by its clocks (DOMAIN-RULES §3): satisfied
minus started, **less the time paused** waiting on the customer
(`paused_total_ms`). A ticket no policy matched has no clocks, and is timed from
its creation to the first public staff reply, and to `closed_at`.

M11 migration support is in development. Its rollup includes an imported agent's
first public reply when the author is retained as a name only. Anonymous system
messages do not count as agent replies, and a name-only author does not get an
invented staff account or per-agent workload row. Historical ratings count on
their original rating day; they are separate from live surveys.

An import rebuilds reports over its range when it finishes. It works in
resumable 31-day chunks through the brand's current local day, so imported open
tickets contribute to later backlog snapshots. The default window is 400 days;
older history needs **Rebuild reports for all imported history** on the import
wizard's Scope step (`rebuildAllReports`). A clipped rebuild records a warning.

Only a ticket's **initial** clocks count, unless the brand turns on "count
reopens" (`slaCountReopens`, Inbox › SLA policies): then a reopened ticket's
next-response clock counts as a response and its later resolution clocks as
resolutions, in times and in compliance alike (DOMAIN-RULES §3.5). The rollup
reads the setting when it runs, so a change shows in the trailing week at the
next hourly run.

Medians and p90s are taken over every response or resolution in the range, not
averaged from daily figures.

## Filters

| Filter | Applies to |
|---|---|
| `from`, `to` | Everything but Backlog by status, which is the tickets open now. Inclusive local days, at most 366 apart |
| `departmentId` | Every ticket report. Not help center searches, which have no department |
| `channel` | Every ticket report. Not help center searches |
| `agentId` | Every ticket report, by the ticket's assignee; Agent workload, by the agent. Not help center searches or AI cost, which have no agent |

## How fresh it is

The numbers are read from rollup tables that the worker's `stats.rollup` job
rebuilds hourly, at seven minutes past, for every active brand:

```
:07 every hour  stats.rollup.schedule   one job per active brand
                stats.rollup (brand)    rebuild the last 7 local days
```

- A run deletes the days it covers and writes them again from the tickets, so
  running it twice changes nothing, and a ticket marked spam or deleted during
  the week drops out of the days it was counted in.
- A brand with no rollups yet — an install upgraded to M8, or a new brand — is
  backfilled from its first ticket, up to 400 days back, in transactions of 31
  days. So is a brand whose rollups in those 400 days were built at an older
  grain: each `report_daily` row records the `rollup_version` it was built at,
  and a run that finds one below the code's `REPORT_ROLLUP_VERSION` rebuilds the
  brand's whole history once, then goes back to the trailing week.
- Days older than a week are not rebuilt. A ticket deleted after that stays in
  the history it was counted in, the backlog of a past day is the snapshot
  taken at the time, and retention purging old tickets does not rewrite old
  reports. Help center searches stay in the rollups after the search log itself
  is purged (DOMAIN-RULES §11: "aggregates for reports kept").

`computedAt` in the answer is when the oldest rollup in the range was written.
By status, Volume by tag and Backlog by status are not rollups: they describe
what tickets are now, so they are read from the tickets on each request and are
as fresh as the page.

The rollup tables are `report_daily` and `report_agent_daily`
(department-scoped), and `report_search_daily` and `report_help_center_daily`
(brand-scoped), from migration `0037_report_rollups`. Migration
`0044_report_daily_assignee` added the assignee to `report_daily`'s grain (day,
department, channel, priority and assignee) and the `rollup_version` column;
rows from before it read as version 1, so on an upgraded install each brand's
next hourly run rebuilds its last 400 days with the assignee, and the Agent
filter and per-agent times, SLA and CSAT cover that history. Days older than
400 days keep no assignee.

## API

| Route | Permission | |
|---|---|---|
| `GET /api/brands/:brandId/reports?from=&to=[&departmentId=][&channel=][&agentId=]` | `report:read` | The summary: every report above, ranked lists cut at 20 rows |
| `GET /api/brands/:brandId/reports/exports/:report?from=&to=[…]` | `report:read` | One report as CSV, every row |

The summary's shape is `reportSummarySchema` in `@helpdock/schemas`. A range
that ends before it starts, or runs past 366 days, is a 400.

## CSV export

`:report` is one of `volume`, `volume_by_status`, `volume_by_tag`, `response_times`, `sla`,
`backlog`, `csat`, `agents`, `busiest_hours` and `searches`. The file is UTF-8 with CRLF line
ends, named `helpdock-<report>-<from>-<to>.csv`, with a header row of English
column keys: a script reading the file should not break when the reader's
language changes.

The ticket reports (`volume`, `response_times`, `sla`, `csat`) have one row per
day, department, channel, priority and assignee (`agent_id`, `agent`; both
empty for no assignee); `response_times` carries that slice's own percentiles,
so SLA by priority and volume by channel or priority are sums over these rows.
`volume_by_status` has one row per day of creation and current status
(`day,status_id,status,created`). `volume_by_tag` has one row per tag with
tickets created in the range, most used first (`tag_id,tag,tag_ar,created`;
`tag_ar` is empty where the brand wrote no Arabic name). `agents` has every agent with replies,
resolutions, open assigned, first responses and their median, resolutions and
their median, SLA met and breached, and CSAT responses and average, then one
row with no agent whose `assigned_open` is the unassigned open tickets.

**Safe to open in a spreadsheet.** A cell that starts with `=`, `+`, `-` or `@`
(or a tab or a carriage return) is written with a leading `'`, so a department
called `=HYPERLINK(…)` or a search for `+1 555` opens as text and never runs as
a formula.

The rows are read inside the request's transaction, where row-level security
applies, and then streamed out; a stream that read the database as it went
would run outside that transaction.

## Known gaps

- **The screen draws what the summary carries.** Response and resolution times
  are the period's median and p90 rather than a line per day, and CSAT has no
  "% of surveys answered" or comment count.
- **Agent workload** counts open tickets, times, SLA and ratings by today's
  assignee, as departments count by today's department. A ticket's first
  response is its assignee's even when someone else wrote it.
- **Scheduled email reports** are v1.1 (REQUIREMENTS §4.8).
