kit.js 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  1. 'use strict';
  2. /**
  3. * napos kit —— 给「运营 skill 脚本」复用的运行时工具箱。
  4. *
  5. * 为什么单独抽一层:
  6. * MCP 的 9 个工具是「一次请求」粒度(napos_call),拿不下跨域签名、多轮拼装、
  7. * 分页聚合这类活儿。skill 需要的是「一次调用完成一个业务动作」。
  8. * 所以这里把公共能力沉淀下来:登录态获取、签名、跨域取数、输出落盘。
  9. *
  10. * ★ 可迁移的关键设计:ksid(登录态)一律**运行时从页面里读**,绝不硬编码。
  11. * 硬编码的脚本拷到别的电脑必然失效 —— 这是能力迁移的第一道坎。
  12. *
  13. * 依赖:仅 ./cdp(同目录)。零第三方依赖。
  14. */
  15. const fs = require('fs');
  16. const path = require('path');
  17. const crypto = require('crypto');
  18. const cdp = require('./cdp');
  19. const guard = require('./guard');
  20. /** 数据中心里「实测不带签名也安全」的白名单(与 guard 共用同一份,避免两处打架) */
  21. const SIGN_SAFE_PATHS = guard.SIGN_SAFE_PATHS;
  22. const DEFAULT_PORT = Number(process.env.NAPOS_CDP_PORT || cdp.DEFAULT_PORT || 9669);
  23. /** 经营数据(数据中心)—— 唯一的自定义区间取数口 */
  24. const HISTORY_URL = 'https://lsycm.alibaba.com/api/overview/chain/custom/historyOverview';
  25. const HISTORY_METHOD = 'historyOverview'; // 参与签名的 targetId
  26. const SALT = '!@naposStats@!';
  27. const md5 = (s) => crypto.createHash('md5').update(String(s), 'utf8').digest('hex');
  28. /**
  29. * 接口签名。算法来自真实抓包反推:
  30. * secretkey = md5(ksid + '&' + targetId + '&' + timestamp + '&' + '!@naposStats@!')
  31. */
  32. function sign(ksid, targetId, timestamp, salt = SALT) {
  33. return md5(`${ksid}&${targetId}&${timestamp}&${salt}`);
  34. }
  35. // ------------------------------------------------------------------ 登录态
  36. /**
  37. * 运行时读取登录态 ksid。
  38. * 不传 api 时自己开一次页面连接;传了就复用(省一次握手)。
  39. * @returns {Promise<string|null>}
  40. */
  41. async function getKsid({ port = DEFAULT_PORT, api = null } = {}) {
  42. if (api) return cdp.findKsid(api);
  43. return cdp.withPageFor(port, 'shop', (a) => cdp.findKsid(a), { autoOpen: false });
  44. }
  45. // ------------------------------------------------------------------ 形态 A:直接调(无需签名)
  46. /**
  47. * 调一个商家后台/数据中心接口(不带签名)。
  48. * 自动按域名选正确的子站页面;拿不到正确来源页时**拒发**(避免触发客户端鉴权)。
  49. */
  50. async function call({ port = DEFAULT_PORT, url, method = 'GET', query = {}, body = null, headers = {}, needExact = true } = {}) {
  51. if (!url) throw new Error('call 需要 url');
  52. let full = url;
  53. if (query && Object.keys(query).length) {
  54. const u = new URL(url);
  55. for (const [k, v] of Object.entries(query)) {
  56. if (v === undefined || v === null) continue;
  57. u.searchParams.set(k, typeof v === 'object' ? JSON.stringify(v) : String(v));
  58. }
  59. full = u.toString();
  60. }
  61. return cdp.withPageFor(port, full, (api) =>
  62. cdp.pageFetch(api, { method, url: full, body, headers, allowWrite: false }),
  63. { needExact, autoOpen: true });
  64. }
  65. // ------------------------------------------------------------------ 形态 B:签名调(经营数据)
  66. /**
  67. * 经营数据 historyOverview —— 支持任意区间(含超 30 天)。
  68. *
  69. * @param {object} o
  70. * @param {string} [o.chainId='-1'] 链 ID,'-1' = 全公司
  71. * @param {string} [o.shopListIn=''] 门店 ID;非空 = 单店/多店粒度(这是钥匙,不是 shopId)
  72. * @param {string} [o.from] 起始日 YYYYMMDD
  73. * @param {string} [o.to] 结束日 YYYYMMDD
  74. * @param {string} [o.dateType='self_define'] ★ 自定义区间必须用 self_define
  75. * 预设值:recent_7d / recent_30d / week / month
  76. * @param {string} [o.compareOption='']
  77. * @returns {Promise<{code:*, all:object|null, rows:object[], daily:object[], ksidSource:string}>}
  78. */
  79. async function statsHistory(o = {}) {
  80. const port = Number(o.port || DEFAULT_PORT);
  81. const url = o.url || HISTORY_URL;
  82. const target = o.target || HISTORY_METHOD;
  83. const chainId = String(o.chainId == null ? '-1' : o.chainId);
  84. const shopListIn = o.shopListIn == null ? '' : String(o.shopListIn);
  85. const dateType = o.dateType || 'self_define';
  86. const from = normDay(o.from);
  87. const to = normDay(o.to);
  88. const key = o.key || dateType;
  89. return cdp.withPageFor(port, url, async (api) => {
  90. const ksid = await cdp.findKsid(api);
  91. if (!ksid) {
  92. const err = new Error(
  93. '读不到登录态 ksid:客户端可能未登录,或数据中心页面未就绪。\n' +
  94. ' 处理:在客户端打开「数据中心/生意参谋」页面后重试。'
  95. );
  96. err.code = 'NAPOS_NO_KSID';
  97. throw err;
  98. }
  99. const ts = Date.now();
  100. const body = {
  101. shopId: '', secretkey: sign(ksid, target, ts), timestamp: ts,
  102. chainId, dateType, key, compareOption: o.compareOption || '',
  103. beginDate: from || '', endDate: to || '', bizDate: o.bizDate || to || '',
  104. shopListIn,
  105. };
  106. const res = await cdp.pageFetch(api, { method: 'POST', url, body, allowWrite: false });
  107. const d = (res && res.data) || {};
  108. let rowsRaw = [];
  109. if (Array.isArray(d.data)) rowsRaw = d.data;
  110. else if (d.data && Array.isArray(d.data.list)) rowsRaw = d.data.list;
  111. else if (Array.isArray(d.result)) rowsRaw = d.result;
  112. const daily = rowsRaw.filter((x) => x && x.ds && /^\d{8}$/.test(String(x.ds)));
  113. const all = rowsRaw.find((x) => x && x.ds === 'all') || null;
  114. // 形态守卫:有原始行却一条 ds 形态都对不上 = 接口/页面结构变了。
  115. // 不标记的话上层会把这批行当"合法空数据"静默落库(全零类问题同根因)。
  116. const shapeWarning = rowsRaw.length > 0 && !daily.length && !all;
  117. return {
  118. ok: !!res.ok, status: res.status, risk: !!res.risk, authFail: !!res.authFail,
  119. shapeWarning,
  120. code: d.code != null ? d.code : (d.success === false ? 'success:false' : undefined),
  121. msg: d.msg || d.message || undefined,
  122. contextOrigin: res.contextOrigin || null,
  123. all, rows: rowsRaw, daily,
  124. _raw: res,
  125. };
  126. }, { needExact: true, autoOpen: true });
  127. }
  128. function normDay(v) {
  129. if (v == null || v === '') return '';
  130. const s = String(v).replace(/[-/.]/g, '').trim();
  131. return /^\d{8}$/.test(s) ? s : String(v);
  132. }
  133. /** 天数差(YYYYMMDD) */
  134. function dayDiff(from, to) {
  135. const p = (s) => new Date(Number(s.slice(0, 4)), Number(s.slice(4, 6)) - 1, Number(s.slice(6, 8)));
  136. return Math.round((p(normDay(to)) - p(normDay(from))) / 86400000);
  137. }
  138. /** 今天 YYYYMMDD(本地时区) */
  139. function today() {
  140. const d = new Date();
  141. const z = (n) => String(n).padStart(2, '0');
  142. return `${d.getFullYear()}${z(d.getMonth() + 1)}${z(d.getDate())}`;
  143. }
  144. /** N 天前 YYYYMMDD */
  145. function daysAgo(n) {
  146. const d = new Date(Date.now() - n * 86400000);
  147. const z = (x) => String(x).padStart(2, '0');
  148. return `${d.getFullYear()}${z(d.getMonth() + 1)}${z(d.getDate())}`;
  149. }
  150. // ------------------------------------------------------------------ 形态 C:xtop 网关(商家后台)
  151. const XTOP_BASE = 'https://app-api.shop.ele.me/xtop';
  152. /**
  153. * 调 xtop 网关接口。
  154. * 真实请求体结构(来自抓包):
  155. * { metas: { shopId, ksid, loginRestaurantId }, params: { request: {...} } }
  156. * ★ ksid 在 body 里也要带 —— 同样运行时读取,不硬编码。
  157. *
  158. * @param {object} o
  159. * @param {string} o.method 完整服务方法名,如 'xtop.napos.keeper.shop.queryShopTree'
  160. * @param {object} [o.request] 业务参数(放进 params.request)
  161. * @param {number|string} [o.shopId=-1]
  162. * @param {number|string} [o.loginRestaurantId=-1]
  163. */
  164. async function xtop(o = {}) {
  165. if (!o.method) throw new Error('xtop 需要 method');
  166. const port = Number(o.port || DEFAULT_PORT);
  167. const url = `${XTOP_BASE}/${o.method}/1.0`;
  168. return cdp.withPageFor(port, 'shop', async (api) => {
  169. const ksid = o.ksid || (await cdp.findKsid(api));
  170. if (!ksid) {
  171. const err = new Error('读不到登录态 ksid —— 客户端可能未登录。');
  172. err.code = 'NAPOS_NO_KSID';
  173. throw err;
  174. }
  175. const body = {
  176. metas: { shopId: o.shopId == null ? -1 : o.shopId, ksid, loginRestaurantId: o.loginRestaurantId == null ? -1 : o.loginRestaurantId },
  177. params: { request: o.request || {} },
  178. };
  179. const res = await cdp.pageFetch(api, { method: 'POST', url, body, allowWrite: false });
  180. return { ok: !!res.ok, status: res.status, risk: !!res.risk, authFail: !!res.authFail, data: res.data };
  181. }, { needExact: false, autoOpen: false });
  182. }
  183. /**
  184. * 门店组织树 —— 一次拿到「总部 → 连锁 → 门店」三层 + 每店营业状态。
  185. * @returns {Promise<{merchant:object|null, chains:object[], shops:object[], raw:object}>}
  186. */
  187. async function shopTree(o = {}) {
  188. const r = await xtop({
  189. port: o.port,
  190. method: 'xtop.napos.keeper.shop.queryShopTree',
  191. request: { restaurantId: o.restaurantId == null ? -1 : o.restaurantId, rootChainId: o.rootChainId == null ? -1 : o.rootChainId },
  192. shopId: -1, loginRestaurantId: -1,
  193. });
  194. const root = (r.data && r.data.result && r.data.result.shopTreeNode) || null;
  195. const chains = [];
  196. const shops = [];
  197. const walk = (n, chain) => {
  198. if (!n) return;
  199. if (n.nodeType === 'SHOP') {
  200. shops.push({
  201. shopId: n.id, shopName: n.name, busyLevel: n.busyLevel || null,
  202. chainId: chain ? chain.chainId : null, chainName: chain ? chain.chainName : null,
  203. restaurantType: n.restaurantType, shopBizType: n.shopBizType, shopSubBizType: n.shopSubBizType,
  204. });
  205. return;
  206. }
  207. if (n.nodeType === 'ROOT_CHAIN' || n.menuType === 'CHAIN') {
  208. const c = { chainId: n.id, chainName: n.name, parentId: n.parentId };
  209. chains.push(c);
  210. (n.childList || []).forEach((k) => walk(k, c));
  211. return;
  212. }
  213. (n.childList || []).forEach((k) => walk(k, chain)); // MERCHANT / UNIT 层透传
  214. };
  215. walk(root, null);
  216. return {
  217. ok: r.ok, code: (r.data && r.data.code) || r.status,
  218. msg: (r.data && (r.data.msg || r.data.message)) || undefined,
  219. authFail: !!r.authFail, risk: !!r.risk,
  220. merchant: root ? { id: root.id, name: root.name, nodeType: root.nodeType } : null,
  221. chains, shops, raw: r.data,
  222. };
  223. }
  224. /** 营业状态语义(busyLevel) */
  225. const BUSY_LEVEL = {
  226. OPEN: { label: '营业中', group: '在营', weight: 1 },
  227. CLOSE: { label: '休息中(非营业时段)', group: '在营', weight: 2 },
  228. SUSPEND_BUSINESS: { label: '暂停营业', group: '异常', weight: 3 },
  229. INVALID: { label: '未生效 / 已下架', group: '异常', weight: 4 },
  230. };
  231. // ------------------------------------------------------------------ 形态 D:数据中心其它只读接口
  232. const STATS_BASE = 'https://lsycm.alibaba.com';
  233. /**
  234. * 调数据中心(lsycm)任意只读 POST 接口。
  235. * 自动走数据中心上下文 + 自动补齐该域鉴权头。
  236. *
  237. * ★ 风控自保:lsycm 的验签接口若不带 secretkey,服务端判为伪造并弹验证码。
  238. * 这里对「非白名单」接口**自动补签名**(timestamp + secretkey),调用方无需关心。
  239. */
  240. async function statsApi(pathname, body = {}, o = {}) {
  241. const url = /^https?:/i.test(pathname) ? pathname : STATS_BASE + pathname;
  242. const port = Number(o.port || DEFAULT_PORT);
  243. const path = (() => { try { return new URL(url).pathname; } catch { return pathname; } })();
  244. const isStats = /(^|\.)lsycm\.alibaba\.com$/i.test((() => { try { return new URL(url).hostname; } catch { return ''; } })());
  245. const needSign = isStats && !SIGN_SAFE_PATHS.some((re) => re.test(path));
  246. return cdp.withPageFor(port, url, async (api) => {
  247. const payload = { ...body };
  248. if (needSign && !payload.secretkey) {
  249. const ksid = await cdp.findKsid(api);
  250. if (!ksid) {
  251. const err = new Error('读不到登录态 ksid,无法为验签接口补签名。请确认客户端已登录。');
  252. err.code = 'NAPOS_NO_KSID';
  253. throw err;
  254. }
  255. const ts = Date.now();
  256. // targetId 对齐前端真实行为:有 chainId 用 chainId,否则用 shopId(实测 16 个接口 100% 命中)
  257. const targetId = o.target != null
  258. ? o.target
  259. : (payload.chainId != null && payload.chainId !== ''
  260. ? String(payload.chainId)
  261. : (payload.shopId != null && payload.shopId !== '' ? String(payload.shopId) : path.split('/').filter(Boolean).pop()));
  262. payload.timestamp = ts;
  263. payload.secretkey = sign(ksid, targetId, ts);
  264. payload.shopId = payload.shopId == null ? '' : payload.shopId;
  265. if (payload.compareOption == null) payload.compareOption = '';
  266. }
  267. const r = await cdp.pageFetch(api, { method: o.method || 'POST', url, body: payload, allowWrite: false });
  268. return { ok: !!r.ok, status: r.status, risk: !!r.risk, authFail: !!r.authFail, contextOrigin: r.contextOrigin, data: r.data };
  269. }, { needExact: true, autoOpen: false });
  270. }
  271. /**
  272. * 经营归因(近 7 日 vs 上周)—— 返回 factors[],指出「谁在拉高/拉低」。
  273. * ⚠️ 固定窗口,不随日期参数变化;要自定义区间请用 statsHistory()。
  274. */
  275. async function businessSummary(o = {}) {
  276. const r = await statsApi('/api/overview/chain/custom/queryBusinessSummary',
  277. { chainId: String(o.chainId == null ? '-1' : o.chainId) }, { port: o.port });
  278. const d = (r.data && r.data.data) || null;
  279. return { ...r, summary: d };
  280. }
  281. /**
  282. * 城市维度汇总(近 7 日 vs 上周)—— 用于区域/渠道对比。
  283. * ⚠️ 同样是固定窗口。
  284. */
  285. async function cityList(o = {}) {
  286. const r = await statsApi('/api/naposOverview/queryChainCityList',
  287. { chainId: String(o.chainId == null ? '-1' : o.chainId) }, { port: o.port });
  288. const rows = (r.data && r.data.data && r.data.data.data) || (r.data && r.data.data) || [];
  289. return { ...r, cities: Array.isArray(rows) ? rows : [] };
  290. }
  291. /** 数据最近更新时间 */
  292. async function latestTime(o = {}) {
  293. const r = await statsApi('/api/naposOverview/getLatestTime', {}, { port: o.port });
  294. return (r.data && r.data.data) || null;
  295. }
  296. // ------------------------------------------------------------------ 形态 D:melody 业务接口(履约 / 订单 / 设置)
  297. const MELODY_BASE = 'https://app-api.shop.ele.me';
  298. /** 生成 melody 风格请求 id:<32位大写HEX>|<毫秒时间戳> */
  299. function melodyReqId() {
  300. let h = '';
  301. for (let i = 0; i < 32; i++) h += '0123456789ABCDEF'[(Math.random() * 16) | 0];
  302. return `${h}|${Date.now()}`;
  303. }
  304. /**
  305. * 调商家后台「melody」业务接口(body 结构来自真实抓包)。
  306. *
  307. * body = { service, method, params, id, metas:{appVersion,appName:'melody',ksid,shopId}, ncp:'2.0.0' }
  308. * ★ ksid 放在 metas 里 —— 运行时读取,不硬编码。
  309. *
  310. * @param {object} o
  311. * @param {string} o.service 如 'PollingService'
  312. * @param {string} o.method 如 'abnormalOrders'
  313. * @param {string} o.path 接口路径,如 '/fulfill/weborder/abnormalOrders/'
  314. * @param {object} [o.params] 业务参数(内含 shopId)
  315. */
  316. async function melody(o = {}) {
  317. if (!o.service || !o.method || !o.path) throw new Error('melody 需要 service / method / path');
  318. const port = Number(o.port || DEFAULT_PORT);
  319. const url = `${MELODY_BASE}${o.path}?method=${o.service}.${o.method}`;
  320. return cdp.withPageFor(port, url, async (api) => {
  321. const ksid = o.ksid || (await cdp.findKsid(api));
  322. if (!ksid) {
  323. const err = new Error('读不到登录态 ksid —— 客户端可能未登录。');
  324. err.code = 'NAPOS_NO_KSID';
  325. throw err;
  326. }
  327. const params = o.params || {};
  328. const shopId = o.shopId != null ? o.shopId : (params.shopId != null ? params.shopId : -1);
  329. const body = {
  330. service: o.service, method: o.method, params,
  331. id: melodyReqId(),
  332. metas: { appVersion: o.appVersion || '1.0.0', appName: 'melody', ksid, shopId },
  333. ncp: '2.0.0',
  334. };
  335. const res = await cdp.pageFetch(api, { method: 'POST', url, body, allowWrite: false });
  336. const d = res.data || {};
  337. return {
  338. ok: !!res.ok, status: res.status, risk: !!res.risk, authFail: !!res.authFail,
  339. error: d.error || null,
  340. result: d.result !== undefined ? d.result : (d.data !== undefined ? d.data : null),
  341. code: d.code, raw: d,
  342. };
  343. }, { needExact: false, autoOpen: false });
  344. }
  345. /**
  346. * 订单履约巡检 —— 一次抓「当前」的异常/待办订单计数(全公司或指定门店)。
  347. * ⚠️ 这是**实时快照**,不是历史;要看趋势必须定时落库累积。
  348. *
  349. * @returns {Promise<{ok:boolean, newOrder:?number, urge:?number, preparing:?number, callDelivery:?number,
  350. * riderAccept:?number, unprocessedBooking:?number, bookingOrderIds:string[],
  351. * exceptional:?number, cancel:?number, refund:?number, fastRefund:?number,
  352. * noProcesNegotiate:*, timeOutNegotiate:*, needRemindException:boolean, raw:object,
  353. * risk:boolean, authFail:boolean}>}
  354. * 任一子调用失败(HTTP/风控/鉴权/业务错误)时 ok=false 且各计数为 **null** ——
  355. * 绝不返回 0:那会把"取数失败"伪装成"健康零负载"快照。
  356. */
  357. async function orderAlerts(o = {}) {
  358. const shopId = o.shopId == null ? -1 : o.shopId;
  359. const P = { port: o.port, ksid: o.ksid, shopId };
  360. const [ab, non, un] = await Promise.all([
  361. melody({ ...P, service: 'PollingService', method: 'abnormalOrders', path: '/fulfill/weborder/abnormalOrders/', params: { shopId } }),
  362. melody({ ...P, service: 'PollingService', method: 'nonCoreOrders', path: '/fulfill/weborder/nonCoreOrders/', params: { shopId } }),
  363. melody({ ...P, service: 'PollingService', method: 'unprocessedOrders', path: '/fulfill/weborder/unprocessedOrders/', params: { shopId } }),
  364. ]);
  365. const subFail = (r) => !r || r.ok === false || !!r.risk || !!r.authFail || !!r.error;
  366. const anyFail = subFail(ab) || subFail(non) || subFail(un);
  367. const A = (ab && ab.result && typeof ab.result === 'object') ? ab.result : {};
  368. const N = (non && non.result && typeof non.result === 'object') ? non.result : {};
  369. const U = (un && un.result && typeof un.result === 'object') ? un.result : {};
  370. // 失败时计数不可信 → 一律 null,让调用方显式处理"不可知",而不是当成 0
  371. const n = (v) => (anyFail ? null : (Number(v) || 0));
  372. const bookingIds = (!anyFail && N.bookingNotice && Array.isArray(N.bookingNotice.orderIds)) ? N.bookingNotice.orderIds : [];
  373. return {
  374. ok: !anyFail,
  375. shopId,
  376. newOrder: n(U.newOrderCount),
  377. urge: n(N.urgeOrderCount),
  378. preparing: n(N.preparingOrderCount),
  379. callDelivery: n(N.waitingCallDeliveryCount),
  380. riderAccept: n(N.riderAcceptOrderCount),
  381. unprocessedBooking: n(N.unprocessedBookingOrderCount),
  382. bookingOrderIds: bookingIds,
  383. exceptional: n(A.exceptionalOrderCount),
  384. cancel: n(A.cancelOrderCount),
  385. refund: n(A.refundOrderCount),
  386. fastRefund: n(A.fastRefundOrderCount),
  387. noProcesNegotiate: anyFail ? null : (A.noProcesNegotiateOrder == null ? null : n(A.noProcesNegotiateOrder)),
  388. timeOutNegotiate: anyFail ? null : (A.timeOutNegotiateOrder == null ? null : n(A.timeOutNegotiateOrder)),
  389. needRemindException: !anyFail && !!A.needRemindExceptionOrder,
  390. raw: { abnormal: A, nonCore: N, unprocessed: U },
  391. risk: !!(ab && ab.risk) || !!(non && non.risk) || !!(un && un.risk),
  392. authFail: !!(ab && ab.authFail) || !!(non && non.authFail) || !!(un && un.authFail),
  393. };
  394. }
  395. /** 接单/履约设置(91 字段,含预订单、备餐提醒、自动接单等) */
  396. async function orderSetting(o = {}) {
  397. const shopId = o.shopId == null ? -1 : o.shopId;
  398. const r = await melody({ port: o.port, ksid: o.ksid, shopId, service: 'ShopSettingService', method: 'getOrderSetting', path: '/nevermore/invoke/', params: { shopId } });
  399. const setting = (r.result && r.result.result) ? r.result.result : (r.result || null);
  400. return { ...r, setting };
  401. }
  402. /** 售后托管设置(是否开启托管/补发/补偿,含补偿比例上限) */
  403. async function afterSaleHosting(o = {}) {
  404. const shopId = o.shopId == null ? -1 : o.shopId;
  405. const r = await xtop({ port: o.port, method: 'xtop.eleme.merchant.fulfillment.shopSettings.getAfterSaleHostingSettings', request: { shopId }, shopId: -1 });
  406. const inner = (r.data && r.data.result && r.data.result.data) ? r.data.result.data : null;
  407. return { ...r, hosting: inner };
  408. }
  409. /** 出餐/配送设置类小接口合集(提醒时长、索赔提示、轮询策略) */
  410. async function orderTips(o = {}) {
  411. const shopId = o.shopId == null ? -1 : o.shopId;
  412. const P = { port: o.port, ksid: o.ksid, shopId };
  413. const [cook, claim, poll] = await Promise.all([
  414. melody({ ...P, service: 'ShopSettingService', method: 'getRemindCookTimeSetting', path: '/fulfill/strategy/getRemindCookTimeSetting/', params: { shopId } }),
  415. melody({ ...P, service: 'DeliveryClaimService', method: 'getOrderClaimTips', path: '/fulfill/weborder/getOrderClaimTips/', params: { shopId } }),
  416. melody({ ...P, service: 'PollingService', method: 'getPollingStrategy', path: '/fulfill/weborder/getPollingStrategy/', params: { shopId } }),
  417. ]);
  418. return { cookTime: cook.result, claimTips: claim.result, polling: poll.result };
  419. }
  420. // ------------------------------------------------------------------ 形态 E:agw 网关(财务 / 成长)
  421. /**
  422. * agw 网关 = 阿里本地生活网关,财务(账单/结算)与成长中心都挂在上面。
  423. *
  424. * ★ 与 lsycm 完全不同的两个坑(实测,2026-10-11):
  425. * ① 请求**必须**由「该子站自己的 H5 执行上下文」发出 —— 子站是商家后台页里的
  426. * 跨域 iframe,从外层页面发会被判为伪造来源 → 网关直接回 `111006 用户未登录`。
  427. * 财务 H5 → https://napos-bill-pc.faas.ele.me 路由 /app/unit/billDetail
  428. * 成长 H5 → https://napos-shop-operation-pc.faas.ele.me 路由 /app/unit/business-task-new
  429. * (路由表与鉴权头已在 cdp.js 的 APPS / buildAuthHeaders 里配好,这里只管取数)
  430. * ② 鉴权是 `ksid` + `current-shop-id` + `X-AGW-BIZ-CONTEXT` 三个头,**不是** secretkey。
  431. */
  432. const AGW_BASE = { bill: 'https://agw.alsc.taobao.com', growth: 'https://agw.ele.me' };
  433. const AGW_QUERY = {
  434. bill: { source: 'ELE', h: 'napos-bill-pc.faas.ele.me' },
  435. growth: { source: 'ELE' },
  436. };
  437. /** YYYYMMDD → 毫秒(which: 'start' 当日 00:00:00 / 'end' 当日 23:59:59.999) */
  438. function msOf(day, which) {
  439. const s = normDay(day);
  440. if (!/^\d{8}$/.test(s)) return undefined;
  441. const y = +s.slice(0, 4), m = +s.slice(4, 6), d = +s.slice(6, 8);
  442. return which === 'end' ? new Date(y, m - 1, d, 23, 59, 59, 999).getTime() : new Date(y, m - 1, d, 0, 0, 0, 0).getTime();
  443. }
  444. /** 毫秒 → YYYYMMDD */
  445. function ymd(ms) {
  446. const d = new Date(Number(ms));
  447. const z = (n) => String(n).padStart(2, '0');
  448. return `${d.getFullYear()}${z(d.getMonth() + 1)}${z(d.getDate())}`;
  449. }
  450. /** 毫秒 → YYYY-MM-DD */
  451. function ymdDash(ms) {
  452. const s = ymd(ms);
  453. return `${s.slice(0, 4)}-${s.slice(4, 6)}-${s.slice(6, 8)}`;
  454. }
  455. /**
  456. * 确保某个 agw 子站的宿主页已就绪(不存在就导航主页面过去把它拉起来)。
  457. * @returns {Promise<{ok:boolean, opened:boolean, contexts:string[]}>}
  458. */
  459. async function ensureApp(appId, o = {}) {
  460. const port = Number(o.port || DEFAULT_PORT);
  461. const app = typeof appId === 'object' && appId.id ? appId : cdp.resolveApp(appId);
  462. const has = async () => {
  463. try {
  464. const ctxs = await cdp.withPageFor(port, app.id, (api) => [...api.contexts.keys()], { needExact: false, autoOpen: false });
  465. return ctxs.some((o2) => cdp.ctxMatchesApp(o2, app)) ? ctxs : null;
  466. } catch { return null; }
  467. };
  468. const hit = await has();
  469. if (hit) return { ok: true, opened: false, contexts: hit };
  470. if (!app.openPath) return { ok: false, opened: false, contexts: [] };
  471. // 导航主页面到该子站路由(同源导航,不会触发鉴权),把 iframe 带起来
  472. try {
  473. await cdp.withPageFor(port, 'shop', (api) => api.evaluate(
  474. `location.href = ${JSON.stringify('https://melody.shop.ele.me' + app.openPath)}`
  475. ), { needExact: false, autoOpen: false });
  476. } catch { /* 忽略 */ }
  477. const deadline = Date.now() + Number(o.waitMs || 20000);
  478. while (Date.now() < deadline) {
  479. await cdp.sleep(1200);
  480. const r = await has();
  481. if (r) return { ok: true, opened: true, contexts: r };
  482. }
  483. return { ok: false, opened: true, contexts: [] };
  484. }
  485. /** 读该 agw 子站上下文里的凭证(ksid / unitId / shopId)—— 全部运行时读,不硬编码 */
  486. async function agwCred(appId, o = {}) {
  487. const port = Number(o.port || DEFAULT_PORT);
  488. const app = cdp.resolveApp(appId);
  489. return cdp.withPageFor(port, app.id, async (api) => {
  490. let ctx = null;
  491. for (const [origin, c] of api.contexts) { if (cdp.ctxMatchesApp(origin, app)) { ctx = c; break; } }
  492. const v = await api.evaluate(cdp.AGW_CRED_PROBE, ctx ? { contextId: ctx.id } : undefined);
  493. return v || {};
  494. }, { needExact: false, autoOpen: false });
  495. }
  496. /** 调一个 agw 接口(body 固定为 { params: [...] } 形态) */
  497. async function agw(appId, path, params, o = {}) {
  498. const base = AGW_BASE[appId];
  499. if (!base) throw new Error(`agw 不支持子站 ${appId}(现支持:${Object.keys(AGW_BASE).join(' / ')})`);
  500. const url = /^https?:/i.test(path) ? path : base + path;
  501. const query = { ...(AGW_QUERY[appId] || {}), ...(o.query || {}) };
  502. const r = await call({ port: o.port, url, method: 'POST', query, body: { params }, needExact: o.needExact !== false });
  503. const d = (r.data && (r.data.data !== undefined ? r.data.data : r.data.result)) || null;
  504. return { ...r, data: r.data, payload: d };
  505. }
  506. // ---- 财务:账单 / 结算 -------------------------------------------------------
  507. /**
  508. * 可查账单的时间范围(最早可查日 + 服务器当前时间)。
  509. * 实测最早可查 ≈ 2023-12-01(比经营数据只保留 180 天宽松得多)。
  510. */
  511. async function billRange(o = {}) {
  512. const port = Number(o.port || DEFAULT_PORT);
  513. await ensureApp('bill', { port, waitMs: o.waitMs });
  514. const r = await agw('bill', '/gw/h5api/ele-shop-bill-query.GrayFacade.getGrayDatetime', [{}], { port });
  515. const d = r.payload || {};
  516. return { ...r, startDisplayDate: d.startDisplayDate || null, currentDateTime: d.currentDateTime || null,
  517. startDay: d.startDisplayDate ? ymd(d.startDisplayDate) : null };
  518. }
  519. /**
  520. * 连锁结算账单(日结,逐日一行;自动翻页聚合)。
  521. *
  522. * ★ 血泪教训:`shopId` / `chainId` 传 `'-1'` 会**返回空列表**(和经营数据一样,
  523. * -1 在账单域不是"全公司")。必须传真实 `unitId`,脚本已自动读取。
  524. *
  525. * @returns {Promise<{ok,unitId,biz,from,to,rows:object[],meta:{totalCount,shopCount,settleAmount,summaryPeriod}}>}
  526. * rows[] = { billDate, incomeAmount, expendAmount, settleAmount, settleStatus, settleShopCount }
  527. * settleStatus: TO_BE_SETTLED(待结算) / SETTLED(已结算) …
  528. */
  529. async function settleList(o = {}) {
  530. const port = Number(o.port || DEFAULT_PORT);
  531. const ens = await ensureApp('bill', { port, waitMs: o.waitMs });
  532. let unit = o.unitId || o.shopId || '';
  533. if (!unit) unit = (await agwCred('bill', { port })).unitId || '';
  534. unit = String(unit || '');
  535. if (!unit) {
  536. const err = new Error('读不到 unitId —— 无法确定账单主体。请确认财务页已登录(napos-ops-core 体检)。');
  537. err.code = 'NAPOS_NO_UNIT';
  538. throw err;
  539. }
  540. const biz = o.settleBizType || 'TRADE';
  541. const from = o.from ? normDay(o.from) : daysAgo(o.days == null ? 30 : Number(o.days));
  542. const to = o.to ? normDay(o.to) : today();
  543. const size = Number(o.pageSize || 100);
  544. const maxPage = Number(o.maxPage || 60);
  545. const rows = [];
  546. let pageNo = 1, totalPage = 1, meta = null;
  547. let last = null; // 末次翻页响应:决定整体 ok(失败不得伪装成"成功 0 行")
  548. let pages = 0;
  549. while (pageNo <= Math.min(totalPage, maxPage)) {
  550. const r = await agw('bill', '/gw/h5api/ele-shop-bill-query.ShopSummaryQueryFacade.queryChainSettleListByPage',
  551. [{ shopId: unit, pageNo, pageSize: size, startBillDate: msOf(from, 'start'), endBillDate: msOf(to, 'end'), chainId: unit, settleBizType: biz }],
  552. { port });
  553. last = r;
  554. pages++;
  555. const d = r.payload || {};
  556. if (Array.isArray(d.list)) rows.push(...d.list);
  557. totalPage = Number(d.totalPage || 1) || 1;
  558. if (!meta) meta = { totalCount: d.totalCount != null ? d.totalCount : null, shopCount: d.shopCount != null ? d.shopCount : null, settleAmount: d.settleAmount != null ? d.settleAmount : null, summaryPeriod: d.summaryPeriod || null };
  559. if (!Array.isArray(d.list) || d.list.length < size) break;
  560. pageNo++;
  561. }
  562. // 口径统一:末页 HTTP 失败 / 风控 / 鉴权失效 / 业务层没回 list(空区间成功时 list 也是数组,只是为空)
  563. const ld = (last && last.payload) || null;
  564. const failed = !last || !last.ok || !!last.risk || !!last.authFail || !ld || !Array.isArray(ld.list);
  565. return {
  566. ok: !failed,
  567. risk: !!(last && last.risk), authFail: !!(last && last.authFail),
  568. error: failed
  569. ? `结算账单翻页异常(第 ${pages} 页):${!last ? '无响应' : last.authFail ? '鉴权失效' : last.risk ? '触发风控' : !last.ok ? `HTTP ${last.status || '?'}` : '响应缺少 list 字段(接口形态可能已变化)'}`
  570. : null,
  571. unitId: unit, biz, from, to, rows, meta, ensured: ens,
  572. };
  573. }
  574. /** 结算账单区间汇总(按日聚合 → 收入/支出/结算额/天数/状态分布) */
  575. function summarizeSettle(rows) {
  576. const n = (v) => Number(v) || 0;
  577. const s = { days: rows.length, income: 0, expense: 0, settle: 0, settleShopCount: 0, status: {} };
  578. for (const r of rows) {
  579. s.income += n(r.incomeAmount);
  580. s.expense += n(r.expendAmount);
  581. s.settle += n(r.settleAmount);
  582. s.settleShopCount += n(r.settleShopCount);
  583. const k = r.settleStatus || 'UNKNOWN';
  584. s.status[k] = (s.status[k] || 0) + 1;
  585. }
  586. s.income = +s.income.toFixed(2);
  587. s.expense = +s.expense.toFixed(2);
  588. s.settle = +s.settle.toFixed(2);
  589. s.margin = s.income > 0 ? +((s.settle / s.income) * 100).toFixed(2) : 0; // 结算率
  590. return s;
  591. }
  592. // ---- 成长:产能 / 诊断 / 周报 / 任务 -------------------------------------------
  593. /** 成长中心汇总:门店产能分层(高/中/低)+ 经营诊断(L1/L2 未通过门店数) */
  594. async function growthSummary(o = {}) {
  595. const port = Number(o.port || DEFAULT_PORT);
  596. await ensureApp('growth', { port, waitMs: o.waitMs });
  597. const chainId = o.chainId == null ? '' : String(o.chainId);
  598. const r = await agw('growth', '/gw/h5api/ele-shop-growth-product.ChainBusinessTaskPageWebService.getSummaryInfo', [{ chainId }], { port });
  599. return { ...r, summary: r.payload || null };
  600. }
  601. /** 成长周报(GMV / 营收 / 曝光 / 访购率 + 环比 + 核心策略) */
  602. async function growthWeekly(o = {}) {
  603. const port = Number(o.port || DEFAULT_PORT);
  604. await ensureApp('growth', { port, waitMs: o.waitMs });
  605. const chainId = o.chainId == null ? '' : String(o.chainId);
  606. const r = await agw('growth', '/gw/h5api/ele-shop-growth-product.ChainBusinessTaskPageWebService.getWeeklyReportData',
  607. [{ chainId, brandId: o.brandId == null ? -1 : o.brandId }], { port });
  608. return { ...r, weekly: r.payload || null };
  609. }
  610. /** 生意任务完成率(按门店 DetailType=DETAIL_TYPE_SHOP,自动翻页) */
  611. async function growthTaskRate(o = {}) {
  612. const port = Number(o.port || DEFAULT_PORT);
  613. await ensureApp('growth', { port, waitMs: o.waitMs });
  614. const chainId = o.chainId == null ? '' : String(o.chainId);
  615. const size = Number(o.size || 50), maxPage = Number(o.maxPage || 20);
  616. const rows = [];
  617. let page = 1, total = 1;
  618. let last = null;
  619. while (page <= Math.min(total, maxPage)) {
  620. const r = await agw('growth', '/gw/h5api/ele-shop-growth-product.ChainBusinessTaskPageWebService.getBusinessTaskCompleteRateByPage',
  621. [{ chainId, page, size, data: { detailType: o.detailType || 'DETAIL_TYPE_SHOP', brandId: o.brandId == null ? -1 : o.brandId, useNew: true } }], { port });
  622. last = r;
  623. const d = r.payload || {};
  624. if (Array.isArray(d.data)) rows.push(...d.data);
  625. total = Number(d.total || 0) ? Math.ceil(Number(d.total) / size) : 1;
  626. if (!Array.isArray(d.data) || d.data.length < size) break;
  627. page++;
  628. }
  629. // 口径统一:末页失败/形态异常不再报 ok:true(否则翻页失败会被当"完成率全空"误读)
  630. const ld = (last && last.payload) || null;
  631. const failed = !last || !last.ok || !!last.risk || !!last.authFail || !ld || !Array.isArray(ld.data);
  632. return {
  633. ok: !failed,
  634. risk: !!(last && last.risk), authFail: !!(last && last.authFail),
  635. error: failed
  636. ? `生意任务完成率翻页异常:${!last ? '无响应' : last.authFail ? '鉴权失效' : last.risk ? '触发风控' : !last.ok ? `HTTP ${last.status || '?'}` : '响应缺少 data 字段(接口形态可能已变化)'}`
  637. : null,
  638. rows,
  639. };
  640. }
  641. /** 成长中心品牌列表(brandId 用于周报 / 任务过滤) */
  642. async function growthBrands(o = {}) {
  643. const port = Number(o.port || DEFAULT_PORT);
  644. await ensureApp('growth', { port, waitMs: o.waitMs });
  645. const chainId = o.chainId == null ? '' : String(o.chainId);
  646. const r = await agw('growth', '/gw/h5api/ele-shop-growth-product.ChainBusinessTaskPageWebService.getBrands', [{ chainId }], { port });
  647. return { ...r, brands: r.payload || null };
  648. }
  649. // ------------------------------------------------------------------ 形态 F:渠道 / 联盟 / 金融
  650. /**
  651. * 渠道域身份(ksid / unitId / keeperId / 当前店)。
  652. * ★ 全部运行时读(localStorage → sessionStorage → cookie),绝不硬编码 —— 换机可用。
  653. * 实测:localStorage 与 cookie 里都有 unitId / keeperId / ksid(同值)。
  654. */
  655. async function channelIdentity(o = {}) {
  656. const port = Number(o.port || DEFAULT_PORT);
  657. const app = cdp.resolveApp('channel');
  658. return cdp.withPageFor(port, app.id, async (api) => {
  659. const ids = [undefined];
  660. for (const [origin, c] of api.contexts) if (cdp.ctxMatchesApp(origin, app)) ids.push(c.id);
  661. let fallback = {};
  662. for (const contextId of ids) {
  663. let v = null;
  664. try { v = await api.evaluate(cdp.CHANNEL_ID_PROBE, contextId ? { contextId } : undefined); } catch { continue; }
  665. if (v && v.ksid && v.unitId) return v;
  666. if (v && v.ksid && !fallback.ksid) fallback = v;
  667. }
  668. return fallback;
  669. }, { needExact: false, autoOpen: false });
  670. }
  671. const VAS_URL = 'https://app-api.shop.ele.me/xtop/xtop.vas.gateway.iOneRoute.callFromNapos/1.0';
  672. /** callFromNapos 的 reqId(实测格式:<随机数><毫秒><unitId>z6SvSyc9A+C) */
  673. function vasReqId(unitId) {
  674. return `${Math.floor(Math.random() * 1e12)}${Date.now()}${unitId}z6SvSyc9A+C`;
  675. }
  676. /**
  677. * 调「增值服务」网关(vas)—— 闪购联盟 / 店铺推广的公共入口。
  678. *
  679. * ★ 与 lsycm(签名)和 agw(头鉴权)都不同:鉴权是 **body.metas.ksid**(请求头里没有),
  680. * 业务参数形如 `params.params = [身份包{loginId,bizCode,isChain}, 业务参数]`。
  681. * bizCode:闪购联盟 = 'eleCps' / 店铺推广 = 'eleChain'。
  682. * ★ 实测(2026-10-11):从商家后台主页面直接发即可成功,**不需要**专属 H5 上下文。
  683. *
  684. * @param {string} service 例 oneReportService
  685. * @param {string} method 例 findTotalReport
  686. * @param {object} arg 业务参数(params[1])
  687. * @param {object} o { bizCode, isChain, unitId, identity, port }
  688. */
  689. async function vas(service, method, arg = {}, o = {}) {
  690. const port = Number(o.port || DEFAULT_PORT);
  691. const id = o.identity || await channelIdentity({ port });
  692. const unit = o.unitId || id.unitId;
  693. if (!id.ksid) { const e = new Error('读不到 ksid —— 请确认客户端已登录商家后台(napos-ops-core 体检)。'); e.code = 'NAPOS_NO_KSID'; throw e; }
  694. if (!unit) { const e = new Error('读不到 unitId —— 请确认客户端已登录商家后台。'); e.code = 'NAPOS_NO_UNIT'; throw e; }
  695. const url = `${VAS_URL}?service=${encodeURIComponent(service)}&method=${encodeURIComponent(method)}`;
  696. const body = {
  697. metas: { ksid: String(id.ksid), shopId: Number(unit), appName: 'napos' },
  698. params: {
  699. from: 'napos', to: 'alsc-ad-onebp', method, service,
  700. params: [{ loginId: Number(unit), bizCode: o.bizCode || 'eleCps', isChain: o.isChain !== false }, arg || {}],
  701. reqId: vasReqId(unit),
  702. },
  703. };
  704. const r = await call({ port, url, method: 'POST', body, needExact: true });
  705. const d = r.data || {};
  706. const payload = d.result ? d.result.data : (d.data !== undefined ? d.data : null);
  707. return { ...r, payload };
  708. }
  709. // ---- 渠道:闪购联盟(CPS / 联盟) --------------------------------------------
  710. /** 联盟开通概览:门店总数 / CPS 已开通门店数 / 权限码 / 商品与卡券概况 */
  711. async function cpsShopInfo(o = {}) {
  712. const r = await vas('shopService', 'getShopInfo', {}, { bizCode: 'eleCps', isChain: true, ...o });
  713. return { ...r, info: r.payload || null };
  714. }
  715. /** 联盟权益列表(queryType:AVOID_COMMISSION 免佣 …) */
  716. async function cpsRights(queryType = 'AVOID_COMMISSION', status = [1, 2], o = {}) {
  717. const r = await vas('oneRightService', 'getRightInfoList', { queryType, status }, { bizCode: 'eleCps', isChain: true, ...o });
  718. return { ...r, rows: Array.isArray(r.payload) ? r.payload : [] };
  719. }
  720. /** 联盟合约签署状态(signBaseValue / openValue / invoiceType) */
  721. async function cpsContract(o = {}) {
  722. const r = await vas('oneUserService', 'getSignedContract', {}, { bizCode: 'eleCps', isChain: true, ...o });
  723. return { ...r, contract: r.payload || null };
  724. }
  725. /** 联盟门店授权 */
  726. async function cpsAuthority(o = {}) {
  727. const r = await vas('shopService', 'queryShopAuthority', { isChain: true }, { bizCode: o.bizCode || 'eleCps', isChain: true, ...o });
  728. return { ...r, authority: r.payload || null };
  729. }
  730. /** 联盟推广组(oneAdGroupService.get) */
  731. async function cpsAdGroup(o = {}) {
  732. const r = await vas('oneAdGroupService', 'get', {}, { bizCode: 'eleCps', isChain: true, ...o });
  733. return { ...r, groups: r.payload };
  734. }
  735. // ---- 渠道:店铺推广(推广余额 / 花费 / 锦囊) ---------------------------------
  736. /** 推广账户余额(连锁汇总;detail 里是各类余额分项,balance 单位为分) */
  737. async function promoBalance(o = {}) {
  738. const port = Number(o.port || DEFAULT_PORT);
  739. const r = await call({
  740. port, method: 'POST', needExact: true,
  741. url: 'https://agw.alsc.taobao.com/gw/h5api/alsc-ad-account.IGwBalanceService.findBalanceInfo',
  742. query: { source: 'ELE', h: 'r.ele.me' },
  743. body: { params: [{}] },
  744. });
  745. const d = (r.data && r.data.result) || null;
  746. const fen = d && d.detail ? Number(d.detail.balance || 0) : null;
  747. return { ...r, balance: d, balanceFen: fen, balanceYuan: fen == null ? null : (fen / 100).toFixed(2) };
  748. }
  749. /** 门店推广余额汇总(total 单位为分) */
  750. async function promoLeafBalance(o = {}) {
  751. const port = Number(o.port || DEFAULT_PORT);
  752. const r = await call({
  753. port, method: 'POST', needExact: true,
  754. url: 'https://agw.alsc.taobao.com/gw/h5api/alsc-ad-account.IGwBalanceService.findLeafShopBalanceInfoAsync',
  755. query: { source: 'ELE', h: 'r.ele.me' },
  756. body: { params: [{}] },
  757. });
  758. const d = (r.data && r.data.result && r.data.result.result) || null;
  759. const fen = d ? Number(d.total || 0) : null;
  760. return { ...r, summary: d, totalFen: fen, totalYuan: fen == null ? null : (fen / 100).toFixed(2) };
  761. }
  762. /** 推广花费报表(默认近 7 天;reportStartDate/reportEndDate 支持自定义区间) */
  763. async function promoReport(o = {}) {
  764. const endMs = o.to ? msOf(o.to, 'end') : (Date.now() - 86400000);
  765. const startMs = o.from ? msOf(o.from, 'start') : (endMs - Math.max(0, Number(o.days || 7) - 1) * 86400000);
  766. const from = ymdDash(startMs), to = ymdDash(endMs);
  767. const arg = { reportTypeEnum: o.reportType || 'CHAIN_HIS_COST', showDetail: true, reportStartDate: from, reportEndDate: to };
  768. const r = await vas('oneReportService', 'findTotalReport', arg, { bizCode: o.bizCode || 'eleChain', isChain: false, ...o });
  769. return { ...r, report: r.payload || null, from, to };
  770. }
  771. /** 店铺推广:锦囊 / 流量袋 */
  772. async function silkBag(o = {}) {
  773. const arg = {
  774. shopId: Number(o.shopId || 0), pageSize: Number(o.pageSize || 20),
  775. stateList: o.stateList || [10, 20], pageNum: Number(o.pageNum || 1),
  776. bagType: o.bagType || 'BROCADEBAG',
  777. };
  778. const r = await vas('marketingToolService', 'findSilkBagPage', arg, { bizCode: o.bizCode || 'eleChain', isChain: false, ...o });
  779. const d = r.payload;
  780. const rows = Array.isArray(d) ? d : (d && Array.isArray(d.data) ? d.data : []);
  781. return { ...r, rows, total: d && d.totalCount != null ? d.totalCount : rows.length };
  782. }
  783. // ---- 渠道:金融保险(储值卡 / 可见金融产品) ---------------------------------
  784. /** 可见金融资源(借款等,code:napos_eat_loan_profit …) */
  785. async function finResources(code = 'napos_eat_loan_profit', o = {}) {
  786. const port = Number(o.port || DEFAULT_PORT);
  787. const r = await call({
  788. port, method: 'POST', needExact: true,
  789. url: 'https://agw.ele.me/gw/h5api/fn-alsc-fin-ops.alsc-fin-ops.common-config',
  790. query: { source: 'ELE', h: 'r.ele.me' },
  791. body: { params: [{ className: 'me.ele.fin.promotion.fn.service.H5ResourceService', methodName: 'queryVisibleResourceList', param: { code, cityId: o.cityId || '' } }] },
  792. });
  793. return { ...r, rows: (r.data && r.data.data) || [] };
  794. }
  795. /** 储值卡可签门店清单(全公司,unitType=UNIT) */
  796. async function finShops(o = {}) {
  797. const port = Number(o.port || DEFAULT_PORT);
  798. const id = o.identity || await channelIdentity({ port });
  799. const unitId = o.unitId || id.unitId, keeperId = o.keeperId || id.keeperId;
  800. if (!unitId || !keeperId) { const e = new Error('读不到 unitId / keeperId —— 请确认客户端已登录商家后台。'); e.code = 'NAPOS_NO_UNIT'; throw e; }
  801. const r = await call({
  802. port, method: 'POST', needExact: true,
  803. url: 'https://httpizza.ele.me/xtop/xtop.storedcard.commonShopApi.getShopIdsByKeeperIdAndUnitId/1.0',
  804. body: { params: { request: { keeperId: Number(keeperId), unitId: Number(unitId), unitType: o.unitType || 'UNIT' } } },
  805. });
  806. const ids = (r.data && r.data.result && r.data.result.data && r.data.result.data.shopIds) || [];
  807. return { ...r, shopIds: ids };
  808. }
  809. /** 储值卡签约状态(逐店 status:SIGNED / CAN_SIGN …) */
  810. async function finSign(shopIds, o = {}) {
  811. const port = Number(o.port || DEFAULT_PORT);
  812. const id = o.identity || await channelIdentity({ port });
  813. const unitId = o.unitId || id.unitId;
  814. if (!unitId) { const e = new Error('读不到 unitId —— 请确认客户端已登录商家后台。'); e.code = 'NAPOS_NO_UNIT'; throw e; }
  815. const r = await call({
  816. port, method: 'POST', needExact: true,
  817. url: 'https://httpizza.ele.me/xtop/xtop.storedcard.merchant.signrecord.get/1.0',
  818. body: { params: { request: { shopIds: (shopIds || []).map(Number), shopType: o.shopType || 'UNIT', unitId: Number(unitId) } } },
  819. });
  820. const rows = (r.data && r.data.result && r.data.result.data) || [];
  821. return { ...r, rows };
  822. }
  823. // ------------------------------------------------------------------ 商品域(nevermore.goods)
  824. /**
  825. * nevermore.goods 网关通用只读调用。
  826. * 商品 / 门店属性 / 菜单 / 回收站等接口都在这个网关下,方法名在 query 的 method 里。
  827. */
  828. async function goodsInvoke(service, method, params = {}, shopId = -1, o = {}) {
  829. return melody({ service, method, path: '/nevermore.goods/invoke/', params, shopId, appVersion: o.appVersion || '4.4.0' });
  830. }
  831. /** 门店商品属性(包装费 / 口味分类 / 各类开关)—— 返回 result 为对象 */
  832. async function restaurantAttribute(shopId, o = {}) {
  833. return goodsInvoke('GrayService', 'getRestaurantAttribute', { shopId }, shopId, o);
  834. }
  835. // ------------------------------------------------------------------ 输出落盘
  836. function ensureDir(p) {
  837. try { fs.mkdirSync(p, { recursive: true }); } catch { /* ignore */ }
  838. return p;
  839. }
  840. function csvCell(v) {
  841. if (v === null || v === undefined) return '';
  842. const s = typeof v === 'object' ? JSON.stringify(v) : String(v);
  843. return /[",\n\r]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
  844. }
  845. /** 写 CSV(UTF-8 BOM + CRLF,Excel 直接可读) */
  846. function writeCsv(file, header, rows) {
  847. const head = Array.isArray(header) ? header : Object.keys(rows[0] || {});
  848. const lines = [head.join(',')];
  849. for (const r of rows) {
  850. // 支持两种行形态:数组(按表头顺序)或对象(键 = 表头文字)
  851. const cells = Array.isArray(r) ? r : head.map((k) => (r ? r[k] : ''));
  852. lines.push(cells.map(csvCell).join(','));
  853. }
  854. ensureDir(path.dirname(file));
  855. fs.writeFileSync(file, '\ufeff' + lines.join('\r\n'), 'utf8');
  856. return file;
  857. }
  858. function writeJson(file, obj) {
  859. ensureDir(path.dirname(file));
  860. fs.writeFileSync(file, JSON.stringify(obj, null, 2), 'utf8');
  861. return file;
  862. }
  863. // ------------------------------------------------------------------ 汇总口径
  864. /** 经营指标字段(historyOverview 返回值)*/
  865. const METRIC_KEYS = [
  866. 'valid_order_cnt', 'gross_amt', 'exp_uv', 'clk_exp_rate', 'ord_clk_rate',
  867. 'per_actual_pay', 'order_user_cnt', 'income_amt', 'expense_amt', 'shop_roi',
  868. ];
  869. /** 把逐日序列按指标求和/求均值,得到区间合计 */
  870. function summarize(daily) {
  871. const s = { days: daily.length };
  872. for (const k of METRIC_KEYS) s[k] = 0;
  873. let rateW = 0, rateD = 0;
  874. for (const r of daily) {
  875. for (const k of ['valid_order_cnt', 'gross_amt', 'exp_uv', 'order_user_cnt', 'income_amt', 'expense_amt']) {
  876. s[k] += Number(r[k]) || 0;
  877. }
  878. const uv = Number(r.exp_uv) || 0;
  879. if (uv > 0) {
  880. if (r.clk_exp_rate != null) { rateW += (Number(r.clk_exp_rate) || 0) * uv; rateD += uv; }
  881. }
  882. }
  883. s.clk_exp_rate = rateD > 0 ? +(rateW / rateD).toFixed(4) : 0;
  884. s.per_actual_pay = s.valid_order_cnt > 0 ? +(s.gross_amt / s.valid_order_cnt).toFixed(2) : 0;
  885. s.ord_clk_rate = s.exp_uv > 0 ? +(s.valid_order_cnt / s.exp_uv).toFixed(4) : 0;
  886. for (const k of ['gross_amt', 'income_amt', 'expense_amt']) s[k] = +s[k].toFixed(2);
  887. return s;
  888. }
  889. // ------------------------------------------------------------------ 便捷
  890. /** 状态体检(不含 MCP 目录,纯通道) */
  891. async function status(port = DEFAULT_PORT) {
  892. const p = await cdp.probe(port);
  893. const out = { port, portOk: p.ok, browser: p.ok ? p.version.Browser : null };
  894. if (p.ok) {
  895. try {
  896. const targets = (await cdp.listTargets(port)).filter((t) => t.webSocketDebuggerUrl);
  897. out.targets = targets.map((t) => `${t.type} | ${t.url}`);
  898. const ctxs = await cdp.withPageFor(port, 'shop', (api) => [...api.contexts.keys()], { autoOpen: false });
  899. out.contexts = ctxs;
  900. } catch (e) { out.probeError = String(e.message || e); }
  901. }
  902. return out;
  903. }
  904. module.exports = {
  905. DEFAULT_PORT, HISTORY_URL, HISTORY_METHOD, SALT, METRIC_KEYS, XTOP_BASE, STATS_BASE, MELODY_BASE, BUSY_LEVEL, AGW_BASE,
  906. md5, sign, getKsid, call, xtop, shopTree, statsHistory, statsApi, businessSummary, cityList, latestTime, status,
  907. melody, melodyReqId, orderAlerts, orderSetting, afterSaleHosting, orderTips,
  908. ensureApp, agwCred, agw, billRange, settleList, summarizeSettle,
  909. growthSummary, growthWeekly, growthTaskRate, growthBrands,
  910. channelIdentity, vas, vasReqId,
  911. cpsShopInfo, cpsRights, cpsContract, cpsAuthority, cpsAdGroup,
  912. promoBalance, promoLeafBalance, promoReport, silkBag,
  913. finResources, finShops, finSign,
  914. goodsInvoke, restaurantAttribute,
  915. normDay, dayDiff, today, daysAgo, msOf, ymd, ymdDash,
  916. ensureDir, writeCsv, writeJson, summarize,
  917. cdp,
  918. };