Files
Ydisks-Xianyu-Helper/frontend/App.tsx
Christ 6032dfed0f feat: 支持通过管理页面完成首次初始化
初始化流程:

- 新增一次性 POST /initialize 接口,仅在系统尚未存在管理员时允许创建账号。

- 校验管理员密码不少于 8 个字符,初始化成功后自动建立会话并登录。

- 增加初始化并发保护,避免首次打开多个页面时互相覆盖密码。

前端与资源:

- 将初始化页面改为密码和确认密码表单,移除普通用户需要执行的 CLI 命令和数据库路径提示。

- 初始化成功后直接进入管理后台,并重新构建嵌入式前端资源。

- 增加未初始化接口回归测试和自动登录验证。

文档同步:

- 更新 README、文档站、GitHub Wiki、前端说明和 AGENTS.md。

- 明确 Docker 使用 XIANYU_ADMIN_PASSWORD 非交互初始化。

- 明确独立二进制和 Linux 安装包通过 Web 页面初始化,CLI 仅作为无浏览器或运维备用方式。

- 同步桌面端 Chromium runtime 内置、Linux 安装流程和 Windows/macOS 签名包说明。
2026-08-12 03:04:28 +08:00

373 lines
15 KiB
TypeScript

import React, { useState, useEffect } from 'react';
import Sidebar from './components/Sidebar';
import Dashboard from './components/Dashboard';
import AccountList from './components/AccountList';
import OrderList from './components/OrderList';
import CardList from './components/CardList';
import ItemList from './components/ItemList';
import Settings from './components/Settings';
import Rules from './components/Rules';
import Notifications from './components/Notifications';
import Chat from './components/Chat';
import { readSidebarCollapsed, writeSidebarCollapsed } from './components/sidebarState';
import { YdisksBrandIcon } from './components/YdisksLogo';
import { initializeAdmin, login, logout, verifySession } from './services/api';
import { ShieldCheck, ArrowRight, Loader2, User, Lock } from 'lucide-react';
interface DeliveryRuleTarget {
cookieId: string;
itemId: string;
requestId: number;
}
// 路由:URL path ↔ tab id。所有 SPA 路由统一挂 /app/ 前缀,避免和后端 API
// 路径(/orders、/cards、/items 等)冲突——后者在 chi 里先注册,刷新会直接
// 返回 JSON 而不是 SPA 页面。
const ROUTES: Record<string, string> = {
'/app/dashboard': 'dashboard',
'/app/accounts': 'accounts',
'/app/chat': 'chat',
'/app/orders': 'orders',
'/app/cards': 'cards',
'/app/items': 'items',
'/app/rules': 'rules',
'/app/notifications': 'notifications',
'/app/settings': 'settings',
};
const TAB_TO_PATH: Record<string, string> = Object.fromEntries(
Object.entries(ROUTES).map(([path, tab]) => [tab, path])
);
const tabFromPath = (): string => ROUTES[window.location.pathname] || 'dashboard';
const App: React.FC = () => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [isAdmin, setIsAdmin] = useState(false);
const [activeTab, setActiveTab] = useState(tabFromPath);
const [checkingAuth, setCheckingAuth] = useState(true);
const [needsInit, setNeedsInit] = useState(false);
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [loginLoading, setLoginLoading] = useState(false);
const [loginError, setLoginError] = useState('');
const [initialPassword, setInitialPassword] = useState('');
const [initialPasswordConfirm, setInitialPasswordConfirm] = useState('');
const [initializing, setInitializing] = useState(false);
const [initializationError, setInitializationError] = useState('');
const [deliveryRuleTarget, setDeliveryRuleTarget] = useState<DeliveryRuleTarget | undefined>();
const [sidebarCollapsed, setSidebarCollapsed] = useState(readSidebarCollapsed);
// 切换 tab 并同步 URL。若 tab 没有对应 path(不应发生)则只切 tab。
const navigate = (tab: string) => {
const nextTab = tab === 'settings' && !isAdmin ? 'dashboard' : tab;
const path = TAB_TO_PATH[nextTab];
if (path && path !== window.location.pathname) {
window.history.pushState({}, '', path);
}
setActiveTab(nextTab);
};
// 浏览器后退/前进同步 tab。
useEffect(() => {
const onPopState = () => setActiveTab(tabFromPath());
window.addEventListener('popstate', onPopState);
return () => window.removeEventListener('popstate', onPopState);
}, []);
// Check auth on mount
useEffect(() => {
verifySession()
.then((res) => {
if (res?.initialized === false) {
setNeedsInit(true);
setIsLoggedIn(false);
setIsAdmin(false);
return;
}
setNeedsInit(false);
if (res?.authenticated) {
setIsLoggedIn(true);
setIsAdmin(res.is_admin === true);
} else {
setIsAdmin(false);
}
})
.catch(() => {
setIsLoggedIn(false);
setIsAdmin(false);
})
.finally(() => setCheckingAuth(false));
const handleAuthLogoutEvent = () => {
setIsLoggedIn(false);
setIsAdmin(false);
};
window.addEventListener('auth:logout', handleAuthLogoutEvent);
return () => window.removeEventListener('auth:logout', handleAuthLogoutEvent);
}, []);
useEffect(() => {
if (!checkingAuth && isLoggedIn && !isAdmin && activeTab === 'settings') {
window.history.replaceState({}, '', TAB_TO_PATH.dashboard);
setActiveTab('dashboard');
}
}, [checkingAuth, isLoggedIn, isAdmin, activeTab]);
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
setLoginLoading(true);
setLoginError('');
try {
const res = await login({ username, password });
if (res.success) {
setIsLoggedIn(true);
setIsAdmin(res.is_admin === true);
} else {
setLoginError(res.message || '登录失败');
}
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
setLoginError(msg || '登录失败');
} finally {
setLoginLoading(false);
}
};
const handleInitialize = async (e: React.FormEvent) => {
e.preventDefault();
setInitializationError('');
if (initialPassword.length < 8) {
setInitializationError('密码至少需要 8 个字符');
return;
}
if (initialPassword !== initialPasswordConfirm) {
setInitializationError('两次输入的密码不一致');
return;
}
setInitializing(true);
try {
const res = await initializeAdmin(initialPassword);
if (!res.success) {
setInitializationError(res.message || '初始化失败,请重试');
return;
}
setNeedsInit(false);
setIsLoggedIn(true);
setIsAdmin(res.is_admin === true);
setInitialPassword('');
setInitialPasswordConfirm('');
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
setInitializationError(msg || '初始化失败,请重试');
} finally {
setInitializing(false);
}
};
const handleLogout = async () => {
try {
await logout();
} catch (err) {
console.error('退出登录失败', err);
} finally {
setIsLoggedIn(false);
setIsAdmin(false);
}
};
if (checkingAuth) {
return (
<div className="min-h-screen flex items-center justify-center bg-surface">
<Loader2 className="w-8 h-8 text-brand animate-spin" />
</div>
);
}
// Init Screen (system not initialized)
if (needsInit) {
return (
<div className="min-h-screen flex items-center justify-center bg-canvas p-4 relative overflow-hidden font-sans">
<div className="absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"></div>
<div className="absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse" style={{animationDelay: '2s'}}></div>
<div className="bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-panel w-full max-w-xl border border-white relative z-10 animate-fade-in">
<div className="text-center mb-8">
<div className="mx-auto mb-6 flex justify-center">
<YdisksBrandIcon sizeClass="w-24 h-24" />
</div>
<h2 className="text-3xl font-extrabold text-gray-900 mb-2 tracking-tight">首次设置管理员密码</h2>
<p className="text-gray-600 font-medium">设置完成后会自动进入系统,管理员账号为 admin。</p>
</div>
<form onSubmit={handleInitialize} className="space-y-5">
<div className="space-y-4">
<div className="relative group">
<Lock className="absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors" />
<input
type="password"
placeholder="设置管理员密码(至少 8 个字符)"
value={initialPassword}
onChange={e => setInitialPassword(e.target.value)}
autoFocus
className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"
/>
</div>
<div className="relative group">
<ShieldCheck className="absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors" />
<input
type="password"
placeholder="再次输入密码"
value={initialPasswordConfirm}
onChange={e => setInitialPasswordConfirm(e.target.value)}
className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"
/>
</div>
</div>
{initializationError && (
<div className="p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2">
<ShieldCheck className="w-4 h-4" /> {initializationError}
</div>
)}
<button
type="submit"
disabled={initializing}
className="w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group disabled:opacity-70"
>
{initializing ? <Loader2 className="w-5 h-5 animate-spin" /> : <>设置密码并进入系统 <ArrowRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" /></>}
</button>
</form>
<div className="mt-8 pt-6 border-t border-gray-100 text-center">
<span className="text-xs text-gray-400 font-medium tracking-widest uppercase">Secure Bootstrap</span>
</div>
</div>
</div>
);
}
// Login Screen Component
if (!isLoggedIn) {
return (
<div className="min-h-screen flex items-center justify-center bg-canvas p-4 relative overflow-hidden font-sans">
{/* Animated Background Blobs */}
<div className="absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"></div>
<div className="absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse" style={{animationDelay: '2s'}}></div>
<div className="bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-panel w-full max-w-lg border border-white relative z-10 animate-fade-in">
{/* Header with Logo */}
<div className="text-center mb-10">
<div className="group mx-auto mb-6 flex cursor-pointer justify-center">
<YdisksBrandIcon sizeClass="w-24 h-24" logoClassName="w-full h-full text-white group-hover:scale-110 transition-transform" />
</div>
<h2 className="text-3xl font-extrabold text-gray-900 mb-2 tracking-tight">欢迎回来</h2>
<p className="text-gray-500 font-medium">Ydisks闲鱼助手 · 自动发货与管家系统</p>
</div>
<form onSubmit={handleLogin} className="space-y-5">
<div className="space-y-4">
<div className="relative group">
<User className="absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors" />
<input
type="text"
placeholder="管理员账号"
value={username}
onChange={e => setUsername(e.target.value)}
className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"
/>
</div>
<div className="relative group">
<Lock className="absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors" />
<input
type="password"
placeholder="密码"
value={password}
onChange={e => setPassword(e.target.value)}
className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"
/>
</div>
</div>
{loginError && (
<div className="p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2">
<ShieldCheck className="w-4 h-4" /> {loginError}
</div>
)}
<button
type="submit"
disabled={loginLoading}
className="w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group disabled:opacity-70"
>
{loginLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : <>立即登录 <ArrowRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" /></>}
</button>
</form>
<div className="mt-8 pt-6 border-t border-gray-100">
<div className="mt-6 text-center">
<span className="text-xs text-gray-400 font-medium tracking-widest uppercase">
Ydisks闲鱼助手 v1.0
</span>
</div>
</div>
</div>
</div>
);
}
// Main App Layout
const renderContent = () => {
switch (activeTab) {
case 'dashboard': return <Dashboard />;
case 'accounts': return <AccountList />;
case 'chat': return <Chat />;
case 'orders': return <OrderList />;
case 'cards': return <CardList />;
case 'items': return <ItemList onConfigureDelivery={(item) => {
setDeliveryRuleTarget({ cookieId: item.cookie_id, itemId: item.item_id, requestId: Date.now() });
navigate('rules');
}} />;
case 'rules': return <Rules
initialDeliveryTarget={deliveryRuleTarget}
onDeliveryTargetHandled={() => setDeliveryRuleTarget(undefined)}
/>;
case 'notifications': return <Notifications isAdmin={isAdmin} />;
case 'settings': return isAdmin ? <Settings /> : <Dashboard />;
default: return <Dashboard />;
}
};
return (
<div className="flex min-h-screen bg-canvas text-ink">
<Sidebar
activeTab={activeTab}
isAdmin={isAdmin}
collapsed={sidebarCollapsed}
onToggleCollapsed={() => setSidebarCollapsed(current => {
const next = !current;
writeSidebarCollapsed(next);
return next;
})}
onNavigate={navigate}
onLogout={handleLogout}
/>
<main className={`h-screen min-w-0 flex-1 overflow-x-hidden overflow-y-auto scroll-smooth transition-[margin] duration-300 ${sidebarCollapsed ? 'ml-16' : 'ml-64'} ${activeTab === 'chat' ? 'p-4 md:p-6' : 'p-8 md:p-12'}`}>
{/* Subtle background decoration */}
<div className="fixed top-0 right-0 w-[800px] h-[800px] bg-gradient-to-bl from-blue-50 to-transparent rounded-full blur-[120px] pointer-events-none -z-10 opacity-60"></div>
<div className={`${activeTab === 'chat' ? 'mx-auto max-w-[1680px]' : 'mx-auto max-w-[1400px] pb-10'}`}>
{renderContent()}
</div>
</main>
</div>
);
};
export default App;