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 };
|
||||
|
||||
Reference in New Issue
Block a user