ops.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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 MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
  9. const UPLOAD_ID_RE = /^\d{8}-\d{6}-[a-z0-9]{6}$/;
  10. const XLSX_MIME = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  11. const PARSER_VERSION = 1;
  12. const METRIC_KEYS = opsImport.METRIC_KEYS;
  13. const SUM_METRICS = new Set(['order_cnt', 'revenue', 'exposure']);
  14. function pad2(n) {
  15. return String(n).padStart(2, '0');
  16. }
  17. function newUploadId() {
  18. const d = new Date();
  19. const stamp = `${d.getFullYear()}${pad2(d.getMonth() + 1)}${pad2(d.getDate())}-${pad2(d.getHours())}${pad2(d.getMinutes())}${pad2(d.getSeconds())}`;
  20. return `${stamp}-${crypto.randomBytes(3).toString('hex')}`;
  21. }
  22. function sanitizeName(name) {
  23. const text = String(name || 'upload.xlsx')
  24. .replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_')
  25. .trim()
  26. .slice(0, 120);
  27. return text || 'upload.xlsx';
  28. }
  29. function splitList(value) {
  30. return String(value || '')
  31. .split(',')
  32. .map((s) => s.trim())
  33. .filter(Boolean);
  34. }
  35. function parseMetricsParam(value) {
  36. const wanted = splitList(value);
  37. if (!wanted.length) return METRIC_KEYS.slice();
  38. return METRIC_KEYS.filter((k) => wanted.includes(k));
  39. }
  40. function parseYmd(value) {
  41. const text = String(value || '').replace(/-/g, '');
  42. return /^\d{8}$/.test(text) ? text : '';
  43. }
  44. /** 存储不可用时的统一响应(summary 例外,它要返回 200 + enabled:false) */
  45. async function requireHealthy(store, res) {
  46. const health = await store.health();
  47. if (health.ok) return true;
  48. sendJson(res, 503, {
  49. error: '存储不可用',
  50. reason: health.reason || 'storage-unreachable',
  51. detail: health.detail || '',
  52. });
  53. return false;
  54. }
  55. function buildMatrix(rows, dates) {
  56. const schools = new Map();
  57. for (const row of rows) {
  58. const schoolName = row.school || '未分组';
  59. if (!schools.has(schoolName)) schools.set(schoolName, new Map());
  60. const shopMap = schools.get(schoolName);
  61. if (!shopMap.has(row.shopKey)) {
  62. shopMap.set(row.shopKey, {
  63. key: row.shopKey,
  64. shopId: row.shopId,
  65. shopName: row.shopName,
  66. status: row.status,
  67. series: {},
  68. quality: {},
  69. totals: {},
  70. });
  71. }
  72. const shop = shopMap.get(row.shopKey);
  73. for (const metric of METRIC_KEYS) {
  74. if (!shop.series[metric]) shop.series[metric] = {};
  75. shop.series[metric][row.date] = row[metric];
  76. }
  77. if (Array.isArray(row.quality) && row.quality.length) shop.quality[row.date] = row.quality;
  78. }
  79. const groups = [];
  80. for (const [school, shopMap] of [...schools.entries()].sort((a, b) => a[0].localeCompare(b[0], 'zh-Hans-CN'))) {
  81. const shops = [...shopMap.values()].sort((a, b) => String(a.shopName).localeCompare(String(b.shopName), 'zh-Hans-CN'));
  82. for (const shop of shops) {
  83. for (const metric of METRIC_KEYS) {
  84. if (!SUM_METRICS.has(metric)) continue;
  85. let sum = 0;
  86. let seen = false;
  87. for (const date of dates) {
  88. const value = shop.series[metric][date];
  89. if (typeof value === 'number') { sum += value; seen = true; }
  90. }
  91. shop.totals[metric] = seen ? Math.round(sum * 100) / 100 : null;
  92. }
  93. }
  94. groups.push({ school, shops });
  95. }
  96. return groups;
  97. }
  98. function csvCell(value) {
  99. const text = value == null ? '' : String(value);
  100. return /[",\n\r]/.test(text) ? '"' + text.replace(/"/g, '""') + '"' : text;
  101. }
  102. function register(app, ctx) {
  103. const store = createOpsStore(ctx.config);
  104. // ---------- 上传 ----------
  105. app.post('/api/ops/upload', async ({ req, res }) => {
  106. const body = await readBody(req);
  107. const fileName = sanitizeName(body.fileName);
  108. if (!/\.xlsx$/i.test(fileName)) {
  109. return sendJson(res, 400, { error: '只支持 .xlsx 文件' });
  110. }
  111. const base64 = String(body.contentBase64 || '').replace(/^data:[^;]+;base64,/, '');
  112. if (!base64) return sendJson(res, 400, { error: '缺少文件内容' });
  113. let content;
  114. try {
  115. content = Buffer.from(base64, 'base64');
  116. } catch {
  117. return sendJson(res, 400, { error: 'base64 解码失败' });
  118. }
  119. if (!content.length) return sendJson(res, 400, { error: '文件内容为空' });
  120. if (content.length > MAX_UPLOAD_BYTES) {
  121. return sendJson(res, 413, { error: '文件超过 10MB 上限' });
  122. }
  123. if (!(await requireHealthy(store, res))) return;
  124. const sha256 = crypto.createHash('sha256').update(content).digest('hex');
  125. const existing = await store.findUploadBySha(sha256);
  126. if (!body.force) {
  127. if (existing) {
  128. return sendJson(res, 409, { error: '该文件已导入过', uploadId: existing, duplicate: true });
  129. }
  130. }
  131. const year = Number(body.year) || new Date().getFullYear();
  132. const school = String(body.school || '').trim().slice(0, 60);
  133. let parsed;
  134. try {
  135. parsed = opsImport.parseWorkbook(content, { year, school });
  136. } catch (e) {
  137. return sendJson(res, 400, { error: e.message || '解析失败', code: e.code || 'OPS_PARSE_FAILED' });
  138. }
  139. if (!parsed.rows.length) {
  140. return sendJson(res, 400, { error: '未解析到有效数据行' });
  141. }
  142. // 表格里没有「学校名称」列、上传时也没指定 → 让用户补选,避免落成空白分组
  143. if (!parsed.shops.some((shop) => shop.school && shop.school.trim())) {
  144. return sendJson(res, 400, {
  145. error: '表格里没有「学校名称」列,请在上传时选择或填写学校',
  146. code: 'OPS_SCHOOL_REQUIRED',
  147. });
  148. }
  149. const uploadId = newUploadId();
  150. const uploadedAt = new Date().toISOString();
  151. const from = parsed.dates[0] || '';
  152. const to = parsed.dates[parsed.dates.length - 1] || '';
  153. // 覆盖计数:该区间内已存在的「日期 + 店铺」组合
  154. let overwritten = 0;
  155. try {
  156. const existingRows = await store.queryRows({ from, to });
  157. const known = new Set(existingRows.map((r) => `${r.date}|${r.shopKey}`));
  158. for (const row of parsed.rows) if (known.has(`${row.date}|${row.shopKey}`)) overwritten += 1;
  159. } catch { /* 计数失败不影响导入 */ }
  160. const report = {
  161. rows: parsed.rows.length,
  162. shops: parsed.shops.length,
  163. overwritten,
  164. warningCount: parsed.warnings.length,
  165. dates: { from, to },
  166. year,
  167. schoolOverride: school,
  168. parser: { kind: 'manual-ops', version: PARSER_VERSION },
  169. warnings: parsed.warnings.slice(0, 500),
  170. };
  171. try {
  172. await store.withTransaction(async (tx) => {
  173. if (body.force) await tx.deleteRowsBySha(sha256);
  174. await tx.insertUpload({
  175. id: uploadId,
  176. originalName: fileName,
  177. sha256,
  178. sizeBytes: content.length,
  179. uploadedAt,
  180. year,
  181. parserKind: 'manual-ops',
  182. parserVersion: PARSER_VERSION,
  183. report,
  184. content,
  185. });
  186. await tx.upsertRows(parsed.rows.map((row) => ({ ...row, uploadId })));
  187. await tx.upsertShops(parsed.shops.map((shop) => ({ ...shop, lastUploadId: uploadId })));
  188. await tx.pruneOrphanShops();
  189. });
  190. } catch (e) {
  191. return sendJson(res, 500, { error: '写入失败', detail: e.message || String(e) });
  192. }
  193. sendJson(res, 200, {
  194. ok: true,
  195. uploadId,
  196. report,
  197. warnings: parsed.warnings.slice(0, 200),
  198. });
  199. });
  200. // ---------- 概览 ----------
  201. app.get('/api/ops/summary', async ({ res }) => {
  202. const health = await store.health();
  203. if (!health.ok) {
  204. return sendJson(res, 200, {
  205. enabled: false,
  206. driver: store.kind,
  207. reason: health.reason || 'storage-unreachable',
  208. detail: health.detail || '',
  209. });
  210. }
  211. try {
  212. const data = await store.summary();
  213. sendJson(res, 200, { enabled: true, driver: store.kind, ...data });
  214. } catch (e) {
  215. sendJson(res, 200, {
  216. enabled: false,
  217. driver: store.kind,
  218. reason: 'storage-unreachable',
  219. detail: e.message || String(e),
  220. });
  221. }
  222. });
  223. // ---------- 矩阵查询 ----------
  224. app.get('/api/ops/rows', async ({ res, query }) => {
  225. if (!(await requireHealthy(store, res))) return;
  226. const from = parseYmd(query.from);
  227. const to = parseYmd(query.to);
  228. const schools = splitList(query.schools);
  229. const shops = splitList(query.shops);
  230. const metrics = parseMetricsParam(query.metrics);
  231. let rows;
  232. try {
  233. rows = await store.queryRows({ from: from || undefined, to: to || undefined, schools, shops });
  234. } catch (e) {
  235. return sendJson(res, 503, { error: '查询失败', detail: e.message || String(e) });
  236. }
  237. const dates = [...new Set(rows.map((r) => r.date))].sort();
  238. sendJson(res, 200, {
  239. from: from || (dates[0] || null),
  240. to: to || (dates[dates.length - 1] || null),
  241. dates,
  242. metrics,
  243. groups: buildMatrix(rows, dates),
  244. });
  245. });
  246. // ---------- 导入记录 ----------
  247. app.get('/api/ops/uploads', async ({ res }) => {
  248. if (!(await requireHealthy(store, res))) return;
  249. try {
  250. const uploads = await store.listUploads();
  251. sendJson(res, 200, { uploads });
  252. } catch (e) {
  253. sendJson(res, 503, { error: '读取失败', detail: e.message || String(e) });
  254. }
  255. });
  256. // ---------- 原件下载 ----------
  257. app.get('/api/ops/uploads/:id/file', async ({ res, params }) => {
  258. if (!UPLOAD_ID_RE.test(params.id)) return sendJson(res, 400, { error: '非法的上传 ID' });
  259. if (!(await requireHealthy(store, res))) return;
  260. const record = await store.getContent(params.id);
  261. if (!record) return sendJson(res, 404, { error: '找不到该上传记录' });
  262. const name = sanitizeName(record.originalName);
  263. res.writeHead(200, {
  264. 'Content-Type': XLSX_MIME,
  265. 'Content-Length': record.content.length,
  266. 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(name)}`,
  267. });
  268. res.end(record.content);
  269. });
  270. // ---------- 重新解析 ----------
  271. app.post('/api/ops/uploads/:id/reparse', async ({ res, params }) => {
  272. if (!UPLOAD_ID_RE.test(params.id)) return sendJson(res, 400, { error: '非法的上传 ID' });
  273. if (!(await requireHealthy(store, res))) return;
  274. const record = await store.getContent(params.id);
  275. if (!record) return sendJson(res, 404, { error: '找不到该上传记录' });
  276. const upload = await store.getUpload(params.id);
  277. const year = (upload && upload.year) || new Date().getFullYear();
  278. const school = (upload && upload.report && upload.report.schoolOverride) || '';
  279. let parsed;
  280. try {
  281. parsed = opsImport.parseWorkbook(record.content, { year, school });
  282. } catch (e) {
  283. return sendJson(res, 400, { error: e.message || '解析失败', code: e.code || 'OPS_PARSE_FAILED' });
  284. }
  285. const from = parsed.dates[0] || '';
  286. const to = parsed.dates[parsed.dates.length - 1] || '';
  287. const report = {
  288. rows: parsed.rows.length,
  289. shops: parsed.shops.length,
  290. overwritten: 0,
  291. warningCount: parsed.warnings.length,
  292. dates: { from, to },
  293. year,
  294. schoolOverride: school,
  295. parser: { kind: 'manual-ops', version: PARSER_VERSION },
  296. warnings: parsed.warnings.slice(0, 500),
  297. reparsedAt: new Date().toISOString(),
  298. };
  299. try {
  300. await store.withTransaction(async (tx) => {
  301. await tx.deleteRowsByUpload(params.id);
  302. await tx.upsertRows(parsed.rows.map((row) => ({ ...row, uploadId: params.id })));
  303. await tx.upsertShops(parsed.shops.map((shop) => ({ ...shop, lastUploadId: params.id })));
  304. await tx.pruneOrphanShops();
  305. await tx.updateReport(params.id, report);
  306. });
  307. } catch (e) {
  308. return sendJson(res, 500, { error: '重新解析写入失败', detail: e.message || String(e) });
  309. }
  310. sendJson(res, 200, { ok: true, uploadId: params.id, report });
  311. });
  312. // ---------- 导出 ----------
  313. app.get('/api/ops/export', async ({ res, query }) => {
  314. if (!(await requireHealthy(store, res))) return;
  315. const from = parseYmd(query.from);
  316. const to = parseYmd(query.to);
  317. const schools = splitList(query.schools);
  318. const shops = splitList(query.shops);
  319. const metrics = parseMetricsParam(query.metrics);
  320. let rows;
  321. try {
  322. rows = await store.queryRows({ from: from || undefined, to: to || undefined, schools, shops });
  323. } catch (e) {
  324. return sendJson(res, 503, { error: '查询失败', detail: e.message || String(e) });
  325. }
  326. const lines = [];
  327. if (metrics.length === 1) {
  328. const metric = metrics[0];
  329. const dates = [...new Set(rows.map((r) => r.date))].sort();
  330. lines.push(['学校', '店铺ID', '店铺名称', '状态', ...dates].map(csvCell).join(','));
  331. const byShop = new Map();
  332. for (const row of rows) {
  333. if (!byShop.has(row.shopKey)) byShop.set(row.shopKey, { row, values: {} });
  334. byShop.get(row.shopKey).values[row.date] = row[metric];
  335. }
  336. for (const { row, values } of byShop.values()) {
  337. lines.push([row.school, row.shopId || '', row.shopName, row.status || '',
  338. ...dates.map((d) => (values[d] == null ? '' : values[d]))].map(csvCell).join(','));
  339. }
  340. } else {
  341. lines.push(['学校', '店铺ID', '店铺名称', '日期', '指标', '数值'].map(csvCell).join(','));
  342. for (const row of rows) {
  343. for (const metric of metrics) {
  344. const value = row[metric];
  345. lines.push([row.school, row.shopId || '', row.shopName, row.date, metric, value == null ? '' : value]
  346. .map(csvCell).join(','));
  347. }
  348. }
  349. }
  350. const csv = '\ufeff' + lines.join('\r\n');
  351. res.writeHead(200, {
  352. 'Content-Type': 'text/csv; charset=utf-8',
  353. 'Content-Disposition': `attachment; filename="ops-${from || 'all'}-${to || 'all'}.csv"`,
  354. });
  355. res.end(csv);
  356. });
  357. }
  358. module.exports = { register };