first commit
This commit is contained in:
202
frontend/src/App.tsx
Normal file
202
frontend/src/App.tsx
Normal file
@@ -0,0 +1,202 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Routes, Route, Navigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Database, CheckCircle, BarChart2, LogOut, User, FlaskConical } from 'lucide-react';
|
||||
import { ImportView } from './components/ImportView';
|
||||
import { ReviewView } from './components/ReviewView';
|
||||
import { DashboardView } from './components/DashboardView';
|
||||
import { LabView } from './components/LabView';
|
||||
import { LoginPage } from './components/LoginPage';
|
||||
import { LanguageSwitch } from './components/common/LanguageSwitch';
|
||||
import { authApi } from './services/api';
|
||||
|
||||
type TabId = 'import' | 'review' | 'dashboard' | 'lab';
|
||||
|
||||
interface Tab {
|
||||
id: TabId;
|
||||
icon: React.ElementType;
|
||||
labelKey: string;
|
||||
badge?: number;
|
||||
}
|
||||
|
||||
const MainLayout: React.FC<{ onLogout: () => void }> = ({ onLogout }) => {
|
||||
const { t } = useTranslation();
|
||||
const [activeTab, setActiveTab] = useState<TabId>('import');
|
||||
const [reviewCount, setReviewCount] = useState(0);
|
||||
const [userEmail, setUserEmail] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
authApi.me().then(user => {
|
||||
setUserEmail(user.email);
|
||||
}).catch(() => { });
|
||||
}, []);
|
||||
|
||||
const tabs: Tab[] = [
|
||||
{ id: 'import', icon: Database, labelKey: 'nav.import' },
|
||||
{ id: 'review', icon: CheckCircle, labelKey: 'nav.review', badge: reviewCount },
|
||||
{ id: 'dashboard', icon: BarChart2, labelKey: 'nav.dashboard' },
|
||||
{ id: 'lab', icon: FlaskConical, labelKey: 'nav.lab' },
|
||||
];
|
||||
|
||||
const handleEtlComplete = () => {
|
||||
setReviewCount(2);
|
||||
setActiveTab('review');
|
||||
};
|
||||
|
||||
const handleReviewComplete = () => {
|
||||
setReviewCount(0);
|
||||
setActiveTab('dashboard');
|
||||
};
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('token');
|
||||
onLogout();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-50 font-sans text-slate-800">
|
||||
<header className="bg-white border-b border-slate-200 sticky top-0 z-10">
|
||||
<div className="max-w-7xl mx-auto px-4 h-16 flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 bg-indigo-600 rounded-lg flex items-center justify-center text-white font-bold">
|
||||
S
|
||||
</div>
|
||||
<div>
|
||||
<span className="font-bold text-lg text-slate-800 block leading-tight">
|
||||
{t('common.appName')}
|
||||
</span>
|
||||
<span className="text-[10px] text-slate-500 font-medium">
|
||||
{t('common.appSubtitle')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-1 bg-slate-100 p-1 rounded-lg">
|
||||
{tabs.map(tab => (
|
||||
<button
|
||||
key={tab.id}
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
className={`
|
||||
flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-all
|
||||
${activeTab === tab.id
|
||||
? 'bg-white text-indigo-600 shadow-sm'
|
||||
: 'text-slate-500 hover:text-slate-700 hover:bg-slate-200/50'}
|
||||
`}
|
||||
>
|
||||
<tab.icon size={16} />
|
||||
{t(tab.labelKey)}
|
||||
{tab.badge !== undefined && tab.badge > 0 && (
|
||||
<span className="bg-rose-500 text-white text-[10px] px-1.5 py-0.5 rounded-full">
|
||||
{tab.badge}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex items-center gap-2 text-sm text-emerald-600 bg-emerald-50 px-3 py-1 rounded-full border border-emerald-100">
|
||||
<div className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></div>
|
||||
{t('common.systemRunning')}
|
||||
</div>
|
||||
|
||||
<LanguageSwitch />
|
||||
|
||||
<div className="flex items-center gap-2 text-sm text-slate-600">
|
||||
<User size={16} />
|
||||
<span className="hidden sm:inline">{userEmail}</span>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="flex items-center gap-2 px-3 py-2 text-sm text-slate-600 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
|
||||
title={t('nav.logout')}
|
||||
>
|
||||
<LogOut size={16} />
|
||||
<span className="hidden sm:inline">{t('nav.logout')}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main className="max-w-7xl mx-auto px-4 py-8">
|
||||
{activeTab === 'import' && (
|
||||
<ImportView onEtlComplete={handleEtlComplete} />
|
||||
)}
|
||||
|
||||
{activeTab === 'review' && (
|
||||
<ReviewView onReviewComplete={handleReviewComplete} />
|
||||
)}
|
||||
|
||||
{activeTab === 'dashboard' && (
|
||||
<DashboardView />
|
||||
)}
|
||||
|
||||
{activeTab === 'lab' && (
|
||||
<LabView />
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
function App() {
|
||||
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem('token');
|
||||
if (token) {
|
||||
authApi.me()
|
||||
.then(() => setIsAuthenticated(true))
|
||||
.catch(() => {
|
||||
localStorage.removeItem('token');
|
||||
setIsAuthenticated(false);
|
||||
});
|
||||
} else {
|
||||
setIsAuthenticated(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleLogin = () => {
|
||||
setIsAuthenticated(true);
|
||||
};
|
||||
|
||||
const handleLogout = () => {
|
||||
setIsAuthenticated(false);
|
||||
};
|
||||
|
||||
if (isAuthenticated === null) {
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-50 flex items-center justify-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-4 border-indigo-600 border-t-transparent"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Routes>
|
||||
<Route
|
||||
path="/login"
|
||||
element={
|
||||
isAuthenticated ? (
|
||||
<Navigate to="/" replace />
|
||||
) : (
|
||||
<LoginPage onLogin={handleLogin} />
|
||||
)
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/*"
|
||||
element={
|
||||
isAuthenticated ? (
|
||||
<MainLayout onLogout={handleLogout} />
|
||||
) : (
|
||||
<Navigate to="/login" replace />
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
279
frontend/src/components/DashboardView.tsx
Normal file
279
frontend/src/components/DashboardView.tsx
Normal file
@@ -0,0 +1,279 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import {
|
||||
BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as RechartsTooltip, ResponsiveContainer,
|
||||
Cell
|
||||
} from 'recharts';
|
||||
import { Filter, Activity, Download, Info, CheckCircle, HelpCircle, XCircle } from 'lucide-react';
|
||||
import { Card } from './common/Card';
|
||||
import { dashboardApi, reportApi } from '../services/api';
|
||||
import type { DashboardKPI, FunnelData, AttributionRow } from '../types';
|
||||
|
||||
export const DashboardView: React.FC = () => {
|
||||
const [kpi, setKpi] = useState<DashboardKPI>({
|
||||
total_dit: 0,
|
||||
sample_rate: 0,
|
||||
hit_rate: 0,
|
||||
fulfillment_rate: 0,
|
||||
orphan_sample_rate: 0,
|
||||
total_revenue: 0,
|
||||
});
|
||||
const [funnelData, setFunnelData] = useState<FunnelData[]>([]);
|
||||
const [attribution, setAttribution] = useState<AttributionRow[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [filterType, setFilterType] = useState<'all' | 'sample' | 'order'>('all');
|
||||
|
||||
useEffect(() => {
|
||||
loadDashboardData();
|
||||
}, []);
|
||||
|
||||
const loadDashboardData = async () => {
|
||||
try {
|
||||
const [kpiData, funnelRes, attrRes] = await Promise.all([
|
||||
dashboardApi.getKPI(),
|
||||
dashboardApi.getFunnel(),
|
||||
dashboardApi.getAttribution(),
|
||||
]);
|
||||
setKpi(kpiData);
|
||||
setFunnelData(funnelRes);
|
||||
setAttribution(attrRes);
|
||||
} catch (error) {
|
||||
console.error('Error loading dashboard:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleExport = async (format: 'xlsx' | 'pdf') => {
|
||||
try {
|
||||
const blob = format === 'xlsx'
|
||||
? await reportApi.exportExcel()
|
||||
: await reportApi.exportPdf();
|
||||
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `report.${format}`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(url);
|
||||
document.body.removeChild(a);
|
||||
} catch (error) {
|
||||
console.error('Export error:', error);
|
||||
alert('匯出失敗,請稍後再試');
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-20">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const filteredAttribution = attribution.filter(row => {
|
||||
if (filterType === 'sample') return !!row.sample;
|
||||
if (filterType === 'order') return !!row.order;
|
||||
return true;
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6 animate-in fade-in slide-in-from-right-4 duration-500">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-slate-800">業務轉換率戰情室 (v1.0)</h1>
|
||||
<p className="text-slate-500 mt-1">
|
||||
數據來源:DIT Report, 樣品紀錄, 訂單明細 | 邏輯:瀑布式比對 + LIFO 歸因
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => handleExport('xlsx')}
|
||||
className="flex items-center gap-2 px-4 py-2 border border-slate-300 rounded-lg text-slate-600 hover:bg-slate-50 text-sm font-medium"
|
||||
>
|
||||
<Download size={16} />
|
||||
匯出報表
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* KPI Cards */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-5 gap-4">
|
||||
<Card className="p-4 border-l-4 border-l-indigo-500">
|
||||
<div className="text-xs text-slate-500 mb-1">DIT 總案件數</div>
|
||||
<div className="text-2xl font-bold text-slate-800">{kpi.total_dit}</div>
|
||||
<div className="text-[10px] text-slate-400 mt-1">Total Pipeline</div>
|
||||
</Card>
|
||||
<Card className="p-4 border-l-4 border-l-purple-500">
|
||||
<div className="text-xs text-slate-500 mb-1">送樣轉換率</div>
|
||||
<div className="text-2xl font-bold text-slate-800">{kpi.sample_rate}%</div>
|
||||
<div className="text-[10px] text-purple-600 mt-1">Sample Rate</div>
|
||||
</Card>
|
||||
<Card className="p-4 border-l-4 border-l-emerald-500">
|
||||
<div className="text-xs text-slate-500 mb-1">訂單命中率</div>
|
||||
<div className="text-2xl font-bold text-slate-800">{kpi.hit_rate}%</div>
|
||||
<div className="text-[10px] text-emerald-600 mt-1">Hit Rate (Binary)</div>
|
||||
</Card>
|
||||
<Card className="p-4 border-l-4 border-l-amber-500">
|
||||
<div className="text-xs text-slate-500 mb-1">EAU 達成率</div>
|
||||
<div className="text-2xl font-bold text-slate-800">{kpi.fulfillment_rate}%</div>
|
||||
<div className="text-[10px] text-amber-600 mt-1">Fulfillment (LIFO)</div>
|
||||
</Card>
|
||||
<Card className="p-4 border-l-4 border-l-rose-500">
|
||||
<div className="text-xs text-slate-500 mb-1">無效送樣率</div>
|
||||
<div className="text-2xl font-bold text-rose-600">{kpi.orphan_sample_rate}%</div>
|
||||
<div className="text-[10px] text-rose-400 mt-1">Orphan Sample</div>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* Funnel Chart */}
|
||||
<Card className="lg:col-span-2 p-6">
|
||||
<h3 className="font-bold text-slate-700 mb-6 flex items-center gap-2">
|
||||
<Filter size={18} />
|
||||
DIT 轉換漏斗 (Funnel Analysis)
|
||||
</h3>
|
||||
<div className="h-64 w-full">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart
|
||||
layout="vertical"
|
||||
data={funnelData}
|
||||
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
|
||||
>
|
||||
<CartesianGrid strokeDasharray="3 3" horizontal={false} />
|
||||
<XAxis type="number" />
|
||||
<YAxis dataKey="name" type="category" width={100} />
|
||||
<RechartsTooltip cursor={{ fill: '#f1f5f9' }} />
|
||||
<Bar
|
||||
dataKey="value"
|
||||
barSize={30}
|
||||
radius={[0, 4, 4, 0]}
|
||||
label={{ position: 'right' }}
|
||||
onClick={(data) => {
|
||||
if (data.name === '成功送樣') setFilterType('sample');
|
||||
else if (data.name === '取得訂單') setFilterType('order');
|
||||
else setFilterType('all');
|
||||
}}
|
||||
style={{ cursor: 'pointer' }}
|
||||
>
|
||||
{funnelData.map((entry, index) => (
|
||||
<Cell
|
||||
key={`cell-${index}`}
|
||||
fill={entry.fill}
|
||||
fillOpacity={filterType === 'all' || (filterType === 'sample' && entry.name === '成功送樣') || (filterType === 'order' && entry.name === '取得訂單') ? 1 : 0.3}
|
||||
/>
|
||||
))}
|
||||
</Bar>
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Total Revenue Card */}
|
||||
<Card className="p-6 flex flex-col justify-center items-center bg-gradient-to-br from-emerald-500 to-teal-600 text-white">
|
||||
<Activity size={48} className="mb-4 opacity-80" />
|
||||
<h3 className="text-lg font-medium opacity-90">歸因總營收</h3>
|
||||
<div className="text-4xl font-bold my-2">
|
||||
${kpi.total_revenue.toLocaleString()}
|
||||
</div>
|
||||
<p className="text-xs opacity-70 text-center px-4">
|
||||
基於 LIFO 邏輯分配至各 DIT 案件之實際訂單金額總和
|
||||
</p>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Attribution Table */}
|
||||
<Card className="overflow-hidden">
|
||||
<div className="bg-slate-50 px-6 py-4 border-b border-slate-200 flex justify-between items-center">
|
||||
<div className="flex items-center gap-4">
|
||||
<h3 className="font-bold text-slate-700 flex items-center gap-2">
|
||||
<Activity size={18} />
|
||||
DIT 歸因明細表 (LIFO 業績分配)
|
||||
</h3>
|
||||
{filterType !== 'all' && (
|
||||
<span className="flex items-center gap-1 px-2 py-0.5 bg-indigo-100 text-indigo-700 text-xs font-bold rounded-full animate-in zoom-in duration-300">
|
||||
篩選:{filterType === 'sample' ? '成功送樣' : '取得訂單'}
|
||||
<button onClick={() => setFilterType('all')} className="hover:text-indigo-900">
|
||||
<XCircle size={14} />
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-slate-500">
|
||||
<span className="flex items-center gap-1">
|
||||
<Info size={12} />
|
||||
Hover <HelpCircle size={10} /> to see matching logic
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm text-left">
|
||||
<thead className="bg-white text-slate-500 border-b border-slate-200">
|
||||
<tr>
|
||||
<th className="px-6 py-3">OP編號 / 日期</th>
|
||||
<th className="px-6 py-3">Customer / Stage</th>
|
||||
<th className="px-6 py-3">Part No.</th>
|
||||
<th className="px-6 py-3 text-right">EAU / 歸因量</th>
|
||||
<th className="px-6 py-3 text-center">達成率</th>
|
||||
<th className="px-6 py-3 text-center">送樣 / 訂單</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100">
|
||||
{filteredAttribution.map((row, i) => (
|
||||
<tr key={i} className="hover:bg-slate-50 group transition-colors">
|
||||
<td className="px-6 py-3">
|
||||
<div className="font-mono text-xs text-slate-500 font-bold">{row.dit.op_id}</div>
|
||||
<div className="text-[10px] text-slate-400">{row.dit.date}</div>
|
||||
</td>
|
||||
<td className="px-6 py-3">
|
||||
<div className="font-medium text-slate-800">{row.dit.customer}</div>
|
||||
<div className="text-[10px] text-slate-400 font-light">{row.dit.stage}</div>
|
||||
</td>
|
||||
<td className="px-6 py-3 font-mono text-slate-600 text-xs">{row.dit.pn}</td>
|
||||
<td className="px-6 py-3 text-right">
|
||||
<div className="font-mono text-slate-600">{row.dit.eau.toLocaleString()}</div>
|
||||
<div className="font-mono text-emerald-600 font-bold">+{row.attributed_qty.toLocaleString()}</div>
|
||||
</td>
|
||||
<td className="px-6 py-3 text-center">
|
||||
<div className={`text-xs font-bold ${row.fulfillment_rate >= 100 ? 'text-emerald-600' : 'text-slate-500'}`}>
|
||||
{row.fulfillment_rate}%
|
||||
</div>
|
||||
<div className="w-16 h-1 bg-slate-100 rounded-full mt-1 mx-auto overflow-hidden">
|
||||
<div
|
||||
className={`h-full ${row.fulfillment_rate >= 100 ? 'bg-emerald-500' : 'bg-indigo-500'}`}
|
||||
style={{ width: `${Math.min(row.fulfillment_rate, 100)}%` }}
|
||||
></div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-3 text-center">
|
||||
<div className="flex justify-center gap-2">
|
||||
{row.sample ? (
|
||||
<div
|
||||
className="p-1 bg-purple-50 text-purple-700 rounded border border-purple-100 cursor-help"
|
||||
title={`送樣單號: ${row.sample.order_no} (${row.sample.date})`}
|
||||
>
|
||||
<CheckCircle size={14} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-1 text-slate-200"><CheckCircle size={14} /></div>
|
||||
)}
|
||||
{row.order ? (
|
||||
<div
|
||||
className="p-1 bg-emerald-50 text-emerald-700 rounded border border-emerald-100 cursor-help flex items-center gap-1"
|
||||
title={row.match_source || `訂單單號: ${row.order.order_no}`}
|
||||
>
|
||||
<CheckCircle size={14} />
|
||||
<HelpCircle size={10} className="text-emerald-400" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-1 text-slate-200"><CheckCircle size={14} /></div>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
286
frontend/src/components/ImportView.tsx
Normal file
286
frontend/src/components/ImportView.tsx
Normal file
@@ -0,0 +1,286 @@
|
||||
import React, { useState, useRef } from 'react';
|
||||
import {
|
||||
FileText, Database, CheckCircle, RefreshCw, Activity,
|
||||
} from 'lucide-react';
|
||||
import { Card, Badge } from './common/Card';
|
||||
import { etlApi, matchApi } from '../services/api';
|
||||
import type { ParsedFile, DitRecord, OrderRecord } from '../types';
|
||||
|
||||
interface ImportViewProps {
|
||||
onEtlComplete: () => void;
|
||||
}
|
||||
|
||||
type FileType = 'dit' | 'sample' | 'order';
|
||||
|
||||
interface FileState {
|
||||
file: File | null;
|
||||
parsed: ParsedFile | null;
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
export const ImportView: React.FC<ImportViewProps> = ({ onEtlComplete }) => {
|
||||
const [files, setFiles] = useState<Record<FileType, FileState>>({
|
||||
dit: { file: null, parsed: null, loading: false },
|
||||
sample: { file: null, parsed: null, loading: false },
|
||||
order: { file: null, parsed: null, loading: false },
|
||||
});
|
||||
|
||||
const [isProcessing, setIsProcessing] = useState(false);
|
||||
const [processingStep, setProcessingStep] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const fileInputRefs = {
|
||||
dit: useRef<HTMLInputElement>(null),
|
||||
sample: useRef<HTMLInputElement>(null),
|
||||
order: useRef<HTMLInputElement>(null),
|
||||
};
|
||||
|
||||
const handleFileSelect = async (type: FileType, file: File) => {
|
||||
setFiles(prev => ({
|
||||
...prev,
|
||||
[type]: { ...prev[type], file, loading: true }
|
||||
}));
|
||||
|
||||
try {
|
||||
const parsed = await etlApi.upload(file, type);
|
||||
setFiles(prev => ({
|
||||
...prev,
|
||||
[type]: { file, parsed, loading: false }
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error(`Error uploading ${type} file:`, error);
|
||||
setFiles(prev => ({
|
||||
...prev,
|
||||
[type]: { file: null, parsed: null, loading: false }
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
const allFilesReady = files.dit.parsed && files.sample.parsed && files.order.parsed;
|
||||
|
||||
const runEtl = async () => {
|
||||
if (!allFilesReady) {
|
||||
alert("請先上傳所有檔案!");
|
||||
return;
|
||||
}
|
||||
|
||||
setError(null);
|
||||
setIsProcessing(true);
|
||||
const steps = [
|
||||
"正在匯入 DIT Report...",
|
||||
"正在匯入 樣品紀錄...",
|
||||
"正在匯入 訂單明細...",
|
||||
"執行資料標準化 (Normalization)...",
|
||||
"執行模糊比對 (Fuzzy Matching)...",
|
||||
"運算完成!"
|
||||
];
|
||||
|
||||
try {
|
||||
for (let i = 0; i < steps.length - 2; i++) {
|
||||
setProcessingStep(steps[i]);
|
||||
if (i === 0 && files.dit.parsed) {
|
||||
await etlApi.import(files.dit.parsed.file_id);
|
||||
} else if (i === 1 && files.sample.parsed) {
|
||||
await etlApi.import(files.sample.parsed.file_id);
|
||||
} else if (i === 2 && files.order.parsed) {
|
||||
await etlApi.import(files.order.parsed.file_id);
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
}
|
||||
|
||||
setProcessingStep(steps[4]);
|
||||
await matchApi.run();
|
||||
|
||||
setProcessingStep(steps[5]);
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
|
||||
onEtlComplete();
|
||||
} catch (error: any) {
|
||||
console.error('ETL error:', error);
|
||||
const msg = error.response?.data?.detail || error.message || 'ETL 處理失敗,請檢查檔案格式';
|
||||
setError(msg);
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const fileConfigs = [
|
||||
{ type: 'dit' as FileType, title: '1. DIT Report', desc: '含 Metadata (前16行)' },
|
||||
{ type: 'sample' as FileType, title: '2. 樣品紀錄', desc: '含檔頭 (前9行)' },
|
||||
{ type: 'order' as FileType, title: '3. 訂單明細', desc: '標準格式' },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
|
||||
<div className="flex justify-between items-end">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-slate-800">原始資料匯入中心</h1>
|
||||
<p className="text-slate-500 mt-1">系統將自動偵測 Excel/CSV 檔頭位置並進行智慧欄位對應。</p>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
onClick={runEtl}
|
||||
disabled={isProcessing || !allFilesReady}
|
||||
className={`flex items-center gap-2 px-6 py-3 rounded-lg text-white font-bold shadow-lg transition-all ${isProcessing || !allFilesReady
|
||||
? 'bg-slate-400 cursor-not-allowed shadow-none'
|
||||
: 'bg-indigo-600 hover:bg-indigo-700 hover:scale-105 shadow-indigo-200'
|
||||
}`}
|
||||
>
|
||||
{isProcessing ? (
|
||||
<>
|
||||
<RefreshCw size={18} className="animate-spin" />
|
||||
運算中...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Activity size={18} />
|
||||
開始 ETL 運算
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isProcessing && (
|
||||
<div className="bg-slate-800 text-green-400 font-mono p-4 rounded-lg text-sm shadow-inner">
|
||||
<p className="flex items-center gap-2">
|
||||
<span className="animate-pulse">▶</span> {processingStep}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-50 border border-red-200 text-red-700 p-4 rounded-lg text-sm shadow-sm animate-in fade-in duration-300">
|
||||
<p className="flex items-center gap-2 font-bold">
|
||||
<span className="text-red-500">⚠</span> 錯誤:{error}
|
||||
</p>
|
||||
<p className="mt-1 text-xs opacity-80">請檢查檔案格式或連線狀態,並重新嘗試。</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
{fileConfigs.map(({ type, title, desc }) => {
|
||||
const fileState = files[type];
|
||||
const isLoaded = !!fileState.parsed;
|
||||
|
||||
return (
|
||||
<Card
|
||||
key={type}
|
||||
className={`p-6 border-dashed border-2 transition-colors cursor-pointer hover:border-indigo-300 ${isLoaded ? 'border-emerald-300 bg-emerald-50/30' : 'border-slate-300'
|
||||
}`}
|
||||
onClick={() => fileInputRefs[type].current?.click()}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRefs[type]}
|
||||
type="file"
|
||||
accept=".xlsx,.xls,.csv"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) handleFileSelect(type, file);
|
||||
}}
|
||||
/>
|
||||
<div className="flex justify-between items-start mb-4">
|
||||
<div className={`p-3 rounded-lg ${isLoaded ? 'bg-emerald-100 text-emerald-600' : 'bg-slate-100 text-slate-500'
|
||||
}`}>
|
||||
{fileState.loading ? (
|
||||
<RefreshCw size={24} className="animate-spin" />
|
||||
) : isLoaded ? (
|
||||
<CheckCircle size={24} />
|
||||
) : (
|
||||
<FileText size={24} />
|
||||
)}
|
||||
</div>
|
||||
{isLoaded && <Badge type="success">Ready</Badge>}
|
||||
</div>
|
||||
<h3 className="text-lg font-bold text-slate-800">{title}</h3>
|
||||
<p className="text-xs text-slate-500 font-mono mt-1 mb-3 truncate">
|
||||
{fileState.file?.name || "點擊上傳..."}
|
||||
</p>
|
||||
<p className="text-sm text-slate-600">{desc}</p>
|
||||
|
||||
{fileState.parsed && (
|
||||
<div className="mt-4 pt-3 border-t border-slate-200/60 flex justify-between text-sm">
|
||||
<span className="text-slate-500">預覽筆數</span>
|
||||
<span className="font-bold font-mono text-slate-700">
|
||||
{fileState.parsed.row_count} 筆
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{allFilesReady && (
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6 animate-in fade-in slide-in-from-bottom-2 duration-500">
|
||||
<Card className="overflow-hidden">
|
||||
<div className="bg-slate-50 px-4 py-3 border-b border-slate-200 flex justify-between items-center">
|
||||
<h3 className="font-bold text-slate-700 text-sm flex items-center gap-2">
|
||||
<Database size={16} />
|
||||
DIT 解析結果 (預覽)
|
||||
</h3>
|
||||
<Badge type="info">Auto-Skipped Header</Badge>
|
||||
</div>
|
||||
<table className="w-full text-xs text-left">
|
||||
<thead className="bg-white text-slate-500 border-b border-slate-200">
|
||||
<tr>
|
||||
<th className="px-4 py-2">Customer</th>
|
||||
<th className="px-4 py-2">Part No</th>
|
||||
<th className="px-4 py-2">Stage</th>
|
||||
<th className="px-4 py-2 text-right">EAU</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100">
|
||||
{(files.dit.parsed?.preview as unknown as DitRecord[] || []).slice(0, 5).map((row, i) => (
|
||||
<tr key={i} className="hover:bg-slate-50">
|
||||
<td className="px-4 py-2 font-medium text-slate-700">{row.customer}</td>
|
||||
<td className="px-4 py-2 font-mono text-slate-500">{row.pn}</td>
|
||||
<td className="px-4 py-2 text-slate-600">{row.stage}</td>
|
||||
<td className="px-4 py-2 text-right font-mono">{row.eau?.toLocaleString()}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</Card>
|
||||
|
||||
<Card className="overflow-hidden">
|
||||
<div className="bg-slate-50 px-4 py-3 border-b border-slate-200 flex justify-between items-center">
|
||||
<h3 className="font-bold text-slate-700 text-sm flex items-center gap-2">
|
||||
<Database size={16} />
|
||||
訂單解析結果 (預覽)
|
||||
</h3>
|
||||
<Badge type="info">Detected CP950</Badge>
|
||||
</div>
|
||||
<table className="w-full text-xs text-left">
|
||||
<thead className="bg-white text-slate-500 border-b border-slate-200">
|
||||
<tr>
|
||||
<th className="px-4 py-2">Customer</th>
|
||||
<th className="px-4 py-2">Part No</th>
|
||||
<th className="px-4 py-2">Status</th>
|
||||
<th className="px-4 py-2 text-right">Qty</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100">
|
||||
{(files.order.parsed?.preview as unknown as OrderRecord[] || []).slice(0, 5).map((row, i) => (
|
||||
<tr key={i} className="hover:bg-slate-50">
|
||||
<td className="px-4 py-2 font-medium text-slate-700">{row.customer}</td>
|
||||
<td className="px-4 py-2 font-mono text-slate-500">{row.pn}</td>
|
||||
<td className="px-4 py-2">
|
||||
<span className={`px-1.5 py-0.5 rounded text-[10px] ${row.status === 'Shipped' ? 'bg-green-100 text-green-700' : 'bg-pink-100 text-pink-700'
|
||||
}`}>
|
||||
{row.status}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-2 text-right font-mono">{row.qty?.toLocaleString()}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
337
frontend/src/components/LabView.tsx
Normal file
337
frontend/src/components/LabView.tsx
Normal file
@@ -0,0 +1,337 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import {
|
||||
ScatterChart, Scatter, XAxis, YAxis, ZAxis, CartesianGrid, Tooltip as RechartsTooltip,
|
||||
ResponsiveContainer, Label
|
||||
} from 'recharts';
|
||||
import {
|
||||
FlaskConical, Calendar, Clock, Target, AlertTriangle, Copy,
|
||||
Check, TrendingUp, Info, HelpCircle
|
||||
} from 'lucide-react';
|
||||
import { Card } from './common/Card';
|
||||
import { labApi } from '../services/api';
|
||||
import type { LabKPI, ScatterPoint, OrphanSample } from '../types';
|
||||
|
||||
export const LabView: React.FC = () => {
|
||||
const [kpi, setKpi] = useState<LabKPI>({
|
||||
avg_velocity: 0,
|
||||
conversion_rate: 0,
|
||||
orphan_count: 0
|
||||
});
|
||||
const [scatterData, setScatterData] = useState<ScatterPoint[]>([]);
|
||||
const [orphans, setOrphans] = useState<OrphanSample[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [dateRange, setDateRange] = useState<'all' | '12m' | '6m' | '3m'>('all');
|
||||
const [useLogScale, setUseLogScale] = useState(false);
|
||||
const [copiedId, setCopiedId] = useState<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
loadLabData();
|
||||
}, [dateRange]);
|
||||
|
||||
const loadLabData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
let start_date = '';
|
||||
const now = new Date();
|
||||
if (dateRange === '12m') {
|
||||
start_date = new Date(now.setFullYear(now.getFullYear() - 1)).toISOString().split('T')[0];
|
||||
} else if (dateRange === '6m') {
|
||||
start_date = new Date(now.setMonth(now.getMonth() - 6)).toISOString().split('T')[0];
|
||||
} else if (dateRange === '3m') {
|
||||
start_date = new Date(now.setMonth(now.getMonth() - 3)).toISOString().split('T')[0];
|
||||
}
|
||||
|
||||
const params = start_date ? { start_date } : {};
|
||||
|
||||
const [kpiData, scatterRes, orphanRes] = await Promise.all([
|
||||
labApi.getKPI(params),
|
||||
labApi.getScatter(params),
|
||||
labApi.getOrphans()
|
||||
]);
|
||||
|
||||
setKpi(kpiData);
|
||||
setScatterData(scatterRes);
|
||||
setOrphans(orphanRes);
|
||||
} catch (error) {
|
||||
console.error('Error loading lab data:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCopy = (orphan: OrphanSample, index: number) => {
|
||||
const text = `Customer: ${orphan.customer}\nPart No: ${orphan.pn}\nSent Date: ${orphan.date}\nDays Ago: ${orphan.days_since_sent}`;
|
||||
navigator.clipboard.writeText(text);
|
||||
setCopiedId(index);
|
||||
setTimeout(() => setCopiedId(null), 2000);
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-20">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
|
||||
<div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-slate-800 flex items-center gap-2">
|
||||
<FlaskConical className="text-indigo-600" />
|
||||
送樣成效分析戰情室 (Sample Conversion Lab)
|
||||
</h1>
|
||||
<p className="text-slate-500 mt-1">
|
||||
焦點分析:樣品投資報酬率 (ROI) 與 轉換速度 | 邏輯:ERP Code + PN 直接比對
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 bg-white p-1 rounded-lg border border-slate-200 shadow-sm">
|
||||
{(['all', '12m', '6m', '3m'] as const).map((r) => (
|
||||
<button
|
||||
key={r}
|
||||
onClick={() => setDateRange(r)}
|
||||
className={`px-3 py-1.5 text-xs font-bold rounded-md transition-all ${dateRange === r
|
||||
? 'bg-indigo-600 text-white'
|
||||
: 'text-slate-500 hover:bg-slate-50'
|
||||
}`}
|
||||
>
|
||||
{r === 'all' ? '全部時間' : r === '12m' ? '最近 12 個月' : r === '6m' ? '最近 6 個月' : '最近 3 個月'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* KPI Cards */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
<Card className="p-6 border-b-4 border-b-indigo-500 bg-gradient-to-br from-white to-indigo-50/30">
|
||||
<div className="flex justify-between items-start">
|
||||
<div>
|
||||
<div className="text-sm text-slate-500 font-medium mb-1">平均轉換速度</div>
|
||||
<div className="text-3xl font-bold text-slate-800">{kpi.avg_velocity} 天</div>
|
||||
<div className="text-xs text-indigo-600 mt-2 flex items-center gap-1 font-bold">
|
||||
<Clock size={12} />
|
||||
Conversion Velocity
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-3 bg-indigo-100 text-indigo-600 rounded-xl">
|
||||
<TrendingUp size={24} />
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card className="p-6 border-b-4 border-b-emerald-500 bg-gradient-to-br from-white to-emerald-50/30">
|
||||
<div className="flex justify-between items-start">
|
||||
<div>
|
||||
<div className="text-sm text-slate-500 font-medium mb-1">整體轉換倍率 (ROI)</div>
|
||||
<div className="text-3xl font-bold text-slate-800">{kpi.conversion_rate}%</div>
|
||||
<div className="text-xs text-emerald-600 mt-2 flex items-center gap-1 font-bold">
|
||||
<Target size={12} />
|
||||
Sample to Order Ratio
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-3 bg-emerald-100 text-emerald-600 rounded-xl">
|
||||
<FlaskConical size={24} />
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card className="p-6 border-b-4 border-b-rose-500 bg-gradient-to-br from-white to-rose-50/30">
|
||||
<div className="flex justify-between items-start">
|
||||
<div>
|
||||
<div className="text-sm text-slate-500 font-medium mb-1">孤兒樣品總數</div>
|
||||
<div className="text-3xl font-bold text-rose-600">{kpi.orphan_count} 筆</div>
|
||||
<div className="text-xs text-rose-400 mt-2 flex items-center gap-1 font-bold">
|
||||
<AlertTriangle size={12} />
|
||||
Wait-time > 90 Days
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-3 bg-rose-100 text-rose-600 rounded-xl">
|
||||
<AlertTriangle size={24} />
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* Scatter Matrix */}
|
||||
<Card className="lg:col-span-2 p-6 overflow-hidden relative">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h3 className="font-bold text-slate-700 flex items-center gap-2">
|
||||
<FlaskConical size={18} className="text-indigo-500" />
|
||||
送樣量與訂單量分佈矩陣 (Sample ROI Matrix)
|
||||
</h3>
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs text-slate-500 font-medium">Log Scale</label>
|
||||
<button
|
||||
onClick={() => setUseLogScale(!useLogScale)}
|
||||
className={`w-10 h-5 rounded-full transition-colors relative ${useLogScale ? 'bg-indigo-600' : 'bg-slate-200'}`}
|
||||
>
|
||||
<div className={`absolute top-1 w-3 h-3 bg-white rounded-full transition-all ${useLogScale ? 'left-6' : 'left-1'}`} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="h-[400px] w-full">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<ScatterChart margin={{ top: 20, right: 20, bottom: 20, left: 20 }}>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" />
|
||||
<XAxis
|
||||
type="number"
|
||||
dataKey="sample_qty"
|
||||
name="Sample Qty"
|
||||
scale={useLogScale ? "log" : "linear"}
|
||||
domain={useLogScale ? ['auto', 'auto'] : [0, 'auto']}
|
||||
>
|
||||
<Label value="樣品端 (Samples Sent)" offset={-10} position="insideBottom" style={{ fontSize: '12px', fill: '#64748b', fontWeight: 600 }} />
|
||||
</XAxis>
|
||||
<YAxis
|
||||
type="number"
|
||||
dataKey="order_qty"
|
||||
name="Order Qty"
|
||||
scale={useLogScale ? "log" : "linear"}
|
||||
domain={useLogScale ? ['auto', 'auto'] : [0, 'auto']}
|
||||
>
|
||||
<Label value="訂單端 (Orders Received)" angle={-90} position="insideLeft" style={{ fontSize: '12px', fill: '#64748b', fontWeight: 600 }} />
|
||||
</YAxis>
|
||||
<ZAxis type="number" range={[60, 400]} />
|
||||
<RechartsTooltip
|
||||
cursor={{ strokeDasharray: '3 3' }}
|
||||
content={({ active, payload }) => {
|
||||
if (active && payload && payload.length) {
|
||||
const data = payload[0].payload as ScatterPoint;
|
||||
return (
|
||||
<div className="bg-white border border-slate-200 p-3 rounded-lg shadow-xl outline-none ring-0">
|
||||
<p className="font-bold text-slate-800">{data.customer}</p>
|
||||
<p className="text-xs text-indigo-600 font-mono mb-2">{data.pn}</p>
|
||||
<div className="space-y-1 border-t border-slate-100 pt-2">
|
||||
<p className="text-xs flex justify-between gap-4">
|
||||
<span className="text-slate-500">送樣量:</span>
|
||||
<span className="font-bold">{data.sample_qty.toLocaleString()}</span>
|
||||
</p>
|
||||
<p className="text-xs flex justify-between gap-4">
|
||||
<span className="text-slate-500">訂單量:</span>
|
||||
<span className="font-bold text-emerald-600">{data.order_qty.toLocaleString()}</span>
|
||||
</p>
|
||||
<p className="text-[10px] text-slate-400 mt-2 italic">
|
||||
{data.order_qty > data.sample_qty ? '✨ 高效轉換 (High ROI)' : data.order_qty > 0 ? '穩定轉換' : '尚無訂單 (Orphan?)'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}}
|
||||
/>
|
||||
<Scatter
|
||||
name="Projects"
|
||||
data={scatterData}
|
||||
fill="#6366f1"
|
||||
fillOpacity={0.6}
|
||||
stroke="#4338ca"
|
||||
strokeWidth={1}
|
||||
/>
|
||||
</ScatterChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
|
||||
<div className="absolute top-20 right-10 flex flex-col gap-2 text-[10px]">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-2 h-2 rounded-full bg-indigo-500 opacity-60"></div>
|
||||
<span className="text-slate-500">案件資料 (Customer/PN Group)</span>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Insight Card */}
|
||||
<Card className="p-6 bg-slate-900 text-white flex flex-col justify-between">
|
||||
<div>
|
||||
<h3 className="font-bold text-slate-100 mb-4 flex items-center gap-2">
|
||||
<Info size={18} className="text-indigo-400" />
|
||||
戰情室洞察 (Lab Insights)
|
||||
</h3>
|
||||
<div className="space-y-4">
|
||||
<div className="p-3 bg-slate-800/50 rounded-lg border border-slate-700">
|
||||
<p className="text-xs text-slate-400 mb-1">高效轉換客戶</p>
|
||||
<p className="text-sm font-medium">識別散佈圖中「左上角」點位,代表投入少量樣品即獲得大量訂單。</p>
|
||||
</div>
|
||||
<div className="p-3 bg-slate-800/50 rounded-lg border border-slate-700">
|
||||
<p className="text-xs text-slate-400 mb-1">風險警示</p>
|
||||
<p className="text-sm font-medium">右下角點位代表送樣頻繁但轉換效率低,需檢視應用場景或產品適配度。</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-8 p-4 bg-indigo-600/20 rounded-xl border border-indigo-500/30">
|
||||
<p className="text-[11px] text-indigo-300 leading-relaxed italic">
|
||||
"本模組直接比對 ERP 編號,確保不因專案名稱模糊而漏失任何實際營收數據。"
|
||||
</p>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Orphan Samples Table */}
|
||||
<Card className="overflow-hidden">
|
||||
<div className="px-6 py-4 bg-slate-50 border-b border-slate-200 flex justify-between items-center">
|
||||
<h3 className="font-bold text-slate-700 flex items-center gap-2">
|
||||
<AlertTriangle size={18} className="text-rose-500" />
|
||||
Orphan Alert Table - > 90 Days
|
||||
</h3>
|
||||
<div className="text-[10px] text-slate-400 font-medium">
|
||||
共 {orphans.length} 筆待追蹤案件
|
||||
</div>
|
||||
</div>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm text-left">
|
||||
<thead className="bg-white text-slate-500 border-b border-slate-200">
|
||||
<tr>
|
||||
<th className="px-6 py-3">客戶名稱</th>
|
||||
<th className="px-6 py-3">產品料號 (Part No)</th>
|
||||
<th className="px-6 py-3">送樣日期</th>
|
||||
<th className="px-6 py-3 text-center">滯留天數</th>
|
||||
<th className="px-6 py-3 text-center">狀態</th>
|
||||
<th className="px-6 py-3 text-right">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100">
|
||||
{orphans.map((row, i) => (
|
||||
<tr key={i} className="hover:bg-slate-50 transition-colors group">
|
||||
<td className="px-6 py-4 font-medium text-slate-800">{row.customer}</td>
|
||||
<td className="px-6 py-4 font-mono text-xs text-slate-600">{row.pn}</td>
|
||||
<td className="px-6 py-4 text-slate-500">{row.date}</td>
|
||||
<td className="px-6 py-4 text-center">
|
||||
<span className={`font-bold ${row.days_since_sent > 180 ? 'text-rose-600' : 'text-amber-600'}`}>
|
||||
{row.days_since_sent} 天
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 text-center">
|
||||
<span className={`px-2 py-0.5 rounded-full text-[10px] font-bold ${row.days_since_sent > 180 ? 'bg-rose-100 text-rose-700' : 'bg-amber-100 text-amber-700'
|
||||
}`}>
|
||||
{row.days_since_sent > 180 ? '呆滯庫存 (Dead Stock)' : '需採取行動'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 text-right">
|
||||
<button
|
||||
onClick={() => handleCopy(row, i)}
|
||||
className="inline-flex items-center gap-1 text-xs text-indigo-600 hover:text-indigo-800 font-medium bg-indigo-50 px-2 py-1 rounded"
|
||||
>
|
||||
{copiedId === i ? <Check size={12} /> : <Copy size={12} />}
|
||||
{copiedId === i ? '已複製' : '複製詳情'}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{orphans.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={6} className="px-6 py-10 text-center text-slate-400">
|
||||
目前沒有孤兒樣品,所有送樣皆在有效時限內或已轉化。
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
193
frontend/src/components/LoginPage.tsx
Normal file
193
frontend/src/components/LoginPage.tsx
Normal file
@@ -0,0 +1,193 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { LogIn, UserPlus, Mail, Lock, Eye, EyeOff } from 'lucide-react';
|
||||
import { authApi } from '../services/api';
|
||||
import { LanguageSwitch } from './common/LanguageSwitch';
|
||||
|
||||
interface LoginPageProps {
|
||||
onLogin: (token: string) => void;
|
||||
}
|
||||
|
||||
export const LoginPage: React.FC<LoginPageProps> = ({ onLogin }) => {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const [isLogin, setIsLogin] = useState(true);
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
|
||||
if (!email) {
|
||||
setError(t('auth.emailRequired'));
|
||||
return;
|
||||
}
|
||||
if (!password) {
|
||||
setError(t('auth.passwordRequired'));
|
||||
return;
|
||||
}
|
||||
if (!isLogin && password !== confirmPassword) {
|
||||
setError(t('auth.passwordMismatch'));
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
if (isLogin) {
|
||||
const response = await authApi.login({ email, password });
|
||||
localStorage.setItem('token', response.access_token);
|
||||
onLogin(response.access_token);
|
||||
navigate('/');
|
||||
} else {
|
||||
await authApi.register({ email, password });
|
||||
setIsLogin(true);
|
||||
setError('');
|
||||
setPassword('');
|
||||
setConfirmPassword('');
|
||||
}
|
||||
} catch (err: any) {
|
||||
if (isLogin) {
|
||||
setError(t('auth.invalidCredentials'));
|
||||
} else {
|
||||
setError(t('auth.registerFailed'));
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-slate-50 to-indigo-50 flex flex-col">
|
||||
<header className="flex justify-end p-4">
|
||||
<LanguageSwitch />
|
||||
</header>
|
||||
|
||||
<div className="flex-1 flex items-center justify-center px-4">
|
||||
<div className="w-full max-w-md">
|
||||
<div className="bg-white rounded-2xl shadow-xl p-8">
|
||||
<div className="text-center mb-8">
|
||||
<div className="w-16 h-16 bg-indigo-600 rounded-2xl flex items-center justify-center text-white text-2xl font-bold mx-auto mb-4">
|
||||
S
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold text-slate-800">{t('common.appName')}</h1>
|
||||
<p className="text-slate-500 text-sm mt-1">{t('common.appSubtitle')}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex bg-slate-100 rounded-lg p-1 mb-6">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsLogin(true)}
|
||||
className={`flex-1 flex items-center justify-center gap-2 py-2 rounded-md text-sm font-medium transition-all ${
|
||||
isLogin ? 'bg-white text-indigo-600 shadow-sm' : 'text-slate-500'
|
||||
}`}
|
||||
>
|
||||
<LogIn size={16} />
|
||||
{t('auth.login')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsLogin(false)}
|
||||
className={`flex-1 flex items-center justify-center gap-2 py-2 rounded-md text-sm font-medium transition-all ${
|
||||
!isLogin ? 'bg-white text-indigo-600 shadow-sm' : 'text-slate-500'
|
||||
}`}
|
||||
>
|
||||
<UserPlus size={16} />
|
||||
{t('auth.register')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-700 mb-1">
|
||||
{t('auth.email')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" size={18} />
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className="w-full pl-10 pr-4 py-2.5 border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none transition-all"
|
||||
placeholder="your@email.com"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-700 mb-1">
|
||||
{t('auth.password')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" size={18} />
|
||||
<input
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="w-full pl-10 pr-10 py-2.5 border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none transition-all"
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
|
||||
>
|
||||
{showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!isLogin && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-700 mb-1">
|
||||
{t('auth.confirmPassword')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" size={18} />
|
||||
<input
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
className="w-full pl-10 pr-4 py-2.5 border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none transition-all"
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-50 text-red-600 text-sm px-4 py-2 rounded-lg">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="w-full bg-indigo-600 text-white py-2.5 rounded-lg font-medium hover:bg-indigo-700 focus:ring-4 focus:ring-indigo-200 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{loading ? t('common.loading') : isLogin ? t('auth.login') : t('auth.register')}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p className="text-center text-sm text-slate-500 mt-6">
|
||||
{isLogin ? t('auth.noAccount') : t('auth.hasAccount')}{' '}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsLogin(!isLogin)}
|
||||
className="text-indigo-600 hover:text-indigo-700 font-medium"
|
||||
>
|
||||
{isLogin ? t('auth.register') : t('auth.login')}
|
||||
</button>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
157
frontend/src/components/ReviewView.tsx
Normal file
157
frontend/src/components/ReviewView.tsx
Normal file
@@ -0,0 +1,157 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { CheckCircle, XCircle } from 'lucide-react';
|
||||
import { Card, Badge } from './common/Card';
|
||||
import { matchApi } from '../services/api';
|
||||
import type { MatchResult, ReviewAction } from '../types';
|
||||
|
||||
interface ReviewViewProps {
|
||||
onReviewComplete: () => void;
|
||||
}
|
||||
|
||||
export const ReviewView: React.FC<ReviewViewProps> = ({ onReviewComplete }) => {
|
||||
const [reviews, setReviews] = useState<MatchResult[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
loadReviews();
|
||||
}, []);
|
||||
|
||||
const loadReviews = async () => {
|
||||
try {
|
||||
const results = await matchApi.getResults();
|
||||
setReviews(results.filter(r => r.status === 'pending'));
|
||||
} catch (error) {
|
||||
console.error('Error loading reviews:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleReviewAction = async (id: number, action: ReviewAction) => {
|
||||
try {
|
||||
await matchApi.review(id, action);
|
||||
setReviews(prev => prev.filter(r => r.id !== id));
|
||||
|
||||
if (reviews.length === 1) {
|
||||
onReviewComplete();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error submitting review:', error);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-20">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 animate-in fade-in zoom-in-95 duration-300">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-slate-800 flex items-center gap-2">
|
||||
模糊比對審核工作台
|
||||
<span className="text-sm bg-indigo-100 text-indigo-700 px-2 py-1 rounded-full font-normal">
|
||||
待審核: {reviews.length}
|
||||
</span>
|
||||
</h1>
|
||||
<p className="text-slate-500 mt-1">系統發現以下案件名稱相似,請人工確認關聯性。</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{reviews.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-20 bg-white rounded-lg border border-dashed border-slate-300">
|
||||
<div className="w-16 h-16 bg-emerald-100 text-emerald-600 rounded-full flex items-center justify-center mb-4">
|
||||
<CheckCircle size={32} />
|
||||
</div>
|
||||
<h3 className="text-xl font-bold text-slate-800">所有案件已審核完畢!</h3>
|
||||
<p className="text-slate-500 mt-2">您的資料比對已完成,請查看分析儀表板。</p>
|
||||
<button
|
||||
onClick={onReviewComplete}
|
||||
className="mt-6 px-6 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors"
|
||||
>
|
||||
前往儀表板
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-4">
|
||||
{reviews.map(item => (
|
||||
<Card key={item.id} className="p-0 overflow-hidden group hover:shadow-md transition-all border-l-4 border-l-amber-400">
|
||||
<div className="flex flex-col md:flex-row">
|
||||
{/* Left: DIT */}
|
||||
<div className="flex-1 p-5 border-b md:border-b-0 md:border-r border-slate-100 bg-slate-50/50">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Badge type="info">DIT (設計導入)</Badge>
|
||||
<span className="text-xs text-slate-400">OP編號: {item.dit?.op_id}</span>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="text-xs text-slate-400 uppercase">Customer Name</div>
|
||||
<div className="font-bold text-slate-800 text-lg">{item.dit?.customer}</div>
|
||||
<div className="text-xs text-slate-400 uppercase mt-2">Part Number</div>
|
||||
<div className="font-mono text-slate-700 bg-white border border-slate-200 px-2 py-1 rounded inline-block text-sm">
|
||||
{item.dit?.pn}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Middle: Score & Reason */}
|
||||
<div className="w-full md:w-48 p-4 flex flex-col items-center justify-center bg-white z-10">
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-amber-500 mb-1">{item.score}%</div>
|
||||
<div className="text-[10px] font-medium text-amber-600 bg-amber-50 px-2 py-0.5 rounded-full mb-2">
|
||||
相似度
|
||||
</div>
|
||||
<div className="text-xs text-slate-400 text-center px-2 leading-tight">
|
||||
{item.reason}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right: Target (Sample/Order) */}
|
||||
<div className="flex-1 p-5 border-t md:border-t-0 md:border-l border-slate-100 bg-indigo-50/30">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Badge type={item.target_type === 'ORDER' ? 'warning' : 'success'}>
|
||||
{item.target_type === 'ORDER' ? 'Order (訂單)' : 'Sample (樣品)'}
|
||||
</Badge>
|
||||
<span className="text-xs text-slate-400">
|
||||
來源單號: {(item.target as { order_no?: string })?.order_no || 'N/A'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="text-xs text-slate-400 uppercase">Customer Name</div>
|
||||
<div className="font-bold text-slate-800 text-lg">
|
||||
{(item.target as { customer?: string })?.customer}
|
||||
</div>
|
||||
<div className="text-xs text-slate-400 uppercase mt-2">Part Number</div>
|
||||
<div className="font-mono text-slate-700 bg-white border border-slate-200 px-2 py-1 rounded inline-block text-sm">
|
||||
{(item.target as { pn?: string })?.pn}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="w-full md:w-40 p-4 bg-slate-50 flex flex-row md:flex-col gap-3 justify-center items-center border-t md:border-t-0 md:border-l border-slate-200">
|
||||
<button
|
||||
onClick={() => handleReviewAction(item.id, 'accept')}
|
||||
className="flex-1 md:flex-none w-full py-2 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-sm font-medium flex items-center justify-center gap-2 transition-colors shadow-sm"
|
||||
>
|
||||
<CheckCircle size={16} /> 確認關聯
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleReviewAction(item.id, 'reject')}
|
||||
className="flex-1 md:flex-none w-full py-2 bg-white border border-slate-300 text-slate-600 hover:bg-slate-50 rounded-lg text-sm font-medium flex items-center justify-center gap-2 transition-colors"
|
||||
>
|
||||
<XCircle size={16} /> 駁回
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
37
frontend/src/components/common/Card.tsx
Normal file
37
frontend/src/components/common/Card.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import React from 'react';
|
||||
|
||||
interface CardProps {
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
export const Card: React.FC<CardProps> = ({ children, className = "", onClick }) => (
|
||||
<div
|
||||
className={`bg-white rounded-lg border border-slate-200 shadow-sm ${className}`}
|
||||
onClick={onClick}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
interface BadgeProps {
|
||||
children: React.ReactNode;
|
||||
type?: 'neutral' | 'success' | 'warning' | 'danger' | 'info';
|
||||
}
|
||||
|
||||
export const Badge: React.FC<BadgeProps> = ({ children, type = "neutral" }) => {
|
||||
const styles: Record<string, string> = {
|
||||
neutral: "bg-slate-100 text-slate-600",
|
||||
success: "bg-emerald-100 text-emerald-700",
|
||||
warning: "bg-amber-100 text-amber-700",
|
||||
danger: "bg-rose-100 text-rose-700",
|
||||
info: "bg-blue-100 text-blue-700"
|
||||
};
|
||||
|
||||
return (
|
||||
<span className={`px-2 py-1 rounded-full text-xs font-medium ${styles[type]}`}>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
41
frontend/src/components/common/LanguageSwitch.tsx
Normal file
41
frontend/src/components/common/LanguageSwitch.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
import React from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Globe } from 'lucide-react';
|
||||
|
||||
const languages = [
|
||||
{ code: 'zh-TW', label: '繁體中文' },
|
||||
{ code: 'en', label: 'English' },
|
||||
];
|
||||
|
||||
export const LanguageSwitch: React.FC = () => {
|
||||
const { i18n } = useTranslation();
|
||||
|
||||
const handleLanguageChange = (langCode: string) => {
|
||||
i18n.changeLanguage(langCode);
|
||||
localStorage.setItem('language', langCode);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative group">
|
||||
<button className="flex items-center gap-2 px-3 py-2 text-sm text-slate-600 hover:text-slate-800 hover:bg-slate-100 rounded-lg transition-colors">
|
||||
<Globe size={16} />
|
||||
<span className="hidden sm:inline">
|
||||
{languages.find(l => l.code === i18n.language)?.label || '繁體中文'}
|
||||
</span>
|
||||
</button>
|
||||
<div className="absolute right-0 mt-1 w-40 bg-white rounded-lg shadow-lg border border-slate-200 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all z-50">
|
||||
{languages.map((lang) => (
|
||||
<button
|
||||
key={lang.code}
|
||||
onClick={() => handleLanguageChange(lang.code)}
|
||||
className={`w-full text-left px-4 py-2 text-sm hover:bg-slate-100 first:rounded-t-lg last:rounded-b-lg transition-colors ${
|
||||
i18n.language === lang.code ? 'text-indigo-600 font-medium bg-indigo-50' : 'text-slate-700'
|
||||
}`}
|
||||
>
|
||||
{lang.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
69
frontend/src/hooks/useAuth.ts
Normal file
69
frontend/src/hooks/useAuth.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { authApi } from '../services/api';
|
||||
import type { User, LoginRequest } from '../types';
|
||||
|
||||
export function useAuth() {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const checkAuth = useCallback(async () => {
|
||||
const token = localStorage.getItem('token');
|
||||
if (!token) {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const userData = await authApi.me();
|
||||
setUser(userData);
|
||||
} catch {
|
||||
localStorage.removeItem('token');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
checkAuth();
|
||||
}, [checkAuth]);
|
||||
|
||||
const login = async (data: LoginRequest) => {
|
||||
setError(null);
|
||||
try {
|
||||
const response = await authApi.login(data);
|
||||
localStorage.setItem('token', response.access_token);
|
||||
setUser(response.user);
|
||||
return true;
|
||||
} catch (err) {
|
||||
setError('登入失敗,請檢查帳號密碼');
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const register = async (data: LoginRequest) => {
|
||||
setError(null);
|
||||
try {
|
||||
await authApi.register(data);
|
||||
return await login(data);
|
||||
} catch (err) {
|
||||
setError('註冊失敗,該 Email 可能已被使用');
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
localStorage.removeItem('token');
|
||||
setUser(null);
|
||||
};
|
||||
|
||||
return {
|
||||
user,
|
||||
loading,
|
||||
error,
|
||||
isAuthenticated: !!user,
|
||||
login,
|
||||
register,
|
||||
logout,
|
||||
};
|
||||
}
|
||||
30
frontend/src/i18n/index.ts
Normal file
30
frontend/src/i18n/index.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import i18n from 'i18next';
|
||||
import { initReactI18next } from 'react-i18next';
|
||||
import LanguageDetector from 'i18next-browser-languagedetector';
|
||||
|
||||
import zhTW from './locales/zh-TW.json';
|
||||
import en from './locales/en.json';
|
||||
|
||||
const resources = {
|
||||
'zh-TW': { translation: zhTW },
|
||||
'en': { translation: en },
|
||||
};
|
||||
|
||||
i18n
|
||||
.use(LanguageDetector)
|
||||
.use(initReactI18next)
|
||||
.init({
|
||||
resources,
|
||||
fallbackLng: 'zh-TW',
|
||||
defaultNS: 'translation',
|
||||
detection: {
|
||||
order: ['localStorage', 'navigator', 'htmlTag'],
|
||||
caches: ['localStorage'],
|
||||
lookupLocalStorage: 'language',
|
||||
},
|
||||
interpolation: {
|
||||
escapeValue: false,
|
||||
},
|
||||
});
|
||||
|
||||
export default i18n;
|
||||
140
frontend/src/i18n/locales/en.json
Normal file
140
frontend/src/i18n/locales/en.json
Normal file
@@ -0,0 +1,140 @@
|
||||
{
|
||||
"common": {
|
||||
"appName": "SalesPipeline",
|
||||
"appSubtitle": "Sales Pipeline Management System",
|
||||
"systemRunning": "System Running",
|
||||
"loading": "Loading...",
|
||||
"save": "Save",
|
||||
"cancel": "Cancel",
|
||||
"confirm": "Confirm",
|
||||
"delete": "Delete",
|
||||
"edit": "Edit",
|
||||
"search": "Search",
|
||||
"filter": "Filter",
|
||||
"export": "Export",
|
||||
"import": "Import",
|
||||
"refresh": "Refresh",
|
||||
"back": "Back",
|
||||
"next": "Next",
|
||||
"previous": "Previous",
|
||||
"submit": "Submit",
|
||||
"reset": "Reset",
|
||||
"close": "Close",
|
||||
"yes": "Yes",
|
||||
"no": "No",
|
||||
"success": "Success",
|
||||
"error": "Error",
|
||||
"warning": "Warning",
|
||||
"info": "Info"
|
||||
},
|
||||
"nav": {
|
||||
"import": "Data Import",
|
||||
"review": "Match Review",
|
||||
"dashboard": "Dashboard",
|
||||
"lab": "Sample Conversion Lab",
|
||||
"settings": "Settings",
|
||||
"logout": "Logout"
|
||||
},
|
||||
"auth": {
|
||||
"login": "Login",
|
||||
"register": "Register",
|
||||
"email": "Email",
|
||||
"password": "Password",
|
||||
"confirmPassword": "Confirm Password",
|
||||
"rememberMe": "Remember me",
|
||||
"forgotPassword": "Forgot password?",
|
||||
"noAccount": "Don't have an account?",
|
||||
"hasAccount": "Already have an account?",
|
||||
"loginSuccess": "Login successful",
|
||||
"loginFailed": "Login failed",
|
||||
"registerSuccess": "Registration successful",
|
||||
"registerFailed": "Registration failed",
|
||||
"invalidCredentials": "Invalid email or password",
|
||||
"emailRequired": "Email is required",
|
||||
"passwordRequired": "Password is required",
|
||||
"passwordMismatch": "Passwords do not match"
|
||||
},
|
||||
"import": {
|
||||
"title": "Data Import",
|
||||
"subtitle": "Upload Excel files to import DIT, Sample, and Order data",
|
||||
"ditFile": "DIT File",
|
||||
"sampleFile": "Sample File",
|
||||
"orderFile": "Order File",
|
||||
"selectFile": "Select File",
|
||||
"dragDrop": "or drag and drop here",
|
||||
"supportedFormats": "Supported formats: xlsx, xls",
|
||||
"uploading": "Uploading...",
|
||||
"parsing": "Parsing...",
|
||||
"importing": "Importing...",
|
||||
"uploadSuccess": "Upload successful",
|
||||
"uploadFailed": "Upload failed",
|
||||
"importSuccess": "Import successful",
|
||||
"importFailed": "Import failed",
|
||||
"recordsImported": "{{count}} records imported",
|
||||
"preview": "Preview",
|
||||
"startImport": "Start Import",
|
||||
"clearAll": "Clear All"
|
||||
},
|
||||
"review": {
|
||||
"title": "Match Review",
|
||||
"subtitle": "Review automatically matched results",
|
||||
"pendingReview": "Pending Review",
|
||||
"accepted": "Accepted",
|
||||
"rejected": "Rejected",
|
||||
"autoMatched": "Auto Matched",
|
||||
"similarity": "Similarity",
|
||||
"matchReason": "Match Reason",
|
||||
"ditRecord": "DIT Record",
|
||||
"matchedRecord": "Matched Record",
|
||||
"accept": "Accept",
|
||||
"reject": "Reject",
|
||||
"acceptAll": "Accept All",
|
||||
"rejectAll": "Reject All",
|
||||
"noRecords": "No records pending review",
|
||||
"reviewComplete": "Review Complete",
|
||||
"reviewSuccess": "Review successful",
|
||||
"reviewFailed": "Review failed"
|
||||
},
|
||||
"dashboard": {
|
||||
"title": "Analytics Dashboard",
|
||||
"subtitle": "Sales Pipeline Overview & Analysis",
|
||||
"totalDit": "Total DIT",
|
||||
"matchedSamples": "Matched Samples",
|
||||
"matchedOrders": "Matched Orders",
|
||||
"conversionRate": "Conversion Rate",
|
||||
"totalRevenue": "Total Revenue",
|
||||
"conversionFunnel": "Conversion Funnel",
|
||||
"attribution": "DIT Attribution",
|
||||
"exportExcel": "Export Excel",
|
||||
"exportPdf": "Export PDF",
|
||||
"customer": "Customer",
|
||||
"partNumber": "Part Number",
|
||||
"stage": "Stage",
|
||||
"eau": "EAU",
|
||||
"sample": "Sample",
|
||||
"order": "Order",
|
||||
"amount": "Amount"
|
||||
},
|
||||
"settings": {
|
||||
"title": "Settings",
|
||||
"language": "Language",
|
||||
"theme": "Theme",
|
||||
"darkMode": "Dark Mode",
|
||||
"lightMode": "Light Mode",
|
||||
"profile": "Profile",
|
||||
"displayName": "Display Name",
|
||||
"changePassword": "Change Password",
|
||||
"currentPassword": "Current Password",
|
||||
"newPassword": "New Password",
|
||||
"saveChanges": "Save Changes"
|
||||
},
|
||||
"errors": {
|
||||
"networkError": "Network connection error",
|
||||
"serverError": "Server error",
|
||||
"unauthorized": "Unauthorized, please login again",
|
||||
"forbidden": "No permission to perform this action",
|
||||
"notFound": "Resource not found",
|
||||
"validationError": "Validation error",
|
||||
"unknownError": "Unknown error occurred"
|
||||
}
|
||||
}
|
||||
140
frontend/src/i18n/locales/zh-TW.json
Normal file
140
frontend/src/i18n/locales/zh-TW.json
Normal file
@@ -0,0 +1,140 @@
|
||||
{
|
||||
"common": {
|
||||
"appName": "SalesPipeline",
|
||||
"appSubtitle": "銷售管線管理系統",
|
||||
"systemRunning": "系統運作中",
|
||||
"loading": "載入中...",
|
||||
"save": "儲存",
|
||||
"cancel": "取消",
|
||||
"confirm": "確認",
|
||||
"delete": "刪除",
|
||||
"edit": "編輯",
|
||||
"search": "搜尋",
|
||||
"filter": "篩選",
|
||||
"export": "匯出",
|
||||
"import": "匯入",
|
||||
"refresh": "重新整理",
|
||||
"back": "返回",
|
||||
"next": "下一步",
|
||||
"previous": "上一步",
|
||||
"submit": "提交",
|
||||
"reset": "重置",
|
||||
"close": "關閉",
|
||||
"yes": "是",
|
||||
"no": "否",
|
||||
"success": "成功",
|
||||
"error": "錯誤",
|
||||
"warning": "警告",
|
||||
"info": "資訊"
|
||||
},
|
||||
"nav": {
|
||||
"import": "資料匯入",
|
||||
"review": "比對審核",
|
||||
"dashboard": "分析儀表板",
|
||||
"lab": "送樣成效分析",
|
||||
"settings": "設定",
|
||||
"logout": "登出"
|
||||
},
|
||||
"auth": {
|
||||
"login": "登入",
|
||||
"register": "註冊",
|
||||
"email": "電子郵件",
|
||||
"password": "密碼",
|
||||
"confirmPassword": "確認密碼",
|
||||
"rememberMe": "記住我",
|
||||
"forgotPassword": "忘記密碼?",
|
||||
"noAccount": "還沒有帳號?",
|
||||
"hasAccount": "已有帳號?",
|
||||
"loginSuccess": "登入成功",
|
||||
"loginFailed": "登入失敗",
|
||||
"registerSuccess": "註冊成功",
|
||||
"registerFailed": "註冊失敗",
|
||||
"invalidCredentials": "帳號或密碼錯誤",
|
||||
"emailRequired": "請輸入電子郵件",
|
||||
"passwordRequired": "請輸入密碼",
|
||||
"passwordMismatch": "密碼不一致"
|
||||
},
|
||||
"import": {
|
||||
"title": "資料匯入",
|
||||
"subtitle": "上傳 Excel 檔案以匯入 DIT、樣品和訂單資料",
|
||||
"ditFile": "DIT 檔案",
|
||||
"sampleFile": "樣品檔案",
|
||||
"orderFile": "訂單檔案",
|
||||
"selectFile": "選擇檔案",
|
||||
"dragDrop": "或拖放檔案至此",
|
||||
"supportedFormats": "支援格式:xlsx, xls",
|
||||
"uploading": "上傳中...",
|
||||
"parsing": "解析中...",
|
||||
"importing": "匯入中...",
|
||||
"uploadSuccess": "上傳成功",
|
||||
"uploadFailed": "上傳失敗",
|
||||
"importSuccess": "匯入成功",
|
||||
"importFailed": "匯入失敗",
|
||||
"recordsImported": "已匯入 {{count}} 筆資料",
|
||||
"preview": "預覽",
|
||||
"startImport": "開始匯入",
|
||||
"clearAll": "清除全部"
|
||||
},
|
||||
"review": {
|
||||
"title": "比對審核",
|
||||
"subtitle": "審核系統自動比對的結果",
|
||||
"pendingReview": "待審核",
|
||||
"accepted": "已接受",
|
||||
"rejected": "已拒絕",
|
||||
"autoMatched": "自動配對",
|
||||
"similarity": "相似度",
|
||||
"matchReason": "配對原因",
|
||||
"ditRecord": "DIT 記錄",
|
||||
"matchedRecord": "配對記錄",
|
||||
"accept": "接受",
|
||||
"reject": "拒絕",
|
||||
"acceptAll": "全部接受",
|
||||
"rejectAll": "全部拒絕",
|
||||
"noRecords": "沒有待審核的記錄",
|
||||
"reviewComplete": "審核完成",
|
||||
"reviewSuccess": "審核成功",
|
||||
"reviewFailed": "審核失敗"
|
||||
},
|
||||
"dashboard": {
|
||||
"title": "分析儀表板",
|
||||
"subtitle": "銷售管線總覽與分析",
|
||||
"totalDit": "DIT 總數",
|
||||
"matchedSamples": "配對樣品數",
|
||||
"matchedOrders": "配對訂單數",
|
||||
"conversionRate": "轉換率",
|
||||
"totalRevenue": "總營收",
|
||||
"conversionFunnel": "轉換漏斗",
|
||||
"attribution": "DIT 歸因表",
|
||||
"exportExcel": "匯出 Excel",
|
||||
"exportPdf": "匯出 PDF",
|
||||
"customer": "客戶",
|
||||
"partNumber": "料號",
|
||||
"stage": "階段",
|
||||
"eau": "EAU",
|
||||
"sample": "樣品",
|
||||
"order": "訂單",
|
||||
"amount": "金額"
|
||||
},
|
||||
"settings": {
|
||||
"title": "設定",
|
||||
"language": "語言",
|
||||
"theme": "主題",
|
||||
"darkMode": "深色模式",
|
||||
"lightMode": "淺色模式",
|
||||
"profile": "個人資料",
|
||||
"displayName": "顯示名稱",
|
||||
"changePassword": "變更密碼",
|
||||
"currentPassword": "目前密碼",
|
||||
"newPassword": "新密碼",
|
||||
"saveChanges": "儲存變更"
|
||||
},
|
||||
"errors": {
|
||||
"networkError": "網路連線錯誤",
|
||||
"serverError": "伺服器錯誤",
|
||||
"unauthorized": "未經授權,請重新登入",
|
||||
"forbidden": "無權限執行此操作",
|
||||
"notFound": "找不到資源",
|
||||
"validationError": "資料驗證錯誤",
|
||||
"unknownError": "發生未知錯誤"
|
||||
}
|
||||
}
|
||||
57
frontend/src/index.css
Normal file
57
frontend/src/index.css
Normal file
@@ -0,0 +1,57 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@keyframes fade-in {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
|
||||
@keyframes slide-in-from-bottom-4 {
|
||||
from { transform: translateY(1rem); opacity: 0; }
|
||||
to { transform: translateY(0); opacity: 1; }
|
||||
}
|
||||
|
||||
@keyframes slide-in-from-right-4 {
|
||||
from { transform: translateX(1rem); opacity: 0; }
|
||||
to { transform: translateX(0); opacity: 1; }
|
||||
}
|
||||
|
||||
@keyframes zoom-in-95 {
|
||||
from { transform: scale(0.95); opacity: 0; }
|
||||
to { transform: scale(1); opacity: 1; }
|
||||
}
|
||||
|
||||
.animate-in {
|
||||
animation-duration: 0.5s;
|
||||
animation-fill-mode: both;
|
||||
}
|
||||
|
||||
.fade-in {
|
||||
animation-name: fade-in;
|
||||
}
|
||||
|
||||
.slide-in-from-bottom-4 {
|
||||
animation-name: slide-in-from-bottom-4;
|
||||
}
|
||||
|
||||
.slide-in-from-bottom-2 {
|
||||
animation-name: slide-in-from-bottom-4;
|
||||
animation-duration: 0.3s;
|
||||
}
|
||||
|
||||
.slide-in-from-right-4 {
|
||||
animation-name: slide-in-from-right-4;
|
||||
}
|
||||
|
||||
.zoom-in-95 {
|
||||
animation-name: zoom-in-95;
|
||||
}
|
||||
|
||||
.duration-500 {
|
||||
animation-duration: 0.5s;
|
||||
}
|
||||
|
||||
.duration-300 {
|
||||
animation-duration: 0.3s;
|
||||
}
|
||||
26
frontend/src/main.tsx
Normal file
26
frontend/src/main.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import App from './App'
|
||||
import './i18n'
|
||||
import './index.css'
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 1000 * 60 * 5,
|
||||
retry: 1,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
</React.StrictMode>,
|
||||
)
|
||||
173
frontend/src/services/api.ts
Normal file
173
frontend/src/services/api.ts
Normal file
@@ -0,0 +1,173 @@
|
||||
import axios from 'axios';
|
||||
import type {
|
||||
LoginRequest,
|
||||
LoginResponse,
|
||||
User,
|
||||
MatchResult,
|
||||
DashboardKPI,
|
||||
ParsedFile,
|
||||
ReviewAction,
|
||||
DitRecord,
|
||||
SampleRecord,
|
||||
OrderRecord,
|
||||
LabKPI,
|
||||
ScatterPoint,
|
||||
OrphanSample
|
||||
} from '../types';
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: '/api',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
// 請求攔截器:加入 JWT Token
|
||||
api.interceptors.request.use((config) => {
|
||||
const token = localStorage.getItem('token');
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
// 響應攔截器:處理 401 錯誤
|
||||
api.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error) => {
|
||||
// 只有在非登入/驗證相關的 API 返回 401 時才跳轉
|
||||
const isAuthEndpoint = error.config?.url?.includes('/auth/');
|
||||
if (error.response?.status === 401 && !isAuthEndpoint) {
|
||||
localStorage.removeItem('token');
|
||||
window.location.href = '/login';
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
// Auth API
|
||||
export const authApi = {
|
||||
login: async (data: LoginRequest): Promise<LoginResponse> => {
|
||||
const formData = new URLSearchParams();
|
||||
formData.append('username', data.email);
|
||||
formData.append('password', data.password);
|
||||
|
||||
const response = await api.post<LoginResponse>('/auth/login', formData, {
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
});
|
||||
return response.data;
|
||||
},
|
||||
|
||||
register: async (data: LoginRequest): Promise<User> => {
|
||||
const response = await api.post<User>('/auth/register', data);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
me: async (): Promise<User> => {
|
||||
const response = await api.get<User>('/auth/me');
|
||||
return response.data;
|
||||
},
|
||||
};
|
||||
|
||||
// ETL API
|
||||
export const etlApi = {
|
||||
upload: async (file: File, fileType: 'dit' | 'sample' | 'order'): Promise<ParsedFile> => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('file_type', fileType);
|
||||
const response = await api.post<ParsedFile>('/etl/upload', formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
});
|
||||
return response.data;
|
||||
},
|
||||
|
||||
preview: async (fileId: string): Promise<ParsedFile> => {
|
||||
const response = await api.get<ParsedFile>(`/etl/preview/${fileId}`);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
import: async (fileId: string): Promise<{ imported_count: number }> => {
|
||||
const response = await api.post<{ imported_count: number }>('/etl/import', { file_id: fileId });
|
||||
return response.data;
|
||||
},
|
||||
|
||||
getData: async (type: 'dit' | 'sample' | 'order'): Promise<(DitRecord | SampleRecord | OrderRecord)[]> => {
|
||||
const response = await api.get(`/etl/data/${type}`);
|
||||
return response.data;
|
||||
},
|
||||
};
|
||||
|
||||
// Match API
|
||||
export const matchApi = {
|
||||
run: async (): Promise<{ match_count: number; auto_matched: number; pending_review: number }> => {
|
||||
const response = await api.post('/match/run');
|
||||
return response.data;
|
||||
},
|
||||
|
||||
getResults: async (): Promise<MatchResult[]> => {
|
||||
const response = await api.get<MatchResult[]>('/match/results');
|
||||
return response.data;
|
||||
},
|
||||
|
||||
review: async (id: number, action: ReviewAction): Promise<MatchResult> => {
|
||||
const response = await api.put<MatchResult>(`/match/${id}/review`, { action });
|
||||
return response.data;
|
||||
},
|
||||
};
|
||||
|
||||
// Dashboard API
|
||||
export const dashboardApi = {
|
||||
getKPI: async (): Promise<DashboardKPI> => {
|
||||
const response = await api.get<DashboardKPI>('/dashboard/kpi');
|
||||
return response.data;
|
||||
},
|
||||
|
||||
getFunnel: async () => {
|
||||
const response = await api.get('/dashboard/funnel');
|
||||
return response.data;
|
||||
},
|
||||
|
||||
getAttribution: async () => {
|
||||
const response = await api.get('/dashboard/attribution');
|
||||
return response.data;
|
||||
},
|
||||
};
|
||||
|
||||
// Report API
|
||||
export const reportApi = {
|
||||
exportExcel: async (): Promise<Blob> => {
|
||||
const response = await api.get('/report/export', {
|
||||
params: { format: 'xlsx' },
|
||||
responseType: 'blob',
|
||||
});
|
||||
return response.data;
|
||||
},
|
||||
|
||||
exportPdf: async (): Promise<Blob> => {
|
||||
const response = await api.get('/report/export', {
|
||||
params: { format: 'pdf' },
|
||||
responseType: 'blob',
|
||||
});
|
||||
return response.data;
|
||||
},
|
||||
};
|
||||
|
||||
// Lab API
|
||||
export const labApi = {
|
||||
getKPI: async (params?: { start_date?: string; end_date?: string }): Promise<LabKPI> => {
|
||||
const response = await api.get<LabKPI>('/lab/kpi', { params });
|
||||
return response.data;
|
||||
},
|
||||
|
||||
getScatter: async (params?: { start_date?: string; end_date?: string }): Promise<ScatterPoint[]> => {
|
||||
const response = await api.get<ScatterPoint[]>('/lab/scatter', { params });
|
||||
return response.data;
|
||||
},
|
||||
|
||||
getOrphans: async (): Promise<OrphanSample[]> => {
|
||||
const response = await api.get<OrphanSample[]>('/lab/orphans');
|
||||
return response.data;
|
||||
},
|
||||
};
|
||||
|
||||
export default api;
|
||||
146
frontend/src/types/index.ts
Normal file
146
frontend/src/types/index.ts
Normal file
@@ -0,0 +1,146 @@
|
||||
// 使用者相關類型
|
||||
export interface User {
|
||||
id: number;
|
||||
email: string;
|
||||
display_name?: string;
|
||||
language: string;
|
||||
role: 'admin' | 'user';
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface LoginRequest {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
access_token: string;
|
||||
token_type: string;
|
||||
user: User;
|
||||
}
|
||||
|
||||
// DIT 資料類型
|
||||
export interface DitRecord {
|
||||
id: number;
|
||||
op_id: string;
|
||||
erp_account?: string;
|
||||
customer: string;
|
||||
pn: string;
|
||||
eau: number;
|
||||
stage: string;
|
||||
date: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
// 樣品資料類型
|
||||
export interface SampleRecord {
|
||||
id: number;
|
||||
sample_id: string;
|
||||
order_no: string;
|
||||
oppy_no?: string;
|
||||
cust_id?: string;
|
||||
customer: string;
|
||||
pn: string;
|
||||
qty: number;
|
||||
date: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
// 訂單資料類型
|
||||
export interface OrderRecord {
|
||||
id: number;
|
||||
order_id: string;
|
||||
order_no: string;
|
||||
cust_id?: string;
|
||||
customer: string;
|
||||
pn: string;
|
||||
qty: number;
|
||||
status: string;
|
||||
amount: number;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
// 比對結果類型
|
||||
export interface MatchResult {
|
||||
id: number;
|
||||
dit_id: number;
|
||||
target_type: 'SAMPLE' | 'ORDER';
|
||||
target_id: number;
|
||||
score: number;
|
||||
match_priority: number;
|
||||
match_source: string;
|
||||
reason: string;
|
||||
status: 'pending' | 'accepted' | 'rejected' | 'auto_matched';
|
||||
dit: DitRecord;
|
||||
target: SampleRecord | OrderRecord;
|
||||
}
|
||||
|
||||
// 審核動作
|
||||
export type ReviewAction = 'accept' | 'reject';
|
||||
|
||||
// Dashboard KPI
|
||||
export interface DashboardKPI {
|
||||
total_dit: number;
|
||||
sample_rate: number;
|
||||
hit_rate: number;
|
||||
fulfillment_rate: number;
|
||||
orphan_sample_rate: number;
|
||||
total_revenue: number;
|
||||
}
|
||||
|
||||
// 漏斗數據
|
||||
export interface FunnelData {
|
||||
name: string;
|
||||
value: number;
|
||||
fill: string;
|
||||
}
|
||||
|
||||
// 歸因明細
|
||||
export interface AttributionRow {
|
||||
dit: DitRecord;
|
||||
sample?: SampleRecord;
|
||||
order?: OrderRecord;
|
||||
match_source?: string;
|
||||
attributed_qty: number;
|
||||
fulfillment_rate: number;
|
||||
}
|
||||
|
||||
// Excel 上傳預覽
|
||||
export interface ParsedFile {
|
||||
file_id: string;
|
||||
file_type: 'dit' | 'sample' | 'order';
|
||||
filename: string;
|
||||
row_count: number;
|
||||
header_row: number;
|
||||
preview: Record<string, unknown>[];
|
||||
}
|
||||
|
||||
// Lab 分析相關類型
|
||||
export interface LabKPI {
|
||||
avg_velocity: number;
|
||||
conversion_rate: number;
|
||||
orphan_count: number;
|
||||
}
|
||||
|
||||
export interface ScatterPoint {
|
||||
customer: string;
|
||||
pn: string;
|
||||
sample_qty: number;
|
||||
order_qty: number;
|
||||
}
|
||||
|
||||
export interface OrphanSample {
|
||||
customer: string;
|
||||
pn: string;
|
||||
days_since_sent: number;
|
||||
order_no: string;
|
||||
date: string;
|
||||
}
|
||||
|
||||
// API 響應包裝
|
||||
export interface ApiResponse<T> {
|
||||
success: boolean;
|
||||
data?: T;
|
||||
message?: string;
|
||||
error?: string;
|
||||
}
|
||||
Reference in New Issue
Block a user