129 lines
42 KiB
TypeScript
129 lines
42 KiB
TypeScript
import { useState, useEffect, useCallback, useId } from 'react';
|
||
import type { ReactNode } from 'react';
|
||
import { ArrowRight, ArrowUpRight, BarChart3, BookOpen, Check, ChevronLeft, ChevronRight, Database, Download, FileUp, Globe2, GraduationCap, LayoutDashboard, ListFilter, Loader2, Network, Pause, Play, Plus, RefreshCw, Search, Settings2, ShieldCheck, Square, Star, X } from 'lucide-react';
|
||
import { api, post } from './api';
|
||
import { display, scopeName, statusName, modeName, queryString, scoreSeries } from './format';
|
||
import type { Row, Overview, Province, Major, Job, Log, Config, Proxy, Auth, History, Filters } from './types';
|
||
|
||
type Tab = 'overview' | 'workspace' | 'jobs' | 'proxy' | 'settings';
|
||
type Notify = (message: string, error?: boolean) => void;
|
||
const NAV = [{ key: 'overview', label: '数据概览', icon: LayoutDashboard }, { key: 'workspace', label: '院校工作区', icon: GraduationCap }, { key: 'jobs', label: '采集任务', icon: RefreshCw }, { key: 'proxy', label: '代理 IP 池', icon: Network }, { key: 'settings', label: '设置与登录', icon: Settings2 }] as const;
|
||
const currentYear = new Date().getFullYear();
|
||
const activeStates = ['queued', 'running'];
|
||
const resumeStates = ['paused', 'partial', 'failed', 'waiting_login', 'waiting_proxy'];
|
||
|
||
function Badge({ children, tone = '' }: { children: ReactNode; tone?: string }) { return <span className={`badge ${tone}`}>{children}</span>; }
|
||
function Empty({ title, children }: { title: string; children?: ReactNode }) { return <div className="empty"><Database size={34} strokeWidth={1.3} /><h3>{title}</h3><div>{children}</div></div>; }
|
||
function Modal({ title, children, close, wide = false }: { title: string; children: ReactNode; close: () => void; wide?: boolean }) {
|
||
useEffect(() => { const listener = (e: KeyboardEvent) => { if (e.key === 'Escape') close(); }; document.addEventListener('keydown', listener); const old = document.body.style.overflow; document.body.style.overflow = 'hidden'; return () => { document.removeEventListener('keydown', listener); document.body.style.overflow = old; }; }, [close]);
|
||
return <div className="modal-backdrop" onClick={close}><section className={`modal ${wide ? 'wide' : ''}`} role="dialog" aria-modal="true" aria-label={title} onClick={e => e.stopPropagation()}><div className="modal-head"><h2>{title}</h2><button className="icon-button" aria-label="关闭" onClick={close}><X size={20} /></button></div>{children}</section></div>;
|
||
}
|
||
function MajorInput({ majors, value, onChange, label = '专业代码', required = false }: { majors: Major[]; value: string; onChange: (value: string) => void; label?: string; required?: boolean }) {
|
||
const id = useId();
|
||
return <label>{label}<input value={value} list={id} placeholder="全部专业 / 如 081200" onChange={e => onChange(e.target.value.split(' ')[0])} required={required} /><datalist id={id}>{majors.map((m, i) => <option key={`${m.code}-${i}`} value={m.code}>{m.name} · {m.degree_type}</option>)}</datalist></label>;
|
||
}
|
||
function Stat({ label, value, icon, sub }: { label: string; value: number; icon: ReactNode; sub: string }) { return <div className="stat"><div className="stat-top">{label}<span>{icon}</span></div><strong>{Number(value || 0).toLocaleString()}</strong><small>{sub}</small></div>; }
|
||
|
||
export default function App() {
|
||
const [tab, setTab] = useState<Tab>('overview');
|
||
const [overview, setOverview] = useState<Overview | null>(null);
|
||
const [majors, setMajors] = useState<Major[]>([]);
|
||
const [version, setVersion] = useState(0);
|
||
const [notice, setNotice] = useState<{ message: string; error: boolean } | null>(null);
|
||
const notify = useCallback<Notify>((message, error = false) => setNotice({ message, error }), []);
|
||
const refresh = useCallback(() => setVersion(v => v + 1), []);
|
||
useEffect(() => { const controller = new AbortController(); Promise.all([api<Overview>('/overview', { signal: controller.signal }), api<Major[]>('/majors', { signal: controller.signal })]).then(([o, m]) => { setOverview(o); setMajors(m); }).catch(e => { if (e.name !== 'AbortError') notify(e.message, true); }); return () => controller.abort(); }, [version, notify]);
|
||
useEffect(() => { if (!notice) return; const timer = setTimeout(() => setNotice(null), 6500); return () => clearTimeout(timer); }, [notice]);
|
||
const props = { overview, majors, notify, refresh };
|
||
return <div className="app-shell"><aside className="sidebar"><a className="brand" href="#" onClick={e => { e.preventDefault(); setTab('overview'); }}><span className="brand-symbol"><GraduationCap size={28} /></span><span><b>研途<span className="brand-dot">.</span></b><small>考研数据工作台</small></span></a><div className="nav-label">WORKSPACE / 本地工作区</div><nav aria-label="主导航">{NAV.map(n => <button key={n.key} className={tab === n.key ? 'active' : ''} onClick={() => setTab(n.key)}><n.icon size={19} /><span>{n.label}</span>{tab === n.key && <span className="nav-active-dot" />}</button>)}</nav><div className="sidebar-bottom"><div className="local-indicator"><span /> 本机数据 · 独立保存</div><p>把全国目录与历年考情<br />放在同一个工作区。</p><div className="sidebar-version">YAM × yzw <span>v1.0</span></div></div></aside><div className="main-shell"><header className="topbar"><div className="breadcrumb">工作台 <ChevronRight size={14} /><span>{NAV.find(n => n.key === tab)?.label}</span></div><div className="topbar-right"><span className="local-tag"><ShieldCheck size={14} /> 本地运行</span><button className="icon-button" aria-label="刷新数据" onClick={refresh}><RefreshCw size={17} /></button></div></header><main>{tab === 'overview' && <Dashboard {...props} go={setTab} />}{tab === 'workspace' && <Workspace {...props} />}{tab === 'jobs' && <Tasks {...props} />}{tab === 'proxy' && <ProxyPanel notify={notify} />}{tab === 'settings' && <SettingsPanel notify={notify} />}</main><footer>研途 · 数据以院校当年招生简章为准<span>全国招生目录 / 历年考情 / 本地工作区</span></footer></div>{notice && <div role="status" className={`toast ${notice.error ? 'error' : ''}`}>{notice.error ? <X size={18} /> : <Check size={18} />}{notice.message}<button aria-label="关闭提示" onClick={() => setNotice(null)}><X size={16} /></button></div>}</div>;
|
||
}
|
||
|
||
type Shared = { overview: Overview | null; majors: Major[]; notify: Notify; refresh: () => void };
|
||
function PageTitle({ eyebrow, title, description, children }: { eyebrow: string; title: string; description: string; children?: ReactNode }) { return <div className="page-title"><div><div className="eyebrow">{eyebrow}</div><h1>{title}</h1><p>{description}</p></div><div className="page-actions">{children}</div></div>; }
|
||
|
||
function Dashboard({ overview: o, go }: Shared & { go: (tab: Tab) => void }) {
|
||
const [jobs, setJobs] = useState<Job[]>([]);
|
||
useEffect(() => { const controller = new AbortController(); api<Job[]>('/jobs', { signal: controller.signal }).then(setJobs).catch(() => {}); return () => controller.abort(); }, []);
|
||
return <><PageTitle eyebrow="YOUR RESEARCH, IN ONE PLACE" title="从数据出发,找到适合的院校" description="连接全国招生目录与历年考情,让每一次择校都有依据。"><button className="primary" onClick={() => go('jobs')}><Plus size={17} />新建采集任务</button></PageTitle><div className="stats-grid"><Stat label="已采集院校" value={o?.schools || 0} icon={<GraduationCap size={20} />} sub={`另有 ${o?.indexed_schools || 0} 所院校公开索引`} /><Stat label="目录与计划记录" value={o?.records || 0} icon={<Database size={19} />} sub="按年份、方向和科目组合保存" /><Stat label="历史分数线" value={o?.scores || 0} icon={<BarChart3 size={19} />} sub="保留专业、学科与门类口径" /><Stat label="我的收藏" value={o?.favorites || 0} icon={<Star size={19} />} sub="在工作区筛选与横向对比" /></div><div className="dashboard-grid"><section className="card welcome"><div className="section-kicker">开始你的研究</div><h2>一个工作区,两种数据来源</h2><p>先建立招生目录,再补充历年分数线和计划。已有数据也可以直接导入,继续筛选、收藏与对比。</p><div className="steps"><div><span>01</span><div><b>连接账号与代理池</b><small>登录学信网,选择当前网络策略</small></div><button aria-label="打开设置与登录" onClick={() => go('settings')}><ArrowUpRight size={20} /></button></div><div><span>02</span><div><b>选择年份、地区和专业</b><small>按省采集,也可覆盖全国 31 个省级地区</small></div><button aria-label="打开采集任务" onClick={() => go('jobs')}><ArrowUpRight size={20} /></button></div><div><span>03</span><div><b>把数据变成择校清单</b><small>多条件筛选、历史趋势和 Excel 导出</small></div><button aria-label="打开院校工作区" onClick={() => go('workspace')}><ArrowUpRight size={20} /></button></div></div></section><section className="card sources"><div className="card-title"><h2>已接入数据来源</h2><Badge tone="green">2 个来源</Badge></div>{o?.sources.map((s, i) => <a key={s.name} className="source-row" href={s.url} target="_blank" rel="noreferrer"><span className={`source-icon source-${i}`}>{i === 0 ? <Globe2 size={22} /> : <BookOpen size={22} />}</span><div><b>{s.name}</b><small>{s.role}</small></div><ArrowUpRight size={17} /></a>)}<div className="source-note"><ShieldCheck size={18} /><p>数据保存在本机。每条记录都保留来源和年份,未知字段明确标记。</p></div><button className="text-button" onClick={() => go('proxy')}>管理代理 IP 池 <ArrowRight size={16} /></button></section></div><section className="card recent"><div className="card-title"><h2>最近采集任务</h2><button className="text-button" onClick={() => go('jobs')}>全部任务 <ArrowRight size={16} /></button></div>{jobs.length ? <div className="recent-list">{jobs.slice(0, 4).map(j => <div key={j.id}><span className="job-dot" /><div><b>{modeName(j.params.mode)} · {j.params.year} 年</b><small>{j.message}</small></div><Badge tone={j.status === 'completed' ? 'green' : ''}>{statusName(j.status)}</Badge><span>{j.completed_units} 个完成单元</span></div>)}</div> : <div className="onboarding-empty"><div className="dashed-icon"><RefreshCw size={22} /></div><div><b>还没有采集任务</b><p>创建一个任务,或在院校工作区导入 YAM / yzw 的已有数据。</p></div><button onClick={() => go('jobs')}>开始采集 <ArrowRight size={16} /></button></div>}</section></>;
|
||
}
|
||
|
||
function Workspace({ overview, majors, notify, refresh }: Shared) {
|
||
const [filters, setFilters] = useState<Filters>({ sort: 'year' });
|
||
const [page, setPage] = useState(1);
|
||
const [rows, setRows] = useState<Row[]>([]);
|
||
const [total, setTotal] = useState(0);
|
||
const [loading, setLoading] = useState(true);
|
||
const [localVersion, setLocalVersion] = useState(0);
|
||
const [selected, setSelected] = useState<Row[]>([]);
|
||
const [compare, setCompare] = useState(false);
|
||
const [detail, setDetail] = useState<number | null>(null);
|
||
const [importing, setImporting] = useState(false);
|
||
const [more, setMore] = useState(false);
|
||
const query = queryString({ ...filters, page, page_size: 30 });
|
||
useEffect(() => { const controller = new AbortController(); setLoading(true); const timer = setTimeout(() => api<{ items: Row[]; total: number }>('/catalog?' + query, { signal: controller.signal }).then(data => { setRows(data.items); setTotal(data.total); }).catch(e => { if (e.name !== 'AbortError') notify(e.message, true); }).finally(() => { if (!controller.signal.aborted) setLoading(false); }), 180); return () => { clearTimeout(timer); controller.abort(); }; }, [query, localVersion, notify]);
|
||
const change = (key: string, value: string | boolean) => { setFilters(f => ({ ...f, [key]: value })); setPage(1); };
|
||
async function favorite(row: Row) { try { await api(`/catalog/${row.id}/favorite`, { method: 'PUT', body: JSON.stringify({ enabled: !row.favorite }) }); setLocalVersion(v => v + 1); refresh(); } catch (e) { notify((e as Error).message, true); } }
|
||
const toggleSelected = (row: Row) => { if (selected.some(s => s.id === row.id)) setSelected(s => s.filter(v => v.id !== row.id)); else if (selected.length < 6) setSelected(s => [...s, row]); else notify('最多同时对比 6 条记录', true); };
|
||
return <><PageTitle eyebrow="SCHOOL WORKSPACE" title="院校工作区" description="从全国目录中筛选候选院校,查看考情,建立自己的择校清单。"><button onClick={() => setImporting(true)}><FileUp size={17} />导入数据</button><select aria-label="选择导出格式" defaultValue="" disabled={!total} onChange={e => { if (e.target.value) { window.location.href = '/api/export?' + queryString({ ...filters, format: e.target.value }); e.target.value = ''; } }}><option value="" disabled>导出筛选结果</option><option value="xlsx">Excel (.xlsx)</option><option value="csv">CSV</option><option value="json">JSON 完整快照</option></select></PageTitle><section className="card filters"><div className="filter-main"><label className="search-input"><Search size={17} /><input aria-label="搜索院校、专业或院系" placeholder="搜索院校、专业或院系" value={String(filters.keyword || '')} onChange={e => change('keyword', e.target.value)} /></label><select aria-label="筛选省份" value={String(filters.province || '')} onChange={e => change('province', e.target.value)}><option value="">全国地区</option>{overview?.provinces_list.map(p => <option key={p.code}>{p.name}</option>)}</select><select aria-label="筛选年份" value={String(filters.year || '')} onChange={e => change('year', e.target.value)}><option value="">全部年份</option>{overview?.years.map(y => <option key={y}>{y}</option>)}</select><button className={filters.favorites ? 'selected-button' : ''} onClick={() => change('favorites', !filters.favorites)}><Star size={16} />仅收藏</button><button onClick={() => setMore(m => !m)}><ListFilter size={16} />更多筛选</button></div>{more && <div className="filter-more"><MajorInput majors={majors} value={String(filters.major_code || '')} onChange={v => change('major_code', v)} /><label>学习方式<select value={String(filters.study_mode || '')} onChange={e => change('study_mode', e.target.value)}><option value="">全部</option><option>全日制</option><option>非全日制</option></select></label><label>学位类型<select value={String(filters.degree_type || '')} onChange={e => change('degree_type', e.target.value)}><option value="">全部</option><option>学术学位</option><option>专业学位</option></select></label><label>院校层次<select value={String(filters.level || '')} onChange={e => change('level', e.target.value)}><option value="">全部</option><option>985</option><option>211</option><option>双一流</option></select></label><label>考试科目<input placeholder="如 408、英语一" value={String(filters.subject || '')} onChange={e => change('subject', e.target.value)} /></label><label>院系<input value={String(filters.department_name || '')} onChange={e => change('department_name', e.target.value)} /></label><label>研究方向<input value={String(filters.direction || '')} onChange={e => change('direction', e.target.value)} /></label><label>明确招生人数 ≥<input type="number" min="0" value={String(filters.min_quota || '')} onChange={e => change('min_quota', e.target.value)} /></label><label>最近参考线 ≤<input type="number" min="0" value={String(filters.max_score || '')} onChange={e => change('max_score', e.target.value)} /></label><button className="text-button reset" onClick={() => { setFilters({ sort: 'year' }); setPage(1); }}>重置筛选</button></div>}</section><section className="card data-card"><div className="data-toolbar"><div><b>{total.toLocaleString()}</b> 条记录 <span>· 人数保留原文,科目组合分别展示</span>{loading && <Loader2 className="spin" size={16} />}</div><label>排序<select aria-label="排序" value={String(filters.sort)} onChange={e => change('sort', e.target.value)}><option value="year">年份优先</option><option value="school">院校名称</option><option value="quota">明确人数从高到低</option><option value="score">参考线从低到高</option></select></label></div>{rows.length ? <div className="table-scroll"><table className="catalog-table"><thead><tr><th className="narrow">对比</th><th>院校 / 专业</th><th>院系 / 方向</th><th>初试科目</th><th>招生人数</th><th>最近参考线</th><th>年份 / 来源</th><th className="narrow">收藏</th></tr></thead><tbody>{rows.map(row => <tr key={row.id}><td><input type="checkbox" aria-label={`对比 ${row.school_name} ${row.id}`} checked={selected.some(s => s.id === row.id)} onChange={() => toggleSelected(row)} /></td><td><button className="row-link" onClick={() => setDetail(row.id)}>{row.school_name}</button><small>{row.major_code} · {display(row.major_name)}</small><div className="row-badges">{row.province && <Badge>{row.province}</Badge>}{row.level && <Badge tone="green">{row.level}</Badge>}{row.study_mode && <Badge>{row.study_mode}</Badge>}</div></td><td><div>{display(row.department_name)}</div><small>{display(row.direction)}</small></td><td className="subjects-cell">{row.subjects.some(Boolean) ? row.subjects.map((s, i) => s && <div key={i}>{s}</div>) : <span className="muted">未提供</span>}</td><td><b>{display(row.quota)}</b><small>{row.quota_text || '来源未提供人数'}</small></td><td>{row.score_total !== null ? <><b className="score-number">{row.score_total}</b><small>{row.score_year} · {scopeName(row.score_scope)}</small></> : <span className="muted">未提供</span>}</td><td><b>{row.year}</b><small>{row.source}</small>{!row.year_verified && <span className="verification-note">年份由文件指定</span>}</td><td><button className={`icon-button favorite ${row.favorite ? 'is-favorite' : ''}`} aria-label={`${row.favorite ? '取消收藏' : '收藏'} ${row.school_name} ${row.id}`} onClick={() => favorite(row)}><Star size={18} fill={row.favorite ? 'currentColor' : 'none'} /></button></td></tr>)}</tbody></table></div> : !loading ? <Empty title="没有符合条件的数据"><p>可以调整筛选条件,或导入 YAM / yzw 数据、创建新的采集任务。</p><button onClick={() => setImporting(true)}><FileUp size={16} />导入已有数据</button></Empty> : <div className="loading-area"><Loader2 className="spin" />正在读取本地数据…</div>}<div className="pagination"><span>第 {page} / {Math.max(1, Math.ceil(total / 30))} 页 · 每页 30 条</span><div><button aria-label="上一页" disabled={page <= 1} onClick={() => setPage(p => p - 1)}><ChevronLeft size={16} /></button><button aria-label="下一页" disabled={page * 30 >= total} onClick={() => setPage(p => p + 1)}><ChevronRight size={16} /></button></div></div></section>{selected.length > 0 && <div className="compare-bar"><div><GraduationCap size={20} /><b>已选 {selected.length} 条记录</b><span>{selected.map(s => s.school_name).join(' / ')}</span></div><button className="text-button" onClick={() => setSelected([])}>清空</button><button className="primary" disabled={selected.length < 2} onClick={() => setCompare(true)}>开始对比 <ArrowRight size={16} /></button></div>}{detail !== null && <Detail rid={detail} close={() => setDetail(null)} notify={notify} />}{compare && <Comparison rows={selected} close={() => setCompare(false)} />}{importing && <ImportDialog close={() => setImporting(false)} notify={notify} done={() => { setLocalVersion(v => v + 1); refresh(); }} />}</>;
|
||
}
|
||
|
||
function ImportDialog({ close, done, notify }: { close: () => void; done: () => void; notify: Notify }) {
|
||
const [file, setFile] = useState<File | null>(null), [year, setYear] = useState(String(currentYear)), [busy, setBusy] = useState(false);
|
||
async function submit(e: React.FormEvent) { e.preventDefault(); if (!file) return; const body = new FormData(); body.set('file', file); if (year) body.set('year', year); setBusy(true); try { const result = await api<{ records: number; scores: number }>('/import', { method: 'POST', body }); notify(`已导入 ${result.records} 条目录/计划、${result.scores} 条分数线`); done(); close(); } catch (e) { notify((e as Error).message, true); } finally { setBusy(false); } }
|
||
return <Modal title="导入已有数据" close={close}><form onSubmit={submit} className="modal-body form-stack"><p>支持 yzw CSV、工作台 JSON / Excel,以及 YAM SQLite 数据库。相同记录按年份更新,其他年份保留。</p><label>数据文件<input type="file" accept=".csv,.xlsx,.json,.db,.sqlite,.sqlite3" required onChange={e => setFile(e.target.files?.[0] || null)} /></label><label>这份目录的招生年份<input type="number" min="2000" max="2100" value={year} onChange={e => setYear(e.target.value)} /></label><div className="info-box">文件本身有年份时使用文件年份。yzw CSV 和 YAM 无年份目录必须明确填写;分数线仍保留其原始年份。</div><button className="primary" disabled={busy || !file}>{busy ? <Loader2 className="spin" size={17} /> : <FileUp size={17} />}开始导入</button></form></Modal>;
|
||
}
|
||
|
||
function Comparison({ rows, close }: { rows: Row[]; close: () => void }) {
|
||
const fields: [string, (row: Row) => ReactNode][] = [['专业', r => `${r.major_code} ${r.major_name}`], ['地区 / 层次', r => `${r.province} ${r.level}`], ['院系', r => display(r.department_name)], ['方向', r => display(r.direction)], ['学制形式', r => display(r.study_mode)], ['初试科目', r => r.subjects.filter(Boolean).map((s, i) => <div key={i}>{s}</div>)], ['人数原文', r => display(r.quota_text)], ['明确人数 / 口径', r => `${display(r.quota)} / ${r.quota_scope === 'major' ? '专业' : r.quota_scope === 'college' ? '学院' : '口径待核实'}`], ['最近参考线', r => r.score_total !== null ? `${r.score_year} 年 ${r.score_total} · ${scopeName(r.score_scope)}` : '未提供'], ['导师', r => display(r.advisor)], ['专项计划', r => r.special_plans.join(' / ') || '未提供'], ['来源', r => `${r.year} 年 · ${r.source}`]];
|
||
return <Modal title="院校与专业对比" close={close} wide><div className="modal-body"><p className="muted">每列是一条独立方向/科目组合。专业人数可能重复展示,不能按列相加。</p><div className="table-scroll"><table className="compare-table"><thead><tr><th>比较项</th>{rows.map(r => <th key={r.id}>{r.school_name}<small>{r.year} 年</small></th>)}</tr></thead><tbody>{fields.map(([label, field]) => <tr key={label}><th>{label}</th>{rows.map(r => <td key={r.id}>{field(r)}</td>)}</tr>)}</tbody></table></div></div></Modal>;
|
||
}
|
||
|
||
function Detail({ rid, close, notify }: { rid: number; close: () => void; notify: Notify }) {
|
||
const [data, setData] = useState<History | null>(null);
|
||
useEffect(() => { const controller = new AbortController(); api<History>(`/catalog/${rid}`, { signal: controller.signal }).then(setData).catch(e => { if (e.name !== 'AbortError') notify(e.message, true); }); return () => controller.abort(); }, [rid, notify]);
|
||
const r = data?.record;
|
||
return <Modal title={r ? `${r.school_name} · ${r.major_name || r.major_code}` : '读取记录…'} close={close} wide>{data && r ? <div className="modal-body"><div className="detail-meta"><Badge tone="green">{r.year} 年</Badge><Badge>{r.province || '地区未提供'}</Badge><Badge>{r.source}</Badge><span>{r.year_verified ? '来源年份已核实' : '年份由导入文件指定'}</span>{/^https:\/\//.test(r.source_url) && <a href={r.source_url} target="_blank" rel="noreferrer">查看来源 <ArrowUpRight size={14} /></a>}</div><div className="detail-grid">{[['院系', r.department_name], ['研究方向', r.direction], ['学习方式', r.study_mode], ['学位类型', r.degree_type], ['导师', r.advisor], ['拟招生人数原文', r.quota_text], ['专项计划', r.special_plans.join(' / ')], ['采集时间', r.fetched_at]].map(([k, v]) => <div key={k}><small>{k}</small><b>{display(v)}</b></div>)}</div><div className="subject-pills">{r.subjects.filter(Boolean).map((s, i) => <span key={i}>{s}</span>)}</div>{r.remarks && <div className="info-box">{r.remarks}</div>}{r.reference_books?.length ? <p>参考书:{r.reference_books.join(';')}</p> : null}<h3 className="subheading">历年分数线</h3><Trend scores={data.scores} /><div className="table-scroll"><table><thead><tr><th>年份</th><th>口径</th><th>总分</th><th>政治</th><th>外语</th><th>业务一</th><th>业务二</th><th>备注</th></tr></thead><tbody>{data.scores.map((s, i) => <tr key={i}><td>{s.year}</td><td>{scopeName(s.scope)}<small>{s.raw_code}</small></td><td>{display(s.total)}</td><td>{display(s.politics)}</td><td>{display(s.english)}</td><td>{display(s.special_one)}</td><td>{display(s.special_two)}</td><td>{s.note || '—'}</td></tr>)}</tbody></table></div><h3 className="subheading">历年招生计划 / 目录快照</h3><div className="table-scroll"><table><thead><tr><th>年份</th><th>方向</th><th>招生人数原文</th><th>科目组合</th><th>来源</th></tr></thead><tbody>{data.plans.map((p, i) => <tr key={i}><td>{p.year}</td><td>{display(p.direction)}</td><td>{display(p.quota_text)}</td><td>{p.subjects.filter(Boolean).join(' / ') || '未提供'}</td><td>{p.source}</td></tr>)}</tbody></table></div></div> : <div className="loading-area"><Loader2 className="spin" />正在读取…</div>}</Modal>;
|
||
}
|
||
|
||
function Trend({ scores }: { scores: History['scores'] }) {
|
||
const groups = scoreSeries(scores), points = groups.flatMap(g => g.points), colors = ['#14816f', '#4279ae', '#bb883c', '#965f93'];
|
||
if (!points.length) return <div className="chart-empty">暂未获取该院系的历史分数线。采集历年考情后可查看趋势。</div>;
|
||
const years = [...new Set(points.map(p => p.year))].sort(), low = Math.floor((Math.min(...points.map(p => p.total)) - 10) / 10) * 10, high = Math.ceil((Math.max(...points.map(p => p.total)) + 10) / 10) * 10;
|
||
const x = (year: number) => years.length === 1 ? 380 : 55 + (year - years[0]) / (years[years.length - 1] - years[0]) * 650;
|
||
const y = (score: number) => 170 - (score - low) / (high - low) * 140;
|
||
return <div className="trend"><svg viewBox="0 0 760 210" role="img" aria-label="历年分数线趋势,不同口径独立展示">{[low, (low + high) / 2, high].map(t => <g key={t}><line x1="50" x2="710" y1={y(t)} y2={y(t)} stroke="#e7edef" /><text x="12" y={y(t) + 4}>{t}</text></g>)}{years.map(t => <text key={t} x={x(t)} y="199" textAnchor="middle">{t}</text>)}{groups.map((g, i) => <g key={i}><polyline fill="none" stroke={colors[i % colors.length]} strokeWidth="2.5" points={g.points.map(p => `${x(p.year)},${y(p.total)}`).join(' ')} />{g.points.map((p, j) => <g key={j}><circle cx={x(p.year)} cy={y(p.total)} r="4" fill={colors[i % colors.length]} /><text x={x(p.year)} y={y(p.total) - 10} textAnchor="middle">{p.total}</text></g>)}</g>)}</svg><div className="chart-legend">{groups.map((g, i) => <span key={i}><i style={{ background: colors[i % colors.length] }} />{g.label}</span>)}</div></div>;
|
||
}
|
||
|
||
function Tasks({ overview, majors, notify, refresh }: Shared) {
|
||
const [mode, setMode] = useState('combined'), [year, setYear] = useState(currentYear + 1), [major, setMajor] = useState(''), [province, setProvince] = useState(''), [school, setSchool] = useState(''), [years, setYears] = useState([currentYear - 2, currentYear - 1, currentYear]), [plans, setPlans] = useState(true), [jobs, setJobs] = useState<Job[]>([]), [logs, setLogs] = useState<Log[]>([]), [selected, setSelected] = useState(''), [busy, setBusy] = useState(false), [config, setConfig] = useState<Config | null>(null);
|
||
const load = useCallback(async () => { const data = await api<Job[]>('/jobs'); setJobs(data); setSelected(s => s || data[0]?.id || ''); }, []);
|
||
useEffect(() => { load().catch(e => notify(e.message, true)); api<Config>('/settings').then(setConfig).catch(e => notify(e.message, true)); }, [load, notify]);
|
||
const hasActive = jobs.some(j => activeStates.includes(j.status));
|
||
useEffect(() => { if (!hasActive) return; const timer = setInterval(() => { load().catch(() => {}); refresh(); }, 2500); return () => clearInterval(timer); }, [hasActive, load, refresh]);
|
||
const job = jobs.find(j => j.id === selected);
|
||
const stamp = job?.updated_at;
|
||
useEffect(() => { if (!selected) return; const controller = new AbortController(); api<Log[]>(`/jobs/${selected}/logs`, { signal: controller.signal }).then(setLogs).catch(e => { if (e.name !== 'AbortError') notify(e.message, true); }); return () => controller.abort(); }, [selected, stamp, notify]);
|
||
async function start(e: React.FormEvent) { e.preventDefault(); setBusy(true); try { const result = await post<Job>('/jobs', { mode, year, major_code: major, school_keyword: school, provinces: province ? [province] : [], score_years: years, include_plans: plans }); setSelected(result.id); await load(); notify('采集任务已启动'); } catch (e) { notify((e as Error).message, true); } finally { setBusy(false); } }
|
||
async function action(action: string) { if (!job) return; setBusy(true); try { await post(`/jobs/${job.id}/${action}`); await load(); refresh(); } catch (e) { notify((e as Error).message, true); } finally { setBusy(false); } }
|
||
return <><PageTitle eyebrow="COLLECTION CENTER" title="采集任务" description="按地区、专业与年份采集;暂停后保留断点,重新启动服务也可以继续。"><Badge tone="green">{config ? modeName(config.network_mode) : '读取网络策略…'}</Badge></PageTitle><div className="task-grid"><section className="card task-form"><h2>新建采集</h2><form onSubmit={start} className="form-stack"><label>采集内容<select value={mode} onChange={e => setMode(e.target.value)}><option value="combined">招生目录 + 历年考情</option><option value="catalog">仅研招网招生目录</option><option value="scores">仅掌上考研历年考情</option></select></label><div className="two-fields"><label>目录年份<input type="number" min="2000" max="2100" value={year} onChange={e => setYear(Number(e.target.value))} required /></label><label>采集地区<select value={province} onChange={e => setProvince(e.target.value)}><option value="">全国 31 个地区</option>{overview?.provinces_list.map(p => <option key={p.code} value={p.code}>{p.name}</option>)}</select></label></div><MajorInput majors={majors} value={major} onChange={setMajor} /><label>院校关键词<input value={school} onChange={e => setSchool(e.target.value)} placeholder="留空采集所选地区全部院校" /></label>{mode !== 'catalog' && <><label>分数线 / 计划年份</label><div className="year-checks">{Array.from({ length: 8 }, (_, i) => currentYear - i).map(y => <label key={y}><input type="checkbox" checked={years.includes(y)} onChange={e => setYears(old => e.target.checked ? [...old, y] : old.filter(v => v !== y))} />{y}</label>)}</div><label className="check-label"><input type="checkbox" checked={plans} onChange={e => setPlans(e.target.checked)} />同时补充历史招生计划</label></>}<div className="info-box">研招网仅开放当前目录。任务开始时核验年份;历史目录可从文件导入。仅采集历年考情时,使用已存目录或指定专业的院校索引。</div><button className="primary" disabled={busy || hasActive}>{busy ? <Loader2 className="spin" size={17} /> : <Play size={17} />}开始采集</button><p className="form-hint">首次使用,请先在「设置与登录」完成学信网登录。</p></form></section><div className="task-right"><section className="card job-list"><div className="card-title"><h2>任务记录</h2><button className="icon-button" aria-label="刷新任务记录" onClick={() => load().catch(e => notify(e.message, true))}><RefreshCw size={16} /></button></div>{jobs.length ? jobs.map(j => <button className={`job-row ${selected === j.id ? 'selected' : ''}`} key={j.id} onClick={() => setSelected(j.id)}><div><b>{modeName(j.params.mode)} · {j.params.year}</b><small>{j.params.major_code || '全部专业'} · {j.completed_units} 个完成单元</small></div><Badge tone={j.status === 'completed' ? 'green' : j.status === 'failed' ? 'red' : ''}>{statusName(j.status)}</Badge></button>) : <div className="inline-empty">还没有任务。填写左侧条件开始采集。</div>}</section><section className="card job-detail"><div className="card-title"><h2>运行日志</h2>{job && <div className="button-group">{activeStates.includes(job.status) && <button disabled={busy} onClick={() => action('pause')}><Pause size={14} />暂停</button>}{resumeStates.includes(job.status) && <button disabled={busy} onClick={() => action('resume')}><Play size={14} />恢复</button>}{!['completed', 'cancelled'].includes(job.status) && <button disabled={busy} onClick={() => action('cancel')}><Square size={14} />取消</button>}</div>}</div>{job ? <><div className="job-summary"><span>状态 <b>{statusName(job.status)}</b></span><span>完成单元 <b>{job.completed_units}</b></span><span>保存记录 <b>{job.records}</b></span><span>失败单元 <b>{job.errors}</b></span></div><div className="job-message">{job.message}</div><div className="log-panel" aria-live="polite">{logs.map(l => <div key={l.id} className={l.level}><time>{l.created_at.slice(11, 19)}</time><span>{l.message}</span></div>)}{!logs.length && <span className="muted">暂无日志</span>}</div></> : <div className="inline-empty">选择一个任务查看进度和日志。</div>}</section></div></div></>;
|
||
}
|
||
|
||
function ProxyPanel({ notify }: { notify: Notify }) {
|
||
const [data, setData] = useState<Proxy | null>(null), [busy, setBusy] = useState(false), [output, setOutput] = useState('');
|
||
const load = useCallback(async () => setData(await api<Proxy>('/proxy?refresh=true')), []);
|
||
useEffect(() => { load().catch(e => notify(e.message, true)); }, [load, notify]);
|
||
async function operate(action: string) { setBusy(true); try { if (action === 'rotate') { setData(await post<Proxy>('/proxy/rotate')); notify('已切换当前路由'); } else if (action === 'refresh') await load(); else { const result = await post<{ output: string; ok: boolean }>('/proxy/manage', { action }); setOutput(result.output); notify(result.ok ? '代理池操作完成' : '代理池返回异常,请查看输出', !result.ok); await load(); } } catch (e) { notify((e as Error).message, true); } finally { setBusy(false); } }
|
||
return <><PageTitle eyebrow="NETWORK & PROXY" title="代理 IP 池" description="接入现有 proxy_pool,管理可用 HTTPS 代理和当前采集路由。"><button disabled={busy} onClick={() => operate('refresh')}><RefreshCw size={16} />刷新代理</button><button className="primary" disabled={busy} onClick={() => operate('rotate')}><Network size={16} />切换 IP</button></PageTitle><div className="stats-grid proxy-stats"><Stat label="代理池总数" value={data?.counts.count || 0} icon={<Globe2 size={20} />} sub="以代理池 API 返回为准" /><Stat label="HTTPS 代理" value={data?.counts.http_type?.https || 0} icon={<ShieldCheck size={20} />} sub="用于两个 HTTPS 数据源" /><Stat label="可选代理与备用 IP" value={data?.available || 0} icon={<Network size={20} />} sub="连接失败会切换其他候选" /><Stat label="本次隔离代理" value={data?.quarantined || 0} icon={<Pause size={20} />} sub="保留池记录,修改配置可重置" /></div><section className="card route-card"><div><span className={`route-indicator ${data?.fallback ? 'amber' : ''}`} /><div><small>当前网络路由 · {data ? modeName(data.mode) : '加载中'}</small><h2>{data?.route === 'direct' ? '直接连接' : data?.route === 'pending' ? '等待可用代理' : data?.route || '正在读取代理池…'}</h2><p>{data?.fallback ? '代理池暂无可用 IP,优先代理模式已回退直连。' : '登录、招生目录和历年考情共用该路由。'}</p></div></div><Badge tone={data?.fallback ? 'amber' : 'green'}>{data?.fallback ? '直连回退' : data?.active_proxy ? '代理已选择' : '当前策略'}</Badge></section>{data?.error && <div className="info-box warning">{data.error}</div>}<div className="proxy-grid"><section className="card"><div className="card-title"><h2>可用代理列表</h2><Badge>{data?.proxies.length || 0} 个候选</Badge></div><div className="proxy-list">{data?.proxies.length ? data.proxies.map(p => <div key={p.url}><code>{p.url}</code><Badge tone={p.failed ? 'red' : p.active ? 'green' : ''}>{p.failed ? '已隔离' : p.active ? '当前 IP' : '池内可选'}</Badge></div>) : <div className="inline-empty">没有 HTTPS 候选。可启动代理池抓取服务,或在设置中添加备用 IP。</div>}</div></section><section className="card pool-controls"><h2>本机代理池服务</h2><p>通过现有项目的 manage.ps1 控制 Redis、API 与抓取调度器。</p><div className="button-group"><button disabled={busy} onClick={() => operate('start')}><Play size={15} />启动</button><button disabled={busy} onClick={() => operate('status')}>检查状态</button><button disabled={busy} onClick={() => operate('stop')}><Square size={14} />停止</button></div>{busy && <p><Loader2 className="spin" size={16} />正在处理…</p>}{output && <pre className="service-output">{output}</pre>}<div className="info-box">切换 IP 保留原代理;连接失败仅在本次工作台运行中隔离。代理池的持续可用性由其检测服务维护。</div></section></div></>;
|
||
}
|
||
|
||
function SettingsPanel({ notify }: { notify: Notify }) {
|
||
const [config, setConfig] = useState<Config | null>(null), [auth, setAuth] = useState<Auth | null>(null), [backup, setBackup] = useState(''), [cookie, setCookie] = useState(''), [username, setUsername] = useState(''), [password, setPassword] = useState(''), [busy, setBusy] = useState('');
|
||
useEffect(() => { Promise.all([api<Config>('/settings'), api<Auth>('/auth')]).then(([c, a]) => { setConfig(c); setBackup(c.backup_proxies.join('\n')); setAuth(a); }).catch(e => notify(e.message, true)); }, [notify]);
|
||
const browserWaiting = auth && ['opening', 'waiting'].includes(auth.browser_state);
|
||
useEffect(() => { if (!browserWaiting) return; const timer = setInterval(() => api<Auth>('/auth').then(setAuth).catch(() => {}), 2000); return () => clearInterval(timer); }, [browserWaiting]);
|
||
async function save(e: React.FormEvent) { e.preventDefault(); setBusy('save'); try { setConfig(await api<Config>('/settings', { method: 'PUT', body: JSON.stringify({ ...config, backup_proxies: backup.split('\n').filter(Boolean) }) })); notify('网络设置已保存'); } catch (e) { notify((e as Error).message, true); } finally { setBusy(''); } }
|
||
async function authenticate(action: string) { setBusy(action); try { const result = await post<Auth>('/auth/' + action, action === 'cookie' ? { cookie } : action === 'login' ? { username, password } : {}); setAuth(result); notify(action === 'browser' ? result.browser_message : result.message, action === 'check' && !result.valid); } catch (e) { notify((e as Error).message, true); } finally { setBusy(''); if (action === 'cookie') setCookie(''); if (action === 'login') setPassword(''); } }
|
||
function update(key: keyof Config, value: string | number) { setConfig(c => c ? { ...c, [key]: value } : c); }
|
||
return <><PageTitle eyebrow="CONNECTION SETTINGS" title="设置与登录" description="配置本机网络策略,安全保存学信网登录状态。密码不会写入配置或日志。" /><div className="settings-grid"><section className="card"><h2>网络与代理设置</h2>{config ? <form className="form-stack" onSubmit={save}><label>网络策略<select value={config.network_mode} onChange={e => update('network_mode', e.target.value)}><option value="prefer_proxy">优先代理 · 无可用代理时直连</option><option value="proxy_only">严格代理 · 无代理时等待</option><option value="direct">直接连接</option></select></label><label>代理池 API 地址<input value={config.pool_url} onChange={e => update('pool_url', e.target.value)} required /></label><label>代理池项目目录<input value={config.pool_project} onChange={e => update('pool_project', e.target.value)} required /></label><label>备用代理 IP <small>每行一个 IP:端口</small><textarea rows={3} value={backup} onChange={e => setBackup(e.target.value)} placeholder="127.0.0.1:7890" /></label><div className="three-fields"><label>请求间隔(秒)<input type="number" min="0.3" max="60" step="0.1" value={config.request_interval} onChange={e => update('request_interval', Number(e.target.value))} /></label><label>超时(秒)<input type="number" min="5" max="120" value={config.timeout} onChange={e => update('timeout', Number(e.target.value))} /></label><label>重试次数<input type="number" min="1" max="6" value={config.retries} onChange={e => update('retries', Number(e.target.value))} /></label></div><button className="primary" disabled={!!busy}>{busy === 'save' ? <Loader2 className="spin" size={16} /> : <Check size={16} />}保存设置</button></form> : <div className="loading-area"><Loader2 className="spin" /></div>}</section><section className="card auth-card"><div className="card-title"><h2>学信网登录</h2><Badge tone={auth?.valid ? 'green' : 'amber'}>{auth?.valid ? '已验证' : auth?.saved ? '已保存,待验证' : '尚未登录'}</Badge></div><p>{auth?.message}</p><div className="browser-login"><div><Globe2 size={22} /><div><b>在 Edge 中完成登录</b><small>支持验证码,自动获取并加密保存 Cookie</small></div></div><button className="primary" disabled={!!busy || !!browserWaiting} onClick={() => authenticate('browser')}>打开登录窗口 <ArrowUpRight size={16} /></button>{auth?.browser_message && <p className="form-hint">{auth.browser_message}</p>}</div><details><summary>粘贴已有 Cookie</summary><div className="form-stack"><label>Cookie 请求头<textarea rows={3} value={cookie} onChange={e => setCookie(e.target.value)} placeholder="JSESSIONID=…; …" autoComplete="off" /></label><button disabled={!!busy || !cookie} onClick={() => authenticate('cookie')}>加密保存 Cookie</button><p className="form-hint">在已登录研招网页的开发者工具 → Network 中复制目录请求的 Cookie。保存后输入框会清空。</p></div></details><details><summary>使用账号密码登录</summary><div className="form-stack"><label>学信网账号<input value={username} onChange={e => setUsername(e.target.value)} autoComplete="username" /></label><label>密码<input type="password" value={password} onChange={e => setPassword(e.target.value)} autoComplete="off" /></label><button disabled={!!busy || !username || !password} onClick={() => authenticate('login')}>登录并验证</button><p className="form-hint">遇到验证码时使用上方浏览器登录。</p></div></details><div className="button-group auth-actions"><button disabled={!!busy} onClick={() => authenticate('check')}>{busy === 'check' ? <Loader2 className="spin" size={16} /> : <ShieldCheck size={16} />}验证目录访问</button><button disabled={!!busy || !auth?.saved} onClick={() => authenticate('clear')}>清除登录凭据</button></div><div className="info-box">Cookie 由当前 Windows 用户的 DPAPI 加密,保存在项目的本地数据目录中,导出文件不包含凭据。</div></section></div></>;
|
||
}
|