kcg-ai-monitoring/frontend/src/features/parent-inference/ParentReview.tsx
htlee c1cc36b134 refactor(design-system): 하드코딩 색상 라이트/다크 대응 + raw button/input 공통 컴포넌트 치환
30개 파일 전 영역에 동일한 패턴으로 SSOT 준수:

**StatBox 재설계 (2파일)**:
- RealGearGroups, RealVesselAnalysis 의 `color: string` prop 제거
- `intent: BadgeIntent` prop + `INTENT_TEXT_CLASS` 매핑 도입

**raw `<button>` → Button 컴포넌트 (다수)**:
- `bg-blue-600 hover:bg-blue-500 text-on-vivid ...` → `<Button variant="primary">`
- `bg-orange-600 ...` / `bg-green-600 ...` → `<Button variant="primary">`
- `bg-red-600 ...` → `<Button variant="destructive">`
- 아이콘 전용 → `<Button variant="ghost" aria-label=".." icon={...} />`
- detection/enforcement/admin/parent-inference/statistics/ai-operations/auth 전영역

**raw `<input>` → Input 컴포넌트**:
- parent-inference (ParentReview, ParentExclusion, LabelSession)
- admin (PermissionsPanel, UserRoleAssignDialog)
- ai-operations (AIAssistant)
- auth (LoginPage)

**raw `<select>` → Select 컴포넌트**:
- detection (RealGearGroups, RealVesselAnalysis, ChinaFishing)

**커스텀 탭 → TabBar/TabButton (segmented/underline)**:
- ChinaFishing: 모드 탭 + 선박 탭 + 통계 탭

**raw `<input type="checkbox">` → Checkbox**:
- GearDetection FilterCheckGroup

**하드코딩 Tailwind 색상 라이트/다크 쌍 변환 (전영역)**:
- `text-red-400` → `text-red-600 dark:text-red-400`
- `text-green-400` → `text-green-600 dark:text-green-400`
- blue/cyan/orange/yellow/purple/amber 동일 패턴
- `text-*-500` 아이콘도 `text-*-600 dark:text-*-500` 로 라이트 모드 대응
- 상태 dot (bg-red-500 animate-pulse 등)은 의도적 시각 구분이므로 유지

**에러 메시지 한글 → t('error.errorPrefix') 통일**:
- detection/parent-inference/admin 에서 `에러: {error}` 패턴 → `t('error.errorPrefix', { msg: error })`

**결과**: tsc 0 errors / eslint 0 errors (84 warnings 기존)
2026-04-16 17:09:14 +09:00

300 lines
11 KiB
TypeScript

import { useEffect, useState, useCallback } from 'react';
import { CheckCircle, XCircle, RotateCcw, Loader2, GitMerge } from 'lucide-react';
import { Card, CardContent } from '@shared/components/ui/card';
import { Badge } from '@shared/components/ui/badge';
import { Button } from '@shared/components/ui/button';
import { Input } from '@shared/components/ui/input';
import { Select } from '@shared/components/ui/select';
import { PageContainer, PageHeader } from '@shared/components/layout';
import { useAuth } from '@/app/auth/AuthContext';
import {
fetchReviewList,
reviewParent,
createLabelSession,
excludeForGroup,
type ParentResolution,
} from '@/services/parentInferenceApi';
import { formatDateTime } from '@shared/utils/dateFormat';
import { getParentResolutionIntent, getParentResolutionLabel } from '@shared/constants/parentResolutionStatuses';
import { useSettingsStore } from '@stores/settingsStore';
import { useTranslation } from 'react-i18next';
/**
* 모선 확정/거부/리셋 페이지.
* - 운영자가 prediction이 추론한 모선 후보를 확정/거부.
* - 권한: parent-inference-workflow:parent-review (READ + UPDATE)
* - 모든 액션은 백엔드에서 audit_log + review_log에 기록
*/
export function ParentReview() {
const { t: tc } = useTranslation('common');
const lang = useSettingsStore((s) => s.language);
const { hasPermission } = useAuth();
const canUpdate = hasPermission('parent-inference-workflow:parent-review', 'UPDATE');
const [items, setItems] = useState<ParentResolution[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [actionLoading, setActionLoading] = useState<number | null>(null);
const [filter, setFilter] = useState<string>('');
// 새 그룹 입력 폼 (테스트용)
const [newGroupKey, setNewGroupKey] = useState('');
const [newSubCluster, setNewSubCluster] = useState('1');
const [newMmsi, setNewMmsi] = useState('');
const load = useCallback(async () => {
setLoading(true);
setError('');
try {
const res = await fetchReviewList(filter || undefined, 0, 50);
setItems(res.content);
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : 'unknown';
setError(msg);
} finally {
setLoading(false);
}
}, [filter]);
useEffect(() => {
load();
}, [load]);
const handleAction = async (
item: ParentResolution,
action: 'CONFIRM' | 'REJECT' | 'RESET',
selectedMmsi?: string,
) => {
if (!canUpdate) return;
setActionLoading(item.id);
try {
await reviewParent(item.groupKey, item.subClusterId, {
action,
selectedParentMmsi: selectedMmsi || item.selectedParentMmsi || undefined,
comment: `${action} via UI`,
});
// CONFIRM → LabelSession 자동 생성 (학습 데이터 수집 시작)
if (action === 'CONFIRM') {
const mmsi = selectedMmsi || item.selectedParentMmsi;
if (mmsi) {
await createLabelSession(item.groupKey, item.subClusterId, {
labelParentMmsi: mmsi,
}).catch(() => { /* LabelSession 실패는 무시 — 리뷰 자체는 성공 */ });
}
}
// REJECT → Exclusion 자동 등록 (잘못된 후보 재추론 방지)
if (action === 'REJECT') {
const mmsi = item.selectedParentMmsi;
if (mmsi) {
await excludeForGroup(item.groupKey, item.subClusterId, {
excludedMmsi: mmsi,
reason: '운영자 거부',
}).catch(() => { /* Exclusion 실패는 무시 */ });
}
}
await load();
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : 'unknown';
alert(tc('error.processFailed', { msg }));
} finally {
setActionLoading(null);
}
};
const handleCreate = async () => {
if (!canUpdate || !newGroupKey || !newMmsi) return;
setActionLoading(-1);
try {
await reviewParent(newGroupKey, parseInt(newSubCluster, 10), {
action: 'CONFIRM',
selectedParentMmsi: newMmsi,
comment: '운영자 직접 등록',
});
setNewGroupKey('');
setNewMmsi('');
await load();
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : 'unknown';
alert(tc('error.registerFailed', { msg }));
} finally {
setActionLoading(null);
}
};
return (
<PageContainer size="lg">
<PageHeader
icon={GitMerge}
iconColor="text-purple-400"
title="모선 확정/거부"
description="추론된 모선 후보를 확정/거부합니다. 권한: parent-inference-workflow:parent-review (UPDATE)"
actions={
<>
<Select size="sm" title="상태 필터" value={filter} onChange={(e) => setFilter(e.target.value)}>
<option value=""> </option>
<option value="UNRESOLVED"></option>
<option value="MANUAL_CONFIRMED"></option>
<option value="REVIEW_REQUIRED"></option>
</Select>
<Button variant="primary" size="sm" onClick={load}>
</Button>
</>
}
/>
{/* 신규 등록 폼 (테스트용) */}
{canUpdate && (
<Card>
<CardContent className="p-4">
<div className="text-xs text-muted-foreground mb-2"> ()</div>
<div className="flex items-center gap-2">
<Input
aria-label={tc('aria.groupKey')}
size="sm"
value={newGroupKey}
onChange={(e) => setNewGroupKey(e.target.value)}
placeholder="group_key (예: 渔船A)"
className="flex-1"
/>
<Input
aria-label={tc('aria.subClusterId')}
size="sm"
type="number"
value={newSubCluster}
onChange={(e) => setNewSubCluster(e.target.value)}
placeholder="sub_cluster_id"
className="w-32"
/>
<Input
aria-label="parent MMSI"
size="sm"
value={newMmsi}
onChange={(e) => setNewMmsi(e.target.value)}
placeholder="parent MMSI"
className="w-40"
/>
<Button
variant="primary"
size="sm"
onClick={handleCreate}
disabled={!newGroupKey || !newMmsi || actionLoading === -1}
icon={actionLoading === -1 ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <CheckCircle className="w-3.5 h-3.5" />}
>
</Button>
</div>
</CardContent>
</Card>
)}
{!canUpdate && (
<Card>
<CardContent className="p-4">
<div className="text-xs text-yellow-600 dark:text-yellow-400">
(UPDATE ). // .
</div>
</CardContent>
</Card>
)}
{error && (
<Card>
<CardContent className="p-4">
<div className="text-xs text-red-600 dark:text-red-400">{tc('error.errorPrefix', { msg: error })}</div>
</CardContent>
</Card>
)}
{loading && (
<div className="flex items-center justify-center py-12 text-muted-foreground">
<Loader2 className="w-5 h-5 animate-spin" />
</div>
)}
{!loading && items.length === 0 && (
<Card>
<CardContent className="p-8 text-center text-hint text-sm">
. , prediction .
</CardContent>
</Card>
)}
{!loading && items.length > 0 && (
<Card>
<CardContent className="p-0 overflow-x-auto">
<table className="w-full text-xs">
<thead className="bg-surface-overlay text-hint">
<tr>
<th className="px-3 py-2 text-left">ID</th>
<th className="px-3 py-2 text-left">Group Key</th>
<th className="px-3 py-2 text-center">Sub</th>
<th className="px-3 py-2 text-left"></th>
<th className="px-3 py-2 text-left"> MMSI</th>
<th className="px-3 py-2 text-left"> </th>
<th className="px-3 py-2 text-center"></th>
</tr>
</thead>
<tbody>
{items.map((it) => (
<tr key={it.id} className="border-t border-border hover:bg-surface-overlay/50">
<td className="px-3 py-2 text-hint font-mono">{it.id}</td>
<td className="px-3 py-2 text-heading font-medium">{it.groupKey}</td>
<td className="px-3 py-2 text-center text-muted-foreground">{it.subClusterId}</td>
<td className="px-3 py-2">
<Badge intent={getParentResolutionIntent(it.status)} size="sm">
{getParentResolutionLabel(it.status, tc, lang)}
</Badge>
</td>
<td className="px-3 py-2 text-cyan-600 dark:text-cyan-400 font-mono">{it.selectedParentMmsi || '-'}</td>
<td className="px-3 py-2 text-muted-foreground text-[10px]">
{formatDateTime(it.updatedAt)}
</td>
<td className="px-3 py-2">
<div className="flex items-center justify-center gap-1">
<Button
variant="ghost"
size="sm"
disabled={!canUpdate || actionLoading === it.id}
onClick={() => handleAction(it, 'CONFIRM')}
title="확정"
aria-label="확정"
className="text-green-600 dark:text-green-400 hover:bg-green-500/20"
icon={<CheckCircle className="w-3.5 h-3.5" />}
/>
<Button
variant="ghost"
size="sm"
disabled={!canUpdate || actionLoading === it.id}
onClick={() => handleAction(it, 'REJECT')}
title="거부"
aria-label="거부"
className="text-red-600 dark:text-red-400 hover:bg-red-500/20"
icon={<XCircle className="w-3.5 h-3.5" />}
/>
<Button
variant="ghost"
size="sm"
disabled={!canUpdate || actionLoading === it.id}
onClick={() => handleAction(it, 'RESET')}
title="리셋"
aria-label="리셋"
className="text-blue-600 dark:text-blue-400 hover:bg-blue-500/20"
icon={<RotateCcw className="w-3.5 h-3.5" />}
/>
</div>
</td>
</tr>
))}
</tbody>
</table>
</CardContent>
</Card>
)}
</PageContainer>
);
}