feat(ops): 站点概览卡片点击弹窗查看访客详情

弹窗含 PV/访客/趋势及页面、来源、地区、城市、语言、设备、OS、浏览器等排行。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-16 03:07:58 -05:00
parent 7b3c926bfb
commit b5a6907b85
2 changed files with 271 additions and 70 deletions

View File

@ -279,6 +279,18 @@ def website_analytics(website_id: str, range_key: str = "7d") -> dict[str, Any]:
code_browser, browsers = _umami_request(
"GET", f"/api/websites/{website_id}/metrics", token=token, query={**q, "type": "browser", "limit": 6}
)
code_os, oses = _umami_request(
"GET", f"/api/websites/{website_id}/metrics", token=token, query={**q, "type": "os", "limit": 6}
)
code_lang, langs = _umami_request(
"GET", f"/api/websites/{website_id}/metrics", token=token, query={**q, "type": "language", "limit": 8}
)
code_city, cities = _umami_request(
"GET", f"/api/websites/{website_id}/metrics", token=token, query={**q, "type": "city", "limit": 8}
)
code_title, titles = _umami_request(
"GET", f"/api/websites/{website_id}/metrics", token=token, query={**q, "type": "title", "limit": 8}
)
stats_obj = stats if isinstance(stats, dict) else {}
pageviews_n = int(stats_obj.get("pageviews") or 0)
@ -304,6 +316,10 @@ def website_analytics(website_id: str, range_key: str = "7d") -> dict[str, Any]:
"active": None if code_active == 200 else active,
"pageviews": None if code_pv == 200 else pageviews,
"path": None if code_path == 200 else paths,
"os": None if code_os == 200 else oses,
"language": None if code_lang == 200 else langs,
"city": None if code_city == 200 else cities,
"title": None if code_title == 200 else titles,
},
"active": int((active or {}).get("visitors") or 0) if isinstance(active, dict) else 0,
"stats": {
@ -321,6 +337,10 @@ def website_analytics(website_id: str, range_key: str = "7d") -> dict[str, Any]:
"top_countries": _metric_list(countries),
"top_devices": _metric_list(devices),
"top_browsers": _metric_list(browsers),
"top_os": _metric_list(oses),
"top_languages": _metric_list(langs),
"top_cities": _metric_list(cities),
"top_titles": _metric_list(titles),
"umami_url": umami_config()["url"],
}

View File

@ -16,6 +16,7 @@ import {
ShieldCheck,
Users,
Wifi,
X,
} from "lucide-react";
import { Shell } from "@/components/Shell";
@ -73,6 +74,7 @@ type AnalyticsDetail = {
bounces?: number;
bounce_rate?: number;
avg_visit_sec?: number;
totaltime?: number;
};
series?: { x: string; y: number }[];
top_paths?: { name: string; value: number }[];
@ -80,6 +82,10 @@ type AnalyticsDetail = {
top_countries?: { name: string; value: number }[];
top_devices?: { name: string; value: number }[];
top_browsers?: { name: string; value: number }[];
top_os?: { name: string; value: number }[];
top_languages?: { name: string; value: number }[];
top_cities?: { name: string; value: number }[];
top_titles?: { name: string; value: number }[];
umami_url?: string;
};
@ -196,6 +202,169 @@ function MetricList({ title, rows }: { title: string; rows?: { name: string; val
);
}
function SiteDetailBody({
detail,
loading,
}: {
detail: AnalyticsDetail | null;
loading?: boolean;
}) {
const st = detail?.stats;
if (loading && !detail) {
return (
<div className="flex items-center justify-center gap-2 py-16 text-sm text-slate-400">
<Loader2 className="h-4 w-4 animate-spin" /> 加载访客详情…
</div>
);
}
if (!detail) {
return <div className="py-12 text-center text-sm text-slate-500">暂无该站点数据</div>;
}
return (
<div className="space-y-4">
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
{[
{ label: "浏览量 PV", value: fmtNum(st?.pageviews), icon: Eye },
{ label: "独立访客", value: fmtNum(st?.visitors), icon: Users },
{ label: "访问次数", value: fmtNum(st?.visits), icon: MousePointerClick },
{ label: "跳出率", value: `${st?.bounce_rate ?? 0}%`, icon: Activity },
{ label: "平均停留", value: fmtDuration(st?.avg_visit_sec), icon: Radar },
].map((card) => (
<div key={card.label} className="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
<div className="flex items-center gap-1.5 text-[11px] text-slate-400">
<card.icon className="h-3.5 w-3.5 text-teal-300" />
{card.label}
</div>
<div className="mt-1 text-xl font-semibold text-white">{card.value}</div>
</div>
))}
</div>
<div className="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
<div className="mb-1 flex items-center justify-between text-xs text-slate-400">
<span>浏览量趋势</span>
<span className="text-teal-300">当前在线 {detail.active ?? 0}</span>
</div>
<Sparkline series={detail.series} />
</div>
<div className="grid gap-3 lg:grid-cols-2">
<MetricList title="热门页面" rows={detail.top_paths} />
<MetricList title="页面标题" rows={detail.top_titles} />
<MetricList title="来源 Referrer" rows={detail.top_referrers} />
<MetricList title="国家 / 地区" rows={detail.top_countries} />
<MetricList title="城市" rows={detail.top_cities} />
<MetricList title="语言" rows={detail.top_languages} />
<MetricList title="设备" rows={detail.top_devices} />
<MetricList title="操作系统" rows={detail.top_os} />
<MetricList title="浏览器" rows={detail.top_browsers} />
</div>
</div>
);
}
function SiteDetailModal({
open,
domain,
role,
range,
detail,
loading,
onClose,
onRange,
umamiUrl,
}: {
open: boolean;
domain: string;
role?: string;
range: string;
detail: AnalyticsDetail | null;
loading?: boolean;
onClose: () => void;
onRange: (id: string) => void;
umamiUrl?: string;
}) {
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", onKey);
const prev = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => {
window.removeEventListener("keydown", onKey);
document.body.style.overflow = prev;
};
}, [open, onClose]);
if (!open) return null;
return (
<div
className="fixed inset-0 z-[80] flex items-end justify-center bg-black/70 p-0 backdrop-blur-sm sm:items-center sm:p-4"
onClick={onClose}
role="presentation"
>
<div
role="dialog"
aria-modal="true"
aria-label={`${domain} 访客详情`}
className="flex max-h-[92vh] w-full max-w-5xl flex-col overflow-hidden rounded-t-3xl border border-white/10 bg-[#0b1220] shadow-2xl sm:rounded-3xl"
onClick={(e) => e.stopPropagation()}
>
<div className="flex flex-wrap items-start justify-between gap-3 border-b border-white/10 px-4 py-3 sm:px-5">
<div className="min-w-0">
<div className="text-[11px] uppercase tracking-[0.16em] text-teal-200/70">站点访客详情</div>
<h2 className="truncate text-lg font-semibold text-white">{domain}</h2>
{role ? <p className="mt-0.5 text-[11px] text-slate-500">{role}</p> : null}
</div>
<div className="flex flex-wrap items-center gap-2">
<div className="flex flex-wrap gap-1">
{RANGES.map((r) => (
<button
key={r.id}
type="button"
onClick={() => onRange(r.id)}
className={`rounded-lg px-2.5 py-1 text-[11px] ${
range === r.id ? "bg-sky-400/20 text-sky-200" : "bg-white/5 text-slate-400"
}`}
>
{r.label}
</button>
))}
</div>
<a
href={umamiUrl || "https://umami.nomadro.com"}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-[11px] text-slate-200"
>
Umami <ExternalLink className="h-3 w-3" />
</a>
<button
type="button"
onClick={onClose}
className="rounded-lg border border-white/10 bg-white/5 p-1.5 text-slate-300 hover:bg-white/10"
aria-label="关闭"
>
<X className="h-4 w-4" />
</button>
</div>
</div>
<div className="relative flex-1 overflow-y-auto p-4 sm:p-5">
{loading ? (
<div className="pointer-events-none absolute right-4 top-3 inline-flex items-center gap-1 rounded-full bg-black/50 px-2 py-0.5 text-[10px] text-slate-300">
<Loader2 className="h-3 w-3 animate-spin" /> 刷新中
</div>
) : null}
<SiteDetailBody detail={detail} loading={loading} />
</div>
</div>
</div>
);
}
export default function OpsPage() {
const toast = useToast();
const now = useNow(1000);
@ -204,6 +373,8 @@ export default function OpsPage() {
const [overview, setOverview] = useState<OverviewSite[]>([]);
const [detail, setDetail] = useState<AnalyticsDetail | null>(null);
const [domain, setDomain] = useState("dylive.nomadro.com");
const [modalOpen, setModalOpen] = useState(false);
const [modalLoading, setModalLoading] = useState(false);
const [range, setRange] = useState("7d");
const [loading, setLoading] = useState(true);
const [syncing, setSyncing] = useState(false);
@ -219,9 +390,11 @@ export default function OpsPage() {
const domainRef = useRef(domain);
const rangeRef = useRef(range);
const tabRef = useRef(tab);
const modalOpenRef = useRef(modalOpen);
domainRef.current = domain;
rangeRef.current = range;
tabRef.current = tab;
modalOpenRef.current = modalOpen;
useEffect(() => {
const onVis = () => setPageVisible(document.visibilityState === "visible");
@ -238,16 +411,22 @@ export default function OpsPage() {
else setSyncing(true);
try {
const tasks: Promise<void>[] = [];
// Always keep analytics fresh on analytics tab; monitor on monitor tab;
// still refresh both lightly so switching tabs feels live.
tasks.push(
(async () => {
const ov = await fetchJson(`/api/ops/analytics?range=${encodeURIComponent(rangeRef.current)}`);
setOverview(ov?.sites || []);
const d = await fetchJson(
`/api/ops/analytics?range=${encodeURIComponent(rangeRef.current)}&domain=${encodeURIComponent(domainRef.current)}`
);
setDetail(d);
// Only pull heavy site detail while modal is open (or first paint needs it)
if (modalOpenRef.current && domainRef.current) {
setModalLoading(true);
try {
const d = await fetchJson(
`/api/ops/analytics?range=${encodeURIComponent(rangeRef.current)}&domain=${encodeURIComponent(domainRef.current)}`
);
setDetail(d);
} finally {
setModalLoading(false);
}
}
})()
);
tasks.push(
@ -271,6 +450,46 @@ export default function OpsPage() {
}
}, [toast]);
const openSiteModal = useCallback(
async (d: string) => {
setDomain(d);
setModalOpen(true);
setModalLoading(true);
try {
const detailRes = await fetchJson(
`/api/ops/analytics?range=${encodeURIComponent(rangeRef.current)}&domain=${encodeURIComponent(d)}`
);
setDetail(detailRes);
} catch (e) {
toast.push((e as Error).message || "加载详情失败", "err");
} finally {
setModalLoading(false);
}
},
[toast]
);
const closeSiteModal = useCallback(() => setModalOpen(false), []);
const onModalRange = useCallback(
async (id: string) => {
setRange(id);
if (!domainRef.current) return;
setModalLoading(true);
try {
const detailRes = await fetchJson(
`/api/ops/analytics?range=${encodeURIComponent(id)}&domain=${encodeURIComponent(domainRef.current)}`
);
setDetail(detailRes);
} catch (e) {
toast.push((e as Error).message || "切换时间失败", "err");
} finally {
setModalLoading(false);
}
},
[toast]
);
// Poll server continuously while page is visible (no manual refresh required).
useAutoRefresh(loadSilent, {
intervalMs: tab === "analytics" ? 10000 : 12000,
@ -286,9 +505,9 @@ export default function OpsPage() {
const dnsOkCount = useMemo(() => (data?.sites || []).filter((s) => s.dns_ok).length, [data]);
const svcOkCount = useMemo(() => (data?.services || []).filter((s) => s.ok).length, [data]);
const trackedDomains = useMemo(
() => (data?.sites || []).filter((s) => s.kind !== "infra" && s.umami_website_id).map((s) => s.domain),
[data]
const modalRole = useMemo(
() => overview.find((s) => s.domain === domain)?.role || data?.sites?.find((s) => s.domain === domain)?.role,
[overview, data, domain]
);
const agoSec = lastOkAt ? Math.max(0, Math.floor((now - lastOkAt) / 1000)) : null;
@ -321,8 +540,6 @@ export default function OpsPage() {
}
}
const st = detail?.stats;
return (
<Shell>
<div className="mx-auto max-w-6xl space-y-5 pb-8">
@ -395,7 +612,10 @@ export default function OpsPage() {
<>
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<div className="text-sm font-medium text-white">各站点概览</div>
<div>
<div className="text-sm font-medium text-white">各站点概览</div>
<div className="text-[11px] text-slate-500">点击卡片弹出访客详情(页面 / 来源 / 地区 / 设备等)</div>
</div>
<div className="flex flex-wrap gap-1.5">
{RANGES.map((r) => (
<button
@ -414,16 +634,19 @@ export default function OpsPage() {
<button
key={s.domain}
type="button"
onClick={() => setDomain(s.domain)}
className={`rounded-2xl border p-3 text-left transition ${
domain === s.domain ? "border-teal-300/40 bg-teal-400/10" : "border-white/10 bg-white/[0.03] hover:bg-white/[0.05]"
}`}
onClick={() => void openSiteModal(s.domain)}
className="group rounded-2xl border border-white/10 bg-white/[0.03] p-3 text-left transition hover:border-teal-300/40 hover:bg-teal-400/10"
>
<div className="flex items-center justify-between gap-2">
<div className="truncate text-sm font-medium text-white">{s.domain}</div>
<span className="text-[10px] text-teal-300">在线 {s.active}</span>
</div>
<div className="mt-0.5 truncate text-[11px] text-slate-500">{s.role}</div>
<div className="mt-0.5 flex items-center justify-between gap-2">
<div className="truncate text-[11px] text-slate-500">{s.role}</div>
<div className="shrink-0 text-[10px] text-sky-300/80 opacity-0 transition group-hover:opacity-100">
查看详情 →
</div>
</div>
<div className="mt-3 grid grid-cols-3 gap-2 text-center">
<div>
<div className="text-base font-semibold text-white">{fmtNum(s.pageviews)}</div>
@ -448,59 +671,17 @@ export default function OpsPage() {
</div>
</section>
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<div>
<div className="text-sm font-medium text-white">站点详情 · {domain}</div>
<div className="text-[11px] text-slate-500">类似 GA 的摘要指标与排行</div>
</div>
<select
value={domain}
onChange={(e) => setDomain(e.target.value)}
className="rounded-xl border border-white/10 bg-black/40 px-3 py-1.5 text-xs text-white"
>
{(trackedDomains.length ? trackedDomains : [domain]).map((d) => (
<option key={d} value={d}>
{d}
</option>
))}
</select>
</div>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
{[
{ label: "浏览量 PV", value: fmtNum(st?.pageviews), icon: Eye },
{ label: "独立访客", value: fmtNum(st?.visitors), icon: Users },
{ label: "访问次数", value: fmtNum(st?.visits), icon: MousePointerClick },
{ label: "跳出率", value: `${st?.bounce_rate ?? 0}%`, icon: Activity },
{ label: "平均停留", value: fmtDuration(st?.avg_visit_sec), icon: Radar },
].map((card) => (
<div key={card.label} className="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
<div className="flex items-center gap-1.5 text-[11px] text-slate-400">
<card.icon className="h-3.5 w-3.5 text-teal-300" />
{card.label}
</div>
<div className="mt-1 text-xl font-semibold text-white">{card.value}</div>
</div>
))}
</div>
<div className="mt-4 rounded-2xl border border-white/10 bg-white/[0.03] p-3">
<div className="mb-1 flex items-center justify-between text-xs text-slate-400">
<span>浏览量趋势</span>
<span className="text-teal-300">当前在线 {detail?.active ?? 0}</span>
</div>
<Sparkline series={detail?.series} />
</div>
<div className="mt-4 grid gap-3 lg:grid-cols-2">
<MetricList title="热门页面" rows={detail?.top_paths} />
<MetricList title="来源 Referrer" rows={detail?.top_referrers} />
<MetricList title="国家 / 地区" rows={detail?.top_countries} />
<MetricList title="设备" rows={detail?.top_devices} />
<MetricList title="浏览器" rows={detail?.top_browsers} />
</div>
</section>
<SiteDetailModal
open={modalOpen}
domain={domain}
role={modalRole}
range={range}
detail={detail?.domain === domain ? detail : detail}
loading={modalLoading}
onClose={closeSiteModal}
onRange={(id) => void onModalRange(id)}
umamiUrl={detail?.umami_url || data?.umami?.url}
/>
</>
)}