refactor: v2 重构 — 模块化拆分 + AI Prompt模板化 + 前端状态管理
P0 - AI交互层:
- ai/prompt.js: 模块化 Prompt 模板
- ai/validator.js: JSON Schema 校验 + normalize
- ai/client.js: DeepSeek API 封装
- 金额计算唯一化,时间格式归一化
P1 - 后端架构:
- routes/: auth/rooms/messages/purchases 独立路由
- middleware/auth.js: 认证授权中间件
- ws/index.js: WebSocket 连接管理
- db.js: 启用 foreign_keys
- server.js: 从588行精简到40行入口
P2 - 前端架构:
- public/css/style.css: CSS 独立
- public/js/store.js: 全局状态 Store
- public/js/{chat,ws,purchases,auth}.js: 功能模块拆分
- index.html: 纯 HTML 结构, v2.6
This commit is contained in:
19
server/ai/client.js
Normal file
19
server/ai/client.js
Normal file
@@ -0,0 +1,19 @@
|
||||
// DeepSeek API 客户端
|
||||
const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY || '';
|
||||
|
||||
async function callDeepSeek(messages, temperature = 0.1) {
|
||||
console.log('🤖 调用 DeepSeek...');
|
||||
const res = await fetch('https://api.deepseek.com/chat/completions', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${DEEPSEEK_API_KEY}` },
|
||||
body: JSON.stringify({ model: 'deepseek-v4-flash', messages, temperature, stream: false })
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!data.choices || !data.choices[0]) {
|
||||
console.error('🤖 DeepSeek 返回异常:', JSON.stringify(data));
|
||||
throw new Error('DeepSeek API 返回异常: ' + (data.error?.message || JSON.stringify(data)));
|
||||
}
|
||||
return data.choices[0].message.content;
|
||||
}
|
||||
|
||||
module.exports = { callDeepSeek };
|
||||
54
server/ai/prompt.js
Normal file
54
server/ai/prompt.js
Normal file
@@ -0,0 +1,54 @@
|
||||
// AI Prompt 模板 — 模块化拼接
|
||||
function buildSystemPrompt(username, isAdmin) {
|
||||
const now = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false });
|
||||
|
||||
const role = `你是智能财务助手"小财"。当前服务器时间:${now}。结合对话历史理解用户意图,只返回JSON。`;
|
||||
|
||||
const intent = `
|
||||
意图分类:
|
||||
- 采购/付款/发票相关:action="purchase",提取字段:purchase_item, quantity(默认1), unit_price(默认0), freight(默认0), payment_method(淘宝默认支付宝), invoice_type(默认无票), status, applicant, remarks, created_time
|
||||
- 查询汇总:action="query"
|
||||
- 聊天:action="chat",reply简短回复
|
||||
- 删除指定物品:action="delete",delete_item为物品名
|
||||
- 清空所有采购数据:action="clear_all"
|
||||
- 忽略(仅当完全无关):action="ignore"`;
|
||||
|
||||
const permission = `
|
||||
⚠️ 权限规则:
|
||||
- 当前用户${username},管理员状态:${isAdmin}。仅管理员可执行删除/清空操作。
|
||||
- 如果用户要求删除或清空,且 isAdmin 为 false,你必须返回 action="chat" 并说明"仅管理员可操作"。
|
||||
- 如果 isAdmin 为 true,正常返回 delete 或 clear_all。`;
|
||||
|
||||
const deleteRules = `
|
||||
⚠️ 删除规则:
|
||||
- 特殊批量删除:delete_item="__AMOUNT_ZERO__"(金额为0)、"__NULL_NAME__"(空名称)
|
||||
- 精确删除:用户指定数量/金额时同时返回 quantity/amount 字段,只匹配一条
|
||||
- 不要返回 action="ask" 处理删除请求`;
|
||||
|
||||
const attachmentRules = `
|
||||
⚠️ 附件规则:
|
||||
- 图片+物品名("这是XX的图片")→ 只返回 purchase_item,绝对不要 is_new/quantity/unit_price
|
||||
- 引用历史图片("上面/前面/刚刚那张")→ use_recent_image: true
|
||||
- 纯图片+物品名不是新建采购,系统自动关联附件`;
|
||||
|
||||
const prohibitionRules = `
|
||||
⚠️ 绝对禁止:
|
||||
- 图片+物品名请求 → 只能返回 purchase_item,禁止返回 is_new、quantity、unit_price、amount`;
|
||||
|
||||
const purchaseRules = `
|
||||
⚠️ 采购规则:
|
||||
- 只有明确消费意图(购买/采购/下单/付款/买了/花了)才返回 action="purchase"
|
||||
- 纯陈述(如"前天deep")→ action="ignore"
|
||||
- 信息不完整 → action="ask" 追问
|
||||
- 新建 vs 更新:
|
||||
* "昨天/今天/又/再/新/另一批"等重复购买 → is_new: true(强制新建)
|
||||
* "改一下/更新/修改/调整"等 → 不提供 is_new(匹配已有更新)
|
||||
* "纯图片+物品名"不是新建,不要返回 is_new
|
||||
* 无法确定 → 默认 is_new: true
|
||||
- amount 由系统自动计算(quantity × unit_price + freight),AI 无需提供
|
||||
- 无法确定物品名 → action="ask" 追问`;
|
||||
|
||||
return [role, intent, permission, deleteRules, attachmentRules, prohibitionRules, purchaseRules].join('\n');
|
||||
}
|
||||
|
||||
module.exports = { buildSystemPrompt };
|
||||
40
server/ai/validator.js
Normal file
40
server/ai/validator.js
Normal file
@@ -0,0 +1,40 @@
|
||||
// JSON Schema 校验 — 验证 AI 返回的 JSON 结构
|
||||
const schemas = {
|
||||
purchase: { required: ['purchase_item'], optional: ['quantity','unit_price','freight','payment_method','invoice_type','status','applicant','remarks','created_time','is_new','use_recent_image'] },
|
||||
query: { required: [], optional: [] },
|
||||
chat: { required: ['reply'], optional: [] },
|
||||
delete: { required: ['delete_item'], optional: ['quantity','amount'] },
|
||||
clear_all: { required: [], optional: [] },
|
||||
ignore: { required: [], optional: [] },
|
||||
};
|
||||
|
||||
function validate(aiResult) {
|
||||
if (!aiResult || !aiResult.action) {
|
||||
return { valid: false, error: '缺少 action 字段' };
|
||||
}
|
||||
const schema = schemas[aiResult.action];
|
||||
if (!schema) {
|
||||
return { valid: false, error: `未知 action: ${aiResult.action}` };
|
||||
}
|
||||
for (const field of schema.required) {
|
||||
if (aiResult[field] === undefined || aiResult[field] === null) {
|
||||
return { valid: false, error: `action=${aiResult.action} 缺少必填字段: ${field}` };
|
||||
}
|
||||
}
|
||||
return { valid: true };
|
||||
}
|
||||
|
||||
// 修复常见问题
|
||||
function normalize(aiResult) {
|
||||
// action="ask" 兼容 reply/question
|
||||
if (aiResult.action === 'ask') {
|
||||
aiResult.question = aiResult.question || aiResult.reply || '请提供更多信息。';
|
||||
}
|
||||
// chat 兼容 reply 为空
|
||||
if (aiResult.action === 'chat' && !aiResult.reply) {
|
||||
aiResult.reply = '好的。';
|
||||
}
|
||||
return aiResult;
|
||||
}
|
||||
|
||||
module.exports = { validate, normalize };
|
||||
Reference in New Issue
Block a user