ops.js 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565
  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, extractJson } = 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 cachedPlatformRows(store)).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. const PLATFORM_CACHE_TTL_MS = 5 * 60 * 1000;
  202. const platformRowCache = new WeakMap(); // store -> { at, rows }
  203. /** 平台明细整表缓存:云端库单次拉取约 1.6MB,避免每个请求重复传输 */
  204. async function cachedPlatformRows(store) {
  205. const hit = platformRowCache.get(store);
  206. if (hit && Date.now() - hit.at < PLATFORM_CACHE_TTL_MS) return hit.rows;
  207. const rows = await store.queryPlatformRows({});
  208. platformRowCache.set(store, { at: Date.now(), rows });
  209. return rows;
  210. }
  211. async function loadMergedRows(store, { from, to, schools, shops } = {}) {
  212. let platform = [];
  213. try {
  214. platform = await cachedPlatformRows(store);
  215. } catch { /* 平台表不可用不影响人工数据 */ }
  216. if (from) platform = platform.filter((row) => row.date >= from);
  217. if (to) platform = platform.filter((row) => row.date <= to);
  218. const manual = await store.queryRows({ from, to, schools, shops });
  219. const map = new Map();
  220. for (const row of platform) map.set(`${row.date}|${row.shopId}`, platformRowToMatrix(row));
  221. for (const row of manual) {
  222. const key = `${row.date}|${row.shopKey}`;
  223. const base = map.get(key);
  224. map.set(key, { ...(base || {}), ...row, platform: base ? base.platform : null });
  225. }
  226. let rows = [...map.values()];
  227. if (schools && schools.length) rows = rows.filter((r) => schools.includes(String(r.school || '')));
  228. if (shops && shops.length) rows = rows.filter((r) => shops.includes(String(r.shopId || r.shopKey || '')));
  229. return rows;
  230. }
  231. function addDays(ymd, n) {
  232. const d = new Date(Date.UTC(Number(ymd.slice(0, 4)), Number(ymd.slice(4, 6)) - 1, Number(ymd.slice(6, 8))));
  233. d.setUTCDate(d.getUTCDate() + n);
  234. return `${d.getUTCFullYear()}${pad2(d.getUTCMonth() + 1)}${pad2(d.getUTCDate())}`;
  235. }
  236. function dayCount(from, to) {
  237. const a = Date.UTC(Number(from.slice(0, 4)), Number(from.slice(4, 6)) - 1, Number(from.slice(6, 8)));
  238. const b = Date.UTC(Number(to.slice(0, 4)), Number(to.slice(4, 6)) - 1, Number(to.slice(6, 8)));
  239. return Math.max(1, Math.round((b - a) / 86400000) + 1);
  240. }
  241. function pctDelta(cur, prev) {
  242. if (prev == null || prev === 0 || cur == null) return null;
  243. return Math.round(((cur - prev) / prev) * 1000) / 10;
  244. }
  245. function sumSeries(rows, key) {
  246. let sum = 0;
  247. for (const row of rows) if (typeof row[key] === 'number') sum += row[key];
  248. return sum;
  249. }
  250. function platformNum(row, column) {
  251. if (!row.platform) return null;
  252. return numOrNull(row.platform[column]);
  253. }
  254. /** 零单门店诊断:用平台字段区分「未开业 / 闭店 / 无曝光 / 无进店 / 无转化」 */
  255. function diagnoseZeroOrder(row) {
  256. const p = row.platform;
  257. const orders = Number(row.order_cnt);
  258. if (!(orders === 0)) return null;
  259. if (!p) {
  260. return { reason: 'unknown', reasonText: '缺少平台明细,无法判断' };
  261. }
  262. const bizHours = String(p['营业时长'] == null ? '' : p['营业时长']).trim();
  263. const zeroBiz = /^0\s*小时\s*0\s*分$/.test(bizHours) || bizHours === '0' || bizHours === '';
  264. const abnormal = numOrNull(p['异常关店时长']) || 0;
  265. const exposure = numOrNull(p['曝光人数']);
  266. const visit = numOrNull(p['进店人数']);
  267. const validShop = String(p['是否有效门店'] || '').trim();
  268. if (zeroBiz) {
  269. if (validShop === '否') {
  270. return { reason: 'not-open', reasonText: '未开业(非有效门店,当日无营业时长)', bizHours, abnormal, exposure, visit, validShop };
  271. }
  272. if (abnormal > 0) {
  273. return { reason: 'closed', reasonText: `当日闭店(异常关店 ${abnormal} 分钟,无营业时长)`, bizHours, abnormal, exposure, visit, validShop };
  274. }
  275. return { reason: 'not-open', reasonText: '未营业(当日无营业时长,也未记录异常关店)', bizHours, abnormal, exposure, visit, validShop };
  276. }
  277. if (exposure === 0) {
  278. return { reason: 'no-traffic', reasonText: '营业中但无曝光(未进流量池)', bizHours, abnormal, exposure, visit, validShop };
  279. }
  280. if (visit === 0) {
  281. return { reason: 'no-visit', reasonText: `有曝光 ${exposure} 但无进店`, bizHours, abnormal, exposure, visit, validShop };
  282. }
  283. return { reason: 'no-conversion', reasonText: `有进店 ${visit} 但零下单(转化问题)`, bizHours, abnormal, exposure, visit, validShop };
  284. }
  285. /** 一次聚合:KPI 口径集中在这里,前端不再二次计算 */
  286. function aggregateRows(rows) {
  287. let revenue = 0;
  288. let orders = 0;
  289. let exposure = 0;
  290. let visit = 0;
  291. let buyers = 0;
  292. let expense = 0;
  293. let subsidy = 0;
  294. let ratingSum = 0;
  295. let ratingCount = 0;
  296. let rateWeight = 0;
  297. let rateAcc = 0;
  298. for (const row of rows) {
  299. if (typeof row.revenue === 'number') revenue += row.revenue;
  300. if (typeof row.order_cnt === 'number') orders += row.order_cnt;
  301. if (typeof row.exposure === 'number') exposure += row.exposure;
  302. if (typeof row.click_rate === 'number' && row.exposure > 0) {
  303. rateWeight += row.exposure;
  304. rateAcc += row.click_rate * row.exposure;
  305. }
  306. const v = platformNum(row, '进店人数');
  307. if (v != null) visit += v;
  308. const b = platformNum(row, '下单人数');
  309. if (b != null) buyers += b;
  310. const e = platformNum(row, '支出');
  311. if (e != null) expense += e;
  312. const sub = platformNum(row, '活动总补贴');
  313. if (sub != null) subsidy += sub;
  314. const rating = platformNum(row, '店铺评分');
  315. if (rating != null && rating > 0) {
  316. ratingSum += rating;
  317. ratingCount += 1;
  318. }
  319. }
  320. const conversion = visit > 0 && exposure > 0
  321. ? visit / exposure
  322. : (rateWeight > 0 ? rateAcc / rateWeight : null);
  323. return {
  324. revenue: Math.round(revenue * 100) / 100,
  325. orders,
  326. exposure,
  327. visit,
  328. buyers,
  329. expense: Math.round(expense * 100) / 100,
  330. subsidy: Math.round(subsidy * 100) / 100,
  331. rating: ratingCount ? Math.round((ratingSum / ratingCount) * 100) / 100 : null,
  332. avgTicket: orders > 0 ? Math.round((revenue / orders) * 100) / 100 : null,
  333. conversion: conversion == null ? null : Math.round(conversion * 10000) / 10000,
  334. };
  335. }
  336. async function buildDashboard(store, { from, to, schools, shops }) {
  337. const filters = { schools, shops };
  338. let rows = await loadMergedRows(store, { from, to, ...filters });
  339. const dates = [...new Set(rows.map((r) => r.date))].sort();
  340. const start = from || dates[0];
  341. const end = to || dates[dates.length - 1];
  342. if (!start || !end) {
  343. return { from: null, to: null, prev: null, kpis: null, trend: [], ranking: [], funnel: null, structure: [] };
  344. }
  345. // 未指定区间时按实际数据范围收敛
  346. if (!from || !to) rows = await loadMergedRows(store, { from: start, to: end, ...filters });
  347. const span = dayCount(start, end);
  348. const prevTo = addDays(start, -1);
  349. const prevFrom = addDays(prevTo, -(span - 1));
  350. let prevRows = [];
  351. try {
  352. prevRows = await loadMergedRows(store, { from: prevFrom, to: prevTo, ...filters });
  353. } catch { /* 上期缺失不影响本期 */ }
  354. const cur = aggregateRows(rows);
  355. const prev = prevRows.length ? aggregateRows(prevRows) : null;
  356. const kpi = (value, prevValue, unit, isRate) => ({
  357. value,
  358. prev: prevValue,
  359. delta: prevValue == null || value == null
  360. ? null
  361. : (isRate ? Math.round((value - prevValue) * 1000) / 10 : pctDelta(value, prevValue)),
  362. unit,
  363. });
  364. const kpis = {
  365. revenue: kpi(cur.revenue, prev && prev.revenue, 'money'),
  366. orders: kpi(cur.orders, prev && prev.orders, 'int'),
  367. avgTicket: kpi(cur.avgTicket, prev && prev.avgTicket, 'money'),
  368. exposure: kpi(cur.exposure, prev && prev.exposure, 'int'),
  369. conversion: kpi(cur.conversion, prev && prev.conversion, 'pp', true),
  370. rating: { value: cur.rating, prev: null, delta: null, unit: 'num' },
  371. };
  372. const byDate = new Map();
  373. const byShop = new Map();
  374. for (const row of rows) {
  375. if (!byDate.has(row.date)) byDate.set(row.date, []);
  376. byDate.get(row.date).push(row);
  377. const key = String(row.shopId || row.shopKey || '');
  378. if (!key) continue;
  379. if (!byShop.has(key)) byShop.set(key, { shopId: key, shopName: row.shopName || key, school: row.school || '', rows: [] });
  380. byShop.get(key).rows.push(row);
  381. }
  382. const trend = [...byDate.entries()].sort((a, b) => (a[0] < b[0] ? -1 : 1)).map(([date, list]) => {
  383. const agg = aggregateRows(list);
  384. return { date, revenue: agg.revenue, orders: agg.orders };
  385. });
  386. const allShops = [...byShop.values()]
  387. .map((shop) => {
  388. const agg = aggregateRows(shop.rows);
  389. return { shopId: shop.shopId, shopName: shop.shopName, school: shop.school, revenue: agg.revenue, orders: agg.orders };
  390. })
  391. .sort((a, b) => b.revenue - a.revenue);
  392. const ranking = allShops.slice(0, 10);
  393. const bottom = allShops.slice(-5).reverse();
  394. const funnel = {
  395. exposure: cur.exposure,
  396. visit: cur.visit,
  397. order: cur.buyers || cur.orders,
  398. };
  399. const zeroOrder = [];
  400. for (const row of rows) {
  401. const diagnosis = diagnoseZeroOrder(row);
  402. if (!diagnosis) continue;
  403. zeroOrder.push({
  404. date: row.date,
  405. shopId: row.shopId,
  406. shopName: row.shopName,
  407. school: row.school || '',
  408. orders: 0,
  409. ...diagnosis,
  410. });
  411. }
  412. const zeroOrderSummary = zeroOrder.reduce((acc, item) => {
  413. acc[item.reason] = (acc[item.reason] || 0) + 1;
  414. return acc;
  415. }, {});
  416. const structure = [...byDate.entries()].sort((a, b) => (a[0] < b[0] ? -1 : 1)).map(([date, list]) => {
  417. const agg = aggregateRows(list);
  418. return { date, income: agg.revenue, expense: agg.expense, subsidy: agg.subsidy };
  419. });
  420. return {
  421. from: start,
  422. to: end,
  423. prev: prevRows.length ? { from: prevFrom, to: prevTo } : null,
  424. kpis,
  425. trend,
  426. ranking,
  427. bottom,
  428. zeroOrder,
  429. zeroOrderSummary,
  430. shopCount: allShops.length,
  431. funnel,
  432. structure,
  433. };
  434. }
  435. const INSIGHT_SYSTEM_PROMPT = [
  436. '你是连锁餐饮公司的经营分析师。用户会给一段 JSON,包含某段时间的经营汇总(kpis)、按日趋势(trend)、门店排行(ranking)与垫底(bottom)、转化漏斗(funnel)、收入支出结构(structure)。',
  437. '请用中文输出 3~5 条要点,每行一条,以「- 」开头。要求:',
  438. '1. 先给结论,再给依据;',
  439. '2. 必须引用 JSON 里的具体数字(金额保留两位小数、人数/单量用整数、比率用百分比);',
  440. '3. 指出风险(下滑、零单门店、成本占比高、漏斗转化偏低等),并给一句可执行建议;',
  441. '4. 数据不足(如 prev 为 null、只有 1 天)就直接说明,不要编造;',
  442. '5. 若 zeroOrder 非空,必须用一条要点按原因归类汇总(未开业/闭店/无曝光/无进店/无转化各多少店次),并点明哪一类需要运营介入;不要笼统说「零单门店」;',
  443. '6. 每条不超过 60 字,不要输出 JSON、标题或前后缀。',
  444. ].join('\n');
  445. function insightContext(data) {
  446. const k = (key) => (data.kpis[key] ? { value: data.kpis[key].value, delta: data.kpis[key].delta } : null);
  447. const rate = (a, b) => (b > 0 ? Math.round((a / b) * 1000) / 10 : null);
  448. const funnel = data.funnel || {};
  449. return {
  450. range: { from: data.from, to: data.to, days: data.trend.length, prev: data.prev },
  451. kpis: {
  452. revenue: k('revenue'),
  453. orders: k('orders'),
  454. avgTicket: k('avgTicket'),
  455. exposure: k('exposure'),
  456. conversion: k('conversion'),
  457. rating: k('rating'),
  458. },
  459. funnel: {
  460. exposure: funnel.exposure,
  461. visit: funnel.visit,
  462. order: funnel.order,
  463. visitRate: rate(funnel.visit, funnel.exposure),
  464. orderRate: rate(funnel.order, funnel.visit),
  465. },
  466. trend: data.trend.slice(-14),
  467. shopCount: data.shopCount,
  468. topShops: (data.ranking || []).slice(0, 5).map((s) => ({ name: s.shopName, revenue: s.revenue, orders: s.orders })),
  469. bottomShops: (data.bottom || []).map((s) => ({ name: s.shopName, revenue: s.revenue, orders: s.orders })),
  470. zeroOrderSummary: data.zeroOrderSummary || {},
  471. zeroOrder: (data.zeroOrder || []).slice(0, 20).map((z) => ({
  472. date: z.date,
  473. shop: z.shopName,
  474. reason: z.reason,
  475. reasonText: z.reasonText,
  476. })),
  477. structure: (data.structure || []).map((s) => ({
  478. date: s.date,
  479. income: s.income,
  480. expense: s.expense,
  481. subsidy: s.subsidy,
  482. expenseRatio: s.income > 0 ? Math.round((s.expense / s.income) * 1000) / 10 : null,
  483. })),
  484. };
  485. }
  486. function parseInsightPoints(text) {
  487. return String(text || '')
  488. .split(/\r?\n/)
  489. .map((line) => line.replace(/^\s*(?:[-*•]|\d+[.、)])\s*/, '').trim())
  490. .filter(Boolean)
  491. .slice(0, 6);
  492. }
  493. /** 由聚合结果生成 Report JSON(图文 / 交互 / PDF 三版共用;数值全部来自后端计算) */
  494. function buildReport(data, meta = {}) {
  495. const { kpis, trend, ranking, bottom, zeroOrder, funnel, structure, from, to, prev, shopCount } = data;
  496. const money = (v) => (v == null ? null : Math.round(v * 100) / 100);
  497. const pct = (v) => (v == null ? null : Math.round(v * 1000) / 10);
  498. const findings = [];
  499. const rev = kpis.revenue || {};
  500. if (rev.delta != null) {
  501. findings.push({
  502. severity: rev.delta < -5 ? 'warning' : rev.delta > 5 ? 'positive' : 'neutral',
  503. finding: `营业额 ${money(rev.value)} 元,较上期 ${rev.delta > 0 ? '增长' : '下降'} ${Math.abs(rev.delta)}%`,
  504. evidence: [`营业额:${money(rev.value)}`, `上期营业额:${money(rev.prev)}`],
  505. interpretation: rev.delta < 0 ? '规模收缩,需要结合订单量与流量拆解原因' : '规模增长,关注是否由活动或流量投放带来',
  506. confidence: 'high',
  507. });
  508. }
  509. const conv = kpis.conversion || {};
  510. if (conv.value != null) {
  511. findings.push({
  512. severity: conv.delta != null && conv.delta < -0.5 ? 'warning' : 'neutral',
  513. finding: `进店转化率 ${pct(conv.value)}%${conv.delta != null ? `,较上期 ${conv.delta > 0 ? '+' : ''}${conv.delta}pp` : ''}`,
  514. evidence: [`进店转化率:${pct(conv.value)}%`],
  515. interpretation: '转化率反映进店后的下单意愿,需结合定价、售罄与出餐时长判断',
  516. confidence: 'medium',
  517. });
  518. }
  519. const zeroByReason = (zeroOrder || []).reduce((acc, item) => {
  520. acc[item.reason] = acc[item.reason] || [];
  521. acc[item.reason].push(item);
  522. return acc;
  523. }, {});
  524. const zeroTotal = (zeroOrder || []).length;
  525. if (zeroTotal) {
  526. const parts = Object.entries(zeroByReason).map(([reason, list]) => `${REASON_LABEL[reason] || reason} ${list.length} 店次`);
  527. findings.push({
  528. severity: (zeroByReason['no-conversion'] || []).length ? 'warning' : 'neutral',
  529. finding: `零单合计 ${zeroTotal} 店次:${parts.join('、')}`,
  530. evidence: [`零单店次:${zeroTotal}`],
  531. interpretation: '未开业/闭店属于营业状态问题;有进店无下单才是转化问题,需要优先处理',
  532. confidence: 'high',
  533. });
  534. }
  535. if (ranking && ranking.length && rev.value > 0) {
  536. const share = Math.round((ranking[0].revenue / rev.value) * 1000) / 10;
  537. findings.push({
  538. severity: share > 40 ? 'warning' : 'neutral',
  539. finding: `头部门店「${ranking[0].shopName}」贡献营业额 ${money(ranking[0].revenue)} 元,占比 ${share}%`,
  540. evidence: [`头部门店:${ranking[0].shopName}(${money(ranking[0].revenue)} 元)`],
  541. interpretation: share > 40 ? '集中度偏高,单店波动会显著影响大盘' : '门店贡献相对分散',
  542. confidence: 'high',
  543. });
  544. }
  545. if (!prev) {
  546. findings.push({
  547. severity: 'neutral',
  548. finding: '所选区间之前没有可比数据,本期不计算环比趋势',
  549. evidence: ['上期数据:无'],
  550. interpretation: '只能做横向门店对比与当日诊断,不要据此判断长期趋势',
  551. confidence: 'high',
  552. });
  553. }
  554. const alerts = [];
  555. for (const [reason, list] of Object.entries(zeroByReason)) {
  556. alerts.push({
  557. severity: reason === 'no-conversion' ? 'P1' : 'P2',
  558. store_id: list[0].shopId || null,
  559. title: `${REASON_LABEL[reason] || reason}:${list.length} 店次`,
  560. evidence: list.slice(0, 5).map((z) => `${formatYmd(z.date)} ${z.shopName}:${z.reasonText}`),
  561. hypotheses: reason === 'no-conversion'
  562. ? ['菜品/定价与周边相比缺乏竞争力', '出餐或配送时长导致流失', '活动力度不足或库存售罄']
  563. : ['门店未上线或当日排班缺失', '平台侧闭店/审核状态异常'],
  564. next_checks: reason === 'no-conversion'
  565. ? ['核对当日菜品售罄记录', '查看差评与退款原因', '对比同商圈同类门店客单价']
  566. : ['确认门店上线状态与营业时间设置', '核对平台闭店记录'],
  567. });
  568. }
  569. if (conv.delta != null && conv.delta < -0.5) {
  570. alerts.push({
  571. severity: 'P1', store_id: null, title: '进店转化率下滑',
  572. evidence: [`本期进店转化率:${pct(conv.value)}%`, `上期进店转化率:${pct(conv.prev)}%`],
  573. hypotheses: ['菜单改价或活动结束', '高峰期出餐变慢', '竞品补贴'],
  574. next_checks: ['对比改价/活动时间', '查看出餐时长与超时单'],
  575. });
  576. }
  577. const actionPlan = [];
  578. if ((zeroByReason['no-conversion'] || []).length) {
  579. actionPlan.push({
  580. priority: 'P0',
  581. action: '对「有进店无下单」门店做单店诊断:菜品可售、价格带、出餐与配送时长',
  582. owner_role: '运营负责人',
  583. time_horizon: '24 小时内',
  584. success_metric: '次日进店→下单转化率回升',
  585. related_alerts: ['有进店无下单'],
  586. });
  587. }
  588. if ((zeroByReason['not-open'] || []).length || (zeroByReason['closed'] || []).length) {
  589. actionPlan.push({
  590. priority: 'P1',
  591. action: '核对未开业/闭店门店的上线状态、营业时间与异常关店记录',
  592. owner_role: '门店督导',
  593. time_horizon: '48 小时内',
  594. success_metric: '营业时长恢复、零单店次下降',
  595. related_alerts: ['未开业', '当日闭店'],
  596. });
  597. }
  598. if (conv.delta != null && conv.delta < -0.5) {
  599. actionPlan.push({
  600. priority: 'P1',
  601. action: '排查转化率下滑:活动是否结束、是否改价、是否有售罄',
  602. owner_role: '运营负责人',
  603. time_horizon: '72 小时内',
  604. success_metric: '转化率回到上期水平',
  605. related_alerts: ['进店转化率下滑'],
  606. });
  607. }
  608. if (prev) {
  609. actionPlan.push({
  610. priority: 'P2',
  611. action: '补全成本与结算口径,再评估毛利与真实利润',
  612. owner_role: '财务',
  613. time_horizon: '2 周内',
  614. success_metric: '可计算毛利与费用率',
  615. related_alerts: [],
  616. });
  617. }
  618. const kpiList = [
  619. ['revenue', '营业额', 'CNY', '平台「营业额」列求和'],
  620. ['orders', '有效订单', '单', '平台「有效订单」列求和'],
  621. ['avgTicket', '客单价', 'CNY', '营业额 ÷ 有效订单'],
  622. ['exposure', '曝光人数', '人', '平台「曝光人数」列求和'],
  623. ['conversion', '进店转化率', '%', 'Σ进店人数 ÷ Σ曝光人数'],
  624. ['rating', '店铺评分', '分', '有效评分门店均值(排除 0 分)'],
  625. ].map(([key, label, unit, definition]) => {
  626. const item = kpis[key] || {};
  627. const fmt = (value) => {
  628. if (value == null) return null;
  629. if (unit === '%') return pct(value);
  630. if (unit === '单' || unit === '人') return Math.round(value);
  631. return money(value);
  632. };
  633. return {
  634. key, label, unit, definition,
  635. current: fmt(item.value),
  636. previous: fmt(item.prev),
  637. difference: item.value != null && item.prev != null && unit !== '%'
  638. ? Math.round((item.value - item.prev) * 100) / 100
  639. : (item.value != null && item.prev != null ? Math.round((item.value - item.prev) * 1000) / 10 : null),
  640. change_pct: item.delta,
  641. status: item.delta == null ? 'unknown' : item.delta > 0 ? 'up' : item.delta < 0 ? 'down' : 'flat',
  642. };
  643. });
  644. return {
  645. meta: {
  646. title: meta.title || '经营分析报告',
  647. organization: meta.organization || '',
  648. period_start: formatYmd(from),
  649. period_end: formatYmd(to),
  650. generated_at: new Date().toISOString(),
  651. currency: 'CNY',
  652. data_scope: `${shopCount} 家门店 · ${trend.length} 天 · ${zeroTotal} 个零单店次`,
  653. source_files: meta.sourceFiles || [],
  654. },
  655. executive_summary: {
  656. overall_assessment: rev.delta == null
  657. ? '本期有经营数据,但缺少可比的上期,暂不做趋势判断;以下结论基于本期横向对比与门店诊断。'
  658. : `本期营业额 ${money(rev.value)} 元,较上期${rev.delta >= 0 ? '增长' : '下降'} ${Math.abs(rev.delta)}%,订单 ${kpis.orders.value} 单。`,
  659. key_findings: findings,
  660. },
  661. kpis: kpiList,
  662. sections: [
  663. { id: 'overview', title: '经营概览', summary: rev.delta == null ? '本期无上期对比' : `营业额环比 ${rev.delta}%`, paragraphs: [], chart_ids: ['chart_trend'], table_ids: [], evidence_keys: ['revenue', 'orders'] },
  664. { id: 'stores', title: '门店表现', summary: `共 ${shopCount} 家门店,Top1 为「${(ranking[0] || {}).shopName || '—'}」`, paragraphs: [], chart_ids: ['chart_rank'], table_ids: ['table_stores'], evidence_keys: ['revenue'] },
  665. { id: 'funnel', title: '流量与转化', summary: `曝光 ${funnel.exposure} → 进店 ${funnel.visit} → 下单 ${funnel.order}`, paragraphs: [], chart_ids: ['chart_funnel'], table_ids: [], evidence_keys: ['conversion'] },
  666. { id: 'finance', title: '收入与费用', summary: '仅展示平台收入、支出与补贴,不等同于利润', paragraphs: [], chart_ids: ['chart_structure'], table_ids: [], evidence_keys: ['revenue'] },
  667. { id: 'quality', title: '数据质量', summary: '', paragraphs: [], chart_ids: [], table_ids: [], evidence_keys: [] },
  668. ],
  669. stores: (ranking || []).slice(0, 10).map((shop, index) => ({
  670. store_id: shop.shopId,
  671. name: shop.shopName,
  672. rank: index + 1,
  673. facts: [`营业额 ${money(shop.revenue)} 元,订单 ${shop.orders} 单`],
  674. diagnosis: index === 0 ? '本期贡献最高,需保持供给与活动稳定' : '贡献靠后,结合流量与转化排查',
  675. risks: [],
  676. recommendations: [],
  677. })),
  678. charts: [
  679. { id: 'chart_trend', type: 'line_bar', title: '营业额与订单趋势', description: '柱为营业额,线为订单量;天数较少时不做平滑趋势判断。', source: '平台明细按日聚合', unit: 'CNY', data: trend },
  680. { id: 'chart_rank', type: 'horizontal_bar', title: '门店营业额 Top 10', description: '按所选区间营业额排序。', source: '平台明细按门店聚合', unit: 'CNY', data: ranking },
  681. { id: 'chart_funnel', type: 'funnel', title: '曝光 → 进店 → 下单', description: '三层人数不可跨口径混算。', source: '平台「曝光人数/进店人数/下单人数」', unit: '人', data: funnel },
  682. { id: 'chart_structure', type: 'bar', title: '收入与支出结构', description: '收入为营业额;支出与补贴按平台口径。', source: '平台「营业额/支出/活动总补贴」', unit: 'CNY', data: structure },
  683. ],
  684. tables: [{
  685. id: 'table_stores',
  686. title: '门店明细(Top 10)',
  687. columns: [
  688. { key: 'name', label: '门店' }, { key: 'revenue', label: '营业额' },
  689. { key: 'orders', label: '订单' }, { key: 'share', label: '占比' },
  690. ],
  691. rows: (ranking || []).map((shop) => ({
  692. name: shop.shopName, revenue: money(shop.revenue), orders: shop.orders,
  693. share: rev.value > 0 ? Math.round((shop.revenue / rev.value) * 1000) / 10 : null,
  694. })),
  695. footnote: '占比 = 门店营业额 ÷ 本期总营业额',
  696. }],
  697. alerts,
  698. action_plan: actionPlan,
  699. data_quality: {
  700. coverage: `${formatYmd(from)} ~ ${formatYmd(to)},共 ${trend.length} 天`,
  701. warnings: prev ? [] : ['所选区间前无数据,环比不可用'],
  702. comparability: '同店对比要求门店集合一致;本期未做同店筛选',
  703. missing_metrics: ['成本、平台佣金明细缺失,无法计算毛利与净利'],
  704. },
  705. methodology: [
  706. '金额与单量均由后端按「日期+门店」明细求和,不由模型生成',
  707. '进店转化率 = Σ进店人数 ÷ Σ曝光人数(同层级口径)',
  708. '客单价 = 营业额 ÷ 有效订单,订单为 0 时为 null',
  709. '上期为紧邻的等长区间,比率变化用百分点(pp)',
  710. ],
  711. };
  712. }
  713. const REPORT_AI_PROMPT = [
  714. '你是连锁餐饮公司的经营分析师。用户会给一段已经计算好的经营数据 JSON(含 kpis/trend/ranking/bottom/funnel/structure/zeroOrder)。',
  715. '数值全部由后端计算,你不得修改、杜撰或重算;只做解释、诊断与建议。',
  716. '只输出一个 JSON 对象,不要代码块、不要前后缀,结构如下:',
  717. '{"overall_assessment":"一段客观判断",',
  718. ' "key_findings":[{"severity":"positive|neutral|warning|critical","finding":"结论","evidence":["指标:数值"],"interpretation":"解释","confidence":"high|medium|low"}],',
  719. ' "sections":[{"id":"overview|stores|funnel|finance","summary":"本节结论","paragraphs":["事实与解释"]}],',
  720. ' "alerts":[{"severity":"P0|P1|P2","title":"告警标题","evidence":["数据证据"],"hypotheses":["待验证原因"],"next_checks":["核查步骤"]}],',
  721. ' "action_plan":[{"priority":"P0|P1|P2","action":"具体行动","owner_role":"负责人角色","time_horizon":"时间窗","success_metric":"可衡量指标"}]}',
  722. '要求:3~5 条 findings、2~4 条 alerts、1~4 条 action;金额保留两位小数,比率用百分比;',
  723. 'zeroOrder 非空时必须按原因归类(未开业/闭店/无曝光/无进店/无转化各多少店次)并点明哪类需要运营介入;',
  724. '没有上期数据时明确说明不可做趋势判断;不输出「赋能」「抓手」等套话。',
  725. '术语必须与指标名一致:revenue 是「营业额」(不是收入/结算收入/利润),avgTicket 是「客单价」,conversion 是「进店转化率」;日期一律写成 YYYY-MM-DD。',
  726. 'evidence 必须写成「中文指标名:数值」(如「营业额:14926.92」「零单店次:11」),禁止出现 zeroOrder、revenue、top_shop 等内部字段名。',
  727. ].join('\n');
  728. const EVIDENCE_CN = {
  729. revenue: '营业额', orders: '有效订单', avgTicket: '客单价', exposure: '曝光人数',
  730. conversion: '进店转化率', rating: '店铺评分', zeroOrder: '零单店次',
  731. previous: '上期值', prev: '上期值', top_shop: '头部门店', shop_id: '门店ID',
  732. visit: '进店人数', buyers: '下单人数', expense: '支出', subsidy: '补贴',
  733. };
  734. /** 把模型偶发的内部字段名(zeroOrder/revenue 等)翻成中文,普通用户才看得懂 */
  735. function humanizeText(value) {
  736. return String(value == null ? '' : value)
  737. .replace(/\b(zeroOrder|revenue|orders|avgTicket|exposure|conversion|rating|previous|prev|top_shop|shop_id|visit|buyers|expense|subsidy)\b(:?)/g,
  738. (match, key, colon) => EVIDENCE_CN[key] + (colon || ''));
  739. }
  740. function humanizeEvidence(list) {
  741. return (list || []).map(humanizeText);
  742. }
  743. /** 把模型返回的叙述字段覆盖到规则版报告上;结构不合法就返回 null(保留规则版) */
  744. function overlayAiReport(base, ai, meta = {}) {
  745. if (!ai || typeof ai !== 'object') return null;
  746. const report = JSON.parse(JSON.stringify(base));
  747. let touched = false;
  748. if (typeof ai.overall_assessment === 'string' && ai.overall_assessment.trim()) {
  749. report.executive_summary.overall_assessment = ai.overall_assessment.trim();
  750. touched = true;
  751. }
  752. if (Array.isArray(ai.key_findings) && ai.key_findings.length) {
  753. const findings = ai.key_findings
  754. .filter((f) => f && f.finding)
  755. .slice(0, 6)
  756. .map((f) => ({
  757. severity: ['positive', 'neutral', 'warning', 'critical'].includes(f.severity) ? f.severity : 'neutral',
  758. finding: humanizeText(f.finding).slice(0, 120),
  759. evidence: humanizeEvidence(f.evidence).slice(0, 5),
  760. interpretation: f.interpretation ? humanizeText(f.interpretation).slice(0, 200) : '',
  761. confidence: ['high', 'medium', 'low'].includes(f.confidence) ? f.confidence : 'medium',
  762. }));
  763. if (findings.length) {
  764. report.executive_summary.key_findings = findings;
  765. touched = true;
  766. }
  767. }
  768. if (Array.isArray(ai.sections)) {
  769. const byId = new Map(report.sections.map((sec) => [sec.id, sec]));
  770. for (const sec of ai.sections) {
  771. const target = sec && byId.get(sec.id);
  772. if (!target) continue;
  773. if (sec.summary) target.summary = String(sec.summary).slice(0, 200);
  774. if (Array.isArray(sec.paragraphs) && sec.paragraphs.length) {
  775. target.paragraphs = sec.paragraphs.slice(0, 4).map((t) => String(t).slice(0, 400));
  776. }
  777. touched = true;
  778. }
  779. }
  780. if (Array.isArray(ai.alerts) && ai.alerts.length) {
  781. report.alerts = ai.alerts.slice(0, 5).map((a) => ({
  782. severity: ['P0', 'P1', 'P2'].includes(a.severity) ? a.severity : 'P2',
  783. store_id: a.store_id || null,
  784. title: humanizeText(a.title || '').slice(0, 80),
  785. evidence: humanizeEvidence(a.evidence).slice(0, 6),
  786. hypotheses: Array.isArray(a.hypotheses) ? a.hypotheses.slice(0, 4).map(String) : [],
  787. next_checks: Array.isArray(a.next_checks) ? a.next_checks.slice(0, 4).map(String) : [],
  788. }));
  789. touched = true;
  790. }
  791. if (Array.isArray(ai.action_plan) && ai.action_plan.length) {
  792. report.action_plan = ai.action_plan.slice(0, 4).map((p) => ({
  793. priority: ['P0', 'P1', 'P2'].includes(p.priority) ? p.priority : 'P2',
  794. action: String(p.action || '').slice(0, 160),
  795. owner_role: String(p.owner_role || '').slice(0, 40),
  796. time_horizon: String(p.time_horizon || '').slice(0, 40),
  797. success_metric: String(p.success_metric || '').slice(0, 80),
  798. related_alerts: Array.isArray(p.related_alerts) ? p.related_alerts : [],
  799. }));
  800. touched = true;
  801. }
  802. if (!touched) return null;
  803. report.ai = { source: 'llm', model: meta.model || '', generatedAt: new Date().toISOString() };
  804. return report;
  805. }
  806. const REASON_LABEL = { 'not-open': '未开业', closed: '当日闭店', 'no-traffic': '无曝光', 'no-visit': '无进店', 'no-conversion': '有进店无下单', unknown: '数据不足' };
  807. function formatYmd(ymd) {
  808. const s = String(ymd || '');
  809. return /^\d{8}$/.test(s) ? `${s.slice(0, 4)}-${s.slice(4, 6)}-${s.slice(6, 8)}` : '';
  810. }
  811. function csvCell(value) {
  812. const text = value == null ? '' : String(value);
  813. return /[",\n\r]/.test(text) ? '"' + text.replace(/"/g, '""') + '"' : text;
  814. }
  815. /** 从文件名识别已登记学校(取最长匹配,如「浙江工商桐庐校区20261018…」→ 浙江工商大学桐庐校区) */
  816. function resolveSchoolFromFileName(fileName) {
  817. let best = '';
  818. let bestName = '';
  819. for (const school of loadSchools()) {
  820. for (const candidate of [school.name, ...(school.aliases || [])]) {
  821. const name = String(candidate || '').trim();
  822. if (name && fileName.includes(name) && name.length > bestName.length) {
  823. best = school.name;
  824. bestName = name;
  825. }
  826. }
  827. }
  828. return best;
  829. }
  830. function register(app, ctx) {
  831. const store = createOpsStore(ctx.config);
  832. // ---------- 上传 ----------
  833. app.post('/api/ops/upload', async ({ req, res }) => {
  834. const body = await readBody(req);
  835. const fileName = sanitizeName(body.fileName);
  836. if (!/\.xlsx$/i.test(fileName)) {
  837. return sendJson(res, 400, { error: '只支持 .xlsx 文件' });
  838. }
  839. const base64 = String(body.contentBase64 || '').replace(/^data:[^;]+;base64,/, '');
  840. if (!base64) return sendJson(res, 400, { error: '缺少文件内容' });
  841. let content;
  842. try {
  843. content = Buffer.from(base64, 'base64');
  844. } catch {
  845. return sendJson(res, 400, { error: 'base64 解码失败' });
  846. }
  847. if (!content.length) return sendJson(res, 400, { error: '文件内容为空' });
  848. if (content.length > MAX_UPLOAD_BYTES) {
  849. return sendJson(res, 413, { error: '文件超过 10MB 上限' });
  850. }
  851. if (!(await requireHealthy(store, res))) return;
  852. const sha256 = crypto.createHash('sha256').update(content).digest('hex');
  853. const existing = await store.findUploadBySha(sha256);
  854. if (!body.force) {
  855. if (existing) {
  856. return sendJson(res, 409, { error: '该文件已导入过', uploadId: existing, duplicate: true });
  857. }
  858. }
  859. const year = Number(body.year) || new Date().getFullYear();
  860. let school = String(body.school || '').trim().slice(0, 60);
  861. let parsed;
  862. try {
  863. parsed = opsImport.parseAny(content, { year, school });
  864. } catch (e) {
  865. return sendJson(res, 400, { error: e.message || '解析失败', code: e.code || 'OPS_PARSE_FAILED' });
  866. }
  867. if (!parsed.rows.length) {
  868. return sendJson(res, 400, { error: '未解析到有效数据行' });
  869. }
  870. const uploadId = newUploadId();
  871. const uploadedAt = new Date().toISOString();
  872. const from = parsed.dates[0] || '';
  873. const to = parsed.dates[parsed.dates.length - 1] || '';
  874. // ---------- 平台导出(全字段明细) ----------
  875. if (parsed.kind === 'platform-export') {
  876. // 表里没有学校列:优先用上传时选定的学校,其次从文件名识别(如「浙江工商桐庐校区20261018…」)
  877. if (!school) school = resolveSchoolFromFileName(fileName);
  878. if (!school) {
  879. return sendJson(res, 400, { error: '请选择学校(平台导出表里没有学校列)', code: 'OPS_SCHOOL_REQUIRED' });
  880. }
  881. const existingRows = await store.queryPlatformRows({ from, to });
  882. const known = new Map(existingRows.map((r) => [`${r.date}|${r.shopId}`, r]));
  883. let newRows = 0;
  884. let identicalRows = 0;
  885. let conflictRows = 0;
  886. const incoming = [];
  887. for (const row of parsed.rows) {
  888. const key = `${row.date}|${row.shopId}`;
  889. const old = known.get(key);
  890. if (!old) { newRows += 1; incoming.push(row); continue; }
  891. const sameData = JSON.stringify(old.data) === JSON.stringify(row.data);
  892. if (sameData && old.school === school) { identicalRows += 1; continue; }
  893. conflictRows += 1;
  894. if (body.force) incoming.push(row);
  895. }
  896. const toWrite = body.force ? parsed.rows : incoming;
  897. const report = {
  898. kind: 'platform-export',
  899. rows: parsed.rows.length,
  900. shops: parsed.shops.length,
  901. newRows,
  902. identicalRows,
  903. conflictRows,
  904. writtenRows: toWrite.length,
  905. warningCount: parsed.warnings.length,
  906. dates: { from, to },
  907. year,
  908. schoolOverride: school,
  909. parser: { kind: 'platform-export', version: PARSER_VERSION },
  910. columns: parsed.columns || [],
  911. warnings: parsed.warnings.slice(0, 500),
  912. };
  913. try {
  914. await store.withTransaction(async (tx) => {
  915. // 事务内二次校验:并发同名文件只允许一个写入
  916. if (!body.force && await tx.findUploadBySha(sha256)) {
  917. const err = new Error('duplicate');
  918. err.code = 'OPS_DUPLICATE';
  919. throw err;
  920. }
  921. if (body.force) await tx.deletePlatformRowsBySha(sha256);
  922. await tx.insertUpload({
  923. id: uploadId,
  924. originalName: fileName,
  925. sha256,
  926. sizeBytes: content.length,
  927. uploadedAt,
  928. year,
  929. parserKind: 'platform-export',
  930. parserVersion: PARSER_VERSION,
  931. report,
  932. content,
  933. });
  934. if (toWrite.length) {
  935. await tx.upsertPlatformRows(toWrite.map((row) => ({ ...row, school, uploadId })));
  936. }
  937. });
  938. } catch (e) {
  939. if (e.code === 'OPS_DUPLICATE') {
  940. return sendJson(res, 409, { error: '该文件已导入过', uploadId: await store.findUploadBySha(sha256), duplicate: true });
  941. }
  942. return sendJson(res, 500, { error: '写入失败', detail: e.message || String(e) });
  943. }
  944. platformRowCache.delete(store);
  945. return sendJson(res, 200, {
  946. ok: true,
  947. uploadId,
  948. report,
  949. warnings: parsed.warnings.slice(0, 200),
  950. duplicateData: report.newRows === 0 && report.conflictRows === 0,
  951. });
  952. }
  953. // ---------- 人工统计表 ----------
  954. // 表格里没有「学校名称」列、上传时也没指定 → 让用户补选,避免落成空白分组
  955. if (!parsed.shops.some((shop) => shop.school && shop.school.trim())) {
  956. return sendJson(res, 400, {
  957. error: '表格里没有「学校名称」列,请在上传时选择或填写学校',
  958. code: 'OPS_SCHOOL_REQUIRED',
  959. });
  960. }
  961. // 覆盖计数:该区间内已存在的「日期 + 店铺」组合
  962. let overwritten = 0;
  963. try {
  964. const existingDaily = await store.queryRows({ from, to });
  965. const knownDaily = new Set(existingDaily.map((r) => `${r.date}|${r.shopKey}`));
  966. for (const row of parsed.rows) if (knownDaily.has(`${row.date}|${row.shopKey}`)) overwritten += 1;
  967. } catch { /* 计数失败不影响导入 */ }
  968. const report = {
  969. kind: 'manual-ops',
  970. rows: parsed.rows.length,
  971. shops: parsed.shops.length,
  972. overwritten,
  973. warningCount: parsed.warnings.length,
  974. dates: { from, to },
  975. year,
  976. schoolOverride: school,
  977. parser: { kind: 'manual-ops', version: PARSER_VERSION },
  978. warnings: parsed.warnings.slice(0, 500),
  979. };
  980. try {
  981. await store.withTransaction(async (tx) => {
  982. if (!body.force && await tx.findUploadBySha(sha256)) {
  983. const err = new Error('duplicate');
  984. err.code = 'OPS_DUPLICATE';
  985. throw err;
  986. }
  987. if (body.force) await tx.deleteRowsBySha(sha256);
  988. await tx.insertUpload({
  989. id: uploadId,
  990. originalName: fileName,
  991. sha256,
  992. sizeBytes: content.length,
  993. uploadedAt,
  994. year,
  995. parserKind: 'manual-ops',
  996. parserVersion: PARSER_VERSION,
  997. report,
  998. content,
  999. });
  1000. await tx.upsertRows(parsed.rows.map((row) => ({ ...row, uploadId })));
  1001. await tx.upsertShops(parsed.shops.map((shop) => ({ ...shop, lastUploadId: uploadId })));
  1002. await tx.pruneOrphanShops();
  1003. });
  1004. } catch (e) {
  1005. if (e.code === 'OPS_DUPLICATE') {
  1006. return sendJson(res, 409, { error: '该文件已导入过', uploadId: await store.findUploadBySha(sha256), duplicate: true });
  1007. }
  1008. return sendJson(res, 500, { error: '写入失败', detail: e.message || String(e) });
  1009. }
  1010. platformRowCache.delete(store);
  1011. sendJson(res, 200, {
  1012. ok: true,
  1013. uploadId,
  1014. report,
  1015. warnings: parsed.warnings.slice(0, 200),
  1016. });
  1017. });
  1018. // ---------- 概览 ----------
  1019. app.get('/api/ops/summary', async ({ res }) => {
  1020. const health = await store.health();
  1021. if (!health.ok) {
  1022. return sendJson(res, 200, {
  1023. enabled: false,
  1024. driver: store.kind,
  1025. reason: health.reason || 'storage-unreachable',
  1026. detail: health.detail || '',
  1027. });
  1028. }
  1029. try {
  1030. const data = await store.summary();
  1031. sendJson(res, 200, { enabled: true, driver: store.kind, ...data });
  1032. } catch (e) {
  1033. sendJson(res, 200, {
  1034. enabled: false,
  1035. driver: store.kind,
  1036. reason: 'storage-unreachable',
  1037. detail: e.message || String(e),
  1038. });
  1039. }
  1040. });
  1041. // ---------- 矩阵查询 ----------
  1042. app.get('/api/ops/fields', async ({ res }) => {
  1043. if (!(await requireHealthy(store, res))) return;
  1044. try {
  1045. const fields = await buildFieldCatalog(store);
  1046. sendJson(res, 200, {
  1047. fields: fields.map(({ key, label, type, source }) => ({ key, label, type, source })),
  1048. defaults: BASE_FIELD_KEYS,
  1049. });
  1050. } catch (e) {
  1051. sendJson(res, 503, { error: '读取失败', detail: e.message || String(e) });
  1052. }
  1053. });
  1054. // ---------- 统一报告生成(经营解读与经营报告共用一份 JSON) ----------
  1055. async function currentDataVersion() {
  1056. try {
  1057. const summary = await store.summary();
  1058. return `${summary.uploadCount || 0}|${summary.platformRowCount || 0}|${(summary.coverage && summary.coverage.to) || ''}`;
  1059. } catch {
  1060. return '';
  1061. }
  1062. }
  1063. async function getReportPayload(params, { ai = false, force = false } = {}) {
  1064. const key = JSON.stringify(params);
  1065. const version = await currentDataVersion();
  1066. if (!force && version) {
  1067. const cached = await store.getReportCache(key, version);
  1068. if (cached && cached.report && (!ai || cached.source === 'llm')) {
  1069. return { ...cached.report, cached: true };
  1070. }
  1071. }
  1072. const data = await buildDashboard(store, params);
  1073. if (!data.kpis) return { empty: true };
  1074. const uploads = await store.listUploads().catch(() => []);
  1075. const base = buildReport(data, {
  1076. organization: (params.schools && params.schools[0]) || '',
  1077. sourceFiles: uploads.slice(0, 3).map((u) => u.originalName),
  1078. });
  1079. base.ai = { source: 'rules', model: '', generatedAt: new Date().toISOString() };
  1080. let payload = base;
  1081. let source = 'rules';
  1082. let aiError = '';
  1083. const chatCfg = makeChatCfg(ctx);
  1084. const configured = chatCfg.chatApiKey && chatCfg.chatApiKey !== 'your-api-key-here';
  1085. if (ai && configured) {
  1086. let aiOk = false;
  1087. for (let attempt = 0; attempt < 2 && !aiOk; attempt += 1) {
  1088. try {
  1089. const text = await chatCompletion({
  1090. apiBase: chatCfg.chatApiBase,
  1091. apiKey: chatCfg.chatApiKey,
  1092. model: chatCfg.chatModel,
  1093. temperature: 0.3,
  1094. timeoutMs: 60000,
  1095. messages: [
  1096. { role: 'system', content: REPORT_AI_PROMPT },
  1097. { role: 'user', content: JSON.stringify(insightContext(data)) },
  1098. ],
  1099. });
  1100. const merged = overlayAiReport(base, extractJson(text), { model: chatCfg.chatModel });
  1101. if (merged) {
  1102. payload = merged;
  1103. source = 'llm';
  1104. aiOk = true;
  1105. aiError = '';
  1106. } else {
  1107. aiError = '模型返回结构不合法,已退回规则版';
  1108. }
  1109. } catch (e) {
  1110. aiError = e.message || String(e);
  1111. if (attempt === 0) await new Promise((resolve) => setTimeout(resolve, 800));
  1112. }
  1113. }
  1114. } else if (ai && !configured) {
  1115. aiError = '未配置对话模型,当前为规则版';
  1116. }
  1117. if (aiError) payload.aiError = aiError;
  1118. if (version) {
  1119. try {
  1120. await store.saveReportCache({
  1121. cacheKey: key,
  1122. updatedAt: new Date().toISOString(),
  1123. dataVersion: version,
  1124. source,
  1125. report: payload,
  1126. });
  1127. } catch { /* 缓存写失败不影响返回 */ }
  1128. }
  1129. return { ...payload, cached: false };
  1130. }
  1131. // 经营解读 = 报告 JSON 的摘要视图
  1132. app.post('/api/ops/insights', async ({ req, res }) => {
  1133. if (!(await requireHealthy(store, res))) return;
  1134. const body = await readBody(req);
  1135. const params = {
  1136. from: parseYmd(body.from) || undefined,
  1137. to: parseYmd(body.to) || undefined,
  1138. schools: splitList(body.schools),
  1139. shops: splitList(body.shops),
  1140. };
  1141. try {
  1142. const report = await getReportPayload(params, { ai: true, force: !!body.refresh });
  1143. if (report.empty || !report.executive_summary) {
  1144. return sendJson(res, 200, { enabled: true, points: [], note: '所选范围没有数据' });
  1145. }
  1146. const findings = report.executive_summary.key_findings || [];
  1147. const points = findings.slice(0, 5).map((f) => f.finding);
  1148. const alerts = (report.alerts || []).slice(0, 3).map((a) => ({ severity: a.severity, title: a.title }));
  1149. sendJson(res, 200, {
  1150. enabled: true,
  1151. points,
  1152. alerts,
  1153. source: (report.ai && report.ai.source) || 'rules',
  1154. model: (report.ai && report.ai.model) || '',
  1155. generatedAt: (report.ai && report.ai.generatedAt) || new Date().toISOString(),
  1156. aiError: report.aiError || '',
  1157. range: { from: report.meta.period_start, to: report.meta.period_end },
  1158. cached: !!report.cached,
  1159. });
  1160. } catch (e) {
  1161. sendJson(res, 502, { enabled: true, error: '生成失败', detail: e.message || String(e) });
  1162. }
  1163. });
  1164. app.get('/api/ops/report', async ({ res, query }) => {
  1165. if (!(await requireHealthy(store, res))) return;
  1166. const params = {
  1167. from: parseYmd(query.from) || undefined,
  1168. to: parseYmd(query.to) || undefined,
  1169. schools: splitList(query.schools),
  1170. shops: splitList(query.shops),
  1171. };
  1172. try {
  1173. const report = await getReportPayload(params, { ai: query.ai === '1', force: query.refresh === '1' });
  1174. if (report.empty) return sendJson(res, 200, { empty: true });
  1175. sendJson(res, 200, { report });
  1176. } catch (e) {
  1177. sendJson(res, 503, { error: '报告生成失败', detail: e.message || String(e) });
  1178. }
  1179. });
  1180. // ---------- 报告中心(保存 / 列表 / 查看 / 删除) ----------
  1181. app.post('/api/ops/reports', async ({ req, res }) => {
  1182. if (!(await requireHealthy(store, res))) return;
  1183. const body = await readBody(req);
  1184. const params = {
  1185. from: parseYmd(body.from) || undefined,
  1186. to: parseYmd(body.to) || undefined,
  1187. schools: splitList(body.schools),
  1188. shops: splitList(body.shops),
  1189. };
  1190. try {
  1191. // 前端会把它当前看到的 Report JSON 一起提交,保证「保存的就是所见」
  1192. let report = body.report;
  1193. if (!report || !report.meta || !Array.isArray(report.kpis)) {
  1194. report = await getReportPayload(params, { ai: false });
  1195. }
  1196. if (!report || report.empty) return sendJson(res, 400, { error: '所选范围没有数据,无法保存' });
  1197. const id = `rpt_${newUploadId()}`;
  1198. const record = {
  1199. id,
  1200. createdAt: new Date().toISOString(),
  1201. periodFrom: String(report.meta.period_start || '').replace(/-/g, ''),
  1202. periodTo: String(report.meta.period_end || '').replace(/-/g, ''),
  1203. schools: params.schools,
  1204. shops: params.shops,
  1205. source: (report.ai && report.ai.source) || 'rules',
  1206. model: (report.ai && report.ai.model) || '',
  1207. title: report.meta.title || '经营分析报告',
  1208. report,
  1209. };
  1210. await store.insertReport(record);
  1211. sendJson(res, 200, { ok: true, id, createdAt: record.createdAt, source: record.source });
  1212. } catch (e) {
  1213. sendJson(res, 500, { error: '保存失败', detail: e.message || String(e) });
  1214. }
  1215. });
  1216. app.get('/api/ops/reports', async ({ res }) => {
  1217. if (!(await requireHealthy(store, res))) return;
  1218. try {
  1219. const reports = await store.listReports();
  1220. // 把保存时记录的店铺 key 映射成名称,历史记录才看得懂范围
  1221. let shopNameByKey = new Map();
  1222. try {
  1223. const summary = await store.summary();
  1224. shopNameByKey = new Map((summary.shops || []).map((s) => [String(s.key || s.shopId || ''), s.shopName || '']));
  1225. } catch { /* 映射失败时保留 key */ }
  1226. sendJson(res, 200, {
  1227. reports: reports.map((item) => ({
  1228. ...item,
  1229. schoolNames: item.schools || [],
  1230. shopNames: (item.shops || []).map((key) => shopNameByKey.get(String(key)) || String(key)),
  1231. })),
  1232. });
  1233. } catch (e) {
  1234. sendJson(res, 503, { error: '读取失败', detail: e.message || String(e) });
  1235. }
  1236. });
  1237. app.get('/api/ops/reports/:id', async ({ res, params }) => {
  1238. if (!/^rpt_\d{8}-\d{6}-[a-z0-9]{6}$/.test(params.id)) return sendJson(res, 400, { error: '非法的报告 ID' });
  1239. if (!(await requireHealthy(store, res))) return;
  1240. try {
  1241. const report = await store.getReport(params.id);
  1242. if (!report) return sendJson(res, 404, { error: '报告不存在' });
  1243. sendJson(res, 200, { report });
  1244. } catch (e) {
  1245. sendJson(res, 503, { error: '读取失败', detail: e.message || String(e) });
  1246. }
  1247. });
  1248. app.del('/api/ops/reports/:id', async ({ res, params }) => {
  1249. if (!/^rpt_\d{8}-\d{6}-[a-z0-9]{6}$/.test(params.id)) return sendJson(res, 400, { error: '非法的报告 ID' });
  1250. if (!(await requireHealthy(store, res))) return;
  1251. try {
  1252. const removed = await store.deleteReport(params.id);
  1253. sendJson(res, 200, { ok: true, removed });
  1254. } catch (e) {
  1255. sendJson(res, 500, { error: '删除失败', detail: e.message || String(e) });
  1256. }
  1257. });
  1258. app.get('/api/ops/dashboard', async ({ res, query }) => {
  1259. if (!(await requireHealthy(store, res))) return;
  1260. const from = parseYmd(query.from);
  1261. const to = parseYmd(query.to);
  1262. const schools = splitList(query.schools);
  1263. const shops = splitList(query.shops);
  1264. try {
  1265. const data = await buildDashboard(store, { from: from || undefined, to: to || undefined, schools, shops });
  1266. sendJson(res, 200, data);
  1267. } catch (e) {
  1268. sendJson(res, 503, { error: '聚合失败', detail: e.message || String(e) });
  1269. }
  1270. });
  1271. app.get('/api/ops/rows', async ({ res, query }) => {
  1272. if (!(await requireHealthy(store, res))) return;
  1273. const from = parseYmd(query.from);
  1274. const to = parseYmd(query.to);
  1275. const schools = splitList(query.schools);
  1276. const shops = splitList(query.shops);
  1277. let rows;
  1278. try {
  1279. rows = await loadMergedRows(store, { from: from || undefined, to: to || undefined, schools, shops });
  1280. } catch (e) {
  1281. return sendJson(res, 503, { error: '查询失败', detail: e.message || String(e) });
  1282. }
  1283. const catalog = await buildFieldCatalog(store);
  1284. const wantedFields = parseFieldKeys(query.fields);
  1285. let fields = wantedFields.length
  1286. ? wantedFields.map((key) => catalog.find((f) => f.key === key)).filter(Boolean)
  1287. : catalog.filter((f) => BASE_FIELD_KEYS.includes(f.key));
  1288. if (!fields.length) fields = catalog.filter((f) => BASE_FIELD_KEYS.includes(f.key));
  1289. const dates = [...new Set(rows.map((r) => r.date))].sort();
  1290. sendJson(res, 200, {
  1291. from: from || (dates[0] || null),
  1292. to: to || (dates[dates.length - 1] || null),
  1293. dates,
  1294. fields: fields.map(({ key, label, type }) => ({ key, label, type })),
  1295. groups: buildMatrix(rows, dates, fields),
  1296. });
  1297. });
  1298. // ---------- 导入记录 ----------
  1299. app.get('/api/ops/uploads', async ({ res }) => {
  1300. if (!(await requireHealthy(store, res))) return;
  1301. try {
  1302. const uploads = await store.listUploads();
  1303. sendJson(res, 200, { uploads });
  1304. } catch (e) {
  1305. sendJson(res, 503, { error: '读取失败', detail: e.message || String(e) });
  1306. }
  1307. });
  1308. // ---------- 原件下载 ----------
  1309. app.get('/api/ops/uploads/:id/file', async ({ res, params }) => {
  1310. if (!UPLOAD_ID_RE.test(params.id)) return sendJson(res, 400, { error: '非法的上传 ID' });
  1311. if (!(await requireHealthy(store, res))) return;
  1312. const record = await store.getContent(params.id);
  1313. if (!record) return sendJson(res, 404, { error: '找不到该上传记录' });
  1314. const name = sanitizeName(record.originalName);
  1315. res.writeHead(200, {
  1316. 'Content-Type': XLSX_MIME,
  1317. 'Content-Length': record.content.length,
  1318. 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(name)}`,
  1319. });
  1320. res.end(record.content);
  1321. });
  1322. // ---------- 重新解析 ----------
  1323. app.post('/api/ops/uploads/:id/reparse', async ({ res, params }) => {
  1324. if (!UPLOAD_ID_RE.test(params.id)) return sendJson(res, 400, { error: '非法的上传 ID' });
  1325. if (!(await requireHealthy(store, res))) return;
  1326. const record = await store.getContent(params.id);
  1327. if (!record) return sendJson(res, 404, { error: '找不到该上传记录' });
  1328. const upload = await store.getUpload(params.id);
  1329. const year = (upload && upload.year) || new Date().getFullYear();
  1330. const school = (upload && upload.report && upload.report.schoolOverride) || '';
  1331. let parsed;
  1332. try {
  1333. parsed = opsImport.parseAny(record.content, { year, school });
  1334. } catch (e) {
  1335. return sendJson(res, 400, { error: e.message || '解析失败', code: e.code || 'OPS_PARSE_FAILED' });
  1336. }
  1337. const from = parsed.dates[0] || '';
  1338. const to = parsed.dates[parsed.dates.length - 1] || '';
  1339. if (parsed.kind === 'platform-export') {
  1340. const report = {
  1341. kind: 'platform-export',
  1342. rows: parsed.rows.length,
  1343. shops: parsed.shops.length,
  1344. newRows: parsed.rows.length,
  1345. identicalRows: 0,
  1346. conflictRows: 0,
  1347. writtenRows: parsed.rows.length,
  1348. warningCount: parsed.warnings.length,
  1349. dates: { from, to },
  1350. year,
  1351. schoolOverride: school,
  1352. parser: { kind: 'platform-export', version: PARSER_VERSION },
  1353. warnings: parsed.warnings.slice(0, 500),
  1354. reparsedAt: new Date().toISOString(),
  1355. };
  1356. try {
  1357. await store.withTransaction(async (tx) => {
  1358. await tx.deletePlatformRowsByUpload(params.id);
  1359. await tx.upsertPlatformRows(parsed.rows.map((row) => ({ ...row, school, uploadId: params.id })));
  1360. await tx.updateReport(params.id, report);
  1361. });
  1362. } catch (e) {
  1363. return sendJson(res, 500, { error: '重新解析写入失败', detail: e.message || String(e) });
  1364. }
  1365. return sendJson(res, 200, { ok: true, uploadId: params.id, report });
  1366. }
  1367. const report = {
  1368. kind: 'manual-ops',
  1369. rows: parsed.rows.length,
  1370. shops: parsed.shops.length,
  1371. overwritten: 0,
  1372. warningCount: parsed.warnings.length,
  1373. dates: { from, to },
  1374. year,
  1375. schoolOverride: school,
  1376. parser: { kind: 'manual-ops', version: PARSER_VERSION },
  1377. warnings: parsed.warnings.slice(0, 500),
  1378. reparsedAt: new Date().toISOString(),
  1379. };
  1380. try {
  1381. await store.withTransaction(async (tx) => {
  1382. await tx.deleteRowsByUpload(params.id);
  1383. await tx.upsertRows(parsed.rows.map((row) => ({ ...row, uploadId: params.id })));
  1384. await tx.upsertShops(parsed.shops.map((shop) => ({ ...shop, lastUploadId: params.id })));
  1385. await tx.pruneOrphanShops();
  1386. await tx.updateReport(params.id, report);
  1387. });
  1388. } catch (e) {
  1389. return sendJson(res, 500, { error: '重新解析写入失败', detail: e.message || String(e) });
  1390. }
  1391. sendJson(res, 200, { ok: true, uploadId: params.id, report });
  1392. });
  1393. // ---------- 导出 ----------
  1394. app.get('/api/ops/export', async ({ res, query }) => {
  1395. if (!(await requireHealthy(store, res))) return;
  1396. const from = parseYmd(query.from);
  1397. const to = parseYmd(query.to);
  1398. const schools = splitList(query.schools);
  1399. const shops = splitList(query.shops);
  1400. let rows;
  1401. try {
  1402. rows = await loadMergedRows(store, { from: from || undefined, to: to || undefined, schools, shops });
  1403. } catch (e) {
  1404. return sendJson(res, 503, { error: '查询失败', detail: e.message || String(e) });
  1405. }
  1406. const catalog = await buildFieldCatalog(store);
  1407. const wantedFields = parseFieldKeys(query.fields);
  1408. let fields = wantedFields.length
  1409. ? wantedFields.map((key) => catalog.find((f) => f.key === key)).filter(Boolean)
  1410. : catalog.filter((f) => BASE_FIELD_KEYS.includes(f.key));
  1411. if (!fields.length) fields = catalog.filter((f) => BASE_FIELD_KEYS.includes(f.key));
  1412. const sorted = rows.slice().sort((a, b) => {
  1413. const school = String(a.school || '').localeCompare(String(b.school || ''), 'zh-Hans-CN');
  1414. if (school !== 0) return school;
  1415. const shop = String(a.shopName || '').localeCompare(String(b.shopName || ''), 'zh-Hans-CN');
  1416. if (shop !== 0) return shop;
  1417. return a.date < b.date ? -1 : a.date > b.date ? 1 : 0;
  1418. });
  1419. const lines = [];
  1420. lines.push(['学校', '店铺ID', '店铺名称', '日期', ...fields.map((f) => f.label)].map(csvCell).join(','));
  1421. for (const row of sorted) {
  1422. lines.push([
  1423. row.school || '',
  1424. row.shopId || '',
  1425. row.shopName || '',
  1426. row.date,
  1427. ...fields.map((field) => {
  1428. const value = fieldValue(row, field);
  1429. return value == null ? '' : value;
  1430. }),
  1431. ].map(csvCell).join(','));
  1432. }
  1433. const csv = '\ufeff' + lines.join('\r\n');
  1434. res.writeHead(200, {
  1435. 'Content-Type': 'text/csv; charset=utf-8',
  1436. 'Content-Disposition': `attachment; filename="ops-${from || 'all'}-${to || 'all'}.csv"`,
  1437. });
  1438. res.end(csv);
  1439. });
  1440. }
  1441. module.exports = { register };