import type { Payload } from 'payload' import type { StatsVisit } from '../collection.js' import type { StatsSummary } from '../summarize.js' import { STATS_SLUG } from '../collection.js' import { lastDays, summarize } from '../summarize.js' const VISIT_FIELDS = { day: true, device: true, entry: true, exit: true, lastAt: true, pageCount: true, pages: true, referrer: true, startedAt: true, visitorId: true, } as const /** Summary of the last `days` days. Callers check the user is an admin first. */ export async function loadStats(payload: Payload, { days = 30, timeZone = 'Europe/Warsaw' } = {}): Promise { const range = lastDays(days, timeZone) const { docs } = await payload.find({ collection: STATS_SLUG as never, depth: 0, overrideAccess: true, pagination: false, select: VISIT_FIELDS as never, where: { day: { greater_than_equal: range[0] } }, }) return summarize(docs as unknown as StatsVisit[], range) } /** Every stored visit of one consenting visitor, newest first. */ export async function loadVisitor(payload: Payload, visitorId: string): Promise { const { docs } = await payload.find({ collection: STATS_SLUG as never, depth: 0, limit: 500, overrideAccess: true, pagination: false, select: VISIT_FIELDS as never, sort: '-startedAt', where: { visitorId: { equals: visitorId } }, }) return docs as unknown as StatsVisit[] } /** Latest visits that carry a visitor id — the entry points into visitor history. */ export async function loadRecentVisitors(payload: Payload, limit = 20): Promise { const { docs } = await payload.find({ collection: STATS_SLUG as never, depth: 0, limit, overrideAccess: true, select: VISIT_FIELDS as never, sort: '-lastAt', where: { visitorId: { exists: true } }, }) return docs as unknown as StatsVisit[] }