[feat] solution/frontend: 사이트관리 방문 통계 — 방문/크롤링 하위 탭, 실시간 30초 갱신

- 전체 통계 탭과 사이트별 통계 페이지에 "방문 / 크롤링" 하위 탭(KindTabs). 사람 방문과 봇 크롤링은
  세는 방법이 달라 한 화면에 섞지 않는다. 기본은 방문
- 방문 패널: 실시간 방문자(최근 5분) · 페이지뷰 · 방문자 · 마지막 방문 → 일별 방문자·페이지뷰 차트 →
  (전체) 방문이 많은 사이트 / (사이트별) 많이 본 페이지·캠페인(utm) → 유입 도메인 · 기기
- 실시간 숫자는 화면을 열어 둔 채 보는 값이라 30초마다 다시 부른다. 보이는 탭의 쿼리만 켠다
- VisitDailyChart 는 lazy() — recharts 는 차트 청크에만 있고 사장님 화면 첫 로딩 스크립트에는 없다
- CrawlerStatsPanel 의 Stat·Section·Table 을 export 해 방문 패널이 같이 쓴다
- orval 재생성(useVisitStats·useSiteVisitStats) — 줄바꿈만 바뀐 생성 파일은 되돌리고 실제 변경분만 담았다

lint(typegen·tsc·eslint)·build 통과. 통계 API 는 임시 개발자 계정으로 nginx·5173 경유 호출 확인.
This commit is contained in:
skkim committed 2026-10-12 15:31:40 +09:00
1 parent 5c5b07d375
commit d15c8185b6
24 files changed
+735 -16

No files matched your search

@@ -31,7 +31,7 @@ export function RangeTabs({value, onChange}: {value: RangeDays; onChange: (days:
);
}
function Stat({label, value}: {label: string; value: ReactNode}) {
export function Stat({label, value}: {label: string; value: ReactNode}) {
return (
<Card>
<CardContent className="pt-4">
@@ -42,7 +42,7 @@ function Stat({label, value}: {label: string; value: ReactNode}) {
);
}
function Section({title, children}: {title: string; children: ReactNode}) {
export function Section({title, children}: {title: string; children: ReactNode}) {
return (
<Card>
<CardHeader>
@@ -53,7 +53,7 @@ function Section({title, children}: {title: string; children: ReactNode}) {
);
}
function Table({head, rows}: {head: string[]; rows: ReactNode[][]}) {
export function Table({head, rows}: {head: string[]; rows: ReactNode[][]}) {
if (rows.length === 0) return <p className="text-xs text-muted-foreground">기록이 없습니다.</p>;
return (
<div className="overflow-x-auto">
@@ -0,0 +1,29 @@
import {cn} from '@/lib/utils';
export type StatsKind = 'visits' | 'crawlers';
const KINDS: ReadonlyArray<readonly [StatsKind, string]> = [
['visits', '방문'],
['crawlers', '크롤링'],
];
/** 통계 종류 — 사람 방문과 봇 크롤링은 세는 방법이 달라 한 화면에 섞지 않는다. */
export function KindTabs({kind, onChange}: {kind: StatsKind; onChange: (kind: StatsKind) => void}) {
return (
<div className="inline-flex rounded-md border border-border p-0.5">
{KINDS.map(([value, label]) => (
<button
key={value}
type="button"
onClick={() => onChange(value)}
className={cn(
'h-7 cursor-pointer rounded px-3 text-xs font-medium transition-colors',
kind === value ? 'bg-foreground text-background' : 'text-muted-foreground hover:text-foreground',
)}
>
{label}
</button>
))}
</div>
);
}
@@ -0,0 +1,15 @@
import {useState} from 'react';
import {KindTabs, type StatsKind} from './KindTabs';
import {OverallCrawlerStats} from './OverallCrawlerStats';
import {OverallVisitStats} from './OverallVisitStats';
/** 사이트관리 "전체 통계" 탭 본문 — 방문과 크롤링을 하위 탭으로 가른다. */
export function OverallStats() {
const [kind, setKind] = useState<StatsKind>('visits');
return (
<div className="space-y-4">
<KindTabs kind={kind} onChange={setKind} />
{kind === 'visits' ? <OverallVisitStats /> : <OverallCrawlerStats />}
</div>
);
}
@@ -0,0 +1,39 @@
import {useState} from 'react';
import {keepPreviousData} from '@tanstack/react-query';
import {Loader2} from 'lucide-react';
import {useVisitStats} from '@/api';
import {EmptyState} from '@/components/layout/AppShell';
import {RangeTabs} from './CrawlerStatsPanel';
import {rangeParams, type RangeDays} from './range';
import {VisitStatsPanel} from './VisitStatsPanel';
/** 실시간 숫자는 30초마다 다시 부른다 — "지금 몇 명" 은 화면을 열어 둔 채 보는 숫자다. */
const REFRESH_MS = 30_000;
export function OverallVisitStats() {
const [days, setDays] = useState<RangeDays>(7);
const {data, isLoading, isError, error} = useVisitStats(rangeParams(days), {
query: {placeholderData: keepPreviousData, refetchInterval: REFRESH_MS},
});
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h2 className="text-sm font-semibold">방문 (전체 사이트)</h2>
<RangeTabs value={days} onChange={setDays} />
</div>
{isLoading && (
<div className="flex justify-center py-20 text-muted-foreground">
<Loader2 className="size-5 animate-spin" />
</div>
)}
{(isError || data?.result?.success === false) && (
<EmptyState
title="통계를 불러오지 못했습니다"
description={(error as Error)?.message ?? data?.result?.desc ?? '잠시 후 다시 시도해 주세요.'}
/>
)}
{data?.result?.success && <VisitStatsPanel data={data} scope="overall" />}
</div>
);
}
@@ -0,0 +1,28 @@
import {Bar, CartesianGrid, ComposedChart, Legend, Line, ResponsiveContainer, Tooltip, XAxis, YAxis} from 'recharts';
import type {VisitDaily} from '@/api';
import {daysBetween} from './range';
const LABEL: Record<string, string> = {views: '페이지뷰', visitors: '방문자'};
/** recharts 는 이 파일에만 둔다 — VisitStatsPanel 이 lazy() 로 부른다. */
export default function VisitDailyChart({daily, from, to}: {daily: VisitDaily[]; from: string; to: string}) {
const byDay = new Map(daily.map((d) => [d.day, d]));
const rows = daysBetween(from, to).map((day) => ({
day,
views: byDay.get(day)?.views ?? 0,
visitors: byDay.get(day)?.visitors ?? 0,
}));
return (
<ResponsiveContainer width="100%" height={240}>
<ComposedChart data={rows} margin={{top: 8, right: 8, bottom: 0, left: 0}}>
<CartesianGrid strokeDasharray="3 3" vertical={false} />
<XAxis dataKey="day" tickFormatter={(day: string) => day.slice(5)} fontSize={11} />
<YAxis allowDecimals={false} fontSize={11} width={32} />
<Tooltip formatter={(value, name) => [value, LABEL[String(name)] ?? name]} />
<Legend formatter={(value) => LABEL[String(value)] ?? value} wrapperStyle={{fontSize: 11}} />
<Bar dataKey="views" fill="#93c5fd" />
<Line dataKey="visitors" stroke="#2563eb" strokeWidth={2} dot={false} />
</ComposedChart>
</ResponsiveContainer>
);
}
@@ -0,0 +1,82 @@
import {lazy, Suspense} from 'react';
import {Link} from 'react-router';
import {Loader2, Users} from 'lucide-react';
import type {ResVisitStats} from '@/api';
import {EmptyState} from '@/components/layout/AppShell';
import {Section, Stat, Table} from './CrawlerStatsPanel';
import {formatKst} from './labels';
const VisitDailyChart = lazy(() => import('./VisitDailyChart'));
const DEVICE_LABEL: Record<string, string> = {desktop: '데스크톱', mobile: '모바일', tablet: '태블릿'};
/** 방문 탭 본문. 전체: 사이트 순위 / 사이트별: 페이지·캠페인. 유입·기기는 공통. */
export function VisitStatsPanel({data, scope}: {data: ResVisitStats; scope: 'overall' | 'site'}) {
const summary = data.summary;
const realtime = data.realtime ?? 0;
// 기간 안에 기록이 없어도 지금 들어와 있는 사람이 있으면 그 숫자는 보여 준다.
if (!summary?.views && !realtime) {
return <EmptyState icon={Users} title="아직 방문 기록이 없습니다" description="선택한 기간에 들어온 방문이 없습니다." />;
}
return (
<div className="space-y-4">
<div className="grid grid-cols-2 gap-3 md:grid-cols-4">
<Stat label="실시간 방문자 (최근 5분)" value={realtime} />
<Stat label="페이지뷰" value={summary?.views ?? 0} />
<Stat label="방문자" value={summary?.visitors ?? 0} />
<Stat label="마지막 방문" value={<span className="text-base">{formatKst(summary?.last_at)}</span>} />
</div>
<Section title="일별 방문자 · 페이지뷰">
{data.date_from && data.date_to && (
<Suspense fallback={<Loader2 className="mx-auto size-5 animate-spin text-muted-foreground" />}>
<VisitDailyChart daily={data.daily ?? []} from={data.date_from} to={data.date_to} />
</Suspense>
)}
</Section>
{scope === 'overall' ? (
<Section title="방문이 많은 사이트">
<Table
head={['사이트', '페이지뷰', '방문자']}
rows={(data.sites ?? []).map((s) => [
<Link key="n" to={`/ops/sites/${s.place_id}/stats`} className="font-medium hover:underline">
{s.name}
</Link>,
s.views,
s.visitors,
])}
/>
</Section>
) : (
<>
<Section title="많이 본 페이지">
<Table
head={['경로', '페이지뷰', '방문자']}
rows={(data.pages ?? []).map((p) => [
<span key="p" className="break-all">
{p.path}
</span>,
p.views,
p.visitors,
])}
/>
</Section>
<Section title="캠페인 (utm_source)">
<Table head={['출처', '페이지뷰']} rows={(data.utm ?? []).map((u) => [u.source, u.views])} />
</Section>
</>
)}
<Section title="유입 도메인">
<Table head={['도메인', '페이지뷰']} rows={(data.referrers ?? []).map((r) => [r.domain, r.views])} />
</Section>
<Section title="기기">
<Table
head={['기기', '페이지뷰']}
rows={(data.devices ?? []).map((d) => [DEVICE_LABEL[d.device] ?? d.device, d.views])}
/>
</Section>
</div>
);
}