kit.js 47 KB

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