ops.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. if (!body.force) {
  126. const existing = await store.findUploadBySha(sha256);
  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. let parsed;
  133. try {
  134. parsed = opsImport.parseWorkbook(content, { year });
  135. } catch (e) {
  136. return sendJson(res, 400, { error: e.message || '解析失败', code: e.code || 'OPS_PARSE_FAILED' });
  137. }
  138. if (!parsed.rows.length) {
  139. return sendJson(res, 400, { error: '未解析到有效数据行' });
  140. }
  141. const uploadId = newUploadId();
  142. const uploadedAt = new Date().toISOString();
  143. const from = parsed.dates[0] || '';
  144. const to = parsed.dates[parsed.dates.length - 1] || '';
  145. // 覆盖计数:该区间内已存在的「日期 + 店铺」组合
  146. let overwritten = 0;
  147. try {
  148. const existingRows = await store.queryRows({ from, to });
  149. const known = new Set(existingRows.map((r) => `${r.date}|${r.shopKey}`));
  150. for (const row of parsed.rows) if (known.has(`${row.date}|${row.shopKey}`)) overwritten += 1;
  151. } catch { /* 计数失败不影响导入 */ }
  152. const report = {
  153. rows: parsed.rows.length,
  154. shops: parsed.shops.length,
  155. overwritten,
  156. warningCount: parsed.warnings.length,
  157. dates: { from, to },
  158. year,
  159. parser: { kind: 'manual-ops', version: PARSER_VERSION },
  160. warnings: parsed.warnings.slice(0, 500),
  161. };
  162. try {
  163. await store.withTransaction(async (tx) => {
  164. await tx.insertUpload({
  165. id: uploadId,
  166. originalName: fileName,
  167. sha256,
  168. sizeBytes: content.length,
  169. uploadedAt,
  170. year,
  171. parserKind: 'manual-ops',
  172. parserVersion: PARSER_VERSION,
  173. report,
  174. content,
  175. });
  176. await tx.upsertRows(parsed.rows.map((row) => ({ ...row, uploadId })));
  177. await tx.upsertShops(parsed.shops.map((shop) => ({ ...shop, lastUploadId: uploadId })));
  178. });
  179. } catch (e) {
  180. return sendJson(res, 500, { error: '写入失败', detail: e.message || String(e) });
  181. }
  182. sendJson(res, 200, {
  183. ok: true,
  184. uploadId,
  185. report,
  186. warnings: parsed.warnings.slice(0, 200),
  187. });
  188. });
  189. // ---------- 概览 ----------
  190. app.get('/api/ops/summary', async ({ res }) => {
  191. const health = await store.health();
  192. if (!health.ok) {
  193. return sendJson(res, 200, {
  194. enabled: false,
  195. driver: store.kind,
  196. reason: health.reason || 'storage-unreachable',
  197. detail: health.detail || '',
  198. });
  199. }
  200. try {
  201. const data = await store.summary();
  202. sendJson(res, 200, { enabled: true, driver: store.kind, ...data });
  203. } catch (e) {
  204. sendJson(res, 200, {
  205. enabled: false,
  206. driver: store.kind,
  207. reason: 'storage-unreachable',
  208. detail: e.message || String(e),
  209. });
  210. }
  211. });
  212. // ---------- 矩阵查询 ----------
  213. app.get('/api/ops/rows', async ({ res, query }) => {
  214. if (!(await requireHealthy(store, res))) return;
  215. const from = parseYmd(query.from);
  216. const to = parseYmd(query.to);
  217. const schools = splitList(query.schools);
  218. const shops = splitList(query.shops);
  219. const metrics = parseMetricsParam(query.metrics);
  220. let rows;
  221. try {
  222. rows = await store.queryRows({ from: from || undefined, to: to || undefined, schools, shops });
  223. } catch (e) {
  224. return sendJson(res, 503, { error: '查询失败', detail: e.message || String(e) });
  225. }
  226. const dates = [...new Set(rows.map((r) => r.date))].sort();
  227. sendJson(res, 200, {
  228. from: from || (dates[0] || null),
  229. to: to || (dates[dates.length - 1] || null),
  230. dates,
  231. metrics,
  232. groups: buildMatrix(rows, dates),
  233. });
  234. });
  235. // ---------- 导入记录 ----------
  236. app.get('/api/ops/uploads', async ({ res }) => {
  237. if (!(await requireHealthy(store, res))) return;
  238. try {
  239. const uploads = await store.listUploads();
  240. sendJson(res, 200, { uploads });
  241. } catch (e) {
  242. sendJson(res, 503, { error: '读取失败', detail: e.message || String(e) });
  243. }
  244. });
  245. // ---------- 原件下载 ----------
  246. app.get('/api/ops/uploads/:id/file', async ({ res, params }) => {
  247. if (!UPLOAD_ID_RE.test(params.id)) return sendJson(res, 400, { error: '非法的上传 ID' });
  248. if (!(await requireHealthy(store, res))) return;
  249. const record = await store.getContent(params.id);
  250. if (!record) return sendJson(res, 404, { error: '找不到该上传记录' });
  251. const name = sanitizeName(record.originalName);
  252. res.writeHead(200, {
  253. 'Content-Type': XLSX_MIME,
  254. 'Content-Length': record.content.length,
  255. 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(name)}`,
  256. });
  257. res.end(record.content);
  258. });
  259. // ---------- 重新解析 ----------
  260. app.post('/api/ops/uploads/:id/reparse', async ({ res, params }) => {
  261. if (!UPLOAD_ID_RE.test(params.id)) return sendJson(res, 400, { error: '非法的上传 ID' });
  262. if (!(await requireHealthy(store, res))) return;
  263. const record = await store.getContent(params.id);
  264. if (!record) return sendJson(res, 404, { error: '找不到该上传记录' });
  265. const upload = await store.getUpload(params.id);
  266. const year = (upload && upload.year) || new Date().getFullYear();
  267. let parsed;
  268. try {
  269. parsed = opsImport.parseWorkbook(record.content, { year });
  270. } catch (e) {
  271. return sendJson(res, 400, { error: e.message || '解析失败', code: e.code || 'OPS_PARSE_FAILED' });
  272. }
  273. const from = parsed.dates[0] || '';
  274. const to = parsed.dates[parsed.dates.length - 1] || '';
  275. const report = {
  276. rows: parsed.rows.length,
  277. shops: parsed.shops.length,
  278. overwritten: 0,
  279. warningCount: parsed.warnings.length,
  280. dates: { from, to },
  281. year,
  282. parser: { kind: 'manual-ops', version: PARSER_VERSION },
  283. warnings: parsed.warnings.slice(0, 500),
  284. reparsedAt: new Date().toISOString(),
  285. };
  286. try {
  287. await store.withTransaction(async (tx) => {
  288. await tx.deleteRowsByUpload(params.id);
  289. await tx.upsertRows(parsed.rows.map((row) => ({ ...row, uploadId: params.id })));
  290. await tx.upsertShops(parsed.shops.map((shop) => ({ ...shop, lastUploadId: params.id })));
  291. await tx.updateReport(params.id, report);
  292. });
  293. } catch (e) {
  294. return sendJson(res, 500, { error: '重新解析写入失败', detail: e.message || String(e) });
  295. }
  296. sendJson(res, 200, { ok: true, uploadId: params.id, report });
  297. });
  298. // ---------- 导出 ----------
  299. app.get('/api/ops/export', async ({ res, query }) => {
  300. if (!(await requireHealthy(store, res))) return;
  301. const from = parseYmd(query.from);
  302. const to = parseYmd(query.to);
  303. const schools = splitList(query.schools);
  304. const shops = splitList(query.shops);
  305. const metrics = parseMetricsParam(query.metrics);
  306. let rows;
  307. try {
  308. rows = await store.queryRows({ from: from || undefined, to: to || undefined, schools, shops });
  309. } catch (e) {
  310. return sendJson(res, 503, { error: '查询失败', detail: e.message || String(e) });
  311. }
  312. const lines = [];
  313. if (metrics.length === 1) {
  314. const metric = metrics[0];
  315. const dates = [...new Set(rows.map((r) => r.date))].sort();
  316. lines.push(['学校', '店铺ID', '店铺名称', '状态', ...dates].map(csvCell).join(','));
  317. const byShop = new Map();
  318. for (const row of rows) {
  319. if (!byShop.has(row.shopKey)) byShop.set(row.shopKey, { row, values: {} });
  320. byShop.get(row.shopKey).values[row.date] = row[metric];
  321. }
  322. for (const { row, values } of byShop.values()) {
  323. lines.push([row.school, row.shopId || '', row.shopName, row.status || '',
  324. ...dates.map((d) => (values[d] == null ? '' : values[d]))].map(csvCell).join(','));
  325. }
  326. } else {
  327. lines.push(['学校', '店铺ID', '店铺名称', '日期', '指标', '数值'].map(csvCell).join(','));
  328. for (const row of rows) {
  329. for (const metric of metrics) {
  330. const value = row[metric];
  331. lines.push([row.school, row.shopId || '', row.shopName, row.date, metric, value == null ? '' : value]
  332. .map(csvCell).join(','));
  333. }
  334. }
  335. }
  336. const csv = '\ufeff' + lines.join('\r\n');
  337. res.writeHead(200, {
  338. 'Content-Type': 'text/csv; charset=utf-8',
  339. 'Content-Disposition': `attachment; filename="ops-${from || 'all'}-${to || 'all'}.csv"`,
  340. });
  341. res.end(csv);
  342. });
  343. }
  344. module.exports = { register };