Remove unused columns and simplify schema across database and routes
Drop `parent_id` from categories, remove `ai_category` and `review_notes` from transactions, and eliminate category/reviewed filters from transaction queries. Clean up code style and formatting.
This commit is contained in:
+1
-6
@@ -59,7 +59,6 @@ function initDB() {
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
keywords TEXT,
|
||||
parent_id INTEGER,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
@@ -77,11 +76,9 @@ function initDB() {
|
||||
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,
|
||||
@@ -98,7 +95,7 @@ function initDB() {
|
||||
|
||||
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_amount ON transactions(ABS(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);
|
||||
@@ -114,11 +111,9 @@ function initDB() {
|
||||
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"],
|
||||
["updated_at", "DATETIME"],
|
||||
|
||||
+44
-26
@@ -1,15 +1,20 @@
|
||||
const express = require('express');
|
||||
const { getDB } = require('../db');
|
||||
const { loadConfig, saveConfig, getOpenAIClient, resetClient } = require('../services/llm');
|
||||
const express = require("express");
|
||||
const { getDB } = require("../db");
|
||||
const {
|
||||
loadConfig,
|
||||
saveConfig,
|
||||
getOpenAIClient,
|
||||
resetClient,
|
||||
} = require("../services/llm");
|
||||
const router = express.Router();
|
||||
|
||||
// GET /api/config
|
||||
router.get('/', (req, res) => {
|
||||
router.get("/", (req, res) => {
|
||||
res.json(loadConfig());
|
||||
});
|
||||
|
||||
// PUT /api/config — 同时存 JSON + 清 LLM 缓存
|
||||
router.put('/', (req, res) => {
|
||||
router.put("/", (req, res) => {
|
||||
const cfg = { ...loadConfig(), ...req.body };
|
||||
saveConfig(cfg);
|
||||
resetClient();
|
||||
@@ -17,26 +22,35 @@ router.put('/', (req, res) => {
|
||||
});
|
||||
|
||||
// POST /api/config/test-llm
|
||||
router.post('/test-llm', async (req, res) => {
|
||||
console.log('[Reco] === LLM 连接测试 ===');
|
||||
router.post("/test-llm", async (req, res) => {
|
||||
console.log("[Reco] === LLM 连接测试 ===");
|
||||
const cfg = loadConfig();
|
||||
console.log(' API Key:', cfg.llm_api_key ? cfg.llm_api_key.substring(0, 8) + '...' : '(无)');
|
||||
console.log(' Base URL:', cfg.llm_base_url || '默认');
|
||||
console.log(' Model:', cfg.llm_model || '默认');
|
||||
console.log(
|
||||
" API Key:",
|
||||
cfg.llm_api_key ? cfg.llm_api_key.substring(0, 8) + "..." : "(无)",
|
||||
);
|
||||
console.log(" Base URL:", cfg.llm_base_url || "默认");
|
||||
console.log(" Model:", cfg.llm_model || "默认");
|
||||
|
||||
const client = getOpenAIClient();
|
||||
if (!client) return res.status(400).json({ error: '请先配置 LLM API Key' });
|
||||
if (!client) return res.status(400).json({ error: "请先配置 LLM API Key" });
|
||||
|
||||
const t0 = Date.now();
|
||||
try {
|
||||
const resp = await client.chat.completions.create({
|
||||
model: client._model,
|
||||
messages: [{ role: 'user', content: '回复"连接成功"' }],
|
||||
max_tokens: 10, timeout: 15000,
|
||||
messages: [{ role: "user", content: '回复"连接成功"' }],
|
||||
max_tokens: 10,
|
||||
timeout: 15000,
|
||||
});
|
||||
const reply = resp.choices?.[0]?.message?.content || '(空)';
|
||||
const reply = resp.choices?.[0]?.message?.content || "(空)";
|
||||
console.log(` 成功 ${Date.now() - t0}ms: ${reply}`);
|
||||
res.json({ success: true, reply, model: client._model, elapsed_ms: Date.now() - t0 });
|
||||
res.json({
|
||||
success: true,
|
||||
reply,
|
||||
model: client._model,
|
||||
elapsed_ms: Date.now() - t0,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(` 失败 ${Date.now() - t0}ms:`, err.message);
|
||||
res.status(500).json({ error: `连接失败: ${err.message}` });
|
||||
@@ -44,27 +58,31 @@ router.post('/test-llm', async (req, res) => {
|
||||
});
|
||||
|
||||
// Categories
|
||||
router.get('/categories', (req, res) => {
|
||||
res.json(getDB().prepare('SELECT * FROM categories ORDER BY id').all());
|
||||
router.get("/categories", (req, res) => {
|
||||
res.json(getDB().prepare("SELECT * FROM categories ORDER BY id").all());
|
||||
});
|
||||
|
||||
router.put('/categories/:id', (req, res) => {
|
||||
router.put("/categories/:id", (req, res) => {
|
||||
const { name, keywords } = req.body;
|
||||
getDB().prepare('UPDATE categories SET name=COALESCE(?,name), keywords=COALESCE(?,keywords) WHERE id=?')
|
||||
getDB()
|
||||
.prepare(
|
||||
"UPDATE categories SET name=COALESCE(?,name), keywords=COALESCE(?,keywords) WHERE id=?",
|
||||
)
|
||||
.run(name, keywords ? JSON.stringify(keywords) : null, req.params.id);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
router.post('/categories', (req, res) => {
|
||||
const { name, keywords, parent_id } = req.body;
|
||||
if (!name) return res.status(400).json({ error: '分类名称不能为空' });
|
||||
const r = getDB().prepare('INSERT INTO categories (name,keywords,parent_id) VALUES (?,?,?)')
|
||||
.run(name, JSON.stringify(keywords || []), parent_id || null);
|
||||
router.post("/categories", (req, res) => {
|
||||
const { name, keywords } = req.body;
|
||||
if (!name) return res.status(400).json({ error: "分类名称不能为空" });
|
||||
const r = getDB()
|
||||
.prepare("INSERT INTO categories (name,keywords) VALUES (?,?)")
|
||||
.run(name, JSON.stringify(keywords || []));
|
||||
res.json({ success: true, id: r.lastInsertRowid });
|
||||
});
|
||||
|
||||
router.delete('/categories/:id', (req, res) => {
|
||||
getDB().prepare('DELETE FROM categories WHERE id=?').run(req.params.id);
|
||||
router.delete("/categories/:id", (req, res) => {
|
||||
getDB().prepare("DELETE FROM categories WHERE id=?").run(req.params.id);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
|
||||
@@ -16,8 +16,6 @@ router.get("/", (req, res) => {
|
||||
end_date,
|
||||
source_type,
|
||||
direction,
|
||||
category,
|
||||
reviewed,
|
||||
min_amount,
|
||||
max_amount,
|
||||
keyword,
|
||||
@@ -45,14 +43,6 @@ router.get("/", (req, res) => {
|
||||
conditions.push("t.direction = ?");
|
||||
params.push(direction);
|
||||
}
|
||||
if (category) {
|
||||
conditions.push("t.category = ?");
|
||||
params.push(category);
|
||||
}
|
||||
if (reviewed !== undefined) {
|
||||
conditions.push("t.reviewed = ?");
|
||||
params.push(parseInt(reviewed));
|
||||
}
|
||||
if (min_amount) {
|
||||
conditions.push("ABS(t.amount) >= ?");
|
||||
params.push(parseFloat(min_amount));
|
||||
@@ -63,10 +53,10 @@ router.get("/", (req, res) => {
|
||||
}
|
||||
if (keyword) {
|
||||
conditions.push(
|
||||
"(t.counterparty LIKE ? OR t.description LIKE ? OR t.notes LIKE ? OR t.ai_description LIKE ?)",
|
||||
"(t.counterparty LIKE ? OR t.description LIKE ? OR t.notes LIKE ?)",
|
||||
);
|
||||
const kw = `%${keyword}%`;
|
||||
params.push(kw, kw, kw, kw);
|
||||
params.push(kw, kw, kw);
|
||||
}
|
||||
|
||||
const whereClause =
|
||||
@@ -244,68 +234,4 @@ router.post("/classify-all", async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/transactions/stats/summary - 获取汇总统计
|
||||
router.get("/stats/summary", (req, res) => {
|
||||
// This is handled by the stats route, but let's keep a simple version here too
|
||||
const db = getDB();
|
||||
|
||||
const { start_date, end_date } = req.query;
|
||||
const conditions = [];
|
||||
const params = [];
|
||||
|
||||
if (start_date) {
|
||||
conditions.push("transaction_date >= ?");
|
||||
params.push(start_date);
|
||||
}
|
||||
if (end_date) {
|
||||
conditions.push("transaction_date <= ?");
|
||||
params.push(end_date);
|
||||
}
|
||||
|
||||
const where =
|
||||
conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";
|
||||
|
||||
const incomeResult = db
|
||||
.prepare(
|
||||
`SELECT COALESCE(SUM(amount), 0) as total FROM transactions ${where} AND direction = 'income'`,
|
||||
)
|
||||
.get(...params);
|
||||
|
||||
const expenseResult = db
|
||||
.prepare(
|
||||
`SELECT COALESCE(SUM(ABS(amount)), 0) as total FROM transactions ${where} AND direction = 'expense'`,
|
||||
)
|
||||
.get(...params);
|
||||
|
||||
const countResult = db
|
||||
.prepare(`SELECT COUNT(*) as total FROM transactions ${where}`)
|
||||
.get(...params);
|
||||
|
||||
const unreviewedCount = db
|
||||
.prepare(
|
||||
`SELECT COUNT(*) as total FROM transactions ${where} AND reviewed = 0 AND ABS(amount) >= 100`,
|
||||
)
|
||||
.get(...params);
|
||||
|
||||
const categoryBreakdown = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT category, COUNT(*) as count, SUM(ABS(amount)) as total_amount
|
||||
FROM transactions ${where} AND direction = 'expense'
|
||||
GROUP BY category
|
||||
ORDER BY total_amount DESC
|
||||
`,
|
||||
)
|
||||
.all(...params);
|
||||
|
||||
res.json({
|
||||
totalIncome: incomeResult.total,
|
||||
totalExpense: expenseResult.total,
|
||||
netAmount: incomeResult.total - expenseResult.total,
|
||||
totalCount: countResult.total,
|
||||
unreviewedCount: unreviewedCount.total,
|
||||
categoryBreakdown,
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -195,7 +195,7 @@ async function classifyDeals(dealIds) {
|
||||
|
||||
if (results && results.length > 0) {
|
||||
const upd = db.prepare(
|
||||
"UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
"UPDATE deals SET ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
);
|
||||
const t1 = Date.now();
|
||||
db.transaction(() => {
|
||||
@@ -203,7 +203,6 @@ async function classifyDeals(dealIds) {
|
||||
const d = deals[item.index - 1];
|
||||
if (d && item.category) {
|
||||
upd.run(
|
||||
item.category,
|
||||
item.description || "",
|
||||
item.confidence || 0.8,
|
||||
item.category,
|
||||
@@ -236,7 +235,7 @@ function classifyDealsByRules(deals) {
|
||||
const cats = db.prepare("SELECT id, name, keywords FROM categories").all();
|
||||
console.log(`[Reco] classifyDealsByRules — ${cats.length} 个分类可用`);
|
||||
const upd = db.prepare(
|
||||
"UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
"UPDATE deals SET ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
);
|
||||
|
||||
const t0 = Date.now();
|
||||
@@ -264,7 +263,7 @@ function classifyDealsByRules(deals) {
|
||||
actionText +
|
||||
Math.abs(d.amount).toFixed(2) +
|
||||
"元";
|
||||
upd.run(best, desc.substring(0, 100), score > 0 ? 0.7 : 0.3, best, d.id);
|
||||
upd.run(desc.substring(0, 100), score > 0 ? 0.7 : 0.3, best, d.id);
|
||||
}
|
||||
})();
|
||||
console.log(
|
||||
|
||||
Reference in New Issue
Block a user