settings.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. 'use strict';
  2. // 系统设置:模型列表、配置读写(脱敏)、生图/对话 API 连通性测试
  3. const fs = require('fs');
  4. const path = require('path');
  5. const https = require('https');
  6. const { URL } = require('url');
  7. const { sendJson, readBody } = require('../util.js');
  8. const { DEFAULT_CHAT_MODEL } = require('../context.js');
  9. function register(app, ctx) {
  10. app.get('/api/models', async ({ res }) => {
  11. sendJson(res, 200, { models: ctx.models.MODELS, default: ctx.config.model });
  12. });
  13. app.get('/api/settings', async ({ res }) => {
  14. sendJson(res, 200, {
  15. apiKey: ctx.config.apiKey ? ctx.config.apiKey.slice(0, 8) + '••••••••' : '',
  16. apiBase: ctx.config.apiBase,
  17. model: ctx.config.model,
  18. rootDir: ctx.workspace.getWorkspaceRoot(),
  19. pageSize: ctx.config.pageSize,
  20. delayMs: ctx.config.delayMs,
  21. crawlChannel: ctx.config.crawlChannel || 'auto',
  22. cookieConfigured: !!ctx.session.cookie && !!ctx.session.getKsid(),
  23. port: ctx.config.port,
  24. chatModel: ctx.config.chatModel || '',
  25. chatApiBase: ctx.config.chatApiBase || ctx.config.apiBase,
  26. chatApiKey: ctx.config.chatApiKey ? ctx.config.chatApiKey.slice(0, 8) + '••••••••' : '',
  27. chatKeyFallback: !ctx.config.chatApiKey && !!ctx.config.apiKey,
  28. chatModelAgent: ctx.config.chatModelAgent || '',
  29. chatJsonMode: !!ctx.config.chatJsonMode,
  30. autoSyncEnabled: !!(ctx.config.autoSync && ctx.config.autoSync.enabled),
  31. autoSyncTime: (ctx.config.autoSync && ctx.config.autoSync.time) || '06:00',
  32. accessTokenSet: !!ctx.config.accessToken,
  33. aitableEnabled: !!(ctx.config.aitable && ctx.config.aitable.enabled),
  34. aitableReadOnly: !!(ctx.config.aitable && ctx.config.aitable.readOnly),
  35. aitableAppKey: (ctx.config.aitable && ctx.config.aitable.appKey) || '',
  36. aitableBaseId: (ctx.config.aitable && ctx.config.aitable.baseId) || '',
  37. aitableSheetDetail: (ctx.config.aitable && ctx.config.aitable.sheetDetail) || '门店明细',
  38. aitableSheetChain: (ctx.config.aitable && ctx.config.aitable.sheetChain) || '连锁汇总',
  39. aitableSheetCompany: (ctx.config.aitable && ctx.config.aitable.sheetCompany) || '公司汇总',
  40. aitableSecretSet: !!(ctx.config.aitable && ctx.config.aitable.appSecret),
  41. aitableOperatorSet: !!(ctx.config.aitable && ctx.config.aitable.operatorId),
  42. });
  43. });
  44. app.post('/api/settings', async ({ req, res }) => {
  45. const body = await readBody(req);
  46. const config = ctx.config;
  47. const previousApiKey = config.apiKey;
  48. const previousCookie = ctx.session.cookie;
  49. if (body.apiKey && !body.apiKey.includes('••••')) config.apiKey = body.apiKey;
  50. if (body.model && ctx.models.MODEL_IDS.has(body.model)) config.model = body.model;
  51. if (body.rootDir) {
  52. const rootDir = path.resolve(String(body.rootDir).trim());
  53. if (!fs.existsSync(rootDir) || !fs.statSync(rootDir).isDirectory()) {
  54. return sendJson(res, 400, { error: '输出根目录不存在: ' + rootDir });
  55. }
  56. config.rootDir = rootDir;
  57. }
  58. if (body.pageSize !== undefined) {
  59. const pageSize = Number(body.pageSize);
  60. if (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > 200) {
  61. return sendJson(res, 400, { error: '每页条数必须为 1-200 的整数' });
  62. }
  63. config.pageSize = pageSize;
  64. }
  65. if (body.delayMs !== undefined) {
  66. const delayMs = Number(body.delayMs);
  67. if (!Number.isFinite(delayMs) || delayMs < 0 || delayMs > 60000) {
  68. return sendJson(res, 400, { error: '间隔必须为 0-60000 毫秒' });
  69. }
  70. config.delayMs = delayMs;
  71. }
  72. if (body.crawlChannel !== undefined) {
  73. const ch = String(body.crawlChannel);
  74. if (!['auto', 'client', 'cookie'].includes(ch)) {
  75. return sendJson(res, 400, { error: '采集通道取值应为 auto / client / cookie' });
  76. }
  77. config.crawlChannel = ch;
  78. }
  79. if (body.chatModel !== undefined) config.chatModel = String(body.chatModel).trim();
  80. if (body.chatApiBase !== undefined) config.chatApiBase = String(body.chatApiBase).trim();
  81. if (body.chatApiKey !== undefined && !String(body.chatApiKey).includes('••••')) config.chatApiKey = String(body.chatApiKey).trim();
  82. if (body.chatModelAgent !== undefined) config.chatModelAgent = String(body.chatModelAgent).trim();
  83. if (body.chatJsonMode !== undefined) config.chatJsonMode = !!body.chatJsonMode;
  84. if (body.autoSyncEnabled !== undefined || body.autoSyncTime !== undefined) {
  85. if (!config.autoSync || typeof config.autoSync !== 'object') config.autoSync = { enabled: false, time: '06:00' };
  86. if (body.autoSyncEnabled !== undefined) config.autoSync.enabled = !!body.autoSyncEnabled;
  87. if (body.autoSyncTime !== undefined) {
  88. const t = String(body.autoSyncTime).trim();
  89. const hm = /^\d{1,2}:\d{2}$/.test(t) ? t.split(':').map(Number) : null;
  90. if (!hm || hm[0] > 23 || hm[1] > 59) {
  91. return sendJson(res, 400, { error: '自动同步时间格式应为 HH:mm' });
  92. }
  93. config.autoSync.time = t;
  94. }
  95. }
  96. if (body.accessToken !== undefined) {
  97. const t = String(body.accessToken).trim();
  98. if (t === '-') config.accessToken = ''; // 约定:输入 - 清除口令
  99. else if (t) config.accessToken = t;
  100. }
  101. if (body.aitableEnabled !== undefined || body.aitableReadOnly !== undefined || body.aitableAppKey !== undefined || body.aitableBaseId !== undefined || body.aitableSheetDetail !== undefined || body.aitableSheetChain !== undefined || body.aitableSheetCompany !== undefined || body.aitableAppSecret !== undefined || body.aitableOperatorId !== undefined) {
  102. if (!config.aitable || typeof config.aitable !== 'object') config.aitable = { enabled: false, appKey: '', appSecret: '', baseId: '', operatorId: '' };
  103. if (body.aitableEnabled !== undefined) config.aitable.enabled = !!body.aitableEnabled;
  104. if (body.aitableReadOnly !== undefined) config.aitable.readOnly = !!body.aitableReadOnly;
  105. if (body.aitableAppKey !== undefined) config.aitable.appKey = String(body.aitableAppKey).trim();
  106. if (body.aitableBaseId !== undefined) {
  107. // 支持直接粘贴 AI 表格分享链接:自动提取 /i/nodes/<ID> 里的节点 ID 作为 Base ID
  108. const raw = String(body.aitableBaseId).trim();
  109. const m = /i\/nodes\/([A-Za-z0-9]+)/.exec(raw) || /[?&]baseId=([A-Za-z0-9]+)/.exec(raw);
  110. config.aitable.baseId = m ? m[1] : raw;
  111. }
  112. // 三张表按维度拆分:门店明细/连锁汇总/公司汇总(空值回退默认名)
  113. if (body.aitableSheetDetail !== undefined) config.aitable.sheetDetail = String(body.aitableSheetDetail).trim() || '门店明细';
  114. if (body.aitableSheetChain !== undefined) config.aitable.sheetChain = String(body.aitableSheetChain).trim() || '连锁汇总';
  115. if (body.aitableSheetCompany !== undefined) config.aitable.sheetCompany = String(body.aitableSheetCompany).trim() || '公司汇总';
  116. if (body.aitableAppSecret !== undefined) {
  117. const sec = String(body.aitableAppSecret).trim();
  118. if (sec === '-') config.aitable.appSecret = ''; // 约定:输入 - 清除
  119. else if (sec) config.aitable.appSecret = sec;
  120. }
  121. if (body.aitableOperatorId !== undefined) {
  122. const op = String(body.aitableOperatorId).trim();
  123. if (op === '-') config.aitable.operatorId = '';
  124. else if (op) config.aitable.operatorId = op;
  125. }
  126. }
  127. ctx.saveConfig();
  128. if (body.cookie !== undefined) {
  129. ctx.session.cookie = body.cookie;
  130. ctx.session.saveSession();
  131. }
  132. // 变更摘要:只列本次实际提交过的面板域(设置页按面板分域保存)
  133. const changed = [];
  134. if (previousApiKey !== config.apiKey) changed.push('API Key 已更新');
  135. if (body.cookie !== undefined && previousCookie !== ctx.session.cookie) changed.push('采集 Cookie 已更新');
  136. if (body.chatModel !== undefined || body.chatApiBase !== undefined || body.chatApiKey !== undefined) changed.push('对话模型已更新');
  137. if (body.aitableEnabled !== undefined || body.aitableAppKey !== undefined || body.aitableBaseId !== undefined
  138. || body.aitableSheetDetail !== undefined || body.aitableSheetChain !== undefined || body.aitableSheetCompany !== undefined
  139. || body.aitableAppSecret !== undefined || body.aitableOperatorId !== undefined) changed.push('钉钉 AI 表格配置已更新');
  140. if (body.autoSyncEnabled !== undefined || body.autoSyncTime !== undefined) changed.push('自动同步已更新');
  141. if (body.crawlChannel !== undefined) changed.push(`采集通道已切换为 ${config.crawlChannel}`);
  142. if (body.accessToken !== undefined) changed.push('访问口令已更新');
  143. ctx.logs.pushSystemLog(
  144. `系统设置已保存:模型=${config.model},根目录=${config.rootDir},每页=${config.pageSize},间隔=${config.delayMs}ms` +
  145. (changed.length ? `,${changed.join(',')}` : ''),
  146. 'success'
  147. );
  148. sendJson(res, 200, { ok: true });
  149. });
  150. // 生图 API 连通性测试:GET /v1/models(轻量、不产生生图费用)
  151. app.post('/api/image/test', async ({ res }) => {
  152. return new Promise((resolve) => {
  153. let base;
  154. try { base = new URL(ctx.config.apiBase); } catch { return sendJson(res, 400, { error: 'API 地址不合法: ' + ctx.config.apiBase }); }
  155. const options = {
  156. hostname: base.hostname, port: base.port || 443, path: '/v1/models', method: 'GET',
  157. headers: { Authorization: `Bearer ${ctx.config.apiKey}` }, timeout: 15000,
  158. };
  159. const up = https.request(options, (upRes) => {
  160. const chunks = [];
  161. upRes.on('data', (c) => chunks.push(c));
  162. upRes.on('end', () => {
  163. let json = null;
  164. try { json = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { /* 保留空 */ }
  165. const models = json && Array.isArray(json.data) ? json.data.map((m) => (m && m.id) || '').filter(Boolean) : null;
  166. sendJson(res, 200, { statusCode: upRes.statusCode, models, modelFound: !!(models && models.includes(ctx.config.model)), model: ctx.config.model });
  167. });
  168. });
  169. up.on('error', (e) => sendJson(res, 200, { statusCode: 0, error: e.message || String(e) }));
  170. up.on('timeout', () => up.destroy(new Error('请求超时')));
  171. up.end();
  172. });
  173. });
  174. app.post('/api/chat/test', async ({ req, res }) => {
  175. const body = await readBody(req);
  176. const nlQuery = require('../../nl-query.js');
  177. const cfg = {
  178. chatApiBase: body.chatApiBase || ctx.config.chatApiBase || ctx.config.apiBase,
  179. chatApiKey: (body.chatApiKey && !String(body.chatApiKey).includes('••••')) ? body.chatApiKey : (ctx.config.chatApiKey || ctx.config.apiKey),
  180. chatModel: body.chatModel || ctx.config.chatModel || DEFAULT_CHAT_MODEL,
  181. };
  182. try {
  183. const reply = await nlQuery.ping(cfg);
  184. sendJson(res, 200, { ok: true, reply });
  185. } catch (e) {
  186. sendJson(res, 502, { error: e.message });
  187. }
  188. });
  189. // ---------- 云端数据库(PostgreSQL)配置 ----------
  190. function pgInstalled() {
  191. try { require.resolve('pg'); return true; } catch { return false; }
  192. }
  193. function storageFormFromBody(body) {
  194. const current = (ctx.config.storage && ctx.config.storage.postgres) || {};
  195. const driver = body.driver === 'postgres' ? 'postgres' : 'sqlite';
  196. const pw = body.pgPassword;
  197. return {
  198. driver,
  199. sqlite: {
  200. file: String(body.sqliteFile
  201. || (ctx.config.storage && ctx.config.storage.sqlite && ctx.config.storage.sqlite.file)
  202. || 'data/ops.db'),
  203. },
  204. postgres: {
  205. // 未提交的字段回落到已保存配置(测试连接时可直接复用)
  206. host: String(body.pgHost !== undefined ? body.pgHost : (current.host || '')).trim(),
  207. port: Number(body.pgPort) || current.port || 5432,
  208. database: String(body.pgDatabase !== undefined ? body.pgDatabase : (current.database || '')).trim(),
  209. user: String(body.pgUser !== undefined ? body.pgUser : (current.user || '')).trim(),
  210. password: (pw !== undefined && pw !== null && !String(pw).includes('••')) ? String(pw) : (current.password || ''),
  211. ssl: body.pgSsl !== undefined ? !!body.pgSsl : !!current.ssl,
  212. schema: String(body.pgSchema || current.schema || 'public'),
  213. max: current.max || 5,
  214. connectTimeoutMs: 10000,
  215. },
  216. };
  217. }
  218. app.get('/api/settings/storage', async ({ res }) => {
  219. const st = ctx.config.storage || {};
  220. const pg = st.postgres || {};
  221. sendJson(res, 200, {
  222. driver: st.driver || 'sqlite',
  223. sqliteFile: (st.sqlite && st.sqlite.file) || 'data/ops.db',
  224. pgInstalled: pgInstalled(),
  225. postgres: {
  226. host: pg.host || '',
  227. port: pg.port || 5432,
  228. database: pg.database || '',
  229. user: pg.user || '',
  230. passwordSet: !!pg.password,
  231. ssl: !!pg.ssl,
  232. schema: pg.schema || 'public',
  233. },
  234. });
  235. });
  236. app.post('/api/settings/storage/test', async ({ req, res }) => {
  237. const body = await readBody(req);
  238. if (!pgInstalled()) return sendJson(res, 200, { ok: false, error: '未安装 pg 驱动(npm install pg)' });
  239. const form = storageFormFromBody(body).postgres;
  240. if (!form.host || !form.database || !form.user) {
  241. return sendJson(res, 200, { ok: false, error: '请填写主机、数据库名和用户名' });
  242. }
  243. const { Client } = require('pg');
  244. const client = new Client({
  245. host: form.host,
  246. port: form.port,
  247. database: form.database,
  248. user: form.user,
  249. password: form.password,
  250. ssl: form.ssl ? { rejectUnauthorized: false } : false,
  251. connectionTimeoutMillis: 8000,
  252. });
  253. try {
  254. await client.connect();
  255. const r = await client.query('select version() as v, current_database() as db');
  256. sendJson(res, 200, {
  257. ok: true,
  258. version: String(r.rows[0].v).split(' ').slice(0, 2).join(' '),
  259. database: r.rows[0].db,
  260. });
  261. } catch (e) {
  262. sendJson(res, 200, { ok: false, error: e.message || String(e) });
  263. } finally {
  264. await client.end().catch(() => {});
  265. }
  266. });
  267. app.post('/api/settings/storage', async ({ req, res }) => {
  268. const body = await readBody(req);
  269. const next = storageFormFromBody(body);
  270. if (next.driver === 'postgres' && (!next.postgres.host || !next.postgres.database || !next.postgres.user)) {
  271. return sendJson(res, 400, { error: '启用云端数据库需要填写主机、数据库名和用户名' });
  272. }
  273. const previous = (ctx.config.storage && ctx.config.storage.driver) || 'sqlite';
  274. ctx.config.storage = { ...(ctx.config.storage || {}), ...next };
  275. ctx.saveConfig();
  276. ctx.logs.pushSystemLog(
  277. `存储驱动已配置为 ${next.driver}${next.driver === 'postgres' ? `(${next.postgres.host}:${next.postgres.port}/${next.postgres.database})` : ''}`,
  278. 'success',
  279. );
  280. sendJson(res, 200, { ok: true, restartRequired: previous !== next.driver });
  281. });
  282. }
  283. module.exports = { register };