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,
PoolServiceStatus,
PoolManageResult,
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",
"waiting_source",
];
function Badge({
children,
tone = "",
}: {
children: ReactNode;
tone?: string;
}) {
return {children};
}
function Empty({ title, children }: { title: string; children?: ReactNode }) {
return (
);
}
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 (
e.stopPropagation()}
>
{title}
{children}
);
}
function MajorInput({
majors,
value,
onChange,
label = "专业代码",
required = false,
}: {
majors: Major[];
value: string;
onChange: (value: string) => void;
label?: string;
required?: boolean;
}) {
const id = useId();
return (
);
}
function Stat({
label,
value,
icon,
sub,
}: {
label: string;
value: number;
icon: ReactNode;
sub: string;
}) {
return (
{label}
{icon}
{Number(value || 0).toLocaleString()}
{sub}
);
}
export default function App() {
const [tab, setTab] = useState("overview");
const [overview, setOverview] = useState(null);
const [majors, setMajors] = useState([]);
const [version, setVersion] = useState(0);
const [notice, setNotice] = useState<{
message: string;
error: boolean;
} | null>(null);
const notify = useCallback(
(message, error = false) => setNotice({ message, error }),
[],
);
const refresh = useCallback(() => setVersion((v) => v + 1), []);
useEffect(() => {
const controller = new AbortController();
Promise.all([
api("/overview", { signal: controller.signal }),
api("/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 (
{tab === "overview" && }
{tab === "workspace" && }
{tab === "jobs" && }
{tab === "proxy" && }
{tab === "settings" && }
{notice && (
{notice.error ? : }
{notice.message}
)}
);
}
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 (
{eyebrow}
{title}
{description}
{children}
);
}
function Dashboard({ overview: o, go }: Shared & { go: (tab: Tab) => void }) {
const [jobs, setJobs] = useState([]);
useEffect(() => {
const controller = new AbortController();
api("/jobs", { signal: controller.signal })
.then(setJobs)
.catch(() => {});
return () => controller.abort();
}, []);
return (
<>
}
sub={`另有 ${o?.indexed_schools || 0} 所院校公开索引`}
/>
}
sub="按年份、方向和科目组合保存"
/>
}
sub="保留专业、学科与门类口径"
/>
}
sub="在工作区筛选与横向对比"
/>
开始你的研究
一个工作区,两种数据来源
先建立招生目录,再补充历年分数线和计划。已有数据也可以直接导入,继续筛选、收藏与对比。
01
连接账号与代理池
登录学信网,选择当前网络策略
02
选择年份、地区和专业
按省采集,也可覆盖全国 31 个省级地区
03
把数据变成择校清单
多条件筛选、历史趋势和 Excel 导出
{jobs.length ? (
{jobs.slice(0, 4).map((j) => (
{modeName(j.params.mode)} · {j.params.year} 年
{j.message}
{statusName(j.status)}
{j.completed_units} 个完成单元
))}
) : (
还没有采集任务
创建一个任务,或在院校工作区导入 YAM / yzw 的已有数据。
)}
>
);
}
function Workspace({ overview, majors, notify, refresh }: Shared) {
const [filters, setFilters] = useState({ sort: "year" });
const [page, setPage] = useState(1);
const [rows, setRows] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(true);
const [localVersion, setLocalVersion] = useState(0);
const [selected, setSelected] = useState([]);
const [compare, setCompare] = useState(false);
const [detail, setDetail] = useState(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 (
<>
{more && (
change("major_code", v)}
/>
)}
{total.toLocaleString()} 条记录{" "}
· 人数保留原文,科目组合分别展示
{loading && }
{rows.length ? (
| 对比 |
院校 / 专业 |
院系 / 方向 |
初试科目 |
招生人数 |
最近参考线 |
年份 / 来源 |
收藏 |
{rows.map((row) => (
|
s.id === row.id)}
onChange={() => toggleSelected(row)}
/>
|
{row.major_code} · {display(row.major_name)}
{row.province && {row.province}}
{row.level && {row.level}}
{row.study_mode && {row.study_mode}}
|
{display(row.department_name)}
{display(row.direction)}
|
{row.subjects.some(Boolean) ? (
row.subjects.map((s, i) => s && {s} )
) : (
未提供
)}
|
{display(row.quota)}
{row.quota_text || "来源未提供人数"}
|
{row.score_total !== null ? (
<>
{row.score_total}
{row.score_year} · {scopeName(row.score_scope)}
>
) : (
未提供
)}
|
{row.year}
{row.source}
{!row.year_verified && (
年份由文件指定
)}
|
|
))}
) : !loading ? (
可以调整筛选条件,或导入 YAM / yzw 数据、创建新的采集任务。
) : (
正在读取本地数据…
)}
第 {page} / {Math.max(1, Math.ceil(total / 30))} 页 · 每页 30 条
{selected.length > 0 && (
已选 {selected.length} 条记录
{selected.map((s) => s.school_name).join(" / ")}
)}
{detail !== null && (
setDetail(null)} notify={notify} />
)}
{compare && (
setCompare(false)} />
)}
{importing && (
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(null),
[year, setYear] = useState(""),
[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;
indexed_schools: number;
}>("/import", {
method: "POST",
body,
});
notify(
`已导入 ${result.records} 条目录/计划、${result.scores} 条分数线${result.indexed_schools ? `,${result.indexed_schools} 所院校索引` : ""}`,
);
done();
close();
} catch (e) {
notify((e as Error).message, true);
} finally {
setBusy(false);
}
}
return (
);
}
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) => {s}
),
],
["人数原文", (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 (
每列是一条独立方向/科目组合。专业人数可能重复展示,不能按列相加。
| 比较项 |
{rows.map((r) => (
{r.school_name}
{r.year} 年
|
))}
{fields.map(([label, field]) => (
| {label} |
{rows.map((r) => (
{field(r)} |
))}
))}
);
}
function Detail({
rid,
close,
notify,
}: {
rid: number;
close: () => void;
notify: Notify;
}) {
const [data, setData] = useState(null);
useEffect(() => {
const controller = new AbortController();
api(`/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 (
{data && r ? (
{r.year} 年
{r.province || "地区未提供"}
{r.source}
{r.year_verified ? "来源年份已核实" : "年份由导入文件指定"}
{/^https:\/\//.test(r.source_url) && (
查看来源
)}
{[
["院系", 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]) => (
{k}
{display(v)}
))}
{r.subjects.filter(Boolean).map((s, i) => (
{s}
))}
{r.remarks &&
{r.remarks}
}
{r.reference_books?.length ? (
参考书:{r.reference_books.join(";")}
) : null}
历年分数线
| 年份 |
口径 |
总分 |
政治 |
外语 |
业务一 |
业务二 |
备注 |
{data.scores.map((s, i) => (
| {s.year} |
{scopeName(s.scope)}
{s.raw_code}
|
{display(s.total)} |
{display(s.politics)} |
{display(s.english)} |
{display(s.special_one)} |
{display(s.special_two)} |
{s.note || "—"} |
))}
历年招生计划 / 目录快照
| 年份 |
方向 |
招生人数原文 |
科目组合 |
来源 |
{data.plans.map((p, i) => (
| {p.year} |
{display(p.direction)} |
{display(p.quota_text)} |
{p.subjects.filter(Boolean).join(" / ") || "未提供"}
|
{p.source} |
))}
) : (
正在读取…
)}
);
}
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 (
暂未获取该院系的历史分数线。采集历年考情后可查看趋势。
);
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 (
{groups.map((g, i) => (
{g.label}
))}
);
}
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([]),
[logs, setLogs] = useState([]),
[selected, setSelected] = useState(""),
[busy, setBusy] = useState(false),
[config, setConfig] = useState(null);
const load = useCallback(async () => {
const data = await api("/jobs");
setJobs(data);
setSelected((s) => s || data[0]?.id || "");
}, []);
useEffect(() => {
load().catch((e) => notify(e.message, true));
api("/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(`/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("/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 (
<>
{config ? modeName(config.network_mode) : "读取网络策略…"}
任务记录
{jobs.length ? (
jobs.map((j) => (
))
) : (
还没有任务。填写左侧条件开始采集。
)}
运行日志
{job && (
{activeStates.includes(job.status) && (
)}
{resumeStates.includes(job.status) && (
)}
{!["completed", "cancelled"].includes(job.status) && (
)}
)}
{job ? (
<>
状态 {statusName(job.status)}
完成单元 {job.completed_units}
保存记录 {job.records}
失败单元 {job.errors}
{job.message}
{logs.map((l) => (
{l.message}
))}
{!logs.length &&
暂无日志}
>
) : (
选择一个任务查看进度和日志。
)}
>
);
}
function ProxyPanel({ notify }: { notify: Notify }) {
const [data, setData] = useState(null),
[services, setServices] = useState(null),
[busy, setBusy] = useState(false),
[output, setOutput] = useState("");
const load = useCallback(
async () => setData(await api("/proxy?refresh=true")),
[],
);
const loadServices = useCallback(
async () => setServices(await api("/proxy/services")),
[],
);
useEffect(() => {
Promise.all([load(), loadServices()]).catch((e) => notify(e.message, true));
}, [load, loadServices, notify]);
async function operate(action: string) {
setBusy(true);
try {
if (action === "rotate") {
setData(await post("/proxy/rotate"));
notify("已切换当前路由");
} else if (action === "refresh")
await Promise.all([load(), loadServices()]);
else {
const result = await post("/proxy/manage", {
action,
});
setServices(result.status);
setOutput(action === "status" ? "" : result.output);
notify(
result.ok
? result.message
: result.status.warning
? "服务操作受限,请查看下方说明"
: result.message,
!result.ok,
);
if (result.changed) await load();
}
} catch (e) {
notify((e as Error).message, true);
} finally {
setBusy(false);
}
}
return (
<>
}
sub="以代理池 API 返回为准"
/>
}
sub="用于两个 HTTPS 数据源"
/>
}
sub="连接失败会切换其他候选"
/>
}
sub="保留池记录,修改配置可重置"
/>
当前网络路由 · {data ? modeName(data.mode) : "加载中"}
{data?.route === "direct"
? "直接连接"
: data?.route === "pending"
? "等待可用代理"
: data?.route || "正在读取代理池…"}
{data?.fallback
? "代理池暂无可用 IP,优先代理模式已回退直连。"
: "登录、招生目录和历年考情共用该路由。"}
{data?.fallback
? "直连回退"
: data?.active_proxy
? "代理已选择"
: "当前策略"}
{data?.error && {data.error}
}
可用代理列表
{data?.proxies.length || 0} 个候选
{data?.proxies.length ? (
data.proxies.map((p) => (
{p.url}
{p.failed ? "已隔离" : p.active ? "当前 IP" : "池内可选"}
))
) : (
没有 HTTPS 候选。可启动代理池抓取服务,或在设置中添加备用 IP。
)}
本机代理池服务
{services
? services.api_ready
? "API 正常"
: "API 未响应"
: "正在查询"}
查看 API、代理抓取与检测、Redis 的运行状态,管理本机服务。
{services && (
)}
{busy && (
正在处理…
)}
{services?.warning && (
{services.warning}
{services.admin_command &&
{services.admin_command}}
)}
{output && (
查看操作输出
{output}
)}
切换 IP
保留原代理;连接失败仅在本次工作台运行中隔离。代理池的持续可用性由其检测服务维护。
>
);
}
function SettingsPanel({ notify }: { notify: Notify }) {
const [config, setConfig] = useState(null),
[auth, setAuth] = useState(null),
[backup, setBackup] = useState(""),
[cookie, setCookie] = useState(""),
[username, setUsername] = useState(""),
[password, setPassword] = useState(""),
[busy, setBusy] = useState("");
useEffect(() => {
Promise.all([api("/settings"), api("/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 (busy) return;
let active = true;
const refreshAuth = () =>
api("/auth")
.then((result) => {
if (active) setAuth(result);
})
.catch(() => {});
const timer = setInterval(refreshAuth, 2000);
window.addEventListener("focus", refreshAuth);
return () => {
active = false;
clearInterval(timer);
window.removeEventListener("focus", refreshAuth);
};
}, [busy]);
async function save(e: React.FormEvent) {
e.preventDefault();
setBusy("save");
try {
setConfig(
await api("/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/" + 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 (
<>
网络与代理设置
{config ? (
) : (
)}
学信网登录
{auth?.valid
? "已验证"
: auth?.state === "captcha_required"
? "需人工验证"
: auth?.state === "login_required"
? "需重新登录"
: auth?.saved
? "已保存,待验证"
: "尚未登录"}
{auth?.message}
{auth?.checked_at && (
最近检查:
{new Date(auth.checked_at).toLocaleString("zh-CN", {
hour12: false,
})}
)}
在 Edge 中完成登录
支持验证码,自动获取并加密保存 Cookie
{auth?.browser_message && (
{auth.browser_message}
)}
粘贴已有 Cookie
在已登录研招网页的开发者工具 → Network 中复制目录请求的
Cookie。保存后输入框会清空。
使用账号密码登录
Cookie 由当前 Windows 用户的 DPAPI
加密,保存在项目的本地数据目录中,导出文件不包含凭据。
>
);
}