server_data_statisticsv2.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. const logger = require('./logger')
  2. var remote_config_db = require("./db/remote_config_db");
  3. var collect_coins_db = require("./db/collect_coins_db");
  4. var withdraw_db = require("./db/withdraw_db");
  5. var moralis = require("./moralis_sdk");
  6. var utils = require("./utils");
  7. const axios = require('axios');
  8. var { account_config } = require('../config/config.js');
  9. const { max } = require('moment');
  10. const redis = require('./db/redis_db');
  11. // 拿到飞书写入的 token
  12. const feishu_write_table_token_url = 'https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal'
  13. const feishu_write_table_data_url = 'https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/shtcnp6zbrsep1Sz3Cvk7NXRpDg/values_batch_update'
  14. const feishu_insert_table_url = 'https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/shtcnp6zbrsep1Sz3Cvk7NXRpDg/insert_dimension_range'
  15. const feishu_delete_table_url = 'https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/shtcnp6zbrsep1Sz3Cvk7NXRpDg/dimension_range'
  16. const feishu_get_table_metadata_url = 'https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/shtcnp6zbrsep1Sz3Cvk7NXRpDg/metainfo'
  17. const feishu_create_table_url = 'https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/shtcnp6zbrsep1Sz3Cvk7NXRpDg/dimension_range'
  18. const mTokenPriceCache = new Map()
  19. const mDecimalsCache = new Map()
  20. //########################################### 出入金数据统计 ########################################
  21. const http_request_get = async (data) => {
  22. var host = account_config.STATISTICS_URL
  23. // host = 'https://api.denetme.net/denet/wallet/stat/getMoneyStat?date='
  24. var path = data
  25. var url = host + path
  26. logger.log('http_request_get', url)
  27. return new Promise(response => {
  28. axios.get(url)
  29. .then(res => {
  30. logger.log('res=>', res.status, res.data);
  31. if (res.data.code == 0) {
  32. response(res.data)
  33. } else {
  34. response({
  35. code: 0,
  36. msg: err.toString(),
  37. data: {
  38. canNotWithdrawUSD: '0',
  39. canWithdrawUSD: '0',
  40. incomeUSDTotal: '0',
  41. incomeUSDFee: '0'
  42. }
  43. })
  44. }
  45. }).catch(err => {
  46. logger.error('http_request_get', err.toString(), url.toString());
  47. response({
  48. code: -1,
  49. msg: err.toString(),
  50. data: {
  51. canNotWithdrawUSD: '0',
  52. canWithdrawUSD: '0',
  53. incomeUSDTotal: '0',
  54. incomeUSDFee: '0'
  55. }
  56. })
  57. });
  58. })
  59. }
  60. function getBscEnv() {
  61. var bsc_env
  62. switch (process.env.NODE_ENV) {
  63. case 'dev':
  64. case 'test':
  65. bsc_env = 'bsc_testnet'
  66. bsc_env = 'bsc_mainnet'
  67. break
  68. case 'prd':
  69. bsc_env = 'bsc_mainnet'
  70. break
  71. default:
  72. bsc_env = 'bsc_mainnet'
  73. break
  74. }
  75. return bsc_env;
  76. }
  77. async function findCurBalance(type, address) {
  78. var balances
  79. var price
  80. var tokenItems = []
  81. switch (type) {
  82. case 'bsc':
  83. balances = await moralis.getAccountAllCoins({
  84. chain: getBscEnv(),
  85. address: address
  86. })
  87. // price = await moralis.getAllTotkenPrice({ chain: getBscEnv() })
  88. price = await getPrice(getBscEnv())
  89. break
  90. case 'czz':
  91. balances = await moralis.getAccountAllCoins({
  92. chain: 'czz',
  93. address: address
  94. })
  95. price = await getPrice('czz')
  96. // price = await moralis.getAllTotkenPrice({ chain: 'czz' })
  97. break
  98. }
  99. logger.info('findCurBalance', type, address, balances, price)
  100. if (typeof price === 'string') {
  101. price = JSON.parse(price)
  102. }
  103. if (!balances || !price) return null
  104. priceItem = moralis.findTokenPriceItem('0x0000000000000000000000000000000000000000', price)
  105. if (!balances.native.balance) {
  106. balances.native.balance = '0'
  107. }
  108. if (balances.native) {
  109. balances.native.usdPrice = parseFloat(balances.native.balance) / parseFloat(10 ** 18) * priceItem.usdPrice
  110. logger.info('findTokenPriceItem 0x0000000000000000000000000000000000000000 ', balances, priceItem, type)
  111. var bo = {
  112. address: address,
  113. token_address: '0x0000000000000000000000000000000000000000',
  114. chain: type,
  115. amount: balances.native.balance,
  116. decimals: 18,
  117. price: priceItem.usdPrice,
  118. usd: balances.native.usdPrice
  119. }
  120. tokenItems.push(bo)
  121. }
  122. if (balances.other && Array.isArray(balances.other)) {
  123. for (let index = 0; index < balances.other.length; index++) {
  124. const element = balances.other[index];
  125. priceItem = moralis.findTokenPriceItem(element.token_address, price)
  126. logger.info('findTokenPriceItem element ', priceItem, element.token_address)
  127. if (priceItem) {
  128. if (!element.decimals || element.decimals == 0)
  129. element.decimals = 18
  130. element.usdPrice = parseFloat(element.balance) / parseFloat(10 ** element.decimals) * priceItem.usdPrice
  131. var bo = {
  132. address: address,
  133. token_address: element.token_address,
  134. chain: type,
  135. amount: element.balance,
  136. decimals: element.decimals,
  137. price: priceItem.usdPrice,
  138. usd: element.usdPrice
  139. }
  140. tokenItems.push(bo)
  141. }
  142. }
  143. }
  144. logger.debug('tokenUsds', tokenItems, type)
  145. return {
  146. nativeUsd: balances.native.usdPrice,
  147. tokenUsds: tokenItems,
  148. totalUsd: addUsds(tokenItems, 'token_balance')
  149. }
  150. }
  151. async function getAllBalanceV2() {
  152. var company = await moralis.queryCompanyInfoFromId(0)
  153. logger.info('getAllBalance company', company)
  154. var bsc_balances = await findCurBalance('bsc', company.user_address)
  155. var czz_balances = await findCurBalance('czz', company.user_address)
  156. logger.info('findCurBalance bsc_balances', bsc_balances)
  157. logger.info('findCurBalance czz_balances', czz_balances)
  158. let lists = bsc_balances.tokenUsds.concat(czz_balances.tokenUsds);
  159. return {
  160. bsc: bsc_balances,
  161. czz: czz_balances,
  162. infos: lists,
  163. totalUsd: bsc_balances.totalUsd + czz_balances.totalUsd,
  164. totalNativeBalanceUsd: bsc_balances.nativeUsd + czz_balances.nativeUsd
  165. }
  166. }
  167. function parseGas(response, index, price) {
  168. try {
  169. logger.info('parseGas in', response, index)
  170. if (response && Array.isArray(response) && response.length > 0) {
  171. var obj
  172. if (response[index] && typeof response[index] === 'string')
  173. try {
  174. obj = JSON.parse(response[index])
  175. } catch (error) {
  176. logger.error('JSON.parse(response[index])', error.toString)
  177. }
  178. return parseFloat(obj.gasPrice.number) * parseFloat(obj.gasLimit.number) / parseFloat(10 ** 18) * parseFloat(price)
  179. }
  180. else return 0
  181. } catch (error) {
  182. logger.error('parseGas', error.toString(), JSON.stringify(response))
  183. return 0
  184. }
  185. }
  186. async function getPrice(key) {
  187. if (mTokenPriceCache.has(key)) {
  188. price = mTokenPriceCache.get(key)
  189. } else {
  190. var price = await moralis.getAllTotkenPrice({
  191. chain: key
  192. })
  193. if (typeof price === 'string') {
  194. price = JSON.parse(price)
  195. }
  196. mTokenPriceCache.set(key, price)
  197. }
  198. return price
  199. }
  200. async function getPriceFromCache(key, address) {
  201. console.info('getPriceFromCache>', key, address)
  202. var price = await getPrice(key)
  203. // var price = await moralis.getAllTotkenPrice({
  204. // chain: key
  205. // })
  206. // if (typeof price === 'string') {
  207. // price = JSON.parse(price)
  208. // }
  209. var priceItem = moralis.findTokenPriceItem(address, price)
  210. if (priceItem && priceItem.usdPrice) {
  211. return priceItem.usdPrice
  212. } else {
  213. return '0'
  214. }
  215. }
  216. function convertChain(chain) {
  217. return chain
  218. }
  219. function balance2USDPrice(amount, decimals, price) {
  220. return parseFloat(amount) / parseFloat(10 ** decimals) * parseFloat(price)
  221. }
  222. async function getDecimalsFromRedis(chain, address) {
  223. var decimals = 18
  224. try {
  225. var newKey = redis.formatRedisKey('REDIS_ERC20_CONTRACT_DECIMALS', chain, address.toLowerCase())
  226. if (mDecimalsCache.has(newKey)) {
  227. decimals = mDecimalsCache.get(newKey)
  228. } else {
  229. decimals = await redis.readAppendRedis('REDIS_ERC20_CONTRACT_DECIMALS', chain, address.toLowerCase())
  230. mDecimalsCache.set(newKey, decimals)
  231. }
  232. if (!decimals) decimals = '18'
  233. } catch (error) {
  234. logger.error('getDecimalsFromRedis', chain, address, error.toString())
  235. decimals = 18
  236. }
  237. return decimals
  238. }
  239. function addUsds(infos, type) {
  240. var total = 0
  241. if (infos && Array.isArray(infos) && infos.length > 0) {
  242. for (let index = 0; index < infos.length; index++) {
  243. const element = infos[index];
  244. switch (type) {
  245. case 'gas':
  246. // logger.info('addUsds total ', type, element.gasUsd, element, total)
  247. total += element.gasUsd
  248. break
  249. case 'withdraw':
  250. total += element.withdrawUsd
  251. break
  252. case 'collect_coins':
  253. total += element.withdrawUsd
  254. break
  255. case 'slGas':
  256. total += element.slGasUsd
  257. break
  258. case 'token_balance':
  259. total += element.usd
  260. break
  261. case 'native_in_coins':
  262. if (element.token_address && element.token_address == '0x0000000000000000000000000000000000000000')
  263. total += element.inUsd
  264. break
  265. case 'native_token_in_coins':
  266. total += element.inUsd
  267. break
  268. }
  269. }
  270. }
  271. return total
  272. }
  273. async function getWithdrawOutInfoV2(startTime, endTime) {
  274. if (startTime && endTime) {
  275. startTime = new Date(startTime).getTime()
  276. endTime = new Date(endTime).getTime()
  277. }
  278. if (!startTime && endTime) {
  279. startTime = 0
  280. endTime = new Date(endTime).getTime()
  281. }
  282. var withdraw_ret = await withdraw_db.getWidthdrawTotalFee(startTime, endTime)
  283. var withDrawInfos = []
  284. for (let index = 0; index < withdraw_ret.length; index++) {
  285. const trs = withdraw_ret[index];
  286. // console.log('getWithdrawOutInfoV2 element ', trs)
  287. var token_address = trs.contract_address
  288. if (!trs.contract_address)
  289. token_address = '0x0000000000000000000000000000000000000000'
  290. try {
  291. var input = {
  292. dt: utils.chinaTimeMs(trs.update_time),
  293. user_address: trs.to_address,
  294. token_address: token_address,
  295. chain: convertChain(trs.chain_id + ""),
  296. amount: trs.amount,
  297. decimals: await getDecimalsFromRedis(convertChain(trs.chain_id + ""), token_address),
  298. price: await getPriceFromCache(convertChain(trs.chain_id + ""), token_address),
  299. gasUsd: parseFloat(trs.gas_price) * parseFloat(trs.gas_limit) / parseFloat(10 ** 18) * await getPriceFromCache(convertChain(trs.chain_id + ""), '0x0000000000000000000000000000000000000000')
  300. }
  301. if (!input.gasUsd) {
  302. logger.info('withdraw_ret input ', trs, input)
  303. input.gasUsd = 0
  304. }
  305. //换算成美元
  306. input.withdrawUsd = balance2USDPrice(input.amount, input.decimals, input.price)
  307. console.log('getWithdrawOutInfoV2 input ', input)
  308. withDrawInfos.push(input)
  309. } catch (error) {
  310. logger.error('getWithdrawOutInfoV2 trs', error.toString())
  311. }
  312. }
  313. // logger.log('getWithdrawOutInfoV2 totalOutGasFeeUsd addUsds', addUsds(withDrawInfos, 'gas'), withDrawInfos[0], withDrawInfos[1])
  314. return {
  315. infos: withDrawInfos,
  316. totalOutGasFeeUsd: addUsds(withDrawInfos, 'gas'),
  317. totalWithdrawUsd: addUsds(withDrawInfos, 'withdraw'),
  318. }
  319. }
  320. async function getCollectCoinsOutInfoV2(startTime, endTime) {
  321. var collect_ret = await collect_coins_db.query_collect_total_fee(startTime, endTime);
  322. // console.log('getCollectCoinsOutInfoV2 collect_ret', collect_ret.results.length)
  323. //每笔入金的详细信息
  324. var infos = []
  325. //入金充值的 gas 和实际消费的 gas
  326. var inGasFeeInfo = []
  327. if (collect_ret && collect_ret.results && Array.isArray(collect_ret.results) && collect_ret.results.length > 0) {
  328. for (let index = 0; index < collect_ret.results.length; index++) {
  329. var element = collect_ret.results[index]
  330. if (!element.chain)
  331. element.chain = 'bsc_mainnet'
  332. var update_tm = element.update_time
  333. var user_address = element.user_address
  334. // console.log('getCollectCoinsOutInfoV2 element', element.before_gas_fee, element.resposes, typeof element.resposes, JSON.parse(element.resposes))
  335. var resposes;
  336. if (element.resposes && typeof element.resposes === 'string') {
  337. try {
  338. resposes = JSON.parse(element.resposes)
  339. } catch (error) {
  340. logger.error('element.response parse', error.toString())
  341. }
  342. }
  343. if (element.prestore_gas_fee && typeof element.prestore_gas_fee === 'string') {
  344. try {
  345. var gasObj = JSON.parse(element.prestore_gas_fee)
  346. var before_gas_fee = element.before_gas_fee ? element.before_gas_fee : '0'
  347. if (gasObj) {
  348. // logger.log('element.prestore_gas_fee parse', before_gas_fee, gasObj, gasObj.chain)
  349. var newGasObj = {
  350. chain: convertChain(gasObj.chain),
  351. amount: gasObj.amount,
  352. useGas: before_gas_fee,
  353. price: await getPriceFromCache(convertChain(gasObj.chain), '0x0000000000000000000000000000000000000000'),
  354. }
  355. //实际充值手续费用到的 usd
  356. newGasObj.gasUsd = balance2USDPrice(newGasObj.useGas, 18, newGasObj.price)
  357. //散落 gas
  358. newGasObj.slGasUsd = balance2USDPrice(parseFloat(newGasObj.amount) - parseFloat(newGasObj.useGas), 18, newGasObj.price)
  359. inGasFeeInfo.push(newGasObj)
  360. }
  361. } catch (error) {
  362. logger.error('element.prestore_gas_fee parse', error.toString())
  363. }
  364. }
  365. if (element.transfers && typeof element.transfers === 'string') {
  366. try {
  367. var trss = JSON.parse(element.transfers)
  368. // console.log('trss.transfers', trss.chain)
  369. for (let index = 0; index < trss.length; index++) {
  370. const trs = trss[index];
  371. var address = trs.contractAddress == null ? '0x0000000000000000000000000000000000000000' : trs.contractAddress
  372. console.log('trss.transfers', address, trs)
  373. var input = {
  374. dt: update_tm,
  375. user_address: user_address,
  376. token_address: address,
  377. chain: convertChain(trs.chain),
  378. amount: trs.amount,
  379. decimals: trs.contractAddress == null ? 18 : await getDecimalsFromRedis(convertChain(trs.chain), trs.contractAddress),
  380. price: await getPriceFromCache(convertChain(trs.chain), address),
  381. gasUsd: parseGas(resposes, index, await getPriceFromCache(convertChain(trs.chain), '0x0000000000000000000000000000000000000000')) //入金 gas 手续费
  382. }
  383. //换算成美元
  384. input.inUsd = balance2USDPrice(input.amount, input.decimals, input.price)
  385. infos.push(input)
  386. }
  387. } catch (error) {
  388. logger.error('transfers handle error', error.toString())
  389. }
  390. }
  391. }
  392. }
  393. return {
  394. infos: infos,
  395. totalNativeInFee: addUsds(infos, 'native_in_coins'), //总 native 入金
  396. totalInFee: addUsds(infos, 'native_token_in_coins'), //总入金
  397. totalInGasFeeUsd: addUsds(infos, 'gas') + addUsds(inGasFeeInfo, 'gas'),//总入金消耗的 gas 包含打 gas fee
  398. slTotalGasFeeUsd: addUsds(inGasFeeInfo, 'slGas') //散落 gas
  399. }
  400. }
  401. async function getServerData(startTime, endTime) {
  402. //拿到所有归集 list
  403. var collectCoinsInfos = await getCollectCoinsOutInfoV2(startTime, endTime)
  404. // console.log('getCollectCoinsOutInfoV2 collectCoinsInfos ', collectCoinsInfos)
  405. //拿到所有出金
  406. var withdrawInfos = await getWithdrawOutInfoV2(startTime, endTime)
  407. // console.log('getWithdrawOutInfoV2 withdrawInfos ', withdrawInfos)
  408. return {
  409. collectCoinsInfos: collectCoinsInfos,
  410. withdrawInfos: withdrawInfos
  411. }
  412. }
  413. function sortList(lists) {
  414. lists.sort((a, b) => {
  415. let t1 = new Date(a.dt)
  416. let t2 = new Date(b.dt)
  417. return t2.getTime() - t1.getTime()
  418. })
  419. return lists
  420. }
  421. function formatTableData(type, datas) {
  422. var arrs = []
  423. for (let index = 0; index < datas.length; index++) {
  424. const element = datas[index];
  425. switch (type) {
  426. case 'incoins':
  427. arrs.push([element.dt,
  428. element.user_address,
  429. element.token_address,
  430. element.chain,
  431. element.amount,
  432. element.decimals,
  433. element.price,
  434. element.gasUsd,
  435. element.inUsd
  436. ])
  437. break;
  438. case 'outcoins':
  439. arrs.push([element.dt,
  440. element.user_address,
  441. element.token_address,
  442. element.chain,
  443. element.amount,
  444. element.decimals,
  445. element.price,
  446. element.gasUsd,
  447. element.withdrawUsd
  448. ])
  449. break
  450. case 'balances':
  451. arrs.push([element.address,
  452. element.token_address,
  453. element.chain,
  454. element.amount,
  455. element.decimals,
  456. element.price,
  457. element.usd
  458. ])
  459. break
  460. default:
  461. break;
  462. }
  463. }
  464. logger.info('formatTableData', arrs)
  465. return arrs
  466. }
  467. async function getStatisticsInfoV2(day) {
  468. // //今日
  469. var startTime = utils.getLastDay(day, 'YYYY-MM-DD') + " 00:00:00"
  470. var endTime = utils.getLastDay(day, 'YYYY-MM-DD') + " 23:59:59"
  471. logger.info('getTotalOutGasFee', startTime, endTime)
  472. var rangeData = await getServerData(startTime, endTime)
  473. logger.info('getServerData rangeData', rangeData)
  474. var allData = await getServerData(null, endTime)
  475. // var allData = rangeData
  476. logger.info('getServerData allData', allData)
  477. var data = await http_request_get(utils.getLastDay(day, 'YYYYMMDD'))
  478. logger.info('http_request_get data', data)
  479. //获取当前账户总余额
  480. var curBalances = await getAllBalanceV2()
  481. logger.info('getAllBalanceV2 curBalances', curBalances)
  482. return {
  483. updateTime: utils.getLastDay(day, 'YYYY-MM-DD'),
  484. todayTotalProfit: parseFloat(data.data.incomeUSDTotal) - parseFloat(rangeData.collectCoinsInfos.totalInGasFeeUsd + rangeData.withdrawInfos.totalOutGasFeeUsd),//今日收入
  485. todayTotalOutGasFee: rangeData.collectCoinsInfos.totalInGasFeeUsd + rangeData.withdrawInfos.totalOutGasFeeUsd,//今日总支出的 gas fee
  486. canNotWithdrawUSD: parseFloat(data.data.canNotWithdrawUSD), //不可提现余额
  487. canWithdrawUSD: parseFloat(data.data.canWithdrawUSD), //可提现余额
  488. todayIncomeUSDTotal: parseFloat(data.data.incomeUSDTotal), //今日总收入
  489. todayIncomeUSDFee: parseFloat(data.data.incomeUSDFee), //今日固定收入
  490. totalOutGasFee: allData.collectCoinsInfos.totalInGasFeeUsd + allData.withdrawInfos.totalOutGasFeeUsd, //总支出 gas fee
  491. totalWithdrawGasFee: allData.withdrawInfos.totalOutGasFeeUsd, //总提币 gas fee
  492. totalCollectCoinsGasFee: allData.collectCoinsInfos.totalInGasFeeUsd, //总归集 gas fee
  493. totalInFee: allData.collectCoinsInfos.totalInFee, //总入金
  494. totalNativeInFee: allData.collectCoinsInfos.totalNativeInFee, //总 native 入金
  495. totalOutFee: allData.withdrawInfos.totalWithdrawUsd, //总出金
  496. totalBalances: curBalances.totalUsd, //总余额
  497. ylGasBalance: curBalances.totalNativeBalanceUsd - allData.collectCoinsInfos.totalNativeInFee, //预留 gas 费余额 native 总余额 - 总入金
  498. slGasBalance: allData.collectCoinsInfos.slTotalGasFeeUsd, //散落 gas 费余额 充值 0.5 gas - 使用 0.3 gas= 散落 0.2gas
  499. todayInUsdLists: sortList(rangeData.collectCoinsInfos.infos),//入金列表
  500. todayOutUsdLists: sortList(rangeData.withdrawInfos.infos),//出金列表
  501. totalInUsdLists: sortList(allData.collectCoinsInfos.infos),//总入金列表
  502. totalOutUsdLists: sortList(allData.withdrawInfos.infos),//总出金列表
  503. totalBalanceLists: curBalances.infos //总余额
  504. }
  505. }
  506. const getFeishuToken = async (params) => {
  507. return new Promise(resolve => {
  508. axios.post(feishu_write_table_token_url,
  509. {
  510. app_id: "cli_a223f015abbad00e",
  511. app_secret: "DMCF6tBwIpeOQPnWrFUMYd6tmjb53C4n"
  512. },
  513. {
  514. timeout: 1 * 60 * 1000,
  515. headers: {
  516. 'Content-Type': "application/json; charset=utf-8"
  517. }
  518. })
  519. .then(res => {
  520. logger.log('getFeishuToken res=>', res.status, res.data);
  521. resolve(res.data)
  522. }).catch(err => {
  523. logger.error('getFeishuToken error ', JSON.stringify(err));
  524. resolve(JSON.stringify(err))
  525. });
  526. })
  527. }
  528. function formatTableRangle(id, size) {
  529. var newId = id + size
  530. logger.info('formatTableRangle', id, size, newId)
  531. return newId
  532. }
  533. async function writeTable(app_token, data) {
  534. logger.info('writeTable', data)
  535. var valueRanges = []
  536. if (data.todayInUsdLists.length > 0) {
  537. await insertTableRows(app_token, 'Ji1hLG', 1, data.todayInUsdLists.length + 1)
  538. valueRanges.push({//入金汇总
  539. 'range': formatTableRangle('Ji1hLG!A2:I', data.todayInUsdLists.length + 1),
  540. 'values': formatTableData('incoins', data.todayInUsdLists)
  541. })
  542. }
  543. if (data.todayOutUsdLists.length > 0) {
  544. await insertTableRows(app_token, 'aFCrrP', 1, data.todayOutUsdLists.length + 1)
  545. valueRanges.push({//出金汇总
  546. 'range': formatTableRangle('aFCrrP!A2:I', data.todayOutUsdLists.length + 1),
  547. 'values': formatTableData('outcoins', data.todayOutUsdLists)
  548. })
  549. }
  550. if (data.totalBalanceLists.length > 0) {
  551. var rows = await getTableRows(app_token, 2)
  552. if (rows > 1) {
  553. logger.info('getTableRows', rows)
  554. await delTableRows(app_token, '2hNaot', 2, rows)
  555. await addTableRows(app_token, '2hNaot', rows)
  556. }
  557. valueRanges.push({ //总余额汇总
  558. 'range': formatTableRangle('2hNaot!A2:I', data.totalBalanceLists.length + 1),
  559. 'values': formatTableData('balances', data.totalBalanceLists)
  560. })
  561. }
  562. valueRanges.push({//归集汇总
  563. 'range': formatTableRangle('0pRQpu!A2:C', 2),
  564. 'values': [
  565. [data.totalCollectCoinsGasFee, //归集总 gas
  566. data.totalWithdrawGasFee, //提币总 gas
  567. data.totalOutGasFee], //总支出 gas
  568. ]
  569. })
  570. valueRanges.push({//总入账
  571. 'range': formatTableRangle('1ygrMB!A2:B', 2),
  572. 'values': [
  573. [
  574. data.totalInFee, //总入金
  575. data.totalOutFee,//总出金
  576. ]
  577. ]
  578. })
  579. valueRanges.push({//利润表单
  580. 'range': formatTableRangle('BMjMDr!A3:J', 3),
  581. 'values': [
  582. [
  583. data.updateTime, //更新时间
  584. data.todayTotalProfit,//今日总利润
  585. data.todayIncomeUSDTotal,//今日总收入
  586. data.todayIncomeUSDFee,//今日固定手续费收入
  587. data.todayTotalOutGasFee,//今日总 gas 支出
  588. data.totalBalances, //总余额
  589. data.canNotWithdrawUSD, //不可提现余额
  590. data.canWithdrawUSD,//可提现余额
  591. data.ylGasBalance,//预留 gas
  592. data.slGasBalance,//散落 gas
  593. ],
  594. ]
  595. })
  596. var body = {
  597. 'valueRanges': valueRanges
  598. }
  599. return new Promise(resolve => {
  600. axios.post(feishu_write_table_data_url,
  601. body,
  602. {
  603. timeout: 1 * 60 * 1000,
  604. headers: {
  605. 'Content-Type': "application/json; charset=utf-8",
  606. 'Authorization': 'Bearer ' + app_token
  607. }
  608. })
  609. .then(res => {
  610. logger.log('writeTable res=>', res.status, res.data);
  611. resolve(res.data)
  612. }).catch(err => {
  613. logger.error('writeTable error ', JSON.stringify(err));
  614. resolve(JSON.stringify(err))
  615. });
  616. })
  617. }
  618. async function getTableRows(app_token, index) {
  619. return new Promise(resolve => {
  620. axios.get(feishu_get_table_metadata_url,
  621. {
  622. timeout: 1 * 60 * 1000,
  623. headers: {
  624. 'Content-Type': "application/json; charset=utf-8",
  625. 'Authorization': 'Bearer ' + app_token
  626. }
  627. })
  628. .then(res => {
  629. console.log('res=>', res.status, res.data, res.data.data.sheets);
  630. resolve(res.data.data.sheets[index].rowCount)
  631. }).catch(err => {
  632. logger.error('error ', JSON.stringify(err));
  633. resolve(0)
  634. });
  635. })
  636. }
  637. async function delTableRows(app_token, sheetId, startIndex, endIndex) {
  638. var body = {
  639. dimension: {
  640. sheetId: sheetId,
  641. majorDimension: 'ROWS',
  642. startIndex: startIndex,
  643. endIndex: endIndex,
  644. },
  645. }
  646. return new Promise(resolve => {
  647. axios.delete(feishu_delete_table_url,
  648. {
  649. data: body,
  650. timeout: 1 * 60 * 1000,
  651. headers: {
  652. 'Content-Type': "application/json; charset=utf-8",
  653. 'Authorization': 'Bearer ' + app_token
  654. }
  655. })
  656. .then(res => {
  657. console.log('delTableRows res=>', res.status, res.data);
  658. resolve(res.data)
  659. }).catch(err => {
  660. logger.error('delTableRows error ', JSON.stringify(err));
  661. resolve(JSON.stringify(err))
  662. });
  663. })
  664. }
  665. async function insertTableRows(app_token, sheetId, startIndex, endIndex) {
  666. logger.info('insertTableRows', app_token, sheetId, startIndex, endIndex)
  667. var body = {
  668. dimension: {
  669. sheetId: sheetId,
  670. majorDimension: 'ROWS',
  671. startIndex: startIndex,
  672. endIndex: endIndex,
  673. },
  674. inheritStyle: 'AFTER'
  675. }
  676. return new Promise(resolve => {
  677. axios.post(feishu_insert_table_url,
  678. JSON.stringify(body),
  679. {
  680. timeout: 1 * 60 * 1000,
  681. headers: {
  682. 'Content-Type': "application/json; charset=utf-8",
  683. 'Authorization': 'Bearer ' + app_token
  684. }
  685. })
  686. .then(res => {
  687. console.log('res=>', res.status, res.data);
  688. resolve(res.data)
  689. }).catch(err => {
  690. logger.error('error ', JSON.stringify(err));
  691. resolve(JSON.stringify(err))
  692. });
  693. })
  694. }
  695. async function addTableRows(app_token, sheetId, endIndex) {
  696. var body = {
  697. dimension: {
  698. sheetId: sheetId,
  699. majorDimension: 'ROWS',
  700. length: endIndex,
  701. },
  702. }
  703. return new Promise(resolve => {
  704. axios.post(feishu_create_table_url,
  705. JSON.stringify(body),
  706. {
  707. timeout: 1 * 60 * 1000,
  708. headers: {
  709. 'Content-Type': "application/json; charset=utf-8",
  710. 'Authorization': 'Bearer ' + app_token
  711. }
  712. })
  713. .then(res => {
  714. console.log('res=>', res.status, res.data);
  715. resolve(res.data)
  716. }).catch(err => {
  717. logger.error('error ', JSON.stringify(err));
  718. resolve(JSON.stringify(err))
  719. });
  720. })
  721. }
  722. async function exec(data) {
  723. var app = await getFeishuToken()
  724. await insertTableRows(app.app_access_token, 'BMjMDr', 2, 3)
  725. return await writeTable(app.app_access_token, data)
  726. }
  727. async function report2FeishuTable(day) {
  728. try {
  729. logger.error('数据统计 start')
  730. logger.info('report2FeishuTable')
  731. var data = await getStatisticsInfoV2(day);
  732. // data = ''
  733. logger.info('getStatisticsInfo', data)
  734. var ret = await exec(data)
  735. logger.error('数据统计完成:', 'https://st94nif1cq.feishu.cn/sheets/shtcnp6zbrsep1Sz3Cvk7NXRpDg?sheet=BMjMDr')
  736. mTokenPriceCache.clear()
  737. } catch (error) {
  738. logger.error('report2FeishuTable', error.toString())
  739. }
  740. }
  741. async function test() {
  742. // var ret = await getStatisticsInfoV2(2)
  743. // logger.debug('getStatisticsInfoV2', await getStatisticsInfoV2(2), mTokenPriceCache.size)
  744. // for (let index = 40; index >=0; index--) {
  745. await report2FeishuTable(1)
  746. // }
  747. }
  748. // test()
  749. // exec()
  750. module.exports = {
  751. getStatisticsInfoV2
  752. }