# Analytics and scorecards (Prompt 7)

The `analytics` module controls ingestion, CMS reports, exports, scorecards and their
jobs. All CMS routes require Sanctum, an active account, role-required 2FA, throttling
and a permission. Public counters use the existing `public-counts` module (the
`public_stats` feature in the build prompt), with `show_view_counts` and
`show_share_counts` sub-flags. Both flags off returns `404 module_disabled`.

## Ingestion

`POST /api/v1/events` accepts 1–50 events and returns HTTP 202:

```json
{
  "visitor_id": "browser-uuid",
  "surface": "web",
  "district": "kailali",
  "referrer": "https://www.google.com/",
  "events": [
    {"type": "view", "story": "01jdz3k6q8m4r2t7v9w1x3y5za"},
    {"type": "read_progress", "story": "01jdz3k6q8m4r2t7v9w1x3y5za", "value": 90},
    {"type": "engaged_seconds", "story": "01jdz3k6q8m4r2t7v9w1x3y5za", "value": 45},
    {"type": "share", "story": "01jdz3k6q8m4r2t7v9w1x3y5za", "network": "whatsapp"}
  ]
}
```

The response `data` has `accepted`, `duplicates` and `dropped` counts. Other event
types: `click`, `play`, `complete`, `push_open`, `newsletter_click`, `ad_impression`,
`ad_click`, `epaper_page_view`, `search`. Subjects use `subject_type` (`video`,
`radio_episode`, `epaper_edition`, `ad_campaign`) and a `subject` ULID. Page views
without a story can carry `path`. Search events carry `query` and `results`.
Server integrations can record `comment`, `reaction` and `bookmark` through
`AnalyticsIngestService::recordServer()`; clients cannot submit these types.

Bots and empty user agents are dropped. Unknown subjects and unsupported progress
values are dropped; progress supports 25/50/75/90. Engaged seconds are clamped to
1–600 per event. Optional `at` timestamps outside the last day / next five minutes
are replaced with server time. Device, surface, traffic-source class and reader
district are added to each event. `throttle:events` allows 1,200 requests/minute/IP.

Reader hashes are 32-character HMACs of the authenticated account, anonymous visitor
ID, or IP plus user agent as a fallback. Raw events contain no account ID, visitor ID
or IP. Clients should send a stable random visitor ID and a bearer token when signed
in. Views dedupe per reader/story for 30 minutes using Redis `SET NX EX`; the legacy
`POST public/stories/{uid}/view` uses the same dedupe window and pipeline.

Ingestion updates Redis minute hashes and a stream. `ConsumeAnalyticsEventsJob`
batch-inserts the stream into `analytics_events`. The table has a composite primary
key `(id, occurred_at)`, no foreign keys and daily MySQL RANGE partitions.

## Reports

All paths below are under `/api/v1/cms`. Presets: `today`, `yesterday`, `7d`, `30d`,
`90d`, `month`, `bs_month`, `fiscal_year`, `custom`. Custom `from`/`to` are inclusive
Nepal dates; the maximum span is 400 days. Storage bounds are UTC `[from, to)`.

| Endpoint | Permission / scope |
| --- | --- |
| `GET analytics/dashboard` | analytics or scorecards own/desk/all; role dashboard |
| `GET analytics/overview` | `analytics.view.all`; live readers and last 30 minutes |
| `GET analytics/stories/{uid}` | `analytics.view.own|desk|all`; verifies story access |
| `GET analytics/categories/{uid-or-slug}` | `analytics.view.all` |
| `GET analytics/locations/{province|district|local-level}/{slug}` | `analytics.view.all` |
| `GET analytics/leaderboards?dimension=&metric=&period=` | `analytics.view.own|desk|all` |
| `GET analytics/compare?dimension=&key=&from=&to=&compare_from=&compare_to=` | analytics scope for the subject |
| `POST analytics/exports` | `analytics.export` plus the report's read permission |
| `GET analytics/exports/{uid}` | `analytics.export`, requesting user only |

Leaderboards support story, author, editor, category, tag, topic, province, district,
local level, desk, content type, surface, referrer, device and reader district.
Own/desk viewers can use only story/author/editor dimensions. Metrics: views,
uniques, shares, engaged, completion, comments, push opens, ad revenue and growth.
Desk access covers desks headed by, joined by or scoped to the viewer and their
members; own access covers stories created or co-authored by the viewer.

Rollups recompute whole buckets from raw events, making repeated runs idempotent.
Hours use UTC boundaries; days use Nepal midnight. They contain views, distinct
readers, engaged seconds/readers, completion readers (90% progress), shares by
network, clicks, plays/completes, push opens, newsletter clicks, ads, e-paper page
views, searches, comments, reactions and bookmarks. Whole-period uniques are exact
distinct raw reader hashes, rather than sums of daily uniques. Revenue uses CPM/CPC
campaign rates attached to ad events. Derived fields include engagement average,
completion percentage, RPM and CTR. Facebook engagement is fetched hourly when
`FACEBOOK_GRAPH_TOKEN` is configured and exposed separately on story reports.

Exports accept `{report, format, params}`; formats are CSV (UTF-8 BOM), XLSX and PDF.
Reports: leaderboard, story, category, location, scorecards, priority. Story/category
reports require `params.uid`; location requires `params.type` and `params.slug`.
They return 202, run on `analytics`, and store files on the configured private media
disk. Poll for `queued|running|ready|failed`; ready reports include a ten-minute
signed download URL. Authorization is checked again in the worker. Category and
location exports require all analytics access; priority requires all analytics or
all scorecard access; scorecard exports require desk/all scorecard access.

`GET /api/v1/public/stories/{uid}/counts` returns only enabled view/share counts,
with English and Nepali display strings such as `12.4K` / `१२.४ हजार`. It supports
ETag and Cache-Control and only resolves publicly visible stories. Flags are
checked on every request, separately from cached totals.

## Scorecards and fairness

| Endpoint (under `/api/v1/cms`) | Permission |
| --- | --- |
| `GET scorecards/me`, `GET scorecards/users/{uid}[/history]` | `scorecards.view.own|desk|all` |
| `GET scorecards?role=&sort=&district=&period=` | `scorecards.view.desk|all` |
| `GET scorecards/locations/{type}/{slug}`, `GET scorecards/priority` | all analytics or all scorecards |
| `GET scorecards/weights` | any scorecard scope |
| `PUT scorecards/weights` | `scorecards.weights.manage`; all six weights, total 100 |
| `GET/POST stories/{uid}/accuracy-flags` | `factcheck.rate` or `corrections.manage` (read also allows all scorecards), plus story scope |
| `POST accuracy-flags/{uid}/revoke` | `factcheck.manage` or `corrections.manage`, plus story scope |
| `GET/POST scorecards/appeals` | own scorecards; deciders may list all |
| `POST scorecards/appeals/{uid}/decide` | `scorecards.appeals.decide`; cannot decide your own appeal |

Reporter metrics come from transitions, reviews, revisions, sources, assignments,
media and analytics: submitted, published, returned, rejected, merged, current
pending, acceptance, relevance/in-beat, accuracy, fake/misleading counts,
corrections, edit intensity, timeliness, assignments on time, breaking/exclusive,
original media, source quality, duplication/plagiarism, upheld complaints, audience,
coverage and priority accuracy. Stringer/contributor cards extend reporter cards.
Other cards cover editors, admins, desk heads, fact-checkers, photo/video editors,
radio, e-paper, ads, SEO/social and moderation. `ROLE_KINDS` maps newsroom role names
to card kinds. Each role receives its cards through the dashboard endpoint.

Credibility weights: accuracy 35, relevance 20, acceptance 15, inverse edit intensity
10, timeliness 10, impact 10. Parts without data are omitted and remaining weights
are normalized. Relevance scales the review rating 1–5 to 0–100 and blends in-beat
coverage when available. Timeliness and impact use newsroom percentile ranks.
Edit intensity measures changed word counts between submitted and published
snapshots. A confirmed fake flag or fake/fabricated rejection caps credibility at
50 for 90 days and alerts the chief editor.

Flags require evidence of at least ten characters. Upheld flag appeals revoke only
that flag; upheld rejection appeals clear the rejection's score penalty. Other
confirmed flags remain in effect. Flags, revocations, appeals, decisions, weight
changes, alert-rule changes, acknowledgements and views of another person's
scorecard use `AuditService`. Notification events are `AccuracyFlagged`,
`AppealDecided` and `AnalyticsAlert`; templates exist in ne/en. Workflow transitions
trigger `RecordStoryMetrics` and incremental scorecard refreshes.

Metrics supplied by later modules remain `null` with `pending_modules` (community
moderation, full fact-check claims, SEO/search-console/social reach and citizen
tips). Stringer payments remain null until the client confirms
`STRINGER_RATE_PER_STORY`. These are dependency gaps, not measured zeroes.

## Operations

| Task | Schedule (Nepal time) / queue |
| --- | --- |
| Consume event stream | every minute / `analytics` |
| Refresh current/previous hour and today | every five minutes / `analytics` |
| Close yesterday (all hours + daily totals) | 00:20 / `analytics` |
| Evaluate alert rules | every fifteen minutes / `analytics` |
| Snapshot active staff scorecards | 01:00 / `analytics`; closes previous month on day 1 |
| Facebook engagement | hourly / `low`, when configured |
| `analytics:partitions` | 00:40; creates 14 future days and removes raw data older than 13 months |

`ScorecardWeightsSeeder` and `AlertRulesSeeder` run through `ReferenceDataSeeder`
and record seed versions. `AnalyticsRolePermissionsSeeder` adds own-scorecard access
once to unchanged default newsroom roles; customized roles remain as configured.
New role defaults include own-scorecard access. Alert defaults cover viral stories, falling accuracy,
districts silent for three days, SLA breaches, traffic drops above 40%, and confirmed
fakes. Rules store thresholds, recipient roles, cooldown and active state. CMS
`analytics/alerts` lists/acknowledges alerts (`analytics.view.all`);
`analytics/alert-rules` lists/updates rules (`analytics.alerts.manage`).

Raw retention does not delete rollups or audit history. Run Horizon and the scheduler
for ingestion persistence, rollups, exports, alerts and scorecard snapshots.
For an existing installation, apply migrations and run
`php artisan db:seed --class=AnalyticsSeeder` to add Phase 7 defaults without
reseeding geography or demo content. Existing thresholds, weights, notification
templates and module switches are preserved.
See [redis.md](redis.md) for keys and [openapi.json](openapi.json) for generated API
schemas. Tests live in `tests/Feature/Analytics` and cover dedupe, bots, enrichment,
rollup maths/idempotence, reports, formulas, fake caps, appeals, access scopes,
exports, dashboard, snapshots, alerts and public-count flags.
