napos-service.js 30 KB

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