[feat] negodata: 통계 페이지(성과 분석) 추가 — 파생 집계 API + recharts 차트
- 백엔드 GET /v1/statistics/summary: 회사/내견적 스코프, 최근 6개월 파생 집계(저장 X, DDL 0) - 지표: 총절감/절감률/낙찰률/앵커도달률/마감수/재견적라운드 + 월별추이·마감결과분해·참여율·유형별(협상/견적)·카테고리·카드빈도 - 프론트 recharts+shadcn Chart, 사이드바 통계 nav, /statistics Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
dc0e78ec73
commit
c32ee300e6
39 files changed
+2140
-1
No files matched your search
@@ -0,0 +1,69 @@
|
||||
import { Award, Percent, RefreshCw, Target, TrendingDown, CircleCheckBig } from 'lucide-react';
|
||||
import { Panel } from './components/Panel';
|
||||
import { StatTile } from './components/StatTile';
|
||||
import { SavingsTrendChart } from './components/SavingsTrendChart';
|
||||
import { OutcomeChart } from './components/OutcomeChart';
|
||||
import { ParticipationChart } from './components/ParticipationChart';
|
||||
import { TypeSplitChart } from './components/TypeSplitChart';
|
||||
import { CategoryChart } from './components/CategoryChart';
|
||||
import { CardEffectChart } from './components/CardEffectChart';
|
||||
import { wonCompact, pct, signedWonCompact } from './fmt';
|
||||
import type { StatData } from './types';
|
||||
|
||||
// 통계 본문. KPI 요약 + 절감 분석 + 성사/프로세스 + 카드 효과. scope(회사/내견적)별로 동일 레이아웃.
|
||||
export function StatisticsView({ data }: { data: StatData }) {
|
||||
const k = data.kpi;
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* 임팩트 요약 KPI */}
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
|
||||
<StatTile
|
||||
label="총 절감액 (목표가 대비)"
|
||||
value={wonCompact(k.totalSavings)}
|
||||
icon={TrendingDown}
|
||||
tone="emerald"
|
||||
delta={{ text: `${signedWonCompact(k.savingsDeltaMoM)} 전월비`, good: k.savingsDeltaMoM >= 0 }}
|
||||
/>
|
||||
<StatTile label="평균 절감률" value={pct(k.savingsRate)} icon={Percent} tone="emerald" />
|
||||
<StatTile label="낙찰률" value={pct(k.awardRate)} icon={Award} tone="blue" />
|
||||
<StatTile label="평균 앵커 도달률" value={pct(k.anchorReachRate)} icon={Target} tone="purple" />
|
||||
<StatTile label="마감 견적" value={`${k.closedCount}건`} icon={CircleCheckBig} tone="zinc" />
|
||||
<StatTile label="평균 재견적 라운드" value={k.regenAvgRound.toFixed(1)} icon={RefreshCw} tone="amber" />
|
||||
</div>
|
||||
|
||||
{/* 절감 분석 */}
|
||||
<div className="grid gap-4 lg:grid-cols-3">
|
||||
<Panel
|
||||
title="월별 절감 추이"
|
||||
subtitle="목표가 대비 절감액 · 막대에 마우스를 올리면 절감률"
|
||||
className="lg:col-span-2"
|
||||
>
|
||||
<SavingsTrendChart data={data.trend} />
|
||||
</Panel>
|
||||
<Panel title="마감 결과" subtitle="낙찰 vs 개찰 사유 4종">
|
||||
<OutcomeChart data={data.outcome} />
|
||||
</Panel>
|
||||
</div>
|
||||
|
||||
{/* 성사 · 프로세스 */}
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<Panel title="협력사 참여" subtitle="초대 세션 대비 응찰·미응찰·거부">
|
||||
<ParticipationChart data={data.participation} />
|
||||
</Panel>
|
||||
<Panel title="유형별 성과" subtitle="협상(1:1) vs 견적(1:N) 낙찰률">
|
||||
<TypeSplitChart data={data.typeSplit} />
|
||||
</Panel>
|
||||
</div>
|
||||
|
||||
{/* 카테고리 · 카드 */}
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<Panel title="카테고리별 절감" subtitle="어디서 절감이 났나">
|
||||
<CategoryChart data={data.categories} />
|
||||
</Panel>
|
||||
<Panel title="협상카드 효과" subtitle="유형별 사용빈도 + 사용 직후 평균 제시가 하락">
|
||||
<CardEffectChart data={data.cards} />
|
||||
</Panel>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { useGetStatisticsSummary } from '@/api/generated/statistics/statistics';
|
||||
import type { StatScope as ApiScope } from '@/api/generated/model/statScope';
|
||||
import type { StatData } from './types';
|
||||
|
||||
// 생성 API(snake_case, 전부 optional) → 도메인 StatData(camelCase) 매퍼.
|
||||
// api/generated 는 수정 금지라 여기서 한 번에 흡수한다(mapXxx 관례). 차트 컴포넌트는 StatData만 안다.
|
||||
function mapScope(s?: ApiScope): StatData {
|
||||
const k = s?.kpi ?? {};
|
||||
const o = s?.outcome ?? {};
|
||||
const p = s?.participation ?? {};
|
||||
return {
|
||||
kpi: {
|
||||
totalSavings: k.total_savings ?? 0,
|
||||
savingsRate: k.savings_rate ?? 0,
|
||||
awardRate: k.award_rate ?? 0,
|
||||
anchorReachRate: k.anchor_reach_rate ?? 0,
|
||||
savingsDeltaMoM: k.savings_delta_mom ?? 0,
|
||||
closedCount: k.closed_count ?? 0,
|
||||
regenAvgRound: k.regen_avg_round ?? 0,
|
||||
},
|
||||
trend: (s?.trend ?? []).map((t) => ({ month: t.month, savings: t.savings ?? 0, rate: t.rate ?? 0 })),
|
||||
outcome: {
|
||||
awarded: o.awarded ?? 0,
|
||||
openPrice: o.open_price ?? 0,
|
||||
openEqual: o.open_equal ?? 0,
|
||||
openNoshow: o.open_noshow ?? 0,
|
||||
openReject: o.open_reject ?? 0,
|
||||
},
|
||||
participation: {
|
||||
bid: p.bid ?? 0,
|
||||
noParticipate: p.no_participate ?? 0,
|
||||
rejected: p.rejected ?? 0,
|
||||
},
|
||||
typeSplit: (s?.type_split ?? []).map((r) => ({
|
||||
label: r.label,
|
||||
awardRate: r.award_rate ?? 0,
|
||||
avgSavings: r.avg_savings ?? 0,
|
||||
count: r.count ?? 0,
|
||||
})),
|
||||
categories: (s?.categories ?? []).map((c) => ({ category: c.category, savings: c.savings ?? 0, count: c.count ?? 0 })),
|
||||
cards: (s?.cards ?? []).map((c) => ({
|
||||
type: c.type === 'wild' ? 'wild' : 'nego',
|
||||
label: c.label,
|
||||
uses: c.uses ?? 0,
|
||||
avgDrop: c.avg_drop ?? 0,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
// 통계 요약 훅. company/mine 두 스코프를 매핑해 함께 돌려준다.
|
||||
export function useStatistics() {
|
||||
const q = useGetStatisticsSummary();
|
||||
return {
|
||||
isLoading: q.isLoading,
|
||||
isError: q.isError,
|
||||
company: mapScope(q.data?.company),
|
||||
mine: mapScope(q.data?.mine),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { Bar, BarChart, CartesianGrid, Cell, XAxis, YAxis } from 'recharts';
|
||||
import { ChartContainer, ChartTooltip, type ChartConfig } from '@/components/ui/chart';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { SERIES_BG, themeOf, type SeriesKey } from '../palette';
|
||||
import { won } from '../fmt';
|
||||
import type { CardTypeUsage } from '../types';
|
||||
|
||||
// 카드 유형별 사용빈도(막대) + 효과(평균 제시가 하락, avgDrop=B안). 유형별 색.
|
||||
const TONE: Record<CardTypeUsage['type'], SeriesKey> = { nego: 'blue', wild: 'purple' };
|
||||
|
||||
export function CardEffectChart({ data }: { data: CardTypeUsage[] }) {
|
||||
const rows = data.map((d) => ({ ...d, key: d.type, tone: TONE[d.type] }));
|
||||
const config = Object.fromEntries(rows.map((r) => [r.key, { label: r.label, theme: themeOf(r.tone) }])) satisfies ChartConfig;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<ChartContainer config={config} className="aspect-auto h-44 w-full">
|
||||
<BarChart data={rows} margin={{ top: 8, right: 8, left: 4, bottom: 0 }}>
|
||||
<CartesianGrid vertical={false} strokeDasharray="3 3" />
|
||||
<XAxis dataKey="label" tickLine={false} axisLine={false} tickMargin={8} />
|
||||
<YAxis tickLine={false} axisLine={false} width={32} />
|
||||
<ChartTooltip cursor={false} content={<CardTooltip />} />
|
||||
<Bar dataKey="uses" radius={[4, 4, 0, 0]} maxBarSize={64}>
|
||||
{rows.map((r) => (
|
||||
<Cell key={r.key} fill={`var(--color-${r.key})`} />
|
||||
))}
|
||||
</Bar>
|
||||
</BarChart>
|
||||
</ChartContainer>
|
||||
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{rows.map((r) => (
|
||||
<div key={r.key} className="flex items-center gap-1.5 rounded border border-border bg-muted/30 px-3 py-1.5">
|
||||
<span className={cn('size-2.5 shrink-0 rounded-[3px]', SERIES_BG[r.tone])} />
|
||||
<div className="min-w-0">
|
||||
<Typography as="p" variant="caption" className="truncate">
|
||||
{r.label} 평균 하락
|
||||
</Typography>
|
||||
<Typography as="p" variant="small" className="font-mono text-[12px] font-bold text-foreground">
|
||||
{/* TODO: 제시가 하락 델타 미배선 — 백엔드 avg_drop=0 동안 '측정 예정' */}
|
||||
{r.avgDrop > 0 ? won(r.avgDrop) : '측정 예정'}
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CardTooltip({ active, payload }: { active?: boolean; payload?: { payload: CardTypeUsage }[] }) {
|
||||
if (!active || !payload?.length) return null;
|
||||
const p = payload[0].payload;
|
||||
return (
|
||||
<div className="rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl">
|
||||
<Typography as="p" variant="caption" className="mb-0.5 font-medium text-foreground">
|
||||
{p.label}
|
||||
</Typography>
|
||||
<Typography as="p" variant="caption">
|
||||
사용 <span className="font-mono text-foreground">{p.uses.toLocaleString()}회</span>
|
||||
</Typography>
|
||||
{p.avgDrop > 0 && (
|
||||
<Typography as="p" variant="caption">
|
||||
평균 제시가 하락 <span className="font-mono text-foreground">{won(p.avgDrop)}</span>
|
||||
</Typography>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Bar, BarChart, LabelList, XAxis, YAxis } from 'recharts';
|
||||
import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from '@/components/ui/chart';
|
||||
import { themeOf } from '../palette';
|
||||
import { won, wonCompact } from '../fmt';
|
||||
import type { CategorySaving } from '../types';
|
||||
|
||||
// 카테고리별 절감액(가로 막대, 단일 hue=크기). 막대 끝 직접 라벨.
|
||||
const config = {
|
||||
savings: { label: '절감액', theme: themeOf('blue') },
|
||||
} satisfies ChartConfig;
|
||||
|
||||
export function CategoryChart({ data }: { data: CategorySaving[] }) {
|
||||
const rows = [...data].sort((a, b) => b.savings - a.savings);
|
||||
|
||||
return (
|
||||
<ChartContainer config={config} className="aspect-auto h-56 w-full">
|
||||
<BarChart data={rows} layout="vertical" margin={{ top: 4, right: 44, left: 4, bottom: 0 }}>
|
||||
<XAxis type="number" hide />
|
||||
<YAxis type="category" dataKey="category" tickLine={false} axisLine={false} width={56} />
|
||||
<ChartTooltip
|
||||
cursor={false}
|
||||
content={<ChartTooltipContent nameKey="savings" formatter={(value) => `절감액 ${won(Number(value))}`} />}
|
||||
/>
|
||||
<Bar dataKey="savings" fill="var(--color-savings)" radius={[0, 4, 4, 0]} maxBarSize={26}>
|
||||
<LabelList dataKey="savings" position="right" className="fill-foreground" fontSize={11} formatter={(v: number) => wonCompact(v)} />
|
||||
</Bar>
|
||||
</BarChart>
|
||||
</ChartContainer>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Cell, Pie, PieChart } from 'recharts';
|
||||
import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from '@/components/ui/chart';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { SERIES_BG, themeOf, type SeriesKey } from '../palette';
|
||||
import { pct } from '../fmt';
|
||||
import type { OutcomeBreakdown } from '../types';
|
||||
|
||||
// 마감 결과 분해: 낙찰 + 개찰 4종(도넛). 가운데 낙찰률, 하단 범례+건수.
|
||||
const SLICES: { key: keyof OutcomeBreakdown; label: string; tone: SeriesKey }[] = [
|
||||
{ key: 'awarded', label: '낙찰', tone: 'emerald' },
|
||||
{ key: 'openPrice', label: '개찰·가격', tone: 'amber' },
|
||||
{ key: 'openEqual', label: '개찰·동가', tone: 'purple' },
|
||||
{ key: 'openNoshow', label: '개찰·미응찰', tone: 'zinc' },
|
||||
{ key: 'openReject', label: '개찰·거부', tone: 'rose' },
|
||||
];
|
||||
|
||||
const config = Object.fromEntries(SLICES.map((s) => [s.key, { label: s.label, theme: themeOf(s.tone) }])) satisfies ChartConfig;
|
||||
|
||||
export function OutcomeChart({ data }: { data: OutcomeBreakdown }) {
|
||||
const rows = SLICES.map((s) => ({ ...s, value: data[s.key] }));
|
||||
const total = rows.reduce((sum, r) => sum + r.value, 0) || 1;
|
||||
const awardRate = data.awarded / total;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="relative mx-auto">
|
||||
<ChartContainer config={config} className="aspect-square h-44">
|
||||
<PieChart>
|
||||
<ChartTooltip cursor={false} content={<ChartTooltipContent nameKey="key" hideLabel />} />
|
||||
<Pie data={rows} dataKey="value" nameKey="key" innerRadius={52} outerRadius={72} strokeWidth={2} paddingAngle={2}>
|
||||
{rows.map((r) => (
|
||||
<Cell key={r.key} fill={`var(--color-${r.key})`} className="stroke-background" />
|
||||
))}
|
||||
</Pie>
|
||||
</PieChart>
|
||||
</ChartContainer>
|
||||
<div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center">
|
||||
<Typography variant="h3" className="leading-none">
|
||||
{pct(awardRate, 0)}
|
||||
</Typography>
|
||||
<Typography variant="caption">낙찰률</Typography>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-1.5">
|
||||
{rows.map((r) => (
|
||||
<div key={r.key} className="flex items-center gap-1.5">
|
||||
<span className={cn('size-2.5 shrink-0 rounded-[3px]', SERIES_BG[r.tone])} />
|
||||
<Typography as="span" variant="caption" className="flex-1 truncate">
|
||||
{r.label}
|
||||
</Typography>
|
||||
<Typography as="span" variant="caption" className={cn('font-mono', r.tone === 'emerald' && 'text-foreground')}>
|
||||
{r.value}
|
||||
</Typography>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
// 통계 섹션 카드. 제목/부제 + 우측 슬롯(범례 등) + 본문.
|
||||
export function Panel({
|
||||
title,
|
||||
subtitle,
|
||||
right,
|
||||
className,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
right?: ReactNode;
|
||||
className?: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<Card className={cn('flex flex-col gap-3 p-4', className)}>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<Typography variant="h4" className="text-[15px]">
|
||||
{title}
|
||||
</Typography>
|
||||
{subtitle && (
|
||||
<Typography variant="caption" className="mt-0.5 block">
|
||||
{subtitle}
|
||||
</Typography>
|
||||
)}
|
||||
</div>
|
||||
{right}
|
||||
</div>
|
||||
{children}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { Bar, BarChart, XAxis, YAxis } from 'recharts';
|
||||
import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from '@/components/ui/chart';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { SERIES_BG, themeOf, type SeriesKey } from '../palette';
|
||||
import { pct } from '../fmt';
|
||||
import type { ParticipationBreakdown } from '../types';
|
||||
|
||||
// 협력사 참여: 초대 세션 대비 응찰/미응찰/거부(가로 100% 스택). 응찰=참여율.
|
||||
const PARTS: { key: keyof ParticipationBreakdown; label: string; tone: SeriesKey }[] = [
|
||||
{ key: 'bid', label: '응찰', tone: 'emerald' },
|
||||
{ key: 'noParticipate', label: '미응찰', tone: 'zinc' },
|
||||
{ key: 'rejected', label: '거부', tone: 'rose' },
|
||||
];
|
||||
|
||||
const config = Object.fromEntries(PARTS.map((p) => [p.key, { label: p.label, theme: themeOf(p.tone) }])) satisfies ChartConfig;
|
||||
|
||||
export function ParticipationChart({ data }: { data: ParticipationBreakdown }) {
|
||||
const total = PARTS.reduce((sum, p) => sum + data[p.key], 0) || 1;
|
||||
const rate = data.bid / total;
|
||||
const row = [{ name: '세션', ...data }];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-baseline gap-2">
|
||||
<Typography variant="h3" className="leading-none">
|
||||
{pct(rate)}
|
||||
</Typography>
|
||||
<Typography variant="caption">응찰 참여율 · 전체 {total.toLocaleString()}건</Typography>
|
||||
</div>
|
||||
|
||||
<ChartContainer config={config} className="aspect-auto h-12 w-full">
|
||||
<BarChart data={row} layout="vertical" margin={{ top: 0, right: 0, left: 0, bottom: 0 }}>
|
||||
<XAxis type="number" hide />
|
||||
<YAxis type="category" dataKey="name" hide />
|
||||
<ChartTooltip cursor={false} content={<ChartTooltipContent />} />
|
||||
<Bar dataKey="bid" stackId="a" fill="var(--color-bid)" radius={[6, 0, 0, 6]} />
|
||||
<Bar dataKey="noParticipate" stackId="a" fill="var(--color-noParticipate)" />
|
||||
<Bar dataKey="rejected" stackId="a" fill="var(--color-rejected)" radius={[0, 6, 6, 0]} />
|
||||
</BarChart>
|
||||
</ChartContainer>
|
||||
|
||||
<div className="flex flex-wrap gap-x-4 gap-y-1.5">
|
||||
{PARTS.map((p) => (
|
||||
<div key={p.key} className="flex items-center gap-1.5">
|
||||
<span className={cn('size-2.5 shrink-0 rounded-[3px]', SERIES_BG[p.tone])} />
|
||||
<Typography as="span" variant="caption">
|
||||
{p.label}
|
||||
</Typography>
|
||||
<Typography as="span" variant="caption" className="font-mono text-foreground">
|
||||
{data[p.key].toLocaleString()}
|
||||
</Typography>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from 'recharts';
|
||||
import { ChartContainer, ChartTooltip, type ChartConfig } from '@/components/ui/chart';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
import { themeOf } from '../palette';
|
||||
import { won, wonCompact, pct, monthLabel } from '../fmt';
|
||||
import type { MonthPoint } from '../types';
|
||||
|
||||
// 월별 목표가 대비 절감액(단일 시리즈=크기). 한 축 원칙 — 절감률은 이중축 대신 툴팁에 얹는다.
|
||||
const config = {
|
||||
savings: { label: '절감액', theme: themeOf('emerald') },
|
||||
} satisfies ChartConfig;
|
||||
|
||||
export function SavingsTrendChart({ data }: { data: MonthPoint[] }) {
|
||||
return (
|
||||
<ChartContainer config={config} className="aspect-auto h-56 w-full">
|
||||
<BarChart data={data} margin={{ top: 8, right: 8, left: 4, bottom: 0 }}>
|
||||
<CartesianGrid vertical={false} strokeDasharray="3 3" />
|
||||
<XAxis dataKey="month" tickLine={false} axisLine={false} tickMargin={8} tickFormatter={monthLabel} />
|
||||
<YAxis tickLine={false} axisLine={false} width={44} tickFormatter={(v) => wonCompact(Number(v))} />
|
||||
<ChartTooltip cursor={false} content={<TrendTooltip />} />
|
||||
<Bar dataKey="savings" fill="var(--color-savings)" radius={[4, 4, 0, 0]} maxBarSize={48} />
|
||||
</BarChart>
|
||||
</ChartContainer>
|
||||
);
|
||||
}
|
||||
|
||||
// 절감액(₩) + 절감률을 한 툴팁에. payload[0].payload = MonthPoint.
|
||||
function TrendTooltip({ active, payload }: { active?: boolean; payload?: { payload: MonthPoint }[] }) {
|
||||
if (!active || !payload?.length) return null;
|
||||
const p = payload[0].payload;
|
||||
return (
|
||||
<div className="rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl">
|
||||
<Typography as="p" variant="caption" className="mb-0.5 font-medium text-foreground">
|
||||
{monthLabel(p.month)}
|
||||
</Typography>
|
||||
<Typography as="p" variant="caption" className="font-mono text-foreground">
|
||||
{won(p.savings)} · {pct(p.rate)}
|
||||
</Typography>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { ElementType } from 'react';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { TONE_CHIP, type Tone } from '@/features/dashboard/tones';
|
||||
|
||||
// 통계 상단 KPI 타일. 컬러 아이콘칩 + 큰 값(문자열) + 라벨 + 옵션 증감칩.
|
||||
// 대시보드 KpiTile 은 숫자 전용이라, 문자열 값(₩/%)·증감을 받는 통계용 변형으로 둔다.
|
||||
export function StatTile({
|
||||
label,
|
||||
value,
|
||||
icon: Icon,
|
||||
tone,
|
||||
delta,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
icon: ElementType;
|
||||
tone: Tone;
|
||||
delta?: { text: string; good?: boolean };
|
||||
}) {
|
||||
return (
|
||||
<Card className="gap-0 py-0">
|
||||
<CardContent className="flex items-center gap-3 px-4 py-3.5">
|
||||
<div className={cn('flex size-9 shrink-0 items-center justify-center rounded-lg', TONE_CHIP[tone])}>
|
||||
<Icon size={18} />
|
||||
</div>
|
||||
<div className="min-w-0 space-y-0.5">
|
||||
<div className="flex items-baseline gap-1.5">
|
||||
<Typography variant="h3" className="leading-none">
|
||||
{value}
|
||||
</Typography>
|
||||
{delta && (
|
||||
<Typography
|
||||
as="span"
|
||||
variant="caption"
|
||||
className={cn('font-medium', delta.good ? 'text-emerald-600 dark:text-emerald-400' : 'text-muted-foreground')}
|
||||
>
|
||||
{delta.text}
|
||||
</Typography>
|
||||
)}
|
||||
</div>
|
||||
<Typography variant="caption" className="block truncate">
|
||||
{label}
|
||||
</Typography>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Bar, BarChart, CartesianGrid, Cell, XAxis, YAxis } from 'recharts';
|
||||
import { ChartContainer, ChartTooltip, type ChartConfig } from '@/components/ui/chart';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
import { themeOf, type SeriesKey } from '../palette';
|
||||
import { won, pct } from '../fmt';
|
||||
import type { TypeSplitRow } from '../types';
|
||||
|
||||
// 견적 유형(협상 1:1 / 경매 1:N)별 낙찰률 비교(막대=낙찰률, 한 축). 평균 절감·건수는 툴팁.
|
||||
// 유형마다 색이 달라 --color-<key> 를 유형별 키로 주입한다(다크모드 자동 전환).
|
||||
const TONES: SeriesKey[] = ['blue', 'purple'];
|
||||
|
||||
export function TypeSplitChart({ data }: { data: TypeSplitRow[] }) {
|
||||
const rows = data.map((d, i) => ({ ...d, key: `t${i}`, tone: TONES[i % TONES.length] }));
|
||||
const config = Object.fromEntries(rows.map((r) => [r.key, { label: r.label, theme: themeOf(r.tone) }])) satisfies ChartConfig;
|
||||
|
||||
return (
|
||||
<ChartContainer config={config} className="aspect-auto h-56 w-full">
|
||||
<BarChart data={rows} margin={{ top: 8, right: 8, left: 4, bottom: 0 }}>
|
||||
<CartesianGrid vertical={false} strokeDasharray="3 3" />
|
||||
<XAxis dataKey="label" tickLine={false} axisLine={false} tickMargin={8} />
|
||||
<YAxis tickLine={false} axisLine={false} width={40} domain={[0, 1]} tickFormatter={(v) => pct(Number(v), 0)} />
|
||||
<ChartTooltip cursor={false} content={<TypeTooltip />} />
|
||||
<Bar dataKey="awardRate" radius={[4, 4, 0, 0]} maxBarSize={72}>
|
||||
{rows.map((r) => (
|
||||
<Cell key={r.key} fill={`var(--color-${r.key})`} />
|
||||
))}
|
||||
</Bar>
|
||||
</BarChart>
|
||||
</ChartContainer>
|
||||
);
|
||||
}
|
||||
|
||||
function TypeTooltip({ active, payload }: { active?: boolean; payload?: { payload: TypeSplitRow }[] }) {
|
||||
if (!active || !payload?.length) return null;
|
||||
const p = payload[0].payload;
|
||||
return (
|
||||
<div className="rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl">
|
||||
<Typography as="p" variant="caption" className="mb-0.5 font-medium text-foreground">
|
||||
{p.label}
|
||||
</Typography>
|
||||
<Typography as="p" variant="caption">
|
||||
낙찰률 <span className="font-mono text-foreground">{pct(p.awardRate)}</span>
|
||||
</Typography>
|
||||
<Typography as="p" variant="caption">
|
||||
평균 절감 <span className="font-mono text-foreground">{won(p.avgSavings)}</span>
|
||||
</Typography>
|
||||
<Typography as="p" variant="caption">
|
||||
건수 <span className="font-mono text-foreground">{p.count}</span>
|
||||
</Typography>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// 통계 표기 포맷터. 금액 단위 원, 비율 0~1.
|
||||
|
||||
export const won = (n: number) => `₩${Math.round(n).toLocaleString()}`;
|
||||
|
||||
// 축/타일용 압축 표기: 억/만 (한글). 큰 금액을 좁은 폭에 담을 때.
|
||||
export function wonCompact(n: number): string {
|
||||
const abs = Math.abs(n);
|
||||
const sign = n < 0 ? '−' : '';
|
||||
if (abs >= 100_000_000) return `${sign}${(abs / 100_000_000).toFixed(1)}억`;
|
||||
if (abs >= 10_000) return `${sign}${Math.round(abs / 10_000).toLocaleString()}만`;
|
||||
return `${sign}${abs.toLocaleString()}`;
|
||||
}
|
||||
|
||||
// 비율 → %. 소수 자릿수 기본 1.
|
||||
export const pct = (r: number, digits = 1) => `${(r * 100).toFixed(digits)}%`;
|
||||
|
||||
// 증감 표기(+/−). 절감 증가는 긍정이라 + 를 명시한다.
|
||||
export const signedWonCompact = (n: number) => `${n >= 0 ? '+' : ''}${wonCompact(n)}`;
|
||||
|
||||
// 'YYYY-MM' → 'M월'
|
||||
export const monthLabel = (ym: string) => `${parseInt(ym.slice(5, 7), 10)}월`;
|
||||
@@ -0,0 +1,3 @@
|
||||
export { StatisticsView } from './StatisticsView';
|
||||
export { useStatistics } from './api';
|
||||
export { type Scope, type StatData } from './types';
|
||||
@@ -0,0 +1,27 @@
|
||||
// 통계 차트 시리즈 색. features/dashboard/tones 와 같은 계열(Tailwind 램프)을 라이트/다크 한 쌍으로 둔다.
|
||||
// shadcn ChartConfig 의 theme({light,dark}) 로 주입 → [data-chart] 스코프 --color-<key> CSS 변수 → 다크모드 자동 전환.
|
||||
// 색 단독 식별 금지 — 모든 차트는 범례/값을 함께 노출한다(색맹 안전, dataviz 6단계).
|
||||
export type SeriesKey = 'emerald' | 'amber' | 'blue' | 'purple' | 'rose' | 'zinc';
|
||||
|
||||
export const SERIES_COLOR: Record<SeriesKey, { light: string; dark: string }> = {
|
||||
emerald: { light: '#10b981', dark: '#34d399' }, // 절감/낙찰/응찰 = 긍정
|
||||
amber: { light: '#f59e0b', dark: '#fbbf24' }, // 개찰(가격) = 주의
|
||||
blue: { light: '#3b82f6', dark: '#60a5fa' }, // 협상/카테고리 기본
|
||||
purple: { light: '#a855f7', dark: '#c084fc' }, // 경매/동가
|
||||
rose: { light: '#f43f5e', dark: '#fb7185' }, // 거부
|
||||
zinc: { light: '#d4d4d8', dark: '#52525b' }, // 미응찰/중립
|
||||
};
|
||||
|
||||
// shadcn ChartConfig 의 theme 슬롯용.
|
||||
export const themeOf = (k: SeriesKey) => ({ light: SERIES_COLOR[k].light, dark: SERIES_COLOR[k].dark });
|
||||
|
||||
// 차트 밖(범례 점 등) DOM 요소용 Tailwind bg 클래스. --color-<key> CSS 변수는 [data-chart] 스코프 안에만 있어
|
||||
// 차트 바깥에선 못 쓰므로, 여기서 라이트/다크 램프 스텝을 직접 건다.
|
||||
export const SERIES_BG: Record<SeriesKey, string> = {
|
||||
emerald: 'bg-emerald-500 dark:bg-emerald-400',
|
||||
amber: 'bg-amber-500 dark:bg-amber-400',
|
||||
blue: 'bg-blue-500 dark:bg-blue-400',
|
||||
purple: 'bg-purple-500 dark:bg-purple-400',
|
||||
rose: 'bg-rose-500 dark:bg-rose-400',
|
||||
zinc: 'bg-zinc-300 dark:bg-zinc-600',
|
||||
};
|
||||
@@ -0,0 +1,65 @@
|
||||
// 통계 도메인 타입. 백엔드 생성타입(snake_case)을 api.ts mapScope 가 이 camelCase 형태로 변환한다.
|
||||
// 금액 단위: 원. 비율: 0~1.
|
||||
|
||||
export type Scope = 'company' | 'mine';
|
||||
|
||||
export interface StatKpi {
|
||||
totalSavings: number; // 총 절감액(목표가 대비)
|
||||
savingsRate: number; // 평균 절감률
|
||||
awardRate: number; // 낙찰률(마감 견적 중 낙찰 비율)
|
||||
anchorReachRate: number; // 평균 앵커 도달률 (목표−투찰)/(목표−앵커)
|
||||
savingsDeltaMoM: number; // 전월 대비 절감액 증감
|
||||
closedCount: number; // 마감 견적 수(창)
|
||||
regenAvgRound: number; // 평균 재견적 라운드(1=재견적 없음)
|
||||
}
|
||||
|
||||
export interface MonthPoint {
|
||||
month: string; // 'YYYY-MM'
|
||||
savings: number;
|
||||
rate: number;
|
||||
}
|
||||
|
||||
export interface OutcomeBreakdown {
|
||||
awarded: number;
|
||||
openPrice: number; // 가격 미달
|
||||
openEqual: number; // 동가
|
||||
openNoshow: number; // 미응찰
|
||||
openReject: number; // 협상 거부
|
||||
}
|
||||
|
||||
export interface ParticipationBreakdown {
|
||||
bid: number; // 응찰(완료)
|
||||
noParticipate: number; // 미응찰
|
||||
rejected: number; // 거부
|
||||
}
|
||||
|
||||
export interface TypeSplitRow {
|
||||
label: string;
|
||||
awardRate: number;
|
||||
avgSavings: number;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface CategorySaving {
|
||||
category: string;
|
||||
savings: number;
|
||||
count: number; // 낙찰 세션 건수
|
||||
}
|
||||
|
||||
// avgDrop = 카드 사용 직후 상대 제시가 평균 하락액(B안). 미배선 시 0 → 프론트 '측정 예정'.
|
||||
export interface CardTypeUsage {
|
||||
type: 'nego' | 'wild';
|
||||
label: string;
|
||||
uses: number;
|
||||
avgDrop: number;
|
||||
}
|
||||
|
||||
export interface StatData {
|
||||
kpi: StatKpi;
|
||||
trend: MonthPoint[];
|
||||
outcome: OutcomeBreakdown;
|
||||
participation: ParticipationBreakdown;
|
||||
typeSplit: TypeSplitRow[];
|
||||
categories: CategorySaving[];
|
||||
cards: CardTypeUsage[];
|
||||
}
|
||||
Reference in new issue
Block a user