Files
reco/server/db.js
T
fukunee 784da617a9 Add deals feature for reconciled transactions
- Create deals schema and routes to group matched transactions
- Display deals in a new card on the Transactions page
- Generate deals during reconciliation and refresh them on demand
2026-05-05 20:13:11 +08:00

170 lines
6.4 KiB
JavaScript

const Database = require("better-sqlite3");
const path = require("path");
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 });
}
let db;
function getDB() {
if (!db) {
db = new Database(DB_PATH);
db.pragma("journal_mode = WAL");
db.pragma("foreign_keys = ON");
}
return db;
}
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, -- 用户自定义名称,如 "工商银行工资卡"
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, -- 统一交易编码
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, -- 交易金额(正=收入,负=支出)
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数组字符串
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
);
-- 分类配置表:保存大模型分类类别
CREATE TABLE IF NOT EXISTS categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
keywords TEXT, -- JSON数组:关联关键词
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,
amount REAL NOT NULL,
counterparty TEXT,
description TEXT,
match_count INTEGER DEFAULT 2,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS deal_transactions (
deal_id INTEGER NOT NULL,
transaction_id INTEGER NOT NULL,
PRIMARY KEY (deal_id, transaction_id),
FOREIGN KEY (deal_id) REFERENCES deals(id) ON DELETE CASCADE,
FOREIGN KEY (transaction_id) REFERENCES transactions(id) ON DELETE CASCADE
);
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 = [
["餐饮美食", '["餐厅","外卖","食堂","咖啡","奶茶","零食","水果","买菜"]'],
[
"交通出行",
'["公交","地铁","打车","出租车","加油","停车","高速","火车","飞机","骑行"]',
],
[
"购物消费",
'["淘宝","京东","拼多多","超市","百货","服饰","数码","家电","日用品"]',
],
["住房相关", '["房租","房贷","物业","水电","燃气","维修","装修"]'],
["通讯网络", '["话费","宽带","流量"]'],
["投资理财", '["基金","股票","理财","定期","转入","转出","收益"]'],
["工资收入", '["工资","薪资","奖金","报销","劳务"]'],
["转账红包", '["转账","红包","汇款","收款","提现","充值"]'],
["医疗健康", '["医院","药店","挂号","体检","保险"]'],
["教育学习", '["学费","培训","书本","课程","考试"]'],
["娱乐休闲", '["电影","演出","旅游","酒店","游戏","充值","会员"]'],
["信用卡还款", '["还款","信用卡","花呗","借呗","白条"]'],
["其他杂项", "[]"],
];
database.transaction(() => {
defaults.forEach((c) => insertCategory.run(c[0], c[1]));
})();
console.log("[Reco] 已初始化默认分类");
}
console.log("[Reco] 数据库初始化完成");
}
module.exports = { getDB, initDB };