Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

feat(analytics): add ECharts trends, range picker and daily archives

Timothy Yin4cee356724fb
diff --git a/apps/cloud/app/pages/analytics.vue b/apps/cloud/app/pages/analytics.vue
index f2b78ae0..55b39684 100644
--- a/apps/cloud/app/pages/analytics.vue
+++ b/apps/cloud/app/pages/analytics.vue
@@ -1,4 +1,5 @@
<script setup lang="ts">
+import { relativeRange } from '#saas-ui/utils/analytics-range'
definePageMeta({ layout: 'portal' })
const { locale } = useI18n()
const zh = computed(() => locale.value.startsWith('zh'))
@@ -23,12 +24,18 @@ const sites = computed(() =>
(s: any) => s.workspaceId === billing.selected.value,
),
)
-const siteId = ref(''),
- to = ref(new Date().toISOString().slice(0, 10)),
- from = ref(new Date(Date.now() - 6 * 86400000).toISOString().slice(0, 10))
+const siteId = ref('')
+const range = useState('workspace-analytics-range', () =>
+ relativeRange(7 * 86400),
+)
const report = ref<any>(),
loading = ref(false),
error = ref('')
+function refreshRange() {
+ if (range.value.preset && !range.value.allTime)
+ range.value = relativeRange(range.value.preset)
+ void load()
+}
let generation = 0
async function load() {
const request = ++generation
@@ -40,8 +47,9 @@ async function load() {
query: {
workspaceId: billing.selected.value,
siteId: siteId.value || undefined,
- from: from.value,
- to: to.value,
+ from: range.value.from,
+ to: range.value.to,
+ allTime: range.value.allTime ? '1' : undefined,
},
timeout: 20000,
})
@@ -86,6 +94,7 @@ await load()
>{{ tr('Site', '站点')
}}<select
v-model="siteId"
+ @change="load"
class="cf-input"
>
<option value="">{{ tr('All sites', '全部站点') }}</option>
@@ -98,32 +107,28 @@ await load()
</option>
</select></label
>
- <label class="grid gap-2"
- >{{ tr('From (UTC)', '开始日期(UTC)')
- }}<input
- v-model="from"
- type="date"
- required
- class="cf-input"
- /></label>
- <label class="grid gap-2"
- >{{ tr('To (UTC)', '结束日期(UTC)')
- }}<input
- v-model="to"
- type="date"
- required
- class="cf-input"
- /></label>
+ <CfAnalyticsRange
+ v-model="range"
+ :zh="zh"
+ :disabled="loading"
+ @apply="load"
+ />
<CfButton
- type="submit"
+ type="button"
+ variant="secondary"
:disabled="loading"
- >{{ tr('Apply', '应用') }}</CfButton
- >
+ :aria-label="tr('Refresh', '刷新')"
+ :title="tr('Refresh', '刷新')"
+ @click="refreshRange"
+ ><UIcon
+ name="i-lucide-refresh-cw"
+ class="size-4"
+ /></CfButton>
<p class="cf-field-hint">
{{
tr(
- 'Select up to 31 days within the last 90 days.',
- '可查询最近 90 天内、最长 31 天的数据。',
+ 'Custom ranges support the past year; all-time reports use daily archives.',
+ '自定义范围支持最近一年;所有时间使用按天归档数据。',
)
}}
</p>
diff --git a/apps/cloud/server/plugins/analytics-archive.ts b/apps/cloud/server/plugins/analytics-archive.ts
new file mode 100644
index 00000000..8f81b4ad
--- /dev/null
+++ b/apps/cloud/server/plugins/analytics-archive.ts
@@ -0,0 +1,16 @@
+import { archiveAnalytics } from '../../../../packages/platform/src/analytics-archive'
+import type { PlatformD1 } from '../../../../packages/platform/src/index'
+export default defineNitroPlugin((app) => {
+ app.hooks.hook('cloudflare:scheduled', async ({ env }) => {
+ if (!env.DB || !env.ANALYTICS_API_TOKEN || !env.ANALYTICS_DATASET) return
+ try {
+ await archiveAnalytics(env.DB as PlatformD1, {
+ accountId: String(env.ANALYTICS_ACCOUNT_ID ?? ''),
+ token: String(env.ANALYTICS_API_TOKEN),
+ dataset: String(env.ANALYTICS_DATASET),
+ })
+ } catch {
+ console.error('analytics_archive_failed')
+ }
+ })
+})
diff --git a/apps/shared/analytics/query.ts b/apps/shared/analytics/query.ts
index a213a48a..3130b380 100644
--- a/apps/shared/analytics/query.ts
+++ b/apps/shared/analytics/query.ts
@@ -1,18 +1,26 @@
import type { H3Event } from 'h3'
import { createError } from 'h3'
+import { historicalAnalytics } from '../../../packages/platform/src/analytics-archive'
+import { analyticsWindow } from '../../../packages/platform/src/analytics'
+import { platformDatabase } from '../platform/runtime'
import { queryAnalytics } from '../../../packages/platform/src/analytics'
import type { AnalyticsFilter } from '../../../packages/platform/src/analytics'
export async function analyticsReport(event: H3Event, filter: AnalyticsFilter) {
const env = event.context.cloudflare?.env ?? {}
try {
- return await queryAnalytics(
- {
- accountId: String(env.ANALYTICS_ACCOUNT_ID ?? ''),
- token: String(env.ANALYTICS_API_TOKEN ?? ''),
- dataset: String(env.ANALYTICS_DATASET ?? ''),
- },
- filter,
+ const config = {
+ accountId: String(env.ANALYTICS_ACCOUNT_ID ?? ''),
+ token: String(env.ANALYTICS_API_TOKEN ?? ''),
+ dataset: String(env.ANALYTICS_DATASET ?? ''),
+ }
+ const window = analyticsWindow(filter.from, filter.to)
+ if (
+ filter.allTime ||
+ window.end - window.start > 31 * 86400000 ||
+ window.start < Date.now() - 89 * 86400000
)
+ return await historicalAnalytics(platformDatabase(event), config, filter)
+ return await queryAnalytics(config, filter)
} catch (error) {
throw createError({
statusCode: 503,
diff --git a/packages/platform/migrations/0038_analytics_archive.sql b/packages/platform/migrations/0038_analytics_archive.sql
new file mode 100644
index 00000000..33c89306
--- /dev/null
+++ b/packages/platform/migrations/0038_analytics_archive.sql
@@ -0,0 +1,16 @@
+CREATE TABLE platform_analytics_archive_state (
+ dataset TEXT PRIMARY KEY, start_day TEXT NOT NULL, cursor_day TEXT NOT NULL,
+ snapshot TEXT NOT NULL, phase INTEGER NOT NULL DEFAULT 0, page_offset INTEGER NOT NULL DEFAULT 0,
+ lease_token TEXT, lease_until INTEGER NOT NULL DEFAULT 0, updated_at INTEGER NOT NULL DEFAULT 0
+);
+CREATE TABLE platform_analytics_archive_days (
+ dataset TEXT NOT NULL, day TEXT NOT NULL, snapshot TEXT NOT NULL, completed_at INTEGER NOT NULL,
+ PRIMARY KEY(dataset,day)
+);
+CREATE TABLE platform_analytics_archive_rows (
+ dataset TEXT NOT NULL, snapshot TEXT NOT NULL, day TEXT NOT NULL,
+ kind TEXT NOT NULL, workspace_id INTEGER NOT NULL, site_id INTEGER NOT NULL,
+ dimension TEXT NOT NULL, label TEXT NOT NULL, pv REAL NOT NULL, uv REAL NOT NULL, sample_interval REAL NOT NULL,
+ PRIMARY KEY(dataset,snapshot,kind,workspace_id,site_id,dimension,label)
+);
+CREATE INDEX platform_analytics_archive_lookup ON platform_analytics_archive_rows(dataset,day,workspace_id,site_id,kind,dimension);
diff --git a/packages/platform/src/analytics-archive.ts b/packages/platform/src/analytics-archive.ts
new file mode 100644
index 00000000..ac95fca9
--- /dev/null
+++ b/packages/platform/src/analytics-archive.ts
@@ -0,0 +1,315 @@
+import type { PlatformD1 } from './index.ts'
+import { allRows } from './subscriptions.ts'
+import {
+ analyticsWindow,
+ queryAnalytics,
+ type AnalyticsConfig,
+ type AnalyticsFilter,
+ type AnalyticsReport,
+ type AnalyticsRow,
+} from './analytics.ts'
+const DAY = 86400000,
+ PAGE = 250
+const dimensions = [
+ ['summary', "''"],
+ ['pages', 'blob6'],
+ ['sources', 'blob8'],
+ ['countries', 'blob9'],
+ ['browsers', 'blob10'],
+ ['devices', 'blob11'],
+ ['systems', 'blob12'],
+ ['campaigns', 'blob13'],
+ ['sites', 'blob5'],
+] as const
+const phases = dimensions.length * 2
+const isoDay = (now: number) => new Date(now).toISOString().slice(0, 10)
+function configuration(config: AnalyticsConfig) {
+ if (
+ !/^[a-f0-9]{32}$/.test(config.accountId) ||
+ !config.token ||
+ !/^[a-z][a-z0-9_]{0,63}$/.test(config.dataset)
+ )
+ throw new Error('analytics_not_configured')
+}
+async function sqlRows(
+ config: AnalyticsConfig,
+ sql: string,
+ fetcher: typeof fetch,
+) {
+ const response = await fetcher(
+ `https://api.cloudflare.com/client/v4/accounts/${config.accountId}/analytics_engine/sql`,
+ {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${config.token}` },
+ body: sql,
+ signal: AbortSignal.timeout(10000),
+ },
+ )
+ if (!response.ok) {
+ const text = await response.text()
+ if (
+ response.status === 400 &&
+ /(?:unknown table|table[^\n]*(?:does not exist|not found))/i.test(text)
+ )
+ throw new Error('analytics_dataset_missing')
+ throw new Error('analytics_archive_query_failed')
+ }
+ const result = (await response.json()) as { data?: Record<string, unknown>[] }
+ if (!Array.isArray(result.data))
+ throw new Error('analytics_archive_query_failed')
+ return result.data
+}
+export async function firstAnalyticsDay(
+ config: AnalyticsConfig,
+ fetcher: typeof fetch = fetch,
+) {
+ configuration(config)
+ let rows: Record<string, unknown>[]
+ try {
+ rows = await sqlRows(
+ config,
+ `SELECT toDate(MIN(timestamp)) AS day FROM ${config.dataset} WHERE blob1='v1' FORMAT JSON`,
+ fetcher,
+ )
+ } catch (e) {
+ if (e instanceof Error && e.message === 'analytics_dataset_missing')
+ return null
+ throw e
+ }
+ const day = String(rows[0]?.day ?? '')
+ return /^\d{4}-\d{2}-\d{2}$/.test(day) && day >= '2020-01-01' ? day : null
+}
+/** Incremental, leased archive. Publish a day atomically only after every dimension/page completes. */
+export async function archiveAnalytics(
+ db: PlatformD1,
+ config: AnalyticsConfig,
+ now = Date.now(),
+ fetcher: typeof fetch = fetch,
+) {
+ configuration(config)
+ const today = isoDay(now),
+ token = crypto.randomUUID()
+ let state = await db
+ .prepare('SELECT * FROM platform_analytics_archive_state WHERE dataset=?')
+ .bind(config.dataset)
+ .first<any>()
+ if (
+ state &&
+ (state.cursor_day >= today ||
+ (state.cursor_day === isoDay(Date.parse(today) - DAY) &&
+ now < Date.parse(today) + 2 * 3600000))
+ )
+ return
+ if (!state) {
+ const first = await firstAnalyticsDay(config, fetcher)
+ if (!first) return
+ await db
+ .prepare(
+ 'INSERT OR IGNORE INTO platform_analytics_archive_state(dataset,start_day,cursor_day,snapshot) VALUES(?,?,?,?)',
+ )
+ .bind(config.dataset, first, first, crypto.randomUUID())
+ .run()
+ }
+ const claimed = await db
+ .prepare(
+ 'UPDATE platform_analytics_archive_state SET lease_token=?,lease_until=? WHERE dataset=? AND lease_until<?',
+ )
+ .bind(token, now + 300000, config.dataset, now)
+ .run()
+ if (!claimed.meta.changes) return
+ try {
+ for (let step = 0; step < 12; step++) {
+ state = await db
+ .prepare(
+ 'SELECT * FROM platform_analytics_archive_state WHERE dataset=? AND lease_token=?',
+ )
+ .bind(config.dataset, token)
+ .first<any>()
+ if (!state || state.cursor_day >= today) return
+ if (state.cursor_day < isoDay(now - 93 * DAY))
+ throw new Error('analytics_archive_retention_gap')
+ // Allow Analytics Engine ingestion to settle before finalizing yesterday.
+ if (
+ state.cursor_day === isoDay(Date.parse(today) - DAY) &&
+ now < Date.parse(today) + 2 * 3600000
+ )
+ return
+ if (state.phase >= phases) {
+ const next = isoDay(Date.parse(state.cursor_day) + DAY)
+ await db.batch([
+ db
+ .prepare(
+ 'INSERT INTO platform_analytics_archive_days(dataset,day,snapshot,completed_at) SELECT dataset,cursor_day,snapshot,? FROM platform_analytics_archive_state WHERE dataset=? AND lease_token=? ON CONFLICT(dataset,day) DO UPDATE SET snapshot=excluded.snapshot,completed_at=excluded.completed_at',
+ )
+ .bind(now, config.dataset, token),
+ db
+ .prepare(
+ 'DELETE FROM platform_analytics_archive_rows WHERE dataset=? AND day=? AND snapshot<>? AND EXISTS(SELECT 1 FROM platform_analytics_archive_state WHERE dataset=? AND lease_token=?)',
+ )
+ .bind(
+ config.dataset,
+ state.cursor_day,
+ state.snapshot,
+ config.dataset,
+ token,
+ ),
+ db
+ .prepare(
+ 'UPDATE platform_analytics_archive_state SET cursor_day=?,snapshot=?,phase=0,page_offset=0,updated_at=? WHERE dataset=? AND lease_token=?',
+ )
+ .bind(next, crypto.randomUUID(), now, config.dataset, token),
+ ])
+ continue
+ }
+ const [dimension, column] = dimensions[Math.floor(state.phase / 2)]!
+ const perSite = state.phase % 2 === 1
+ const end = isoDay(Date.parse(state.cursor_day) + DAY)
+ const sql = `SELECT blob2 AS kind,blob3 AS workspaceId,${perSite ? 'blob4' : "'0'"} AS siteId,${column} AS label,SUM(_sample_interval) AS pv,COUNT(DISTINCT blob7) AS uv,MAX(_sample_interval) AS sampleInterval FROM ${config.dataset} WHERE blob1='v1' AND timestamp>=toDateTime('${state.cursor_day} 00:00:00') AND timestamp<toDateTime('${end} 00:00:00')${perSite ? " AND blob2='site'" : ''} GROUP BY kind,workspaceId,siteId,label ORDER BY kind,workspaceId,siteId,label LIMIT ${PAGE} OFFSET ${state.page_offset} FORMAT JSON`
+ const rows = await sqlRows(config, sql, fetcher)
+ if (
+ rows.some(
+ (row) =>
+ !['website', 'portal', 'site'].includes(String(row.kind)) ||
+ !Number.isSafeInteger(Number(row.workspaceId)) ||
+ Number(row.workspaceId) < 0 ||
+ !Number.isSafeInteger(Number(row.siteId)) ||
+ Number(row.siteId) < 0 ||
+ !Number.isFinite(Number(row.pv)) ||
+ !Number.isFinite(Number(row.uv)) ||
+ !Number.isFinite(Number(row.sampleInterval)),
+ )
+ )
+ throw new Error('invalid_analytics_archive_rows')
+ await db.batch([
+ db
+ .prepare(
+ `INSERT INTO platform_analytics_archive_rows(dataset,snapshot,day,kind,workspace_id,site_id,dimension,label,pv,uv,sample_interval) SELECT ?,?,?,json_extract(value,'$.kind'),CAST(json_extract(value,'$.workspaceId') AS INTEGER),CAST(json_extract(value,'$.siteId') AS INTEGER),?,COALESCE(json_extract(value,'$.label'),''),json_extract(value,'$.pv'),json_extract(value,'$.uv'),json_extract(value,'$.sampleInterval') FROM json_each(?) WHERE EXISTS(SELECT 1 FROM platform_analytics_archive_state WHERE dataset=? AND lease_token=?) ON CONFLICT(dataset,snapshot,kind,workspace_id,site_id,dimension,label) DO UPDATE SET pv=excluded.pv,uv=excluded.uv,sample_interval=excluded.sample_interval`,
+ )
+ .bind(
+ config.dataset,
+ state.snapshot,
+ state.cursor_day,
+ dimension,
+ JSON.stringify(rows),
+ config.dataset,
+ token,
+ ),
+ db
+ .prepare(
+ 'UPDATE platform_analytics_archive_state SET phase=?,page_offset=?,updated_at=? WHERE dataset=? AND lease_token=?',
+ )
+ .bind(
+ rows.length === PAGE ? state.phase : state.phase + 1,
+ rows.length === PAGE ? state.page_offset + PAGE : 0,
+ now,
+ config.dataset,
+ token,
+ ),
+ ])
+ }
+ } finally {
+ await db
+ .prepare(
+ 'UPDATE platform_analytics_archive_state SET lease_until=0,lease_token=NULL WHERE dataset=? AND lease_token=?',
+ )
+ .bind(config.dataset, token)
+ .run()
+ }
+}
+export async function historicalAnalytics(
+ db: PlatformD1,
+ config: AnalyticsConfig,
+ filter: AnalyticsFilter,
+ now = Date.now(),
+ fetcher: typeof fetch = fetch,
+): Promise<AnalyticsReport> {
+ configuration(config)
+ const state = await db
+ .prepare('SELECT * FROM platform_analytics_archive_state WHERE dataset=?')
+ .bind(config.dataset)
+ .first<any>()
+ const first =
+ state?.start_day ??
+ (await firstAnalyticsDay(config, fetcher)) ??
+ isoDay(now)
+ const start = filter.allTime
+ ? first
+ : isoDay(analyticsWindow(filter.from, filter.to).start)
+ const end = filter.allTime
+ ? isoDay(now)
+ : isoDay(analyticsWindow(filter.from, filter.to).end - 1)
+ const from = start < first ? first : start
+ const cutoff = state?.cursor_day ?? first
+ const values: (string | number)[] = [config.dataset, from, end, cutoff]
+ let scope = 'r.dataset=? AND r.day>=? AND r.day<=? AND r.day<?'
+ if (filter.kind) {
+ scope += ' AND r.kind=?'
+ values.push(filter.kind)
+ }
+ if (filter.workspaceId) {
+ scope += ' AND r.workspace_id=?'
+ values.push(filter.workspaceId)
+ }
+ scope += ' AND r.site_id=?'
+ values.push(filter.siteId ?? 0)
+ let raw: AnalyticsReport | null = null
+ if (end >= cutoff && from <= end)
+ raw = await queryAnalytics(
+ config,
+ {
+ ...filter,
+ allTime: false,
+ from: [from, cutoff, isoDay(now - 93 * DAY)].sort().at(-1)!,
+ to: end,
+ },
+ fetcher,
+ { bucket: 'day', limit: 5000 },
+ )
+ const source = `FROM platform_analytics_archive_rows r JOIN platform_analytics_archive_days d ON d.dataset=r.dataset AND d.day=r.day AND d.snapshot=r.snapshot WHERE ${scope}`
+ const result = await Promise.all(
+ dimensions.map(async ([dimension]) => {
+ const live =
+ dimension === 'summary'
+ ? raw
+ ? [{ ...raw.summary, label: '' }]
+ : []
+ : (raw?.[dimension] ?? [])
+ const rows = await allRows<AnalyticsRow>(
+ db
+ .prepare(
+ `WITH combined AS (SELECT r.label AS label,SUM(r.pv) AS pv,SUM(r.uv) AS uv,MAX(r.sample_interval) AS sampleInterval ${source} AND r.dimension=? GROUP BY r.label UNION ALL SELECT json_extract(value,'$.label'),json_extract(value,'$.pv'),json_extract(value,'$.uv'),json_extract(value,'$.sampleInterval') FROM json_each(?)) SELECT label,SUM(pv) AS pv,SUM(uv) AS uv,MAX(sampleInterval) AS sampleInterval FROM combined GROUP BY label ORDER BY pv DESC,label LIMIT 20`,
+ )
+ .bind(...values, dimension, JSON.stringify(live)),
+ )
+ return [dimension, rows] as const
+ }),
+ )
+ const data = Object.fromEntries(result)
+ const daily = await allRows<AnalyticsRow>(
+ db
+ .prepare(
+ `WITH combined AS (SELECT r.day AS label,SUM(r.pv) AS pv,SUM(r.uv) AS uv,MAX(r.sample_interval) AS sampleInterval ${source} AND r.dimension='summary' GROUP BY r.day UNION ALL SELECT json_extract(value,'$.label'),json_extract(value,'$.pv'),json_extract(value,'$.uv'),json_extract(value,'$.sampleInterval') FROM json_each(?)) SELECT label,SUM(pv) AS pv,SUM(uv) AS uv,MAX(sampleInterval) AS sampleInterval FROM combined GROUP BY label ORDER BY label`,
+ )
+ .bind(...values, JSON.stringify(raw?.daily ?? [])),
+ )
+ return {
+ ...data,
+ from,
+ to: end,
+ bucket: 'day',
+ daily,
+ summary: data.summary?.[0] ?? {
+ label: '',
+ pv: 0,
+ uv: 0,
+ sampleInterval: 1,
+ },
+ notInitialized: !data.summary?.[0]?.pv && (raw?.notInitialized ?? false),
+ archived: true,
+ coverageStart: first,
+ archiveGap: cutoff < isoDay(now - 89 * DAY),
+ detailsLimited:
+ !!raw &&
+ dimensions.some(([d]) => d !== 'summary' && raw![d].length >= 5000),
+ } as AnalyticsReport
+}
diff --git a/packages/platform/src/analytics.ts b/packages/platform/src/analytics.ts
index d11469d2..df7bc996 100644
--- a/packages/platform/src/analytics.ts
+++ b/packages/platform/src/analytics.ts
@@ -12,32 +12,75 @@ export type AnalyticsConfig = {
export type AnalyticsFilter = {
from: string
to: string
+ allTime?: boolean
kind?: VisitScope['kind']
workspaceId?: number
siteId?: number
}
+export type AnalyticsBucket = 'minute' | 'hour' | 'day'
+/** Legacy date-only ranges include the end date; timestamp ranges are half-open. */
+export function analyticsWindow(from: string, to: string) {
+ const pattern = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z)?$/
+ if (!pattern.test(from) || !pattern.test(to))
+ throw new Error('invalid_analytics_range')
+ const start = Date.parse(from),
+ end = Date.parse(to) + (to.length === 10 ? 86400000 : 0)
+ if (
+ !Number.isFinite(start) ||
+ !Number.isFinite(end) ||
+ start >= end ||
+ end - start > 367 * 86400000
+ )
+ throw new Error('invalid_analytics_range')
+ if (
+ new Date(start).toISOString().slice(0, 10) !== from.slice(0, 10) ||
+ new Date(Date.parse(to)).toISOString().slice(0, 10) !== to.slice(0, 10)
+ )
+ throw new Error('invalid_analytics_range')
+ const bucket: AnalyticsBucket =
+ end - start <= 3600000
+ ? 'minute'
+ : end - start <= 2 * 86400000
+ ? 'hour'
+ : 'day'
+ return { start, end, bucket }
+}
export function analyticsFilter(
input: Record<string, unknown>,
now = Date.now(),
): AnalyticsFilter {
+ const allTime = [true, '1', 'true'].includes(
+ input.allTime as boolean | string,
+ )
const today = new Date(now).toISOString().slice(0, 10)
const from = String(
- input.from ?? new Date(now - 6 * 86400000).toISOString().slice(0, 10),
+ (!allTime ? input.from : undefined) ??
+ new Date(now - 6 * 86400000).toISOString().slice(0, 10),
)
- const to = String(input.to ?? today)
- const date = (s: string) =>
- /^\d{4}-\d{2}-\d{2}$/.test(s) &&
- new Date(s).toISOString().slice(0, 10) === s
+ const to = String((!allTime ? input.to : undefined) ?? today)
+ const window = analyticsWindow(from, to)
if (
- !date(from) ||
- !date(to) ||
- from > to ||
- to > today ||
- Date.parse(to) - Date.parse(from) > 30 * 86400000 ||
- Date.parse(from) < Date.parse(today) - 89 * 86400000
+ window.start <
+ Date.UTC(
+ new Date(now).getUTCFullYear() - 1,
+ new Date(now).getUTCMonth(),
+ new Date(now).getUTCDate(),
+ ) ||
+ (to.length === 10 ? to > today : window.end > now + 60000)
)
throw new Error('invalid_analytics_range')
const filter: AnalyticsFilter = { from, to }
+ if (input.allTime !== undefined) {
+ if (
+ ![true, false, '1', '0', 'true', 'false'].includes(
+ input.allTime as boolean | string,
+ )
+ )
+ throw new Error('invalid_analytics_range')
+ filter.allTime = [true, '1', 'true'].includes(
+ input.allTime as boolean | string,
+ )
+ }
if (input.kind !== undefined && input.kind !== '') {
if (!['website', 'portal', 'site'].includes(String(input.kind)))
throw new Error('invalid_analytics_kind')
@@ -175,18 +218,25 @@ export async function visitorHash(
b.toString(16).padStart(2, '0'),
).join('')
}
-export function analyticsQueries(dataset: string, filter: AnalyticsFilter) {
+export function analyticsQueries(
+ dataset: string,
+ filter: AnalyticsFilter,
+ options: { bucket?: AnalyticsBucket; limit?: number } = {},
+) {
if (!/^[a-z][a-z0-9_]{0,63}$/.test(dataset))
throw new Error('invalid_analytics_dataset')
- if (
- !/^\d{4}-\d{2}-\d{2}$/.test(filter.from) ||
- !/^\d{4}-\d{2}-\d{2}$/.test(filter.to) ||
- (filter.kind && !['website', 'portal', 'site'].includes(filter.kind))
- )
+ const window = analyticsWindow(filter.from, filter.to)
+ if (options.bucket) window.bucket = options.bucket
+ const limit = options.limit ?? 20
+ if (!Number.isInteger(limit) || limit < 1 || limit > 5000)
+ throw new Error('invalid_analytics_limit')
+ if (filter.kind && !['website', 'portal', 'site'].includes(filter.kind))
throw new Error('invalid_analytics_filter')
+ const sqlDate = (value: number) =>
+ new Date(value).toISOString().slice(0, 19).replace('T', ' ')
const terms = [
- `timestamp >= toDateTime('${filter.from} 00:00:00')`,
- `timestamp < toDateTime('${new Date(Date.parse(filter.to) + 86400000).toISOString().slice(0, 10)} 00:00:00')`,
+ `timestamp >= toDateTime('${sqlDate(window.start)}')`,
+ `timestamp < toDateTime('${sqlDate(window.end)}')`,
`blob1 = 'v1'`,
]
if (filter.kind) terms.push(`blob2 = '${filter.kind}'`)
@@ -205,10 +255,10 @@ export function analyticsQueries(dataset: string, filter: AnalyticsFilter) {
const metrics =
'SUM(_sample_interval) AS pv, COUNT(DISTINCT blob7) AS uv, MAX(_sample_interval) AS sampleInterval'
const group = (column: string) =>
- `SELECT ${column} AS label, ${metrics} FROM ${where} GROUP BY label ORDER BY pv DESC LIMIT 20 FORMAT JSON`
+ `SELECT ${column} AS label, ${metrics} FROM ${where} GROUP BY label ORDER BY pv DESC LIMIT ${limit} FORMAT JSON`
return {
summary: `SELECT ${metrics} FROM ${where} FORMAT JSON`,
- daily: `SELECT toDate(timestamp) AS label, ${metrics} FROM ${where} GROUP BY label ORDER BY label FORMAT JSON`,
+ daily: `SELECT ${window.bucket === 'minute' ? 'toStartOfMinute(timestamp)' : window.bucket === 'hour' ? 'toStartOfHour(timestamp)' : 'toDate(timestamp)'} AS label, ${metrics} FROM ${where} GROUP BY label ORDER BY label FORMAT JSON`,
pages: group('blob6'),
sources: group('blob8'),
countries: group('blob9'),
@@ -226,6 +276,11 @@ export type AnalyticsRow = {
sampleInterval: number
}
export type AnalyticsReport = {
+ archived?: boolean
+ coverageStart?: string
+ detailsLimited?: boolean
+ archiveGap?: boolean
+ bucket: AnalyticsBucket
from: string
to: string
summary: AnalyticsRow
@@ -245,11 +300,17 @@ export async function queryAnalytics(
config: AnalyticsConfig,
filter: AnalyticsFilter,
fetcher: typeof fetch = fetch,
+ options: { bucket?: AnalyticsBucket; limit?: number } = {},
): Promise<AnalyticsReport> {
if (!/^[a-f0-9]{32}$/.test(config.accountId) || !config.token)
throw new Error('analytics_not_configured')
- const queries = analyticsQueries(config.dataset, filter)
- const cacheKey = JSON.stringify([config.accountId, config.dataset, filter])
+ const queries = analyticsQueries(config.dataset, filter, options)
+ const cacheKey = JSON.stringify([
+ config.accountId,
+ config.dataset,
+ filter,
+ options,
+ ])
const cached = cache.get(cacheKey)
if (cached && cached.until > Date.now()) return cached.value
let notInitialized = false
@@ -303,6 +364,7 @@ export async function queryAnalytics(
const data = Object.fromEntries(result)
const report = {
...data,
+ bucket: options.bucket ?? analyticsWindow(filter.from, filter.to).bucket,
from: filter.from,
to: filter.to,
summary: data.summary?.[0] ?? {
diff --git a/packages/platform/src/legal-defaults.ts b/packages/platform/src/legal-defaults.ts
index 28959d6d..4fc68982 100644
--- a/packages/platform/src/legal-defaults.ts
+++ b/packages/platform/src/legal-defaults.ts
@@ -87,7 +87,7 @@ Published gallery content is disclosed according to its visibility settings. Inf
We use authentication cookies and local preferences necessary for sign-in, account security, language and appearance. We do not describe all cookies as advertising cookies. If optional analytics or marketing technologies are introduced, we will provide the disclosures and choices required by applicable law.
### Visitor analytics
-We use Cloudflare Workers Analytics Engine to measure page views, daily unique visitors, referring hostnames, country/region, device and browser categories, and campaign labels across our website, portal and hosted galleries. We do not store raw IP addresses, full user agents, URL query strings or analytics cookies in this dataset. IP addresses and browser information are used transiently to derive a daily rotating keyed anonymous identifier. We honor Do Not Track and Global Privacy Control signals. Authorized gallery owners may view aggregate statistics for their workspace where their plan includes analytics; platform staff access is permission-controlled. Cross-day UV is the sum of daily unique visitors. Cloudflare may sample results. Analytics records are retained by Analytics Engine for up to three months.
+We use Cloudflare Workers Analytics Engine to measure page views, daily unique visitors, referring hostnames, country/region, device and browser categories, and campaign labels across our website, portal and hosted galleries. We do not store raw IP addresses, full user agents, URL query strings or analytics cookies in this dataset. IP addresses and browser information are used transiently to derive a daily rotating keyed anonymous identifier. We honor Do Not Track and Global Privacy Control signals. Authorized gallery owners may view aggregate statistics for their workspace where their plan includes analytics; platform staff access is permission-controlled. Cross-day UV is the sum of daily unique visitors. Cloudflare may sample results. Analytics Engine retains detailed records for up to three months. We retain daily aggregate counts separately for long-term and all-time reporting, without visitor identifiers.
## 6. Retention and deletion
We retain information as needed to provide the service, protect accounts, resolve disputes and satisfy legal obligations. Content remains until you remove it or applicable account lifecycle rules require cleanup. Unverified or inactive accounts may receive deletion notices with specific deadlines. After an account is marked for deletion, sign-in is disabled and a retention period allows a support restoration request; permanent cleanup follows when that period ends. Quotas, exemptions and lifecycle settings can affect the applicable process. Billing, security or legally required records may have different retention requirements. Copies in backups, caches or third-party systems may take additional time to expire. Your independently operated bucket and provider contract remain under your control.
@@ -123,7 +123,7 @@ The effective date and latest revision appear on this page. We will provide appr
平台使用登录、安全、语言及外观等必要的 Cookie 和本地偏好设置。这些功能不等同于广告追踪。未来如引入可选分析或营销技术,我们会提供适用法律要求的说明与选择。
### 访问统计
-我们使用 Cloudflare Workers Analytics Engine 统计官网、门户及托管站点的页面浏览量、每日独立访客、来源域名、国家/地区、设备与浏览器类别及推广活动标签。该数据集不保存原始 IP、完整浏览器信息、URL 查询参数,也不设置分析 Cookie。IP 和浏览器信息仅用于即时生成每日轮换的匿名密钥标识;我们遵循 Do Not Track 与 Global Privacy Control 信号。具有套餐权益的图库用户可查看所属工作区的汇总数据,平台人员访问受权限控制。跨天 UV 表示每日独立访客合计,Cloudflare 可能对结果采样。Analytics Engine 中的统计记录最长保留三个月。
+我们使用 Cloudflare Workers Analytics Engine 统计官网、门户及托管站点的页面浏览量、每日独立访客、来源域名、国家/地区、设备与浏览器类别及推广活动标签。该数据集不保存原始 IP、完整浏览器信息、URL 查询参数,也不设置分析 Cookie。IP 和浏览器信息仅用于即时生成每日轮换的匿名密钥标识;我们遵循 Do Not Track 与 Global Privacy Control 信号。具有套餐权益的图库用户可查看所属工作区的汇总数据,平台人员访问受权限控制。跨天 UV 表示每日独立访客合计,Cloudflare 可能对结果采样。Analytics Engine 中的明细最长保留三个月;每日汇总计数会单独保存,用于长期及所有时间报表,不包含访客标识。
## 六、保存与删除
我们按提供服务、保护账号、解决争议及履行法律义务所需的期限保存信息。内容可因您的删除操作或适用的账号生命周期规则被清理。未验证或不活跃账号可能收到包含具体日期的删除通知。账号被标记删除后将无法登录,保留期内可联系客服申请恢复,保留期结束后进行永久清理;配额、豁免和生命周期设置可能影响具体流程。计费、安全或依法必须留存的记录可能适用不同期限。备份、缓存及第三方系统中的副本可能需要额外时间到期。您自行运营的存储桶和相关服务合同仍由您控制。
diff --git a/packages/saas-ui/app/components/CfAnalyticsRange.vue b/packages/saas-ui/app/components/CfAnalyticsRange.vue
new file mode 100644
index 00000000..092bfb6c
--- /dev/null
+++ b/packages/saas-ui/app/components/CfAnalyticsRange.vue
@@ -0,0 +1,428 @@
+<script setup lang="ts">
+import { parseDate, type CalendarDate } from '@internationalized/date'
+import {
+ ANALYTICS_PRESETS,
+ inputInstant,
+ rangeInput,
+ relativeRange,
+ type AnalyticsDateRange,
+} from '../utils/analytics-range'
+const props = defineProps<{
+ modelValue: AnalyticsDateRange
+ zh?: boolean
+ disabled?: boolean
+}>()
+const emit = defineEmits<{
+ 'update:modelValue': [AnalyticsDateRange]
+ apply: []
+}>()
+const tr = (en: string, zh: string) => (props.zh ? zh : en)
+const open = ref(false),
+ utc = ref(false),
+ custom = ref(''),
+ draftFrom = ref(''),
+ draftTo = ref(''),
+ preset = ref<number>(),
+ error = ref('')
+const selected = ref<{ start?: CalendarDate; end?: CalendarDate }>({})
+const allTime = ref(false)
+const zoneLabel = computed(
+ () => Intl.DateTimeFormat().resolvedOptions().timeZone,
+)
+function manualEdit() {
+ preset.value = undefined
+ allTime.value = false
+}
+function title(seconds: number) {
+ const unit =
+ seconds < 3600
+ ? tr('minutes', '分钟')
+ : seconds <= 86400
+ ? tr('hours', '小时')
+ : tr('days', '天')
+ const value =
+ seconds / (seconds < 3600 ? 60 : seconds <= 86400 ? 3600 : 86400)
+ return props.zh ? `过去 ${value} ${unit}` : `Past ${value} ${unit}`
+}
+const label = computed(() =>
+ props.modelValue.allTime
+ ? tr('All time', '所有时间')
+ : props.modelValue.preset
+ ? title(props.modelValue.preset)
+ : tr('Custom range', '自定义时间段'),
+)
+function syncCalendar() {
+ if (draftFrom.value && draftTo.value)
+ selected.value = {
+ start: parseDate(draftFrom.value.slice(0, 10)),
+ end: parseDate(draftTo.value.slice(0, 10)),
+ }
+}
+function useRange(range: AnalyticsDateRange) {
+ draftFrom.value = rangeInput(range.from, utc.value)
+ draftTo.value = rangeInput(range.to, utc.value)
+ allTime.value = !!range.allTime
+ preset.value = range.preset
+ error.value = ''
+ if (range.allTime) selected.value = {}
+ else syncCalendar()
+}
+watch(open, (value) => {
+ if (value) {
+ useRange(props.modelValue)
+ custom.value = ''
+ }
+})
+function choose(seconds: number) {
+ useRange(relativeRange(seconds))
+}
+function calendarChange(value: { start?: CalendarDate; end?: CalendarDate }) {
+ selected.value = value
+ allTime.value = false
+ preset.value = undefined
+ if (value.start)
+ draftFrom.value = `${value.start.toString()}T${draftFrom.value.slice(11) || '00:00'}`
+ if (value.end)
+ draftTo.value = `${value.end.toString()}T${draftTo.value.slice(11) || '23:59'}`
+}
+function customRange() {
+ const match = /^\s*(\d+(?:\.\d+)?)\s*(m|min|h|d|分钟|小时|天)\s*$/i.exec(
+ custom.value,
+ )
+ if (!match) {
+ error.value = tr(
+ 'Use a duration such as 30m, 3h or 7d.',
+ '请输入 30m、3h 或 7d 等时间段。',
+ )
+ return
+ }
+ const unit = match[2]!.toLowerCase(),
+ seconds =
+ Number(match[1]) *
+ (['m', 'min', '分钟'].includes(unit)
+ ? 60
+ : ['h', '小时'].includes(unit)
+ ? 3600
+ : 86400)
+ if (seconds < 60 || seconds > 366 * 86400) {
+ error.value = tr(
+ 'Choose between one minute and one year.',
+ '请选择一分钟至一年之间的时间段。',
+ )
+ return
+ }
+ choose(seconds)
+}
+function chooseAll() {
+ useRange({ ...relativeRange(365 * 86400), allTime: true })
+}
+function apply() {
+ if (allTime.value) {
+ emit('update:modelValue', { ...relativeRange(365 * 86400), allTime: true })
+ emit('apply')
+ open.value = false
+ return
+ }
+
+ const start = inputInstant(draftFrom.value, utc.value),
+ end = inputInstant(draftTo.value, utc.value)
+ if (
+ !Number.isFinite(start) ||
+ !Number.isFinite(end) ||
+ start >= end ||
+ end > Date.now() + 60000 ||
+ start <
+ Date.UTC(
+ new Date().getUTCFullYear() - 1,
+ new Date().getUTCMonth(),
+ new Date().getUTCDate(),
+ )
+ ) {
+ error.value = tr(
+ 'Choose a valid range within the past year.',
+ '请选择最近一年内有效的起止时间。',
+ )
+ return
+ }
+ const range = preset.value
+ ? relativeRange(preset.value)
+ : { from: new Date(start).toISOString(), to: new Date(end).toISOString() }
+ emit('update:modelValue', range)
+ emit('apply')
+ open.value = false
+}
+function changeZone() {
+ const previous = !utc.value,
+ start = inputInstant(draftFrom.value, previous),
+ end = inputInstant(draftTo.value, previous)
+ if (Number.isFinite(start) && Number.isFinite(end))
+ useRange({
+ from: new Date(start).toISOString(),
+ to: new Date(end).toISOString(),
+ preset: preset.value,
+ allTime: allTime.value,
+ })
+}
+</script>
+<template>
+ <UPopover
+ v-model:open="open"
+ :content="{ align: 'end', sideOffset: 8 }"
+ :ui="{ content: 'p-0' }"
+ >
+ <CfButton
+ type="button"
+ variant="secondary"
+ :disabled="disabled"
+ ><UIcon
+ name="i-lucide-calendar-days"
+ class="size-4" />{{ label
+ }}<UIcon
+ name="i-lucide-chevron-down"
+ class="size-3.5"
+ /></CfButton>
+ <template #content>
+ <section
+ class="cf-range-picker"
+ :aria-label="tr('Select time range', '选择时间段')"
+ >
+ <div class="cf-range-custom">
+ <input
+ v-model="custom"
+ class="cf-input"
+ :aria-label="tr('Custom duration', '自定义时长')"
+ :placeholder="
+ tr('Custom range: 30m, 3h, 7d…', '自定义时长:30m、3h、7d…')
+ "
+ @keydown.enter.prevent="customRange"
+ /><CfButton
+ v-if="custom"
+ type="button"
+ size="sm"
+ variant="ghost"
+ @click="customRange"
+ ><UIcon
+ name="i-lucide-arrow-right"
+ class="size-4"
+ /><span class="sr-only">{{
+ tr('Use duration', '使用此时长')
+ }}</span></CfButton
+ >
+ </div>
+ <div class="cf-range-main">
+ <div class="cf-range-calendar">
+ <UCalendar
+ :model-value="selected"
+ range
+ size="sm"
+ @update:model-value="calendarChange"
+ />
+ </div>
+ <div class="cf-range-presets">
+ <button
+ v-for="seconds in ANALYTICS_PRESETS"
+ :key="seconds"
+ type="button"
+ :class="{ active: preset === seconds && !allTime }"
+ @click="choose(seconds)"
+ >
+ {{ title(seconds) }}
+ </button>
+ <div class="cf-range-long-divider"></div>
+ <button
+ type="button"
+ :class="{ active: preset === 365 * 86400 && !allTime }"
+ @click="choose(365 * 86400)"
+ >
+ {{ tr('Past year', '过去一年') }}
+ </button>
+ <button
+ type="button"
+ :class="{ active: allTime }"
+ @click="chooseAll"
+ >
+ {{ tr('All time', '所有时间') }}
+ </button>
+ </div>
+ </div>
+ <p
+ v-if="allTime"
+ class="cf-range-all-time"
+ >
+ {{
+ tr(
+ 'All recorded history, from the beginning of collection to now.',
+ '查询自开始采集以来直到现在的全部已记录数据。',
+ )
+ }}
+ </p>
+ <div
+ v-else
+ class="cf-range-inputs"
+ >
+ <label
+ >{{ tr('Start', '开始')
+ }}<input
+ v-model="draftFrom"
+ type="datetime-local"
+ class="cf-input"
+ @input="manualEdit"
+ @change="syncCalendar" /></label
+ ><label
+ >{{ tr('End', '结束')
+ }}<input
+ v-model="draftTo"
+ type="datetime-local"
+ class="cf-input"
+ @input="manualEdit"
+ @change="syncCalendar"
+ /></label>
+ </div>
+ <p
+ v-if="error"
+ class="cf-range-error"
+ role="alert"
+ >
+ {{ error }}
+ </p>
+ <footer class="cf-range-footer">
+ <select
+ v-model="utc"
+ class="cf-input"
+ :aria-label="tr('Time zone', '时区')"
+ @change="changeZone"
+ >
+ <option :value="false">
+ {{
+ zoneLabel === 'UTC' ? tr('Local time', '本地时间') : zoneLabel
+ }}
+ </option>
+ <option :value="true">UTC</option></select
+ ><CfButton
+ type="button"
+ @click="apply"
+ >{{ tr('Apply', '应用') }}</CfButton
+ >
+ </footer>
+ </section>
+ </template>
+ </UPopover>
+</template>
+<style scoped>
+.cf-range-picker {
+ width: min(540px, calc(100vw - 24px));
+ background: var(--card);
+ border-radius: 12px;
+ overflow-y: auto;
+ max-height: min(90dvh, var(--reka-popover-content-available-height, 90dvh));
+}
+.cf-range-custom {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px;
+ border-bottom: 1px solid var(--border);
+}
+.cf-range-custom .cf-input {
+ flex: 1;
+ min-width: 0;
+ border-color: transparent;
+ box-shadow: none;
+ background: transparent;
+}
+.cf-range-main {
+ display: grid;
+ grid-template-columns: 1.2fr 1fr;
+}
+.cf-range-calendar {
+ padding: 16px;
+ border-right: 1px solid var(--border);
+}
+.cf-range-presets {
+ display: grid;
+ align-content: start;
+ gap: 2px;
+ padding: 16px 12px;
+}
+.cf-range-presets button {
+ text-align: left;
+ border: 0;
+ background: transparent;
+ border-radius: 6px;
+ padding: 7px 12px;
+ font-size: 13px;
+ color: var(--foreground);
+ cursor: pointer;
+}
+.cf-range-presets button:hover,
+.cf-range-presets button.active {
+ background: var(--secondary);
+}
+.cf-range-all-time {
+ padding: 16px;
+ border-top: 1px solid var(--border);
+ font-size: 12px;
+ color: var(--muted-foreground);
+}
+.cf-range-long-divider {
+ height: 1px;
+ background: var(--border);
+ margin: 6px 0;
+}
+.cf-range-inputs {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 12px;
+ padding: 16px;
+ border-top: 1px solid var(--border);
+}
+.cf-range-inputs label {
+ display: grid;
+ gap: 6px;
+ font-size: 12px;
+ color: var(--muted-foreground);
+}
+.cf-range-inputs input {
+ width: 100%;
+ min-width: 0;
+ font-size: 12px;
+}
+.cf-range-footer {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 16px;
+ padding: 12px 16px;
+ border-top: 1px solid var(--border);
+ background: var(--background);
+}
+.cf-range-footer select {
+ width: auto;
+ max-width: 70%;
+ font-size: 12px;
+ border: 0;
+ background: transparent;
+}
+.cf-range-error {
+ font-size: 12px;
+ padding: 0 16px 12px;
+ color: var(--destructive);
+}
+@media (max-width: 480px) {
+ .cf-range-main {
+ grid-template-columns: 1fr;
+ }
+ .cf-range-calendar {
+ border-right: 0;
+ display: flex;
+ justify-content: center;
+ }
+ .cf-range-presets {
+ grid-template-columns: 1fr 1fr;
+ border-top: 1px solid var(--border);
+ }
+ .cf-range-inputs {
+ grid-template-columns: 1fr;
+ }
+}
+</style>
diff --git a/packages/saas-ui/app/components/CfAnalyticsReport.vue b/packages/saas-ui/app/components/CfAnalyticsReport.vue
index 38162f50..f3646d3a 100644
--- a/packages/saas-ui/app/components/CfAnalyticsReport.vue
+++ b/packages/saas-ui/app/components/CfAnalyticsReport.vue
@@ -18,9 +18,6 @@ const groups = computed(() => [
tr('Campaigns (source / medium / campaign)', '推广来源/媒介/活动'),
],
])
-const peak = computed(() =>
- Math.max(1, ...props.report.daily.map((r: any) => r.pv)),
-)
</script>
<template>
<div class="cf-analytics-report">
@@ -54,6 +51,25 @@ const peak = computed(() =>
)
}}
</p>
+ <p
+ v-if="report.archived"
+ class="cf-field-hint"
+ >
+ {{ tr('Daily archive range: ', '按日归档统计范围:') }}{{ report.from }} —
+ {{ report.to }} (UTC) · {{ tr('Collection started: ', '采集起始日:')
+ }}{{ report.coverageStart }}
+ </p>
+ <p
+ v-if="report.archiveGap || report.detailsLimited"
+ role="status"
+ >
+ {{
+ tr(
+ 'Some historical detail may be incomplete. Recent traffic is still included; contact support to check archive coverage.',
+ '部分历史明细可能不完整。近期访问仍计入,请联系支持检查归档覆盖情况。',
+ )
+ }}
+ </p>
<div class="cf-analytics-metrics">
<CfStatCard
label="PV"
@@ -72,33 +88,26 @@ const peak = computed(() =>
/>
</div>
<CfCard class="cf-analytics-card">
- <h2>{{ tr('Daily traffic', '每日访问趋势') }}</h2>
- <div
- v-if="report.daily.length"
- class="cf-analytics-trend"
- role="img"
- :aria-label="
- tr(
- 'Daily page views; exact figures are in the table below.',
- '每日浏览量,具体数值见下表。',
- )
- "
- >
- <div
- v-for="row in report.daily"
- :key="row.label"
- :title="`${row.label}: ${format(row.pv)} PV · ${format(row.uv)} UV`"
- class="cf-analytics-bar"
- :style="{ height: `${Math.max(1, (row.pv / peak) * 100)}%` }"
- ></div>
- </div>
+ <h2>{{ tr('Traffic trend', '访问趋势') }}</h2>
+ <ClientOnly>
+ <LazyCfTrafficChart
+ :bucket="report.bucket"
+ :rows="report.daily"
+ :from="report.from"
+ :to="report.to"
+ :zh="zh"
+ />
+ <template #fallback
+ ><CfSkeleton class="cf-traffic-chart-placeholder"
+ /></template>
+ </ClientOnly>
<div class="cf-analytics-table-wrap">
<table class="cf-analytics-table">
<thead>
<tr>
- <th>{{ tr('Date (UTC)', '日期(UTC)') }}</th>
+ <th>{{ tr('Time (UTC)', '时间(UTC)') }}</th>
<th>PV</th>
- <th>{{ tr('Daily UV', '每日 UV') }}</th>
+ <th>UV</th>
</tr>
</thead>
<tbody>
@@ -206,19 +215,9 @@ const peak = computed(() =>
text-align: right;
white-space: nowrap;
}
-.cf-analytics-trend {
- display: flex;
- align-items: flex-end;
- gap: 4px;
- height: 140px;
- padding: 8px 0;
- margin-bottom: 16px;
-}
-.cf-analytics-bar {
- flex: 1;
- background: var(--ui-primary);
- border-radius: 3px 3px 0 0;
- min-width: 2px;
+.cf-traffic-chart-placeholder {
+ width: 100%;
+ height: 260px;
}
@media (max-width: 700px) {
.cf-analytics-metrics,
diff --git a/packages/saas-ui/app/components/CfTrafficChart.client.vue b/packages/saas-ui/app/components/CfTrafficChart.client.vue
new file mode 100644
index 00000000..532d683d
--- /dev/null
+++ b/packages/saas-ui/app/components/CfTrafficChart.client.vue
@@ -0,0 +1,57 @@
+<script setup lang="ts">
+import { use } from 'echarts/core'
+import { LineChart } from 'echarts/charts'
+import {
+ AriaComponent,
+ GridComponent,
+ LegendComponent,
+ TooltipComponent,
+} from 'echarts/components'
+import { SVGRenderer } from 'echarts/renderers'
+import VChart from 'vue-echarts'
+import {
+ trafficDays,
+ trafficChartOption,
+ type TrafficDay,
+ type TrafficBucket,
+} from '../utils/traffic-chart'
+use([
+ LineChart,
+ AriaComponent,
+ GridComponent,
+ LegendComponent,
+ TooltipComponent,
+ SVGRenderer,
+])
+const props = defineProps<{
+ rows: TrafficDay[]
+ from: string
+ to: string
+ zh?: boolean
+ bucket?: TrafficBucket
+}>()
+const colorMode = useColorMode()
+const option = computed(() =>
+ trafficChartOption(
+ trafficDays(props.rows, props.from, props.to, props.bucket),
+ colorMode.value === 'dark',
+ !!props.zh,
+ ),
+)
+</script>
+<template>
+ <VChart
+ class="cf-traffic-chart"
+ :option="option"
+ :init-options="{ renderer: 'svg' }"
+ :update-options="{ notMerge: true }"
+ autoresize
+ />
+</template>
+<style scoped>
+.cf-traffic-chart {
+ height: 260px;
+ width: 100%;
+ min-width: 0;
+}
+</style>
diff --git a/packages/saas-ui/app/utils/analytics-range.ts b/packages/saas-ui/app/utils/analytics-range.ts
new file mode 100644
index 00000000..3f1eccb9
--- /dev/null
+++ b/packages/saas-ui/app/utils/analytics-range.ts
@@ -0,0 +1,30 @@
+export type AnalyticsDateRange = {
+ from: string
+ to: string
+ preset?: number
+ allTime?: boolean
+}
+export const ANALYTICS_PRESETS = [
+ 1800, 3600, 21600, 43200, 86400, 604800, 2592000,
+] as const
+export function relativeRange(
+ seconds: number,
+ now = Date.now(),
+): AnalyticsDateRange {
+ now = Math.floor(now / 60000) * 60000
+ return {
+ from: new Date(now - seconds * 1000).toISOString(),
+ to: new Date(now).toISOString(),
+ preset: seconds,
+ }
+}
+export function rangeInput(value: string, utc: boolean) {
+ const date = new Date(value)
+ return new Date(date.getTime() - (utc ? 0 : date.getTimezoneOffset() * 60000))
+ .toISOString()
+ .slice(0, 16)
+}
+export function inputInstant(value: string, utc: boolean) {
+ if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value)) return NaN
+ return Date.parse(value + (utc ? ':00Z' : ':00'))
+}
diff --git a/packages/saas-ui/app/utils/traffic-chart.ts b/packages/saas-ui/app/utils/traffic-chart.ts
new file mode 100644
index 00000000..c70c03fb
--- /dev/null
+++ b/packages/saas-ui/app/utils/traffic-chart.ts
@@ -0,0 +1,174 @@
+import type { ComposeOption } from 'echarts/core'
+import type { LineSeriesOption } from 'echarts/charts'
+import type {
+ AriaComponentOption,
+ GridComponentOption,
+ LegendComponentOption,
+ TooltipComponentOption,
+} from 'echarts/components'
+export type TrafficDay = { label: string; pv: number; uv: number }
+type TrafficOption = ComposeOption<
+ | LineSeriesOption
+ | AriaComponentOption
+ | GridComponentOption
+ | LegendComponentOption
+ | TooltipComponentOption
+>
+/** Keep zero-traffic dates on the UTC axis rather than stretching one observed day. */
+export type TrafficBucket = 'minute' | 'hour' | 'day'
+export function trafficDays(
+ rows: readonly TrafficDay[],
+ from: string,
+ to: string,
+ bucket: TrafficBucket = 'day',
+): TrafficDay[] {
+ const interval =
+ bucket === 'minute' ? 60000 : bucket === 'hour' ? 3600000 : 86400000
+ const first = Math.floor(Date.parse(from) / interval) * interval
+ const end = Date.parse(to) + (to.length === 10 ? 86400000 : 0)
+ if (!Number.isFinite(first) || !Number.isFinite(end) || first >= end)
+ return []
+ const count = Math.min(10000, Math.ceil((end - first) / interval))
+ const key = (value: number) =>
+ new Date(value).toISOString().slice(0, bucket === 'day' ? 10 : 19) +
+ (bucket === 'day' ? '' : 'Z')
+ const byTime = new Map(
+ rows.map((row) => {
+ const raw =
+ row.label.length === 10 || row.label.endsWith('Z')
+ ? row.label
+ : row.label.replace(' ', 'T') + 'Z'
+ return [key(Math.floor(Date.parse(raw) / interval) * interval), row]
+ }),
+ )
+ return Array.from({ length: count }, (_, index) => {
+ const label = key(first + index * interval),
+ row = byTime.get(label)
+ return { label, pv: row?.pv ?? 0, uv: row?.uv ?? 0 }
+ })
+}
+export function trafficChartOption(
+ days: readonly TrafficDay[],
+ dark: boolean,
+ zh: boolean,
+): TrafficOption {
+ const text = dark ? '#a8aebb' : '#646873',
+ border = dark ? '#353943' : '#e7eaf0'
+ const pv = dark ? '#60a5fa' : '#3b82f6',
+ uv = dark ? '#2dd4bf' : '#0d9488'
+ const locale = zh ? 'zh-CN' : 'en-US'
+ return {
+ animationDuration: 300,
+ backgroundColor: 'transparent',
+ color: [pv, uv],
+ textStyle: { fontFamily: 'Inter, "Noto Sans SC", sans-serif' },
+ aria: {
+ enabled: true,
+ label: {
+ description: zh
+ ? '每日页面浏览量与独立访客,日期以 UTC 计算。具体数值见下方表格。'
+ : 'Daily page views and unique visitors in UTC. Exact values are in the table below.',
+ },
+ },
+ grid: { top: 52, right: 16, bottom: 12, left: 4, containLabel: true },
+ legend: {
+ top: 4,
+ left: 0,
+ icon: 'roundRect',
+ itemWidth: 14,
+ itemHeight: 4,
+ itemGap: 24,
+ textStyle: { color: text, fontSize: 12 },
+ data: ['PV', zh ? '每日 UV' : 'Daily UV'],
+ },
+ tooltip: {
+ trigger: 'axis',
+ confine: true,
+ renderMode: 'richText',
+ backgroundColor: dark ? '#242831' : '#ffffff',
+ borderColor: border,
+ borderWidth: 1,
+ padding: [12, 16],
+ textStyle: { color: dark ? '#e5e7eb' : '#282a30', fontSize: 12 },
+ axisPointer: {
+ type: 'line',
+ lineStyle: { color: dark ? '#707a8e' : '#aab4c6', type: 'dashed' },
+ },
+ valueFormatter: (value) =>
+ new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(
+ Number(value),
+ ),
+ },
+ xAxis: {
+ type: 'category',
+ data: days.map((day) => day.label),
+ boundaryGap: false,
+ axisLine: { lineStyle: { color: border } },
+ axisTick: { show: false },
+ axisLabel: {
+ color: text,
+ fontSize: 11,
+ margin: 14,
+ hideOverlap: true,
+ formatter: (value: string) =>
+ value.includes('T')
+ ? value.slice(5, 10) + '\n' + value.slice(11, 16)
+ : days.length > 366
+ ? value.slice(0, 7)
+ : value.slice(5),
+ },
+ },
+ yAxis: {
+ type: 'value',
+ min: 0,
+ minInterval: 1,
+ axisLabel: {
+ color: text,
+ fontSize: 11,
+ formatter: (value: number) =>
+ new Intl.NumberFormat(locale, { notation: 'compact' }).format(value),
+ },
+ splitLine: { lineStyle: { color: border, type: 'dashed' } },
+ },
+ series: [
+ {
+ name: 'PV',
+ type: 'line',
+ data: days.map((day) => day.pv),
+ showSymbol: days.length === 1,
+ symbol: 'circle',
+ symbolSize: 7,
+ lineStyle: { width: 2.5 },
+ itemStyle: { color: pv },
+ emphasis: { focus: 'series' },
+ areaStyle: {
+ color: {
+ type: 'linear',
+ x: 0,
+ y: 0,
+ x2: 0,
+ y2: 1,
+ colorStops: [
+ {
+ offset: 0,
+ color: dark ? 'rgba(96,165,250,0.24)' : 'rgba(59,130,246,0.18)',
+ },
+ { offset: 1, color: 'rgba(59,130,246,0.01)' },
+ ],
+ },
+ },
+ },
+ {
+ name: zh ? '每日 UV' : 'Daily UV',
+ type: 'line',
+ data: days.map((day) => day.uv),
+ showSymbol: days.length === 1,
+ symbol: 'circle',
+ symbolSize: 7,
+ lineStyle: { width: 2.5 },
+ itemStyle: { color: uv },
+ emphasis: { focus: 'series' },
+ },
+ ],
+ }
+}
diff --git a/packages/saas-ui/package.json b/packages/saas-ui/package.json
index 2283a62f..92f0015e 100644
--- a/packages/saas-ui/package.json
+++ b/packages/saas-ui/package.json
@@ -8,13 +8,16 @@
".": "./nuxt.config.ts"
},
"dependencies": {
+ "@internationalized/date": "3.12.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "echarts": "6.1.0",
"lucide-vue-next": "^1.0.0",
"markdown-it": "^14.3.3",
"reka-ui": "^2.11.0",
"tailwind-merge": "^3.7.0",
- "vue": "3.5.43"
+ "vue": "3.5.43",
+ "vue-echarts": "8.3.2"
},
"devDependencies": {
"@types/markdown-it": "^14.1.2"
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 91d703b0..5a931336 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -915,6 +915,9 @@ importers:
packages/saas-ui:
dependencies:
+ '@internationalized/date':
+ specifier: 3.12.0
+ version: 3.12.0
'@nuxt/ui':
specifier: ^4.11.3
version: 4.11.3(92e70d591260dd1b8304e46d7e1fe6ea)
@@ -924,6 +927,9 @@ importers:
clsx:
specifier: ^2.1.1
version: 2.1.1
+ echarts:
+ specifier: 6.1.0
+ version: 6.1.0
lucide-vue-next:
specifier: ^1.0.0
version: 1.0.0([email protected])
@@ -939,6 +945,9 @@ importers:
vue:
specifier: 3.5.43
version: 3.5.43([email protected])
+ vue-echarts:
+ specifier: 8.3.2
devDependencies:
'@types/markdown-it':
specifier: ^14.1.2
@@ -996,19 +1005,6 @@ importers:
packages:
- '@stablelib/[email protected]':
- resolution: {integrity: sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==}
-
- resolution: {integrity: sha512-hJUfgPis3ug1beOgl31rbj7W5A2+WmM3t/JnfTxdLELBuopNe1bV/kGpTgVuLJpRRuQ7fpmGyaJTS0A5/tVh0w==}
- hasBin: true
-
- resolution: {integrity: sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==}
-
- resolution: {integrity: sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==}
-
'@adonisjs/[email protected]':
resolution: {integrity: sha512-ZkRguwjAp4skKvKDdRAfdJ2oqQ0N7p9l3sioyXO1E8o0WcsyDgEpsTQtuVNoIdMiw4sn4gJlmL3nyF4BcK1ZDQ==}
engines: {node: '>=20.6.0'}
@@ -4703,6 +4699,9 @@ packages:
'@speed-highlight/[email protected]':
resolution: {integrity: sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==}
+ '@stablelib/[email protected]':
+ resolution: {integrity: sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==}
+
'@standard-schema/[email protected]':
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
@@ -6344,6 +6343,10 @@ packages:
resolution: {integrity: sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==}
+ resolution: {integrity: sha512-hJUfgPis3ug1beOgl31rbj7W5A2+WmM3t/JnfTxdLELBuopNe1bV/kGpTgVuLJpRRuQ7fpmGyaJTS0A5/tVh0w==}
+ hasBin: true
+
resolution: {integrity: sha512-BTJ9aZYL3vCfZlZOBLy9v8TUqWGQ0pzFnygKwFZt5udj6viBoFIBviKPUoZLDCPn1FoXffv6McQFDenrm5Krfw==}
engines: {node: '>=20'}
@@ -6467,6 +6470,9 @@ packages:
resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==}
+ resolution: {integrity: sha512-q0yaFPggC9FUdsWH4blavRWFmxdrIodbkoKNAjJudAI6CA9gNPxHtV2RcZNEepZVlk4yvBYkOkbk6HIVpIyHZA==}
+
resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}
@@ -6769,6 +6775,9 @@ packages:
resolution: {integrity: sha512-99jPl8JkCSCa4VlboNU1XuL98ijm74Pm9CGo6H4BoMVoVh1uhguQcvwLgXDT8Vkl2qj/UEQ0J9gD8beHjTFk1w==}
hasBin: true
+ resolution: {integrity: sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==}
+
resolution: {integrity: sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==}
@@ -8944,6 +8953,9 @@ packages:
resolution: {integrity: sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==}
+ resolution: {integrity: sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==}
+
resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==}
engines: {node: '>= 0.8'}
@@ -9195,6 +9207,9 @@ packages:
resolution: {integrity: sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==}
+ resolution: {integrity: sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==}
+
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
@@ -9835,6 +9850,12 @@ packages:
resolution: {integrity: sha512-RutnB7X8c5hjq39NceArgXg28WZtZpGc3+J16ljMiYnFhKvd8hITxSWQSQ5bvldxMDU6gG5mkxl1MTQLXckVSQ==}
+ resolution: {integrity: sha512-FbJD49OZZZv1I8aclHQ+gcQxU+Y9nNWQMuod1sewE7/YjGQUJAaeVcf6WrSfQDBRPke+WoVsUtdRFIqPOsRrnw==}
+ peerDependencies:
+ echarts: ^6.0.0
+ vue: ^3.3.0
+
resolution: {integrity: sha512-oRFZtQjRDRQtfxu7tFlsZlnCa5gPkg/KX89kJDKdC9bz4GIYgo3cAMaD0XFeUx/WHuKoVbDMRTIo9Hvg67HnPw==}
engines: {node: '>= 22'}
@@ -10060,24 +10081,14 @@ packages:
resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==}
+ resolution: {integrity: sha512-oEGMDB6pOP2S6OwRR4PdVv610zrjnA3Bh+JnSG12fYJlBKjtNAoEb5fSUoCOOINlH96I2fU38/A2UpRKs67xYQ==}
+
resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}
snapshots:
- '@stablelib/[email protected]': {}
-
- dependencies:
- standardwebhooks: 1.1.1
-
-
- dependencies:
- '@stablelib/base64': 1.0.1
- fast-sha256: 1.3.0
-
'@adonisjs/[email protected]':
dependencies:
'@phc/format': 1.0.0
@@ -15093,6 +15104,8 @@ snapshots:
'@speed-highlight/[email protected]': {}
+ '@stablelib/[email protected]': {}
+
'@standard-schema/[email protected]': {}
@@ -16808,6 +16821,10 @@ snapshots:
+ dependencies:
+ standardwebhooks: 1.1.1
+
dependencies:
type-fest: 5.10.0
@@ -16850,6 +16867,11 @@ snapshots:
+ dependencies:
+ tslib: 2.3.0
+ zrender: 6.1.0
+
@@ -17263,6 +17285,8 @@ snapshots:
dependencies:
cac: 7.1.0
+
@@ -21089,6 +21113,11 @@ snapshots:
+ dependencies:
+ '@stablelib/base64': 1.0.1
+ fast-sha256: 1.3.0
+
@@ -21330,6 +21359,8 @@ snapshots:
+
@@ -22020,6 +22051,11 @@ snapshots:
+ dependencies:
+ echarts: 6.1.0
+ vue: 3.5.43([email protected])
+
dependencies:
'@intlify/core-base': 11.4.14
@@ -22384,4 +22420,8 @@ snapshots:
+ dependencies:
+ tslib: 2.3.0
+
diff --git a/scripts/analytics-deployment.mjs b/scripts/analytics-deployment.mjs
index b31a7b2e..8ed691d5 100644
--- a/scripts/analytics-deployment.mjs
+++ b/scripts/analytics-deployment.mjs
@@ -14,6 +14,10 @@ export function configureAnalyticsDeployment(config, environment, env) {
)
const preview = environment === 'staging'
const target = preview ? (config.previews ??= {}) : config
+ if (config.name === 'chronoframe-cloud' && !preview)
+ target.triggers = {
+ crons: [...new Set([...(target.triggers?.crons ?? []), '* * * * *'])],
+ }
target.analytics_engine_datasets = [
{
binding: 'VISIT_ANALYTICS',
diff --git a/tests/analytics-archive.test.ts b/tests/analytics-archive.test.ts
new file mode 100644
index 00000000..17490d27
--- /dev/null
+++ b/tests/analytics-archive.test.ts
@@ -0,0 +1,171 @@
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import { createRequire } from 'node:module'
+import { readFile } from 'node:fs/promises'
+import { splitSqlQuery } from './helpers/sql.ts'
+import {
+ archiveAnalytics,
+ historicalAnalytics,
+} from '../packages/platform/src/analytics-archive.ts'
+const require = createRequire(import.meta.url)
+const { Miniflare, convertV4MiniflareOptions } = createRequire(
+ require.resolve('wrangler/package.json'),
+)('miniflare')
+test('daily archive resumes failures, publishes complete snapshots atomically, and isolates tenants without double-counting site totals', async () => {
+ const mf = new Miniflare(
+ convertV4MiniflareOptions({
+ modules: true,
+ compatibilityDate: '2026-10-26',
+ script: 'export default {fetch(){return new Response("ok")}}',
+ d1Databases: ['DB'],
+ }),
+ )
+ try {
+ const db = await mf.getD1Database('DB')
+ for (const sql of splitSqlQuery(
+ await readFile(
+ new URL(
+ '../packages/platform/migrations/0038_analytics_archive.sql',
+ import.meta.url,
+ ),
+ 'utf8',
+ ),
+ ))
+ await db.prepare(sql).run()
+ const config = {
+ accountId: 'a'.repeat(32),
+ token: 'fixture',
+ dataset: 'archive_fixture',
+ },
+ now = Date.parse('2026-11-01T12:00:00Z')
+ let fail = true
+ const fetcher: typeof fetch = async (_url, opts) => {
+ const sql = String(opts?.body)
+ if (sql.includes('MIN(timestamp)'))
+ return new Response(JSON.stringify({ data: [{ day: '2026-10-28' }] }))
+ if (sql.includes('AS workspaceId')) {
+ if (fail && sql.includes('blob9 AS label')) {
+ fail = false
+ return new Response('Temporary failure', { status: 503 })
+ }
+ const match = sql.includes("timestamp>=toDateTime('2026-10-28")
+ const label = sql.includes("'' AS label")
+ ? ''
+ : sql.includes('blob6 AS label')
+ ? '/'
+ : 'example'
+ return new Response(
+ JSON.stringify({
+ data: match
+ ? [
+ {
+ kind: 'site',
+ workspaceId: 1,
+ siteId: sql.includes("AND blob2='site'") ? 11 : 0,
+ label,
+ pv: 10,
+ uv: 3,
+ sampleInterval: 1,
+ },
+ ]
+ : [],
+ }),
+ )
+ }
+ const rows = sql.includes("blob3 = '2'")
+ ? []
+ : [
+ {
+ label: sql.includes('toDate(timestamp) AS label')
+ ? '2026-11-01'
+ : sql.includes('blob6 AS label')
+ ? '/'
+ : '',
+ pv: 2,
+ uv: 1,
+ sampleInterval: 1,
+ },
+ ]
+ return new Response(JSON.stringify({ data: rows }))
+ }
+ await assert.rejects(archiveAnalytics(db, config, now, fetcher))
+ assert.equal(
+ (
+ await db
+ .prepare('SELECT COUNT(*) AS n FROM platform_analytics_archive_days')
+ .first()
+ ).n,
+ 0,
+ )
+ for (let i = 0; i < 8; i++)
+ await archiveAnalytics(db, config, now + i, fetcher)
+ assert.equal(
+ (
+ await db
+ .prepare('SELECT cursor_day FROM platform_analytics_archive_state')
+ .first()
+ ).cursor_day,
+ '2026-11-01',
+ )
+ const report = await historicalAnalytics(
+ db,
+ config,
+ {
+ from: '2025-11-01',
+ to: '2026-11-01',
+ allTime: true,
+ kind: 'site',
+ workspaceId: 1,
+ },
+ now,
+ fetcher,
+ )
+ assert.equal(report.summary.pv, 12)
+ assert.equal(report.summary.uv, 4)
+ assert.equal(report.pages.find((row) => row.label === '/')?.pv, 12)
+ assert.equal(report.bucket, 'day')
+ assert.equal(report.coverageStart, '2026-10-28')
+ const ownSite = await historicalAnalytics(
+ db,
+ config,
+ {
+ from: '2025-11-01',
+ to: '2026-11-01',
+ allTime: true,
+ kind: 'site',
+ workspaceId: 1,
+ siteId: 11,
+ },
+ now,
+ fetcher,
+ )
+ assert.equal(ownSite.summary.pv, 12)
+ const other = await historicalAnalytics(
+ db,
+ config,
+ {
+ from: '2025-11-01',
+ to: '2026-11-01',
+ allTime: true,
+ kind: 'site',
+ workspaceId: 2,
+ },
+ now,
+ fetcher,
+ )
+ assert.equal(other.summary.pv, 0)
+ const historic = await historicalAnalytics(
+ db,
+ config,
+ { from: '2026-10-28', to: '2026-10-28', kind: 'site', workspaceId: 1 },
+ now,
+ async () => {
+ throw new Error('Raw data no longer available')
+ },
+ )
+ assert.equal(historic.summary.pv, 10)
+ assert.equal(historic.summary.uv, 3)
+ } finally {
+ await mf.dispose()
+ }
+})
diff --git a/tests/analytics-presentation.test.ts b/tests/analytics-presentation.test.ts
new file mode 100644
index 00000000..899b7342
--- /dev/null
+++ b/tests/analytics-presentation.test.ts
@@ -0,0 +1,99 @@
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import { createRequire } from 'node:module'
+import { pathToFileURL } from 'node:url'
+import {
+ trafficDays,
+ trafficChartOption,
+} from '../packages/saas-ui/app/utils/traffic-chart.ts'
+import {
+ relativeRange,
+ rangeInput,
+ inputInstant,
+ ANALYTICS_PRESETS,
+} from '../packages/saas-ui/app/utils/analytics-range.ts'
+test('sparse day/minute/hour reports preserve the selected UTC axis and their real values', () => {
+ const days = trafficDays(
+ [{ label: '2026-11-01', pv: 2, uv: 1 }],
+ '2026-10-26',
+ '2026-11-01',
+ )
+ assert.equal(days.length, 7)
+ assert.equal(days[0]!.pv, 0)
+ assert.equal(days[6]!.pv, 2)
+ const minutes = trafficDays(
+ [{ label: '2026-11-01 11:31:00', pv: 3, uv: 1 }],
+ '2026-11-01T11:30:00Z',
+ '2026-11-01T12:00:00Z',
+ 'minute',
+ )
+ assert.equal(minutes.length, 30)
+ assert.equal(minutes[1]!.pv, 3)
+ assert.equal(minutes[1]!.label, '2026-11-01T11:31:00Z')
+ assert.equal(trafficDays([], '2025-11-01', '2026-11-01').length, 366)
+})
+test('relative presets and local/UTC inputs retain actual instants across timezone changes', () => {
+ assert.deepEqual(
+ ANALYTICS_PRESETS,
+ [1800, 3600, 21600, 43200, 86400, 604800, 2592000],
+ )
+ const range = relativeRange(1800, Date.parse('2026-11-01T12:00:39Z'))
+ assert.equal(range.from, '2026-11-01T11:30:00.000Z')
+ assert.equal(range.to, '2026-11-01T12:00:00.000Z')
+ const previous = process.env.TZ
+ try {
+ process.env.TZ = 'Asia/Hong_Kong'
+ const instant = '2026-11-01T04:00:00.000Z'
+ assert.equal(rangeInput(instant, false), '2026-11-01T12:00')
+ assert.equal(inputInstant('2026-11-01T12:00', false), Date.parse(instant))
+ assert.equal(
+ inputInstant('2026-11-01T12:00', true),
+ Date.parse('2026-11-01T12:00Z'),
+ )
+ } finally {
+ if (previous === undefined) delete process.env.TZ
+ else process.env.TZ = previous
+ }
+})
+test('the registered ECharts modules render a single-day report as a valid colored SVG without browser globals', async () => {
+ const require = createRequire(
+ new URL('../packages/saas-ui/package.json', import.meta.url),
+ )
+ const load = (name: string) =>
+ import(pathToFileURL(require.resolve(name)).href)
+ const [core, charts, components, renderers] = await Promise.all(
+ [
+ 'echarts/core',
+ 'echarts/charts',
+ 'echarts/components',
+ 'echarts/renderers',
+ ].map(load),
+ )
+ core.use([
+ charts.LineChart,
+ components.GridComponent,
+ components.LegendComponent,
+ components.TooltipComponent,
+ components.AriaComponent,
+ renderers.SVGRenderer,
+ ])
+ const chart = core.init(null, undefined, {
+ renderer: 'svg',
+ ssr: true,
+ width: 900,
+ height: 260,
+ })
+ try {
+ chart.setOption(
+ trafficChartOption([{ label: '2026-11-01', pv: 2, uv: 1 }], false, true),
+ )
+ const svg = chart.renderToSVGString()
+ assert.match(svg, /<svg/)
+ assert.match(svg, /PV/)
+ assert.match(svg, /#3b82f6/)
+ assert.match(svg, /#0d9488/)
+ assert.ok(!svg.includes('NaN'))
+ } finally {
+ chart.dispose()
+ }
+})
diff --git a/tests/visit-analytics.test.ts b/tests/visit-analytics.test.ts
index 0079f005..97a355ff 100644
--- a/tests/visit-analytics.test.ts
+++ b/tests/visit-analytics.test.ts
@@ -113,8 +113,7 @@ test('analytics filters reject SQL injection and unbounded queries; every query
}
for (const input of [
{ from: "2026-11-01' OR 1=1" },
- { from: '2026-01-01' },
- { from: '2026-09-01' },
+ { from: '2025-01-01' },
{ to: '2026-11-02' },
{ workspaceId: '1 OR 1=1' },
{ siteId: '-1' },
@@ -376,3 +375,30 @@ test('browser tracker counts initial entry and path navigation once, skips query
hooks['page:finish']!()
assert.equal(events.length, 3)
})
+
+test('relative minute/hour ranges preserve exact UTC boundaries and support a year or all time', () => {
+ const now = Date.parse('2026-11-01T12:00:00Z')
+ const short = analyticsFilter(
+ { from: '2026-11-01T11:30:00.000Z', to: '2026-11-01T12:00:00.000Z' },
+ now,
+ )
+ const query = analyticsQueries('chronoframe_visits', short)
+ assert.match(query.summary, /2026-11-01 11:30:00/)
+ assert.match(query.summary, /2026-11-01 12:00:00/)
+ assert.match(query.daily, /toStartOfMinute/)
+ const hours = analyticsFilter(
+ { from: '2026-10-31T12:00:00.000Z', to: '2026-11-01T12:00:00.000Z' },
+ now,
+ )
+ assert.match(
+ analyticsQueries('chronoframe_visits', hours).daily,
+ /toStartOfHour/,
+ )
+ assert.doesNotThrow(() =>
+ analyticsFilter({ from: '2025-11-01', to: '2026-11-01' }, now),
+ )
+ assert.equal(analyticsFilter({ allTime: '1' }, now).allTime, true)
+ assert.throws(() =>
+ analyticsFilter({ from: '2025-10-31', to: '2026-11-01' }, now),
+ )
+})