napos-service.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  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 {
  140. title: 'Windows 带参启动客户端',
  141. steps: [
  142. { text: '任务栏右键完全退出客户端,任务管理器确认进程已退出' },
  143. { text: '右键桌面快捷方式 → 属性 →「目标」末尾追加一个空格和', code: `--remote-debugging-port=${port}` },
  144. { text: '确定后,用该快捷方式启动客户端' },
  145. ],
  146. note: '客户端每次重启都要用这个快捷方式,否则端口不会开启。',
  147. };
  148. }
  149. return {
  150. title: 'macOS 带参启动客户端',
  151. steps: [
  152. { text: '⌘Q 完全退出客户端(活动监视器确认进程已退出)' },
  153. { text: '终端执行:', code: `open -a "淘宝闪购商家版" --args --remote-debugging-port=${port}` },
  154. { text: '应用名以实际为准;也可直接运行', code: `"<客户端.app>/Contents/MacOS/<可执行文件>" --remote-debugging-port=${port}` },
  155. ],
  156. note: '客户端每次重启都要带此参数,否则端口不会开启。',
  157. };
  158. }
  159. async function naposStatus() {
  160. const out = { port: DEFAULT_CDP_PORT, connected: false };
  161. try {
  162. const st = await kit.status(DEFAULT_CDP_PORT);
  163. out.connected = !!st.portOk;
  164. out.browser = st.browser || null;
  165. out.targets = (st.targets || []).length;
  166. out.contexts = (st.contexts || []).length;
  167. if (st.probeError) out.probeError = String(st.probeError);
  168. } catch (e) {
  169. out.error = e.message || String(e);
  170. }
  171. if (!out.connected) out.hint = cdpLaunchHint();
  172. // 自检:本机能否连通调试端口(给用户的浏览器直测地址)
  173. out.selfCheckUrl = `http://127.0.0.1:${DEFAULT_CDP_PORT}/json/version`;
  174. return out;
  175. }
  176. // ---------- 取数诊断(网页一键版 · 全程只读) ----------
  177. // 给「装了商家客户端」的电脑用:网页连点侧边栏版本号出现入口,一键跑门店级取数对照实验,
  178. // 报告在页面直接看 / 复制回开发侧。覆盖三类定位:
  179. // · 门店维度参数(现行 chainId=-1+shopListIn 是否有数,与 B/D 变体对照)
  180. // · 指标字段存在性(下单人数门店级是否缺失、营业时长/异常关店时长是否有源)
  181. // · 暂停营业门店清单(busyLevel 当前状态快照)
  182. let diagnoseRunning = false;
  183. const DIAGNOSE_CORE_METRICS = ['valid_order_cnt', 'gross_amt', 'income_amt', 'expense_amt', 'exp_uv',
  184. 'order_user_cnt', 'clk_exp_rate', 'ord_clk_rate', 'per_actual_pay', 'act_ord_cnt',
  185. 'act_shop_subsidy_amt', 'shop_roi', 'rebuy_rate_30d'];
  186. function diagnoseMetricProbe(row) {
  187. if (!row) return null;
  188. const keys = Object.keys(row);
  189. const coreMetrics = {};
  190. for (const k of DIAGNOSE_CORE_METRICS) {
  191. coreMetrics[k] = Object.prototype.hasOwnProperty.call(row, k) ? row[k] : '(字段不存在)';
  192. }
  193. return {
  194. fieldCount: keys.length,
  195. coreMetrics,
  196. relatedExtraKeys: keys
  197. .filter((k) => /user|buyer|hour|close|open_time|biz|pause|rest/i.test(k))
  198. .map((k) => `${k}=${JSON.stringify(row[k])}`),
  199. };
  200. }
  201. async function runNaposDiagnose({ date, shopId } = {}) {
  202. if (diagnoseRunning) {
  203. const e = new Error('已有诊断在进行中,请稍候');
  204. e.code = 'DIAGNOSE_BUSY'; e.status = 429;
  205. throw e;
  206. }
  207. diagnoseRunning = true;
  208. const t0 = Date.now();
  209. const report = { generatedAt: new Date().toISOString(), port: DEFAULT_CDP_PORT };
  210. try {
  211. const st = await kit.status(DEFAULT_CDP_PORT);
  212. report.status = { portOk: !!st.portOk, browser: st.browser || null, targets: (st.targets || []).length, targetUrls: (st.targets || []).slice(0, 6) };
  213. if (!st.portOk) {
  214. report.conclusion = '客户端不在线:请完全退出商家客户端,用「启动.bat」附带调试端口的方式重启并登录后再诊断。';
  215. return report;
  216. }
  217. // 组织树:失败自动重试一次(热切换账号后内部页面常需几秒恢复),并把原始返回带回报告
  218. let tree = await kit.shopTree({ port: DEFAULT_CDP_PORT });
  219. if (!tree.ok || !tree.merchant) {
  220. await new Promise((res) => setTimeout(res, 1500));
  221. tree = await kit.shopTree({ port: DEFAULT_CDP_PORT });
  222. }
  223. report.treeDiag = {
  224. ok: !!tree.ok && !!tree.merchant,
  225. code: tree.code ?? null,
  226. msg: tree.msg || null,
  227. authFail: !!tree.authFail,
  228. risk: !!tree.risk,
  229. rawHead: (() => { try { return JSON.stringify(tree.raw).slice(0, 600); } catch { return null; } })(),
  230. };
  231. if (!tree.ok || !tree.merchant) {
  232. report.conclusion = '客户端端口在线但读不到门店组织树:多半是刚切换/新登录账号后内部页面状态未刷新。'
  233. + '请在客户端里打开一次「门店管理」页面,仍不行就完全退出客户端、以调试端口重启并重新登录,再重跑本诊断。'
  234. + (report.treeDiag.code || report.treeDiag.msg ? `(服务端返回:${[report.treeDiag.code, report.treeDiag.msg].filter(Boolean).join(' ')})` : '');
  235. return report;
  236. }
  237. report.merchant = tree.merchant || null;
  238. report.chains = (tree.chains || []).map((c) => ({ chainId: String(c.chainId), chainName: c.chainName }));
  239. const shops = (tree.shops || []).map((s) => ({
  240. shopId: String(s.shopId), shopName: s.shopName, chainId: String(s.chainId || ''), busyLevel: s.busyLevel || null,
  241. }));
  242. report.shopCount = shops.length;
  243. report.busyLevelSummary = shops.reduce((a, s) => { const b = s.busyLevel || '(未知)'; a[b] = (a[b] || 0) + 1; return a; }, {});
  244. report.pausedShops = shops.filter((s) => s.busyLevel === 'SUSPEND_BUSINESS' || s.busyLevel === 'INVALID');
  245. if (!report.chains.length) {
  246. report.conclusion = '组织树没有连锁信息,无法构造连锁对照实验。';
  247. return report;
  248. }
  249. const chainId = report.chains[0].chainId;
  250. const z = (n) => String(n).padStart(2, '0');
  251. const ymdShift = (ymd, delta) => {
  252. const d = new Date(Number(ymd.slice(0, 4)), Number(ymd.slice(4, 6)) - 1, Number(ymd.slice(6, 8)));
  253. d.setDate(d.getDate() + delta);
  254. return `${d.getFullYear()}${z(d.getMonth() + 1)}${z(d.getDate())}`;
  255. };
  256. const now = new Date();
  257. const todayYmd = `${now.getFullYear()}${z(now.getMonth() + 1)}${z(now.getDate())}`;
  258. const testDate = /^\d{8}$/.test(date || '') ? date : ymdShift(todayYmd, -1);
  259. report.testDate = testDate;
  260. const picked = [];
  261. if (/^\d+$/.test(shopId || '')) {
  262. const one = shops.find((s) => s.shopId === shopId);
  263. if (one) picked.push(one);
  264. }
  265. for (const s of shops) {
  266. if (picked.length >= 2) break;
  267. if (!picked.includes(s)) picked.push(s);
  268. }
  269. report.testShops = picked.map((s) => ({ shopId: s.shopId, shopName: s.shopName, busyLevel: s.busyLevel || null }));
  270. const sumOf = (rows, f) => Math.round((rows || []).reduce((s2, r) => s2 + (Number(r[f]) || 0), 0) * 100) / 100;
  271. const runCase = async (tag, params) => {
  272. const out = { tag, chainId: params.chainId, shopListIn: params.shopListIn, rows: 0, ordersSum: 0, grossSum: 0, expSum: 0, orderUserSum: 0 };
  273. try {
  274. const r = await kit.statsHistory({ port: DEFAULT_CDP_PORT, from: params.from, to: params.to, dateType: 'self_define',
  275. chainId: params.chainId, shopListIn: params.shopListIn });
  276. const daily = r.daily || [];
  277. out.rows = daily.length;
  278. out.ordersSum = sumOf(daily, 'valid_order_cnt');
  279. out.grossSum = sumOf(daily, 'gross_amt');
  280. out.expSum = sumOf(daily, 'exp_uv');
  281. out.orderUserSum = sumOf(daily, 'order_user_cnt');
  282. out.firstRow = daily[0] ? (({ raw, ...rest }) => rest)(daily[0]) : null;
  283. out.metricProbe = diagnoseMetricProbe(daily[0]);
  284. out.ok = !!r.ok;
  285. if (r.shapeWarning) out.shapeWarning = true;
  286. } catch (e) {
  287. out.error = e.message || String(e);
  288. }
  289. return out;
  290. };
  291. report.chainControl = await runCase('连锁对照·不带门店', { from: testDate, to: testDate, chainId, shopListIn: '' });
  292. report.cases = [];
  293. for (const s of picked) {
  294. for (const c of [
  295. { tag: 'A 现行 chainId=-1+shopListIn', chainId: '-1' },
  296. { tag: `B 变体 chainId=${chainId}+shopListIn`, chainId },
  297. { tag: 'D 变体 chainId=(空)+shopListIn', chainId: '' },
  298. ]) {
  299. const r = await runCase(c.tag, { from: testDate, to: testDate, chainId: c.chainId, shopListIn: s.shopId });
  300. r.shopId = s.shopId;
  301. r.shopName = s.shopName;
  302. report.cases.push(r);
  303. await new Promise((res) => setTimeout(res, 600));
  304. }
  305. }
  306. const chainKeys = new Set(Object.keys(report.chainControl.firstRow || {}));
  307. for (const c of report.cases) {
  308. if (!c.firstRow) continue;
  309. c.missingVsChain = [...chainKeys].filter((k) => !(k in c.firstRow));
  310. }
  311. // 结论:把开发侧关心的判定直接写成人话
  312. const lines = [];
  313. const cc = report.chainControl;
  314. if (!cc || !cc.rows || !cc.ordersSum) {
  315. lines.push('连锁对照查询也为零:该日期可能无经营数据,换一个链级行有数的日期再诊断一次。');
  316. } else {
  317. lines.push(`连锁对照正常(${cc.rows} 行 / 有效订单 ${cc.ordersSum} / 营业额 ${cc.grossSum})。`);
  318. const hit = report.cases.filter((c) => c.rows > 0 && (c.ordersSum > 0 || c.grossSum > 0));
  319. if (hit.length) {
  320. lines.push(`门店维度有数据的参数形式:${[...new Set(hit.map((c) => c.tag.split(' ')[0]))].join('、')}——把本报告发回开发侧即可修正取数参数。`);
  321. } else {
  322. lines.push('所有参数形式下门店维度均为零:需核对数据权限/门店经营状态(详见各变体原始返回首行)。');
  323. }
  324. const probeSrc = hit[0] || report.cases.find((c) => c.metricProbe);
  325. const probe = probeSrc && probeSrc.metricProbe;
  326. if (probe) {
  327. const ouc = probe.coreMetrics.order_user_cnt;
  328. lines.push(ouc === '(字段不存在)'
  329. ? '门店级返回中「下单人数(order_user_cnt)」字段不存在——上游门店粒度不提供该指标,报表该列将恒为 0。'
  330. : `门店级「下单人数(order_user_cnt)」字段存在,样本值 ${JSON.stringify(ouc)}。`);
  331. }
  332. const hourKeys = [cc, ...report.cases]
  333. .flatMap((c) => (c.metricProbe && c.metricProbe.relatedExtraKeys) || []);
  334. lines.push(hourKeys.length
  335. ? `原始返回中与时长/关店相关的键:${[...new Set(hourKeys)].slice(0, 8).join(';')}`
  336. : '原始返回中没有任何营业时长/异常关店相关字段——这两列为预留列,上游接口暂不提供。');
  337. }
  338. report.conclusionLines = lines;
  339. report.conclusion = lines.join(' ');
  340. return report;
  341. } finally {
  342. report.durationMs = Date.now() - t0;
  343. diagnoseRunning = false;
  344. }
  345. }
  346. // ---------- 主体结构(多主体 tab 的来源) ----------
  347. let treeCache = { at: 0, tree: null };
  348. async function fetchTree({ refresh = false } = {}) {
  349. if (!refresh && treeCache.tree && Date.now() - treeCache.at < 5 * 60 * 1000) {
  350. return treeCache.tree;
  351. }
  352. const tree = await kit.shopTree({ port: DEFAULT_CDP_PORT });
  353. if (!tree.ok || !tree.merchant) {
  354. // 新账号/热切换账号后内部页面登录态常失效:把服务端真实原因带出来,别只说「未知错误」
  355. const reason = [tree.code, tree.msg, tree.authFail ? '登录态失效' : null]
  356. .filter(Boolean).join(' ') || `HTTP ${tree.status || '?'}`;
  357. const err = new Error(`读取门店组织树失败:${reason}。若刚切换过账号,请完全退出客户端后以调试端口重启并重新登录,再重试`);
  358. err.code = 'NAPOS_TREE_FAIL';
  359. throw err;
  360. }
  361. const entity = store.upsertEntity({
  362. merchantId: (tree.merchant && tree.merchant.id) || 'default',
  363. merchantName: (tree.merchant && tree.merchant.name) || '默认主体',
  364. chains: tree.chains.map((c) => ({ chainId: String(c.chainId), chainName: c.chainName })),
  365. shops: tree.shops.map((s) => ({
  366. shopId: String(s.shopId), shopName: s.shopName,
  367. chainId: s.chainId ? String(s.chainId) : '', chainName: s.chainName || '',
  368. busyLevel: s.busyLevel || null,
  369. })),
  370. }).entity;
  371. // 缓存必须存补齐 entity 后的完整对象:缓存的消费方(runSync / tree 路由)都依赖 tree.entity
  372. const enriched = { ...tree, entity };
  373. treeCache = { at: Date.now(), tree: enriched };
  374. return enriched;
  375. }
  376. // ---------- 同步任务 ----------
  377. const syncState = {
  378. running: false,
  379. cancelRequested: false,
  380. startedAt: null,
  381. finishedAt: null,
  382. error: null,
  383. entity: null,
  384. from: null,
  385. to: null,
  386. planTotal: 0,
  387. done: 0,
  388. current: '',
  389. added: 0,
  390. updated: 0,
  391. failed: 0,
  392. steps: [],
  393. };
  394. function syncSnapshot() {
  395. const { running, cancelRequested, startedAt, finishedAt, error, entity, from, to,
  396. planTotal, done, current, added, updated, failed } = syncState;
  397. return { running, cancelRequested, startedAt, finishedAt, error,
  398. entity, from, to, planTotal, done, current, added, updated, failed };
  399. }
  400. function dayShift(ymd, delta) {
  401. const d = new Date(Number(ymd.slice(0, 4)), Number(ymd.slice(4, 6)) - 1, Number(ymd.slice(6, 8)));
  402. d.setDate(d.getDate() + delta);
  403. const z = (n) => String(n).padStart(2, '0');
  404. return `${d.getFullYear()}${z(d.getMonth() + 1)}${z(d.getDate())}`;
  405. }
  406. function yesterday() { return dayShift(kit.today(), -1); }
  407. /**
  408. * 同步一个区间到本地数据湖。
  409. * scope:
  410. * 'company' — 仅全公司聚合行
  411. * 'chain' — 各连锁聚合行
  412. * 'shop' — 逐店明细行(可选 chainId 限定 / shopIds 限定)
  413. * 'all' — 以上全部(默认)
  414. */
  415. async function runSync({ from, to, scope = 'all', chainId, shopIds, port } = {}) {
  416. if (syncState.running) {
  417. const err = new Error('已有同步任务在进行中');
  418. err.code = 'SYNC_BUSY';
  419. throw err;
  420. }
  421. // 先同步置位,避免忙碌检查与实际启动之间因 await 出现并发窗口
  422. Object.assign(syncState, {
  423. running: true, cancelRequested: false, startedAt: new Date().toISOString(), finishedAt: null,
  424. error: null, entity: null, from: null, to: null,
  425. planTotal: 0, done: 0, current: '准备中', added: 0, updated: 0, failed: 0, steps: [],
  426. });
  427. try {
  428. const tree = await fetchTree();
  429. const entity = tree.entity;
  430. const fromDay = kit.normDay(from || dayShift(yesterday(), -29));
  431. const toDay = kit.normDay(to || yesterday());
  432. if (!/^\d{8}$/.test(fromDay) || !/^\d{8}$/.test(toDay) || fromDay > toDay) {
  433. const err = new Error('日期区间不合法(需 YYYYMMDD,且开始 ≤ 结束)');
  434. err.code = 'SYNC_BAD_RANGE';
  435. throw err;
  436. }
  437. const jobs = [];
  438. if (scope === 'all' || scope === 'company') {
  439. jobs.push({ kind: 'company', label: '全公司', params: { chainId: '-1', shopListIn: '' }, fn: () => callHistory({ chainId: '-1', shopListIn: '' }, { scope: 'company', chainId: '-1', chainName: '' }) });
  440. }
  441. if (scope === 'all' || scope === 'chain') {
  442. for (const c of tree.chains) {
  443. jobs.push({
  444. kind: 'chain', label: `连锁·${c.chainName}`, params: { chainId: c.chainId, shopListIn: '' },
  445. fn: () => callHistory({ chainId: c.chainId, shopListIn: '' }, { scope: 'chain', chainId: c.chainId, chainName: c.chainName }),
  446. });
  447. }
  448. }
  449. if (scope === 'all' || scope === 'shop') {
  450. let shops = tree.shops;
  451. if (chainId) shops = shops.filter((s) => String(s.chainId) === String(chainId));
  452. if (Array.isArray(shopIds) && shopIds.length) {
  453. const wanted = new Set(shopIds.map(String));
  454. shops = shops.filter((s) => wanted.has(String(s.shopId)));
  455. }
  456. for (const s of shops) {
  457. jobs.push({
  458. kind: 'shop', label: `门店·${s.shopName}`, params: { chainId: '-1', shopListIn: String(s.shopId) },
  459. fn: () => callHistory(
  460. { chainId: '-1', shopListIn: String(s.shopId) },
  461. { scope: 'shop', shopId: s.shopId, shopName: s.shopName, chainId: s.chainId || '', chainName: s.chainName || '' },
  462. ),
  463. });
  464. }
  465. }
  466. Object.assign(syncState, {
  467. entity: { key: entity.key, name: entity.name }, from: fromDay, to: toDay,
  468. planTotal: jobs.length, current: '',
  469. });
  470. const usedPort = Number(port || DEFAULT_CDP_PORT);
  471. const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
  472. for (const job of jobs) {
  473. if (syncState.cancelRequested) break;
  474. syncState.current = job.label;
  475. try {
  476. const rows = await job.fn(usedPort);
  477. const res = store.upsertRows(entity.key, rows);
  478. syncState.added += res.added;
  479. syncState.updated += res.updated;
  480. // 诊断信息:请求参数 + 返回数据概况,便于在「同步记录」里远程排查取数异常
  481. const nonZero = rows.filter((r) => (Number(r.validOrderCnt) || 0) > 0 || (Number(r.grossAmt) || 0) > 0).length;
  482. const step = {
  483. label: job.label, ok: true, added: res.added, updated: res.updated,
  484. rows: rows.length, nonZero,
  485. ordersSum: Math.round(rows.reduce((s, r) => s + (Number(r.validOrderCnt) || 0), 0) * 100) / 100,
  486. grossSum: Math.round(rows.reduce((s, r) => s + (Number(r.grossAmt) || 0), 0) * 100) / 100,
  487. params: job.params || null,
  488. };
  489. if (rows.length && nonZero === 0) step.warn = '返回全零,疑似取数参数或数据权限异常';
  490. syncState.steps.push(step);
  491. } catch (e) {
  492. syncState.failed += 1;
  493. syncState.steps.push({ label: job.label, ok: false, error: e.message || String(e) });
  494. }
  495. syncState.done += 1;
  496. await sleep(180); // 温和节奏,避免连续轰接口
  497. }
  498. const run = {
  499. at: new Date().toISOString(), from: fromDay, to: toDay, scope,
  500. cancelled: syncState.cancelRequested,
  501. added: syncState.added, updated: syncState.updated, failed: syncState.failed,
  502. done: syncState.done, total: syncState.planTotal,
  503. steps: syncState.steps,
  504. };
  505. store.appendSyncLog(entity.key, run);
  506. syncState.error = null;
  507. } catch (e) {
  508. syncState.error = e.message || String(e);
  509. syncState.steps.push({ label: '准备', ok: false, error: syncState.error });
  510. } finally {
  511. syncState.running = false;
  512. syncState.current = '';
  513. syncState.finishedAt = new Date().toISOString();
  514. }
  515. return syncSnapshot();
  516. }
  517. /**
  518. * 调 historyOverview 取一个区间的逐日行并归一化。
  519. * scopeKey = { chainId, shopListIn };ctx 携带行的归属信息。
  520. * 返回:逐日行数组 + (若接口返回 ds='all' 汇总行)一条 scope='summary' 的范围汇总行。
  521. */
  522. async function callHistory(scopeKey, ctx, port = DEFAULT_CDP_PORT) {
  523. const o = {
  524. port,
  525. chainId: scopeKey.chainId,
  526. shopListIn: scopeKey.shopListIn || '',
  527. from: syncState.from,
  528. to: syncState.to,
  529. dateType: 'self_define',
  530. };
  531. const r = await kit.statsHistory(o);
  532. if (r.risk) throw new Error('触发客户端风控(请稍后在客户端完成验证后重试)');
  533. if (r.authFail) throw new Error('登录态失效(ksid 过期),请在商家客户端重新登录');
  534. // HTTP 层失败:pageFetch 拿不到业务数据,不检查会把失败伪装成 0 行落库
  535. if (r.ok === false) throw new Error('接口请求失败:' + (r.error || `HTTP ${r.status || '?'}`));
  536. // 形态守卫:有原始行但无任何 ds 形态行 = 接口/页面结构变化,拒绝静默落空
  537. if (r.shapeWarning) throw new Error(`接口返回形态异常:${(r.rows || []).length} 行均无 ds 字段(接口/页面结构可能已变化),已拒绝把空数据落库`);
  538. if (r.code != null && r.code !== 0 && String(r.code) !== '0') {
  539. throw new Error('接口返回异常 code=' + r.code + (r.msg ? ' ' + r.msg : ''));
  540. }
  541. const daily = (r.daily || []).map((d) => normalizeRow(d, ctx));
  542. if (r.all) {
  543. daily.push(normalizeSummaryRow(r.all, { ...ctx, date: syncState.to }));
  544. }
  545. return daily;
  546. }
  547. function requestSyncCancel() {
  548. if (syncState.running) syncState.cancelRequested = true;
  549. return syncSnapshot();
  550. }
  551. // ---------- 查询 / 汇总 ----------
  552. const SUM_FIELDS = ['validOrderCnt', 'incomeAmt', 'grossAmt', 'expenseAmt', 'expUv', 'orderUserCnt', 'actOrdCnt', 'actSubsidyAmt'];
  553. const RATE_FIELDS = ['clkExpRate', 'ordClkRate'];
  554. function summarizeRows(rows) {
  555. const s = { days: new Set(), shops: new Set() };
  556. for (const f of SUM_FIELDS) s[f] = 0;
  557. let rateWeight = { clkExpRate: 0, ordClkRate: 0 };
  558. let rateBase = { clkExpRate: 0, ordClkRate: 0 };
  559. for (const r of rows) {
  560. s.days.add(r.date);
  561. if (r.shopId) s.shops.add(r.shopId);
  562. for (const f of SUM_FIELDS) s[f] += Number(r[f]) || 0;
  563. if (Number(r.expUv) > 0) { rateWeight.clkExpRate += (Number(r.clkExpRate) || 0) * Number(r.expUv); rateBase.clkExpRate += Number(r.expUv); }
  564. if (Number(r.orderUserCnt) > 0) { rateWeight.ordClkRate += (Number(r.ordClkRate) || 0) * Number(r.orderUserCnt); rateBase.ordClkRate += Number(r.orderUserCnt); }
  565. }
  566. s.perActualPay = s.validOrderCnt > 0 ? +(s.grossAmt / s.validOrderCnt).toFixed(2) : 0;
  567. for (const f of SUM_FIELDS) s[f] = Math.round(s[f] * 100) / 100;
  568. for (const f of RATE_FIELDS) s[f] = rateBase[f] > 0 ? +(rateWeight[f] / rateBase[f]).toFixed(4) : 0;
  569. s.dayCount = s.days.size;
  570. s.shopCount = s.shops.size;
  571. delete s.days;
  572. delete s.shops;
  573. return s;
  574. }
  575. function queryReport({ entity, from, to, shopId, shops, scope, q } = {}) {
  576. const key = store.sanitizeKey(entity);
  577. const meta = store.getEntity(key);
  578. let rows = store.queryRows(key, { from, to, scope });
  579. if (shopId) rows = rows.filter((r) => String(r.shopId) === String(shopId));
  580. if (Array.isArray(shops) && shops.length) {
  581. const wanted = new Set(shops.map(String));
  582. rows = rows.filter((r) => wanted.has(String(r.shopId)));
  583. }
  584. if (q) {
  585. const needle = String(q).toLowerCase();
  586. rows = rows.filter((r) => String(r.shopName || '').toLowerCase().includes(needle));
  587. }
  588. const account = meta ? meta.name : key;
  589. rows = rows.map((r) => ({ ...r, account }));
  590. return {
  591. entity: meta ? { key: meta.key, name: meta.name } : { key, name: key },
  592. from: from || null, to: to || null,
  593. columns: REPORT_COLUMNS,
  594. summary: summarizeRows(rows),
  595. rows,
  596. };
  597. }
  598. /** BI 聚合视图:group = 'shop'(按门店)| 'date'(按日期) */
  599. function aggregateReport({ entity, from, to, group = 'shop', shops } = {}) {
  600. const key = store.sanitizeKey(entity);
  601. const meta = store.getEntity(key);
  602. let rows = store.queryRows(key, { from, to, scope: 'shop' });
  603. if (Array.isArray(shops) && shops.length) {
  604. const wanted = new Set(shops.map(String));
  605. rows = rows.filter((r) => wanted.has(String(r.shopId)));
  606. }
  607. const buckets = new Map();
  608. for (const r of rows) {
  609. const k = group === 'date' ? r.date : String(r.shopId || '');
  610. if (!buckets.has(k)) buckets.set(k, []);
  611. buckets.get(k).push(r);
  612. }
  613. const out = [];
  614. for (const [k, list] of buckets) {
  615. const first = list[0] || {};
  616. const base = group === 'date'
  617. ? { date: k, shopName: `${list.length} 家门店`, shopId: '', scope: 'agg-date' }
  618. : { date: '', shopName: first.shopName || k, shopId: k, scope: 'agg-shop' };
  619. const s = summarizeRows(list);
  620. out.push({ ...base, ...s });
  621. }
  622. out.sort((a, b) => (group === 'date' ? (a.date < b.date ? -1 : 1) : (b.grossAmt || 0) - (a.grossAmt || 0)));
  623. const account = meta ? meta.name : key;
  624. return { columns: REPORT_COLUMNS, rows: out.map((r) => ({ ...r, account })), summary: summarizeRows(rows) };
  625. }
  626. // ---------- CSV 导出 ----------
  627. function csvEscape(v) {
  628. if (v == null) return '';
  629. let s = typeof v === 'object' ? JSON.stringify(v) : String(v);
  630. // 防 Excel 公式注入:非数字值以 = + - @ 开头时前置单引号(负数是数字,不受影响)
  631. if (/^[=+@\t\r]/.test(s) || (/^-/.test(s) && !Number.isFinite(Number(s)))) {
  632. s = "'" + s;
  633. }
  634. return /[",\n\r]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
  635. }
  636. function rowsToCsv(columns, rows) {
  637. const head = columns.map((c) => c.label);
  638. const lines = [head.join(',')];
  639. for (const r of rows) {
  640. const cells = columns.map((c) => {
  641. let v = r[c.key];
  642. if (v == null) v = '';
  643. if (c.type === 'pct') v = v === '' ? '' : (Number(v) * 100).toFixed(2) + '%';
  644. if (c.type === 'date' && /^\d{8}$/.test(String(v))) {
  645. const s = String(v);
  646. v = `${s.slice(0, 4)}-${s.slice(4, 6)}-${s.slice(6, 8)}`;
  647. }
  648. return csvEscape(v);
  649. });
  650. lines.push(cells.join(','));
  651. }
  652. return '\ufeff' + lines.join('\r\n');
  653. }
  654. module.exports = {
  655. DEFAULT_CDP_PORT, REPORT_COLUMNS, FIELD_MAP,
  656. naposStatus, fetchTree, runNaposDiagnose,
  657. runSync, syncSnapshot, requestSyncCancel,
  658. queryReport, aggregateReport, summarizeRows,
  659. rowsToCsv,
  660. store,
  661. };