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;
|
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 elements */
|
||||||
.form-group {
|
.form-group {
|
||||||
margin-bottom: 16px;
|
margin-bottom: 16px;
|
||||||
|
|||||||
@@ -113,11 +113,6 @@ export async function clearDeals() {
|
|||||||
return res.data;
|
return res.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getNeedsClassify() {
|
|
||||||
const res = await api.get("/transactions/needs-classify");
|
|
||||||
return res.data;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Transactions
|
// Transactions
|
||||||
export async function getTransactions(params = {}) {
|
export async function getTransactions(params = {}) {
|
||||||
const res = await api.get("/transactions", { params });
|
const res = await api.get("/transactions", { params });
|
||||||
@@ -149,9 +144,12 @@ export async function classifyTransactions(ids) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function classifyAll() {
|
export async function classifyAll() {
|
||||||
const res = await api.post("/transactions/classify-all", null, {
|
const res = await api.post("/transactions/classify-all");
|
||||||
timeout: 600000,
|
return res.data;
|
||||||
});
|
}
|
||||||
|
|
||||||
|
export async function getClassifyStatus() {
|
||||||
|
const res = await api.get("/transactions/classify-status");
|
||||||
return res.data;
|
return res.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,10 +159,7 @@ export async function getOverview(params = {}) {
|
|||||||
return res.data;
|
return res.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getMonthly(months = 12, categories) {
|
export async function getMonthly(params = {}) {
|
||||||
const params = { months };
|
|
||||||
if (categories && categories.length > 0)
|
|
||||||
params.categories = categories.join(",");
|
|
||||||
const res = await api.get("/stats/monthly", { params });
|
const res = await api.get("/stats/monthly", { params });
|
||||||
return res.data;
|
return res.data;
|
||||||
}
|
}
|
||||||
@@ -207,15 +202,6 @@ export async function updateCategory(id, data) {
|
|||||||
const res = await api.put(`/config/categories/${id}`, data);
|
const res = await api.put(`/config/categories/${id}`, data);
|
||||||
return res.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) {
|
export function formatAmount(amount) {
|
||||||
if (amount === null || amount === undefined) return "--";
|
if (amount === null || amount === undefined) return "--";
|
||||||
const n = Number(amount);
|
const n = Number(amount);
|
||||||
|
|||||||
+136
-39
@@ -1,11 +1,4 @@
|
|||||||
import React, {
|
import React, { useState, useEffect, useMemo } from "react";
|
||||||
useState,
|
|
||||||
useEffect,
|
|
||||||
useMemo,
|
|
||||||
useRef,
|
|
||||||
useCallback,
|
|
||||||
} from "react";
|
|
||||||
import { RefreshCcw } from "lucide-react";
|
|
||||||
import {
|
import {
|
||||||
BarChart,
|
BarChart,
|
||||||
Bar,
|
Bar,
|
||||||
@@ -35,7 +28,41 @@ const COLORS = [
|
|||||||
"#e11d48",
|
"#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;
|
const RADIAN = Math.PI / 180;
|
||||||
function renderPieLabel({ cx, cy, midAngle, outerRadius, percent, category }) {
|
function renderPieLabel({ cx, cy, midAngle, outerRadius, percent, category }) {
|
||||||
@@ -90,12 +117,50 @@ export default function Dashboard() {
|
|||||||
const [monthly, setMonthly] = useState([]);
|
const [monthly, setMonthly] = useState([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [checked, setChecked] = useState(() => new Set());
|
const [checked, setChecked] = useState(() => new Set());
|
||||||
const allRef = useRef(null);
|
const [fy, setFy] = useState(null); // number=财年 | "all" | null=未初始化
|
||||||
|
const [fyOptions, setFyOptions] = useState([]);
|
||||||
|
|
||||||
|
// 初始化:先取全量日期范围,枚举可选财年并默认选最新一个
|
||||||
useEffect(() => {
|
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(() => {
|
useEffect(() => {
|
||||||
if (!raw) return;
|
if (!raw) return;
|
||||||
const cats = [...checked];
|
const cats = [...checked];
|
||||||
@@ -103,25 +168,10 @@ export default function Dashboard() {
|
|||||||
setMonthly([]);
|
setMonthly([]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
getMonthly(12, cats).then(setMonthly).catch(console.error);
|
const params = { categories: cats.join(",") };
|
||||||
}, [checked, raw]);
|
if (fy !== "all" && fy != null) Object.assign(params, fiscalRange(fy));
|
||||||
|
getMonthly(params).then(setMonthly).catch(console.error);
|
||||||
async function loadData() {
|
}, [checked, raw, fy]);
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
function toggleCat(cat) {
|
function toggleCat(cat) {
|
||||||
setChecked((prev) => {
|
setChecked((prev) => {
|
||||||
@@ -147,12 +197,26 @@ export default function Dashboard() {
|
|||||||
if (!raw) return null;
|
if (!raw) return null;
|
||||||
const cb = raw.categoryBreakdown || [];
|
const cb = raw.categoryBreakdown || [];
|
||||||
const cs = raw.categoryStats || [];
|
const cs = raw.categoryStats || [];
|
||||||
|
// 勾选分类参与统计(投资赠与默认不勾选,用户想算进去可手动勾)
|
||||||
const sel = cb.filter((c) => checked.has(c.category));
|
const sel = cb.filter((c) => checked.has(c.category));
|
||||||
const totalIncome = sel.reduce((s, c) => s + c.total_income, 0);
|
const totalIncome = sel.reduce((s, c) => s + c.total_income, 0);
|
||||||
const totalExpense = sel.reduce((s, c) => s + c.total_expense, 0);
|
const totalExpense = sel.reduce((s, c) => s + c.total_expense, 0);
|
||||||
const dealCount = sel.reduce((s, c) => s + c.deal_count, 0);
|
const dealCount = sel.reduce((s, c) => s + c.deal_count, 0);
|
||||||
const pieStats = cs.filter((c) => checked.has(c.category));
|
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]);
|
}, [raw, checked]);
|
||||||
|
|
||||||
const ov = raw?.overview || {};
|
const ov = raw?.overview || {};
|
||||||
@@ -173,15 +237,39 @@ export default function Dashboard() {
|
|||||||
>
|
>
|
||||||
<div>
|
<div>
|
||||||
<h2>📊 财务仪表盘</h2>
|
<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>
|
</div>
|
||||||
<button
|
|
||||||
className="btn btn-secondary"
|
|
||||||
onClick={loadData}
|
|
||||||
style={{ display: "inline-flex", alignItems: "center", gap: 6 }}
|
|
||||||
>
|
|
||||||
<RefreshCcw size={14} /> 刷新
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="stats-grid">
|
<div className="stats-grid">
|
||||||
@@ -199,6 +287,15 @@ export default function Dashboard() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="stat-sub">{checked.size} 个分类合计</div>
|
<div className="stat-sub">{checked.size} 个分类合计</div>
|
||||||
</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-card">
|
||||||
<div className="stat-label">📈 净收支</div>
|
<div className="stat-label">📈 净收支</div>
|
||||||
<div
|
<div
|
||||||
|
|||||||
@@ -63,7 +63,8 @@ export default function Review() {
|
|||||||
min_amount: 100,
|
min_amount: 100,
|
||||||
limit: PAGE_SIZE,
|
limit: PAGE_SIZE,
|
||||||
page: p || 1,
|
page: p || 1,
|
||||||
sort_by: "amount",
|
// 按金额绝对值从大到小排序(收/支混排)
|
||||||
|
sort_by: "abs_amount",
|
||||||
sort_order: "DESC",
|
sort_order: "DESC",
|
||||||
};
|
};
|
||||||
if (!showReviewed) params.reviewed = 0;
|
if (!showReviewed) params.reviewed = 0;
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
updateCategory,
|
updateCategory,
|
||||||
createCategory,
|
createCategory,
|
||||||
deleteCategory,
|
deleteCategory,
|
||||||
reclassifyAffected,
|
classifyTransactions,
|
||||||
} from "../hooks/useApi";
|
} from "../hooks/useApi";
|
||||||
|
|
||||||
export default function SettingsPage() {
|
export default function SettingsPage() {
|
||||||
@@ -122,7 +122,7 @@ export default function SettingsPage() {
|
|||||||
setReclassifying(true);
|
setReclassifying(true);
|
||||||
setReclassifyMsg(null);
|
setReclassifyMsg(null);
|
||||||
try {
|
try {
|
||||||
const result = await reclassifyAffected(ids);
|
const result = await classifyTransactions(ids);
|
||||||
setReclassifyMsg({
|
setReclassifyMsg({
|
||||||
type: "success",
|
type: "success",
|
||||||
text: `重分类完成!${result.classified} 条交易已重新分类(来源: ${result.source === "llm" ? "AI" : "规则匹配"})。`,
|
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>
|
||||||
<td>
|
<td>
|
||||||
@@ -439,6 +450,8 @@ export default function SettingsPage() {
|
|||||||
<div style={{ display: "flex", gap: 6 }}>
|
<div style={{ display: "flex", gap: 6 }}>
|
||||||
<button
|
<button
|
||||||
className="btn btn-secondary btn-sm"
|
className="btn btn-secondary btn-sm"
|
||||||
|
disabled={!!cat.is_locked}
|
||||||
|
title={cat.is_locked ? "内置分类不可修改" : "编辑"}
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
setEditingCat({
|
setEditingCat({
|
||||||
...cat,
|
...cat,
|
||||||
@@ -452,6 +465,8 @@ export default function SettingsPage() {
|
|||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
className="btn btn-danger btn-sm"
|
className="btn btn-danger btn-sm"
|
||||||
|
disabled={!!cat.is_locked}
|
||||||
|
title={cat.is_locked ? "内置分类不可删除" : "删除"}
|
||||||
onClick={() => handleDeleteCategory(cat.id, cat.name)}
|
onClick={() => handleDeleteCategory(cat.id, cat.name)}
|
||||||
>
|
>
|
||||||
<Trash2 size={12} />
|
<Trash2 size={12} />
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useState, useEffect } from "react";
|
import React, { useState, useEffect, useRef } from "react";
|
||||||
import {
|
import {
|
||||||
RotateCcw,
|
RotateCcw,
|
||||||
Link2,
|
Link2,
|
||||||
@@ -17,9 +17,9 @@ import {
|
|||||||
getDeals,
|
getDeals,
|
||||||
updateDeal,
|
updateDeal,
|
||||||
clearDeals,
|
clearDeals,
|
||||||
getNeedsClassify,
|
|
||||||
runReconciliation,
|
runReconciliation,
|
||||||
classifyTransactions,
|
classifyAll,
|
||||||
|
getClassifyStatus,
|
||||||
formatAmount,
|
formatAmount,
|
||||||
SOURCE_TYPE_MAP,
|
SOURCE_TYPE_MAP,
|
||||||
getCategories,
|
getCategories,
|
||||||
@@ -80,6 +80,8 @@ export default function Transactions() {
|
|||||||
const [clearConfirm, setClearConfirm] = useState(false);
|
const [clearConfirm, setClearConfirm] = useState(false);
|
||||||
const [editingDeal, setEditingDeal] = useState(null);
|
const [editingDeal, setEditingDeal] = useState(null);
|
||||||
const [dealFilters, setDealFilters] = useState({ ...DEAL_FILTER_DEFAULT });
|
const [dealFilters, setDealFilters] = useState({ ...DEAL_FILTER_DEFAULT });
|
||||||
|
const classifyPollRef = useRef(null);
|
||||||
|
const reloadRef = useRef(null);
|
||||||
|
|
||||||
/* sort helpers */
|
/* sort helpers */
|
||||||
function dealToggleSort(field) {
|
function dealToggleSort(field) {
|
||||||
@@ -141,38 +143,66 @@ export default function Transactions() {
|
|||||||
setToast({ message: msg, type, key: Date.now() });
|
setToast({ message: msg, type, key: Date.now() });
|
||||||
}
|
}
|
||||||
|
|
||||||
/* restore classify progress */
|
function stopClassifyPoll() {
|
||||||
useEffect(() => {
|
if (classifyPollRef.current) {
|
||||||
const saved = sessionStorage.getItem("classifyTask");
|
clearInterval(classifyPollRef.current);
|
||||||
if (!saved) return;
|
classifyPollRef.current = null;
|
||||||
const task = JSON.parse(saved);
|
|
||||||
if (Date.now() - task.ts > 300000) {
|
|
||||||
sessionStorage.removeItem("classifyTask");
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
setClassifying(true);
|
}
|
||||||
setClassifyProgress(task.progress || 0);
|
|
||||||
const poll = setInterval(async () => {
|
// 轮询服务端全量分类进度
|
||||||
|
function pollClassifyStatus() {
|
||||||
|
const tick = async () => {
|
||||||
try {
|
try {
|
||||||
const { total } = await getNeedsClassify();
|
const s = await getClassifyStatus();
|
||||||
const p =
|
if (s.running) {
|
||||||
task.total > 0
|
setClassifying(true);
|
||||||
? Math.round(((task.total - total) / task.total) * 100)
|
setClassifyProgress(
|
||||||
: 100;
|
s.total ? Math.min(100, Math.round((s.done / s.total) * 100)) : 0,
|
||||||
setClassifyProgress(Math.min(Math.max(p, 0), 100));
|
);
|
||||||
if (total <= 0 || p >= 100) {
|
} else {
|
||||||
clearInterval(poll);
|
stopClassifyPoll();
|
||||||
setClassifying(false);
|
setClassifying(false);
|
||||||
sessionStorage.removeItem("classifyTask");
|
setClassifyProgress(100);
|
||||||
loadTransactions();
|
showToast("分类完成!", "success");
|
||||||
|
if (reloadRef.current) reloadRef.current();
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
clearInterval(poll);
|
stopClassifyPoll();
|
||||||
setClassifying(false);
|
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(() => {
|
useEffect(() => {
|
||||||
@@ -277,66 +307,21 @@ export default function Transactions() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function handleClassifyAll() {
|
async function handleClassifyAll() {
|
||||||
setClassifying(true);
|
|
||||||
setClassifyProgress(0);
|
|
||||||
sessionStorage.setItem(
|
|
||||||
"classifyTask",
|
|
||||||
JSON.stringify({ total: 0, progress: 0, ts: Date.now() }),
|
|
||||||
);
|
|
||||||
try {
|
try {
|
||||||
const { ids, total } = await getNeedsClassify();
|
const { total } = await classifyAll();
|
||||||
if (!ids.length) {
|
if (!total) {
|
||||||
showToast("所有交易分类均有效!", "info");
|
showToast("所有交易分类均有效!", "info");
|
||||||
setClassifying(false);
|
|
||||||
sessionStorage.removeItem("classifyTask");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
sessionStorage.setItem(
|
setClassifying(true);
|
||||||
"classifyTask",
|
setClassifyProgress(0);
|
||||||
JSON.stringify({ total, progress: 0, ts: Date.now() }),
|
pollClassifyStatus();
|
||||||
);
|
|
||||||
// 分批并行处理(每批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();
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
sessionStorage.removeItem("classifyTask");
|
showToast(
|
||||||
showToast("分类失败: " + (e.response?.data?.error || e.message), "error");
|
"分类启动失败: " + (e.response?.data?.error || e.message),
|
||||||
|
"error",
|
||||||
|
);
|
||||||
}
|
}
|
||||||
setClassifying(false);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ============================== RENDER ============================== */
|
/* ============================== RENDER ============================== */
|
||||||
|
|||||||
+83
-3
@@ -1,7 +1,11 @@
|
|||||||
const Database = require("better-sqlite3");
|
const Database = require("better-sqlite3");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
|
|
||||||
const DB_PATH = path.join(__dirname, "..", "data", "reco.db");
|
const DB_PATH =
|
||||||
|
process.env.RECO_DB_PATH || path.join(__dirname, "..", "data", "reco.db");
|
||||||
|
|
||||||
|
// 系统兜底分类:所有用户都不允许修改/删除
|
||||||
|
const SYSTEM_LOCKED_CATEGORIES = ["其他杂项"];
|
||||||
|
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const dataDir = path.join(__dirname, "..", "data");
|
const dataDir = path.join(__dirname, "..", "data");
|
||||||
@@ -68,6 +72,7 @@ function initDB() {
|
|||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
name TEXT NOT NULL,
|
name TEXT NOT NULL,
|
||||||
keywords TEXT,
|
keywords TEXT,
|
||||||
|
is_locked INTEGER DEFAULT 0,
|
||||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -186,6 +191,74 @@ function initDB() {
|
|||||||
console.error("[Reco] config 迁移失败:", e.message);
|
console.error("[Reco] config 迁移失败:", e.message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 兼容旧库:分类锁定标记。
|
||||||
|
// 内置基础分类(最初的 1-10 号)和系统兜底分类(其他杂项)不允许修改/删除。
|
||||||
|
try {
|
||||||
|
const catCols = database
|
||||||
|
.prepare("PRAGMA table_info(categories)")
|
||||||
|
.all()
|
||||||
|
.map((r) => r.name);
|
||||||
|
if (!catCols.includes("is_locked")) {
|
||||||
|
database.exec(
|
||||||
|
"ALTER TABLE categories ADD COLUMN is_locked INTEGER DEFAULT 0",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
database.prepare("UPDATE categories SET is_locked = 1 WHERE id <= 10").run();
|
||||||
|
if (SYSTEM_LOCKED_CATEGORIES.length) {
|
||||||
|
const ph = SYSTEM_LOCKED_CATEGORIES.map(() => "?").join(",");
|
||||||
|
database
|
||||||
|
.prepare(`UPDATE categories SET is_locked = 1 WHERE name IN (${ph})`)
|
||||||
|
.run(...SYSTEM_LOCKED_CATEGORIES);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error("[Reco] 分类锁定初始化失败:", e.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 兼容旧库:合并同名重复分类。
|
||||||
|
// 老用户的历史分类 user_id 为 NULL,之后初始化默认分类时按 user_id 计数为 0,
|
||||||
|
// 于是又插入了一整套默认分类,导致同名分类出现两份。
|
||||||
|
// 合并策略:保留 id 最小的一行(通常是用户手工维护过的),关键词取并集,删除其余行。
|
||||||
|
try {
|
||||||
|
const dupGroups = database
|
||||||
|
.prepare(
|
||||||
|
`SELECT user_id, name, COUNT(*) AS c FROM categories
|
||||||
|
GROUP BY user_id, name HAVING c > 1`,
|
||||||
|
)
|
||||||
|
.all();
|
||||||
|
if (dupGroups.length) {
|
||||||
|
const rowsStmt = database.prepare(
|
||||||
|
"SELECT id, keywords FROM categories WHERE name = ? AND user_id IS ? ORDER BY id",
|
||||||
|
);
|
||||||
|
const setKeywords = database.prepare(
|
||||||
|
"UPDATE categories SET keywords = ? WHERE id = ?",
|
||||||
|
);
|
||||||
|
const delCategory = database.prepare("DELETE FROM categories WHERE id = ?");
|
||||||
|
database.transaction(() => {
|
||||||
|
for (const g of dupGroups) {
|
||||||
|
const rows = rowsStmt.all(g.name, g.user_id);
|
||||||
|
const merged = [];
|
||||||
|
for (const r of rows) {
|
||||||
|
try {
|
||||||
|
const arr = JSON.parse(r.keywords || "[]");
|
||||||
|
if (Array.isArray(arr))
|
||||||
|
for (const k of arr)
|
||||||
|
if (k && !merged.includes(k)) merged.push(k);
|
||||||
|
} catch (e) {}
|
||||||
|
}
|
||||||
|
setKeywords.run(JSON.stringify(merged), rows[0].id);
|
||||||
|
for (const r of rows.slice(1)) delCategory.run(r.id);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
console.log(`[Reco] 已合并 ${dupGroups.length} 组重复分类`);
|
||||||
|
}
|
||||||
|
// 唯一索引:同一用户下不允许同名分类
|
||||||
|
database.exec(
|
||||||
|
"CREATE UNIQUE INDEX IF NOT EXISTS idx_categories_user_name ON categories(user_id, name)",
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
console.error("[Reco] 分类去重失败:", e.message);
|
||||||
|
}
|
||||||
|
|
||||||
console.log("[Reco] 数据库初始化完成");
|
console.log("[Reco] 数据库初始化完成");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -198,7 +271,7 @@ function initDefaultCategories(userId) {
|
|||||||
if (existing > 0) return;
|
if (existing > 0) return;
|
||||||
|
|
||||||
const ins = database.prepare(
|
const ins = database.prepare(
|
||||||
"INSERT INTO categories (name, keywords, user_id) VALUES (?, ?, ?)",
|
"INSERT OR IGNORE INTO categories (name, keywords, user_id, is_locked) VALUES (?, ?, ?, ?)",
|
||||||
);
|
);
|
||||||
const defaults = [
|
const defaults = [
|
||||||
["餐饮美食", '["餐厅","外卖","食堂","咖啡","奶茶","零食","水果","买菜"]'],
|
["餐饮美食", '["餐厅","外卖","食堂","咖啡","奶茶","零食","水果","买菜"]'],
|
||||||
@@ -222,7 +295,14 @@ function initDefaultCategories(userId) {
|
|||||||
["其他杂项", "[]"],
|
["其他杂项", "[]"],
|
||||||
];
|
];
|
||||||
database.transaction(() => {
|
database.transaction(() => {
|
||||||
defaults.forEach((c) => ins.run(c[0], c[1], userId));
|
defaults.forEach((c) =>
|
||||||
|
ins.run(
|
||||||
|
c[0],
|
||||||
|
c[1],
|
||||||
|
userId,
|
||||||
|
SYSTEM_LOCKED_CATEGORIES.includes(c[0]) ? 1 : 0,
|
||||||
|
),
|
||||||
|
);
|
||||||
})();
|
})();
|
||||||
console.log(`[Reco] 已为用户 ${userId} 初始化默认分类`);
|
console.log(`[Reco] 已为用户 ${userId} 初始化默认分类`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ process.noDeprecation = true;
|
|||||||
|
|
||||||
const uploadRoutes = require("./routes/upload");
|
const uploadRoutes = require("./routes/upload");
|
||||||
const transactionRoutes = require("./routes/transactions");
|
const transactionRoutes = require("./routes/transactions");
|
||||||
const classifyRoutes = require("./routes/classify");
|
|
||||||
const statsRoutes = require("./routes/stats");
|
const statsRoutes = require("./routes/stats");
|
||||||
const configRoutes = require("./routes/config");
|
const configRoutes = require("./routes/config");
|
||||||
const dealsRoutes = require("./routes/deals");
|
const dealsRoutes = require("./routes/deals");
|
||||||
@@ -31,7 +30,6 @@ app.use(authMiddleware);
|
|||||||
// 业务 API routes(受认证保护)
|
// 业务 API routes(受认证保护)
|
||||||
app.use("/api/upload", uploadRoutes);
|
app.use("/api/upload", uploadRoutes);
|
||||||
app.use("/api/transactions", transactionRoutes);
|
app.use("/api/transactions", transactionRoutes);
|
||||||
app.use("/api/classify", classifyRoutes);
|
|
||||||
app.use("/api/stats", statsRoutes);
|
app.use("/api/stats", statsRoutes);
|
||||||
app.use("/api/config", configRoutes);
|
app.use("/api/config", configRoutes);
|
||||||
app.use("/api/deals", dealsRoutes);
|
app.use("/api/deals", dealsRoutes);
|
||||||
|
|||||||
@@ -1,23 +0,0 @@
|
|||||||
const express = require("express");
|
|
||||||
const { classifyDeals } = require("../services/llm");
|
|
||||||
|
|
||||||
const router = express.Router();
|
|
||||||
|
|
||||||
// POST /api/classify - 对指定交易进行分类
|
|
||||||
router.post("/", async (req, res) => {
|
|
||||||
const { ids } = req.body;
|
|
||||||
|
|
||||||
if (!ids || !Array.isArray(ids) || ids.length === 0) {
|
|
||||||
return res.status(400).json({ error: "请提供交易ID列表" });
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const result = await classifyDeals(ids, req.userId);
|
|
||||||
res.json({ success: true, ...result });
|
|
||||||
} catch (err) {
|
|
||||||
console.error("[Reco] 分类失败:", err);
|
|
||||||
res.status(500).json({ error: err.message });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
module.exports = router;
|
|
||||||
+93
-20
@@ -93,36 +93,109 @@ router.get("/categories", (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
router.put("/categories/:id", (req, res) => {
|
router.put("/categories/:id", (req, res) => {
|
||||||
|
const db = getDB();
|
||||||
const { name, keywords } = req.body;
|
const { name, keywords } = req.body;
|
||||||
getDB()
|
const current = db
|
||||||
.prepare(
|
.prepare("SELECT * FROM categories WHERE id = ? AND user_id = ?")
|
||||||
"UPDATE categories SET name=COALESCE(?,name), keywords=COALESCE(?,keywords) WHERE id=? AND user_id=?",
|
.get(req.params.id, req.userId);
|
||||||
)
|
if (!current) return res.status(404).json({ error: "分类不存在" });
|
||||||
.run(
|
if (current.is_locked)
|
||||||
name,
|
return res.status(403).json({ error: "内置分类不可修改" });
|
||||||
keywords ? JSON.stringify(keywords) : null,
|
|
||||||
req.params.id,
|
const newName = name === undefined ? current.name : String(name).trim();
|
||||||
req.userId,
|
if (!newName) return res.status(400).json({ error: "分类名称不能为空" });
|
||||||
);
|
|
||||||
res.json({ success: true });
|
const affectedIds = [];
|
||||||
|
try {
|
||||||
|
db.transaction(() => {
|
||||||
|
if (newName !== current.name) {
|
||||||
|
const dup = db
|
||||||
|
.prepare(
|
||||||
|
"SELECT id FROM categories WHERE user_id = ? AND name = ? AND id <> ?",
|
||||||
|
)
|
||||||
|
.get(req.userId, newName, req.params.id);
|
||||||
|
if (dup) {
|
||||||
|
const err = new Error("已存在同名分类");
|
||||||
|
err.status = 409;
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
// 重命名:同步历史 deal 的分类名
|
||||||
|
for (const row of db
|
||||||
|
.prepare("SELECT id FROM deals WHERE user_id = ? AND category = ?")
|
||||||
|
.all(req.userId, current.name))
|
||||||
|
affectedIds.push(row.id);
|
||||||
|
db.prepare(
|
||||||
|
"UPDATE deals SET category = ?, updated_at = CURRENT_TIMESTAMP WHERE user_id = ? AND category = ?",
|
||||||
|
).run(newName, req.userId, current.name);
|
||||||
|
}
|
||||||
|
const sets = [];
|
||||||
|
const params = [];
|
||||||
|
if (newName !== current.name) {
|
||||||
|
sets.push("name = ?");
|
||||||
|
params.push(newName);
|
||||||
|
}
|
||||||
|
if (keywords !== undefined) {
|
||||||
|
sets.push("keywords = ?");
|
||||||
|
params.push(JSON.stringify(Array.isArray(keywords) ? keywords : []));
|
||||||
|
}
|
||||||
|
if (sets.length) {
|
||||||
|
db.prepare(
|
||||||
|
`UPDATE categories SET ${sets.join(", ")} WHERE id = ? AND user_id = ?`,
|
||||||
|
).run(...params, req.params.id, req.userId);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
} catch (err) {
|
||||||
|
return res
|
||||||
|
.status(err.status || 500)
|
||||||
|
.json({ error: err.message || "更新失败" });
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({ success: true, affectedDeals: affectedIds.length, affectedIds });
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post("/categories", (req, res) => {
|
router.post("/categories", (req, res) => {
|
||||||
const { name, keywords, parent_id } = req.body;
|
const db = getDB();
|
||||||
if (!name) return res.status(400).json({ error: "分类名称不能为空" });
|
const { name, keywords } = req.body;
|
||||||
const r = getDB()
|
const trimmed = typeof name === "string" ? name.trim() : "";
|
||||||
|
if (!trimmed) return res.status(400).json({ error: "分类名称不能为空" });
|
||||||
|
const dup = db
|
||||||
|
.prepare("SELECT id FROM categories WHERE user_id = ? AND name = ?")
|
||||||
|
.get(req.userId, trimmed);
|
||||||
|
if (dup) return res.status(409).json({ error: "已存在同名分类" });
|
||||||
|
const r = db
|
||||||
.prepare(
|
.prepare(
|
||||||
"INSERT INTO categories (name,keywords,parent_id,user_id) VALUES (?,?,?,?)",
|
"INSERT INTO categories (name, keywords, user_id) VALUES (?, ?, ?)",
|
||||||
)
|
)
|
||||||
.run(name, JSON.stringify(keywords || []), parent_id || null, req.userId);
|
.run(trimmed, JSON.stringify(keywords || []), req.userId);
|
||||||
res.json({ success: true, id: r.lastInsertRowid });
|
res.json({ success: true, id: r.lastInsertRowid });
|
||||||
});
|
});
|
||||||
|
|
||||||
router.delete("/categories/:id", (req, res) => {
|
router.delete("/categories/:id", (req, res) => {
|
||||||
getDB()
|
const db = getDB();
|
||||||
.prepare("DELETE FROM categories WHERE id=? AND user_id=?")
|
const cat = db
|
||||||
.run(req.params.id, req.userId);
|
.prepare("SELECT name, is_locked FROM categories WHERE id = ? AND user_id = ?")
|
||||||
res.json({ success: true });
|
.get(req.params.id, req.userId);
|
||||||
|
if (!cat) return res.status(404).json({ error: "分类不存在" });
|
||||||
|
if (cat.is_locked)
|
||||||
|
return res.status(403).json({ error: "内置分类不可删除" });
|
||||||
|
|
||||||
|
const affectedIds = db
|
||||||
|
.prepare("SELECT id FROM deals WHERE user_id = ? AND category = ?")
|
||||||
|
.all(req.userId, cat.name)
|
||||||
|
.map((r) => r.id);
|
||||||
|
|
||||||
|
db.transaction(() => {
|
||||||
|
// 历史 deal 重置为待分类
|
||||||
|
db.prepare(
|
||||||
|
"UPDATE deals SET category = NULL, updated_at = CURRENT_TIMESTAMP WHERE user_id = ? AND category = ?",
|
||||||
|
).run(req.userId, cat.name);
|
||||||
|
db.prepare("DELETE FROM categories WHERE id = ? AND user_id = ?").run(
|
||||||
|
req.params.id,
|
||||||
|
req.userId,
|
||||||
|
);
|
||||||
|
})();
|
||||||
|
|
||||||
|
res.json({ success: true, affectedDeals: affectedIds.length, affectedIds });
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|||||||
@@ -67,9 +67,14 @@ router.get("/", (req, res) => {
|
|||||||
"counterparty",
|
"counterparty",
|
||||||
"category",
|
"category",
|
||||||
"match_count",
|
"match_count",
|
||||||
|
"abs_amount",
|
||||||
];
|
];
|
||||||
const safeSort = allowedSort.includes(sort_by) ? sort_by : "deal_date";
|
const safeSort = allowedSort.includes(sort_by) ? sort_by : "deal_date";
|
||||||
const safeOrder = sort_order === "ASC" ? "ASC" : "DESC";
|
const safeOrder = sort_order === "ASC" ? "ASC" : "DESC";
|
||||||
|
// abs_amount:按金额绝对值排序(大额确认用,收/支混排时按体量从大到小)
|
||||||
|
const sortExpr =
|
||||||
|
safeSort === "abs_amount" ? "ABS(d.amount)" : `d.${safeSort}`;
|
||||||
|
const tieBreaker = safeSort === "abs_amount" ? ", d.id DESC" : "";
|
||||||
|
|
||||||
const total = db
|
const total = db
|
||||||
.prepare(`SELECT COUNT(*) as c FROM deals d ${where}`)
|
.prepare(`SELECT COUNT(*) as c FROM deals d ${where}`)
|
||||||
@@ -90,7 +95,7 @@ router.get("/", (req, res) => {
|
|||||||
LEFT JOIN transactions t ON t.id = dt.transaction_id
|
LEFT JOIN transactions t ON t.id = dt.transaction_id
|
||||||
${where}
|
${where}
|
||||||
GROUP BY d.id
|
GROUP BY d.id
|
||||||
ORDER BY d.${safeSort} ${safeOrder}
|
ORDER BY ${sortExpr} ${safeOrder}${tieBreaker}
|
||||||
LIMIT ? OFFSET ?
|
LIMIT ? OFFSET ?
|
||||||
`,
|
`,
|
||||||
)
|
)
|
||||||
|
|||||||
+57
-20
@@ -6,20 +6,32 @@ const router = express.Router();
|
|||||||
// GET /api/stats/overview — 总览统计(基于 deals)
|
// GET /api/stats/overview — 总览统计(基于 deals)
|
||||||
router.get("/overview", (req, res) => {
|
router.get("/overview", (req, res) => {
|
||||||
const db = getDB();
|
const db = getDB();
|
||||||
const { year, month } = req.query;
|
const { year, month, start_date, end_date } = req.query;
|
||||||
|
|
||||||
let where = "WHERE d.user_id = ?";
|
|
||||||
const params = [req.userId];
|
|
||||||
|
|
||||||
|
// 日期条件:支持任意区间(财年),也保留旧的 year/month
|
||||||
|
const dateConds = [];
|
||||||
|
const dateParams = [];
|
||||||
|
if (start_date) {
|
||||||
|
dateConds.push("d.deal_date >= ?");
|
||||||
|
dateParams.push(start_date);
|
||||||
|
}
|
||||||
|
if (end_date) {
|
||||||
|
dateConds.push("d.deal_date <= ?");
|
||||||
|
dateParams.push(end_date);
|
||||||
|
}
|
||||||
if (year) {
|
if (year) {
|
||||||
where += " AND strftime('%Y', d.deal_date) = ?";
|
dateConds.push("strftime('%Y', d.deal_date) = ?");
|
||||||
params.push(String(year));
|
dateParams.push(String(year));
|
||||||
if (month) {
|
if (month) {
|
||||||
where += " AND strftime('%m', d.deal_date) = ?";
|
dateConds.push("strftime('%m', d.deal_date) = ?");
|
||||||
params.push(String(month).padStart(2, "0"));
|
dateParams.push(String(month).padStart(2, "0"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let where = "WHERE d.user_id = ?";
|
||||||
|
const params = [req.userId, ...dateParams];
|
||||||
|
if (dateConds.length) where += " AND " + dateConds.join(" AND ");
|
||||||
|
|
||||||
const stats = db
|
const stats = db
|
||||||
.prepare(
|
.prepare(
|
||||||
`
|
`
|
||||||
@@ -76,23 +88,33 @@ router.get("/overview", (req, res) => {
|
|||||||
)
|
)
|
||||||
.all(...params);
|
.all(...params);
|
||||||
|
|
||||||
|
const dateCondSql = dateConds.length ? " AND " + dateConds.join(" AND ") : "";
|
||||||
const maxIncomeStmt = db.prepare(
|
const maxIncomeStmt = db.prepare(
|
||||||
`SELECT id, amount, counterparty, deal_date, ai_description
|
`SELECT id, amount, counterparty, deal_date, ai_description
|
||||||
FROM deals WHERE category=? AND direction='income' AND user_id=?
|
FROM deals d WHERE d.category=? AND d.direction='income' AND d.user_id=?${dateCondSql}
|
||||||
ORDER BY amount DESC LIMIT 1`,
|
ORDER BY d.amount DESC LIMIT 1`,
|
||||||
);
|
);
|
||||||
const maxExpenseStmt = db.prepare(
|
const maxExpenseStmt = db.prepare(
|
||||||
`SELECT id, amount, counterparty, deal_date, ai_description
|
`SELECT id, amount, counterparty, deal_date, ai_description
|
||||||
FROM deals WHERE category=? AND direction='expense' AND user_id=?
|
FROM deals d WHERE d.category=? AND d.direction='expense' AND d.user_id=?${dateCondSql}
|
||||||
ORDER BY ABS(amount) DESC LIMIT 1`,
|
ORDER BY ABS(d.amount) DESC LIMIT 1`,
|
||||||
);
|
);
|
||||||
|
|
||||||
for (const cat of categoryBreakdown) {
|
for (const cat of categoryBreakdown) {
|
||||||
cat.max_income = maxIncomeStmt.get(cat.category, req.userId) || null;
|
cat.max_income =
|
||||||
cat.max_expense = maxExpenseStmt.get(cat.category, req.userId) || null;
|
maxIncomeStmt.get(cat.category, req.userId, ...dateParams) || null;
|
||||||
|
cat.max_expense =
|
||||||
|
maxExpenseStmt.get(cat.category, req.userId, ...dateParams) || null;
|
||||||
}
|
}
|
||||||
|
|
||||||
res.json({ overview: stats, categoryStats, categoryBreakdown });
|
// 全量日期范围(不受筛选影响),供前端枚举财年
|
||||||
|
const dateRange = db
|
||||||
|
.prepare(
|
||||||
|
"SELECT MIN(deal_date) as min_date, MAX(deal_date) as max_date FROM deals WHERE user_id = ?",
|
||||||
|
)
|
||||||
|
.get(req.userId);
|
||||||
|
|
||||||
|
res.json({ overview: stats, categoryStats, categoryBreakdown, dateRange });
|
||||||
});
|
});
|
||||||
|
|
||||||
// 解析 categories 查询参数
|
// 解析 categories 查询参数
|
||||||
@@ -107,14 +129,29 @@ function parseCategories(query) {
|
|||||||
// GET /api/stats/monthly — 月度趋势(支持 ?categories=餐饮,购物 筛选)
|
// GET /api/stats/monthly — 月度趋势(支持 ?categories=餐饮,购物 筛选)
|
||||||
router.get("/monthly", (req, res) => {
|
router.get("/monthly", (req, res) => {
|
||||||
const db = getDB();
|
const db = getDB();
|
||||||
const months = Math.abs(parseInt(req.query.months) || 12);
|
const { start_date, end_date } = req.query;
|
||||||
const cats = parseCategories(req.query.categories);
|
const cats = parseCategories(req.query.categories);
|
||||||
|
|
||||||
let catFilter = "";
|
const conds = ["d.user_id = ?"];
|
||||||
const params = ["-" + months, req.userId];
|
const params = [req.userId];
|
||||||
|
|
||||||
|
if (start_date) {
|
||||||
|
conds.push("d.deal_date >= ?");
|
||||||
|
params.push(start_date);
|
||||||
|
}
|
||||||
|
if (end_date) {
|
||||||
|
conds.push("d.deal_date <= ?");
|
||||||
|
params.push(end_date);
|
||||||
|
}
|
||||||
|
// 只有显式传了 months 才限制为「最近 N 个月」;
|
||||||
|
// 不传任何时间参数 = 不限制(全部时间)
|
||||||
|
if (!start_date && !end_date && req.query.months != null) {
|
||||||
|
const months = Math.abs(parseInt(req.query.months) || 12);
|
||||||
|
conds.push("d.deal_date >= DATE('now', ? || ' months')");
|
||||||
|
params.push("-" + months);
|
||||||
|
}
|
||||||
if (cats && cats.length > 0) {
|
if (cats && cats.length > 0) {
|
||||||
catFilter = " AND d.category IN (" + cats.map(() => "?").join(",") + ")";
|
conds.push("d.category IN (" + cats.map(() => "?").join(",") + ")");
|
||||||
params.push(...cats);
|
params.push(...cats);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,7 +164,7 @@ router.get("/monthly", (req, res) => {
|
|||||||
SUM(CASE WHEN d.direction = 'income' THEN d.amount ELSE 0 END) as income,
|
SUM(CASE WHEN d.direction = 'income' THEN d.amount ELSE 0 END) as income,
|
||||||
SUM(CASE WHEN d.direction = 'expense' THEN ABS(d.amount) ELSE 0 END) as expense
|
SUM(CASE WHEN d.direction = 'expense' THEN ABS(d.amount) ELSE 0 END) as expense
|
||||||
FROM deals d
|
FROM deals d
|
||||||
WHERE d.deal_date >= DATE('now', ? || ' months') AND d.user_id = ?${catFilter}
|
WHERE ${conds.join(" AND ")}
|
||||||
GROUP BY strftime('%Y-%m', d.deal_date)
|
GROUP BY strftime('%Y-%m', d.deal_date)
|
||||||
ORDER BY month ASC
|
ORDER BY month ASC
|
||||||
`,
|
`,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
const express = require("express");
|
const express = require("express");
|
||||||
const { getDB } = require("../db");
|
const { getDB } = require("../db");
|
||||||
const { runAutoReconciliation } = require("../services/matcher");
|
const { runAutoReconciliation } = require("../services/matcher");
|
||||||
const { classifyDeals, classifyAllDeals } = require("../services/llm");
|
const { classifyDeals, startClassifyAll, getClassifyStatus } = require("../services/llm");
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
@@ -111,25 +111,6 @@ router.get("/", (req, res) => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get("/needs-classify", (req, res) => {
|
|
||||||
const db = getDB();
|
|
||||||
const cats = db
|
|
||||||
.prepare("SELECT name FROM categories WHERE user_id = ?")
|
|
||||||
.all(req.userId)
|
|
||||||
.map((r) => r.name);
|
|
||||||
if (!cats.length) return res.json({ ids: [], total: 0 });
|
|
||||||
const ph = cats.map(() => "?").join(",");
|
|
||||||
const stale = db
|
|
||||||
.prepare(
|
|
||||||
`SELECT id FROM deals WHERE (category IS NULL OR category NOT IN (${ph})) AND user_id = ?`,
|
|
||||||
)
|
|
||||||
.all(...cats, req.userId);
|
|
||||||
console.log(
|
|
||||||
`[Reco] GET /transactions/needs-classify — 返回 ${stale.length} 个待分类 deal`,
|
|
||||||
);
|
|
||||||
res.json({ ids: stale.map((r) => r.id), total: stale.length });
|
|
||||||
});
|
|
||||||
|
|
||||||
// POST /api/transactions/reconcile - 全量清除后重新对账
|
// POST /api/transactions/reconcile - 全量清除后重新对账
|
||||||
router.post("/reconcile", (req, res) => {
|
router.post("/reconcile", (req, res) => {
|
||||||
const db = getDB();
|
const db = getDB();
|
||||||
@@ -225,19 +206,18 @@ router.post("/classify", async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// POST /api/transactions/classify-all — AI分类全部(并行)
|
// POST /api/transactions/classify-all — 启动全量分类(后台执行,前端轮询状态)
|
||||||
router.post("/classify-all", async (req, res) => {
|
router.post("/classify-all", (req, res) => {
|
||||||
console.log(`[Reco] POST /transactions/classify-all — 开始`);
|
const result = startClassifyAll(req.userId);
|
||||||
try {
|
console.log(
|
||||||
const result = await classifyAllDeals(req.userId);
|
`[Reco] POST /transactions/classify-all — started=${result.started}, total=${result.total}`,
|
||||||
console.log(
|
);
|
||||||
`[Reco] POST /transactions/classify-all — 完成, classified: ${result.classified}, total: ${result.total}, source: ${result.source}`,
|
res.json({ success: true, ...result });
|
||||||
);
|
});
|
||||||
res.json({ success: true, ...result });
|
|
||||||
} catch (err) {
|
// GET /api/transactions/classify-status — 全量分类进度
|
||||||
console.error("[Reco] 分类全部失败:", err);
|
router.get("/classify-status", (req, res) => {
|
||||||
res.status(500).json({ error: err.message });
|
res.json(getClassifyStatus(req.userId));
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|||||||
+331
-126
@@ -1,5 +1,9 @@
|
|||||||
const BATCH_SIZE = 30;
|
const BATCH_SIZE = 30;
|
||||||
const CONCURRENCY = 5;
|
const CONCURRENCY = 8;
|
||||||
|
// 单次 LLM 响应的 token 上限。
|
||||||
|
// 注意:reasoning 模型(如 deepseek-flash/reasoner)会先消耗 reasoning tokens,
|
||||||
|
// 该预算如果太小,content 会被截断为空,导致分类静默退回规则匹配。
|
||||||
|
const MAX_TOKENS = Number(process.env.LLM_MAX_TOKENS) || 16000;
|
||||||
|
|
||||||
/* ============================== 配置管理 ============================== */
|
/* ============================== 配置管理 ============================== */
|
||||||
function loadUserLLMConfig(userId) {
|
function loadUserLLMConfig(userId) {
|
||||||
@@ -11,48 +15,82 @@ function loadUserLLMConfig(userId) {
|
|||||||
return row ? JSON.parse(row.value) : {};
|
return row ? JSON.parse(row.value) : {};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const clientCache = new Map(); // userId -> { sig, client }
|
||||||
|
|
||||||
function getOpenAIClient(userId) {
|
function getOpenAIClient(userId) {
|
||||||
const cfg = loadUserLLMConfig(userId);
|
const cfg = loadUserLLMConfig(userId);
|
||||||
if (!cfg.llm_api_key) {
|
if (!cfg.llm_api_key) {
|
||||||
console.log("[Reco] LLM 未配置 API Key (userId=" + userId + ")");
|
console.log("[Reco] LLM 未配置 API Key (userId=" + userId + ")");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
// 配置未变时复用 client,避免每批都重新创建连接池
|
||||||
|
const sig = [
|
||||||
|
cfg.llm_api_key,
|
||||||
|
cfg.llm_base_url || "",
|
||||||
|
cfg.llm_model || "",
|
||||||
|
].join("|");
|
||||||
|
const cached = clientCache.get(userId);
|
||||||
|
if (cached && cached.sig === sig) return cached.client;
|
||||||
|
|
||||||
const { OpenAI } = require("openai");
|
const { OpenAI } = require("openai");
|
||||||
const client = new OpenAI({
|
const client = new OpenAI({
|
||||||
apiKey: cfg.llm_api_key,
|
apiKey: cfg.llm_api_key,
|
||||||
baseURL: cfg.llm_base_url || "https://api.openai.com/v1",
|
baseURL: cfg.llm_base_url || "https://api.openai.com/v1",
|
||||||
});
|
});
|
||||||
client._model = cfg.llm_model || "gpt-4o-mini";
|
client._model = cfg.llm_model || "gpt-4o-mini";
|
||||||
|
clientCache.set(userId, { sig, client });
|
||||||
return client;
|
return client;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ============================== 分类加载 ============================== */
|
||||||
|
function loadCategories(userId) {
|
||||||
|
const { getDB } = require("../db");
|
||||||
|
return getDB()
|
||||||
|
.prepare("SELECT id, name, keywords FROM categories WHERE user_id = ?")
|
||||||
|
.all(userId)
|
||||||
|
.map((c) => {
|
||||||
|
let keywords = [];
|
||||||
|
try {
|
||||||
|
keywords = JSON.parse(c.keywords || "[]");
|
||||||
|
} catch (e) {}
|
||||||
|
return { id: c.id, name: c.name, keywords };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/* ============================== Prompt 构建 ============================== */
|
/* ============================== Prompt 构建 ============================== */
|
||||||
function buildPrompt(deals, userId) {
|
function buildPrompt(deals, userId, cats) {
|
||||||
const { getDB } = require("../db");
|
const { getDB } = require("../db");
|
||||||
const db = getDB();
|
const db = getDB();
|
||||||
|
if (!cats) cats = loadCategories(userId);
|
||||||
|
|
||||||
const cats = db
|
|
||||||
.prepare("SELECT id, name, keywords FROM categories WHERE user_id = ?")
|
|
||||||
.all(userId);
|
|
||||||
const catList = cats
|
const catList = cats
|
||||||
.map(
|
.map((c) => c.name + "(" + c.keywords.join("、") + ")")
|
||||||
(c) => c.name + "(" + JSON.parse(c.keywords || "[]").join("、") + ")",
|
|
||||||
)
|
|
||||||
.join("\n");
|
.join("\n");
|
||||||
|
|
||||||
|
// 一次查出整批 deal 的关联交易,避免逐条查询(N+1)
|
||||||
|
const dealIds = deals.map((d) => d.id);
|
||||||
|
const txByDeal = new Map();
|
||||||
|
if (dealIds.length) {
|
||||||
|
const rows = db
|
||||||
|
.prepare(
|
||||||
|
`
|
||||||
|
SELECT dt.deal_id, t.description, t.counterparty, t.source_type, t.notes
|
||||||
|
FROM deal_transactions dt
|
||||||
|
JOIN transactions t ON t.id = dt.transaction_id
|
||||||
|
WHERE dt.deal_id IN (${dealIds.map(() => "?").join(",")})
|
||||||
|
`,
|
||||||
|
)
|
||||||
|
.all(...dealIds);
|
||||||
|
for (const r of rows) {
|
||||||
|
if (!txByDeal.has(r.deal_id)) txByDeal.set(r.deal_id, []);
|
||||||
|
txByDeal.get(r.deal_id).push(r);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let txTotal = 0;
|
let txTotal = 0;
|
||||||
const dealList = deals
|
const dealList = deals
|
||||||
.map((d, i) => {
|
.map((d, i) => {
|
||||||
const txs = db
|
const txs = txByDeal.get(d.id) || [];
|
||||||
.prepare(
|
|
||||||
`
|
|
||||||
SELECT t.description, t.counterparty, t.source_type, t.notes
|
|
||||||
FROM deal_transactions dt
|
|
||||||
JOIN transactions t ON t.id = dt.transaction_id
|
|
||||||
WHERE dt.deal_id = ?
|
|
||||||
`,
|
|
||||||
)
|
|
||||||
.all(d.id);
|
|
||||||
|
|
||||||
let extra = "";
|
let extra = "";
|
||||||
if (txs.length > 0) {
|
if (txs.length > 0) {
|
||||||
@@ -79,7 +117,7 @@ function buildPrompt(deals, userId) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
`[${i + 1}] 日期:${d.deal_date} | 金额:${d.amount.toFixed(2)}元` +
|
`[${i + 1}] 日期:${d.deal_date} | 金额:${Number(d.amount).toFixed(2)}元` +
|
||||||
` | 对方:${d.counterparty || "未知"} | 描述:${d.description || "无"}${extra}`
|
` | 对方:${d.counterparty || "未知"} | 描述:${d.description || "无"}${extra}`
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
@@ -123,8 +161,89 @@ function extractJsonArray(text) {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ============================== 单次 LLM 请求 ============================== */
|
||||||
|
// 返回 { pairs, finish, contentLen, reasoning },pairs 为 [{ deal, item }]
|
||||||
|
async function requestLLMClassification(deals, client, userId, cats, maxTokens) {
|
||||||
|
const prompt = buildPrompt(deals, userId, cats);
|
||||||
|
const response = await client.chat.completions.create({
|
||||||
|
model: client._model,
|
||||||
|
messages: [
|
||||||
|
{
|
||||||
|
role: "system",
|
||||||
|
content: "你是财务分析助手。只返回要求的JSON数组,不要任何额外文字。",
|
||||||
|
},
|
||||||
|
{ role: "user", content: prompt },
|
||||||
|
],
|
||||||
|
temperature: 0.3,
|
||||||
|
max_tokens: maxTokens,
|
||||||
|
});
|
||||||
|
|
||||||
|
const choice = response.choices?.[0];
|
||||||
|
const content = choice?.message?.content || "";
|
||||||
|
const results = extractJsonArray(content);
|
||||||
|
const pairs = [];
|
||||||
|
if (results && results.length) {
|
||||||
|
for (const item of results) {
|
||||||
|
const d = deals[item.index - 1];
|
||||||
|
if (d && item.category) pairs.push({ deal: d, item });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
pairs,
|
||||||
|
finish: choice?.finish_reason,
|
||||||
|
contentLen: content.length,
|
||||||
|
reasoning: response.usage?.completion_tokens_details?.reasoning_tokens,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 请求 LLM 分类,并对 reasoning 模型“思考吃光 max_tokens → content 被截断为空”
|
||||||
|
* 的情况自愈:把批量对半拆分、顺序重试(深度上限 6,最细拆到单条)。
|
||||||
|
* 返回 [{ deal, item }]。
|
||||||
|
*/
|
||||||
|
async function classifyViaLLM(deals, client, userId, cats, depth) {
|
||||||
|
const r = await requestLLMClassification(
|
||||||
|
deals,
|
||||||
|
client,
|
||||||
|
userId,
|
||||||
|
cats,
|
||||||
|
MAX_TOKENS,
|
||||||
|
);
|
||||||
|
if (r.pairs.length) return r.pairs;
|
||||||
|
|
||||||
|
if (r.finish === "length" && deals.length > 1 && depth < 6) {
|
||||||
|
const mid = Math.ceil(deals.length / 2);
|
||||||
|
console.warn(
|
||||||
|
`[Reco] classifyDeals — LLM 输出被截断 (reasoning=${r.reasoning ?? "-"}, ` +
|
||||||
|
`max_tokens=${MAX_TOKENS}),拆分为 ${mid}+${deals.length - mid} 重试`,
|
||||||
|
);
|
||||||
|
const a = await classifyViaLLM(
|
||||||
|
deals.slice(0, mid),
|
||||||
|
client,
|
||||||
|
userId,
|
||||||
|
cats,
|
||||||
|
depth + 1,
|
||||||
|
);
|
||||||
|
const b = await classifyViaLLM(
|
||||||
|
deals.slice(mid),
|
||||||
|
client,
|
||||||
|
userId,
|
||||||
|
cats,
|
||||||
|
depth + 1,
|
||||||
|
);
|
||||||
|
return [...a, ...b];
|
||||||
|
}
|
||||||
|
|
||||||
|
console.warn(
|
||||||
|
`[Reco] classifyDeals — LLM 返回不可解析,退回规则 (finish=${r.finish}, ` +
|
||||||
|
`content=${r.contentLen}字, reasoning=${r.reasoning ?? "-"}, ` +
|
||||||
|
`max_tokens=${MAX_TOKENS})`,
|
||||||
|
);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
/* ============================== 单批 LLM 分类 ============================== */
|
/* ============================== 单批 LLM 分类 ============================== */
|
||||||
async function classifyDeals(dealIds, userId) {
|
async function classifyDeals(dealIds, userId, opts = {}) {
|
||||||
const { getDB } = require("../db");
|
const { getDB } = require("../db");
|
||||||
const db = getDB();
|
const db = getDB();
|
||||||
const ids = Array.isArray(dealIds) ? dealIds : [dealIds];
|
const ids = Array.isArray(dealIds) ? dealIds : [dealIds];
|
||||||
@@ -141,157 +260,243 @@ async function classifyDeals(dealIds, userId) {
|
|||||||
.all(...ids, userId);
|
.all(...ids, userId);
|
||||||
if (!deals.length) return { classified: 0 };
|
if (!deals.length) return { classified: 0 };
|
||||||
|
|
||||||
|
const cats = opts.cats || loadCategories(userId);
|
||||||
const client = getOpenAIClient(userId);
|
const client = getOpenAIClient(userId);
|
||||||
if (client) {
|
if (client) {
|
||||||
|
const t0 = Date.now();
|
||||||
try {
|
try {
|
||||||
const prompt = buildPrompt(deals, userId);
|
const pairs = await classifyViaLLM(deals, client, userId, cats, 0);
|
||||||
const t0 = Date.now();
|
if (pairs.length) {
|
||||||
const response = await client.chat.completions.create({
|
|
||||||
model: client._model,
|
|
||||||
messages: [
|
|
||||||
{
|
|
||||||
role: "system",
|
|
||||||
content:
|
|
||||||
"你是财务分析助手。只返回要求的JSON数组,不要任何额外文字。",
|
|
||||||
},
|
|
||||||
{ role: "user", content: prompt },
|
|
||||||
],
|
|
||||||
temperature: 0.3,
|
|
||||||
max_tokens: 4000,
|
|
||||||
});
|
|
||||||
|
|
||||||
const rawContent = response.choices[0]?.message?.content || "";
|
|
||||||
const results = extractJsonArray(rawContent);
|
|
||||||
|
|
||||||
if (results && results.length > 0) {
|
|
||||||
const upd = db.prepare(
|
const upd = db.prepare(
|
||||||
"UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
"UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||||
);
|
);
|
||||||
db.transaction(() => {
|
db.transaction(() => {
|
||||||
for (const item of results) {
|
for (const { deal, item } of pairs) {
|
||||||
const d = deals[item.index - 1];
|
upd.run(
|
||||||
if (d && item.category) {
|
item.category,
|
||||||
upd.run(
|
item.description || "",
|
||||||
item.category,
|
item.confidence || 0.8,
|
||||||
item.description || "",
|
item.category,
|
||||||
item.confidence || 0.8,
|
deal.id,
|
||||||
item.category,
|
);
|
||||||
d.id,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
// 截断到单条仍失败的个别 deal,用规则补齐
|
||||||
|
const covered = new Set(pairs.map((p) => p.deal.id));
|
||||||
|
const missing = deals.filter((d) => !covered.has(d.id));
|
||||||
|
let filled = 0;
|
||||||
|
if (missing.length) {
|
||||||
|
const r = classifyDealsByRules(missing, userId, cats);
|
||||||
|
filled = r.classified;
|
||||||
|
}
|
||||||
console.log(
|
console.log(
|
||||||
`[Reco] classifyDeals — 完成 ${results.length} 条, 耗时 ${Date.now() - t0}ms, 来源: llm`,
|
`[Reco] classifyDeals — 完成 ${pairs.length + filled} 条, 耗时 ${Date.now() - t0}ms, 来源: llm`,
|
||||||
);
|
);
|
||||||
return { classified: results.length, source: "llm" };
|
return { classified: pairs.length + filled, source: "llm" };
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(`[Reco] classifyDeals — LLM调用失败:`, e.message);
|
console.error(`[Reco] classifyDeals — LLM调用失败:`, e.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return classifyDealsByRules(deals, userId);
|
return classifyDealsByRules(deals, userId, cats);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ============================== 规则兜底分类 ============================== */
|
/* ============================== 规则兜底分类 ============================== */
|
||||||
function classifyDealsByRules(deals, userId) {
|
// 关键词打分;category=null/score=0 表示没命中任何关键词
|
||||||
|
function bestRuleCategory(deal, cats) {
|
||||||
|
const text = (
|
||||||
|
(deal.description || "") +
|
||||||
|
" " +
|
||||||
|
(deal.counterparty || "")
|
||||||
|
).toLowerCase();
|
||||||
|
let category = null;
|
||||||
|
let score = 0;
|
||||||
|
for (const c of cats) {
|
||||||
|
let s = 0;
|
||||||
|
for (const kw of c.keywords) {
|
||||||
|
if (kw && text.includes(kw.toLowerCase())) s++;
|
||||||
|
}
|
||||||
|
if (s > score) {
|
||||||
|
score = s;
|
||||||
|
category = c.name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { category, score };
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildRuleDescription(deal) {
|
||||||
|
const income = parseFloat(deal.amount) >= 0;
|
||||||
|
const desc =
|
||||||
|
(income ? "收到" : "向") +
|
||||||
|
(deal.counterparty || "对方") +
|
||||||
|
(income ? "" : "支付") +
|
||||||
|
Math.abs(Number(deal.amount) || 0).toFixed(2) +
|
||||||
|
"元";
|
||||||
|
return desc.substring(0, 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 规则分类并写库。
|
||||||
|
* onlyMatched=false:全部写入,未命中归入「其他杂项」(纯规则兑底)。
|
||||||
|
* onlyMatched=true :只写命中关键词的,未命中的返回给 LLM 处理。
|
||||||
|
*/
|
||||||
|
function applyRules(deals, cats, { onlyMatched = false } = {}) {
|
||||||
const { getDB } = require("../db");
|
const { getDB } = require("../db");
|
||||||
const db = getDB();
|
const db = getDB();
|
||||||
const cats = db
|
|
||||||
.prepare("SELECT id, name, keywords FROM categories WHERE user_id = ?")
|
|
||||||
.all(userId);
|
|
||||||
const upd = db.prepare(
|
const upd = db.prepare(
|
||||||
"UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
"UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||||
);
|
);
|
||||||
|
let matched = 0;
|
||||||
const t0 = Date.now();
|
let unclassified = 0;
|
||||||
|
const unmatched = [];
|
||||||
|
// 兜底分类:优先「其他杂项」;用户删掉该分类后就不再强行归类
|
||||||
|
const hasFallback = cats.some((c) => c.name === "其他杂项");
|
||||||
db.transaction(() => {
|
db.transaction(() => {
|
||||||
for (const d of deals) {
|
for (const d of deals) {
|
||||||
const text = (d.description + " " + d.counterparty).toLowerCase();
|
const { category, score } = bestRuleCategory(d, cats);
|
||||||
let best = "其他杂项",
|
if (!category && onlyMatched) {
|
||||||
score = 0;
|
unmatched.push(d);
|
||||||
for (const c of cats) {
|
continue;
|
||||||
let s = 0;
|
|
||||||
for (const kw of JSON.parse(c.keywords || "[]")) {
|
|
||||||
if (kw && text.includes(kw.toLowerCase())) s++;
|
|
||||||
}
|
|
||||||
if (s > score) {
|
|
||||||
score = s;
|
|
||||||
best = c.name;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
const directionText = parseFloat(d.amount) >= 0 ? "收到" : "向";
|
const finalCategory = category || (hasFallback ? "其他杂项" : null);
|
||||||
const actionText = parseFloat(d.amount) >= 0 ? "" : "支付";
|
if (!finalCategory) {
|
||||||
const desc =
|
unclassified++;
|
||||||
directionText +
|
continue;
|
||||||
(d.counterparty || "对方") +
|
}
|
||||||
actionText +
|
upd.run(
|
||||||
Math.abs(d.amount).toFixed(2) +
|
finalCategory,
|
||||||
"元";
|
buildRuleDescription(d),
|
||||||
upd.run(best, desc.substring(0, 100), score > 0 ? 0.7 : 0.3, best, d.id);
|
score > 0 ? 0.7 : 0.3,
|
||||||
|
finalCategory,
|
||||||
|
d.id,
|
||||||
|
);
|
||||||
|
if (score > 0) matched++;
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
return { matched, unmatched, unclassified };
|
||||||
|
}
|
||||||
|
|
||||||
|
function classifyDealsByRules(deals, userId, cats) {
|
||||||
|
if (!cats) cats = loadCategories(userId);
|
||||||
|
const t0 = Date.now();
|
||||||
|
const { matched, unclassified } = applyRules(deals, cats, {
|
||||||
|
onlyMatched: false,
|
||||||
|
});
|
||||||
|
const classified = deals.length - unclassified;
|
||||||
|
if (unclassified > 0) {
|
||||||
|
console.warn(
|
||||||
|
`[Reco] classifyDealsByRules — ${unclassified} 条无关键词命中且无「其他杂项」兜底,保持待分类`,
|
||||||
|
);
|
||||||
|
}
|
||||||
console.log(
|
console.log(
|
||||||
`[Reco] classifyDealsByRules — ${deals.length} 条, ${Date.now() - t0}ms, 来源: rules`,
|
`[Reco] classifyDealsByRules — ${classified}/${deals.length} 条(命中 ${matched}), ${Date.now() - t0}ms, 来源: rules`,
|
||||||
);
|
);
|
||||||
return { classified: deals.length, source: "rules" };
|
return { classified, source: "rules" };
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ============================== AI分类全部(并行) ============================== */
|
/* ============================== AI分类全部(并行) ============================== */
|
||||||
async function classifyAllDeals(userId) {
|
async function classifyAllDeals(userId, cats, stale, job) {
|
||||||
const { getDB } = require("../db");
|
const t0 = Date.now();
|
||||||
const db = getDB();
|
|
||||||
|
|
||||||
const cats = db
|
// 1) 规则优先:命中关键词的直接定,只有没命中的才交给 LLM
|
||||||
.prepare("SELECT name FROM categories WHERE user_id = ?")
|
const { matched, unmatched } = applyRules(stale, cats, { onlyMatched: true });
|
||||||
.all(userId)
|
job.done = matched;
|
||||||
.map((r) => r.name);
|
if (matched > 0) job.source = "rules";
|
||||||
|
console.log(
|
||||||
|
`[Reco] classifyAll — 规则命中 ${matched}/${stale.length},剩余 ${unmatched.length} 交 LLM`,
|
||||||
|
);
|
||||||
|
|
||||||
if (!cats.length) {
|
// 2) LLM 处理未命中的(分批 + 并发)
|
||||||
return { classified: 0, total: 0, source: "none" };
|
if (unmatched.length) {
|
||||||
}
|
const batches = [];
|
||||||
|
for (let i = 0; i < unmatched.length; i += BATCH_SIZE) {
|
||||||
const ph = cats.map(() => "?").join(",");
|
batches.push(unmatched.slice(i, i + BATCH_SIZE));
|
||||||
const stale = db
|
}
|
||||||
.prepare(
|
for (let i = 0; i < batches.length; i += CONCURRENCY) {
|
||||||
`SELECT id FROM deals WHERE (category IS NULL OR category NOT IN (${ph})) AND user_id = ?`,
|
const group = batches.slice(i, i + CONCURRENCY);
|
||||||
)
|
const results = await Promise.all(
|
||||||
.all(...cats, userId);
|
group.map((b) => classifyDeals(b.map((d) => d.id), userId, { cats })),
|
||||||
|
);
|
||||||
if (!stale.length) {
|
for (const r of results) {
|
||||||
return { classified: 0, total: 0, source: "none" };
|
job.done += r.classified || 0;
|
||||||
}
|
if (r.source === "llm") job.source = "llm";
|
||||||
|
}
|
||||||
const ids = stale.map((r) => r.id);
|
|
||||||
const batches = [];
|
|
||||||
for (let i = 0; i < ids.length; i += BATCH_SIZE) {
|
|
||||||
batches.push(ids.slice(i, i + BATCH_SIZE));
|
|
||||||
}
|
|
||||||
|
|
||||||
let totalClassified = 0;
|
|
||||||
let source = "rules";
|
|
||||||
const tStart = Date.now();
|
|
||||||
|
|
||||||
for (let i = 0; i < batches.length; i += CONCURRENCY) {
|
|
||||||
const chunk = batches.slice(i, i + CONCURRENCY);
|
|
||||||
const results = await Promise.all(
|
|
||||||
chunk.map((b) => classifyDeals(b, userId)),
|
|
||||||
);
|
|
||||||
for (const r of results) {
|
|
||||||
totalClassified += r.classified;
|
|
||||||
if (r.source === "llm") source = "llm";
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(
|
console.log(
|
||||||
`[Reco] classifyAllDeals — ${totalClassified}/${ids.length} 条, 来源: ${source}, ${Date.now() - tStart}ms`,
|
`[Reco] classifyAll — 完成 ${job.done}/${stale.length} 条, 来源: ${job.source}, ${Date.now() - t0}ms`,
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return { classified: totalClassified, total: ids.length, source };
|
const runningJobs = new Map(); // userId -> { total, done, source, startedAt }
|
||||||
|
|
||||||
|
function getStaleDeals(userId, cats) {
|
||||||
|
const { getDB } = require("../db");
|
||||||
|
const names = cats.map((c) => c.name);
|
||||||
|
if (!names.length) return [];
|
||||||
|
const ph = names.map(() => "?").join(",");
|
||||||
|
return getDB()
|
||||||
|
.prepare(
|
||||||
|
`SELECT * FROM deals WHERE (category IS NULL OR category NOT IN (${ph})) AND user_id = ?`,
|
||||||
|
)
|
||||||
|
.all(...names, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 启动全量分类:后台执行、立即返回,前端轮询 classify-status 拿进度。
|
||||||
|
* 同一用户已在跑时重复点击直接返回当前任务状态。
|
||||||
|
*/
|
||||||
|
function startClassifyAll(userId) {
|
||||||
|
const running = runningJobs.get(userId);
|
||||||
|
if (running) {
|
||||||
|
return {
|
||||||
|
started: false,
|
||||||
|
running: true,
|
||||||
|
total: running.total,
|
||||||
|
done: running.done,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const cats = loadCategories(userId);
|
||||||
|
if (!cats.length) return { started: false, running: false, total: 0, done: 0 };
|
||||||
|
|
||||||
|
const stale = getStaleDeals(userId, cats);
|
||||||
|
if (!stale.length) return { started: false, running: false, total: 0, done: 0 };
|
||||||
|
|
||||||
|
const job = {
|
||||||
|
total: stale.length,
|
||||||
|
done: 0,
|
||||||
|
source: "rules",
|
||||||
|
startedAt: Date.now(),
|
||||||
|
};
|
||||||
|
runningJobs.set(userId, job);
|
||||||
|
classifyAllDeals(userId, cats, stale, job)
|
||||||
|
.catch((e) => console.error("[Reco] classifyAll 后台任务失败:", e))
|
||||||
|
.finally(() => runningJobs.delete(userId));
|
||||||
|
|
||||||
|
return { started: true, running: true, total: job.total, done: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
function getClassifyStatus(userId) {
|
||||||
|
const job = runningJobs.get(userId);
|
||||||
|
if (!job) return { running: false, total: 0, done: 0, source: null };
|
||||||
|
return {
|
||||||
|
running: true,
|
||||||
|
total: job.total,
|
||||||
|
done: job.done,
|
||||||
|
source: job.source,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
classifyDeals,
|
classifyDeals,
|
||||||
classifyAllDeals,
|
startClassifyAll,
|
||||||
|
getClassifyStatus,
|
||||||
getOpenAIClient,
|
getOpenAIClient,
|
||||||
|
buildPrompt,
|
||||||
|
loadCategories,
|
||||||
|
BATCH_SIZE,
|
||||||
|
CONCURRENCY,
|
||||||
|
MAX_TOKENS,
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user