Rework LLM classification around user categories
Move category CRUD into the config route so renames sync historical deals, feed per-user categories into the LLM prompt, cache clients per user, and drop the separate classify route.
This commit is contained in:
@@ -248,6 +248,17 @@ body {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.btn:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
filter: grayscale(0.6);
|
||||
}
|
||||
|
||||
.btn:disabled:hover {
|
||||
opacity: 0.4;
|
||||
filter: grayscale(0.6);
|
||||
}
|
||||
|
||||
/* Form elements */
|
||||
.form-group {
|
||||
margin-bottom: 16px;
|
||||
|
||||
@@ -113,11 +113,6 @@ export async function clearDeals() {
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function getNeedsClassify() {
|
||||
const res = await api.get("/transactions/needs-classify");
|
||||
return res.data;
|
||||
}
|
||||
|
||||
// Transactions
|
||||
export async function getTransactions(params = {}) {
|
||||
const res = await api.get("/transactions", { params });
|
||||
@@ -149,9 +144,12 @@ export async function classifyTransactions(ids) {
|
||||
}
|
||||
|
||||
export async function classifyAll() {
|
||||
const res = await api.post("/transactions/classify-all", null, {
|
||||
timeout: 600000,
|
||||
});
|
||||
const res = await api.post("/transactions/classify-all");
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function getClassifyStatus() {
|
||||
const res = await api.get("/transactions/classify-status");
|
||||
return res.data;
|
||||
}
|
||||
|
||||
@@ -161,10 +159,7 @@ export async function getOverview(params = {}) {
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function getMonthly(months = 12, categories) {
|
||||
const params = { months };
|
||||
if (categories && categories.length > 0)
|
||||
params.categories = categories.join(",");
|
||||
export async function getMonthly(params = {}) {
|
||||
const res = await api.get("/stats/monthly", { params });
|
||||
return res.data;
|
||||
}
|
||||
@@ -207,15 +202,6 @@ export async function updateCategory(id, data) {
|
||||
const res = await api.put(`/config/categories/${id}`, data);
|
||||
return res.data;
|
||||
}
|
||||
export async function reclassifyAffected(ids) {
|
||||
const res = await api.post(
|
||||
"/config/categories/reclassify-affected",
|
||||
{ ids },
|
||||
{ timeout: 300000 },
|
||||
);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export function formatAmount(amount) {
|
||||
if (amount === null || amount === undefined) return "--";
|
||||
const n = Number(amount);
|
||||
|
||||
+136
-39
@@ -1,11 +1,4 @@
|
||||
import React, {
|
||||
useState,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useCallback,
|
||||
} from "react";
|
||||
import { RefreshCcw } from "lucide-react";
|
||||
import React, { useState, useEffect, useMemo } from "react";
|
||||
import {
|
||||
BarChart,
|
||||
Bar,
|
||||
@@ -35,7 +28,41 @@ const COLORS = [
|
||||
"#e11d48",
|
||||
];
|
||||
|
||||
const DEFAULT_UNCHECKED = ["投资理财", "转账红包"];
|
||||
const DEFAULT_UNCHECKED = ["投资理财", "转账红包", "投资赠与"];
|
||||
// 单独成卡片的分类(默认不勾选,仍可在明细表里手动勾选)
|
||||
const GIFT_CATEGORY = "投资赠与";
|
||||
|
||||
// 财年:以每年 2 月 1 日 00:00:00 为结算点
|
||||
// 财年 Y = [Y-02-01 00:00:00, (Y+1)-01-31 23:59:59]
|
||||
const FY_START_MONTH = 2;
|
||||
|
||||
function fiscalYearOf(value) {
|
||||
if (!value) return null;
|
||||
const d =
|
||||
value instanceof Date ? value : new Date(String(value).replace(" ", "T"));
|
||||
if (Number.isNaN(d.getTime())) return null;
|
||||
return d.getMonth() + 1 >= FY_START_MONTH
|
||||
? d.getFullYear()
|
||||
: d.getFullYear() - 1;
|
||||
}
|
||||
|
||||
function fiscalRange(fy) {
|
||||
const y = Number(fy);
|
||||
return {
|
||||
start_date: `${y}-02-01 00:00:00`,
|
||||
end_date: `${y + 1}-01-31 23:59:59`,
|
||||
};
|
||||
}
|
||||
|
||||
function buildFiscalYears(range) {
|
||||
if (!range?.min_date || !range?.max_date) return [];
|
||||
const lo = fiscalYearOf(range.min_date);
|
||||
const hi = fiscalYearOf(range.max_date);
|
||||
if (lo === null || hi === null) return [];
|
||||
const years = [];
|
||||
for (let y = hi; y >= lo; y--) years.push(y);
|
||||
return years;
|
||||
}
|
||||
|
||||
const RADIAN = Math.PI / 180;
|
||||
function renderPieLabel({ cx, cy, midAngle, outerRadius, percent, category }) {
|
||||
@@ -90,12 +117,50 @@ export default function Dashboard() {
|
||||
const [monthly, setMonthly] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [checked, setChecked] = useState(() => new Set());
|
||||
const allRef = useRef(null);
|
||||
const [fy, setFy] = useState(null); // number=财年 | "all" | null=未初始化
|
||||
const [fyOptions, setFyOptions] = useState([]);
|
||||
|
||||
// 初始化:先取全量日期范围,枚举可选财年并默认选最新一个
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
(async () => {
|
||||
try {
|
||||
const ov = await getOverview();
|
||||
const years = buildFiscalYears(ov?.dateRange);
|
||||
setFyOptions(years);
|
||||
setFy(years.length ? years[0] : "all");
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
})();
|
||||
}, []);
|
||||
|
||||
// 财年变化 -> 重新拉取总览
|
||||
useEffect(() => {
|
||||
if (fy === null) return;
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const params = fy === "all" ? {} : fiscalRange(fy);
|
||||
const ov = await getOverview(params);
|
||||
if (cancelled) return;
|
||||
setRaw(ov);
|
||||
const allCats = new Set(
|
||||
(ov?.categoryBreakdown || []).map((c) => c.category),
|
||||
);
|
||||
for (const c of DEFAULT_UNCHECKED) allCats.delete(c);
|
||||
setChecked(allCats);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
if (!cancelled) setLoading(false);
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [fy]);
|
||||
|
||||
// 勾选分类 / 财年变化 -> 重新拉取月度趋势
|
||||
useEffect(() => {
|
||||
if (!raw) return;
|
||||
const cats = [...checked];
|
||||
@@ -103,25 +168,10 @@ export default function Dashboard() {
|
||||
setMonthly([]);
|
||||
return;
|
||||
}
|
||||
getMonthly(12, cats).then(setMonthly).catch(console.error);
|
||||
}, [checked, raw]);
|
||||
|
||||
async function loadData() {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [ov, mo] = await Promise.all([getOverview(), getMonthly(12)]);
|
||||
setRaw(ov);
|
||||
setMonthly(mo);
|
||||
const allCats = new Set(
|
||||
(ov?.categoryBreakdown || []).map((c) => c.category),
|
||||
);
|
||||
for (const c of DEFAULT_UNCHECKED) allCats.delete(c);
|
||||
setChecked(allCats);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
setLoading(false);
|
||||
}
|
||||
const params = { categories: cats.join(",") };
|
||||
if (fy !== "all" && fy != null) Object.assign(params, fiscalRange(fy));
|
||||
getMonthly(params).then(setMonthly).catch(console.error);
|
||||
}, [checked, raw, fy]);
|
||||
|
||||
function toggleCat(cat) {
|
||||
setChecked((prev) => {
|
||||
@@ -147,12 +197,26 @@ export default function Dashboard() {
|
||||
if (!raw) return null;
|
||||
const cb = raw.categoryBreakdown || [];
|
||||
const cs = raw.categoryStats || [];
|
||||
// 勾选分类参与统计(投资赠与默认不勾选,用户想算进去可手动勾)
|
||||
const sel = cb.filter((c) => checked.has(c.category));
|
||||
const totalIncome = sel.reduce((s, c) => s + c.total_income, 0);
|
||||
const totalExpense = sel.reduce((s, c) => s + c.total_expense, 0);
|
||||
const dealCount = sel.reduce((s, c) => s + c.deal_count, 0);
|
||||
const pieStats = cs.filter((c) => checked.has(c.category));
|
||||
return { sel, totalIncome, totalExpense, dealCount, pieStats };
|
||||
|
||||
// 投资赠与单独一张卡片:净额 = 收入 - 支出
|
||||
const gift = cb.find((c) => c.category === GIFT_CATEGORY) || null;
|
||||
const giftNet = gift ? gift.total_income - gift.total_expense : 0;
|
||||
|
||||
return {
|
||||
sel,
|
||||
totalIncome,
|
||||
totalExpense,
|
||||
dealCount,
|
||||
pieStats,
|
||||
gift,
|
||||
giftNet,
|
||||
};
|
||||
}, [raw, checked]);
|
||||
|
||||
const ov = raw?.overview || {};
|
||||
@@ -173,15 +237,39 @@ export default function Dashboard() {
|
||||
>
|
||||
<div>
|
||||
<h2>📊 财务仪表盘</h2>
|
||||
<p>勾选分类后,所有统计基于选中项计算</p>
|
||||
<p>
|
||||
勾选分类后,所有统计基于选中项计算
|
||||
{fy && fy !== "all"
|
||||
? ` · 财年 ${fy}(${fy}-02-01 ~ ${Number(fy) + 1}-01-31)`
|
||||
: " · 全部时间"}
|
||||
</p>
|
||||
</div>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: 8 }}>
|
||||
<span style={{ fontSize: 13, color: "var(--text-secondary)" }}>
|
||||
财年
|
||||
</span>
|
||||
<select
|
||||
className="form-select"
|
||||
style={{ width: 130 }}
|
||||
value={fy ?? ""}
|
||||
onChange={(e) =>
|
||||
setFy(e.target.value === "all" ? "all" : Number(e.target.value))
|
||||
}
|
||||
disabled={fy === null}
|
||||
title={
|
||||
fy && fy !== "all"
|
||||
? `${fy}-02-01 ~ ${Number(fy) + 1}-01-31`
|
||||
: "全部时间"
|
||||
}
|
||||
>
|
||||
{fyOptions.map((y) => (
|
||||
<option key={y} value={y}>
|
||||
{y} 财年
|
||||
</option>
|
||||
))}
|
||||
<option value="all">全部</option>
|
||||
</select>
|
||||
</div>
|
||||
<button
|
||||
className="btn btn-secondary"
|
||||
onClick={loadData}
|
||||
style={{ display: "inline-flex", alignItems: "center", gap: 6 }}
|
||||
>
|
||||
<RefreshCcw size={14} /> 刷新
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="stats-grid">
|
||||
@@ -199,6 +287,15 @@ export default function Dashboard() {
|
||||
</div>
|
||||
<div className="stat-sub">{checked.size} 个分类合计</div>
|
||||
</div>
|
||||
<div className="stat-card">
|
||||
<div className="stat-label">🎁 投资赠与</div>
|
||||
<div
|
||||
className={`stat-value ${(derived?.giftNet ?? 0) >= 0 ? "income" : "expense"}`}
|
||||
>
|
||||
{formatAmount(derived?.giftNet ?? 0)}
|
||||
</div>
|
||||
<div className="stat-sub">净额,默认不勾选</div>
|
||||
</div>
|
||||
<div className="stat-card">
|
||||
<div className="stat-label">📈 净收支</div>
|
||||
<div
|
||||
|
||||
@@ -63,7 +63,8 @@ export default function Review() {
|
||||
min_amount: 100,
|
||||
limit: PAGE_SIZE,
|
||||
page: p || 1,
|
||||
sort_by: "amount",
|
||||
// 按金额绝对值从大到小排序(收/支混排)
|
||||
sort_by: "abs_amount",
|
||||
sort_order: "DESC",
|
||||
};
|
||||
if (!showReviewed) params.reviewed = 0;
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
updateCategory,
|
||||
createCategory,
|
||||
deleteCategory,
|
||||
reclassifyAffected,
|
||||
classifyTransactions,
|
||||
} from "../hooks/useApi";
|
||||
|
||||
export default function SettingsPage() {
|
||||
@@ -122,7 +122,7 @@ export default function SettingsPage() {
|
||||
setReclassifying(true);
|
||||
setReclassifyMsg(null);
|
||||
try {
|
||||
const result = await reclassifyAffected(ids);
|
||||
const result = await classifyTransactions(ids);
|
||||
setReclassifyMsg({
|
||||
type: "success",
|
||||
text: `重分类完成!${result.classified} 条交易已重新分类(来源: ${result.source === "llm" ? "AI" : "规则匹配"})。`,
|
||||
@@ -378,7 +378,18 @@ export default function SettingsPage() {
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<strong>{cat.name}</strong>
|
||||
<>
|
||||
<strong>{cat.name}</strong>
|
||||
{cat.is_locked ? (
|
||||
<span
|
||||
className="tag tag-matched"
|
||||
style={{ marginLeft: 6, fontSize: 11 }}
|
||||
title="内置分类,不可修改/删除"
|
||||
>
|
||||
🔒 内置
|
||||
</span>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
@@ -439,6 +450,8 @@ export default function SettingsPage() {
|
||||
<div style={{ display: "flex", gap: 6 }}>
|
||||
<button
|
||||
className="btn btn-secondary btn-sm"
|
||||
disabled={!!cat.is_locked}
|
||||
title={cat.is_locked ? "内置分类不可修改" : "编辑"}
|
||||
onClick={() =>
|
||||
setEditingCat({
|
||||
...cat,
|
||||
@@ -452,6 +465,8 @@ export default function SettingsPage() {
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-danger btn-sm"
|
||||
disabled={!!cat.is_locked}
|
||||
title={cat.is_locked ? "内置分类不可删除" : "删除"}
|
||||
onClick={() => handleDeleteCategory(cat.id, cat.name)}
|
||||
>
|
||||
<Trash2 size={12} />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
import React, { useState, useEffect, useRef } from "react";
|
||||
import {
|
||||
RotateCcw,
|
||||
Link2,
|
||||
@@ -17,9 +17,9 @@ import {
|
||||
getDeals,
|
||||
updateDeal,
|
||||
clearDeals,
|
||||
getNeedsClassify,
|
||||
runReconciliation,
|
||||
classifyTransactions,
|
||||
classifyAll,
|
||||
getClassifyStatus,
|
||||
formatAmount,
|
||||
SOURCE_TYPE_MAP,
|
||||
getCategories,
|
||||
@@ -80,6 +80,8 @@ export default function Transactions() {
|
||||
const [clearConfirm, setClearConfirm] = useState(false);
|
||||
const [editingDeal, setEditingDeal] = useState(null);
|
||||
const [dealFilters, setDealFilters] = useState({ ...DEAL_FILTER_DEFAULT });
|
||||
const classifyPollRef = useRef(null);
|
||||
const reloadRef = useRef(null);
|
||||
|
||||
/* sort helpers */
|
||||
function dealToggleSort(field) {
|
||||
@@ -141,38 +143,66 @@ export default function Transactions() {
|
||||
setToast({ message: msg, type, key: Date.now() });
|
||||
}
|
||||
|
||||
/* restore classify progress */
|
||||
useEffect(() => {
|
||||
const saved = sessionStorage.getItem("classifyTask");
|
||||
if (!saved) return;
|
||||
const task = JSON.parse(saved);
|
||||
if (Date.now() - task.ts > 300000) {
|
||||
sessionStorage.removeItem("classifyTask");
|
||||
return;
|
||||
function stopClassifyPoll() {
|
||||
if (classifyPollRef.current) {
|
||||
clearInterval(classifyPollRef.current);
|
||||
classifyPollRef.current = null;
|
||||
}
|
||||
setClassifying(true);
|
||||
setClassifyProgress(task.progress || 0);
|
||||
const poll = setInterval(async () => {
|
||||
}
|
||||
|
||||
// 轮询服务端全量分类进度
|
||||
function pollClassifyStatus() {
|
||||
const tick = async () => {
|
||||
try {
|
||||
const { total } = await getNeedsClassify();
|
||||
const p =
|
||||
task.total > 0
|
||||
? Math.round(((task.total - total) / task.total) * 100)
|
||||
: 100;
|
||||
setClassifyProgress(Math.min(Math.max(p, 0), 100));
|
||||
if (total <= 0 || p >= 100) {
|
||||
clearInterval(poll);
|
||||
const s = await getClassifyStatus();
|
||||
if (s.running) {
|
||||
setClassifying(true);
|
||||
setClassifyProgress(
|
||||
s.total ? Math.min(100, Math.round((s.done / s.total) * 100)) : 0,
|
||||
);
|
||||
} else {
|
||||
stopClassifyPoll();
|
||||
setClassifying(false);
|
||||
sessionStorage.removeItem("classifyTask");
|
||||
loadTransactions();
|
||||
setClassifyProgress(100);
|
||||
showToast("分类完成!", "success");
|
||||
if (reloadRef.current) reloadRef.current();
|
||||
}
|
||||
} catch (e) {
|
||||
clearInterval(poll);
|
||||
stopClassifyPoll();
|
||||
setClassifying(false);
|
||||
sessionStorage.removeItem("classifyTask");
|
||||
}
|
||||
}, 10000);
|
||||
return () => clearInterval(poll);
|
||||
};
|
||||
stopClassifyPoll();
|
||||
classifyPollRef.current = setInterval(tick, 2000);
|
||||
tick();
|
||||
}
|
||||
|
||||
/* 保持 reload 回调最新,避免轮询里拿到旧 filters */
|
||||
useEffect(() => {
|
||||
reloadRef.current = () => {
|
||||
loadTransactions();
|
||||
loadDeals(dealFilters);
|
||||
};
|
||||
});
|
||||
|
||||
/* 恢复全量分类进度:任务在服务端后台执行,刷新页面后继续显示 */
|
||||
useEffect(() => {
|
||||
let stopped = false;
|
||||
(async () => {
|
||||
try {
|
||||
const s = await getClassifyStatus();
|
||||
if (stopped || !s.running) return;
|
||||
setClassifying(true);
|
||||
setClassifyProgress(
|
||||
s.total ? Math.min(100, Math.round((s.done / s.total) * 100)) : 0,
|
||||
);
|
||||
pollClassifyStatus();
|
||||
} catch (e) {}
|
||||
})();
|
||||
return () => {
|
||||
stopped = true;
|
||||
stopClassifyPoll();
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -277,66 +307,21 @@ export default function Transactions() {
|
||||
}
|
||||
|
||||
async function handleClassifyAll() {
|
||||
setClassifying(true);
|
||||
setClassifyProgress(0);
|
||||
sessionStorage.setItem(
|
||||
"classifyTask",
|
||||
JSON.stringify({ total: 0, progress: 0, ts: Date.now() }),
|
||||
);
|
||||
try {
|
||||
const { ids, total } = await getNeedsClassify();
|
||||
if (!ids.length) {
|
||||
const { total } = await classifyAll();
|
||||
if (!total) {
|
||||
showToast("所有交易分类均有效!", "info");
|
||||
setClassifying(false);
|
||||
sessionStorage.removeItem("classifyTask");
|
||||
return;
|
||||
}
|
||||
sessionStorage.setItem(
|
||||
"classifyTask",
|
||||
JSON.stringify({ total, progress: 0, ts: Date.now() }),
|
||||
);
|
||||
// 分批并行处理(每批30条,最多2批同时进行)
|
||||
const B = 30;
|
||||
const CONCURRENCY = 4;
|
||||
const batches = [];
|
||||
for (let i = 0; i < ids.length; i += B) {
|
||||
batches.push(ids.slice(i, i + B));
|
||||
}
|
||||
|
||||
let done = 0;
|
||||
let llmCount = 0;
|
||||
let rulesCount = 0;
|
||||
|
||||
for (let i = 0; i < batches.length; i += CONCURRENCY) {
|
||||
const chunk = batches.slice(i, i + CONCURRENCY);
|
||||
const results = await Promise.all(
|
||||
chunk.map((batch) => classifyTransactions(batch)),
|
||||
);
|
||||
for (const r of results) {
|
||||
done += r.classified || 0;
|
||||
if (r.source === "llm") llmCount += r.classified || 0;
|
||||
else rulesCount += r.classified || 0;
|
||||
}
|
||||
const pct = Math.round((done / total) * 100);
|
||||
setClassifyProgress(pct);
|
||||
sessionStorage.setItem(
|
||||
"classifyTask",
|
||||
JSON.stringify({ total, progress: pct, ts: Date.now() }),
|
||||
);
|
||||
}
|
||||
|
||||
sessionStorage.removeItem("classifyTask");
|
||||
const detail =
|
||||
llmCount > 0
|
||||
? `(LLM: ${llmCount},规则: ${rulesCount})`
|
||||
: `(规则匹配: ${rulesCount})`;
|
||||
showToast(`分类完成!共处理 ${total} 笔 ${detail}`, "success");
|
||||
loadTransactions();
|
||||
setClassifying(true);
|
||||
setClassifyProgress(0);
|
||||
pollClassifyStatus();
|
||||
} catch (e) {
|
||||
sessionStorage.removeItem("classifyTask");
|
||||
showToast("分类失败: " + (e.response?.data?.error || e.message), "error");
|
||||
showToast(
|
||||
"分类启动失败: " + (e.response?.data?.error || e.message),
|
||||
"error",
|
||||
);
|
||||
}
|
||||
setClassifying(false);
|
||||
}
|
||||
|
||||
/* ============================== RENDER ============================== */
|
||||
|
||||
Reference in New Issue
Block a user