kit.js 44 KB

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