GamesPs.js 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540
  1. const axios = require('axios');
  2. const Logs = require('../libs/logs');
  3. const Cache = require('../libs/cache');
  4. const Setting = require('./Setting');
  5. const { eventSolutions } = require('../triangle/eventSolutions');
  6. const { getPassableEvents, eventsCombination } = require('../triangle/trangleCalc');
  7. const { calcTotalProfit, calcTotalProfitWithFixedFirst, getFirstInfo } = require('../triangle/totalProfitCalc');
  8. const { getSetting, updateSetting } = require('../triangle/settings');
  9. const fs = require('fs');
  10. const path = require('path');
  11. const GamesCacheFile = path.join(__dirname, '../data/games.cache');
  12. const childOptions = process.env.NODE_ENV == 'development' ? {
  13. execArgv: ['--inspect=9230'],
  14. stdio: ['pipe', 'pipe', 'pipe', 'ipc']
  15. } : {};
  16. const { fork } = require('child_process');
  17. const events_child = fork('./triangle/eventsMatch.js', [], childOptions);
  18. const PS_IOR_KEYS = [
  19. ['0', 'ior_mh', 'ior_mn', 'ior_mc'],
  20. ['-1', 'ior_rh_15', 'ior_wmh_1', 'ior_rac_05'],
  21. ['-2', 'ior_rh_25', 'ior_wmh_2', 'ior_rac_15'],
  22. ['-3', 'ior_rh_35', 'ior_wmh_3', 'ior_rac_25'],
  23. ['-4', 'ior_rh_45', 'ior_wmh_4', 'ior_rac_35'],
  24. ['-5', 'ior_rh_55', 'ior_wmh_5', 'ior_rac_45'],
  25. ['+1', 'ior_rah_05', 'ior_wmc_1', 'ior_rc_15'],
  26. ['+2', 'ior_rah_15', 'ior_wmc_2', 'ior_rc_25'],
  27. ['+3', 'ior_rah_25', 'ior_wmc_3', 'ior_rc_35'],
  28. ['+4', 'ior_rah_35', 'ior_wmc_4', 'ior_rc_45'],
  29. ['+5', 'ior_rah_45', 'ior_wmc_5', 'ior_rc_55'],
  30. ['jqs', 'ior_ot_1', 'ior_ot_2', 'ior_ot_3', 'ior_ot_4', 'ior_ot_5', 'ior_ot_6', 'ior_ot_7'],
  31. ];
  32. const IOR_KEYS_TYPE = {
  33. A: 1, L: 1,
  34. D: 2, K: 2,
  35. }
  36. // 测试环境
  37. // const BASE_API_URL = 'https://dev.api.czxd8.com/api/p';
  38. const IS_DEV = process.env.NODE_ENV == 'development';
  39. const BASE_API_URL = IS_DEV ? 'https://cb.long.bid/qbapi' : 'http://172.17.222.37/api';
  40. const GAMES = {
  41. Leagues: {},
  42. Baselist: {},
  43. Relations: {},
  44. Solutions: {},
  45. ObOriginalData: {},
  46. UpdateTimestamp: {},
  47. };
  48. const Request = {
  49. callbacks: {},
  50. count: 0,
  51. }
  52. /**
  53. * 精确浮点数字
  54. * @param {number} number
  55. * @param {number} x
  56. * @returns {number}
  57. */
  58. const fixFloat = (number, x=2) => {
  59. return parseFloat(number.toFixed(x));
  60. }
  61. /**
  62. * 获取市场类型
  63. */
  64. const getMarketType = (mk) => {
  65. if (mk == 0) {
  66. return 'early';
  67. }
  68. else if (mk == 2) {
  69. return 'rollball';
  70. }
  71. return 'today';
  72. }
  73. /**
  74. * 获取策略类型
  75. */
  76. const getRuleType = (rule) => {
  77. const rulePrefix = rule.split(':')[0];
  78. return IOR_KEYS_TYPE[rulePrefix];
  79. }
  80. /**
  81. * 关键词匹配比赛
  82. */
  83. const matchGame = (relation, sk) => {
  84. const keys = [];
  85. Object.keys(relation).forEach(platform => {
  86. const { leagueName, teamHomeName, teamAwayName } = relation[platform];
  87. if (platform == 'ps') {
  88. keys.push(leagueName);
  89. }
  90. keys.push(teamHomeName, teamAwayName);
  91. });
  92. return keys.some(key => key.includes(sk));
  93. }
  94. /**
  95. * 同步联赛列表
  96. */
  97. const syncLeaguesList = ({ mk, leagues }) => {
  98. if (IS_DEV) {
  99. return Logs.out('syncLeaguesList', { mk, leagues });
  100. }
  101. axios.post(`${BASE_API_URL}/p/syncLeague`, { mk, leagues }, { proxy: false })
  102. .then(res => {
  103. // Logs.out('syncLeaguesList', res.data);
  104. })
  105. .catch(err => {
  106. Logs.out('syncLeaguesList', err.message);
  107. });
  108. }
  109. /**
  110. * 更新联赛列表
  111. */
  112. const updateLeaguesList = ({ mk, leagues, platform='ps' }) => {
  113. const { Leagues } = GAMES;
  114. if (!Leagues[platform]) {
  115. Leagues[platform] = {};
  116. }
  117. const leaguesMap = Leagues[platform];
  118. const nowTime = Date.now();
  119. const expireTime = nowTime - 1000 * 60 * 5;
  120. if (!leaguesMap[mk]) {
  121. leaguesMap[mk] = {
  122. timestamp: 0,
  123. leagues: [],
  124. };
  125. }
  126. if (leaguesMap[mk].timestamp < expireTime ||
  127. JSON.stringify(leaguesMap[mk].leagues) != JSON.stringify(leagues)) {
  128. leaguesMap[mk].leagues = leagues;
  129. leaguesMap[mk].timestamp = nowTime;
  130. if (platform == 'ps') {
  131. syncLeaguesList({ mk, leagues });
  132. }
  133. return leagues.length;
  134. }
  135. return 0;
  136. }
  137. /**
  138. * 获取筛选过的联赛
  139. */
  140. const getFilteredLeagues = async (mk) => {
  141. return axios.get(`${BASE_API_URL}/p/getLeagueTast?mk=${mk ?? ''}`, { proxy: false })
  142. .then(res => {
  143. // Logs.out('getFilteredLeagues', res.data);
  144. if (res.data.code == 0) {
  145. return res.data.data;
  146. }
  147. return Promise.reject(new Error(res.data.message));
  148. });
  149. }
  150. /**
  151. * 更新OB原始数据
  152. */
  153. const updateOriginalData = ({ leagues, matches }) => {
  154. const { ObOriginalData } = GAMES;
  155. ObOriginalData.leagues = leagues;
  156. ObOriginalData.matches = matches;
  157. ObOriginalData.timestamp = Date.now();
  158. }
  159. /**
  160. * 获取OB原始数据
  161. */
  162. const getOriginalData = () => {
  163. const { ObOriginalData } = GAMES;
  164. return ObOriginalData;
  165. }
  166. /**
  167. * 同步比赛列表到服务器
  168. */
  169. const syncGamesList = ({ platform, mk, games }) => {
  170. if (IS_DEV) {
  171. return Logs.out('syncGamesList', { platform, mk, games });
  172. }
  173. axios.post(`${BASE_API_URL}/p/syncGames`, { platform, mk, games })
  174. .then(res => {
  175. // Logs.out('syncGamesList', { platform, mk, count: games.length }, res.data);
  176. })
  177. .catch(err => {
  178. Logs.out('syncGamesList', { platform, mk }, err.message);
  179. });
  180. }
  181. /**
  182. * 同步基准比赛列表
  183. */
  184. const syncBaseList = ({ marketType, games }) => {
  185. const baseList = GAMES.Baselist;
  186. // 直接创建新列表
  187. if (!baseList[marketType]) {
  188. baseList[marketType] = games;
  189. return;
  190. }
  191. const newMap = new Map(games.map(item => [item.eventId, item]));
  192. // 删除不存在的项
  193. for (let i = baseList[marketType].length - 1; i >= 0; i--) {
  194. if (!newMap.has(baseList[marketType][i].eventId)) {
  195. baseList[marketType].splice(i, 1);
  196. }
  197. }
  198. // 添加或更新
  199. const oldIds = new Set(baseList[marketType].map(item => item.eventId));
  200. games.forEach(game => {
  201. if (!oldIds.has(game.eventId)) {
  202. // 添加新项
  203. baseList[marketType].push(game);
  204. }
  205. });
  206. }
  207. /**
  208. * 清理基准比赛列表
  209. */
  210. // const cleanupBaseList = () => {
  211. // const baseList = GAMES.Baselist;
  212. // const nowTime = Date.now();
  213. // const expireTime = nowTime - 1000*60*60*3;
  214. // Object.keys(baseList).forEach(marketType => {
  215. // baseList[marketType] = baseList[marketType].filter(item => item.timestamp < expireTime);
  216. // });
  217. // }
  218. /**
  219. * 更新比赛列表
  220. */
  221. const updateGamesList = (({ platform, mk, games } = {}) => {
  222. return new Promise((resolve, reject) => {
  223. if (!platform || !games) {
  224. return reject(new Error('PLATFORM_GAMES_INVALID'));
  225. }
  226. syncGamesList({ platform, mk, games });
  227. resolve();
  228. });
  229. });
  230. /**
  231. * 提交盘口数据
  232. */
  233. // const submitOdds = ({ platform, mk, games }) => {
  234. // if (IS_DEV) {
  235. // return Logs.out('syncOdds', { platform, mk, games });
  236. // }
  237. // axios.post(`${BASE_API_URL}/p/syncOdds`, { platform, mk, games}, { proxy: false })
  238. // .then(res => {
  239. // // Logs.out('syncOdds', { platform, mk, count: games.length }, res.data);
  240. // })
  241. // .catch(err => {
  242. // Logs.out('syncOdds', { platform, mk }, err.message);
  243. // });
  244. // }
  245. /**
  246. * 同步基准盘口
  247. */
  248. const syncBaseEvents = ({ mk, games, outrights }) => {
  249. const {
  250. expireTimeEvents, expireTimeSpecial,
  251. subsidyTime, subsidyAmount,
  252. subsidyRbWmAmount, subsidyRbOtAmount
  253. } = getSetting();
  254. const nowTime = Date.now();
  255. const marketType = getMarketType(mk);
  256. const baseList = GAMES.Baselist;
  257. if (!baseList[marketType]) {
  258. return 0;
  259. }
  260. const baseMap = new Map(baseList[marketType].map(item => [item.eventId, item]));
  261. games?.forEach(game => {
  262. const { eventId, originId, stage, retime, score, wm, evtime, events } = game;
  263. const baseGame = baseMap.get(eventId);
  264. if (baseGame) {
  265. const { mk, timestamp } = baseGame;
  266. const isRb = (mk == 2);
  267. const isSubsidy = timestamp > nowTime && timestamp < nowTime + 1000*60*60*subsidyTime;
  268. Object.keys(events).forEach(ior => {
  269. // 滚球胜平负补水
  270. if (isRb && (ior.startsWith('ior_r') || ior.startsWith('ior_m') || ior.startsWith('ior_wm')) && subsidyRbWmAmount) {
  271. const sourceOdds = events[ior].v;
  272. events[ior].v = fixFloat(sourceOdds * (1 + subsidyRbWmAmount), 3);
  273. events[ior].s = sourceOdds
  274. }
  275. // 滚球进球数补水
  276. // API采集特殊盘口用
  277. else if (isRb && ior.startsWith('ior_ot') && subsidyRbOtAmount) {
  278. const sourceOdds = events[ior].v;
  279. events[ior].v = fixFloat(sourceOdds * (1 + subsidyRbOtAmount), 3);
  280. events[ior].s = sourceOdds
  281. }
  282. // 赛前进球数补水
  283. // API采集特殊盘口用
  284. else if (!isRb && isSubsidy && ior.startsWith('ior_ot') && subsidyAmount) {
  285. const sourceOdds = events[ior].v;
  286. events[ior].v = fixFloat(sourceOdds * (1 + subsidyAmount), 3);
  287. events[ior].s = sourceOdds
  288. }
  289. });
  290. baseGame.originId = originId;
  291. baseGame.stage = stage;
  292. baseGame.retime = retime;
  293. baseGame.score = score;
  294. baseGame.wm = wm;
  295. baseGame.evtime = evtime;
  296. baseGame.events = events;
  297. }
  298. });
  299. // 浏览器采集特殊盘口用的
  300. // outrights?.forEach(outright => {
  301. // const { parentId, sptime, special } = outright;
  302. // const baseGame = baseMap.get(parentId);
  303. // if (baseGame) { // 赛前特殊盘口
  304. // const { timestamp } = baseGame;
  305. // const isSubsidy = timestamp > nowTime && timestamp < nowTime + 1000*60*60*subsidyTime;
  306. // if (isSubsidy) {
  307. // Object.keys(special).forEach(ior => {
  308. // if (ior.startsWith('ior_ot') && subsidyAmount) {
  309. // const sourceOdds = special[ior].v;
  310. // special[ior].v = fixFloat(sourceOdds * (1 + subsidyAmount), 3);
  311. // special[ior].s = sourceOdds
  312. // }
  313. // });
  314. // }
  315. // baseGame.sptime = sptime;
  316. // baseGame.special = special;
  317. // }
  318. // else {
  319. // const originBaseMap = new Map(baseList[marketType].map(item => [item.originId, item]));
  320. // const originBaseGame = originBaseMap.get(parentId);
  321. // if (originBaseGame) { // 滚球特殊盘口
  322. // Object.keys(special).forEach(ior => {
  323. // if (ior.startsWith('ior_wm') && subsidyRbWmAmount) {
  324. // const sourceOdds = special[ior].v;
  325. // special[ior].v = fixFloat(sourceOdds * (1 + subsidyRbWmAmount), 3);
  326. // special[ior].s = sourceOdds
  327. // }
  328. // else if (ior.startsWith('ior_ot') && subsidyRbOtAmount) {
  329. // const sourceOdds = special[ior].v;
  330. // special[ior].v = fixFloat(sourceOdds * (1 + subsidyRbOtAmount), 3);
  331. // special[ior].s = sourceOdds
  332. // }
  333. // });
  334. // originBaseGame.sptime = sptime;
  335. // originBaseGame.special = special;
  336. // }
  337. // }
  338. // });
  339. if (games?.length) {
  340. const gamesList = baseList[marketType]?.map(game => {
  341. const { evtime, events, sptime, special, ...gameInfo } = game;
  342. const expireTimeEv = nowTime - expireTimeEvents;
  343. const expireTimeSP = nowTime - expireTimeSpecial;
  344. let odds = {};
  345. if (evtime > expireTimeEv) {
  346. odds = { ...odds, ...events };
  347. }
  348. if (sptime > expireTimeSP) {
  349. odds = { ...odds, ...special };
  350. }
  351. const matches = PS_IOR_KEYS.map(([label, ...keys]) => {
  352. let match = keys.map(key => {
  353. return {
  354. key,
  355. value: odds[key]?.v ?? 0,
  356. origin: odds[key]?.r,
  357. source: odds[key]?.s,
  358. }
  359. });
  360. if (label == 'jqs') {
  361. match = match.filter(item => item.value !== 0);
  362. }
  363. return {
  364. label,
  365. match
  366. };
  367. }).filter(item => {
  368. if (item.label == 'jqs') {
  369. return item.match.length;
  370. }
  371. else {
  372. return item.match.every(entry => entry.value !== 0);
  373. }
  374. });
  375. game.matches = matches; // matches 也记录下来
  376. let uptime = evtime ?? 0;
  377. return { ...gameInfo, matches, uptime };
  378. });
  379. // if (gamesList.filter(item => item.uptime > 0).length) {
  380. // // if (mk == 2) {
  381. // // Logs.out('syncBaseEvents', JSON.stringify({ mk, gamesList }, null, 2));
  382. // // }
  383. // submitOdds({ platform: 'ps', mk, games: gamesList });
  384. // }
  385. const relatedGames = Object.values(GAMES.Relations).map(item => item.rel?.['ps'] ?? {});
  386. if (!relatedGames.length) {
  387. return 0;
  388. }
  389. let update = 0;
  390. const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
  391. gamesList?.forEach(game => {
  392. const { eventId, matches, uptime, stage, retime, score, wm } = game;
  393. const relatedGame = relatedMap.get(eventId);
  394. if (relatedGame) {
  395. const events = {};
  396. matches.forEach(({ label, match }) => {
  397. match.forEach(({ key, value, origin, source }) => {
  398. events[key] = {
  399. v: value,
  400. r: origin,
  401. s: source
  402. };
  403. });
  404. });
  405. relatedGame.evtime = uptime;
  406. relatedGame.events = events;
  407. relatedGame.stage = stage;
  408. relatedGame.retime = retime;
  409. relatedGame.score = score;
  410. relatedGame.wm = wm;
  411. update ++;
  412. }
  413. });
  414. return update;
  415. }
  416. }
  417. const updateBaseEvents = ({ games, timestamp, tp='ps_9_9_1' }) => {
  418. return new Promise((resolve, reject) => {
  419. if (!games) {
  420. return reject(new Error('GAMES_INVALID'));
  421. }
  422. if (!timestamp) {
  423. return reject(new Error('TIMESTAMP_INVALID'));
  424. }
  425. let update = 0;
  426. const { UpdateTimestamp } = GAMES;
  427. if (!UpdateTimestamp[tp] || UpdateTimestamp[tp] < timestamp) {
  428. UpdateTimestamp[tp] = timestamp;
  429. }
  430. else {
  431. return resolve({ update });
  432. }
  433. Object.keys(games).forEach(mk => {
  434. update += syncBaseEvents({ mk, games: games[mk] ?? [] });
  435. });
  436. resolve({ update });
  437. });
  438. }
  439. /**
  440. * 比较外盘与内盘的赔率
  441. */
  442. const compareOdds = (events, baseEvents, platform) => {
  443. const setting = getSetting();
  444. const maxDiff = setting[`${platform}MaxDiff`] ?? 0;
  445. Object.keys(events).forEach(ior => {
  446. const value = events[ior].v;
  447. const baseValue = baseEvents[ior]?.s ?? baseEvents[ior]?.v ?? 1;
  448. if (value - baseValue >= maxDiff) {
  449. events[ior].q = 1;
  450. }
  451. else {
  452. events[ior].q = 0;
  453. }
  454. });
  455. }
  456. const updateGamesEvents = ({ platform, mk, games, outrights, timestamp, tp }) => {
  457. return new Promise((resolve, reject) => {
  458. if (!platform || (!games && !outrights)) {
  459. return reject(new Error('PLATFORM_GAMES_INVALID'));
  460. }
  461. const { UpdateTimestamp } = GAMES;
  462. if (!UpdateTimestamp[tp] || UpdateTimestamp[tp] < timestamp) {
  463. // Logs.out('updateGamesEvents', { tp, timestamp });
  464. UpdateTimestamp[tp] = timestamp;
  465. }
  466. else {
  467. return resolve({ update: 0 });
  468. }
  469. if (platform == 'ps') {
  470. const update = syncBaseEvents({ mk, games, outrights });
  471. return resolve({ update });
  472. }
  473. const relatedGames = Object.values(GAMES.Relations).map(item => {
  474. // item.rel?.[platform] ?? {}
  475. const { rel } = item ?? {};
  476. if (!rel) {
  477. return {};
  478. }
  479. const game = rel[platform] ?? {};
  480. game.baseId = rel['ps']?.eventId;
  481. return game;
  482. });
  483. if (!relatedGames.length) {
  484. return resolve({ update: 0 });
  485. }
  486. const updateCount = {
  487. update: 0
  488. };
  489. const marketType = getMarketType(mk);
  490. const baseList = GAMES.Baselist[marketType] ?? [];
  491. const baseMap = new Map(baseList.map(item => [item.eventId, item]));
  492. const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
  493. games?.forEach(game => {
  494. const { eventId, evtime, events, stage, retime, score, wm } = game;
  495. const relatedGame = relatedMap.get(eventId);
  496. if (!relatedGame) {
  497. return;
  498. }
  499. const baseEvents = baseMap.get(relatedGame.baseId)?.events ?? {};
  500. compareOdds(events, baseEvents, platform);
  501. if (relatedGame) {
  502. relatedGame.evtime = evtime;
  503. relatedGame.events = events;
  504. relatedGame.stage = stage;
  505. relatedGame.retime = retime;
  506. relatedGame.score = score;
  507. relatedGame.wm = wm;
  508. updateCount.update ++;
  509. }
  510. });
  511. outrights?.forEach(outright => {
  512. const { parentId, sptime, special } = outright;
  513. const relatedGame = relatedMap.get(parentId);
  514. if (!relatedGame) {
  515. return;
  516. }
  517. const baseEvents = baseMap.get(relatedGame.baseId)?.events ?? {};
  518. compareOdds(special, baseEvents, platform);
  519. if (relatedGame) {
  520. relatedGame.sptime = sptime;
  521. relatedGame.special = special;
  522. updateCount.update ++;
  523. }
  524. });
  525. resolve(updateCount);
  526. });
  527. }
  528. /**
  529. * 获取比赛盘口
  530. */
  531. const getGamesEvents = ({ platform, relIds = [] } = {}) => {
  532. if (!relIds.length) {
  533. return null;
  534. }
  535. const idSet = new Set(relIds);
  536. const relations = { ...GAMES.Relations };
  537. Object.keys(relations).forEach(id => {
  538. if (idSet.size && !idSet.has(+id)) {
  539. delete relations[id];
  540. }
  541. });
  542. if (platform) {
  543. return Object.values(relations).map(rel => rel[platform] ?? {});
  544. }
  545. const gamesEvents = {};
  546. Object.values(relations).forEach(({ rel }) => {
  547. Object.keys(rel).forEach(platform => {
  548. const game = rel[platform] ?? {};
  549. const { eventId, events, special } = game;
  550. if (!gamesEvents[platform]) {
  551. gamesEvents[platform] = {};
  552. }
  553. gamesEvents[platform][eventId] = { ...events, ...special };
  554. });
  555. });
  556. return gamesEvents;
  557. }
  558. /**
  559. * 获取远程关联比赛列表
  560. */
  561. const fetchGamesRelation = async (mk='') => {
  562. return axios.get(`${BASE_API_URL}/p/getGameTast?mk=${mk}`, {
  563. proxy: false
  564. }).then(({ data: resData }) => {
  565. if (resData.code == 0) {
  566. const nowTime = Date.now();
  567. const gamesRelation = resData.data?.filter?.((item) => {
  568. const timestamp = new Date(item.timestamp).getTime();
  569. const updated = new Date(item.updated_at).getTime();
  570. if (nowTime > timestamp) {
  571. item.mk = 2;
  572. }
  573. item.timestamp = timestamp;
  574. item.updated = updated;
  575. const expireTime = timestamp + 1000*60*60*3;
  576. return expireTime > nowTime;
  577. }).map(item => {
  578. const {
  579. id, mk, league_name,
  580. event_id: ps_event_id,
  581. league_id: ps_league_id,
  582. team_home_name: ps_team_home_name,
  583. team_away_name: ps_team_away_name,
  584. ob_event_id, ob_league_id,
  585. ob_team_home_name,
  586. ob_team_away_name,
  587. hg_event_id, hg_league_id,
  588. hg_team_home_name,
  589. hg_team_away_name,
  590. im_event_id, im_league_id,
  591. im_team_home_name,
  592. im_team_away_name,
  593. updated,
  594. timestamp,
  595. } = item;
  596. const rel = {
  597. ps: {
  598. eventId: +ps_event_id,
  599. leagueId: +ps_league_id,
  600. leagueName: league_name,
  601. teamHomeName: ps_team_home_name,
  602. teamAwayName: ps_team_away_name,
  603. timestamp
  604. },
  605. ob: ob_event_id ? {
  606. eventId: +ob_event_id,
  607. leagueId: +ob_league_id,
  608. leagueName: league_name,
  609. teamHomeName: ob_team_home_name,
  610. teamAwayName: ob_team_away_name,
  611. timestamp
  612. } : null,
  613. hg: hg_event_id ? {
  614. eventId: +hg_event_id,
  615. leagueId: +hg_league_id,
  616. leagueName: league_name,
  617. teamHomeName: hg_team_home_name,
  618. teamAwayName: hg_team_away_name,
  619. timestamp
  620. } : null,
  621. im: im_event_id ? {
  622. eventId: +im_event_id,
  623. leagueId: +im_league_id,
  624. leagueName: league_name,
  625. teamHomeName: im_team_home_name,
  626. teamAwayName: im_team_away_name,
  627. timestamp
  628. } : null
  629. };
  630. return { id: ps_event_id, mk, rel, timestamp, updated };
  631. }) ?? [];
  632. return gamesRelation;
  633. }
  634. return Promise.reject(new Error(resData.message));
  635. });
  636. }
  637. /**
  638. * 获取PC数据
  639. */
  640. const getPCEvents = (events) => {
  641. if (!events) {
  642. return undefined;
  643. }
  644. const pcEvents = {};
  645. Object.keys(events).forEach(ior => {
  646. const { v, s, r } = events[ior];
  647. pcEvents[ior] = {
  648. v: s ?? v,
  649. r: r
  650. }
  651. });
  652. return pcEvents;
  653. }
  654. const getPCData = (id) => {
  655. const baseList = Object.values(GAMES.Baselist).flat();
  656. const baseMap = new Map(baseList.map(item => [item.eventId, item]));
  657. const baseGame = baseMap.get(id);
  658. if (!baseGame) {
  659. return null;
  660. }
  661. const { matches, events, special, ...gameInfo } = baseGame;
  662. return {
  663. events: getPCEvents(events),
  664. special: getPCEvents(special),
  665. ...gameInfo
  666. }
  667. }
  668. /**
  669. * 获取关联比赛列表
  670. * @param {object} options
  671. * @property {number} mk
  672. * @property {number[]} ids
  673. * @property {boolean} listEvents
  674. * @property {boolean} listPC
  675. * @returns {object[]}
  676. */
  677. const getGamesRelation = ({ mk=-1, ids, listEvents=false, listPC=false } = {}) => {
  678. let relations;
  679. if (ids?.length) {
  680. relations = ids.map(id => GAMES.Relations[id]);
  681. }
  682. else {
  683. relations = Object.values(GAMES.Relations);
  684. }
  685. relations = relations.filter(item => !!item && (mk == -1 || item.mk == mk)).sort((a, b) => a.timestamp - b.timestamp);
  686. if (listEvents && !listPC) {
  687. return relations;
  688. }
  689. return relations.map(item => {
  690. const { rel, ...relationInfo } = item;
  691. const tempRel = { ...rel };
  692. const { id } = relationInfo;
  693. if (listPC) {
  694. tempRel.pc = getPCData(id);
  695. }
  696. if (!listEvents) {
  697. Object.keys(tempRel).forEach(platform => {
  698. const { events, evtime, special, sptime, ...gameInfo } = tempRel[platform] ?? {};
  699. tempRel[platform] = gameInfo;
  700. });
  701. }
  702. return { ...relationInfo, rel: tempRel };
  703. });
  704. }
  705. /**
  706. * 定时更新关联比赛列表
  707. */
  708. const updateGamesRelation = () => {
  709. fetchGamesRelation()
  710. .then(gamesRelation => {
  711. // Logs.out('updateGamesRelation', gamesRelation);
  712. const baseList = {};
  713. gamesRelation.map(item => {
  714. const baseGame = item.rel?.['ps'] ?? {};
  715. return { ...baseGame, mk: item.mk };
  716. }).forEach(item => {
  717. const marketType = getMarketType(item.mk);
  718. if (!baseList[marketType]) {
  719. baseList[marketType] = [];
  720. }
  721. baseList[marketType].push(item);
  722. });
  723. Object.keys(baseList).forEach(marketType => {
  724. syncBaseList({ marketType, games: baseList[marketType] });
  725. });
  726. const updateCount = {
  727. add: 0,
  728. update: 0,
  729. delete: 0
  730. };
  731. gamesRelation.forEach(item => {
  732. const { id, mk, updated } = item;
  733. const oldItem = GAMES.Relations[id];
  734. if (!oldItem) {
  735. GAMES.Relations[id] = item;
  736. updateCount.add ++;
  737. }
  738. else if (oldItem.mk != mk) {
  739. GAMES.Relations[id] = item;
  740. updateCount.update ++;
  741. }
  742. else if ((oldItem.updated ?? -1) < updated) {
  743. GAMES.Relations[id] = item;
  744. updateCount.update ++;
  745. }
  746. });
  747. const relations = new Set(gamesRelation.map(item => +item.id));
  748. Object.keys(GAMES.Relations).forEach(id => {
  749. if (!relations.has(+id)) {
  750. delete GAMES.Relations[id];
  751. updateCount.delete ++;
  752. }
  753. });
  754. if (updateCount.add || updateCount.update || updateCount.delete) {
  755. Logs.out('updateGamesRelation', updateCount);
  756. }
  757. else {
  758. Logs.outDev('updateGamesRelation', updateCount);
  759. }
  760. })
  761. .catch(err => {
  762. Logs.out('updateGamesRelation', err.message);
  763. })
  764. .finally(() => {
  765. setTimeout(updateGamesRelation, 60000);
  766. });
  767. }
  768. updateGamesRelation();
  769. const gamesRelationCleanup = () => {
  770. const relations = Object.values(GAMES.Relations);
  771. const expireTime = Date.now() - 1000*60;
  772. relations.forEach(item => {
  773. const { rel } = item;
  774. Object.keys(rel).forEach(platform => {
  775. const { evtime=0, sptime=0 } = rel[platform] ?? {};
  776. if (evtime && evtime < expireTime) {
  777. delete rel[platform].events;
  778. delete rel[platform].evtime;
  779. }
  780. if (sptime && sptime < expireTime) {
  781. delete rel[platform].special;
  782. delete rel[platform].sptime;
  783. }
  784. });
  785. });
  786. }
  787. /**
  788. * 同步比赛结果
  789. */
  790. const syncGamesResult = async (result) => {
  791. if (IS_DEV) {
  792. return Logs.out('updateGamesResult', result);
  793. }
  794. // axios.post(`${BASE_API_URL}/p/syncMatchResult`, result, { proxy: false })
  795. // .then(res => {
  796. // // Logs.out('syncMatchResult', res.data);
  797. // })
  798. // .catch(err => {
  799. // Logs.out('syncMatchResult', err.message);
  800. // });
  801. }
  802. /**
  803. * 更新比赛结果
  804. */
  805. const updateGamesResult = (result) => {
  806. syncGamesResult(result);
  807. return Promise.resolve();
  808. }
  809. /**
  810. * 同步中单方案
  811. */
  812. // const syncSolutions = (solutions) => {
  813. // if (IS_DEV) {
  814. // return Logs.out('syncSolutions', solutions);
  815. // }
  816. // axios.post(`${BASE_API_URL}/p/syncDsOpportunity`, solutions, { proxy: false })
  817. // .then(res => {
  818. // // Logs.out('syncSolutions', res.data);
  819. // })
  820. // .catch(err => {
  821. // Logs.out('syncSolutions', err.message);
  822. // });
  823. // }
  824. /**
  825. * 更新中单方案
  826. */
  827. const getCprKey = (cpr) => {
  828. const { k, p, v, q } = cpr;
  829. return `${k}_${p}_${v}_${q}`;
  830. }
  831. const compareCpr = (cpr1, cpr2) => {
  832. const key1 = getCprKey(cpr1);
  833. const key2 = getCprKey(cpr2);
  834. return key1 === key2;
  835. }
  836. const updateSolutions = (solutions, eventsLogsMap) => {
  837. if (solutions?.length) {
  838. const solutionsHistory = GAMES.Solutions;
  839. const updateIds = { add: [], update: [], retain: [], remove: [] }
  840. solutions.forEach(item => {
  841. const { sid, cpr, sol: { win_average, win_profit_rate } } = item;
  842. if (!solutionsHistory[sid]) {
  843. solutionsHistory[sid] = item;
  844. updateIds.add.push(sid);
  845. return;
  846. }
  847. const historySolution = solutionsHistory[sid];
  848. if (historySolution.sol.win_average !== win_average ||
  849. historySolution.sol.win_profit_rate !== win_profit_rate ||
  850. !compareCpr(historySolution.cpr, cpr)) {
  851. solutionsHistory[sid] = item;
  852. updateIds.update.push(sid);
  853. return;
  854. }
  855. const { timestamp } = item;
  856. historySolution.timestamp = timestamp;
  857. updateIds.retain.push(sid);
  858. });
  859. const solutionsMap = new Map(solutions.map(item => [item.sid, item]));
  860. Object.keys(solutionsHistory).forEach(sid => {
  861. if (!solutionsMap.has(sid)) {
  862. delete solutionsHistory[sid];
  863. updateIds.remove.push(sid);
  864. }
  865. });
  866. // const solutionUpdate = {};
  867. // Object.keys(updateIds).forEach(key => {
  868. // if (key == 'retain' || key == 'remove') {
  869. // solutionUpdate[key] = updateIds[key];
  870. // }
  871. // else {
  872. // solutionUpdate[key] = updateIds[key].map(sid => solutionsHistory[sid]);
  873. // }
  874. // });
  875. // syncSolutions(solutionUpdate);
  876. if (updateIds.add.length / solutions.length > 0.2 ||
  877. updateIds.remove.length / solutions.length > 0.2
  878. ) {
  879. const { expireEvents, removeEvents } = eventsLogsMap;
  880. const expireEvemtsMap = {};
  881. expireEvents.forEach(item => {
  882. const { mk, platform, info, evExpire, spExpire, evtime, sptime } = item;
  883. if (!expireEvemtsMap[mk]) {
  884. expireEvemtsMap[mk] = {};
  885. }
  886. if (!expireEvemtsMap[mk][platform]) {
  887. expireEvemtsMap[mk][platform] = {};
  888. }
  889. if (!expireEvemtsMap[mk][platform].list) {
  890. expireEvemtsMap[mk][platform].list = [];
  891. }
  892. if (!expireEvemtsMap[mk][platform].evtime) {
  893. expireEvemtsMap[mk][platform].evtime = evtime;
  894. }
  895. if (!expireEvemtsMap[mk][platform].sptime) {
  896. expireEvemtsMap[mk][platform].sptime = sptime;
  897. }
  898. expireEvemtsMap[mk][platform].list.push({ info, evExpire, spExpire, evtime, sptime });
  899. });
  900. Object.keys(expireEvemtsMap).forEach(mk => {
  901. Object.keys(expireEvemtsMap[mk]).forEach(platform => {
  902. Logs.out('invalid events, mk %d, platform %s, expire %d, evtime %d, sptime %d',
  903. mk, platform,
  904. expireEvemtsMap[mk][platform].list.length,
  905. expireEvemtsMap[mk][platform].evtime,
  906. expireEvemtsMap[mk][platform].sptime,
  907. )
  908. });
  909. });
  910. Logs.out('solutions add %d, update %d, retain %d, remove %d',
  911. updateIds.add.length, updateIds.update.length, updateIds.retain.length, updateIds.remove.length);
  912. }
  913. else {
  914. Logs.outDev('solutions update complete', updateIds);
  915. }
  916. }
  917. }
  918. /**
  919. * 获取中单方案
  920. */
  921. const getSolutions = async ({ win_min, with_events, show_lower=false, mk=-1 }) => {
  922. // Logs.out('getSolutions', win_min);
  923. const filterMarketType = +mk;
  924. const { minShowAmount } = getSetting();
  925. const solutionsList = Object.values(GAMES.Solutions);
  926. const gamesRelation = getGamesRelation();
  927. const relationsMap = new Map(gamesRelation.map(item => [item.id, item]));
  928. const mkCount = {
  929. all: 0,
  930. rollball: 0,
  931. today: 0,
  932. early: 0,
  933. }
  934. let solutions = solutionsList.filter(item => {
  935. const { sol: { win_average }, lower } = item;
  936. if (!show_lower && lower) {
  937. return false;
  938. }
  939. return win_average >= (win_min ?? minShowAmount);
  940. })
  941. .map(item => {
  942. const { info: { id } } = item;
  943. const { mk, rel } = relationsMap.get(id);
  944. const marketType = getMarketType(mk);
  945. mkCount.all ++;
  946. mkCount[marketType] ++;
  947. return {
  948. ...item,
  949. info: { id, mk, ...rel }
  950. }
  951. });
  952. if (mk >= 0) {
  953. solutions = solutions.filter(item => {
  954. const { info: { mk } } = item;
  955. return mk == filterMarketType;
  956. });
  957. }
  958. solutions = solutions.sort((a, b) => b.sol.win_average - a.sol.win_average);
  959. const relIds = solutions.map(item => item.info.id);
  960. let gamesEvents;
  961. if (with_events) {
  962. gamesEvents = getGamesEvents({ relIds });
  963. }
  964. return { solutions, gamesEvents, mkCount };
  965. }
  966. /**
  967. * 获取中单方案并按照比赛分组
  968. */
  969. const getGamesSolutions = async ({ win_min, with_events, show_lower=false, mk=-1, tp=0, sk }) => {
  970. const filterMarketType = +mk;
  971. const filterDataType = +tp;
  972. const { minShowAmount } = getSetting();
  973. const solutionsList = Object.values(GAMES.Solutions);
  974. const gamesRelation = getGamesRelation({ listEvents: with_events });
  975. const relationsMap = new Map(gamesRelation.map(item => [item.id, item]));
  976. const mkCount = {
  977. all: 0,
  978. rollball: 0,
  979. today: 0,
  980. early: 0,
  981. }
  982. const solutionsMap = {};
  983. solutionsList.forEach(item => {
  984. const { info: { id }, ...solution } = item;
  985. const { rule, sol: { win_average }, lower } = solution;
  986. const ruleType = getRuleType(rule);
  987. if (!show_lower && lower) {
  988. return false;
  989. }
  990. if ((filterDataType == 0 || filterDataType == ruleType) && (!!sk || win_average >= (win_min ?? minShowAmount))) {
  991. const gameRelation = relationsMap.get(id);
  992. if (!solutionsMap[id]) {
  993. solutionsMap[id] = { ...gameRelation, solutions: [] };
  994. }
  995. solutionsMap[id].solutions.push(solution);
  996. }
  997. })
  998. const gamesSolutions = Object.values(solutionsMap)
  999. .filter(item => {
  1000. const { mk, rel, solutions } = item;
  1001. const marketType = getMarketType(mk);
  1002. if (!sk || matchGame(rel, sk)) {
  1003. mkCount.all ++;
  1004. mkCount[marketType] ++;
  1005. solutions.sort((a, b) => b.sol.win_average - a.sol.win_average);
  1006. return filterMarketType == -1 || filterMarketType == mk;
  1007. }
  1008. return false;
  1009. })
  1010. .sort((a, b) => b.solutions[0].sol.win_average - a.solutions[0].sol.win_average);
  1011. return { gamesSolutions, mkCount };
  1012. }
  1013. /**
  1014. * 获取单个中单方案
  1015. */
  1016. const getSolution = async (sid) => {
  1017. if (!sid) {
  1018. return Promise.reject(new Error('sid is required'));
  1019. }
  1020. const solution = GAMES.Solutions[sid];
  1021. if (!solution) {
  1022. return Promise.reject(new Error('solution not found'));
  1023. }
  1024. return solution;
  1025. }
  1026. /**
  1027. * 通过比赛 ID 获取中单方案
  1028. */
  1029. const getSolutionsByIds = async (ids) => {
  1030. const baseList = Object.values(GAMES.Baselist).flat();
  1031. const baseMap = new Map(baseList.map(item => [item.eventId, item]));
  1032. const result = {};
  1033. ids.forEach(id => {
  1034. const baseGame = baseMap.get(id);
  1035. result[id] = {};
  1036. result[id].matches = baseGame?.matches ?? [];
  1037. result[id].sols = [];
  1038. });
  1039. Object.values(GAMES.Solutions).forEach(item => {
  1040. const { info: { id }, lower } = item;
  1041. if (result[id] && !lower) {
  1042. result[id].sols.push(item);
  1043. }
  1044. });
  1045. return result;
  1046. }
  1047. /**
  1048. * 清理中单方案
  1049. */
  1050. const solutionsCleanup = () => {
  1051. const solutionsHistory = GAMES.Solutions;
  1052. const updateIds = { remove: [] }
  1053. Object.keys(solutionsHistory).forEach(sid => {
  1054. const { timestamp } = solutionsHistory[sid];
  1055. const nowTime = Date.now();
  1056. if (nowTime - timestamp > 1000*60) {
  1057. delete solutionsHistory[sid];
  1058. updateIds.remove.push(sid);
  1059. return;
  1060. }
  1061. const solution = solutionsHistory[sid];
  1062. const eventTime = solution.info.timestamp;
  1063. if (nowTime > eventTime) {
  1064. delete solutionsHistory[sid];
  1065. updateIds.remove.push(sid);
  1066. }
  1067. });
  1068. // if (updateIds.remove.length) {
  1069. // syncSolutions(updateIds);
  1070. // }
  1071. }
  1072. /**
  1073. * 清理更新时间戳
  1074. */
  1075. const cleanupUpdateTimestamp = () => {
  1076. const updateTimestamp = GAMES.UpdateTimestamp;
  1077. const nowTime = Date.now();
  1078. const expireTime = nowTime - 1000*60;
  1079. Object.keys(updateTimestamp).forEach(key => {
  1080. if (updateTimestamp[key] < expireTime) {
  1081. delete updateTimestamp[key];
  1082. }
  1083. });
  1084. }
  1085. /**
  1086. * 定时清理中单方案
  1087. * 定时清理盘口信息
  1088. */
  1089. setInterval(() => {
  1090. // cleanupBaseList();
  1091. solutionsCleanup();
  1092. gamesRelationCleanup();
  1093. cleanupUpdateTimestamp();
  1094. }, 1000*30);
  1095. /**
  1096. * 获取综合利润
  1097. */
  1098. const getTotalProfit = async (sol1, sol2, inner_base, inner_rebate) => {
  1099. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  1100. inner_base = inner_base ? +inner_base : innerDefaultAmount;
  1101. inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  1102. const profit = calcTotalProfit(sol1, sol2, inner_base, inner_rebate);
  1103. return profit;
  1104. }
  1105. /**
  1106. * 通过 sid 获取综合利润
  1107. */
  1108. const getTotalProfitWithSid = async (sid1, sid2, inner_base, inner_rebate) => {
  1109. const preSolution = GAMES.Solutions[sid1];
  1110. const subSolution = GAMES.Solutions[sid2];
  1111. const sol1 = preSolution?.sol;
  1112. const sol2 = subSolution?.sol;
  1113. if (!sol1) {
  1114. return Promise.reject(new Error('sid1 已失效'));
  1115. }
  1116. if (!sol2) {
  1117. return Promise.reject(new Error('sid2 已失效'));
  1118. }
  1119. const profit = await getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  1120. return { profit, solutions: [preSolution, subSolution] };
  1121. }
  1122. /**
  1123. * 通过盘口信息获取综合利润
  1124. */
  1125. const getTotalProfitWithBetInfo = async (betInfo1, betInfo2, fixed=false, inner_base, inner_rebate) => {
  1126. if (!betInfo1?.cross_type) {
  1127. return Promise.reject(new Error('第一个下注信息无效'));
  1128. }
  1129. if (!betInfo2?.cross_type) {
  1130. return Promise.reject(new Error('第二个下注信息无效'));
  1131. }
  1132. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  1133. inner_base = typeof(inner_base) != 'undefined' ? +inner_base : innerDefaultAmount;
  1134. inner_rebate = typeof(inner_rebate) != 'undefined' ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  1135. if (fixed) {
  1136. return calcTotalProfitWithFixedFirst(betInfo1, betInfo2, inner_base, inner_rebate);
  1137. }
  1138. const [sol1, sol2] = [betInfo1, betInfo2].map(betinfo => eventSolutions({...betinfo, inner_base, inner_rebate }));
  1139. return getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  1140. }
  1141. /**
  1142. * 计算补单综合利润
  1143. */
  1144. const getTotalReplacement = async (data) => {
  1145. const { event_id, inner_ior, inner_odds, pre_bet_info } = data;
  1146. if (!event_id) {
  1147. Logs.out('getTotalReplacement event_id 无效', data);
  1148. return Promise.reject(new Error('event_id 无效'));
  1149. }
  1150. if (!inner_ior) {
  1151. Logs.out('getTotalReplacement inner_ior 无效', data);
  1152. return Promise.reject(new Error('inner_ior 无效'));
  1153. }
  1154. if (isNaN(+inner_odds)) {
  1155. Logs.out('getTotalReplacement inner_odds 无效', data);
  1156. return Promise.reject(new Error('inner_odds 无效'));
  1157. }
  1158. if (!pre_bet_info || typeof(pre_bet_info) !== 'object') {
  1159. Logs.out('getTotalReplacement pre_bet_info 无效', data);
  1160. return Promise.reject(new Error('pre_bet_info 无效'));
  1161. }
  1162. const { loss_out, inner_ref_value: inner_base, inner_odds: inner_odds_first } = getFirstInfo(pre_bet_info);
  1163. const { innerRebateRatio } = getSetting();
  1164. const inner_rebate = typeof(data.inner_rebate) != 'undefined' ? +data.inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  1165. const inner_odds_value = fixFloat(inner_odds * (inner_odds_first+1), 3);
  1166. const relation = getGamesRelation({ ids: [event_id], listEvents: true, listPC: true }).map(item => {
  1167. const { rel, ...relationInfo } = item;
  1168. const tempRel = { ...rel };
  1169. const events = {};
  1170. events[inner_ior] = { v: inner_odds_value };
  1171. tempRel.ps = { ...rel.ps, events }
  1172. return { ...relationInfo, rel: tempRel };
  1173. });
  1174. if (!relation?.length) {
  1175. Logs.out('getTotalReplacement 没有找到对应的比赛 data %o, relation %o', data, relation);
  1176. return Promise.reject(new Error('没有找到对应的比赛'));
  1177. }
  1178. const passableEvents = getPassableEvents(relation, null);
  1179. const solutions = eventsCombination(passableEvents, inner_base, inner_rebate);
  1180. if (!solutions?.length) {
  1181. Logs.out('getTotalReplacement 没有可用的解决方案 data %o, relation %o, passableEvents %o, solutions %o', data, relation, passableEvents, solutions);
  1182. return Promise.reject(new Error('没有可用的解决方案'));
  1183. }
  1184. Logs.out('getTotalReplacement, event_id[%d], inner_ior[%s], solutions[%d]', event_id, inner_ior, solutions.length);
  1185. // 过滤 .filter(solution => !solution.lower)
  1186. return solutions.map(solution => {
  1187. const { sid, info, sol, ...solutionInfo } = solution;
  1188. const { win_profit_rate, win_average_rate, ...solInfo } = sol;
  1189. const { cross_type } = solInfo;
  1190. solInfo.win_side_a = typeof(solInfo.win_side_a) !== 'number' ? undefined : fixFloat(solInfo.win_side_a - loss_out);
  1191. solInfo.win_side_b = typeof(solInfo.win_side_b) !== 'number' ? undefined : fixFloat(solInfo.win_side_b - loss_out);
  1192. solInfo.win_side_c = cross_type == 'la_wa_rv' ? 0 : (typeof(solInfo.win_side_c) !== 'number' ? undefined : fixFloat(solInfo.win_side_c - loss_out));
  1193. solInfo.win_average = fixFloat(solInfo.win_average - loss_out);
  1194. return { ...solutionInfo, sol: solInfo };
  1195. });
  1196. }
  1197. /**
  1198. * 同步Qboss平台配置
  1199. */
  1200. const syncQbossConfig = () => {
  1201. const setting = getSetting();
  1202. if (!setting.syncSettingEnabled) {
  1203. // Logs.outDev('syncQbossConfig disabled');
  1204. return setTimeout(syncQbossConfig, 1000*5);
  1205. }
  1206. axios.get(`${BASE_API_URL}/p/QbossSystemConfig`, { proxy: false })
  1207. .then(res => {
  1208. const { data } = res;
  1209. Logs.outDev('syncQbossConfig', data);
  1210. if (!data?.data) {
  1211. throw new Error('syncQbossConfig data is empty');
  1212. }
  1213. const {
  1214. qboss_return_ratio,
  1215. ob_return_ratio, ob_return_type, ob_odds_more_than,
  1216. im_return_ratio, im_return_type, im_odds_more_than,
  1217. hg_return_ratio, hg_return_type, hg_odds_more_than,
  1218. pc_return_ratio, pc_return_type,
  1219. qboss_jq_add_odds, qboss_jq_add_hours,
  1220. qboss_gq_add_dy_odds, qboss_gq_add_jq_odds,
  1221. } = data.data;
  1222. const qbossSetting = {
  1223. innerRebateRatio: qboss_return_ratio ? +qboss_return_ratio : 0,
  1224. obRebateRatio: ob_return_ratio ? +ob_return_ratio : 0,
  1225. obRebateType: ob_return_type ? +ob_return_type : 0,
  1226. obMaxDiff: ob_odds_more_than ? +ob_odds_more_than : 0,
  1227. imRebateRatio: im_return_ratio ? +im_return_ratio : 0,
  1228. imRebateType: im_return_type ? +im_return_type : 0,
  1229. imMaxDiff: im_odds_more_than ? +im_odds_more_than : 0,
  1230. hgRebateRatio: hg_return_ratio ? +hg_return_ratio : 0,
  1231. hgRebateType: hg_return_type ? +hg_return_type : 0,
  1232. hgMaxDiff: hg_odds_more_than ? +hg_odds_more_than : 0,
  1233. pcRebateRatio: pc_return_ratio ? +pc_return_ratio : 0,
  1234. pcRebateType: pc_return_type ? +pc_return_type : 0,
  1235. subsidyTime: qboss_jq_add_hours ? +qboss_jq_add_hours : 0,
  1236. subsidyAmount: qboss_jq_add_odds ? +qboss_jq_add_odds : 0,
  1237. subsidyRbWmAmount: qboss_gq_add_dy_odds ? +qboss_gq_add_dy_odds : 0,
  1238. subsidyRbOtAmount: qboss_gq_add_jq_odds ? +qboss_gq_add_jq_odds : 0,
  1239. };
  1240. Logs.outDev('syncQbossConfig', qbossSetting);
  1241. const settingFields = {};
  1242. let needUpdate = false;
  1243. Object.keys(qbossSetting).forEach(key => {
  1244. if (qbossSetting[key] !== setting[key]) {
  1245. settingFields[key] = qbossSetting[key];
  1246. needUpdate = true;
  1247. }
  1248. });
  1249. if (needUpdate) {
  1250. Setting.update(settingFields);
  1251. // Logs.outDev('syncQbossConfig', settingFields);
  1252. }
  1253. // else {
  1254. // Logs.outDev('syncQbossConfig no change');
  1255. // }
  1256. })
  1257. .catch(err => {
  1258. Logs.out('syncQbossConfig error', err.message);
  1259. })
  1260. .finally(() => {
  1261. setTimeout(syncQbossConfig, 1000*15);
  1262. });
  1263. }
  1264. syncQbossConfig();
  1265. /**
  1266. * 异常通知
  1267. */
  1268. const notifyException = (message) => {
  1269. if (IS_DEV) {
  1270. return Logs.out('notifyException', { message });
  1271. }
  1272. const chat_id = -1003032820471;
  1273. axios.get(`${BASE_API_URL}/telegram/jump`, { params: { chat_id, message } }, { proxy: false })
  1274. .then(() => {
  1275. Logs.out('notifyException', '通知成功');
  1276. })
  1277. .catch(err => {
  1278. Logs.out('notifyException', err.message);
  1279. });
  1280. }
  1281. /**
  1282. * 从子进程获取数据
  1283. */
  1284. const getDataFromChild = (type, callback) => {
  1285. const id = ++Request.count;
  1286. Request.callbacks[id] = callback;
  1287. events_child.send({ method: 'get', id, type });
  1288. }
  1289. /**
  1290. * 向子进程发送数据
  1291. */
  1292. const postDataToChild = (type, data) => {
  1293. events_child.send({ method: 'post', type, data });
  1294. }
  1295. /**
  1296. * 处理子进程消息
  1297. */
  1298. events_child.on('message', async (message) => {
  1299. const { callbacks } = Request;
  1300. const { method, id, type, data } = message;
  1301. if (method == 'get' && id) {
  1302. let responseData = null;
  1303. if (type == 'getGamesRelation') {
  1304. responseData = getGamesRelation({ listEvents: true });
  1305. }
  1306. else if (type == 'getSetting') {
  1307. responseData = getSetting();
  1308. }
  1309. // else if (type == 'getSolutionHistory') {
  1310. // responseData = getSolutionHistory();
  1311. // }
  1312. events_child.send({ type: 'response', id, data: responseData });
  1313. }
  1314. else if (method == 'post') {
  1315. if (type == 'updateSolutions') {
  1316. updateSolutions(data.solutions, data.eventsLogsMap);
  1317. }
  1318. }
  1319. else if (method == 'response' && id && callbacks[id]) {
  1320. callbacks[id](data);
  1321. delete callbacks[id];
  1322. }
  1323. });
  1324. events_child.stderr?.on('data', data => {
  1325. Logs.out('events_child stderr', data.toString());
  1326. });
  1327. const settingUpdate = (fields) => {
  1328. updateSetting(fields);
  1329. postDataToChild('updateSetting', fields);
  1330. }
  1331. const syncSetting = async () => {
  1332. const setting = await Setting.get();
  1333. settingUpdate(setting.toObject());
  1334. }
  1335. syncSetting();
  1336. Setting.onUpdate(settingUpdate);
  1337. /**
  1338. * 保存GAMES数据到缓存文件
  1339. */
  1340. const saveGamesToCache = () => {
  1341. Cache.setData(GamesCacheFile, GAMES, err => {
  1342. if (err) {
  1343. Logs.out('Failed to save games cache:', err.message);
  1344. }
  1345. else {
  1346. Logs.out('Games cache saved successfully');
  1347. }
  1348. });
  1349. }
  1350. /**
  1351. * 从缓存文件加载GAMES数据
  1352. */
  1353. const loadGamesFromCache = () => {
  1354. const gamesCacheData = Cache.getData(GamesCacheFile, true) ?? {};
  1355. Object.keys(GAMES).forEach(key => {
  1356. if (key in gamesCacheData) {
  1357. GAMES[key] = gamesCacheData[key];
  1358. }
  1359. });
  1360. Logs.out('Games cache loaded successfully');
  1361. }
  1362. // 在模块加载时尝试从缓存恢复数据
  1363. loadGamesFromCache();
  1364. // 监听进程退出事件,保存GAMES数据
  1365. process.on('exit', saveGamesToCache);
  1366. process.on('SIGINT', () => {
  1367. process.exit(0);
  1368. });
  1369. process.on('SIGTERM', () => {
  1370. process.exit(0);
  1371. });
  1372. process.on('SIGUSR2', () => {
  1373. process.exit(0);
  1374. });
  1375. module.exports = {
  1376. updateLeaguesList, getFilteredLeagues,
  1377. updateGamesList, updateGamesEvents, updateBaseEvents,
  1378. getGamesRelation,
  1379. updateGamesResult,
  1380. updateOriginalData, getOriginalData,
  1381. getSolutions, getGamesSolutions, getSolution, getSolutionsByIds,
  1382. getTotalProfitWithSid, getTotalProfitWithBetInfo, getTotalReplacement,
  1383. notifyException,
  1384. }