chore(lps-admin): 폴더명 lps-temp-fe → lps-admin
임시 FE 가 정식 관리자 콘솔이 되어 이름을 용도에 맞게 변경. 루트 병렬 유지(lps/ 는 파이썬 백엔드 루트라 중첩 시 비대칭 + Docker 빌드 컨텍스트 오염). package.json name 동기화. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6eb71eb035
commit
992a3246a8
21 files changed
+1
-1
No files matched your search
@@ -0,0 +1,3 @@
|
||||
node_modules
|
||||
dist
|
||||
*.local
|
||||
@@ -0,0 +1,33 @@
|
||||
# LPS 관리자 페이지
|
||||
|
||||
LPS(인터넷 최저가 검색)의 운영 지표를 보고 필수 액션(수동 재검색·DEAD 재큐)을 수행하는
|
||||
React 관리자 페이지입니다. 서버 동작 설정은 여기서 바꾸지 않습니다 — 설정 소스는 서버의
|
||||
`config.<env>.toml` 하나(2026-07-13 협의).
|
||||
|
||||
## 실행 (개발)
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run dev # http://localhost:5174 — /v1·/healthz 는 vite 프록시로 :9600 에 전달(CORS 불필요)
|
||||
```
|
||||
|
||||
LPS API 를 먼저 띄워두세요: `cd ../lps && ./run_local_server.sh`.
|
||||
다른 호스트의 API 를 보려면 `VITE_LPS_URL=http://<host>:9600 npm run dev` 또는
|
||||
앱의 **설정** 페이지에서 API 주소를 지정합니다(guard 켜진 prod 는 API 키도 입력 — X-API-Key 자동 첨부).
|
||||
|
||||
## 페이지
|
||||
|
||||
| 페이지 | 내용 | 데이터 |
|
||||
|---|---|---|
|
||||
| 대시보드 | 큐/차단/비용/DB풀 스탯 타일 + 임계 배너 + 큐 추이(5초 폴링) | `GET /v1/lps/ops` |
|
||||
| 작업 큐 | 목록(상태·검색 필터)·상세(결과/원가/오류)·**DEAD 재큐** | `/v1/lps/jobs`, `/jobs/{id}/requeue` |
|
||||
| 상품·가격 | 가격 추이 3선(네이버·쿠팡·최종)·몰별 최저가·검증 링크·**지금 다시 검색** | `/v1/lps/products`, `/products/{code}/history`, `POST /search` |
|
||||
| 크롤 상태 | IP 세션 종료사유 도넛·요청 수 분포(+차단 시작 기준선 = 예산 튜닝 뷰)·차단 이력 | `/v1/lps/stats/ip-sessions`, `/stats/bot` |
|
||||
| 비용 | 시간별 원가 스택(AI vs 프록시)·건당 평균·평균 소요 | `/v1/lps/stats/cost` |
|
||||
|
||||
## 스택·규칙
|
||||
|
||||
- Vite + React + TS + Tailwind v4 + recharts + @tanstack/react-query + react-router (negodata 프론트와 동일 계열, 경량)
|
||||
- 색 토큰은 숫자 스케일(`src/index.css` @theme). 차트 시리즈 색은 **엔터티 고정** —
|
||||
네이버 `#008a43`(적록색약 분리 검증 통과 톤) · 쿠팡 `#f0455b` · 최종 `#4f46e5`. 순서·색 재배정 금지.
|
||||
- 빌드: `npm run build` (tsc 포함) → `dist/`
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>LPS 관리자 — 인터넷 최저가 검색</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+2795
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "lps-admin",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tailwindcss/vite": "^4.1.0",
|
||||
"@tanstack/react-query": "^5.62.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router": "^7.1.0",
|
||||
"recharts": "^2.15.0",
|
||||
"tailwindcss": "^4.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.3.12",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"typescript": "~5.6.3",
|
||||
"vite": "^6.0.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/** fetch 래퍼 — base URL·X-API-Key(설정 페이지, localStorage) 자동 적용 + 봉투(result) 검사. */
|
||||
|
||||
const BASE_KEY = "lps.baseUrl";
|
||||
const API_KEY = "lps.apiKey";
|
||||
|
||||
export const settings = {
|
||||
baseUrl: () => localStorage.getItem(BASE_KEY) ?? "",
|
||||
apiKey: () => localStorage.getItem(API_KEY) ?? "",
|
||||
save(baseUrl: string, apiKey: string) {
|
||||
baseUrl ? localStorage.setItem(BASE_KEY, baseUrl.replace(/\/$/, "")) : localStorage.removeItem(BASE_KEY);
|
||||
apiKey ? localStorage.setItem(API_KEY, apiKey) : localStorage.removeItem(API_KEY);
|
||||
},
|
||||
};
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const headers: Record<string, string> = { ...((init?.headers as Record<string, string>) ?? {}) };
|
||||
const key = settings.apiKey();
|
||||
if (key) headers["X-API-Key"] = key;
|
||||
const res = await fetch(settings.baseUrl() + path, { ...init, headers });
|
||||
if (res.status === 401) throw new Error("인증 실패(401) — 설정에서 API 키를 확인하세요");
|
||||
if (!res.ok) throw new Error(`서버 오류 (HTTP ${res.status})`);
|
||||
const body = (await res.json()) as T & { result?: { success: boolean; desc?: string } };
|
||||
if (body?.result && body.result.success === false) {
|
||||
throw new Error(body.result.desc || "요청이 거절됐습니다");
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
export const get = <T>(path: string) => request<T>(path);
|
||||
|
||||
export const post = <T>(path: string, payload?: unknown) =>
|
||||
request<T>(path, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: payload === undefined ? undefined : JSON.stringify(payload),
|
||||
});
|
||||
|
||||
/** healthz 는 JSON 문자열("시각")을 반환 — 도달 여부만 본다. */
|
||||
export async function healthz(): Promise<boolean> {
|
||||
try {
|
||||
const res = await fetch(settings.baseUrl() + "/healthz");
|
||||
return res.ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
/** LPS API 응답 타입 — 백엔드 protocol/admin_protocol 미러링. */
|
||||
|
||||
export interface ResultEnvelope {
|
||||
success: boolean;
|
||||
code: number;
|
||||
desc: string;
|
||||
}
|
||||
|
||||
export interface OpsSnapshot {
|
||||
pending: number;
|
||||
running: number;
|
||||
done: number;
|
||||
dead: number;
|
||||
dead_1h: number;
|
||||
stuck_running: number;
|
||||
oldest_pending_sec: number;
|
||||
blocks_1h: number;
|
||||
deadline_1h: number;
|
||||
cost_1h_usd: number;
|
||||
pool_checked_out: number;
|
||||
pool_capacity: number;
|
||||
pool_pct: number;
|
||||
}
|
||||
|
||||
export type JobStatusName = "PENDING" | "RUNNING" | "DONE" | "DEAD";
|
||||
|
||||
export interface JobListItem {
|
||||
job_id: string;
|
||||
job_type: number;
|
||||
status: JobStatusName;
|
||||
priority: number;
|
||||
attempts: number;
|
||||
max_attempts: number;
|
||||
product_code?: string;
|
||||
product_name?: string;
|
||||
outcome?: string;
|
||||
final_lowest?: number;
|
||||
cost_usd?: number;
|
||||
last_error?: string;
|
||||
created_at: string;
|
||||
run_started_at?: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface JobListRes {
|
||||
result: ResultEnvelope;
|
||||
items: JobListItem[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface JobDetailRes {
|
||||
result: ResultEnvelope;
|
||||
job_id?: string;
|
||||
status?: JobStatusName;
|
||||
attempts?: number;
|
||||
max_attempts?: number;
|
||||
output?: Record<string, unknown>;
|
||||
last_error?: string;
|
||||
}
|
||||
|
||||
export interface RequeueRes {
|
||||
result: ResultEnvelope;
|
||||
job_id?: string;
|
||||
requeued: boolean;
|
||||
}
|
||||
|
||||
export interface ProductItem {
|
||||
product_code: string;
|
||||
display_name?: string;
|
||||
triggered_at: string;
|
||||
outcome: string;
|
||||
naver_lowest?: number;
|
||||
coupang_lowest?: number;
|
||||
final_lowest?: number;
|
||||
final_source?: string;
|
||||
searches: number;
|
||||
}
|
||||
|
||||
export interface ProductListRes {
|
||||
result: ResultEnvelope;
|
||||
items: ProductItem[];
|
||||
}
|
||||
|
||||
export interface MallEntry {
|
||||
mall?: string;
|
||||
source?: string;
|
||||
price?: number;
|
||||
shipping_fee?: number | null;
|
||||
shipping_type?: string | null;
|
||||
url?: string;
|
||||
}
|
||||
|
||||
export interface PricePoint {
|
||||
triggered_at: string;
|
||||
outcome: string;
|
||||
matched_count?: number;
|
||||
naver?: number;
|
||||
coupang?: number;
|
||||
final?: number;
|
||||
final_source?: string;
|
||||
naver_name?: string;
|
||||
naver_url?: string;
|
||||
coupang_name?: string;
|
||||
coupang_url?: string;
|
||||
by_mall?: MallEntry[];
|
||||
}
|
||||
|
||||
export interface PriceHistoryRes {
|
||||
result: ResultEnvelope;
|
||||
product_code?: string;
|
||||
points: PricePoint[];
|
||||
}
|
||||
|
||||
export interface SearchRes {
|
||||
result: ResultEnvelope;
|
||||
accepted: number;
|
||||
items: { product_code: string; job_id?: string; duplicated: boolean }[];
|
||||
}
|
||||
|
||||
export interface IpSessionRow {
|
||||
source: string;
|
||||
proxy_port?: number;
|
||||
requests: number;
|
||||
ok_count: number;
|
||||
blocked_count: number;
|
||||
elapsed_sec?: number;
|
||||
end_reason: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface IpSessionStatsRes {
|
||||
result: ResultEnvelope;
|
||||
by_reason: Record<string, number>;
|
||||
histogram: { requests: number; count: number }[];
|
||||
block_min_requests?: number | null;
|
||||
sessions: IpSessionRow[];
|
||||
}
|
||||
|
||||
export interface BotRow {
|
||||
source: string;
|
||||
query?: string;
|
||||
ip_request_no?: number;
|
||||
proxy_port?: number;
|
||||
elapsed_sec?: number;
|
||||
marker?: string;
|
||||
html_len?: number;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface BotStatsRes {
|
||||
result: ResultEnvelope;
|
||||
hourly: { bucket: string; count: number }[];
|
||||
items: BotRow[];
|
||||
}
|
||||
|
||||
export interface CostBucket {
|
||||
bucket: string;
|
||||
jobs: number;
|
||||
ai_usd: number;
|
||||
proxy_usd: number;
|
||||
total_usd: number;
|
||||
avg_ms: number;
|
||||
}
|
||||
|
||||
export interface CostStatsRes {
|
||||
result: ResultEnvelope;
|
||||
buckets: CostBucket[];
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/** 앱 레이아웃 — 좌측 네비 + 상단 헬스 배지. */
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { NavLink, Outlet } from "react-router";
|
||||
import { healthz } from "../api/client";
|
||||
|
||||
const MENU = [
|
||||
{ to: "/", label: "대시보드", end: true },
|
||||
{ to: "/jobs", label: "작업 큐" },
|
||||
{ to: "/products", label: "상품·가격" },
|
||||
{ to: "/crawl", label: "크롤 상태" },
|
||||
{ to: "/costs", label: "비용" },
|
||||
{ to: "/settings", label: "설정" },
|
||||
];
|
||||
|
||||
export default function Layout() {
|
||||
const health = useQuery({ queryKey: ["healthz"], queryFn: healthz, refetchInterval: 10_000 });
|
||||
const up = health.data === true;
|
||||
return (
|
||||
<div className="mx-auto flex min-h-screen max-w-[1280px]">
|
||||
<aside className="w-[196px] shrink-0 border-r border-line-200 px-3 py-5">
|
||||
<div className="mb-6 flex items-center gap-2.5 px-2">
|
||||
<span className="grid h-8 w-8 place-items-center rounded-lg bg-gradient-to-br from-primary-600 to-[#8b7bff] text-[14px] font-extrabold text-white">L</span>
|
||||
<div>
|
||||
<div className="text-[14px] font-bold leading-tight">LPS 관리자</div>
|
||||
<div className="text-[10.5px] font-medium text-ink-400">인터넷 최저가 검색</div>
|
||||
</div>
|
||||
</div>
|
||||
<nav aria-label="주 메뉴">
|
||||
<ul className="space-y-0.5">
|
||||
{MENU.map((m) => (
|
||||
<li key={m.to}>
|
||||
<NavLink
|
||||
to={m.to}
|
||||
end={m.end}
|
||||
className={({ isActive }) =>
|
||||
`block rounded-lg px-3 py-2 text-[13px] font-semibold transition-colors ${
|
||||
isActive ? "bg-primary-50 text-primary-700" : "text-ink-700 hover:bg-surface-2"
|
||||
}`
|
||||
}
|
||||
>
|
||||
{m.label}
|
||||
</NavLink>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</nav>
|
||||
<div className="mt-8 flex items-center gap-2 px-3 text-[11.5px] font-semibold text-ink-500">
|
||||
<span
|
||||
className={`h-2 w-2 rounded-full ${up ? "bg-ok-600" : "bg-dead-600"}`}
|
||||
aria-hidden
|
||||
/>
|
||||
{up ? "API 연결됨" : "API 연결 안 됨"}
|
||||
</div>
|
||||
</aside>
|
||||
<main className="min-w-0 flex-1 px-6 py-5">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/** 공용 UI 조각 — 카드·스탯 타일·상태 배지·빈/오류 표시. 웹 표준 시맨틱 마크업 유지. */
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import type { JobStatusName } from "../api/types";
|
||||
|
||||
export function Card({ title, hint, children, className = "" }: {
|
||||
title?: ReactNode; hint?: ReactNode; children: ReactNode; className?: string;
|
||||
}) {
|
||||
return (
|
||||
<section className={`rounded-xl border border-line-200 bg-surface shadow-[0_1px_2px_rgba(16,24,40,.04)] ${className}`}>
|
||||
{title !== undefined && (
|
||||
<header className="flex items-center gap-2 border-b border-line-100 px-4 py-2.5">
|
||||
<h2 className="text-[13px] font-bold tracking-tight">{title}</h2>
|
||||
{hint && <span className="ml-auto text-[11px] text-ink-400">{hint}</span>}
|
||||
</header>
|
||||
)}
|
||||
<div className="p-4">{children}</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function StatTile({ label, value, sub, tone = "default" }: {
|
||||
label: string; value: ReactNode; sub?: ReactNode;
|
||||
tone?: "default" | "ok" | "warn" | "run" | "dead";
|
||||
}) {
|
||||
const toneCls = {
|
||||
default: "text-ink-900",
|
||||
ok: "text-ok-600",
|
||||
warn: "text-warn-600",
|
||||
run: "text-run-600",
|
||||
dead: "text-dead-600",
|
||||
}[tone];
|
||||
return (
|
||||
<div className="rounded-xl border border-line-200 bg-surface px-4 py-3">
|
||||
<div className="text-[11.5px] font-semibold text-ink-500">{label}</div>
|
||||
<div className={`mt-0.5 text-[22px] font-bold leading-tight ${toneCls}`}>{value}</div>
|
||||
{sub && <div className="mt-0.5 text-[11px] text-ink-400">{sub}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const STATUS_STYLE: Record<JobStatusName, { dot: string; bg: string; text: string; label: string }> = {
|
||||
PENDING: { dot: "bg-warn-600", bg: "bg-warn-50", text: "text-warn-700", label: "대기" },
|
||||
RUNNING: { dot: "bg-run-600", bg: "bg-run-50", text: "text-run-600", label: "처리중" },
|
||||
DONE: { dot: "bg-ok-600", bg: "bg-ok-50", text: "text-ok-600", label: "완료" },
|
||||
DEAD: { dot: "bg-dead-600", bg: "bg-dead-50", text: "text-dead-600", label: "실패" },
|
||||
};
|
||||
|
||||
export function StatusBadge({ status }: { status: JobStatusName }) {
|
||||
const s = STATUS_STYLE[status];
|
||||
return (
|
||||
<span className={`inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-[11px] font-semibold ${s.bg} ${s.text}`}>
|
||||
<span className={`h-1.5 w-1.5 rounded-full ${s.dot}`} aria-hidden />
|
||||
{s.label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function Empty({ children }: { children: ReactNode }) {
|
||||
return <p className="py-8 text-center text-[12.5px] text-ink-400">{children}</p>;
|
||||
}
|
||||
|
||||
export function ErrorNote({ error }: { error: unknown }) {
|
||||
return (
|
||||
<p role="alert" className="rounded-lg bg-dead-50 px-3 py-2 text-[12.5px] font-medium text-dead-600">
|
||||
{error instanceof Error ? error.message : "요청에 실패했습니다"}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
export function Loading() {
|
||||
return <p className="py-8 text-center text-[12.5px] text-ink-400" aria-busy="true">불러오는 중…</p>;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
/* 색 토큰 — 숫자 스케일(팀 관례) + dataviz 차트 크롬. 시리즈 색은 엔터티 고정:
|
||||
네이버 #008a43(CVD 검증 통과 톤다운) · 쿠팡 #f0455b · 최종 #4f46e5. */
|
||||
@theme {
|
||||
--color-page: #f7f7f5;
|
||||
--color-surface: #fcfcfb;
|
||||
--color-surface-2: #f4f4f1;
|
||||
--color-line-200: #e6e5df;
|
||||
--color-line-100: #efeee9;
|
||||
--color-grid: #e1e0d9;
|
||||
|
||||
--color-ink-900: #171a20;
|
||||
--color-ink-700: #3d434f;
|
||||
--color-ink-500: #6b7280;
|
||||
--color-ink-400: #9aa1ac;
|
||||
|
||||
--color-primary-700: #4338ca;
|
||||
--color-primary-600: #4f46e5;
|
||||
--color-primary-100: #e5e4fb;
|
||||
--color-primary-50: #eef0ff;
|
||||
|
||||
/* 상태(큐·알림) — status 팔레트, 시리즈로 재사용 금지 */
|
||||
--color-ok-600: #0f9d58;
|
||||
--color-ok-50: #e7f6ee;
|
||||
--color-warn-700: #a36a00;
|
||||
--color-warn-600: #c77800;
|
||||
--color-warn-50: #fdf3e3;
|
||||
--color-run-600: #2563eb;
|
||||
--color-run-50: #e8f0ff;
|
||||
--color-dead-600: #d03b3b;
|
||||
--color-dead-50: #fdeaea;
|
||||
|
||||
/* 차트 시리즈(엔터티 고정) */
|
||||
--color-naver: #008a43;
|
||||
--color-coupang: #f0455b;
|
||||
--color-final: #4f46e5;
|
||||
--color-cost-ai: #2a78d6;
|
||||
--color-cost-proxy: #eda100;
|
||||
|
||||
--font-sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
|
||||
"Apple SD Gothic Neo", "Noto Sans KR", sans-serif;
|
||||
}
|
||||
|
||||
body {
|
||||
@apply bg-page text-ink-900 font-sans text-[13.5px] antialiased;
|
||||
}
|
||||
|
||||
/* 테이블 숫자 열 정렬 */
|
||||
.tnum {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* recharts 기본 폰트 */
|
||||
.recharts-wrapper,
|
||||
.recharts-tooltip-wrapper {
|
||||
font-size: 11.5px;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/** 표시 포맷 유틸 — 원화·달러·상대시각·소요시간. */
|
||||
|
||||
export const won = (v?: number | null) =>
|
||||
v === null || v === undefined ? "—" : `${v.toLocaleString("ko-KR")}원`;
|
||||
|
||||
export const usd = (v?: number | null, digits = 3) =>
|
||||
v === null || v === undefined ? "—" : `$${v.toFixed(digits)}`;
|
||||
|
||||
export function timeAgo(iso?: string | null): string {
|
||||
if (!iso) return "—";
|
||||
const sec = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
|
||||
if (sec < 60) return `${Math.floor(sec)}초 전`;
|
||||
if (sec < 3600) return `${Math.floor(sec / 60)}분 전`;
|
||||
if (sec < 86400) return `${Math.floor(sec / 3600)}시간 전`;
|
||||
return `${Math.floor(sec / 86400)}일 전`;
|
||||
}
|
||||
|
||||
export const hhmm = (iso: string) =>
|
||||
new Date(iso).toLocaleTimeString("ko-KR", { hour: "2-digit", minute: "2-digit", hour12: false });
|
||||
|
||||
export const dateShort = (iso: string) =>
|
||||
new Date(iso).toLocaleString("ko-KR", { month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit", hour12: false });
|
||||
|
||||
export function durationSec(sec?: number | null): string {
|
||||
if (sec === null || sec === undefined) return "—";
|
||||
if (sec < 60) return `${sec}초`;
|
||||
if (sec < 3600) return `${Math.floor(sec / 60)}분 ${sec % 60}초`;
|
||||
return `${Math.floor(sec / 3600)}시간 ${Math.floor((sec % 3600) / 60)}분`;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { createBrowserRouter, RouterProvider } from "react-router";
|
||||
|
||||
import Layout from "./components/Layout";
|
||||
import Dashboard from "./pages/Dashboard";
|
||||
import Jobs from "./pages/Jobs";
|
||||
import Products from "./pages/Products";
|
||||
import Crawl from "./pages/Crawl";
|
||||
import Costs from "./pages/Costs";
|
||||
import Settings from "./pages/Settings";
|
||||
import "./index.css";
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: 1, refetchOnWindowFocus: false } },
|
||||
});
|
||||
|
||||
const router = createBrowserRouter([
|
||||
{
|
||||
element: <Layout />,
|
||||
children: [
|
||||
{ path: "/", element: <Dashboard /> },
|
||||
{ path: "/jobs", element: <Jobs /> },
|
||||
{ path: "/products", element: <Products /> },
|
||||
{ path: "/crawl", element: <Crawl /> },
|
||||
{ path: "/costs", element: <Costs /> },
|
||||
{ path: "/settings", element: <Settings /> },
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RouterProvider router={router} />
|
||||
</QueryClientProvider>
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,101 @@
|
||||
/** 비용 — 시간별 검색원가 스택(AI vs 프록시) + 평균 소요 시간(별도 축이므로 별도 차트). */
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
import {
|
||||
Bar, BarChart, CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis,
|
||||
} from "recharts";
|
||||
import { get } from "../api/client";
|
||||
import type { CostStatsRes } from "../api/types";
|
||||
import { Card, Empty, ErrorNote, Loading, StatTile } from "../components/ui";
|
||||
import { dateShort, usd } from "../lib/format";
|
||||
|
||||
const RANGES = [
|
||||
{ h: 24, label: "24시간" },
|
||||
{ h: 48, label: "48시간" },
|
||||
{ h: 168, label: "7일" },
|
||||
];
|
||||
|
||||
export default function Costs() {
|
||||
const [hours, setHours] = useState(48);
|
||||
const cost = useQuery({
|
||||
queryKey: ["cost", hours],
|
||||
queryFn: () => get<CostStatsRes>(`/v1/lps/stats/cost?hours=${hours}`),
|
||||
refetchInterval: 60_000,
|
||||
});
|
||||
|
||||
const buckets = (cost.data?.buckets ?? []).map((b) => ({ ...b, x: dateShort(b.bucket) }));
|
||||
const totals = buckets.reduce(
|
||||
(acc, b) => ({ jobs: acc.jobs + b.jobs, ai: acc.ai + b.ai_usd, proxy: acc.proxy + b.proxy_usd, total: acc.total + b.total_usd }),
|
||||
{ jobs: 0, ai: 0, proxy: 0, total: 0 },
|
||||
);
|
||||
const perSearch = totals.jobs > 0 ? totals.total / totals.jobs : null;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<h1 className="text-[17px] font-bold tracking-tight">비용</h1>
|
||||
<div role="tablist" aria-label="기간" className="ml-auto flex rounded-lg border border-line-200 bg-surface p-0.5">
|
||||
{RANGES.map((r) => (
|
||||
<button key={r.h} role="tab" aria-selected={hours === r.h} onClick={() => setHours(r.h)}
|
||||
className={`rounded-md px-3 py-1.5 text-[12px] font-semibold ${hours === r.h ? "bg-primary-50 text-primary-700" : "text-ink-500 hover:text-ink-700"}`}>
|
||||
{r.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{cost.isError && <ErrorNote error={cost.error} />}
|
||||
|
||||
<div className="grid grid-cols-2 gap-3 md:grid-cols-4">
|
||||
<StatTile label="완료 검색" value={totals.jobs} sub="기간 내" />
|
||||
<StatTile label="총 비용" value={usd(totals.total, 2)} sub={`AI ${usd(totals.ai, 2)} + 프록시 ${usd(totals.proxy, 2)}`} />
|
||||
<StatTile label="검색 1건당" value={perSearch === null ? "—" : usd(perSearch)} sub="평균 원가" />
|
||||
<StatTile label="프록시 비중" value={totals.total > 0 ? `${Math.round((totals.proxy / totals.total) * 100)}%` : "—"} sub="대역폭이 원가의 대부분" />
|
||||
</div>
|
||||
|
||||
<Card title="시간별 검색원가" hint="AI vs 프록시 대역폭">
|
||||
{cost.isPending && <Loading />}
|
||||
{cost.data && buckets.length === 0 && <Empty>기간 내 완료된 검색이 없습니다</Empty>}
|
||||
{buckets.length > 0 && (
|
||||
<>
|
||||
<ResponsiveContainer width="100%" height={220}>
|
||||
<BarChart data={buckets} margin={{ top: 6, right: 12, bottom: 0, left: -10 }}>
|
||||
<CartesianGrid stroke="var(--color-grid)" vertical={false} />
|
||||
<XAxis dataKey="x" tick={{ fill: "var(--color-ink-400)" }} tickLine={false} axisLine={{ stroke: "var(--color-line-200)" }} minTickGap={40} />
|
||||
<YAxis tick={{ fill: "var(--color-ink-400)" }} tickLine={false} axisLine={false} tickFormatter={(v: number) => `$${v}`} />
|
||||
<Tooltip formatter={(v: number, name: string) => [usd(v), name]}
|
||||
labelFormatter={(l, payload) => {
|
||||
const jobs = (payload?.[0]?.payload as { jobs?: number } | undefined)?.jobs;
|
||||
return `${l}${jobs != null ? ` · 검색 ${jobs}건` : ""}`;
|
||||
}} />
|
||||
<Bar dataKey="ai_usd" name="AI" stackId="c" fill="var(--color-cost-ai)" maxBarSize={28} isAnimationActive={false} />
|
||||
<Bar dataKey="proxy_usd" name="프록시" stackId="c" fill="var(--color-cost-proxy)" radius={[4, 4, 0, 0]} maxBarSize={28} isAnimationActive={false} />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
<p className="mt-1 flex gap-4 text-[11px] font-semibold text-ink-500">
|
||||
<span><span className="mr-1 inline-block h-2 w-2 rounded-full bg-cost-ai" aria-hidden />AI (판정·검색어)</span>
|
||||
<span><span className="mr-1 inline-block h-2 w-2 rounded-full bg-cost-proxy" aria-hidden />프록시 대역폭 (DECODO)</span>
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card title="검색 1건 평균 소요 시간" hint="시간별 · 상승하면 경합/차단 신호">
|
||||
{buckets.length === 0 ? (
|
||||
<Empty>데이터 없음</Empty>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height={160}>
|
||||
<LineChart data={buckets} margin={{ top: 6, right: 12, bottom: 0, left: -10 }}>
|
||||
<CartesianGrid stroke="var(--color-grid)" vertical={false} />
|
||||
<XAxis dataKey="x" tick={{ fill: "var(--color-ink-400)" }} tickLine={false} axisLine={{ stroke: "var(--color-line-200)" }} minTickGap={40} />
|
||||
<YAxis tick={{ fill: "var(--color-ink-400)" }} tickLine={false} axisLine={false} tickFormatter={(v: number) => `${(v / 1000).toFixed(0)}s`} />
|
||||
<Tooltip formatter={(v: number) => [`${(v / 1000).toFixed(1)}초`, "평균 소요"]} />
|
||||
<Line type="monotone" dataKey="avg_ms" name="평균 소요" stroke="var(--color-primary-600)" strokeWidth={2} dot={false} isAnimationActive={false} />
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
/** 크롤 상태 — IP 세션 종료 사유·요청 수 분포(예산 튜닝 뷰)·차단 이력. */
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
import {
|
||||
Bar, BarChart, CartesianGrid, Cell, Pie, PieChart, ReferenceLine, ResponsiveContainer, Tooltip, XAxis, YAxis,
|
||||
} from "recharts";
|
||||
import { get } from "../api/client";
|
||||
import type { BotStatsRes, IpSessionStatsRes } from "../api/types";
|
||||
import { Card, Empty, ErrorNote, Loading } from "../components/ui";
|
||||
import { dateShort, durationSec, hhmm } from "../lib/format";
|
||||
|
||||
// 종료 사유 — 의미 기반 상태색(정상 회전=초록 계열, 차단=적색, 포트사망=주황, 중립=회색/파랑).
|
||||
const REASONS: Record<string, { label: string; color: string; desc: string }> = {
|
||||
budget: { label: "예산 선제 회전", color: "#0ca30c", desc: "정상 — 차단 전에 IP 교체(평판 보존)" },
|
||||
window: { label: "시간창 만료", color: "#2a78d6", desc: "정상 — sticky 10분 주기 교체" },
|
||||
idle: { label: "유휴 정리", color: "#898781", desc: "정상 — 한동안 검색 없어 브라우저 회수" },
|
||||
shutdown: { label: "종료", color: "#c3c2b7", desc: "정상 — 워커 재시작/종료" },
|
||||
rotate: { label: "기타 회전", color: "#9aa1ac", desc: "웜업 재시도 등" },
|
||||
proxy_error: { label: "포트 사망", color: "#ec835a", desc: "주의 — 프록시 전송 실패로 교체" },
|
||||
block: { label: "차단됨", color: "#d03b3b", desc: "위험 — 예산 안에서도 차단(예산 하향 검토)" },
|
||||
};
|
||||
|
||||
const RANGES = [
|
||||
{ h: 24, label: "24시간" },
|
||||
{ h: 168, label: "7일" },
|
||||
{ h: 720, label: "30일" },
|
||||
];
|
||||
|
||||
export default function Crawl() {
|
||||
const [hours, setHours] = useState(168);
|
||||
const ip = useQuery({
|
||||
queryKey: ["ip-sessions", hours],
|
||||
queryFn: () => get<IpSessionStatsRes>(`/v1/lps/stats/ip-sessions?hours=${hours}`),
|
||||
refetchInterval: 30_000,
|
||||
});
|
||||
const bot = useQuery({
|
||||
queryKey: ["bot", hours],
|
||||
queryFn: () => get<BotStatsRes>(`/v1/lps/stats/bot?hours=${hours}`),
|
||||
refetchInterval: 30_000,
|
||||
});
|
||||
|
||||
const reasons = Object.entries(ip.data?.by_reason ?? {})
|
||||
.map(([k, v]) => ({ key: k, ...(REASONS[k] ?? { label: k, color: "#9aa1ac", desc: "" }), value: v }))
|
||||
.sort((a, b) => b.value - a.value);
|
||||
const totalSessions = reasons.reduce((s, r) => s + r.value, 0);
|
||||
const blockCount = ip.data?.by_reason?.block ?? 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<h1 className="text-[17px] font-bold tracking-tight">크롤 상태</h1>
|
||||
<div role="tablist" aria-label="기간" className="ml-auto flex rounded-lg border border-line-200 bg-surface p-0.5">
|
||||
{RANGES.map((r) => (
|
||||
<button key={r.h} role="tab" aria-selected={hours === r.h} onClick={() => setHours(r.h)}
|
||||
className={`rounded-md px-3 py-1.5 text-[12px] font-semibold ${hours === r.h ? "bg-primary-50 text-primary-700" : "text-ink-500 hover:text-ink-700"}`}>
|
||||
{r.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{ip.isError && <ErrorNote error={ip.error} />}
|
||||
|
||||
{ip.data && (
|
||||
blockCount === 0 ? (
|
||||
<p className="rounded-lg bg-ok-50 px-3 py-2 text-[12.5px] font-semibold text-ok-600">
|
||||
✓ 기간 내 차단된 IP 세션 0건 — 요청 예산(선제 회전)이 잘 작동하고 있습니다
|
||||
</p>
|
||||
) : (
|
||||
<p role="alert" className="rounded-lg border border-dead-600/20 bg-dead-50 px-3 py-2 text-[12.5px] font-semibold text-dead-600">
|
||||
⚠ 예산 안에서도 차단된 세션 {blockCount}건 — 최소 {ip.data.block_min_requests}회 요청에서 차단됐습니다.
|
||||
요청 예산을 그보다 낮게 유지하세요(현재 서버 설정은 toml [DecodoConfig].ip_request_budget)
|
||||
</p>
|
||||
)
|
||||
)}
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<Card title="IP 세션 종료 사유" hint={`총 ${totalSessions}건`}>
|
||||
{ip.isPending && <Loading />}
|
||||
{ip.data && reasons.length === 0 && <Empty>기간 내 세션 없음 — 워커가 검색을 시작하면 쌓입니다</Empty>}
|
||||
{reasons.length > 0 && (
|
||||
<div className="flex items-center gap-4">
|
||||
<ResponsiveContainer width={150} height={150}>
|
||||
<PieChart>
|
||||
<Pie data={reasons} dataKey="value" nameKey="label" innerRadius={42} outerRadius={70}
|
||||
paddingAngle={2} stroke="var(--color-surface)" strokeWidth={2} isAnimationActive={false}>
|
||||
{reasons.map((r) => <Cell key={r.key} fill={r.color} />)}
|
||||
</Pie>
|
||||
<Tooltip formatter={(v: number, name: string) => [`${v}건`, name]} />
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
<ul className="min-w-0 flex-1 space-y-1.5 text-[12px]">
|
||||
{reasons.map((r) => (
|
||||
<li key={r.key} className="flex items-baseline gap-2">
|
||||
<span className="mt-1 h-2 w-2 shrink-0 rounded-full" style={{ background: r.color }} aria-hidden />
|
||||
<span className="font-semibold">{r.label}</span>
|
||||
<span className="tnum ml-auto shrink-0 font-bold">{r.value}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
{reasons.length > 0 && (
|
||||
<p className="mt-2 text-[11px] leading-relaxed text-ink-400">
|
||||
초록(예산 선제)·파랑(시간창)이 대부분이면 건강한 상태입니다. 빨강(차단)이 보이면 예산 하향 신호.
|
||||
</p>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card title="세션당 요청 수 분포" hint="예산 튜닝 근거">
|
||||
{ip.isPending && <Loading />}
|
||||
{ip.data && ip.data.histogram.length === 0 && <Empty>데이터 없음</Empty>}
|
||||
{ip.data && ip.data.histogram.length > 0 && (
|
||||
<>
|
||||
<ResponsiveContainer width="100%" height={170}>
|
||||
<BarChart data={ip.data.histogram} margin={{ top: 14, right: 12, bottom: 0, left: -22 }}>
|
||||
<CartesianGrid stroke="var(--color-grid)" vertical={false} />
|
||||
<XAxis dataKey="requests" tick={{ fill: "var(--color-ink-400)" }} tickLine={false}
|
||||
axisLine={{ stroke: "var(--color-line-200)" }} label={undefined} />
|
||||
<YAxis allowDecimals={false} tick={{ fill: "var(--color-ink-400)" }} tickLine={false} axisLine={false} />
|
||||
<Tooltip formatter={(v: number) => [`${v}건`, "세션 수"]} labelFormatter={(l) => `IP당 ${l}회 요청`} />
|
||||
<Bar dataKey="count" fill="var(--color-cost-ai)" radius={[4, 4, 0, 0]} maxBarSize={36} isAnimationActive={false} />
|
||||
{ip.data.block_min_requests != null && (
|
||||
<ReferenceLine x={ip.data.block_min_requests} stroke="#d03b3b" strokeDasharray="4 3"
|
||||
label={{ value: `차단 시작 ${ip.data.block_min_requests}회`, position: "top", fill: "#d03b3b", fontSize: 11, fontWeight: 600 }} />
|
||||
)}
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
<p className="mt-1 text-[11px] leading-relaxed text-ink-400">
|
||||
X축 = 한 IP로 보낸 요청 수. 분포가 예산값에 몰려 있으면 정상, 붉은 기준선(차단 시작점)보다 예산이 낮아야 안전.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<Card title="차단 발생 추이" hint="시간대별">
|
||||
{bot.isPending && <Loading />}
|
||||
{bot.isError && <ErrorNote error={bot.error} />}
|
||||
{bot.data && bot.data.hourly.length === 0 && <Empty>기간 내 차단 없음 🎉</Empty>}
|
||||
{bot.data && bot.data.hourly.length > 0 && (
|
||||
<ResponsiveContainer width="100%" height={150}>
|
||||
<BarChart data={bot.data.hourly.map((h) => ({ ...h, x: dateShort(h.bucket) }))} margin={{ top: 6, right: 12, bottom: 0, left: -22 }}>
|
||||
<CartesianGrid stroke="var(--color-grid)" vertical={false} />
|
||||
<XAxis dataKey="x" tick={{ fill: "var(--color-ink-400)" }} tickLine={false} axisLine={{ stroke: "var(--color-line-200)" }} minTickGap={40} />
|
||||
<YAxis allowDecimals={false} tick={{ fill: "var(--color-ink-400)" }} tickLine={false} axisLine={false} />
|
||||
<Tooltip formatter={(v: number) => [`${v}건`, "차단"]} />
|
||||
<Bar dataKey="count" fill="#d03b3b" radius={[4, 4, 0, 0]} maxBarSize={24} isAnimationActive={false} />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card title="최근 차단 이력" hint="최근 50건">
|
||||
{bot.data && bot.data.items.length === 0 && <Empty>기간 내 차단 없음</Empty>}
|
||||
{bot.data && bot.data.items.length > 0 && (
|
||||
<div className="max-h-64 overflow-y-auto">
|
||||
<table className="w-full text-left text-[12px]">
|
||||
<thead>
|
||||
<tr className="border-b border-line-200 text-[11px] text-ink-400">
|
||||
<th className="pb-1 pr-2 font-semibold">시각</th>
|
||||
<th className="pb-1 pr-2 font-semibold">검색어</th>
|
||||
<th className="pb-1 pr-2 text-right font-semibold">요청#</th>
|
||||
<th className="pb-1 pr-2 text-right font-semibold">포트</th>
|
||||
<th className="pb-1 font-semibold">감지 근거</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{bot.data.items.map((b, i) => (
|
||||
<tr key={i} className="border-b border-line-100">
|
||||
<td className="tnum py-1.5 pr-2 text-ink-500">{hhmm(b.created_at)}</td>
|
||||
<td className="max-w-32 truncate py-1.5 pr-2">{b.query || "—"}</td>
|
||||
<td className="tnum py-1.5 pr-2 text-right">{b.ip_request_no ?? "—"}</td>
|
||||
<td className="tnum py-1.5 pr-2 text-right text-ink-500">{b.proxy_port ?? "—"}</td>
|
||||
<td className="max-w-40 truncate py-1.5 text-[11px] text-ink-500">{b.marker}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card title="최근 IP 세션" hint="최근 50건">
|
||||
{ip.data && ip.data.sessions.length === 0 && <Empty>세션 없음</Empty>}
|
||||
{ip.data && ip.data.sessions.length > 0 && (
|
||||
<div className="max-h-72 overflow-y-auto">
|
||||
<table className="w-full text-left text-[12px]">
|
||||
<thead>
|
||||
<tr className="border-b border-line-200 text-[11px] text-ink-400">
|
||||
<th className="pb-1 pr-2 font-semibold">종료 시각</th>
|
||||
<th className="pb-1 pr-2 font-semibold">소스</th>
|
||||
<th className="pb-1 pr-2 text-right font-semibold">포트</th>
|
||||
<th className="pb-1 pr-2 text-right font-semibold">요청</th>
|
||||
<th className="pb-1 pr-2 text-right font-semibold">성공/차단</th>
|
||||
<th className="pb-1 pr-2 text-right font-semibold">지속</th>
|
||||
<th className="pb-1 font-semibold">종료 사유</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{ip.data.sessions.map((s, i) => {
|
||||
const r = REASONS[s.end_reason] ?? { label: s.end_reason, color: "#9aa1ac" };
|
||||
return (
|
||||
<tr key={i} className="border-b border-line-100">
|
||||
<td className="tnum py-1.5 pr-2 text-ink-500">{dateShort(s.created_at)}</td>
|
||||
<td className="py-1.5 pr-2">{s.source}</td>
|
||||
<td className="tnum py-1.5 pr-2 text-right text-ink-500">{s.proxy_port ?? "—"}</td>
|
||||
<td className="tnum py-1.5 pr-2 text-right font-semibold">{s.requests}</td>
|
||||
<td className="tnum py-1.5 pr-2 text-right text-ink-500">{s.ok_count}/{s.blocked_count}</td>
|
||||
<td className="tnum py-1.5 pr-2 text-right text-ink-500">{durationSec(s.elapsed_sec)}</td>
|
||||
<td className="py-1.5">
|
||||
<span className="inline-flex items-center gap-1.5 text-[11.5px] font-semibold" style={{ color: r.color }}>
|
||||
<span className="h-1.5 w-1.5 rounded-full" style={{ background: r.color }} aria-hidden />
|
||||
{r.label}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
/** 대시보드 — 지금 시스템이 건강한가. /ops 5초 폴링 + 임계 배너 + 큐 추이(세션 내 누적). */
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useRef } from "react";
|
||||
import {
|
||||
CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis,
|
||||
} from "recharts";
|
||||
import { get } from "../api/client";
|
||||
import type { OpsSnapshot } from "../api/types";
|
||||
import { Card, ErrorNote, StatTile } from "../components/ui";
|
||||
import { durationSec, usd } from "../lib/format";
|
||||
|
||||
// 알림 임계 기본값 미러 — 서버 [AlertConfig] 와 동일 기본(서버가 조정했으면 다를 수 있음, 참고용 배너).
|
||||
const TH = { dead_1h: 20, blocks_1h: 80, queue_lag_sec: 300, pool_pct: 90, deadline_1h: 5, cost_1h_usd: 1.0 };
|
||||
|
||||
interface TrendPoint { t: string; pending: number; running: number }
|
||||
|
||||
export default function Dashboard() {
|
||||
const trend = useRef<TrendPoint[]>([]);
|
||||
const ops = useQuery({
|
||||
queryKey: ["ops"],
|
||||
queryFn: () => get<OpsSnapshot>("/v1/lps/ops"),
|
||||
refetchInterval: 5_000,
|
||||
});
|
||||
|
||||
if (ops.data) {
|
||||
const now = new Date().toLocaleTimeString("ko-KR", { hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit" });
|
||||
const last = trend.current[trend.current.length - 1];
|
||||
if (!last || last.t !== now) {
|
||||
trend.current = [...trend.current, { t: now, pending: ops.data.pending, running: ops.data.running }].slice(-120);
|
||||
}
|
||||
}
|
||||
|
||||
const d = ops.data;
|
||||
const alerts: { key: string; msg: string }[] = [];
|
||||
if (d) {
|
||||
if (d.dead_1h >= TH.dead_1h) alerts.push({ key: "dead", msg: `최근 1시간 실패(DEAD) ${d.dead_1h}건 — 검색 실패가 쌓이고 있습니다` });
|
||||
if (d.blocks_1h >= TH.blocks_1h) alerts.push({ key: "blocks", msg: `최근 1시간 차단 ${d.blocks_1h}건 — IP 평판 악화 신호` });
|
||||
if (d.oldest_pending_sec >= TH.queue_lag_sec) alerts.push({ key: "lag", msg: `큐 지연 ${durationSec(d.oldest_pending_sec)} — 워커가 처리를 못 따라갑니다` });
|
||||
if (d.stuck_running > 0) alerts.push({ key: "stuck", msg: `멈춘 작업 ${d.stuck_running}건 — 워커 사망/행 흔적` });
|
||||
if (d.pool_pct >= TH.pool_pct) alerts.push({ key: "pool", msg: `DB 커넥션 풀 ${d.pool_pct}% 포화` });
|
||||
if (d.deadline_1h >= TH.deadline_1h) alerts.push({ key: "deadline", msg: `최근 1시간 데드라인 강제종료 ${d.deadline_1h}건 — 크롤 행 반복 신호` });
|
||||
if (d.cost_1h_usd >= TH.cost_1h_usd) alerts.push({ key: "cost", msg: `최근 1시간 검색원가 ${usd(d.cost_1h_usd, 2)} — 비용 급증 점검` });
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<h1 className="text-[17px] font-bold tracking-tight">대시보드</h1>
|
||||
|
||||
{ops.isError && <ErrorNote error={ops.error} />}
|
||||
{alerts.map((a) => (
|
||||
<p key={a.key} role="alert"
|
||||
className="rounded-lg border border-dead-600/20 bg-dead-50 px-3 py-2 text-[12.5px] font-semibold text-dead-600">
|
||||
⚠ {a.msg}
|
||||
</p>
|
||||
))}
|
||||
{d && alerts.length === 0 && (
|
||||
<p className="rounded-lg bg-ok-50 px-3 py-2 text-[12.5px] font-semibold text-ok-600">
|
||||
✓ 모든 지표가 임계 안에 있습니다
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 gap-3 md:grid-cols-4">
|
||||
<StatTile label="대기" value={d?.pending ?? "—"} tone="warn" sub="검색 순서를 기다리는 작업" />
|
||||
<StatTile label="처리중" value={d?.running ?? "—"} tone="run" sub="워커가 검색 중" />
|
||||
<StatTile label="완료" value={d?.done ?? "—"} tone="ok" sub="누적" />
|
||||
<StatTile label="실패 (DEAD)" value={d?.dead ?? "—"} tone={d && d.dead > 0 ? "dead" : "default"} sub={`최근 1h ${d?.dead_1h ?? "—"}건`} />
|
||||
<StatTile label="큐 지연" value={d ? durationSec(d.oldest_pending_sec) : "—"} sub="가장 오래 기다린 작업" />
|
||||
<StatTile label="차단 (1h)" value={d?.blocks_1h ?? "—"} tone={d && d.blocks_1h > 0 ? "warn" : "default"} sub="쿠팡 봇 감지" />
|
||||
<StatTile label="검색원가 (1h)" value={d ? usd(d.cost_1h_usd, 2) : "—"} sub="AI + 프록시 대역폭" />
|
||||
<StatTile label="DB 풀" value={d ? `${d.pool_pct}%` : "—"} sub={d ? `${d.pool_checked_out}/${d.pool_capacity} 사용 중` : undefined} />
|
||||
</div>
|
||||
|
||||
<Card title="큐 추이" hint="5초 간격 · 이 화면을 열어둔 동안 누적">
|
||||
{trend.current.length < 2 ? (
|
||||
<p className="py-6 text-center text-[12px] text-ink-400">수집 중… 잠시 후 그래프가 나타납니다</p>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height={180}>
|
||||
<LineChart data={trend.current} margin={{ top: 6, right: 12, bottom: 0, left: -18 }}>
|
||||
<CartesianGrid stroke="var(--color-grid)" vertical={false} />
|
||||
<XAxis dataKey="t" tick={{ fill: "var(--color-ink-400)" }} tickLine={false} axisLine={{ stroke: "var(--color-line-200)" }} minTickGap={48} />
|
||||
<YAxis allowDecimals={false} tick={{ fill: "var(--color-ink-400)" }} tickLine={false} axisLine={false} />
|
||||
<Tooltip formatter={(v: number, name: string) => [v, name === "pending" ? "대기" : "처리중"]} />
|
||||
<Line type="monotone" dataKey="pending" name="대기" stroke="var(--color-warn-600)" strokeWidth={2} dot={false} isAnimationActive={false} />
|
||||
<Line type="monotone" dataKey="running" name="처리중" stroke="var(--color-run-600)" strokeWidth={2} dot={false} isAnimationActive={false} />
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
<p className="mt-1 flex gap-4 text-[11px] font-semibold text-ink-500">
|
||||
<span><span className="mr-1 inline-block h-2 w-2 rounded-full bg-warn-600" aria-hidden />대기</span>
|
||||
<span><span className="mr-1 inline-block h-2 w-2 rounded-full bg-run-600" aria-hidden />처리중</span>
|
||||
</p>
|
||||
</Card>
|
||||
|
||||
<p className="text-[11px] text-ink-400">
|
||||
임계 배너는 서버 알림 기본값 기준입니다(서버 toml 에서 조정했으면 실제 알림과 다를 수 있음).
|
||||
전체 룰은 lps/docs/operations.md 참고.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
/** 작업 큐 — 잡 목록(필터·검색·페이지네이션) + 상세 패널 + DEAD 재큐. */
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
import { get, post } from "../api/client";
|
||||
import type { JobDetailRes, JobListItem, JobListRes, JobStatusName, RequeueRes } from "../api/types";
|
||||
import { Card, Empty, ErrorNote, Loading, StatusBadge } from "../components/ui";
|
||||
import { dateShort, usd, won } from "../lib/format";
|
||||
|
||||
const PAGE = 20;
|
||||
const TABS: { v: JobStatusName | ""; label: string }[] = [
|
||||
{ v: "", label: "전체" },
|
||||
{ v: "PENDING", label: "대기" },
|
||||
{ v: "RUNNING", label: "처리중" },
|
||||
{ v: "DONE", label: "완료" },
|
||||
{ v: "DEAD", label: "실패" },
|
||||
];
|
||||
|
||||
export default function Jobs() {
|
||||
const [status, setStatus] = useState<JobStatusName | "">("");
|
||||
const [q, setQ] = useState("");
|
||||
const [qInput, setQInput] = useState("");
|
||||
const [page, setPage] = useState(0);
|
||||
const [selected, setSelected] = useState<JobListItem | null>(null);
|
||||
|
||||
const params = new URLSearchParams({ limit: String(PAGE), offset: String(page * PAGE) });
|
||||
if (status) params.set("status", status);
|
||||
if (q) params.set("q", q);
|
||||
|
||||
const list = useQuery({
|
||||
queryKey: ["jobs", status, q, page],
|
||||
queryFn: () => get<JobListRes>(`/v1/lps/jobs?${params}`),
|
||||
refetchInterval: 15_000,
|
||||
});
|
||||
const pages = Math.max(1, Math.ceil((list.data?.total ?? 0) / PAGE));
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<h1 className="text-[17px] font-bold tracking-tight">작업 큐</h1>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div role="tablist" aria-label="상태 필터" className="flex rounded-lg border border-line-200 bg-surface p-0.5">
|
||||
{TABS.map((t) => (
|
||||
<button key={t.v} role="tab" aria-selected={status === t.v}
|
||||
onClick={() => { setStatus(t.v); setPage(0); }}
|
||||
className={`rounded-md px-3 py-1.5 text-[12px] font-semibold ${
|
||||
status === t.v ? "bg-primary-50 text-primary-700" : "text-ink-500 hover:text-ink-700"
|
||||
}`}>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<form className="ml-auto flex gap-1.5" onSubmit={(e) => { e.preventDefault(); setQ(qInput.trim()); setPage(0); }}>
|
||||
<input value={qInput} onChange={(e) => setQInput(e.target.value)} placeholder="상품코드·상품명 검색"
|
||||
className="w-56 rounded-lg border border-line-200 bg-surface px-3 py-1.5 text-[12.5px] outline-none focus:border-primary-600" />
|
||||
<button type="submit" className="rounded-lg bg-primary-600 px-3 py-1.5 text-[12px] font-semibold text-white hover:bg-primary-700">검색</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-[1fr_360px]">
|
||||
<Card title={`작업 ${list.data?.total ?? "—"}건`} hint="15초마다 갱신">
|
||||
{list.isPending && <Loading />}
|
||||
{list.isError && <ErrorNote error={list.error} />}
|
||||
{list.data && list.data.items.length === 0 && <Empty>조건에 맞는 작업이 없습니다</Empty>}
|
||||
{list.data && list.data.items.length > 0 && (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-[12.5px]">
|
||||
<thead>
|
||||
<tr className="border-b border-line-200 text-[11px] text-ink-400">
|
||||
<th className="pb-1.5 pr-3 font-semibold">상품</th>
|
||||
<th className="pb-1.5 pr-3 font-semibold">상태</th>
|
||||
<th className="pb-1.5 pr-3 font-semibold">결과</th>
|
||||
<th className="pb-1.5 pr-3 text-right font-semibold">최저가</th>
|
||||
<th className="pb-1.5 pr-3 text-right font-semibold">원가</th>
|
||||
<th className="pb-1.5 font-semibold">요청 시각</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{list.data.items.map((j) => (
|
||||
<tr key={j.job_id} onClick={() => setSelected(j)}
|
||||
className={`cursor-pointer border-b border-line-100 hover:bg-surface-2 ${selected?.job_id === j.job_id ? "bg-primary-50/60" : ""}`}>
|
||||
<td className="py-2 pr-3">
|
||||
<div className="font-semibold">{j.product_name || "—"}</div>
|
||||
<div className="text-[11px] text-ink-400">{j.product_code}</div>
|
||||
</td>
|
||||
<td className="py-2 pr-3"><StatusBadge status={j.status} /></td>
|
||||
<td className="py-2 pr-3">{j.outcome === "found" ? "찾음" : j.outcome === "not_found" ? "없음" : "—"}</td>
|
||||
<td className="tnum py-2 pr-3 text-right">{won(j.final_lowest)}</td>
|
||||
<td className="tnum py-2 pr-3 text-right text-ink-500">{usd(j.cost_usd)}</td>
|
||||
<td className="tnum py-2 text-[11.5px] text-ink-500">{dateShort(j.created_at)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{pages > 1 && (
|
||||
<nav aria-label="페이지" className="mt-3 flex items-center justify-end gap-2 text-[12px]">
|
||||
<button disabled={page === 0} onClick={() => setPage((p) => p - 1)}
|
||||
className="rounded-md border border-line-200 px-2.5 py-1 font-semibold disabled:opacity-40">이전</button>
|
||||
<span className="tnum text-ink-500">{page + 1} / {pages}</span>
|
||||
<button disabled={page + 1 >= pages} onClick={() => setPage((p) => p + 1)}
|
||||
className="rounded-md border border-line-200 px-2.5 py-1 font-semibold disabled:opacity-40">다음</button>
|
||||
</nav>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<JobDetail job={selected} onClose={() => setSelected(null)} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function JobDetail({ job, onClose }: { job: JobListItem | null; onClose: () => void }) {
|
||||
const qc = useQueryClient();
|
||||
const detail = useQuery({
|
||||
queryKey: ["job", job?.job_id],
|
||||
queryFn: () => get<JobDetailRes>(`/v1/lps/jobs/${job!.job_id}`),
|
||||
enabled: !!job,
|
||||
});
|
||||
const requeue = useMutation({
|
||||
mutationFn: () => post<RequeueRes>(`/v1/lps/jobs/${job!.job_id}/requeue`),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ["jobs"] }),
|
||||
});
|
||||
|
||||
if (!job) return <Card title="상세"><Empty>왼쪽 목록에서 작업을 선택하세요</Empty></Card>;
|
||||
|
||||
const out = detail.data?.output as Record<string, any> | undefined;
|
||||
return (
|
||||
<Card title="상세" hint={<button onClick={onClose} className="font-semibold text-ink-400 hover:text-ink-700">닫기</button>}>
|
||||
<dl className="space-y-2 text-[12.5px]">
|
||||
<Row k="작업 ID"><span className="tnum break-all text-[11.5px]">{job.job_id}</span></Row>
|
||||
<Row k="상품">{job.product_name || "—"}{job.product_code && <span className="text-ink-400"> ({job.product_code})</span>}</Row>
|
||||
<Row k="상태"><StatusBadge status={job.status} /> <span className="text-ink-400">시도 {job.attempts}/{job.max_attempts}</span></Row>
|
||||
{job.last_error && <Row k="오류"><span className="break-all text-dead-600">{job.last_error}</span></Row>}
|
||||
{out?.outcome && <Row k="결과">{out.outcome === "found" ? "같은 상품을 찾음" : "같은 상품 없음"}</Row>}
|
||||
{out?.lowest && <Row k="최저가"><b>{won(out.lowest.price)}</b> <span className="text-ink-400">({out.lowest.source} · {out.lowest.mall_name || "—"})</span></Row>}
|
||||
{out?.metrics?.cost && (
|
||||
<Row k="검색 원가">
|
||||
{usd(out.metrics.cost.total_usd)} <span className="text-ink-400">(AI {usd(out.metrics.cost.ai_usd)} + 프록시 {usd(out.metrics.cost.proxy_usd)})</span>
|
||||
</Row>
|
||||
)}
|
||||
{out?.metrics?.duration_ms != null && <Row k="소요">{(out.metrics.duration_ms / 1000).toFixed(1)}초</Row>}
|
||||
</dl>
|
||||
|
||||
{job.status === "DEAD" && (
|
||||
<div className="mt-4 border-t border-line-100 pt-3">
|
||||
<button onClick={() => requeue.mutate()} disabled={requeue.isPending}
|
||||
className="w-full rounded-lg bg-primary-600 px-3 py-2 text-[12.5px] font-semibold text-white hover:bg-primary-700 disabled:opacity-50">
|
||||
{requeue.isPending ? "재시도 요청 중…" : "다시 검색하기 (재큐)"}
|
||||
</button>
|
||||
{requeue.isError && <p className="mt-2 text-[12px] font-medium text-dead-600">{(requeue.error as Error).message}</p>}
|
||||
{requeue.isSuccess && <p className="mt-2 text-[12px] font-medium text-ok-600">대기열에 다시 넣었습니다 — 워커가 곧 처리합니다</p>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{out && (
|
||||
<details className="mt-3">
|
||||
<summary className="cursor-pointer text-[11.5px] font-semibold text-ink-400">원본 결과(JSON)</summary>
|
||||
<pre className="mt-1 max-h-64 overflow-auto rounded-lg bg-surface-2 p-2 text-[10.5px] leading-relaxed">{JSON.stringify(out, null, 2)}</pre>
|
||||
</details>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function Row({ k, children }: { k: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex gap-2">
|
||||
<dt className="w-16 shrink-0 text-[11.5px] font-semibold text-ink-400">{k}</dt>
|
||||
<dd className="min-w-0 flex-1">{children}</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
/** 상품·가격 — 이력 상품 목록 → 가격 추이 3선(네이버·쿠팡·최종) + 몰별 최저가 + 재검색. */
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
import {
|
||||
Bar, BarChart, CartesianGrid, Cell, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis,
|
||||
} from "recharts";
|
||||
import { get, post } from "../api/client";
|
||||
import type { PriceHistoryRes, ProductItem, ProductListRes, SearchRes } from "../api/types";
|
||||
import { Card, Empty, ErrorNote, Loading } from "../components/ui";
|
||||
import { dateShort, timeAgo, won } from "../lib/format";
|
||||
|
||||
// 시리즈 색은 엔터티 고정(네이버 초록은 CVD 분리 검증 통과 톤) — 순서·색 재배정 금지.
|
||||
const SERIES = [
|
||||
{ key: "naver", label: "네이버", color: "var(--color-naver)" },
|
||||
{ key: "coupang", label: "쿠팡", color: "var(--color-coupang)" },
|
||||
{ key: "final", label: "최종 최저가", color: "var(--color-final)" },
|
||||
] as const;
|
||||
|
||||
export default function Products() {
|
||||
const [q, setQ] = useState("");
|
||||
const [qInput, setQInput] = useState("");
|
||||
const [selected, setSelected] = useState<ProductItem | null>(null);
|
||||
|
||||
const list = useQuery({
|
||||
queryKey: ["products", q],
|
||||
queryFn: () => get<ProductListRes>(`/v1/lps/products?limit=100${q ? `&q=${encodeURIComponent(q)}` : ""}`),
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<h1 className="text-[17px] font-bold tracking-tight">상품·가격</h1>
|
||||
|
||||
<form className="flex gap-1.5" onSubmit={(e) => { e.preventDefault(); setQ(qInput.trim()); }}>
|
||||
<input value={qInput} onChange={(e) => setQInput(e.target.value)} placeholder="상품코드 검색"
|
||||
className="w-64 rounded-lg border border-line-200 bg-surface px-3 py-1.5 text-[12.5px] outline-none focus:border-primary-600" />
|
||||
<button type="submit" className="rounded-lg bg-primary-600 px-3 py-1.5 text-[12px] font-semibold text-white hover:bg-primary-700">검색</button>
|
||||
</form>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-[400px_1fr]">
|
||||
<Card title={`검색 이력 상품 ${list.data?.items.length ?? "—"}건`} hint="최근 검색순">
|
||||
{list.isPending && <Loading />}
|
||||
{list.isError && <ErrorNote error={list.error} />}
|
||||
{list.data && list.data.items.length === 0 && <Empty>아직 검색된 상품이 없습니다</Empty>}
|
||||
{list.data && list.data.items.length > 0 && (
|
||||
<ul className="max-h-[560px] divide-y divide-line-100 overflow-y-auto">
|
||||
{list.data.items.map((p) => (
|
||||
<li key={p.product_code}>
|
||||
<button onClick={() => setSelected(p)}
|
||||
className={`w-full px-1 py-2 text-left hover:bg-surface-2 ${selected?.product_code === p.product_code ? "bg-primary-50/60" : ""}`}>
|
||||
<div className="flex items-baseline justify-between gap-2">
|
||||
<span className="truncate text-[12.5px] font-semibold">{p.display_name || p.product_code}</span>
|
||||
<span className="tnum shrink-0 text-[12.5px] font-bold">{won(p.final_lowest)}</span>
|
||||
</div>
|
||||
<div className="mt-0.5 flex justify-between text-[11px] text-ink-400">
|
||||
<span>{p.product_code} · 검색 {p.searches}회</span>
|
||||
<span>{timeAgo(p.triggered_at)}{p.outcome === "not_found" ? " · 못 찾음" : ""}</span>
|
||||
</div>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<ProductDetail product={selected} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProductDetail({ product }: { product: ProductItem | null }) {
|
||||
const qc = useQueryClient();
|
||||
const history = useQuery({
|
||||
queryKey: ["history", product?.product_code],
|
||||
queryFn: () => get<PriceHistoryRes>(`/v1/lps/products/${encodeURIComponent(product!.product_code)}/history?limit=200`),
|
||||
enabled: !!product,
|
||||
});
|
||||
const research = useMutation({
|
||||
mutationFn: () => post<SearchRes>("/v1/lps/search", {
|
||||
data: [{ product_code: product!.product_code, product_name: product!.display_name || product!.product_code, job_type: "manual" }],
|
||||
}),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ["jobs"] }),
|
||||
});
|
||||
|
||||
if (!product) return <Card title="가격 추이"><Empty>왼쪽에서 상품을 선택하세요</Empty></Card>;
|
||||
|
||||
const points = (history.data?.points ?? []).map((p) => ({ ...p, x: dateShort(p.triggered_at) }));
|
||||
const latest = history.data?.points.at(-1);
|
||||
const malls = (latest?.by_mall ?? []).filter((m) => m.price != null)
|
||||
.sort((a, b) => (a.price ?? 0) - (b.price ?? 0)).slice(0, 8);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Card
|
||||
title={<>가격 추이 — {product.display_name || product.product_code}</>}
|
||||
hint={
|
||||
<button onClick={() => research.mutate()} disabled={research.isPending}
|
||||
className="rounded-md bg-primary-600 px-2.5 py-1 text-[11.5px] font-semibold text-white hover:bg-primary-700 disabled:opacity-50">
|
||||
{research.isPending ? "요청 중…" : "지금 다시 검색"}
|
||||
</button>
|
||||
}>
|
||||
{research.isSuccess && (
|
||||
<p className="mb-2 rounded-lg bg-ok-50 px-3 py-1.5 text-[12px] font-medium text-ok-600">
|
||||
{research.data.accepted > 0 ? "검색을 접수했습니다 — 잠시 후 새 점이 추가됩니다" : "이미 같은 상품 검색이 진행 중입니다"}
|
||||
</p>
|
||||
)}
|
||||
{research.isError && <ErrorNote error={research.error} />}
|
||||
{history.isPending && <Loading />}
|
||||
{history.isError && <ErrorNote error={history.error} />}
|
||||
{history.data && points.length === 0 && <Empty>이력이 없습니다</Empty>}
|
||||
{points.length > 0 && (
|
||||
<>
|
||||
<ResponsiveContainer width="100%" height={240}>
|
||||
<LineChart data={points} margin={{ top: 6, right: 12, bottom: 0, left: 0 }}>
|
||||
<CartesianGrid stroke="var(--color-grid)" vertical={false} />
|
||||
<XAxis dataKey="x" tick={{ fill: "var(--color-ink-400)" }} tickLine={false} axisLine={{ stroke: "var(--color-line-200)" }} minTickGap={56} />
|
||||
<YAxis tick={{ fill: "var(--color-ink-400)" }} tickLine={false} axisLine={false}
|
||||
width={64} tickFormatter={(v: number) => v.toLocaleString("ko-KR")} domain={["auto", "auto"]} />
|
||||
<Tooltip formatter={(v: number, name: string) => [won(v), name]} />
|
||||
{SERIES.map((s) => (
|
||||
<Line key={s.key} type="monotone" dataKey={s.key} name={s.label} stroke={s.color}
|
||||
strokeWidth={2} dot={{ r: 2.5, strokeWidth: 0, fill: s.color }} connectNulls isAnimationActive={false} />
|
||||
))}
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
<p className="mt-1 flex flex-wrap gap-4 text-[11px] font-semibold text-ink-500">
|
||||
{SERIES.map((s) => (
|
||||
<span key={s.key}>
|
||||
<span className="mr-1 inline-block h-2 w-2 rounded-full" style={{ background: s.color }} aria-hidden />
|
||||
{s.label}
|
||||
</span>
|
||||
))}
|
||||
<span className="ml-auto font-medium text-ink-400">빈 구간 = 그 시점에 해당 소스에서 못 찾음</span>
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{latest && (
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<Card title="몰별 최저가 (최근 검색)" hint={dateShort(latest.triggered_at)}>
|
||||
{malls.length === 0 ? (
|
||||
<Empty>몰별 데이터 없음</Empty>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height={Math.max(120, malls.length * 34)}>
|
||||
<BarChart data={malls} layout="vertical" margin={{ top: 0, right: 56, bottom: 0, left: 8 }}>
|
||||
<XAxis type="number" hide domain={[0, "dataMax"]} />
|
||||
<YAxis type="category" dataKey="mall" width={88} tick={{ fill: "var(--color-ink-700)", fontSize: 11.5 }} tickLine={false} axisLine={false} />
|
||||
<Tooltip formatter={(v: number) => [won(v), "최저가"]} />
|
||||
<Bar dataKey="price" barSize={14} radius={[0, 4, 4, 0]}
|
||||
label={{ position: "right", fill: "var(--color-ink-500)", fontSize: 11, formatter: (v: number) => v.toLocaleString("ko-KR") }}>
|
||||
{malls.map((m, i) => (
|
||||
<Cell key={i} fill={m.source === "naver" ? "var(--color-naver)" : m.source === "coupang" ? "var(--color-coupang)" : "var(--color-ink-400)"} />
|
||||
))}
|
||||
</Bar>
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card title="검증 링크 (최근 검색)">
|
||||
<ul className="space-y-2 text-[12.5px]">
|
||||
{latest.naver_url && (
|
||||
<li>
|
||||
<a href={latest.naver_url} target="_blank" rel="noreferrer" className="font-semibold text-primary-600 hover:underline">
|
||||
네이버 — {won(latest.naver)} ↗
|
||||
</a>
|
||||
<div className="truncate text-[11px] text-ink-400">{latest.naver_name}</div>
|
||||
</li>
|
||||
)}
|
||||
{latest.coupang_url && (
|
||||
<li>
|
||||
<a href={latest.coupang_url} target="_blank" rel="noreferrer" className="font-semibold text-primary-600 hover:underline">
|
||||
쿠팡 — {won(latest.coupang)} ↗
|
||||
</a>
|
||||
<div className="truncate text-[11px] text-ink-400">{latest.coupang_name}</div>
|
||||
</li>
|
||||
)}
|
||||
{!latest.naver_url && !latest.coupang_url && <Empty>링크 없음</Empty>}
|
||||
</ul>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/** 설정 — API base URL·guard 키(localStorage). prod 에서 X-API-Key 헤더로 자동 첨부. */
|
||||
|
||||
import { useState } from "react";
|
||||
import { settings } from "../api/client";
|
||||
import { Card } from "../components/ui";
|
||||
|
||||
export default function Settings() {
|
||||
const [baseUrl, setBaseUrl] = useState(settings.baseUrl());
|
||||
const [apiKey, setApiKey] = useState(settings.apiKey());
|
||||
const [saved, setSaved] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="max-w-xl space-y-4">
|
||||
<h1 className="text-[17px] font-bold tracking-tight">설정</h1>
|
||||
<Card title="API 연결">
|
||||
<form
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
settings.save(baseUrl.trim(), apiKey.trim());
|
||||
setSaved(true);
|
||||
setTimeout(() => setSaved(false), 2000);
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<label htmlFor="base" className="mb-1 block text-[12px] font-semibold text-ink-700">API 주소</label>
|
||||
<input id="base" value={baseUrl} onChange={(e) => setBaseUrl(e.target.value)}
|
||||
placeholder="비우면 현재 주소 기준 (개발: vite 프록시 → :9600)"
|
||||
className="w-full rounded-lg border border-line-200 bg-surface px-3 py-2 text-[12.5px] outline-none focus:border-primary-600" />
|
||||
<p className="mt-1 text-[11px] text-ink-400">예: https://lps.example.com — dev 서버를 직접 보려면 해당 주소 입력</p>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="key" className="mb-1 block text-[12px] font-semibold text-ink-700">API 키 (X-API-Key)</label>
|
||||
<input id="key" type="password" value={apiKey} onChange={(e) => setApiKey(e.target.value)}
|
||||
placeholder="개발(개방 모드)은 비워둠 — prod 만 필요"
|
||||
autoComplete="off"
|
||||
className="w-full rounded-lg border border-line-200 bg-surface px-3 py-2 text-[12.5px] outline-none focus:border-primary-600" />
|
||||
<p className="mt-1 text-[11px] text-ink-400">서버 toml 의 [WebServerConfig].api_keys 중 하나. 이 브라우저에만 저장됩니다.</p>
|
||||
</div>
|
||||
<button type="submit" className="rounded-lg bg-primary-600 px-4 py-2 text-[12.5px] font-semibold text-white hover:bg-primary-700">
|
||||
저장
|
||||
</button>
|
||||
{saved && <span className="ml-2 text-[12px] font-medium text-ok-600">저장했습니다</span>}
|
||||
</form>
|
||||
</Card>
|
||||
<p className="text-[11px] leading-relaxed text-ink-400">
|
||||
지표 임계·요청 예산 등 서버 동작 설정은 이 화면에서 바꾸지 않습니다 — 설정 소스는 서버의
|
||||
config.<env>.toml 하나이며(2026-07-13 협의), 변경은 toml 수정 + 재시작으로 합니다.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"skipLibCheck": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"types": ["vite/client"]
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"root":["./src/main.tsx","./src/api/client.ts","./src/api/types.ts","./src/components/layout.tsx","./src/components/ui.tsx","./src/lib/format.ts","./src/pages/costs.tsx","./src/pages/crawl.tsx","./src/pages/dashboard.tsx","./src/pages/jobs.tsx","./src/pages/products.tsx","./src/pages/settings.tsx"],"version":"5.6.3"}
|
||||
@@ -0,0 +1,19 @@
|
||||
import react from "@vitejs/plugin-react";
|
||||
import tailwindcss from "@tailwindcss/vite";
|
||||
import { defineConfig } from "vite";
|
||||
|
||||
// dev 서버는 /v1·/healthz·/readyz 를 LPS API(:9600)로 프록시한다 — CORS 설정 불필요.
|
||||
// 다른 API 호스트를 보려면 VITE_LPS_URL 로 대상 변경(또는 앱 내 설정에서 base URL 지정).
|
||||
const target = process.env.VITE_LPS_URL || "http://localhost:9600";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
server: {
|
||||
port: 5174,
|
||||
proxy: {
|
||||
"/v1": { target, changeOrigin: true },
|
||||
"/healthz": { target, changeOrigin: true },
|
||||
"/readyz": { target, changeOrigin: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user