napos-service.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. 'use strict';
  2. /**
  3. * 数据报表 · 取数服务层
  4. * ----------------------------------------------------------------------------
  5. * 桥接 napos/(淘宝闪购商家客户端 CDP 取数引擎)与 reports-store(本地数据湖)。
  6. *
  7. * 取数通道:附着本机商家客户端调试端口(默认 9669),由客户端页面自身的登录态
  8. * 代发请求(非爬虫、不模拟点击);数据中心接口按域自动补签名。
  9. *
  10. * 数据来源(数据中心 lsycm · historyOverview):
  11. * ds 日期 / valid_order_cnt 有效订单 / gross_amt 营业额 / income_amt 收入 /
  12. * expense_amt 支出 / exp_uv 曝光人数 / order_user_cnt 下单人数 /
  13. * clk_exp_rate 进店转化率 / ord_clk_rate 下单转化率 / per_actual_pay 客单价 …
  14. *
  15. * 营业时长 / 异常关店时长 / 商品销售额:当前接口目录暂无对应字段,
  16. * 作为预留列返回 null,取数层保留原始返回值,后续补源即可回填。
  17. */
  18. const kit = require('./napos/kit.js');
  19. const store = require('./reports-store.js');
  20. const DEFAULT_CDP_PORT = Number(process.env.NAPOS_CDP_PORT || 9669);
  21. // ---------- BI 列注册表(语义层)----------
  22. // synonyms / description 供「智能问数」的 LLM 做实体对齐与口径解释
  23. const REPORT_COLUMNS = [
  24. { key: 'account', label: '账号名', type: 'text', locked: true, aggregable: false,
  25. synonyms: ['账号', '账号名', '账户', '主体'],
  26. description: '数据所属的商家账号(主体)名称;多账号数据合并查看或导出时用于区分来源' },
  27. { key: 'date', label: '日期', type: 'date', locked: true, aggregable: false,
  28. synonyms: ['日期', '天', '哪天', '日期时间'],
  29. description: '数据日期,格式 YYYYMMDD;当天数据未结算,有效区间一般为 T-1 及更早' },
  30. { key: 'shopName', label: '门店名称', type: 'text', locked: true, aggregable: false,
  31. synonyms: ['门店', '店铺', '店', '门店名'],
  32. description: '门店名称,支持模糊筛选' },
  33. { key: 'bizHours', label: '营业时长(h)', type: 'hours', reserved: true,
  34. synonyms: ['营业时长', '营业时间', '开店时长'],
  35. description: '预留列:当日营业小时数,数据源暂未接入' },
  36. { key: 'abnormalCloseHours', label: '异常关店时长(h)', type: 'hours', reserved: true,
  37. synonyms: ['异常关店', '异常关店时长', '关店时长', '异常闭店'],
  38. description: '预留列:非计划性关店时长,数据源暂未接入' },
  39. { key: 'validOrderCnt', label: '有效订单', type: 'int',
  40. synonyms: ['有效订单', '订单量', '单量', '订单数', '有效单量'],
  41. description: '剔除取消/无效后的订单量' },
  42. { key: 'incomeAmt', label: '收入(元)', type: 'money',
  43. synonyms: ['收入', '实际收入', '到账', '营收'],
  44. description: '商家实际收入(元);营业额 = 收入 + 支出' },
  45. { key: 'grossAmt', label: '营业额(元)', type: 'money',
  46. synonyms: ['营业额', '流水', 'GMV', 'gmv', '销售额', '交易额'],
  47. description: '营业额(元),口径 = 收入 + 支出;做排行/对比的首选指标' },
  48. { key: 'goodsSaleAmt', label: '商品销售额(元)', type: 'money', reserved: true,
  49. synonyms: ['商品销售额', '商品销售', '菜品销售额'],
  50. description: '预留列:仅商品部分的销售金额,数据源暂未接入' },
  51. { key: 'expUv', label: '曝光人数', type: 'int',
  52. synonyms: ['曝光', '曝光人数', '曝光量', '展现人数'],
  53. description: '看到店铺的去重人数' },
  54. { key: 'orderUserCnt', label: '下单人数', type: 'int',
  55. synonyms: ['下单人数', '下单用户', '购买人数', '下单用户数'],
  56. description: '当日下单的去重用户数' },
  57. { key: 'clkExpRate', label: '进店转化率', type: 'pct',
  58. synonyms: ['进店转化率', '进店率', '点击率', '入店转化率'],
  59. description: '进店人数 / 曝光人数;≥9% 健康,<6% 偏低' },
  60. { key: 'ordClkRate', label: '下单转化率', type: 'pct',
  61. synonyms: ['下单转化率', '下单率', '成交转化率', '访购率'],
  62. description: '下单人数 / 进店人数;≥2.5% 健康,<2% 偏低' },
  63. { key: 'perActualPay', label: '客单价(元)', type: 'money',
  64. synonyms: ['客单价', '均价', '笔单价'],
  65. description: '营业额 / 有效订单(元)' },
  66. { key: 'expenseAmt', label: '支出(元)', type: 'money',
  67. synonyms: ['支出', '费用', '成本', '平台扣费'],
  68. description: '支出(元),含平台佣金、推广费用等' },
  69. { key: 'actOrdCnt', label: '活动订单', type: 'int',
  70. synonyms: ['活动订单', '活动单量', '营销订单'],
  71. description: '参与营销活动的订单量' },
  72. { key: 'actSubsidyAmt', label: '活动补贴(元)', type: 'money',
  73. synonyms: ['活动补贴', '补贴金额', '商家补贴'],
  74. description: '活动中商家承担的补贴金额(元)' },
  75. { key: 'shopRoi', label: '推广ROI', type: 'num',
  76. synonyms: ['ROI', 'roi', '投产比', '推广roi'],
  77. description: '推广投入产出比;大盘口径常为 0' },
  78. { key: 'rebuyRate30d', label: '30日复购率', type: 'pct',
  79. synonyms: ['复购率', '30日复购', '老客回购率'],
  80. description: '近 30 天老客复购比例' },
  81. ];
  82. const COLUMN_MAP = Object.fromEntries(REPORT_COLUMNS.map((c) => [c.key, c]));
  83. // ---------- 原始字段 → 标准行 ----------
  84. const FIELD_MAP = {
  85. valid_order_cnt: 'validOrderCnt',
  86. gross_amt: 'grossAmt',
  87. income_amt: 'incomeAmt',
  88. expense_amt: 'expenseAmt',
  89. exp_uv: 'expUv',
  90. order_user_cnt: 'orderUserCnt',
  91. clk_exp_rate: 'clkExpRate',
  92. ord_clk_rate: 'ordClkRate',
  93. per_actual_pay: 'perActualPay',
  94. act_ord_cnt: 'actOrdCnt',
  95. act_shop_subsidy_amt: 'actSubsidyAmt',
  96. shop_roi: 'shopRoi',
  97. rebuy_rate_30d: 'rebuyRate30d',
  98. };
  99. // 全字段落库:原始返回一字不差保留,不做任何裁剪。
  100. // historyOverview 每行约 60+ 字段 = 基础 13 项(ds + 12 指标)+ 环比差值 _diff(12)
  101. // + 同行均值/排名 _mall_avg(_rank)(25) + 上期对比 _last_period(13)。
  102. // 后续渲染加工 / 比对分析直接从 raw 取用,无需重新取数。
  103. function captureRaw(raw) {
  104. return { ...(raw || {}) };
  105. }
  106. function normalizeRow(rawDaily, ctx) {
  107. const row = {
  108. date: String(rawDaily.ds || ''),
  109. scope: ctx.scope,
  110. shopId: ctx.shopId == null ? '' : String(ctx.shopId),
  111. shopName: ctx.shopName || '',
  112. chainId: ctx.chainId == null ? '' : String(ctx.chainId),
  113. chainName: ctx.chainName || '',
  114. bizHours: null,
  115. abnormalCloseHours: null,
  116. goodsSaleAmt: null,
  117. syncedAt: new Date().toISOString(),
  118. raw: captureRaw(rawDaily),
  119. };
  120. for (const [src, dst] of Object.entries(FIELD_MAP)) {
  121. const v = rawDaily[src];
  122. row[dst] = v == null || v === '' ? 0 : Number(v);
  123. }
  124. return row;
  125. }
  126. // 范围汇总行(接口返回 ds='all'):唯一携带同行均值/排名与整段环比的行。
  127. // 以 scope='summary'、date=区间末日 入库,与公司/连锁/门店行互不干扰。
  128. function normalizeSummaryRow(allRow, ctx) {
  129. const row = normalizeRow({ ...allRow, ds: ctx.date }, ctx);
  130. row.scope = 'summary';
  131. row.shopId = '';
  132. row.shopName = '';
  133. return row;
  134. }
  135. // ---------- 连接状态 ----------
  136. /** 按平台给出「以调试端口启动商家客户端」的可执行指引 */
  137. function cdpLaunchHint(port = DEFAULT_CDP_PORT) {
  138. if (process.platform === 'win32') {
  139. return `Windows 启动方法:① 任务栏右键完全退出淘宝闪购客户端(任务管理器确认进程已退出);`
  140. + `② 右键桌面快捷方式 → 属性 → 在「目标」末尾追加一个空格和 --remote-debugging-port=${port} → 确定后用该快捷方式启动。`
  141. + `注意:客户端每次重启都要用这个快捷方式,否则端口不会开启。`;
  142. }
  143. return `macOS 启动方法:① 完全退出客户端(⌘Q,或活动监视器确认进程退出);`
  144. + `② 终端执行:open -a "淘宝闪购商家版" --args --remote-debugging-port=${port}`
  145. + `(应用名以实际为准;也可直接运行 "/Applications/客户端.app/Contents/MacOS/可执行文件" --remote-debugging-port=${port})。`
  146. + `注意:客户端每次重启都要带此参数。`;
  147. }
  148. async function naposStatus() {
  149. const out = { port: DEFAULT_CDP_PORT, connected: false };
  150. try {
  151. const st = await kit.status(DEFAULT_CDP_PORT);
  152. out.connected = !!st.portOk;
  153. out.browser = st.browser || null;
  154. out.targets = (st.targets || []).length;
  155. out.contexts = (st.contexts || []).length;
  156. if (st.probeError) out.probeError = String(st.probeError);
  157. } catch (e) {
  158. out.error = e.message || String(e);
  159. }
  160. if (!out.connected) out.hint = cdpLaunchHint();
  161. // 自检:本机能否连通调试端口(给用户的浏览器直测地址)
  162. out.selfCheckUrl = `http://127.0.0.1:${DEFAULT_CDP_PORT}/json/version`;
  163. return out;
  164. }
  165. // ---------- 主体结构(多主体 tab 的来源) ----------
  166. let treeCache = { at: 0, tree: null };
  167. async function fetchTree({ refresh = false } = {}) {
  168. if (!refresh && treeCache.tree && Date.now() - treeCache.at < 5 * 60 * 1000) {
  169. return treeCache.tree;
  170. }
  171. const tree = await kit.shopTree({ port: DEFAULT_CDP_PORT });
  172. if (!tree.ok) {
  173. const err = new Error('读取门店组织树失败:' + (tree.code || tree.status || '未知错误'));
  174. err.code = 'NAPOS_TREE_FAIL';
  175. throw err;
  176. }
  177. const entity = store.upsertEntity({
  178. merchantId: (tree.merchant && tree.merchant.id) || 'default',
  179. merchantName: (tree.merchant && tree.merchant.name) || '默认主体',
  180. chains: tree.chains.map((c) => ({ chainId: String(c.chainId), chainName: c.chainName })),
  181. shops: tree.shops.map((s) => ({
  182. shopId: String(s.shopId), shopName: s.shopName,
  183. chainId: s.chainId ? String(s.chainId) : '', chainName: s.chainName || '',
  184. busyLevel: s.busyLevel || null,
  185. })),
  186. }).entity;
  187. // 缓存必须存补齐 entity 后的完整对象:缓存的消费方(runSync / tree 路由)都依赖 tree.entity
  188. const enriched = { ...tree, entity };
  189. treeCache = { at: Date.now(), tree: enriched };
  190. return enriched;
  191. }
  192. // ---------- 同步任务 ----------
  193. const syncState = {
  194. running: false,
  195. cancelRequested: false,
  196. startedAt: null,
  197. finishedAt: null,
  198. error: null,
  199. entity: null,
  200. from: null,
  201. to: null,
  202. planTotal: 0,
  203. done: 0,
  204. current: '',
  205. added: 0,
  206. updated: 0,
  207. failed: 0,
  208. steps: [],
  209. };
  210. function syncSnapshot() {
  211. const { running, cancelRequested, startedAt, finishedAt, error, entity, from, to,
  212. planTotal, done, current, added, updated, failed } = syncState;
  213. return { running, cancelRequested, startedAt, finishedAt, error,
  214. entity, from, to, planTotal, done, current, added, updated, failed };
  215. }
  216. function dayShift(ymd, delta) {
  217. const d = new Date(Number(ymd.slice(0, 4)), Number(ymd.slice(4, 6)) - 1, Number(ymd.slice(6, 8)));
  218. d.setDate(d.getDate() + delta);
  219. const z = (n) => String(n).padStart(2, '0');
  220. return `${d.getFullYear()}${z(d.getMonth() + 1)}${z(d.getDate())}`;
  221. }
  222. function yesterday() { return dayShift(kit.today(), -1); }
  223. /**
  224. * 同步一个区间到本地数据湖。
  225. * scope:
  226. * 'company' — 仅全公司聚合行
  227. * 'chain' — 各连锁聚合行
  228. * 'shop' — 逐店明细行(可选 chainId 限定 / shopIds 限定)
  229. * 'all' — 以上全部(默认)
  230. */
  231. async function runSync({ from, to, scope = 'all', chainId, shopIds, port } = {}) {
  232. if (syncState.running) {
  233. const err = new Error('已有同步任务在进行中');
  234. err.code = 'SYNC_BUSY';
  235. throw err;
  236. }
  237. // 先同步置位,避免忙碌检查与实际启动之间因 await 出现并发窗口
  238. Object.assign(syncState, {
  239. running: true, cancelRequested: false, startedAt: new Date().toISOString(), finishedAt: null,
  240. error: null, entity: null, from: null, to: null,
  241. planTotal: 0, done: 0, current: '准备中', added: 0, updated: 0, failed: 0, steps: [],
  242. });
  243. try {
  244. const tree = await fetchTree();
  245. const entity = tree.entity;
  246. const fromDay = kit.normDay(from || dayShift(yesterday(), -29));
  247. const toDay = kit.normDay(to || yesterday());
  248. if (!/^\d{8}$/.test(fromDay) || !/^\d{8}$/.test(toDay) || fromDay > toDay) {
  249. const err = new Error('日期区间不合法(需 YYYYMMDD,且开始 ≤ 结束)');
  250. err.code = 'SYNC_BAD_RANGE';
  251. throw err;
  252. }
  253. const jobs = [];
  254. if (scope === 'all' || scope === 'company') {
  255. jobs.push({ kind: 'company', label: '全公司', params: { chainId: '-1', shopListIn: '' }, fn: () => callHistory({ chainId: '-1', shopListIn: '' }, { scope: 'company', chainId: '-1', chainName: '' }) });
  256. }
  257. if (scope === 'all' || scope === 'chain') {
  258. for (const c of tree.chains) {
  259. jobs.push({
  260. kind: 'chain', label: `连锁·${c.chainName}`, params: { chainId: c.chainId, shopListIn: '' },
  261. fn: () => callHistory({ chainId: c.chainId, shopListIn: '' }, { scope: 'chain', chainId: c.chainId, chainName: c.chainName }),
  262. });
  263. }
  264. }
  265. if (scope === 'all' || scope === 'shop') {
  266. let shops = tree.shops;
  267. if (chainId) shops = shops.filter((s) => String(s.chainId) === String(chainId));
  268. if (Array.isArray(shopIds) && shopIds.length) {
  269. const wanted = new Set(shopIds.map(String));
  270. shops = shops.filter((s) => wanted.has(String(s.shopId)));
  271. }
  272. for (const s of shops) {
  273. jobs.push({
  274. kind: 'shop', label: `门店·${s.shopName}`, params: { chainId: '-1', shopListIn: String(s.shopId) },
  275. fn: () => callHistory(
  276. { chainId: '-1', shopListIn: String(s.shopId) },
  277. { scope: 'shop', shopId: s.shopId, shopName: s.shopName, chainId: s.chainId || '', chainName: s.chainName || '' },
  278. ),
  279. });
  280. }
  281. }
  282. Object.assign(syncState, {
  283. entity: { key: entity.key, name: entity.name }, from: fromDay, to: toDay,
  284. planTotal: jobs.length, current: '',
  285. });
  286. const usedPort = Number(port || DEFAULT_CDP_PORT);
  287. const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
  288. for (const job of jobs) {
  289. if (syncState.cancelRequested) break;
  290. syncState.current = job.label;
  291. try {
  292. const rows = await job.fn(usedPort);
  293. const res = store.upsertRows(entity.key, rows);
  294. syncState.added += res.added;
  295. syncState.updated += res.updated;
  296. // 诊断信息:请求参数 + 返回数据概况,便于在「同步记录」里远程排查取数异常
  297. const nonZero = rows.filter((r) => (Number(r.validOrderCnt) || 0) > 0 || (Number(r.grossAmt) || 0) > 0).length;
  298. const step = {
  299. label: job.label, ok: true, added: res.added, updated: res.updated,
  300. rows: rows.length, nonZero,
  301. ordersSum: Math.round(rows.reduce((s, r) => s + (Number(r.validOrderCnt) || 0), 0) * 100) / 100,
  302. grossSum: Math.round(rows.reduce((s, r) => s + (Number(r.grossAmt) || 0), 0) * 100) / 100,
  303. params: job.params || null,
  304. };
  305. if (rows.length && nonZero === 0) step.warn = '返回全零,疑似取数参数或数据权限异常';
  306. syncState.steps.push(step);
  307. } catch (e) {
  308. syncState.failed += 1;
  309. syncState.steps.push({ label: job.label, ok: false, error: e.message || String(e) });
  310. }
  311. syncState.done += 1;
  312. await sleep(180); // 温和节奏,避免连续轰接口
  313. }
  314. const run = {
  315. at: new Date().toISOString(), from: fromDay, to: toDay, scope,
  316. cancelled: syncState.cancelRequested,
  317. added: syncState.added, updated: syncState.updated, failed: syncState.failed,
  318. done: syncState.done, total: syncState.planTotal,
  319. steps: syncState.steps,
  320. };
  321. store.appendSyncLog(entity.key, run);
  322. syncState.error = null;
  323. } catch (e) {
  324. syncState.error = e.message || String(e);
  325. syncState.steps.push({ label: '准备', ok: false, error: syncState.error });
  326. } finally {
  327. syncState.running = false;
  328. syncState.current = '';
  329. syncState.finishedAt = new Date().toISOString();
  330. }
  331. return syncSnapshot();
  332. }
  333. /**
  334. * 调 historyOverview 取一个区间的逐日行并归一化。
  335. * scopeKey = { chainId, shopListIn };ctx 携带行的归属信息。
  336. * 返回:逐日行数组 + (若接口返回 ds='all' 汇总行)一条 scope='summary' 的范围汇总行。
  337. */
  338. async function callHistory(scopeKey, ctx, port = DEFAULT_CDP_PORT) {
  339. const o = {
  340. port,
  341. chainId: scopeKey.chainId,
  342. shopListIn: scopeKey.shopListIn || '',
  343. from: syncState.from,
  344. to: syncState.to,
  345. dateType: 'self_define',
  346. };
  347. const r = await kit.statsHistory(o);
  348. if (r.risk) throw new Error('触发客户端风控(请稍后在客户端完成验证后重试)');
  349. if (r.authFail) throw new Error('登录态失效(ksid 过期),请在商家客户端重新登录');
  350. if (r.code != null && r.code !== 0 && String(r.code) !== '0') {
  351. throw new Error('接口返回异常 code=' + r.code + (r.msg ? ' ' + r.msg : ''));
  352. }
  353. const daily = (r.daily || []).map((d) => normalizeRow(d, ctx));
  354. if (r.all) {
  355. daily.push(normalizeSummaryRow(r.all, { ...ctx, date: syncState.to }));
  356. }
  357. return daily;
  358. }
  359. function requestSyncCancel() {
  360. if (syncState.running) syncState.cancelRequested = true;
  361. return syncSnapshot();
  362. }
  363. // ---------- 查询 / 汇总 ----------
  364. const SUM_FIELDS = ['validOrderCnt', 'incomeAmt', 'grossAmt', 'expenseAmt', 'expUv', 'orderUserCnt', 'actOrdCnt', 'actSubsidyAmt'];
  365. const RATE_FIELDS = ['clkExpRate', 'ordClkRate'];
  366. function summarizeRows(rows) {
  367. const s = { days: new Set(), shops: new Set() };
  368. for (const f of SUM_FIELDS) s[f] = 0;
  369. let rateWeight = { clkExpRate: 0, ordClkRate: 0 };
  370. let rateBase = { clkExpRate: 0, ordClkRate: 0 };
  371. for (const r of rows) {
  372. s.days.add(r.date);
  373. if (r.shopId) s.shops.add(r.shopId);
  374. for (const f of SUM_FIELDS) s[f] += Number(r[f]) || 0;
  375. if (Number(r.expUv) > 0) { rateWeight.clkExpRate += (Number(r.clkExpRate) || 0) * Number(r.expUv); rateBase.clkExpRate += Number(r.expUv); }
  376. if (Number(r.orderUserCnt) > 0) { rateWeight.ordClkRate += (Number(r.ordClkRate) || 0) * Number(r.orderUserCnt); rateBase.ordClkRate += Number(r.orderUserCnt); }
  377. }
  378. s.perActualPay = s.validOrderCnt > 0 ? +(s.grossAmt / s.validOrderCnt).toFixed(2) : 0;
  379. for (const f of SUM_FIELDS) s[f] = Math.round(s[f] * 100) / 100;
  380. for (const f of RATE_FIELDS) s[f] = rateBase[f] > 0 ? +(rateWeight[f] / rateBase[f]).toFixed(4) : 0;
  381. s.dayCount = s.days.size;
  382. s.shopCount = s.shops.size;
  383. delete s.days;
  384. delete s.shops;
  385. return s;
  386. }
  387. function queryReport({ entity, from, to, shopId, shops, scope, q } = {}) {
  388. const key = store.sanitizeKey(entity);
  389. const meta = store.getEntity(key);
  390. let rows = store.queryRows(key, { from, to, scope });
  391. if (shopId) rows = rows.filter((r) => String(r.shopId) === String(shopId));
  392. if (Array.isArray(shops) && shops.length) {
  393. const wanted = new Set(shops.map(String));
  394. rows = rows.filter((r) => wanted.has(String(r.shopId)));
  395. }
  396. if (q) {
  397. const needle = String(q).toLowerCase();
  398. rows = rows.filter((r) => String(r.shopName || '').toLowerCase().includes(needle));
  399. }
  400. const account = meta ? meta.name : key;
  401. rows = rows.map((r) => ({ ...r, account }));
  402. return {
  403. entity: meta ? { key: meta.key, name: meta.name } : { key, name: key },
  404. from: from || null, to: to || null,
  405. columns: REPORT_COLUMNS,
  406. summary: summarizeRows(rows),
  407. rows,
  408. };
  409. }
  410. /** BI 聚合视图:group = 'shop'(按门店)| 'date'(按日期) */
  411. function aggregateReport({ entity, from, to, group = 'shop', shops } = {}) {
  412. const key = store.sanitizeKey(entity);
  413. const meta = store.getEntity(key);
  414. let rows = store.queryRows(key, { from, to, scope: 'shop' });
  415. if (Array.isArray(shops) && shops.length) {
  416. const wanted = new Set(shops.map(String));
  417. rows = rows.filter((r) => wanted.has(String(r.shopId)));
  418. }
  419. const buckets = new Map();
  420. for (const r of rows) {
  421. const k = group === 'date' ? r.date : String(r.shopId || '');
  422. if (!buckets.has(k)) buckets.set(k, []);
  423. buckets.get(k).push(r);
  424. }
  425. const out = [];
  426. for (const [k, list] of buckets) {
  427. const first = list[0] || {};
  428. const base = group === 'date'
  429. ? { date: k, shopName: `${list.length} 家门店`, shopId: '', scope: 'agg-date' }
  430. : { date: '', shopName: first.shopName || k, shopId: k, scope: 'agg-shop' };
  431. const s = summarizeRows(list);
  432. out.push({ ...base, ...s });
  433. }
  434. out.sort((a, b) => (group === 'date' ? (a.date < b.date ? -1 : 1) : (b.grossAmt || 0) - (a.grossAmt || 0)));
  435. const account = meta ? meta.name : key;
  436. return { columns: REPORT_COLUMNS, rows: out.map((r) => ({ ...r, account })), summary: summarizeRows(rows) };
  437. }
  438. // ---------- CSV 导出 ----------
  439. function csvEscape(v) {
  440. if (v == null) return '';
  441. const s = typeof v === 'object' ? JSON.stringify(v) : String(v);
  442. return /[",\n\r]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
  443. }
  444. function rowsToCsv(columns, rows) {
  445. const head = columns.map((c) => c.label);
  446. const lines = [head.join(',')];
  447. for (const r of rows) {
  448. const cells = columns.map((c) => {
  449. let v = r[c.key];
  450. if (v == null) v = '';
  451. if (c.type === 'pct') v = v === '' ? '' : (Number(v) * 100).toFixed(2) + '%';
  452. if (c.type === 'date' && /^\d{8}$/.test(String(v))) {
  453. const s = String(v);
  454. v = `${s.slice(0, 4)}-${s.slice(4, 6)}-${s.slice(6, 8)}`;
  455. }
  456. return csvEscape(v);
  457. });
  458. lines.push(cells.join(','));
  459. }
  460. return '\ufeff' + lines.join('\r\n');
  461. }
  462. module.exports = {
  463. DEFAULT_CDP_PORT, REPORT_COLUMNS,
  464. naposStatus, fetchTree,
  465. runSync, syncSnapshot, requestSyncCancel,
  466. queryReport, aggregateReport, summarizeRows,
  467. rowsToCsv,
  468. store,
  469. };