const Database = require('better-sqlite3'); const path = require('path'); const DB_PATH = path.join(__dirname, '..', 'data', 'reco.db'); 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, 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, 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 ); CREATE TABLE IF NOT EXISTS categories ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, keywords TEXT, parent_id INTEGER, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE IF NOT EXISTS config ( key TEXT PRIMARY KEY, value TEXT ); CREATE TABLE IF NOT EXISTS deals ( id INTEGER PRIMARY KEY AUTOINCREMENT, deal_date DATETIME NOT NULL, amount REAL NOT NULL, direction TEXT, counterparty TEXT, description TEXT, 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 ); 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_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); `); // 兼容旧库:为 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'] ]; 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] 数据库初始化完成'); } module.exports = { getDB, initDB };