refactor(数据模型): 分类/确认字段从transactions迁移到deals
- deals表新增direction/category/ai_category/ai_description/ai_confidence/reviewed/review_notes/reviewed_at/tags - transactions表不再写入这些字段(旧数据保留) - classifyDeals替代classifyTransactions, AI分类改到deal级别 - needs-classify/classify-all查询deals - deals路由新增PUT :id编辑接口 - 前端交易明细去掉分类列和编辑弹框分类字段
This commit is contained in:
+73
-96
@@ -1,22 +1,19 @@
|
||||
const Database = require("better-sqlite3");
|
||||
const path = require("path");
|
||||
const Database = require('better-sqlite3');
|
||||
const path = require('path');
|
||||
|
||||
const DB_PATH = path.join(__dirname, "..", "data", "reco.db");
|
||||
const DB_PATH = path.join(__dirname, '..', 'data', 'reco.db');
|
||||
|
||||
// Ensure data directory exists
|
||||
const fs = require("fs");
|
||||
const dataDir = path.join(__dirname, "..", "data");
|
||||
if (!fs.existsSync(dataDir)) {
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
}
|
||||
const fs = require('fs');
|
||||
const dataDir = path.join(__dirname, '..', 'data');
|
||||
if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
|
||||
|
||||
let db;
|
||||
|
||||
function getDB() {
|
||||
if (!db) {
|
||||
db = new Database(DB_PATH);
|
||||
db.pragma("journal_mode = WAL");
|
||||
db.pragma("foreign_keys = ON");
|
||||
db.pragma('journal_mode = WAL');
|
||||
db.pragma('foreign_keys = ON');
|
||||
}
|
||||
return db;
|
||||
}
|
||||
@@ -25,93 +22,68 @@ function initDB() {
|
||||
const database = getDB();
|
||||
|
||||
database.exec(`
|
||||
-- 交易来源表:记录每一次导入的账单文件
|
||||
CREATE TABLE IF NOT EXISTS sources (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
source_type TEXT NOT NULL, -- 'alipay', 'wechat', 'bank_debit', 'bank_credit', 'credit_card'
|
||||
source_name TEXT NOT NULL, -- 用户自定义名称,如 "工商银行工资卡"
|
||||
source_type TEXT NOT NULL,
|
||||
source_name TEXT NOT NULL,
|
||||
file_name TEXT NOT NULL,
|
||||
file_hash TEXT,
|
||||
imported_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
record_count INTEGER DEFAULT 0
|
||||
);
|
||||
|
||||
-- 交易记录表:每一笔原始交易
|
||||
CREATE TABLE IF NOT EXISTS transactions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
transaction_code TEXT UNIQUE NOT NULL, -- 统一交易编码
|
||||
transaction_code TEXT UNIQUE NOT NULL,
|
||||
source_id INTEGER NOT NULL,
|
||||
source_type TEXT NOT NULL,
|
||||
|
||||
-- 时间相关
|
||||
transaction_date DATE NOT NULL,
|
||||
transaction_time DATETIME,
|
||||
|
||||
-- 交易方信息
|
||||
counterparty TEXT, -- 交易对方
|
||||
description TEXT, -- 原始描述/商品说明
|
||||
notes TEXT, -- 备注
|
||||
|
||||
-- 金额
|
||||
amount REAL NOT NULL, -- 交易金额(正=收入,负=支出)
|
||||
counterparty TEXT,
|
||||
description TEXT,
|
||||
notes TEXT,
|
||||
amount REAL NOT NULL,
|
||||
currency TEXT DEFAULT 'CNY',
|
||||
balance REAL, -- 余额(如有)
|
||||
|
||||
-- 交易属性
|
||||
direction TEXT, -- 'income' | 'expense' | 'transfer'
|
||||
status TEXT, -- 交易状态
|
||||
method TEXT, -- 支付方式
|
||||
category TEXT, -- 分类(大模型生成或手动指定)
|
||||
ai_category TEXT, -- 大模型原始分类
|
||||
ai_description TEXT, -- 大模型生成的描述
|
||||
ai_confidence REAL, -- 大模型置信度
|
||||
|
||||
-- 对账相关
|
||||
matched_transaction_id INTEGER, -- 匹配到的另一笔交易ID(银行扣款↔支付宝支出)
|
||||
match_score REAL, -- 匹配置信度 0-1
|
||||
reviewed INTEGER DEFAULT 0, -- 是否已人工确认 0=未确认 1=已确认
|
||||
review_notes TEXT, -- 人工备注
|
||||
reviewed_at DATETIME,
|
||||
|
||||
-- 标签
|
||||
tags TEXT, -- JSON数组字符串
|
||||
|
||||
balance REAL,
|
||||
direction TEXT,
|
||||
status TEXT,
|
||||
method TEXT,
|
||||
matched_transaction_id INTEGER,
|
||||
match_score REAL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (matched_transaction_id) REFERENCES transactions(id) ON DELETE SET NULL
|
||||
FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- 分类配置表:保存大模型分类类别
|
||||
CREATE TABLE IF NOT EXISTS categories (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
keywords TEXT, -- JSON数组:关联关键词
|
||||
keywords TEXT,
|
||||
parent_id INTEGER,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- 配置表
|
||||
CREATE TABLE IF NOT EXISTS config (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT
|
||||
);
|
||||
|
||||
-- 索引
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_date ON transactions(transaction_date);
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_code ON transactions(transaction_code);
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_amount ON transactions(amount);
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_source ON transactions(source_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_reviewed ON transactions(reviewed);
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_matched ON transactions(matched_transaction_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_category ON transactions(category);
|
||||
CREATE TABLE IF NOT EXISTS deals (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
deal_date DATE NOT NULL,
|
||||
deal_date DATETIME NOT NULL,
|
||||
amount REAL NOT NULL,
|
||||
direction TEXT,
|
||||
counterparty TEXT,
|
||||
description TEXT,
|
||||
match_count INTEGER DEFAULT 2,
|
||||
match_count INTEGER DEFAULT 1,
|
||||
category TEXT,
|
||||
ai_category TEXT,
|
||||
ai_description TEXT,
|
||||
ai_confidence REAL,
|
||||
reviewed INTEGER DEFAULT 0,
|
||||
review_notes TEXT,
|
||||
reviewed_at DATETIME,
|
||||
tags TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
@@ -123,47 +95,52 @@ function initDB() {
|
||||
FOREIGN KEY (transaction_id) REFERENCES transactions(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_date ON transactions(transaction_date);
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_code ON transactions(transaction_code);
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_amount ON transactions(amount);
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_source ON transactions(source_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_matched ON transactions(matched_transaction_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_deal_date ON deals(deal_date);
|
||||
CREATE INDEX IF NOT EXISTS idx_dt_deal ON deal_transactions(deal_id);
|
||||
|
||||
`);
|
||||
|
||||
// 仅首次初始化时插入默认分类(不再用固定ID)
|
||||
const catCount = database
|
||||
.prepare("SELECT COUNT(*) as c FROM categories")
|
||||
.get().c;
|
||||
if (catCount === 0) {
|
||||
const insertCategory = database.prepare(
|
||||
"INSERT INTO categories (name, keywords) VALUES (?, ?)",
|
||||
);
|
||||
const defaults = [
|
||||
["餐饮美食", '["餐厅","外卖","食堂","咖啡","奶茶","零食","水果","买菜"]'],
|
||||
[
|
||||
"交通出行",
|
||||
'["公交","地铁","打车","出租车","加油","停车","高速","火车","飞机","骑行"]',
|
||||
],
|
||||
[
|
||||
"购物消费",
|
||||
'["淘宝","京东","拼多多","超市","百货","服饰","数码","家电","日用品"]',
|
||||
],
|
||||
["住房相关", '["房租","房贷","物业","水电","燃气","维修","装修"]'],
|
||||
["通讯网络", '["话费","宽带","流量"]'],
|
||||
["投资理财", '["基金","股票","理财","定期","转入","转出","收益"]'],
|
||||
["工资收入", '["工资","薪资","奖金","报销","劳务"]'],
|
||||
["转账红包", '["转账","红包","汇款","收款","提现","充值"]'],
|
||||
["医疗健康", '["医院","药店","挂号","体检","保险"]'],
|
||||
["教育学习", '["学费","培训","书本","课程","考试"]'],
|
||||
["娱乐休闲", '["电影","演出","旅游","酒店","游戏","充值","会员"]'],
|
||||
["信用卡还款", '["还款","信用卡","花呗","借呗","白条"]'],
|
||||
["其他杂项", "[]"],
|
||||
// 兼容旧库:为 deals 表添加新字段
|
||||
try {
|
||||
const dealCols = database.prepare('PRAGMA table_info(deals)').all().map(r => r.name);
|
||||
const newCols = [
|
||||
['direction', 'TEXT'], ['category', 'TEXT'], ['ai_category', 'TEXT'],
|
||||
['ai_description', 'TEXT'], ['ai_confidence', 'REAL'], ['reviewed', 'INTEGER DEFAULT 0'],
|
||||
['review_notes', 'TEXT'], ['reviewed_at', 'DATETIME'], ['tags', 'TEXT']
|
||||
];
|
||||
database.transaction(() => {
|
||||
defaults.forEach((c) => insertCategory.run(c[0], c[1]));
|
||||
})();
|
||||
console.log("[Reco] 已初始化默认分类");
|
||||
for (const [col, type] of newCols) {
|
||||
if (!dealCols.includes(col)) database.exec('ALTER TABLE deals ADD COLUMN ' + col + ' ' + type);
|
||||
}
|
||||
} catch (e) {}
|
||||
|
||||
// 仅首次初始化默认分类
|
||||
const catCount = database.prepare('SELECT COUNT(*) as c FROM categories').get().c;
|
||||
if (catCount === 0) {
|
||||
const ins = database.prepare('INSERT INTO categories (name, keywords) VALUES (?, ?)');
|
||||
const defaults = [
|
||||
['餐饮美食', '["餐厅","外卖","食堂","咖啡","奶茶","零食","水果","买菜"]'],
|
||||
['交通出行', '["公交","地铁","打车","出租车","加油","停车","高速","火车","飞机","骑行"]'],
|
||||
['购物消费', '["淘宝","京东","拼多多","超市","百货","服饰","数码","家电","日用品"]'],
|
||||
['住房相关', '["房租","房贷","物业","水电","燃气","维修","装修"]'],
|
||||
['通讯网络', '["话费","宽带","流量"]'],
|
||||
['投资理财', '["基金","股票","理财","定期","转入","转出","收益"]'],
|
||||
['工资收入', '["工资","薪资","奖金","报销","劳务"]'],
|
||||
['转账红包', '["转账","红包","汇款","收款","提现","充值"]'],
|
||||
['医疗健康', '["医院","药店","挂号","体检","保险"]'],
|
||||
['教育学习', '["学费","培训","书本","课程","考试"]'],
|
||||
['娱乐休闲', '["电影","演出","旅游","酒店","游戏","充值","会员"]'],
|
||||
['信用卡还款', '["还款","信用卡","花呗","借呗","白条"]'],
|
||||
['其他杂项', '[]']
|
||||
];
|
||||
database.transaction(() => { defaults.forEach(c => ins.run(c[0], c[1])); })();
|
||||
console.log('[Reco] 已初始化默认分类');
|
||||
}
|
||||
|
||||
console.log("[Reco] 数据库初始化完成");
|
||||
console.log('[Reco] 数据库初始化完成');
|
||||
}
|
||||
|
||||
module.exports = { getDB, initDB };
|
||||
|
||||
+15
-74
@@ -2,7 +2,7 @@ const express = require('express');
|
||||
const { getDB } = require('../db');
|
||||
const router = express.Router();
|
||||
|
||||
// GET /api/deals — 获取所有对账关联
|
||||
// GET /api/deals
|
||||
router.get('/', (req, res) => {
|
||||
const db = getDB();
|
||||
const { page = 1, limit = 50 } = req.query;
|
||||
@@ -20,7 +20,6 @@ router.get('/', (req, res) => {
|
||||
|
||||
const total = db.prepare('SELECT COUNT(*) as c FROM deals').get().c;
|
||||
|
||||
// 加载每笔 deal 的关联交易
|
||||
for (const deal of deals) {
|
||||
deal.transactions = db.prepare(`
|
||||
SELECT t.*, s.source_name
|
||||
@@ -28,85 +27,27 @@ router.get('/', (req, res) => {
|
||||
JOIN transactions t ON t.id = dt.transaction_id
|
||||
LEFT JOIN sources s ON s.id = t.source_id
|
||||
WHERE dt.deal_id = ?
|
||||
ORDER BY t.transaction_date
|
||||
`).all(deal.id);
|
||||
}
|
||||
|
||||
res.json({ deals, total, page: Number(page), totalPages: Math.ceil(total / limit) });
|
||||
});
|
||||
|
||||
// POST /api/deals/generate — 根据现有 matched 关系生成 deals
|
||||
router.post('/generate', (req, res) => {
|
||||
// PUT /api/deals/:id — 编辑分类/确认
|
||||
router.put('/:id', (req, res) => {
|
||||
const db = getDB();
|
||||
|
||||
// 清除旧数据
|
||||
db.prepare('DELETE FROM deal_transactions').run();
|
||||
db.prepare('DELETE FROM deals').run();
|
||||
|
||||
// 查找所有已匹配的交易对(只取一方避免重复)
|
||||
const pairs = db.prepare(`
|
||||
SELECT DISTINCT
|
||||
MIN(t1.id, t2.id) as id1,
|
||||
MAX(t1.id, t2.id) as id2,
|
||||
t1.transaction_date as d1, t2.transaction_date as d2,
|
||||
t1.amount as a1, t2.amount as a2,
|
||||
t1.counterparty as cp1, t2.counterparty as cp2,
|
||||
t1.description as desc1, t2.description as desc2,
|
||||
t1.match_score
|
||||
FROM transactions t1
|
||||
JOIN transactions t2 ON t2.id = t1.matched_transaction_id
|
||||
WHERE t1.matched_transaction_id IS NOT NULL
|
||||
AND t1.id < t1.matched_transaction_id
|
||||
ORDER BY ABS(t1.amount) DESC
|
||||
`).all();
|
||||
|
||||
const insertDeal = db.prepare('INSERT INTO deals (deal_date, amount, counterparty, description) VALUES (?,?,?,?)');
|
||||
const insertDt = db.prepare('INSERT OR IGNORE INTO deal_transactions (deal_id, transaction_id) VALUES (?,?)');
|
||||
|
||||
let count = 0;
|
||||
for (const p of pairs) {
|
||||
const dealDate = p.d1 || p.d2;
|
||||
const amount = p.a1 || p.a2;
|
||||
const cp = [p.cp1, p.cp2].filter(Boolean).join(' / ');
|
||||
const desc = [p.desc1, p.desc2].filter(Boolean).join(' / ');
|
||||
const r = insertDeal.run(dealDate, amount, cp, desc);
|
||||
insertDt.run(r.lastInsertRowid, p.id1);
|
||||
insertDt.run(r.lastInsertRowid, p.id2);
|
||||
count++;
|
||||
}
|
||||
|
||||
res.json({ success: true, generated: count, total: pairs.length });
|
||||
});
|
||||
|
||||
// POST /api/deals/refresh — 刷新 deals(增量更新)
|
||||
router.post('/refresh', (req, res) => {
|
||||
const db = getDB();
|
||||
|
||||
// 找到有 matched 但不在 deals 中的交易
|
||||
const matched = db.prepare(`
|
||||
SELECT t1.id as id1, t2.id as id2, t1.transaction_date, t1.amount,
|
||||
t1.counterparty as cp1, t2.counterparty as cp2,
|
||||
t1.description as desc1, t2.description as desc2
|
||||
FROM transactions t1
|
||||
JOIN transactions t2 ON t2.id = t1.matched_transaction_id
|
||||
WHERE t1.id < t1.matched_transaction_id
|
||||
AND t1.id NOT IN (SELECT transaction_id FROM deal_transactions)
|
||||
`).all();
|
||||
|
||||
if (matched.length === 0) return res.json({ success: true, added: 0 });
|
||||
|
||||
const insertDeal = db.prepare('INSERT INTO deals (deal_date, amount, counterparty, description) VALUES (?,?,?,?)');
|
||||
const insertDt = db.prepare('INSERT OR IGNORE INTO deal_transactions (deal_id, transaction_id) VALUES (?,?)');
|
||||
|
||||
for (const p of matched) {
|
||||
const r = insertDeal.run(p.transaction_date, p.amount,
|
||||
[p.cp1, p.cp2].filter(Boolean).join(' / '),
|
||||
[p.desc1, p.desc2].filter(Boolean).join(' / '));
|
||||
insertDt.run(r.lastInsertRowid, p.id1);
|
||||
insertDt.run(r.lastInsertRowid, p.id2);
|
||||
}
|
||||
|
||||
res.json({ success: true, added: matched.length });
|
||||
const { category, ai_description, reviewed, review_notes, tags } = req.body;
|
||||
const sets = []; const params = [];
|
||||
if (category !== undefined) { sets.push('category = ?'); params.push(category); }
|
||||
if (ai_description !== undefined) { sets.push('ai_description = ?'); params.push(ai_description); }
|
||||
if (reviewed !== undefined) { sets.push('reviewed = ?'); params.push(reviewed); if (reviewed) sets.push('reviewed_at = CURRENT_TIMESTAMP'); }
|
||||
if (review_notes !== undefined) { sets.push('review_notes = ?'); params.push(review_notes); }
|
||||
if (tags !== undefined) { sets.push('tags = ?'); params.push(JSON.stringify(tags)); }
|
||||
if (!sets.length) return res.status(400).json({ error: '无更新字段' });
|
||||
sets.push('updated_at = CURRENT_TIMESTAMP');
|
||||
params.push(req.params.id);
|
||||
db.prepare('UPDATE deals SET ' + sets.join(', ') + ' WHERE id = ?').run(...params);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
+18
-206
@@ -1,7 +1,7 @@
|
||||
const express = require("express");
|
||||
const { getDB } = require("../db");
|
||||
const { runAutoReconciliation } = require("../services/matcher");
|
||||
const { classifyTransactions } = require("../services/llm");
|
||||
const { classifyDeals } = require("../services/llm");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -79,8 +79,6 @@ router.get("/", (req, res) => {
|
||||
"amount",
|
||||
"created_at",
|
||||
"counterparty",
|
||||
"category",
|
||||
"reviewed",
|
||||
];
|
||||
const safeSortBy = allowedSortFields.includes(sort_by)
|
||||
? sort_by
|
||||
@@ -115,214 +113,28 @@ router.get("/", (req, res) => {
|
||||
|
||||
router.get("/needs-classify", (req, res) => {
|
||||
const db = getDB();
|
||||
const validCats = db
|
||||
.prepare("SELECT name FROM categories")
|
||||
.all()
|
||||
.map((r) => r.name);
|
||||
if (validCats.length === 0) return res.json({ ids: [], total: 0 });
|
||||
const ph = validCats.map(() => "?").join(",");
|
||||
const stale = db
|
||||
.prepare(
|
||||
`SELECT id FROM transactions WHERE category IS NULL OR category NOT IN (${ph})`,
|
||||
)
|
||||
.all(...validCats);
|
||||
res.json({ ids: stale.map((r) => r.id), total: stale.length });
|
||||
const cats = db.prepare("SELECT name FROM categories").all().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})`).all(...cats);
|
||||
res.json({ ids: stale.map(r => r.id), total: stale.length });
|
||||
});
|
||||
|
||||
// GET /api/transactions/:id - 获取单笔交易详情
|
||||
router.get("/:id", (req, res) => {
|
||||
const db = getDB();
|
||||
|
||||
const tx = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT t.*, s.source_name
|
||||
FROM transactions t
|
||||
LEFT JOIN sources s ON s.id = t.source_id
|
||||
WHERE t.id = ?
|
||||
`,
|
||||
)
|
||||
.get(req.params.id);
|
||||
|
||||
if (!tx) {
|
||||
return res.status(404).json({ error: "交易不存在" });
|
||||
}
|
||||
|
||||
// 获取关联的匹配交易
|
||||
let matchedTx = null;
|
||||
if (tx.matched_transaction_id) {
|
||||
matchedTx = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT t.*, s.source_name
|
||||
FROM transactions t
|
||||
LEFT JOIN sources s ON s.id = t.source_id
|
||||
WHERE t.id = ?
|
||||
`,
|
||||
)
|
||||
.get(tx.matched_transaction_id);
|
||||
}
|
||||
|
||||
// 获取同一编码的交易(聚合组)
|
||||
const relatedTxs = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT t.*, s.source_name
|
||||
FROM transactions t
|
||||
LEFT JOIN sources s ON s.id = t.source_id
|
||||
WHERE t.transaction_code = ? AND t.id != ?
|
||||
`,
|
||||
)
|
||||
.all(tx.transaction_code, tx.id);
|
||||
|
||||
res.json({
|
||||
transaction: tx,
|
||||
matchedTransaction: matchedTx,
|
||||
relatedTransactions: relatedTxs,
|
||||
});
|
||||
});
|
||||
|
||||
// PUT /api/transactions/:id - 更新交易(人工确认/修改分类和描述)
|
||||
router.put("/:id", (req, res) => {
|
||||
const db = getDB();
|
||||
const { category, ai_description, reviewed, review_notes, tags } = req.body;
|
||||
|
||||
const tx = db
|
||||
.prepare("SELECT * FROM transactions WHERE id = ?")
|
||||
.get(req.params.id);
|
||||
if (!tx) {
|
||||
return res.status(404).json({ error: "交易不存在" });
|
||||
}
|
||||
|
||||
const updates = [];
|
||||
const params = [];
|
||||
|
||||
if (category !== undefined) {
|
||||
updates.push("category = ?");
|
||||
params.push(category);
|
||||
}
|
||||
if (ai_description !== undefined) {
|
||||
updates.push("ai_description = ?");
|
||||
params.push(ai_description);
|
||||
}
|
||||
if (reviewed !== undefined) {
|
||||
updates.push("reviewed = ?");
|
||||
params.push(parseInt(reviewed));
|
||||
if (parseInt(reviewed) === 1) {
|
||||
updates.push("reviewed_at = CURRENT_TIMESTAMP");
|
||||
}
|
||||
}
|
||||
if (review_notes !== undefined) {
|
||||
updates.push("review_notes = ?");
|
||||
params.push(review_notes);
|
||||
}
|
||||
if (tags !== undefined) {
|
||||
updates.push("tags = ?");
|
||||
params.push(JSON.stringify(tags));
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
return res.status(400).json({ error: "没有提供要更新的字段" });
|
||||
}
|
||||
|
||||
updates.push("updated_at = CURRENT_TIMESTAMP");
|
||||
params.push(req.params.id);
|
||||
|
||||
db.prepare(`UPDATE transactions SET ${updates.join(", ")} WHERE id = ?`).run(
|
||||
...params,
|
||||
);
|
||||
|
||||
const updated = db
|
||||
.prepare("SELECT * FROM transactions WHERE id = ?")
|
||||
.get(req.params.id);
|
||||
res.json({ success: true, transaction: updated });
|
||||
});
|
||||
|
||||
// POST /api/transactions/reconcile - 全量清除后重新对账,每笔交易生成deal
|
||||
router.post("/reconcile", (req, res) => {
|
||||
const db = getDB();
|
||||
// 清除旧数据
|
||||
db.prepare("DELETE FROM deal_transactions").run();
|
||||
db.prepare("DELETE FROM deals").run();
|
||||
db.prepare("UPDATE transactions SET matched_transaction_id=NULL, match_score=NULL").run();
|
||||
// 运行自动匹配
|
||||
const result = runAutoReconciliation();
|
||||
// 收集所有交易,按 matched 关系分组
|
||||
const allTxs = db.prepare("SELECT id,transaction_date,transaction_time,amount,counterparty,description,matched_transaction_id FROM transactions ORDER BY transaction_date,transaction_time").all();
|
||||
const visited = new Set(); const groups = [];
|
||||
for (const tx of allTxs) {
|
||||
if (visited.has(tx.id)) continue; visited.add(tx.id);
|
||||
const group = [tx];
|
||||
for (const other of allTxs) {
|
||||
if (visited.has(other.id)) continue;
|
||||
if (other.matched_transaction_id===tx.id||tx.matched_transaction_id===other.id||(tx.matched_transaction_id&&tx.matched_transaction_id===other.matched_transaction_id)) {
|
||||
group.push(other); visited.add(other.id);
|
||||
}
|
||||
}
|
||||
groups.push(group);
|
||||
}
|
||||
// 为每组生成 deal(取最早一笔填充信息)
|
||||
const insD=db.prepare("INSERT INTO deals(deal_date,amount,counterparty,description,match_count)VALUES(?,?,?,?,?)");
|
||||
const insT=db.prepare("INSERT INTO deal_transactions(deal_id,transaction_id)VALUES(?,?)");
|
||||
let dc=0;
|
||||
for(const group of groups){
|
||||
const e=group.reduce((a,b)=>(a.transaction_time||a.transaction_date)<(b.transaction_time||b.transaction_date)?a:b); const dealTime = e.transaction_time || e.transaction_date;
|
||||
const r=insD.run(dealTime,e.amount,e.counterparty,e.description,group.length);
|
||||
for(const tx of group)insT.run(r.lastInsertRowid,tx.id);
|
||||
dc++;
|
||||
}
|
||||
res.json({success:true,matched:result.matched,total:result.total,deals:dc});
|
||||
});
|
||||
|
||||
// POST /api/transactions/classify - 对选中的交易重新分类
|
||||
router.post("/classify", 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 classifyTransactions(ids);
|
||||
res.json({ success: true, ...result });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/transactions/needs-classify
|
||||
// POST /api/transactions/classify-all — 重分类过期分类的交易
|
||||
// POST /api/transactions/classify-all — 重分类 deals
|
||||
router.post("/classify-all", async (req, res) => {
|
||||
const db = getDB();
|
||||
const validCats = db
|
||||
.prepare("SELECT name FROM categories")
|
||||
.all()
|
||||
.map((r) => r.name);
|
||||
if (validCats.length === 0)
|
||||
return res.json({ success: true, classified: 0, message: "无分类配置" });
|
||||
|
||||
const ph = validCats.map(() => "?").join(",");
|
||||
const stale = db
|
||||
.prepare(
|
||||
`SELECT id FROM transactions WHERE category IS NULL OR category NOT IN (${ph})`,
|
||||
)
|
||||
.all(...validCats);
|
||||
if (stale.length === 0)
|
||||
return res.json({
|
||||
success: true,
|
||||
classified: 0,
|
||||
total: 0,
|
||||
message: "所有交易分类均有效",
|
||||
});
|
||||
|
||||
const ids = stale.map((r) => r.id),
|
||||
batchSize = 50;
|
||||
let classified = 0;
|
||||
for (let i = 0; i < ids.length; i += batchSize) {
|
||||
const r = await classifyTransactions(ids.slice(i, i + batchSize));
|
||||
classified += r.classified;
|
||||
const cats = db.prepare("SELECT name FROM categories").all().map(r => r.name);
|
||||
if (!cats.length) return res.json({ classified: 0 });
|
||||
const ph = cats.map(() => "?").join(",");
|
||||
const stale = db.prepare(`SELECT id FROM deals WHERE category IS NULL OR category NOT IN (${ph})`).all(...cats);
|
||||
if (!stale.length) return res.json({ classified: 0, total: 0 });
|
||||
const ids = stale.map(r => r.id), B = 50;
|
||||
let n = 0;
|
||||
for (let i = 0; i < ids.length; i += B) {
|
||||
const r = await classifyDeals(ids.slice(i, i + B));
|
||||
n += r.classified;
|
||||
}
|
||||
res.json({ success: true, classified, total: ids.length });
|
||||
res.json({ success: true, classified: n, total: ids.length });
|
||||
});
|
||||
|
||||
// GET /api/transactions/stats/summary - 获取汇总统计
|
||||
|
||||
@@ -154,8 +154,8 @@ router.post("/confirm", (req, res) => {
|
||||
|
||||
const ins = db.prepare(`INSERT OR IGNORE INTO transactions (
|
||||
transaction_code, source_id, source_type, transaction_date, transaction_time,
|
||||
counterparty, description, notes, amount, direction, status, method, balance, tags
|
||||
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)`);
|
||||
counterparty, description, notes, amount, direction, status, method, balance
|
||||
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`);
|
||||
|
||||
let inserted = 0,
|
||||
skip = 0;
|
||||
|
||||
+41
-78
@@ -2,133 +2,96 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const CONFIG_PATH = path.join(__dirname, '..', '..', 'data', 'llm_config.json');
|
||||
|
||||
let openaiClient = null;
|
||||
|
||||
function loadConfig() {
|
||||
try {
|
||||
if (fs.existsSync(CONFIG_PATH)) return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
|
||||
} catch (e) {}
|
||||
try { if (fs.existsSync(CONFIG_PATH)) return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8')); } catch (e) {}
|
||||
return {};
|
||||
}
|
||||
|
||||
function saveConfig(cfg) {
|
||||
const dir = path.dirname(CONFIG_PATH);
|
||||
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2), 'utf-8');
|
||||
}
|
||||
|
||||
function resetClient() {
|
||||
openaiClient = null;
|
||||
}
|
||||
function resetClient() { openaiClient = null; }
|
||||
|
||||
function getOpenAIClient() {
|
||||
if (openaiClient) return openaiClient;
|
||||
|
||||
const cfg = loadConfig();
|
||||
const apiKey = cfg.llm_api_key;
|
||||
const baseURL = cfg.llm_base_url || 'https://api.openai.com/v1';
|
||||
const model = cfg.llm_model || 'gpt-4o-mini';
|
||||
|
||||
if (!apiKey) return null;
|
||||
|
||||
if (!cfg.llm_api_key) return null;
|
||||
const { OpenAI } = require('openai');
|
||||
openaiClient = new OpenAI({ apiKey, baseURL });
|
||||
openaiClient._model = model;
|
||||
openaiClient = new OpenAI({ apiKey: cfg.llm_api_key, baseURL: cfg.llm_base_url || 'https://api.openai.com/v1' });
|
||||
openaiClient._model = cfg.llm_model || 'gpt-4o-mini';
|
||||
return openaiClient;
|
||||
}
|
||||
|
||||
function buildClassificationPrompt(transactions) {
|
||||
function buildPrompt(deals) {
|
||||
const { getDB } = require('../db');
|
||||
const db = getDB();
|
||||
const categories = db.prepare('SELECT id, name, keywords FROM categories').all();
|
||||
const categoryList = categories
|
||||
.map(c => `${c.name}(关键词:${JSON.parse(c.keywords || '[]').join('、')})`)
|
||||
.join('\n');
|
||||
const cats = db.prepare('SELECT id, name, keywords FROM categories').all();
|
||||
const catList = cats.map(c => c.name + '(' + JSON.parse(c.keywords || '[]').join('、') + ')').join('\n');
|
||||
|
||||
const txList = transactions.map((tx, i) =>
|
||||
`[${i + 1}] 日期:${tx.transaction_date} | 金额:${tx.amount.toFixed(2)}元 | 对方:${tx.counterparty || '未知'} | 描述:${tx.description || '无'} | 来源:${tx.source_type}`
|
||||
const dealList = deals.map((d, i) =>
|
||||
`[${i + 1}] 日期:${d.deal_date} | 金额:${d.amount.toFixed(2)}元 | 对方:${d.counterparty || '未知'} | 描述:${d.description || '无'}`
|
||||
).join('\n');
|
||||
|
||||
return `你是一个专业的财务分析助手。请对以下交易记录进行分类和描述。
|
||||
|
||||
## 可用分类:
|
||||
${categoryList}
|
||||
|
||||
## 交易记录:
|
||||
${txList}
|
||||
|
||||
## 要求:
|
||||
请为每笔交易返回一个JSON数组,每项包含:
|
||||
- index: 交易序号(整数)
|
||||
- category: 最合适的分类名称(必须从上面的可用分类中选择)
|
||||
- description: 用简洁的中文描述这笔交易(10-30字),例如"在星巴克购买咖啡"、"缴纳本月房租"、"收到工资"
|
||||
- confidence: 你对分类的置信度(0-1之间的浮点数)
|
||||
|
||||
仅返回JSON数组,不要包含其他内容。`;
|
||||
return `你是一个专业的财务分析助手。请对以下交易(Deal)进行分类和描述。\n\n## 可用分类:\n${catList}\n\n## 交易记录:\n${dealList}\n\n## 要求:\n为每笔返回JSON数组,每项含:\n- index: 序号\n- category: 分类名称\n- description: 简洁中文描述(10-30字)\n- confidence: 置信度0-1\n\n仅返回JSON数组。`;
|
||||
}
|
||||
|
||||
async function classifyTransactions(transactionIds) {
|
||||
async function classifyDeals(dealIds) {
|
||||
const { getDB } = require('../db');
|
||||
const db = getDB();
|
||||
const ids = Array.isArray(transactionIds) ? transactionIds : [transactionIds];
|
||||
const transactions = db.prepare(`SELECT * FROM transactions WHERE id IN (${ids.map(() => '?').join(',')})`).all(...ids);
|
||||
if (transactions.length === 0) return { classified: 0 };
|
||||
const ids = Array.isArray(dealIds) ? dealIds : [dealIds];
|
||||
const deals = db.prepare(`SELECT * FROM deals WHERE id IN (${ids.map(() => '?').join(',')})`).all(...ids);
|
||||
if (!deals.length) return { classified: 0 };
|
||||
|
||||
const client = getOpenAIClient();
|
||||
if (client) {
|
||||
try {
|
||||
const prompt = buildClassificationPrompt(transactions);
|
||||
const response = await client.chat.completions.create({
|
||||
model: client._model,
|
||||
messages: [
|
||||
{ role: 'system', content: '你是一个专业的财务分析助手,擅长对交易进行分类。请只返回要求的JSON格式。' },
|
||||
{ role: 'user', content: prompt }
|
||||
{ role: 'system', content: '你是财务分析助手。只返回要求的JSON格式。' },
|
||||
{ role: 'user', content: buildPrompt(deals) }
|
||||
],
|
||||
temperature: 0.3, max_tokens: 2000,
|
||||
});
|
||||
const content = response.choices[0].message.content;
|
||||
console.log(content)
|
||||
const jsonMatch = content.match(/\[[\s\S]*\]/);
|
||||
if (jsonMatch) {
|
||||
const results = JSON.parse(jsonMatch[0]);
|
||||
const updateStmt = db.prepare(`UPDATE transactions SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`);
|
||||
const json = response.choices[0].message.content.match(/\[[\s\S]*\]/);
|
||||
if (json) {
|
||||
const results = JSON.parse(json[0]);
|
||||
const upd = db.prepare('UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?');
|
||||
db.transaction(() => {
|
||||
for (const item of results) {
|
||||
const tx = transactions[item.index - 1];
|
||||
if (tx) updateStmt.run(item.category, item.description, item.confidence, item.category, tx.id);
|
||||
const d = deals[item.index - 1];
|
||||
if (d) upd.run(item.category, item.description, item.confidence, item.category, d.id);
|
||||
}
|
||||
})();
|
||||
return { classified: results.length, source: 'llm' };
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[Reco] LLM分类失败,降级规则匹配:', err.message);
|
||||
}
|
||||
} catch (e) { console.error('[Reco] LLM分类失败:', e.message); }
|
||||
}
|
||||
return classifyByRules(transactions);
|
||||
return classifyDealsByRules(deals);
|
||||
}
|
||||
|
||||
function classifyByRules(transactions) {
|
||||
function classifyDealsByRules(deals) {
|
||||
const { getDB } = require('../db');
|
||||
const db = getDB();
|
||||
const categories = db.prepare('SELECT id, name, keywords FROM categories').all();
|
||||
const updateStmt = db.prepare(`UPDATE transactions SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`);
|
||||
let classified = 0;
|
||||
for (const tx of transactions) {
|
||||
const text = `${tx.description || ''} ${tx.counterparty || ''} ${tx.notes || ''}`.toLowerCase();
|
||||
let bestCategory = '其他杂项', bestScore = 0;
|
||||
for (const cat of categories) {
|
||||
let score = 0;
|
||||
for (const kw of JSON.parse(cat.keywords || '[]')) { if (text.includes(kw.toLowerCase())) score++; }
|
||||
if (score > bestScore) { bestScore = score; bestCategory = cat.name; }
|
||||
const cats = db.prepare('SELECT id, name, keywords FROM categories').all();
|
||||
const upd = db.prepare('UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?');
|
||||
let n = 0;
|
||||
for (const d of deals) {
|
||||
const text = (d.description + ' ' + d.counterparty).toLowerCase();
|
||||
let best = '其他杂项', score = 0;
|
||||
for (const c of cats) {
|
||||
let s = 0;
|
||||
for (const kw of JSON.parse(c.keywords || '[]')) { if (text.includes(kw.toLowerCase())) s++; }
|
||||
if (s > score) { score = s; best = c.name; }
|
||||
}
|
||||
const desc = tx.direction === 'income'
|
||||
? `收到${tx.counterparty || '对方'} ${Math.abs(tx.amount).toFixed(2)}元`
|
||||
: `向${tx.counterparty || '对方'}支付${Math.abs(tx.amount).toFixed(2)}元${tx.description ? '(' + tx.description + ')' : ''}`;
|
||||
updateStmt.run(bestCategory, desc.substring(0, 100), bestScore > 0 ? 0.7 : 0.3, bestCategory, tx.id);
|
||||
classified++;
|
||||
const desc = (parseFloat(d.amount) >= 0 ? '收到' : '向') + (d.counterparty || '对方') + (parseFloat(d.amount) >= 0 ? '' : '支付') + Math.abs(d.amount).toFixed(2) + '元';
|
||||
upd.run(best, desc.substring(0, 100), score > 0 ? 0.7 : 0.3, best, d.id);
|
||||
n++;
|
||||
}
|
||||
return { classified, source: 'rules' };
|
||||
return { classified: n, source: 'rules' };
|
||||
}
|
||||
|
||||
module.exports = { classifyTransactions, getOpenAIClient, loadConfig, saveConfig, resetClient };
|
||||
module.exports = { classifyDeals, getOpenAIClient, loadConfig, saveConfig, resetClient };
|
||||
|
||||
Reference in New Issue
Block a user