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:
2026-05-06 22:16:36 +08:00
parent 965ef2058d
commit 08fbde8a39
4 changed files with 50 additions and 112 deletions
+44 -26
View File
@@ -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 });
});
+2 -76
View File
@@ -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;