---
title: "Visitor Analytics API"
canonical_url: "https://ainode.run/docs/visitor-analytics"
type: "doc"
locale: "en"
description: "Administrator endpoints for visitor profiles, attribution, event history, and related orders."
---

# Visitor Analytics API
> Administrator endpoints for visitor profiles, attribution, event history, and related orders.

All endpoints in this module require an authenticated administrator session and return timestamps as UTC ISO-8601 strings.

## Get Visitor Details

Returns the complete visitor profile, linked user summary, aggregate behavior counts, related order summaries, and up to 100 recent events. Sensitive fulfillment data, payment credentials, and raw payment responses are not included.

**Endpoint:** `GET /api/admin/stats/visitors/:visitor_id`

**Path Parameters:**

- `visitor_id` (required): The full visitor ID stored in the `visitor_id` cookie and visitor analytics tables.

**Response:**

```json
{
  "profile": {
    "visitorId": "0d47f9aa-78a3-45c1-80d1-2d0e348923a7",
    "userId": 42,
    "ip": "203.0.113.10",
    "firstSourceType": "campaign",
    "firstSource": "google",
    "firstMedium": "cpc",
    "firstCampaign": "summer-launch",
    "country": "CN",
    "region": "Shanghai",
    "city": "Shanghai",
    "deviceType": "mobile",
    "browser": "Chrome",
    "os": "Android",
    "firstSeenAt": "2026-07-28T08:00:00.000Z",
    "lastSeenAt": "2026-07-28T09:30:00.000Z"
  },
  "user": {
    "id": 42,
    "email": "buyer@example.com",
    "nickname": "Buyer",
    "status": 1,
    "createdAt": "2026-07-28T08:15:00.000Z"
  },
  "stats": {
    "totalEvents": 18,
    "pageViews": 10,
    "productViews": 4,
    "checkouts": 2,
    "paid": 1,
    "auth": 1,
    "orders": 2
  },
  "orders": [
    {
      "id": "OT20260728123456ABCD",
      "amount": 99,
      "currency": "CNY",
      "productId": 3,
      "productName": "Pro Plan",
      "payStatus": "paid",
      "status": "active",
      "createdAt": "2026-07-28T09:00:00.000Z",
      "paidAt": "2026-07-28T09:02:00.000Z"
    }
  ],
  "recentEvents": [
    {
      "id": 120,
      "eventName": "order_paid",
      "path": "/payment/OT20260728123456ABCD",
      "source": "google",
      "medium": "cpc",
      "campaign": "summer-launch",
      "orderId": "OT20260728123456ABCD",
      "productId": 3,
      "productName": "Pro Plan",
      "createdAt": "2026-07-28T09:02:00.000Z"
    }
  ],
  "recentEventsLimit": 100
}
```

**Errors:**

- `400`: Invalid or oversized visitor ID.
- `404`: Visitor profile not found.

## Get IP Details

Returns aggregate statistics for one IP bucket within the selected reporting range, including all matching visitor identities, linked user summaries, observed location/device contexts, and up to 100 recent events.

**Endpoint:** `GET /api/admin/stats/ip-details`

**Query Parameters:**

- `ip`: The IP address to inspect. Required unless `local=1`.
- `local`: Set to `1` to inspect events whose IP is unavailable (`NULL`).
- `preset`: Reporting range preset (`today`, `yesterday`, `7d`, `30d`, or `90d`).
- `days`: Range size used by compatible custom presets.

**Response:**

```json
{
  "ip": "203.0.113.10",
  "range": { "preset": "today", "days": 1 },
  "stats": {
    "totalEvents": 32,
    "uniqueVisitors": 3,
    "registeredUsers": 1,
    "pageViews": 20,
    "productViews": 6,
    "checkouts": 2,
    "paid": 1,
    "auth": 1,
    "firstSeenAt": "2026-07-28T08:00:00.000Z",
    "lastSeenAt": "2026-07-28T10:00:00.000Z"
  },
  "visitors": [
    {
      "visitorId": "0d47f9aa-78a3-45c1-80d1-2d0e348923a7",
      "eventCount": 18,
      "firstTouch": "google",
      "user": { "id": 42, "email": "buyer@example.com" }
    }
  ],
  "visitorLimit": 100,
  "contexts": [],
  "recentEvents": [],
  "recentEventsLimit": 100
}
```

**Errors:**

- `400`: Invalid or oversized IP address.

## Overview Statistics & Traffic Source Attribution

**Endpoint:** `GET /api/admin/stats`

The report is based on events and order facts inside the selected half-open interval `[from, to)`, in the configured site timezone. It never selects the cohort by the mutable profile `lastSeenAt`. All `range` timestamps are UTC ISO strings.

**Query parameters:**

- `preset`: `today`, `yesterday`, `7d`, `30d`, or `90d`. The preset determines the day count even when `days` is omitted.
- `days`: Custom day count from 1 to 90, used when there is no recognized preset.

**Metric definitions:**

- `uniqueVisitors`: Distinct browser `visitor_id` identities with tracked page/product/checkout/auth activity or linked successful orders in the period. This includes payment-only identities and is not a count of people or sessions.
- `pageViewVisitors`: Identities with a `page_view` in the period. `pageViews` is the event count.
- `authVisitors`, `loginVisitors`, `registerVisitors`: Authentication events in the period, not the current profile's login/registration state. New auth events originate in server handlers.
- `paidVisitors`: Identifiable visitors with at least one real nonzero order currently in `paid` status, selected by `orders.paidAt`. Browser `order_paid` events are not payment facts.
- `paidOrders`: Number of real nonzero paid orders, including orders without a visitor ID. `freeOrders` separately counts zero-amount paid orders.
- `conversionRate`: `paidVisitors / uniqueVisitors * 100`. Each source row uses the same distinct-visitor denominator within that row. This is not orders divided by visitors.
- `revenue`: The configured base-currency total, using `currencySnapshot.baseAmount/baseCurrency` via the shared order currency resolver. `revenueByCurrency` preserves separate accounting-currency totals; different currencies are never added together. For legacy orders without snapshots, the payment currency remains its own bucket.
- Successful orders without a `paidAt` are excluded from period metrics; creation time is not substituted. Such legacy records need separate investigation.
- `unattributedPaidOrders` and `unattributedRevenueByCurrency`: Paid orders without `visitorId`. Their amounts remain in total revenue and are not guessed into a source bucket.
- `uniqueIps`: Distinct raw-event IP buckets, including one missing-IP bucket. IP diagnostics are independent of marketing attribution.
- `overview.comparisons`: Period-over-period comparisons for the three traffic cards (`pageViews`, `uniqueVisitors`, `uniqueIps`). Each metric exposes `{ current, previous, delta, deltaPercent, trend, fullDay?, predictedFullDay? }`: `today` (`mode: 'yesterday_same_time'`): Compares `[today 00:00, now)` against the matching elapsed window yesterday (`[yesterday 00:00, yesterday same time)`) so intraday growth rates are not distorted by an unfinished day, and also returns `fullDay` for full-yesterday (`[yesterday 00:00, today 00:00)`) reference and `predictedFullDay` (today's projected full-day total scaled from yesterday's full day by today's pace, floored at `current`).`yesterday` (`mode: 'day_before_yesterday'`): Compares full yesterday against the day before yesterday.`7d / 30d / 90d` (`mode: 'previous_period'`): Compares against the preceding `N`-day window.
- `funnel`: Retained response field containing independent behavior counts. It is not a sequential/cohort funnel. The page labels it as behavior distribution.

**Attribution scopes:**

- `firstTouch`: The original acquisition source for identities active in the reporting period, using immutable first-entry information (`firstSource` and `firstReferrer` remain frozen at initial profile creation and are never backfilled by subsequent revisits). Current profile geography, user linkage, and last source do not determine historical activity.
- `lastTouch`: Latest identifiable page/product entrance source observed **within the reporting period**. Internal navigation does not replace an identified source. If the period contains no source evidence, the row is shown as direct/unidentified; a source from a later profile update is not substituted.
- `categories`: Channel of the period's `lastTouch`. `external` contains non-direct `lastTouch` rows, including tagged campaigns. The separate `externalVisitors` card counts visitors with observed external referring domains; it can therefore differ from the `external` source-list total.
- `geoConversions`: Shared Country × Channel (`ai` / `search`) cross-conversion rows (`buildVisitorGeoConversions`), also returned by `GET /api/admin/settings/seo-telemetry`. Conversion rates (`conversionRate`, `aiConversionRate`, `searchConversionRate`) use deduplicated paid visitors (`paidVisitors / totalVisitors`), and revenue/AOV are bucketed per accounting currency (`revenueByCurrency`, `aovByCurrency`) without summing across currencies.
- Source commerce metrics group the orders of those visitor identities within the period. They do not yet use a frozen attribution snapshot per order. Source `checkouts` counts visitors who initiated checkout; `paid` is a compatibility alias for `paidVisitors`, not an order count.

**Channels (`sourceType`):**

- `direct`: No identifiable external or campaign evidence. The page displays “Direct / unidentified”.
- `search`, `social`, `ai`, `email`, `referral`: Recognized referring sources; explicit UTM media such as `organic`, `social`, `organic_social`, `ai_referral`, `email`, and `referral` select the corresponding channel.
- `campaign`: Paid click IDs (`gclid`, `wbraid`, `gbraid`, `ttclid`, `msclkid`, `twclid`) or other tagged marketing traffic. A UTM campaign name does not imply paid advertising. `fbclid` alone identifies Facebook social traffic and does not establish a paid campaign.
- `affiliate`: Explicit affiliate medium or supported promotion parameters (`invite`, `inv`, `promo`, `agent`, `ref`, `aff`). Generic `code` is excluded because authentication links also use it. Promo settlement ownership remains separate from marketing channel classification.

UTM fields take precedence over inferred referrer classification. A tagged campaign with missing `utm_source` has source `unknown`, never `Direct`. Unknown referring domains retain their complete normalized hostname. Search keywords (`term`) are extracted from `utm_term`, external referrer query parameters (`q`, `wd`, `word`, `query`, `keyword`, `kw`, `p`, `text`), or tagged landing parameters, while internal site searches without external acquisition stay `Direct`. Source fields are replaced together when switching to a new source, while same-source refreshes and internal navigations preserve captured external referrers and search terms.

**Source row example:**

```json
{
  "key": "[\"social\",\"Telegram\",\"social\",\"launch\"]",
  "label": "Telegram · social · launch",
  "sourceType": "social",
  "source": "Telegram",
  "medium": "social",
  "campaign": "launch",
  "terms": ["tg-keyword"],
  "referrers": ["https://t.me/apay_channel/42"],
  "count": 20,
  "visitors": 20,
  "checkouts": 4,
  "paid": 2,
  "paidVisitors": 2,
  "paidOrders": 3,
  "revenue": 30,
  "currency": "USD",
  "revenueByCurrency": [{ "currency": "USD", "amount": 30 }],
  "conversionRate": 10,
  "percentage": 25
}
```

The response also includes `hourlyTrend` (24-hour UV/PV buckets in the configured timezone when `days === 1` for `today`/`yesterday`, alongside daily `trend`), `topPages` (top visited page paths with `views`, `visitors`, `percentage`), `topLandingPages` (top landing page paths with `visitors`, `views`, `percentage`), `browsers`, `operatingSystems`, `timezone`, `currency`, `attributionVersion: 1`, and `generatedAt`. Source lists are complete rather than silently dropping low-volume sources.

## Visitor List and Source Drill-down

**Endpoint:** `GET /api/admin/stats/visitors`

Accepts the same `preset`/`days`, plus `page` (default 1), `pageSize` (1–100, default 20), and:

- `attribution`: `first` or `last` (default `last`).
- `sourceKey`: Exact source-row `key`; URL-encode it as a query parameter. Send the same attribution mode used by the clicked list. Category rows instead use `sourceType`.
- `sourceType`: A channel, `external` for observed external referrers, or `tagged` for visitors with campaign/promotion tags during the period.
- `type`: `page_view`, `product_view`, `begin_checkout`, `order_paid`, or `auth`. Payment filters use actual nonzero paid orders. Event and source filters are intersected.
- `source`: Compatibility exact source/label filter. New clients should use `sourceKey`; display strings are not stable identifiers and substring matching is not performed.
- `search`: Optional keyword filter matching `visitorId`, `ip`, `country`, `region`, `city`, `deviceType`, `browser`, `os`, `landingPath`, `lastPath`, `firstReferrer`, `lastReferrer`, source/medium/campaign/content/term labels, or linked user `email`/`nickname`.

Summary and drill-down share one cohort and source resolver. `pagination.totalItems` matches the clicked source's `count`. The response also includes `summary` (period-wide counts for `totalVisitors`, `pageViewVisitors`, `productVisitors`, `checkoutVisitors`, `paidVisitors`, `authVisitors`, `externalVisitors`, and `campaignVisitors`). Rows include `firstSourceKey`, `lastSourceKey`, source/medium/campaign/content/term fields (`firstTerm`, `lastTerm`, `firstContent`, `lastContent`), external `firstReferrer`/`lastReferrer` URLs, `landingPath`/`lastPath`, `country`/`region`/`city`, `deviceType`/`browser`/`os`, ISO timestamps, and counts for the selected period. Row `paid`/`paidOrders` counts actual nonzero paid orders. Lifetime visitor details remain a separate endpoint; its `stats.paid` counts real related paid orders. IP details show period sources and actual paid orders for visitor identities observed at that IP; identities can appear under multiple IPs.

The sub-page `/admin/stats/visitors` (alias `/admin/visitors`) provides three top-level tabs (`visitors` / `pageVisits` / `ips`, switchable via `?tab=visitors|pageVisits|ips`) with a back button to `/admin/stats`, shared time presets and keyword search (`GET /api/admin/stats/visitors`, `GET /api/admin/stats/page-visits`, and `GET /api/admin/stats/events` all support `search`), clickable external referrer links, clickable internal page paths, full geographic region (`country · region / city`), and device/browser/OS details. Clicking any overview card (`pageVisits`, `uniqueVisitors`, `todayIp`, etc.) or source row on `/admin/stats` navigates directly to `/admin/stats/visitors` with the corresponding tab and filter query parameters. Loading, successful empty results and request failures are distinct states; a failed request shows a retry action instead of an empty table or zero-result pagination. Summary request failures also show a retry action instead of zero-valued charts.

## Public Page Tracking

**Endpoint:** `POST /api/analytics/track`

Accepts only `page_view` and `product_view`, with a frontend-relative `path`, optional `referrer` and optional positive integer `productId`. Admin/API paths and browser-submitted `auth`, `begin_checkout`, or `order_paid` return `400`. User identity comes from the server session; clients cannot supply order or authentication facts.

An explicit null/empty document referrer stays empty; the analytics POST's own Referer is not treated as acquisition. SPA navigation sends the previous page as its referrer. The mounted/finished hooks are deduplicated per navigation, while genuine revisits are counted even within 15 seconds. If `sendBeacon` declines to queue, the client falls back to a keepalive fetch.

Login, checkout and payment events inherit stored acquisition and cannot rewrite it. Frontend `/callback/**` pages (including locale-prefixed paths) still count activity but do not establish acquisition, so a payment provider cannot replace the original source. Telemetry failures log a warning and return `success: false`; they do not interrupt authentication, checkout or fulfillment.

## Dashboard Alignment

`GET /api/admin/dashboard?range=today|7d|30d` uses the same visitor cohort and `periodPaidVisitors / periodVisitors` conversion definition. `periodRevenue`, `periodRevenueByCurrency`, `periodPaidOrders` and revenue chart points use nonzero orders paid during the range, even if created earlier. `periodOrders` and order chart points count all orders created during the range. In addition to `chart.revenue` and `chart.orders`, `chart` also returns `visitors` and `pageViews` series across the same hourly (`today`) or daily (`7d` / `30d`) buckets, and `trafficInsights` returns period source distribution (`sources`, `topSources`), `topPages`, `topCountries`, `devices`, and `recentVisitors` so non-commerce sites automatically default to live traffic trends and visitor insights instead of empty revenue panels. `stats` includes user growth and engagement metrics (`periodNewUsers`, `periodLoginVisitors`, `periodExternalVisitors`, `activeNewsletterSubscribers`, `totalPromoInvites`, `isCommerceActive`), and `actionItems` includes general operational and 24-hour system health counters (`pendingComments`, `pendingPromoApplications`, `failedEmails24h`, `errorLogs24h`, `paymentFailures24h`). The range uses the configured timezone, includes the current day, and ends at request time. All-time `totalRevenue` retains its existing all-paid-order scope.

## Daily Visitor Rollup (Stats Read Path)

`GET /api/admin/stats`, `GET /api/admin/dashboard`, `GET /api/admin/stats/visitors`, `GET /api/admin/stats/ip-details` and the geo conversions of `GET /api/admin/settings/seo-telemetry` read the daily visitor rollup by default, so request cost no longer grows with the selected range. Raw event endpoints (`stats/events`, `stats/page-visits`, `stats/visitors/:visitor_id`) still query raw events.

**Data and semantics:**

- Three core tables: `visitor_rollup_days` (per-day pointer, rollup version, timezone, site host and distinct hash sets), `visitor_day_facts` (one row per visitor per day) and `visitor_daily_stats` (day × dimension × value). Only immutable visit-event facts are stored; order amounts and status are read live on every request, so refunds show up immediately.
- Each day is computed with the existing single-day report logic, so **single-day reports match the live computation field by field** (enforced by the guard). Days follow `settings.timezone`.
- Multi-day ranges: overview UV, unique IPs and behaviour counts are de-duplicated across days with daily 32-bit hash sets (collision error ≈ n/2³³, about 0.01% at 900k visitors, only ever undercounting); trend, funnel and comparisons match the live computation. **Dimension counts (sources, countries, devices, pages, landing pages) are visitor-days**: a visitor active on N days counts N times, last touch is per day, orders attach to the visitor's record on the payment day, paid counts are visitor-days too, and percentages use total visitor-days. Multi-day dimensions therefore equal the sum of the daily reports.
- Visitor list rows are one visitor on one day (new `statDate` field); `pagination.totalItems` matches the source `count` on the overview, and in multi-day ranges `summary.totalVisitors` is the visitor-day total.
- The rolled-up visitor set is fixed: a visitor that only exists because of an order keeps counting for that day if the order is refunded later (paid counts and revenue still drop live).
- Today's rollup refreshes on demand and lags at most 60 seconds (`APAY_VISITOR_STATS_TODAY_REFRESH_SECONDS`); a day is finalised 5 minutes after it ends. The "yesterday same time" comparison still queries the first part of yesterday live.
- Responses include `rollup`: `source` (`rollup` / `raw`), `complete`, `pendingDays` (days not generated within this request's time budget, missing for now) and `staleDays` (days whose rollup is outdated but whose raw events are gone, kept as-is). The dashboard returns the same under `trafficInsights.rollup`.

**Generation and maintenance:**

- Missing days are computed on demand within a ~1.5 s budget per request; the rest are reported in `pendingDays`.
- Scheduled job `POST /api/cron/visitor-stats-rollup` (`CRON_SECRET` bearer) backfills missing days and cleans up by retention day by day; register it in `/admin/scheduler` as `hourly` with `useCronSecret`.
- Admin rebuild `POST /api/admin/stats/rollup` with body `{ from, to, force? }` (`YYYY-MM-DD`, at most 31 days per call, the rest returned in `remainingDays`); `force` only recomputes days whose raw events are fully retained, others are listed in `skippedDays`.
- After changing the timezone, site host or rollup version, retained days are recomputed on demand; days whose raw events were cleaned keep the old result and appear in `staleDays`.
- The site host comes from `settings.site_url`, then `NUXT_PUBLIC_SITE_URL`, then the admin request host; when none is available the endpoints fall back to live computation (the cron job returns 409).
- Retention: `settings.visitor_events_retention_days` (raw events, default 90, `0` disables) and `settings.visitor_day_facts_retention_days` (visitor-day facts, default 180); `visitor_daily_stats` is kept permanently. Raw events are only deleted for finalised days and cleanup stops at the first day that is not rolled up; the manual `POST /api/admin/stats/cleanup` also rolls up first and returns the new `requestedCutoff / limitedByRollup`. The cleaned boundary is recorded in `settings.visitor_events_cleaned_before`.
- `APAY_VISITOR_STATS_ROLLUP=off` falls back to live per-visitor computation everywhere (for troubleshooting; the memory and latency risk of long ranges returns with it).

## Compatibility, Retention and Validation

These definitions replace the older descriptions that treated internal navigation as new direct acquisition, all UTM traffic as paid, and source `paid` as an order count. Those descriptions are historical, not current API rules. New server-only event restrictions do not establish the provenance of older client-submitted auth events.

No schema migration, order status update, commission change or historical-data rewrite is performed. A code rollback restores the old read/capture logic without dropping data. Existing source details before the period and deleted events cannot be fully reconstructed. Revenue currently reads orders still in `paid` status; refunds can change totals, and refund-time reporting/net revenue require a separate payment/refund ledger. This report is not an immutable financial ledger.

The stats read path now uses the daily visitor rollup (see the previous section); only the `APAY_VISITOR_STATS_ROLLUP=off` fallback still loads period events in application memory. Sessions, cross-product referral configuration, 30-day attribution windows, per-order snapshots, theme event coverage and a true sequential funnel remain follow-up work.

Run `npm run check:visitor-analytics`. It is also included in `prebuild` and executes real SQLite handlers against a disposable database, with currency/time/source consistency checks, failure isolation, all three SQL predicate encoders, SPA tracking behavior and Vue compilation. The real page setup also verifies source-modal requests, loading, retry and reopening. Live traffic and payment gateways require separate deployment verification.
