ops.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. 'use strict';
  2. // 店铺运营数据:上传解析、矩阵查询、导入记录、原件下载、重新解析、CSV 导出。
  3. // 存储由 ops-store 决定(默认本地 SQLite),此处只做协议与编排。
  4. const crypto = require('crypto');
  5. const { sendJson, readBody } = require('../util.js');
  6. const opsImport = require('../../ops-import.js');
  7. const { createOpsStore } = require('../../ops-store.js');
  8. const { loadSchools } = require('../../schools-store.js');
  9. const { makeChatCfg } = require('../context.js');
  10. const { chatCompletion } = require('../agent/llm.js');
  11. const MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
  12. const UPLOAD_ID_RE = /^\d{8}-\d{6}-[a-z0-9]{6}$/;
  13. const XLSX_MIME = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  14. const PARSER_VERSION = 1;
  15. const BASE_FIELDS = [
  16. { key: 'order_cnt', label: '订单量', type: 'int', source: 'manual' },
  17. { key: 'revenue', label: '营收', type: 'money', source: 'manual' },
  18. { key: 'exposure', label: '曝光量', type: 'int', source: 'manual' },
  19. { key: 'click_rate', label: '进店转化率', type: 'rate', source: 'manual' },
  20. ];
  21. const BASE_FIELD_KEYS = BASE_FIELDS.map((f) => f.key);
  22. function pad2(n) {
  23. return String(n).padStart(2, '0');
  24. }
  25. function newUploadId() {
  26. const d = new Date();
  27. const stamp = `${d.getFullYear()}${pad2(d.getMonth() + 1)}${pad2(d.getDate())}-${pad2(d.getHours())}${pad2(d.getMinutes())}${pad2(d.getSeconds())}`;
  28. return `${stamp}-${crypto.randomBytes(3).toString('hex')}`;
  29. }
  30. function sanitizeName(name) {
  31. const text = String(name || 'upload.xlsx')
  32. .replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_')
  33. .trim()
  34. .slice(0, 120);
  35. return text || 'upload.xlsx';
  36. }
  37. function splitList(value) {
  38. return String(value || '')
  39. .split(',')
  40. .map((s) => s.trim())
  41. .filter(Boolean);
  42. }
  43. function parseFieldKeys(value) {
  44. return splitList(value);
  45. }
  46. function parseYmd(value) {
  47. const text = String(value || '').replace(/-/g, '');
  48. return /^\d{8}$/.test(text) ? text : '';
  49. }
  50. /** 存储不可用时的统一响应(summary 例外,它要返回 200 + enabled:false) */
  51. async function requireHealthy(store, res) {
  52. const health = await store.health();
  53. if (health.ok) return true;
  54. sendJson(res, 503, {
  55. error: '存储不可用',
  56. reason: health.reason || 'storage-unreachable',
  57. detail: health.detail || '',
  58. });
  59. return false;
  60. }
  61. function normalizeFieldValue(value, type) {
  62. if (value === null || value === undefined || value === '') return null;
  63. if (type === 'text') return String(value);
  64. const n = Number(value);
  65. if (Number.isFinite(n)) return n;
  66. return type === 'int' || type === 'money' || type === 'rate' ? null : String(value);
  67. }
  68. function fieldValue(row, field) {
  69. if (field.source === 'platform') {
  70. const data = row.platform || {};
  71. const raw = Object.prototype.hasOwnProperty.call(data, field.label) ? data[field.label] : null;
  72. return normalizeFieldValue(raw, field.type);
  73. }
  74. return normalizeFieldValue(row[field.key], field.type);
  75. }
  76. /** 按字段名与样本值推断展示类型 */
  77. function inferFieldType(label, samples) {
  78. const name = String(label || '');
  79. if (/率|占比/.test(name)) return 'rate';
  80. if (/额|费|价|收入|支出|补贴|成本|销售额/.test(name)) return 'money';
  81. if (/时长|时间段|时间$|列表|名称|地址|ID$|id$/.test(name)) return 'text';
  82. const present = samples.filter((v) => v !== null && v !== undefined && v !== '');
  83. if (!present.length) return 'text';
  84. const numeric = present.filter((v) => typeof v === 'number' || (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v))));
  85. return numeric.length === present.length ? 'int' : 'text';
  86. }
  87. /** 可选字段目录:4 个基础字段 + 平台导出里的全部列 */
  88. async function buildFieldCatalog(store) {
  89. const fields = BASE_FIELDS.map((f) => ({ ...f }));
  90. let columns = [];
  91. let sample = [];
  92. try {
  93. const uploads = await store.listUploads();
  94. const seen = new Set();
  95. for (const upload of uploads) {
  96. for (const col of ((upload.report && upload.report.columns) || [])) seen.add(col);
  97. }
  98. sample = (await store.queryPlatformRows({})).slice(0, 300);
  99. if (!seen.size) {
  100. for (const row of sample) for (const col of Object.keys(row.data || {})) seen.add(col);
  101. }
  102. columns = [...seen];
  103. } catch { /* 存储不可用时只有基础字段 */ }
  104. for (const column of columns) {
  105. const key = `p:${column}`;
  106. if (fields.some((f) => f.key === key)) continue;
  107. if (['日期', '门店编号', '门店名称'].includes(column)) continue;
  108. fields.push({
  109. key,
  110. label: column,
  111. type: inferFieldType(column, sample.map((row) => (row.data || {})[column])),
  112. source: 'platform',
  113. });
  114. }
  115. return fields;
  116. }
  117. function buildMatrix(rows, dates, fields) {
  118. const schools = new Map();
  119. for (const row of rows) {
  120. const schoolName = row.school || '未分组';
  121. if (!schools.has(schoolName)) schools.set(schoolName, new Map());
  122. const shopMap = schools.get(schoolName);
  123. if (!shopMap.has(row.shopKey)) {
  124. shopMap.set(row.shopKey, {
  125. key: row.shopKey,
  126. shopId: row.shopId,
  127. shopName: row.shopName,
  128. status: row.status,
  129. series: {},
  130. quality: {},
  131. totals: {},
  132. });
  133. }
  134. const shop = shopMap.get(row.shopKey);
  135. for (const field of fields) {
  136. if (!shop.series[field.key]) shop.series[field.key] = {};
  137. shop.series[field.key][row.date] = fieldValue(row, field);
  138. }
  139. if (Array.isArray(row.quality) && row.quality.length) shop.quality[row.date] = row.quality;
  140. }
  141. const groups = [];
  142. for (const [school, shopMap] of [...schools.entries()].sort((a, b) => a[0].localeCompare(b[0], 'zh-Hans-CN'))) {
  143. const shops = [...shopMap.values()].sort((a, b) => String(a.shopName).localeCompare(String(b.shopName), 'zh-Hans-CN'));
  144. for (const shop of shops) {
  145. for (const field of fields) {
  146. const series = shop.series[field.key] || {};
  147. if (field.type === 'int' || field.type === 'money') {
  148. let sum = 0;
  149. let seen = false;
  150. for (const date of dates) {
  151. const value = series[date];
  152. if (typeof value === 'number') { sum += value; seen = true; }
  153. }
  154. shop.totals[field.key] = seen ? Math.round(sum * 100) / 100 : null;
  155. } else if (field.type === 'rate') {
  156. let weight = 0;
  157. let acc = 0;
  158. const base = shop.series.exposure || {};
  159. for (const date of dates) {
  160. const rate = series[date];
  161. const exposure = base[date];
  162. if (typeof exposure === 'number' && exposure > 0 && typeof rate === 'number') {
  163. weight += exposure;
  164. acc += rate * exposure;
  165. }
  166. }
  167. shop.totals[field.key] = weight > 0 ? acc / weight : null;
  168. } else {
  169. shop.totals[field.key] = null;
  170. }
  171. }
  172. }
  173. groups.push({ school, shops });
  174. }
  175. return groups;
  176. }
  177. function numOrNull(value) {
  178. if (value === null || value === undefined || value === '') return null;
  179. const n = Number(value);
  180. return Number.isFinite(n) ? n : null;
  181. }
  182. /** 平台全字段行 → 矩阵行:4 个基础指标另存,原始 124 字段留在 platform */
  183. function platformRowToMatrix(row) {
  184. const d = row.data || {};
  185. return {
  186. date: row.date,
  187. shopKey: String(row.shopId || ''),
  188. shopId: String(row.shopId || ''),
  189. shopName: row.shopName || '',
  190. school: row.school || '',
  191. status: '',
  192. order_cnt: numOrNull(d['有效订单']),
  193. revenue: numOrNull(d['营业额']),
  194. exposure: numOrNull(d['曝光人数']),
  195. click_rate: numOrNull(d['进店转化率']),
  196. platform: d,
  197. quality: [],
  198. };
  199. }
  200. /** 人工表 + 平台明细合并:同一天同一店,人工的 4 个指标覆盖平台,其余平台字段保留 */
  201. async function loadMergedRows(store, { from, to, schools, shops } = {}) {
  202. let platform = [];
  203. try {
  204. platform = await store.queryPlatformRows({ from, to });
  205. } catch { /* 平台表不可用不影响人工数据 */ }
  206. const manual = await store.queryRows({ from, to, schools, shops });
  207. const map = new Map();
  208. for (const row of platform) map.set(`${row.date}|${row.shopId}`, platformRowToMatrix(row));
  209. for (const row of manual) {
  210. const key = `${row.date}|${row.shopKey}`;
  211. const base = map.get(key);
  212. map.set(key, { ...(base || {}), ...row, platform: base ? base.platform : null });
  213. }
  214. let rows = [...map.values()];
  215. if (schools && schools.length) rows = rows.filter((r) => schools.includes(String(r.school || '')));
  216. if (shops && shops.length) rows = rows.filter((r) => shops.includes(String(r.shopId || r.shopKey || '')));
  217. return rows;
  218. }
  219. function addDays(ymd, n) {
  220. const d = new Date(Date.UTC(Number(ymd.slice(0, 4)), Number(ymd.slice(4, 6)) - 1, Number(ymd.slice(6, 8))));
  221. d.setUTCDate(d.getUTCDate() + n);
  222. return `${d.getUTCFullYear()}${pad2(d.getUTCMonth() + 1)}${pad2(d.getUTCDate())}`;
  223. }
  224. function dayCount(from, to) {
  225. const a = Date.UTC(Number(from.slice(0, 4)), Number(from.slice(4, 6)) - 1, Number(from.slice(6, 8)));
  226. const b = Date.UTC(Number(to.slice(0, 4)), Number(to.slice(4, 6)) - 1, Number(to.slice(6, 8)));
  227. return Math.max(1, Math.round((b - a) / 86400000) + 1);
  228. }
  229. function pctDelta(cur, prev) {
  230. if (prev == null || prev === 0 || cur == null) return null;
  231. return Math.round(((cur - prev) / prev) * 1000) / 10;
  232. }
  233. function sumSeries(rows, key) {
  234. let sum = 0;
  235. for (const row of rows) if (typeof row[key] === 'number') sum += row[key];
  236. return sum;
  237. }
  238. function platformNum(row, column) {
  239. if (!row.platform) return null;
  240. return numOrNull(row.platform[column]);
  241. }
  242. /** 零单门店诊断:用平台字段区分「未开业 / 闭店 / 无曝光 / 无进店 / 无转化」 */
  243. function diagnoseZeroOrder(row) {
  244. const p = row.platform;
  245. const orders = Number(row.order_cnt);
  246. if (!(orders === 0)) return null;
  247. if (!p) {
  248. return { reason: 'unknown', reasonText: '缺少平台明细,无法判断' };
  249. }
  250. const bizHours = String(p['营业时长'] == null ? '' : p['营业时长']).trim();
  251. const zeroBiz = /^0\s*小时\s*0\s*分$/.test(bizHours) || bizHours === '0' || bizHours === '';
  252. const abnormal = numOrNull(p['异常关店时长']) || 0;
  253. const exposure = numOrNull(p['曝光人数']);
  254. const visit = numOrNull(p['进店人数']);
  255. const validShop = String(p['是否有效门店'] || '').trim();
  256. if (zeroBiz) {
  257. if (validShop === '否') {
  258. return { reason: 'not-open', reasonText: '未开业(非有效门店,当日无营业时长)', bizHours, abnormal, exposure, visit, validShop };
  259. }
  260. if (abnormal > 0) {
  261. return { reason: 'closed', reasonText: `当日闭店(异常关店 ${abnormal} 分钟,无营业时长)`, bizHours, abnormal, exposure, visit, validShop };
  262. }
  263. return { reason: 'not-open', reasonText: '未营业(当日无营业时长,也未记录异常关店)', bizHours, abnormal, exposure, visit, validShop };
  264. }
  265. if (exposure === 0) {
  266. return { reason: 'no-traffic', reasonText: '营业中但无曝光(未进流量池)', bizHours, abnormal, exposure, visit, validShop };
  267. }
  268. if (visit === 0) {
  269. return { reason: 'no-visit', reasonText: `有曝光 ${exposure} 但无进店`, bizHours, abnormal, exposure, visit, validShop };
  270. }
  271. return { reason: 'no-conversion', reasonText: `有进店 ${visit} 但零下单(转化问题)`, bizHours, abnormal, exposure, visit, validShop };
  272. }
  273. /** 一次聚合:KPI 口径集中在这里,前端不再二次计算 */
  274. function aggregateRows(rows) {
  275. let revenue = 0;
  276. let orders = 0;
  277. let exposure = 0;
  278. let visit = 0;
  279. let buyers = 0;
  280. let expense = 0;
  281. let subsidy = 0;
  282. let ratingSum = 0;
  283. let ratingCount = 0;
  284. let rateWeight = 0;
  285. let rateAcc = 0;
  286. for (const row of rows) {
  287. if (typeof row.revenue === 'number') revenue += row.revenue;
  288. if (typeof row.order_cnt === 'number') orders += row.order_cnt;
  289. if (typeof row.exposure === 'number') exposure += row.exposure;
  290. if (typeof row.click_rate === 'number' && row.exposure > 0) {
  291. rateWeight += row.exposure;
  292. rateAcc += row.click_rate * row.exposure;
  293. }
  294. const v = platformNum(row, '进店人数');
  295. if (v != null) visit += v;
  296. const b = platformNum(row, '下单人数');
  297. if (b != null) buyers += b;
  298. const e = platformNum(row, '支出');
  299. if (e != null) expense += e;
  300. const sub = platformNum(row, '活动总补贴');
  301. if (sub != null) subsidy += sub;
  302. const rating = platformNum(row, '店铺评分');
  303. if (rating != null && rating > 0) {
  304. ratingSum += rating;
  305. ratingCount += 1;
  306. }
  307. }
  308. const conversion = visit > 0 && exposure > 0
  309. ? visit / exposure
  310. : (rateWeight > 0 ? rateAcc / rateWeight : null);
  311. return {
  312. revenue: Math.round(revenue * 100) / 100,
  313. orders,
  314. exposure,
  315. visit,
  316. buyers,
  317. expense: Math.round(expense * 100) / 100,
  318. subsidy: Math.round(subsidy * 100) / 100,
  319. rating: ratingCount ? Math.round((ratingSum / ratingCount) * 100) / 100 : null,
  320. avgTicket: orders > 0 ? Math.round((revenue / orders) * 100) / 100 : null,
  321. conversion: conversion == null ? null : Math.round(conversion * 10000) / 10000,
  322. };
  323. }
  324. async function buildDashboard(store, { from, to, schools, shops }) {
  325. const filters = { schools, shops };
  326. let rows = await loadMergedRows(store, { from, to, ...filters });
  327. const dates = [...new Set(rows.map((r) => r.date))].sort();
  328. const start = from || dates[0];
  329. const end = to || dates[dates.length - 1];
  330. if (!start || !end) {
  331. return { from: null, to: null, prev: null, kpis: null, trend: [], ranking: [], funnel: null, structure: [] };
  332. }
  333. // 未指定区间时按实际数据范围收敛
  334. if (!from || !to) rows = await loadMergedRows(store, { from: start, to: end, ...filters });
  335. const span = dayCount(start, end);
  336. const prevTo = addDays(start, -1);
  337. const prevFrom = addDays(prevTo, -(span - 1));
  338. let prevRows = [];
  339. try {
  340. prevRows = await loadMergedRows(store, { from: prevFrom, to: prevTo, ...filters });
  341. } catch { /* 上期缺失不影响本期 */ }
  342. const cur = aggregateRows(rows);
  343. const prev = prevRows.length ? aggregateRows(prevRows) : null;
  344. const kpi = (value, prevValue, unit, isRate) => ({
  345. value,
  346. prev: prevValue,
  347. delta: prevValue == null || value == null
  348. ? null
  349. : (isRate ? Math.round((value - prevValue) * 1000) / 10 : pctDelta(value, prevValue)),
  350. unit,
  351. });
  352. const kpis = {
  353. revenue: kpi(cur.revenue, prev && prev.revenue, 'money'),
  354. orders: kpi(cur.orders, prev && prev.orders, 'int'),
  355. avgTicket: kpi(cur.avgTicket, prev && prev.avgTicket, 'money'),
  356. exposure: kpi(cur.exposure, prev && prev.exposure, 'int'),
  357. conversion: kpi(cur.conversion, prev && prev.conversion, 'pp', true),
  358. rating: { value: cur.rating, prev: null, delta: null, unit: 'num' },
  359. };
  360. const byDate = new Map();
  361. const byShop = new Map();
  362. for (const row of rows) {
  363. if (!byDate.has(row.date)) byDate.set(row.date, []);
  364. byDate.get(row.date).push(row);
  365. const key = String(row.shopId || row.shopKey || '');
  366. if (!key) continue;
  367. if (!byShop.has(key)) byShop.set(key, { shopId: key, shopName: row.shopName || key, school: row.school || '', rows: [] });
  368. byShop.get(key).rows.push(row);
  369. }
  370. const trend = [...byDate.entries()].sort((a, b) => (a[0] < b[0] ? -1 : 1)).map(([date, list]) => {
  371. const agg = aggregateRows(list);
  372. return { date, revenue: agg.revenue, orders: agg.orders };
  373. });
  374. const allShops = [...byShop.values()]
  375. .map((shop) => {
  376. const agg = aggregateRows(shop.rows);
  377. return { shopId: shop.shopId, shopName: shop.shopName, school: shop.school, revenue: agg.revenue, orders: agg.orders };
  378. })
  379. .sort((a, b) => b.revenue - a.revenue);
  380. const ranking = allShops.slice(0, 10);
  381. const bottom = allShops.slice(-5).reverse();
  382. const funnel = {
  383. exposure: cur.exposure,
  384. visit: cur.visit,
  385. order: cur.buyers || cur.orders,
  386. };
  387. const zeroOrder = [];
  388. for (const row of rows) {
  389. const diagnosis = diagnoseZeroOrder(row);
  390. if (!diagnosis) continue;
  391. zeroOrder.push({
  392. date: row.date,
  393. shopId: row.shopId,
  394. shopName: row.shopName,
  395. school: row.school || '',
  396. orders: 0,
  397. ...diagnosis,
  398. });
  399. }
  400. const zeroOrderSummary = zeroOrder.reduce((acc, item) => {
  401. acc[item.reason] = (acc[item.reason] || 0) + 1;
  402. return acc;
  403. }, {});
  404. const structure = [...byDate.entries()].sort((a, b) => (a[0] < b[0] ? -1 : 1)).map(([date, list]) => {
  405. const agg = aggregateRows(list);
  406. return { date, income: agg.revenue, expense: agg.expense, subsidy: agg.subsidy };
  407. });
  408. return {
  409. from: start,
  410. to: end,
  411. prev: prevRows.length ? { from: prevFrom, to: prevTo } : null,
  412. kpis,
  413. trend,
  414. ranking,
  415. bottom,
  416. zeroOrder,
  417. zeroOrderSummary,
  418. shopCount: allShops.length,
  419. funnel,
  420. structure,
  421. };
  422. }
  423. const INSIGHT_SYSTEM_PROMPT = [
  424. '你是连锁餐饮公司的经营分析师。用户会给一段 JSON,包含某段时间的经营汇总(kpis)、按日趋势(trend)、门店排行(ranking)与垫底(bottom)、转化漏斗(funnel)、收入支出结构(structure)。',
  425. '请用中文输出 3~5 条要点,每行一条,以「- 」开头。要求:',
  426. '1. 先给结论,再给依据;',
  427. '2. 必须引用 JSON 里的具体数字(金额保留两位小数、人数/单量用整数、比率用百分比);',
  428. '3. 指出风险(下滑、零单门店、成本占比高、漏斗转化偏低等),并给一句可执行建议;',
  429. '4. 数据不足(如 prev 为 null、只有 1 天)就直接说明,不要编造;',
  430. '5. 说到零单门店时,必须引用 zeroOrder[].reasonText 的具体原因(未开业/闭店/无曝光/无进店/无转化),不要笼统说「零单门店」;',
  431. '6. 每条不超过 60 字,不要输出 JSON、标题或前后缀。',
  432. ].join('\n');
  433. function insightContext(data) {
  434. const k = (key) => (data.kpis[key] ? { value: data.kpis[key].value, delta: data.kpis[key].delta } : null);
  435. const rate = (a, b) => (b > 0 ? Math.round((a / b) * 1000) / 10 : null);
  436. const funnel = data.funnel || {};
  437. return {
  438. range: { from: data.from, to: data.to, days: data.trend.length, prev: data.prev },
  439. kpis: {
  440. revenue: k('revenue'),
  441. orders: k('orders'),
  442. avgTicket: k('avgTicket'),
  443. exposure: k('exposure'),
  444. conversion: k('conversion'),
  445. rating: k('rating'),
  446. },
  447. funnel: {
  448. exposure: funnel.exposure,
  449. visit: funnel.visit,
  450. order: funnel.order,
  451. visitRate: rate(funnel.visit, funnel.exposure),
  452. orderRate: rate(funnel.order, funnel.visit),
  453. },
  454. trend: data.trend.slice(-14),
  455. shopCount: data.shopCount,
  456. topShops: (data.ranking || []).slice(0, 5).map((s) => ({ name: s.shopName, revenue: s.revenue, orders: s.orders })),
  457. bottomShops: (data.bottom || []).map((s) => ({ name: s.shopName, revenue: s.revenue, orders: s.orders })),
  458. zeroOrderSummary: data.zeroOrderSummary || {},
  459. zeroOrder: (data.zeroOrder || []).slice(0, 20).map((z) => ({
  460. date: z.date,
  461. shop: z.shopName,
  462. reason: z.reason,
  463. reasonText: z.reasonText,
  464. })),
  465. structure: (data.structure || []).map((s) => ({
  466. date: s.date,
  467. income: s.income,
  468. expense: s.expense,
  469. subsidy: s.subsidy,
  470. expenseRatio: s.income > 0 ? Math.round((s.expense / s.income) * 1000) / 10 : null,
  471. })),
  472. };
  473. }
  474. function parseInsightPoints(text) {
  475. return String(text || '')
  476. .split(/\r?\n/)
  477. .map((line) => line.replace(/^\s*(?:[-*•]|\d+[.、)])\s*/, '').trim())
  478. .filter(Boolean)
  479. .slice(0, 6);
  480. }
  481. function csvCell(value) {
  482. const text = value == null ? '' : String(value);
  483. return /[",\n\r]/.test(text) ? '"' + text.replace(/"/g, '""') + '"' : text;
  484. }
  485. /** 从文件名识别已登记学校(取最长匹配,如「浙江工商桐庐校区20261018…」→ 浙江工商大学桐庐校区) */
  486. function resolveSchoolFromFileName(fileName) {
  487. let best = '';
  488. let bestName = '';
  489. for (const school of loadSchools()) {
  490. for (const candidate of [school.name, ...(school.aliases || [])]) {
  491. const name = String(candidate || '').trim();
  492. if (name && fileName.includes(name) && name.length > bestName.length) {
  493. best = school.name;
  494. bestName = name;
  495. }
  496. }
  497. }
  498. return best;
  499. }
  500. function register(app, ctx) {
  501. const store = createOpsStore(ctx.config);
  502. // ---------- 上传 ----------
  503. app.post('/api/ops/upload', async ({ req, res }) => {
  504. const body = await readBody(req);
  505. const fileName = sanitizeName(body.fileName);
  506. if (!/\.xlsx$/i.test(fileName)) {
  507. return sendJson(res, 400, { error: '只支持 .xlsx 文件' });
  508. }
  509. const base64 = String(body.contentBase64 || '').replace(/^data:[^;]+;base64,/, '');
  510. if (!base64) return sendJson(res, 400, { error: '缺少文件内容' });
  511. let content;
  512. try {
  513. content = Buffer.from(base64, 'base64');
  514. } catch {
  515. return sendJson(res, 400, { error: 'base64 解码失败' });
  516. }
  517. if (!content.length) return sendJson(res, 400, { error: '文件内容为空' });
  518. if (content.length > MAX_UPLOAD_BYTES) {
  519. return sendJson(res, 413, { error: '文件超过 10MB 上限' });
  520. }
  521. if (!(await requireHealthy(store, res))) return;
  522. const sha256 = crypto.createHash('sha256').update(content).digest('hex');
  523. const existing = await store.findUploadBySha(sha256);
  524. if (!body.force) {
  525. if (existing) {
  526. return sendJson(res, 409, { error: '该文件已导入过', uploadId: existing, duplicate: true });
  527. }
  528. }
  529. const year = Number(body.year) || new Date().getFullYear();
  530. let school = String(body.school || '').trim().slice(0, 60);
  531. let parsed;
  532. try {
  533. parsed = opsImport.parseAny(content, { year, school });
  534. } catch (e) {
  535. return sendJson(res, 400, { error: e.message || '解析失败', code: e.code || 'OPS_PARSE_FAILED' });
  536. }
  537. if (!parsed.rows.length) {
  538. return sendJson(res, 400, { error: '未解析到有效数据行' });
  539. }
  540. const uploadId = newUploadId();
  541. const uploadedAt = new Date().toISOString();
  542. const from = parsed.dates[0] || '';
  543. const to = parsed.dates[parsed.dates.length - 1] || '';
  544. // ---------- 平台导出(全字段明细) ----------
  545. if (parsed.kind === 'platform-export') {
  546. // 表里没有学校列:优先用上传时选定的学校,其次从文件名识别(如「浙江工商桐庐校区20261018…」)
  547. if (!school) school = resolveSchoolFromFileName(fileName);
  548. if (!school) {
  549. return sendJson(res, 400, { error: '请选择学校(平台导出表里没有学校列)', code: 'OPS_SCHOOL_REQUIRED' });
  550. }
  551. const existingRows = await store.queryPlatformRows({ from, to });
  552. const known = new Map(existingRows.map((r) => [`${r.date}|${r.shopId}`, r]));
  553. let newRows = 0;
  554. let identicalRows = 0;
  555. let conflictRows = 0;
  556. const incoming = [];
  557. for (const row of parsed.rows) {
  558. const key = `${row.date}|${row.shopId}`;
  559. const old = known.get(key);
  560. if (!old) { newRows += 1; incoming.push(row); continue; }
  561. const sameData = JSON.stringify(old.data) === JSON.stringify(row.data);
  562. if (sameData && old.school === school) { identicalRows += 1; continue; }
  563. conflictRows += 1;
  564. if (body.force) incoming.push(row);
  565. }
  566. const toWrite = body.force ? parsed.rows : incoming;
  567. const report = {
  568. kind: 'platform-export',
  569. rows: parsed.rows.length,
  570. shops: parsed.shops.length,
  571. newRows,
  572. identicalRows,
  573. conflictRows,
  574. writtenRows: toWrite.length,
  575. warningCount: parsed.warnings.length,
  576. dates: { from, to },
  577. year,
  578. schoolOverride: school,
  579. parser: { kind: 'platform-export', version: PARSER_VERSION },
  580. columns: parsed.columns || [],
  581. warnings: parsed.warnings.slice(0, 500),
  582. };
  583. try {
  584. await store.withTransaction(async (tx) => {
  585. if (body.force) await tx.deletePlatformRowsBySha(sha256);
  586. await tx.insertUpload({
  587. id: uploadId,
  588. originalName: fileName,
  589. sha256,
  590. sizeBytes: content.length,
  591. uploadedAt,
  592. year,
  593. parserKind: 'platform-export',
  594. parserVersion: PARSER_VERSION,
  595. report,
  596. content,
  597. });
  598. if (toWrite.length) {
  599. await tx.upsertPlatformRows(toWrite.map((row) => ({ ...row, school, uploadId })));
  600. }
  601. });
  602. } catch (e) {
  603. return sendJson(res, 500, { error: '写入失败', detail: e.message || String(e) });
  604. }
  605. return sendJson(res, 200, {
  606. ok: true,
  607. uploadId,
  608. report,
  609. warnings: parsed.warnings.slice(0, 200),
  610. duplicateData: report.newRows === 0 && report.conflictRows === 0,
  611. });
  612. }
  613. // ---------- 人工统计表 ----------
  614. // 表格里没有「学校名称」列、上传时也没指定 → 让用户补选,避免落成空白分组
  615. if (!parsed.shops.some((shop) => shop.school && shop.school.trim())) {
  616. return sendJson(res, 400, {
  617. error: '表格里没有「学校名称」列,请在上传时选择或填写学校',
  618. code: 'OPS_SCHOOL_REQUIRED',
  619. });
  620. }
  621. // 覆盖计数:该区间内已存在的「日期 + 店铺」组合
  622. let overwritten = 0;
  623. try {
  624. const existingDaily = await store.queryRows({ from, to });
  625. const knownDaily = new Set(existingDaily.map((r) => `${r.date}|${r.shopKey}`));
  626. for (const row of parsed.rows) if (knownDaily.has(`${row.date}|${row.shopKey}`)) overwritten += 1;
  627. } catch { /* 计数失败不影响导入 */ }
  628. const report = {
  629. kind: 'manual-ops',
  630. rows: parsed.rows.length,
  631. shops: parsed.shops.length,
  632. overwritten,
  633. warningCount: parsed.warnings.length,
  634. dates: { from, to },
  635. year,
  636. schoolOverride: school,
  637. parser: { kind: 'manual-ops', version: PARSER_VERSION },
  638. warnings: parsed.warnings.slice(0, 500),
  639. };
  640. try {
  641. await store.withTransaction(async (tx) => {
  642. if (body.force) await tx.deleteRowsBySha(sha256);
  643. await tx.insertUpload({
  644. id: uploadId,
  645. originalName: fileName,
  646. sha256,
  647. sizeBytes: content.length,
  648. uploadedAt,
  649. year,
  650. parserKind: 'manual-ops',
  651. parserVersion: PARSER_VERSION,
  652. report,
  653. content,
  654. });
  655. await tx.upsertRows(parsed.rows.map((row) => ({ ...row, uploadId })));
  656. await tx.upsertShops(parsed.shops.map((shop) => ({ ...shop, lastUploadId: uploadId })));
  657. await tx.pruneOrphanShops();
  658. });
  659. } catch (e) {
  660. return sendJson(res, 500, { error: '写入失败', detail: e.message || String(e) });
  661. }
  662. sendJson(res, 200, {
  663. ok: true,
  664. uploadId,
  665. report,
  666. warnings: parsed.warnings.slice(0, 200),
  667. });
  668. });
  669. // ---------- 概览 ----------
  670. app.get('/api/ops/summary', async ({ res }) => {
  671. const health = await store.health();
  672. if (!health.ok) {
  673. return sendJson(res, 200, {
  674. enabled: false,
  675. driver: store.kind,
  676. reason: health.reason || 'storage-unreachable',
  677. detail: health.detail || '',
  678. });
  679. }
  680. try {
  681. const data = await store.summary();
  682. sendJson(res, 200, { enabled: true, driver: store.kind, ...data });
  683. } catch (e) {
  684. sendJson(res, 200, {
  685. enabled: false,
  686. driver: store.kind,
  687. reason: 'storage-unreachable',
  688. detail: e.message || String(e),
  689. });
  690. }
  691. });
  692. // ---------- 矩阵查询 ----------
  693. app.get('/api/ops/fields', async ({ res }) => {
  694. if (!(await requireHealthy(store, res))) return;
  695. try {
  696. const fields = await buildFieldCatalog(store);
  697. sendJson(res, 200, {
  698. fields: fields.map(({ key, label, type, source }) => ({ key, label, type, source })),
  699. defaults: BASE_FIELD_KEYS,
  700. });
  701. } catch (e) {
  702. sendJson(res, 503, { error: '读取失败', detail: e.message || String(e) });
  703. }
  704. });
  705. const insightCache = new Map();
  706. const INSIGHT_TTL_MS = 10 * 60 * 1000;
  707. app.post('/api/ops/insights', async ({ req, res }) => {
  708. if (!(await requireHealthy(store, res))) return;
  709. const chatCfg = makeChatCfg(ctx);
  710. if (!chatCfg.chatApiKey || chatCfg.chatApiKey === 'your-api-key-here') {
  711. return sendJson(res, 200, { enabled: false, reason: 'chat-not-configured' });
  712. }
  713. const body = await readBody(req);
  714. const params = {
  715. from: parseYmd(body.from) || undefined,
  716. to: parseYmd(body.to) || undefined,
  717. schools: splitList(body.schools),
  718. shops: splitList(body.shops),
  719. };
  720. const cacheKey = JSON.stringify(params);
  721. const cached = insightCache.get(cacheKey);
  722. if (!body.refresh && cached && Date.now() - cached.at < INSIGHT_TTL_MS) {
  723. return sendJson(res, 200, { enabled: true, ...cached.value, cached: true });
  724. }
  725. let data;
  726. try {
  727. data = await buildDashboard(store, params);
  728. } catch (e) {
  729. return sendJson(res, 503, { error: '聚合失败', detail: e.message || String(e) });
  730. }
  731. if (!data.kpis) {
  732. return sendJson(res, 200, { enabled: true, points: [], note: '所选范围没有数据' });
  733. }
  734. const context = insightContext(data);
  735. let text;
  736. try {
  737. text = await chatCompletion({
  738. apiBase: chatCfg.chatApiBase,
  739. apiKey: chatCfg.chatApiKey,
  740. model: chatCfg.chatModel,
  741. temperature: 0.3,
  742. timeoutMs: 45000,
  743. messages: [
  744. { role: 'system', content: INSIGHT_SYSTEM_PROMPT },
  745. { role: 'user', content: JSON.stringify(context) },
  746. ],
  747. });
  748. } catch (e) {
  749. return sendJson(res, 502, { enabled: true, error: '模型调用失败', detail: e.message || String(e) });
  750. }
  751. const value = {
  752. points: parseInsightPoints(text),
  753. model: chatCfg.chatModel,
  754. generatedAt: new Date().toISOString(),
  755. digest: context,
  756. };
  757. insightCache.set(cacheKey, { at: Date.now(), value });
  758. sendJson(res, 200, { enabled: true, ...value });
  759. });
  760. app.get('/api/ops/dashboard', async ({ res, query }) => {
  761. if (!(await requireHealthy(store, res))) return;
  762. const from = parseYmd(query.from);
  763. const to = parseYmd(query.to);
  764. const schools = splitList(query.schools);
  765. const shops = splitList(query.shops);
  766. try {
  767. const data = await buildDashboard(store, { from: from || undefined, to: to || undefined, schools, shops });
  768. sendJson(res, 200, data);
  769. } catch (e) {
  770. sendJson(res, 503, { error: '聚合失败', detail: e.message || String(e) });
  771. }
  772. });
  773. app.get('/api/ops/rows', async ({ res, query }) => {
  774. if (!(await requireHealthy(store, res))) return;
  775. const from = parseYmd(query.from);
  776. const to = parseYmd(query.to);
  777. const schools = splitList(query.schools);
  778. const shops = splitList(query.shops);
  779. let rows;
  780. try {
  781. rows = await loadMergedRows(store, { from: from || undefined, to: to || undefined, schools, shops });
  782. } catch (e) {
  783. return sendJson(res, 503, { error: '查询失败', detail: e.message || String(e) });
  784. }
  785. const catalog = await buildFieldCatalog(store);
  786. const wantedFields = parseFieldKeys(query.fields);
  787. let fields = wantedFields.length
  788. ? wantedFields.map((key) => catalog.find((f) => f.key === key)).filter(Boolean)
  789. : catalog.filter((f) => BASE_FIELD_KEYS.includes(f.key));
  790. if (!fields.length) fields = catalog.filter((f) => BASE_FIELD_KEYS.includes(f.key));
  791. const dates = [...new Set(rows.map((r) => r.date))].sort();
  792. sendJson(res, 200, {
  793. from: from || (dates[0] || null),
  794. to: to || (dates[dates.length - 1] || null),
  795. dates,
  796. fields: fields.map(({ key, label, type }) => ({ key, label, type })),
  797. groups: buildMatrix(rows, dates, fields),
  798. });
  799. });
  800. // ---------- 导入记录 ----------
  801. app.get('/api/ops/uploads', async ({ res }) => {
  802. if (!(await requireHealthy(store, res))) return;
  803. try {
  804. const uploads = await store.listUploads();
  805. sendJson(res, 200, { uploads });
  806. } catch (e) {
  807. sendJson(res, 503, { error: '读取失败', detail: e.message || String(e) });
  808. }
  809. });
  810. // ---------- 原件下载 ----------
  811. app.get('/api/ops/uploads/:id/file', async ({ res, params }) => {
  812. if (!UPLOAD_ID_RE.test(params.id)) return sendJson(res, 400, { error: '非法的上传 ID' });
  813. if (!(await requireHealthy(store, res))) return;
  814. const record = await store.getContent(params.id);
  815. if (!record) return sendJson(res, 404, { error: '找不到该上传记录' });
  816. const name = sanitizeName(record.originalName);
  817. res.writeHead(200, {
  818. 'Content-Type': XLSX_MIME,
  819. 'Content-Length': record.content.length,
  820. 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(name)}`,
  821. });
  822. res.end(record.content);
  823. });
  824. // ---------- 重新解析 ----------
  825. app.post('/api/ops/uploads/:id/reparse', async ({ res, params }) => {
  826. if (!UPLOAD_ID_RE.test(params.id)) return sendJson(res, 400, { error: '非法的上传 ID' });
  827. if (!(await requireHealthy(store, res))) return;
  828. const record = await store.getContent(params.id);
  829. if (!record) return sendJson(res, 404, { error: '找不到该上传记录' });
  830. const upload = await store.getUpload(params.id);
  831. const year = (upload && upload.year) || new Date().getFullYear();
  832. const school = (upload && upload.report && upload.report.schoolOverride) || '';
  833. let parsed;
  834. try {
  835. parsed = opsImport.parseAny(record.content, { year, school });
  836. } catch (e) {
  837. return sendJson(res, 400, { error: e.message || '解析失败', code: e.code || 'OPS_PARSE_FAILED' });
  838. }
  839. const from = parsed.dates[0] || '';
  840. const to = parsed.dates[parsed.dates.length - 1] || '';
  841. if (parsed.kind === 'platform-export') {
  842. const report = {
  843. kind: 'platform-export',
  844. rows: parsed.rows.length,
  845. shops: parsed.shops.length,
  846. newRows: parsed.rows.length,
  847. identicalRows: 0,
  848. conflictRows: 0,
  849. writtenRows: parsed.rows.length,
  850. warningCount: parsed.warnings.length,
  851. dates: { from, to },
  852. year,
  853. schoolOverride: school,
  854. parser: { kind: 'platform-export', version: PARSER_VERSION },
  855. warnings: parsed.warnings.slice(0, 500),
  856. reparsedAt: new Date().toISOString(),
  857. };
  858. try {
  859. await store.withTransaction(async (tx) => {
  860. await tx.deletePlatformRowsByUpload(params.id);
  861. await tx.upsertPlatformRows(parsed.rows.map((row) => ({ ...row, school, uploadId: params.id })));
  862. await tx.updateReport(params.id, report);
  863. });
  864. } catch (e) {
  865. return sendJson(res, 500, { error: '重新解析写入失败', detail: e.message || String(e) });
  866. }
  867. return sendJson(res, 200, { ok: true, uploadId: params.id, report });
  868. }
  869. const report = {
  870. kind: 'manual-ops',
  871. rows: parsed.rows.length,
  872. shops: parsed.shops.length,
  873. overwritten: 0,
  874. warningCount: parsed.warnings.length,
  875. dates: { from, to },
  876. year,
  877. schoolOverride: school,
  878. parser: { kind: 'manual-ops', version: PARSER_VERSION },
  879. warnings: parsed.warnings.slice(0, 500),
  880. reparsedAt: new Date().toISOString(),
  881. };
  882. try {
  883. await store.withTransaction(async (tx) => {
  884. await tx.deleteRowsByUpload(params.id);
  885. await tx.upsertRows(parsed.rows.map((row) => ({ ...row, uploadId: params.id })));
  886. await tx.upsertShops(parsed.shops.map((shop) => ({ ...shop, lastUploadId: params.id })));
  887. await tx.pruneOrphanShops();
  888. await tx.updateReport(params.id, report);
  889. });
  890. } catch (e) {
  891. return sendJson(res, 500, { error: '重新解析写入失败', detail: e.message || String(e) });
  892. }
  893. sendJson(res, 200, { ok: true, uploadId: params.id, report });
  894. });
  895. // ---------- 导出 ----------
  896. app.get('/api/ops/export', async ({ res, query }) => {
  897. if (!(await requireHealthy(store, res))) return;
  898. const from = parseYmd(query.from);
  899. const to = parseYmd(query.to);
  900. const schools = splitList(query.schools);
  901. const shops = splitList(query.shops);
  902. let rows;
  903. try {
  904. rows = await loadMergedRows(store, { from: from || undefined, to: to || undefined, schools, shops });
  905. } catch (e) {
  906. return sendJson(res, 503, { error: '查询失败', detail: e.message || String(e) });
  907. }
  908. const catalog = await buildFieldCatalog(store);
  909. const wantedFields = parseFieldKeys(query.fields);
  910. let fields = wantedFields.length
  911. ? wantedFields.map((key) => catalog.find((f) => f.key === key)).filter(Boolean)
  912. : catalog.filter((f) => BASE_FIELD_KEYS.includes(f.key));
  913. if (!fields.length) fields = catalog.filter((f) => BASE_FIELD_KEYS.includes(f.key));
  914. const sorted = rows.slice().sort((a, b) => {
  915. const school = String(a.school || '').localeCompare(String(b.school || ''), 'zh-Hans-CN');
  916. if (school !== 0) return school;
  917. const shop = String(a.shopName || '').localeCompare(String(b.shopName || ''), 'zh-Hans-CN');
  918. if (shop !== 0) return shop;
  919. return a.date < b.date ? -1 : a.date > b.date ? 1 : 0;
  920. });
  921. const lines = [];
  922. lines.push(['学校', '店铺ID', '店铺名称', '日期', ...fields.map((f) => f.label)].map(csvCell).join(','));
  923. for (const row of sorted) {
  924. lines.push([
  925. row.school || '',
  926. row.shopId || '',
  927. row.shopName || '',
  928. row.date,
  929. ...fields.map((field) => {
  930. const value = fieldValue(row, field);
  931. return value == null ? '' : value;
  932. }),
  933. ].map(csvCell).join(','));
  934. }
  935. const csv = '\ufeff' + lines.join('\r\n');
  936. res.writeHead(200, {
  937. 'Content-Type': 'text/csv; charset=utf-8',
  938. 'Content-Disposition': `attachment; filename="ops-${from || 'all'}-${to || 'all'}.csv"`,
  939. });
  940. res.end(csv);
  941. });
  942. }
  943. module.exports = { register };