helper.js 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441
  1. 'use strict';
  2. /**
  3. * 辅助方法扩展
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/9/28
  7. * @version
  8. */
  9. const moment = require('moment');
  10. const zeroRange = 0.0000000001;
  11. const fs = require('fs');
  12. const path = require('path');
  13. const streamToArray = require('stream-to-array');
  14. const _ = require('lodash');
  15. const bc = require('../lib/base_calc.js');
  16. const Decimal = require('decimal.js');
  17. Decimal.set({ precision: 50, defaults: true });
  18. const SMS = require('../lib/sms');
  19. const WX = require('../lib/wechat');
  20. const timesLen = 100;
  21. const UAParser = require('ua-parser-js');
  22. const math = require('mathjs');
  23. module.exports = {
  24. _,
  25. /**
  26. * 生成随机字符串
  27. *
  28. * @param {Number} length - 需要生成字符串的长度
  29. * @param {Number} type - 1为数字和字符 2为纯数字 3为纯字母
  30. * @return {String} - 返回生成结果
  31. */
  32. generateRandomString(length, type = 1) {
  33. length = parseInt(length);
  34. length = isNaN(length) ? 1 : length;
  35. let randSeed = [];
  36. let numberSeed = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  37. let stringSeed = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
  38. 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
  39. 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
  40. switch (type) {
  41. case 1:
  42. randSeed = stringSeed.concat(numberSeed);
  43. stringSeed = numberSeed = null;
  44. break;
  45. case 2:
  46. randSeed = numberSeed;
  47. break;
  48. case 3:
  49. randSeed = stringSeed;
  50. break;
  51. default:
  52. break;
  53. }
  54. const seedLength = randSeed.length - 1;
  55. let result = '';
  56. for (let i = 0; i < length; i++) {
  57. const index = Math.ceil(Math.random() * seedLength);
  58. result += randSeed[index];
  59. }
  60. return result;
  61. },
  62. /**
  63. * 字节转换
  64. * @param {number} bytes - 字节
  65. * @return {string} - 大小
  66. */
  67. bytesToSize(bytes) {
  68. if (parseInt(bytes) === 0) return '0 B';
  69. const k = 1024;
  70. const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  71. const i = Math.floor(Math.log(bytes) / Math.log(k));
  72. // return (bytes / Math.pow(k, i)) + ' ' + sizes[i];
  73. return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
  74. },
  75. /**
  76. * 浮点乘法计算
  77. * @param {number} arg1 - 乘数
  78. * @param {number} arg2 - 被乘数
  79. * @return {string} - 结果
  80. */
  81. accMul(arg1, arg2) {
  82. if (arg1 === '' || arg1 === null || arg1 === undefined || arg2 === '' || arg2 === null || arg2 === undefined) {
  83. return '';
  84. }
  85. let m = 0;
  86. const s1 = arg1.toString();
  87. const s2 = arg2.toString();
  88. try {
  89. m += s1.split('.')[1] !== undefined ? s1.split('.')[1].length : 0;
  90. } catch (e) {
  91. throw e;
  92. }
  93. try {
  94. m += s2.split('.')[1] !== undefined ? s2.split('.')[1].length : 0;
  95. } catch (e) {
  96. throw e;
  97. }
  98. return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m);
  99. },
  100. accAdd(arg1, arg2) {
  101. let r1;
  102. let r2;
  103. try {
  104. r1 = arg1.toString().split('.')[1].length;
  105. } catch (e) {
  106. r1 = 0;
  107. }
  108. try {
  109. r2 = arg2.toString().split('.')[1].length;
  110. } catch (e) {
  111. r2 = 0;
  112. }
  113. const c = Math.abs(r1 - r2);
  114. const m = Math.pow(10, Math.max(r1, r2));
  115. if (c > 0) {
  116. const cm = Math.pow(10, c);
  117. if (r1 > r2) {
  118. arg1 = Number(arg1.toString().replace('.', ''));
  119. arg2 = Number(arg2.toString().replace('.', '')) * cm;
  120. } else {
  121. arg1 = Number(arg1.toString().replace('.', '')) * cm;
  122. arg2 = Number(arg2.toString().replace('.', ''));
  123. }
  124. } else {
  125. arg1 = Number(arg1.toString().replace('.', ''));
  126. arg2 = Number(arg2.toString().replace('.', ''));
  127. }
  128. return (arg1 + arg2) / m;
  129. },
  130. // 四舍五入或末尾加零,实现类似php的 sprintf("%.".decimal."f", val);
  131. roundNum(val, decimals) {
  132. if (val === '' || val === null) {
  133. return '';
  134. }
  135. if (val !== '') {
  136. val = parseFloat(val);
  137. if (decimals < 1) {
  138. val = (Math.round(val)).toString();
  139. } else {
  140. const num = val.toString();
  141. if (num.lastIndexOf('.') === -1) {
  142. // num += '.';
  143. // num += this.makezero(decimals);
  144. val = num;
  145. } else {
  146. const valdecimals = num.split('.')[1].length;
  147. if (parseInt(valdecimals) < parseInt(decimals)) {
  148. // num += this.makezero(parseInt(decimals) - parseInt(valdecimals));
  149. val = num;
  150. } else if (parseInt(valdecimals) > parseInt(decimals)) {
  151. val = parseFloat(val) !== 0 ? Math.round(this.accMul(val, this.makemultiple(decimals))) / this.makemultiple(decimals) : this.makedecimalzero(decimals);
  152. const num = val.toString();
  153. if (num.lastIndexOf('.') === -1) {
  154. // num += '.';
  155. // num += this.makezero(decimals);
  156. val = num;
  157. } else {
  158. const valdecimals = num.split('.')[1].length;
  159. if (parseInt(valdecimals) < parseInt(decimals)) {
  160. // num += this.makezero(parseInt(decimals) - parseInt(valdecimals));
  161. val = num;
  162. }
  163. }
  164. }
  165. }
  166. }
  167. }
  168. return val;
  169. },
  170. // 生成num位的0
  171. makezero(num) {
  172. const arr = new Array(num);
  173. for (let i = 0; i < num; i++) {
  174. arr[i] = 0;
  175. }
  176. return arr.join('');
  177. },
  178. // 生成num位的10倍数
  179. makemultiple(num) {
  180. return Math.pow(10, parseInt(num));
  181. },
  182. // 根据单位获取小数位数
  183. findDecimal(unit) {
  184. let value = 3;
  185. if (unit !== '') {
  186. value = this.ctx.tender.info.precision.other.value;
  187. const changeUnits = this.ctx.tender.info.precision;
  188. for (const d in changeUnits) {
  189. if (changeUnits[d].unit !== undefined && changeUnits[d].unit === unit) {
  190. value = changeUnits[d].value;
  191. break;
  192. }
  193. }
  194. }
  195. return value;
  196. },
  197. /**
  198. * 显示排序符号
  199. *
  200. * @param {String} field - 字段名称
  201. * @return {String} - 返回字段排序的符号
  202. */
  203. showSortFlag(field) {
  204. const sort = this.ctx.sort;
  205. if (!(sort instanceof Array) || sort.length !== 2) {
  206. return '';
  207. }
  208. sort[1] = sort[1].toUpperCase();
  209. return (sort[0] === field && sort[1] === 'DESC') ? '' : '-';
  210. },
  211. /**
  212. * 判断是否为ajax请求
  213. *
  214. * @param {Object} request - 请求数据
  215. * @return {boolean} 判断结果
  216. */
  217. isAjax(request) {
  218. let headerInfo = request.headers['x-requested-with'] === undefined ? '' : request.headers['x-requested-with'];
  219. headerInfo = headerInfo.toLowerCase();
  220. return headerInfo === 'xmlhttprequest';
  221. },
  222. /**
  223. * 模拟发送请求
  224. *
  225. * @param {String} url - 请求地址
  226. * @param {Object} data - 请求数据
  227. * @param {String} type - 请求类型(POST) POST | GET
  228. * @param {String} dataType - 数据类型 json|text
  229. * @return {Object} - 请求结果
  230. */
  231. async sendRequest(url, data, type = 'POST', dataType = 'json') {
  232. // 发起请求
  233. try {
  234. const response = await this.ctx.curl(url, {
  235. method: type,
  236. data,
  237. dataType,
  238. });
  239. if (response.status !== 200) {
  240. throw '请求失败';
  241. }
  242. return response.data;
  243. } catch (err) {
  244. throw '请求失败';
  245. }
  246. },
  247. /**
  248. * 深度验证数据
  249. *
  250. * @param {Object} rule - 数据规则
  251. * @return {void}
  252. */
  253. validate(rule) {
  254. // 先用内置的验证器验证数据
  255. this.ctx.validate(rule);
  256. // 然后再验证是否有多余的数据
  257. const postData = this.ctx.request.body;
  258. delete postData._csrf_j;
  259. const postDataKey = Object.keys(postData);
  260. const ruleKey = Object.keys(rule);
  261. // 自动增加字段则填充上,以防判断出错
  262. if (postData.create_time !== undefined) {
  263. ruleKey.push('create_time');
  264. }
  265. for (const tmp of postDataKey) {
  266. // 规则里面没有定义则抛出异常
  267. if (ruleKey.indexOf(tmp) < 0) {
  268. throw '参数不正确';
  269. }
  270. }
  271. },
  272. /**
  273. * 拆分path
  274. *
  275. * @param {String|Array} paths - 拆分字符
  276. * @param {String} symbol - 拆分符号
  277. * @return {Array} - 拆分结果
  278. */
  279. explodePath(paths, symbol = '-') {
  280. const result = [];
  281. paths = paths instanceof Array ? paths : [paths];
  282. for (const path of paths) {
  283. // 拆分数据
  284. const pathArray = path.split(symbol);
  285. // 用户缓存循环的数据
  286. const tmpArray = [];
  287. for (const tmp of pathArray) {
  288. // 每次循环都追加一个数据进去
  289. tmpArray.push(tmp);
  290. const tmpPathString = tmpArray.join(symbol);
  291. // 判断是否已经存在有对应数据
  292. if (result.indexOf(tmpPathString) >= 0) {
  293. continue;
  294. }
  295. result.push(tmpPathString);
  296. }
  297. }
  298. return result;
  299. },
  300. /**
  301. * 基于obj, 拷贝sObj中的内容
  302. * obj = {a: 1, b: 2}, sObj = {a: 0, c: 3}, 返回{a: 0, b: 2, c: 3}
  303. * @param obj
  304. * @param sObj
  305. * @return {any}
  306. */
  307. updateObj(obj, sObj) {
  308. if (!obj) {
  309. return JSON.parse(JSON.stringify(sObj));
  310. }
  311. const result = JSON.parse(JSON.stringify(obj));
  312. if (sObj) {
  313. for (const prop in sObj) {
  314. result[prop] = sObj[prop];
  315. }
  316. }
  317. return result;
  318. },
  319. /**
  320. * 在数组中查找
  321. * @param {Array} arr
  322. * @param name -
  323. * @param value
  324. * @return {*}
  325. */
  326. findData(arr, name, value) {
  327. if (!arr instanceof Array) {
  328. throw '该方法仅用于数组查找';
  329. }
  330. if (arr.length === 0) { return undefined; }
  331. for (const data of arr) {
  332. if (data[name] == value) {
  333. return data;
  334. }
  335. }
  336. return undefined;
  337. },
  338. /**
  339. * 检查数字是否为0
  340. * @param {Number} value
  341. * @return {boolean}
  342. */
  343. checkZero(value) {
  344. return value === undefined || value === null || (this._.isNumber(value) && Math.abs(value) < zeroRange);
  345. },
  346. /**
  347. * 检查数字是否相等
  348. * @param {Number} value1
  349. * @param {Number} value2
  350. * @return {boolean}
  351. */
  352. checkNumberEqual(value1, value2) {
  353. if (value1 && value2) {
  354. return Math.abs(value2 - value1) > zeroRange;
  355. }
  356. return (!value1 && !value2);
  357. },
  358. /**
  359. * 比较编码
  360. * @param str1
  361. * @param str2
  362. * @param symbol
  363. * @return {number}
  364. */
  365. compareCode(str1, str2, symbol = '-') {
  366. if (!str1) {
  367. return 1;
  368. } else if (!str2) {
  369. return -1;
  370. }
  371. function compareSubCode(code1, code2) {
  372. if (numReg.test(code1)) {
  373. if (numReg.test(code2)) {
  374. return parseInt(code1) - parseInt(code2);
  375. }
  376. return -1;
  377. }
  378. if (numReg.test(code2)) {
  379. return 1;
  380. }
  381. return code1 === code2 ? 0 : (code1 < code2 ? -1 : 1); // code1.localeCompare(code2);
  382. }
  383. const numReg = /^[0-9]+$/;
  384. const aCodes = str1.split(symbol),
  385. bCodes = str2.split(symbol);
  386. for (let i = 0, iLength = Math.min(aCodes.length, bCodes.length); i < iLength; ++i) {
  387. const iCompare = compareSubCode(aCodes[i], bCodes[i]);
  388. if (iCompare !== 0) {
  389. return iCompare;
  390. }
  391. }
  392. return aCodes.length - bCodes.length;
  393. },
  394. /**
  395. * 根据 清单编号 获取 章级编号
  396. * @param code
  397. * @param symbol
  398. * @return {string}
  399. */
  400. getChapterCode(code, symbol = '-') {
  401. if (!code || code === '') return '';
  402. const codePath = code.split(symbol);
  403. const reg = /^[^0-9]*[0-9]{3,4}$/;
  404. if (reg.test(codePath[0])) {
  405. const numReg = /[0-9]{3,4}$/;
  406. const result = codePath[0].match(numReg);
  407. const num = parseInt(result[0]);
  408. return this.mul(this.div(num, 100, 0), 100) + '';
  409. }
  410. return '10000';
  411. },
  412. /**
  413. * 树结构节点排序,要求最顶层节点须在同一父节点下
  414. * @param treeNodes
  415. * @param idField
  416. * @param pidField
  417. */
  418. sortTreeNodes(treeNodes, idField, pidField) {
  419. const result = [];
  420. const getFirstLevel = function(nodes) {
  421. let result;
  422. for (const node of nodes) {
  423. if (!result || result > node.level) {
  424. result = node.level;
  425. }
  426. }
  427. return result;
  428. };
  429. const getLevelNodes = function(nodes, level) {
  430. const children = nodes.filter(function(a) {
  431. return a.level = level;
  432. });
  433. children.sort(function(a, b) {
  434. return a.order - b.order;
  435. });
  436. return children;
  437. };
  438. const getChildren = function(nodes, node) {
  439. const children = nodes.filter(function(a) {
  440. return a[pidField] = node[idField];
  441. });
  442. children.sort(function(a, b) {
  443. return a.order - b.order;
  444. });
  445. return children;
  446. };
  447. const addSortNodes = function(nodes) {
  448. for (let i = 0; i < nodes.length; i++) {
  449. result.push(nodes[i]);
  450. addSortNodes(getChildren(nodes[i]));
  451. }
  452. };
  453. const firstLevel = getFirstLevel(treeNodes);
  454. addSortNodes(getLevelNodes(treeNodes, firstLevel));
  455. },
  456. /**
  457. * 判断当前用户是否有指定权限
  458. *
  459. * @param {Number|Array} permission - 权限id
  460. * @return {Boolean} - 返回判断结果
  461. */
  462. hasPermission(permission) {
  463. let result = false;
  464. try {
  465. const sessionUser = this.ctx.session.sessionUser;
  466. if (sessionUser.permission === undefined) {
  467. throw '不存在权限数据';
  468. }
  469. let currentPermission = sessionUser.permission;
  470. if (currentPermission === '') {
  471. throw '权限数据为空';
  472. }
  473. // 管理员则直接返回结果
  474. if (currentPermission === 'all') {
  475. return true;
  476. }
  477. currentPermission = currentPermission.split(',');
  478. permission = permission instanceof Array ? permission : [permission];
  479. let counter = 0;
  480. for (const tmp of permission) {
  481. if (currentPermission[tmp] !== undefined) {
  482. counter++;
  483. }
  484. }
  485. result = counter === permission.length;
  486. } catch (error) {
  487. result = false;
  488. }
  489. return result;
  490. },
  491. /**
  492. * 递归创建文件夹(fs.mkdirSync需要上一层文件夹已存在)
  493. * @param pathName
  494. * @return {Promise<void>}
  495. */
  496. async recursiveMkdirSync(pathName) {
  497. if (!fs.existsSync(pathName)) {
  498. const upperPath = path.dirname(pathName);
  499. if (!fs.existsSync(upperPath)) {
  500. await this.recursiveMkdirSync(upperPath);
  501. }
  502. await fs.mkdirSync(pathName);
  503. }
  504. },
  505. /**
  506. * 字节 保存至 本地文件
  507. * @param buffer - 字节
  508. * @param fileName - 文件名
  509. * @return {Promise<void>}
  510. */
  511. async saveBufferFile(buffer, fileName) {
  512. // 检查文件夹是否存在,不存在则直接创建文件夹
  513. const pathName = path.dirname(fileName);
  514. if (!fs.existsSync(pathName)) {
  515. await this.recursiveMkdirSync(pathName);
  516. }
  517. await fs.writeFileSync(fileName, buffer);
  518. },
  519. /**
  520. * 将文件流的数据保存至本地文件
  521. * @param stream
  522. * @param fileName
  523. * @return {Promise<void>}
  524. */
  525. async saveStreamFile(stream, fileName) {
  526. // 读取字节流
  527. const parts = await streamToArray(stream);
  528. // 转化为buffer
  529. const buffer = Buffer.concat(parts);
  530. // 写入文件
  531. await this.saveBufferFile(buffer, fileName);
  532. },
  533. async copyFileSync(source, target) {
  534. const pathName = path.dirname(target);
  535. if (!fs.existsSync(pathName)) {
  536. await this.recursiveMkdirSync(pathName);
  537. }
  538. await fs.copyFileSync(source, target);
  539. },
  540. /**
  541. * 检查code是否是指标模板数据
  542. * @param {String} code
  543. * @return {boolean}
  544. */
  545. validBillsCode(code) {
  546. const reg1 = /(^[0-9]+)([a-z0-9\-]*)/i;
  547. const reg2 = /([a-z0-9]+$)/i;
  548. return reg1.test(code) && reg2.test(code);
  549. },
  550. getNumberFormatter(decimal) {
  551. if (decimal <= 0) {
  552. return '0';
  553. }
  554. let pre = '0.';
  555. for (let i = 0; i < decimal; i++) {
  556. pre += '#';
  557. }
  558. return pre;
  559. },
  560. /**
  561. * 根据单位查找对应的清单精度
  562. * @param {tenderInfo.precision} list - 清单精度列表
  563. * @param {String} unit - 单位
  564. * @return {number}
  565. */
  566. findPrecision(list, unit) {
  567. if (unit) {
  568. for (const p in list) {
  569. if (list[p].unit && list[p].unit === unit) {
  570. return list[p];
  571. }
  572. }
  573. }
  574. return list.other;
  575. },
  576. /**
  577. * 检查数据中的精度
  578. * @param {Object} Obj - 检查的数据
  579. * @param {Array} fields - 检查的属性
  580. * @param {Number} precision - 精度
  581. * @class
  582. */
  583. checkFieldPrecision(Obj, fields, precision = 2) {
  584. if (Obj) {
  585. for (const field of fields) {
  586. if (Obj[field]) {
  587. Obj[field] = this.round(Obj[field], precision);
  588. }
  589. }
  590. }
  591. },
  592. /**
  593. * 过滤无效数据
  594. *
  595. * @param obj
  596. * @param fields - 有效数据的数组
  597. */
  598. filterValidFields(data, fields) {
  599. if (data) {
  600. const result = {};
  601. for (const prop in data) {
  602. if (fields.indexOf(prop) !== -1) {
  603. result[prop] = data[prop];
  604. }
  605. }
  606. return result;
  607. }
  608. return data;
  609. },
  610. // 加减乘除方法,为方便调用,兼容num为空的情况
  611. // 加减法使用base_calc,乘除法使用Decimal(原因详见demo/calc_test)
  612. /**
  613. * 加法 num1 + num2
  614. * @param num1
  615. * @param num2
  616. * @return {number}
  617. */
  618. add(num1, num2) {
  619. return bc.add(num1 ? num1 : 0, num2 ? num2 : 0);
  620. },
  621. /**
  622. * 减法 num1 - num2
  623. * @param num1
  624. * @param num2
  625. * @return {number}
  626. */
  627. sub(num1, num2) {
  628. return bc.sub(num1 ? num1 : 0, num2 ? num2 : 0);
  629. },
  630. /**
  631. * 乘法 num1 * num2
  632. * @param num1
  633. * @param num2
  634. * @return {*}
  635. */
  636. mul(num1, num2, digit = 6) {
  637. if (num1 === '' || num1 === null || num2 === '' || num2 === null) {
  638. return 0;
  639. }
  640. return Decimal.mul(num1 ? num1 : 0, num2 ? num2 : 0).toDecimalPlaces(digit).toNumber();
  641. },
  642. /**
  643. * 除法 num1 / num2
  644. * @param num1 - 被除数
  645. * @param num2 - 除数
  646. * @return {*}
  647. */
  648. div(num1, num2, digit = 6) {
  649. if (num2 && !this.checkZero(num2)) {
  650. return Decimal.div(num1 ? num1 : 0, num2).toDecimalPlaces(digit).toNumber();
  651. }
  652. return null;
  653. },
  654. /**
  655. * 四舍五入(统一,方便以后万一需要置换)
  656. * @param {Number} value - 舍入的数字
  657. * @param {Number} decimal - 要保留的小数位数
  658. * @return {*}
  659. */
  660. round(value, decimal) {
  661. // return value ? bc.round(value, decimal) : null;
  662. return value ? new Decimal(value).toDecimalPlaces(decimal).toNumber() : null;
  663. },
  664. /**
  665. * 汇总
  666. * @param array
  667. * @return {number}
  668. */
  669. sum(array) {
  670. let result = 0;
  671. for (const a of array) {
  672. result = this.add(result, a);
  673. }
  674. return result;
  675. },
  676. /**
  677. * 使用正则替换字符
  678. * @param str
  679. * @param reg
  680. * @param subStr
  681. * @return {*}
  682. */
  683. replaceStr(str, reg, subStr) {
  684. return str ? str.replace(reg, subStr) : str;
  685. },
  686. /**
  687. * 替换字符串中的 换行符回车符
  688. * @param str
  689. * @return {*}
  690. */
  691. replaceReturn(str) {
  692. // return str
  693. // ? (typeof str === 'string') ? str.replace(/[\r\n]/g, '') : str + ''
  694. // : str;
  695. return (str && typeof str === 'string')
  696. ? str.replace(/[\r\n]/g, '')
  697. : !_.isNil(str) ? str + '' : str;
  698. },
  699. /**
  700. * 替换字符串中的 换行符回车符为换行符<br>
  701. * @param str
  702. * @return {*}
  703. */
  704. replaceRntoBr(str) {
  705. // return str
  706. // ? (typeof str === 'string') ? str.replace(/[\r\n]/g, '') : str + ''
  707. // : str;
  708. return (str && typeof str === 'string')
  709. ? str.replace(/[\r\n]/g, '<br>')
  710. : !_.isNil(str) ? str + '' : str;
  711. },
  712. /**
  713. * 获取 字符串 数组的 mysql 筛选条件
  714. *
  715. * @param arr
  716. * @return {*}
  717. */
  718. getInArrStrSqlFilter(arr) {
  719. let result = '';
  720. for (const a of arr) {
  721. if (result !== '') {
  722. result = result + ',';
  723. }
  724. result = result + this.ctx.app.mysql.escape(a);
  725. }
  726. return result;
  727. },
  728. /**
  729. * 合并 相关数据
  730. * @param {Array} main - 主数据
  731. * @param {Array[]}rela - 相关数据 {data, fields, prefix, relaId}
  732. */
  733. assignRelaData(main, rela) {
  734. const index = {},
  735. indexPre = 'id_';
  736. const loadFields = function(datas, fields, prefix, relaId) {
  737. for (const d of datas) {
  738. const key = indexPre + d[relaId];
  739. const m = index[key];
  740. if (m) {
  741. for (const f of fields) {
  742. if (d[f] !== undefined) {
  743. m[prefix + f] = d[f];
  744. }
  745. }
  746. }
  747. }
  748. };
  749. for (const m of main) {
  750. index[indexPre + m.id] = m;
  751. for (const r of rela) {
  752. if (r.defaultData) _.assignIn(m, r.defaultData);
  753. }
  754. }
  755. for (const r of rela) {
  756. loadFields(r.data, r.fields, r.prefix, r.relaId);
  757. }
  758. },
  759. whereSql(where, as) {
  760. if (!where) {
  761. return '';
  762. }
  763. const wheres = [];
  764. const values = [];
  765. for (const key in where) {
  766. const value = where[key];
  767. if (Array.isArray(value)) {
  768. wheres.push('?? IN (?)');
  769. } else {
  770. wheres.push('?? = ?');
  771. }
  772. values.push((as && as !== '') ? as + '.' + key : key);
  773. values.push(value);
  774. }
  775. if (wheres.length > 0) {
  776. return this.ctx.app.mysql.format(' WHERE ' + wheres.join(' AND '), values);
  777. }
  778. return '';
  779. },
  780. formatMoney(s = 0, dot = ',', decimal = 2) {
  781. if (!s) {
  782. s = 0;
  783. return s.toFixed(decimal);
  784. }
  785. s = parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(decimal) + '';
  786. if (!decimal) {
  787. s += '.';
  788. }
  789. const l = s.split('.')[0].split('').reverse(),
  790. r = s.split('.')[1];
  791. let t = '';
  792. for (let i = 0; i < l.length; i++) {
  793. t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? dot : '');
  794. }
  795. return t.split('').reverse().join('') + (decimal === 0 ? '' : '.' + r);
  796. },
  797. transFormToChinese(num) {
  798. const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  799. const unit = ['', '十', '百', '千', '万'];
  800. num = parseInt(num);
  801. const getWan = temp => {
  802. const strArr = temp.toString().split('').reverse();
  803. let newNum = '';
  804. for (let i = 0; i < strArr.length; i++) {
  805. newNum = (i == 0 && strArr[i] == 0 ? '' : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? '' : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
  806. }
  807. return strArr.length === 2 && newNum.indexOf('一十') !== -1 ? newNum.replace('一十', '十') : newNum;
  808. };
  809. const overWan = Math.floor(num / 10000);
  810. let noWan = num % 10000;
  811. if (noWan.toString().length < 4) noWan = '0' + noWan;
  812. return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num);
  813. },
  814. formatNum(num, pattern) {
  815. const strarr = num ? num.toString().split('.') : ['0'];
  816. const fmtarr = pattern ? pattern.split('.') : [''];
  817. let retstr = '';
  818. // 整数部分
  819. let str = strarr[0];
  820. let fmt = fmtarr[0];
  821. let i = str.length - 1;
  822. let comma = false;
  823. for (var f = fmt.length - 1; f >= 0; f--) {
  824. switch (fmt.substr(f, 1)) {
  825. case '#':
  826. if (i >= 0) retstr = str.substr(i--, 1) + retstr;
  827. break;
  828. case '0':
  829. if (i >= 0) retstr = str.substr(i--, 1) + retstr;
  830. else retstr = '0' + retstr;
  831. break;
  832. case ',':
  833. comma = true;
  834. retstr = ',' + retstr;
  835. break;
  836. }
  837. }
  838. if (i >= 0) {
  839. if (comma) {
  840. const l = str.length;
  841. for (;i >= 0; i--) {
  842. retstr = str.substr(i, 1) + retstr;
  843. if (i > 0 && ((l - i) % 3) == 0) retstr = ',' + retstr;
  844. }
  845. } else retstr = str.substr(0, i + 1) + retstr;
  846. }
  847. retstr = retstr + '.';
  848. // 处理小数部分
  849. str = strarr.length > 1 ? strarr[1] : '';
  850. fmt = fmtarr.length > 1 ? fmtarr[1] : '';
  851. i = 0;
  852. for (var f = 0; f < fmt.length; f++) {
  853. switch (fmt.substr(f, 1)) {
  854. case '#':
  855. if (i < str.length) retstr += str.substr(i++, 1);
  856. break;
  857. case '0':
  858. if (i < str.length) retstr += str.substr(i++, 1);
  859. else retstr += '0';
  860. break;
  861. }
  862. }
  863. return retstr.replace(/^,+/, '').replace(/\.$/, '');
  864. },
  865. dateTran(time) {
  866. return moment(time).format('YYYY年MM月DD日 HH:mm');
  867. },
  868. // 审批日期格式:2020-5-7 9:40:30
  869. formatFullDate(time) {
  870. return moment(time).format('YYYY-MM-DD HH:mm:ss');
  871. },
  872. // 预付款详情页时间线所需格式
  873. formatDate(date) {
  874. if (!date) return '';
  875. const year = date.getFullYear();
  876. let mon = date.getMonth() + 1;
  877. let day = date.getDate();
  878. let hour = date.getHours();
  879. let minute = date.getMinutes();
  880. let scond = date.getSeconds();
  881. if (mon < 10) {
  882. mon = '0' + mon.toString();
  883. }
  884. if (day < 10) {
  885. day = '0' + day.toString();
  886. }
  887. if (hour < 10) {
  888. hour = '0' + hour.toString();
  889. }
  890. if (minute < 10) {
  891. minute = '0' + minute.toString();
  892. }
  893. if (scond < 10) {
  894. scond = '0' + scond.toString();
  895. }
  896. return `${year}<span>${mon}-${day}</span><span>${hour}:${minute}:${scond}</span>`;
  897. },
  898. timeAdd(duration) {
  899. const d = parseInt(duration);
  900. let time = 0;
  901. if (d === 1) {
  902. time = 60 * 15 * 1000;
  903. } else if (d === 2) {
  904. time = 60 * 30 * 1000;
  905. } else if (d === 3) {
  906. time = 3600 * 1000;
  907. } else if (d === 4) {
  908. time = 3600 * 2 * 1000;
  909. }
  910. return time;
  911. },
  912. async sendUserSms(userId, type, judge, msg) {
  913. const mobiles = [];
  914. if (!userId || (userId instanceof Array && userId.length === 0)) return;
  915. const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  916. for (const su of smsUser) {
  917. if (!su.auth_mobile || su.auth_mobile === '') continue;
  918. if (!su.sms_type || su.sms_type === '') continue;
  919. const smsType = JSON.parse(su.sms_type);
  920. if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
  921. mobiles.push(su.auth_mobile);
  922. }
  923. }
  924. if (mobiles.length > 0) {
  925. const sms = new SMS(this.ctx);
  926. const tenderName = await sms.contentChange(this.ctx.tender.data.name);
  927. const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
  928. const ptmsg = projectName !== '' ? '项目「' + projectName + '」标段「' + tenderName + '」' : tenderName;
  929. const content = '【纵横计量支付】' + ptmsg + msg;
  930. sms.send(mobiles, content);
  931. }
  932. },
  933. async sendAliSms(userId, type, judge, code, data = {}) {
  934. // const mobiles = [];
  935. // if (!userId || (userId instanceof Array && userId.length === 0)) return;
  936. // const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  937. // for (const su of smsUser) {
  938. // if (!su.auth_mobile || su.auth_mobile === '') continue;
  939. // if (!su.sms_type || su.sms_type === '') continue;
  940. //
  941. // const smsType = JSON.parse(su.sms_type);
  942. // if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
  943. // mobiles.push(su.auth_mobile);
  944. // }
  945. // }
  946. //
  947. // if (mobiles.length > 0) {
  948. // const sms = new SMS(this.ctx);
  949. // const tenderName = await sms.contentChange(this.ctx.tender.data.name);
  950. // const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
  951. // const param = {
  952. // project: projectName,
  953. // number: tenderName,
  954. // };
  955. // const postParam = Object.assign(param, data);
  956. // sms.aliSend(mobiles, postParam, code);
  957. // }
  958. },
  959. async sendWechat(userId, type, judge, template, data = {}) {
  960. const wechats = [];
  961. if (!userId || (userId instanceof Array && userId.length === 0)) return;
  962. const wxUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  963. for (const user of wxUser) {
  964. if (!user.wx_openid || user.wx_openid === '') continue;
  965. if (!user.wx_type || user.wx_type === '') continue;
  966. const wxType = JSON.parse(user.wx_type);
  967. if (wxType[type] && wxType[type].indexOf(judge) !== -1) {
  968. wechats.push(user.wx_openid);
  969. }
  970. }
  971. if (wechats.length > 0) {
  972. const wx = new WX(this.ctx);
  973. const tenderName = await wx.contentChange(this.ctx.tender.data.name);
  974. const projectName = await wx.contentChange(this.ctx.tender.info.deal_info.buildName);
  975. const param = {
  976. projectName,
  977. tenderName,
  978. };
  979. const postParam = Object.assign(param, data);
  980. wx.Send(wechats, template, postParam);
  981. }
  982. },
  983. /**
  984. *
  985. * @param setting
  986. * @param data
  987. * @return {{} & any & {"!ref": string} & {"!cols"}}
  988. */
  989. simpleXlsxSheetData(setting, data) {
  990. const headerStyle = {
  991. font: { sz: 10, bold: true },
  992. alignment: { horizontal: 'center' },
  993. };
  994. const sHeader = setting.header
  995. .map((v, i) => Object.assign({}, { v, s: headerStyle, position: String.fromCharCode(65 + i) + 1 }))
  996. .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v, s: next.s } }), {});
  997. const sData = data
  998. .map((v, i) => v.map((k, j) => Object.assign({}, {
  999. v: k ? k : '',
  1000. s: { font: { sz: 10 }, alignment: { horizontal: setting.hAlign[j] } },
  1001. position: String.fromCharCode(65 + j) + (i + 2) })))
  1002. .reduce((prev, next) => prev.concat(next))
  1003. .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v, s: next.s } }), {});
  1004. const output = Object.assign({}, sHeader, sData);
  1005. const outputPos = Object.keys(output);
  1006. const result = Object.assign({}, output,
  1007. { '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] },
  1008. { '!cols': setting.width.map(w => Object.assign({}, { wpx: w })) });
  1009. return result;
  1010. },
  1011. log(error) {
  1012. if (error.stack) {
  1013. this.ctx.logger.error(error);
  1014. } else {
  1015. this.ctx.getLogger('fail').info(JSON.stringify({
  1016. error,
  1017. project: this.ctx.session.sessionProject,
  1018. user: this.ctx.session.sessionUser,
  1019. body: this.ctx.session.body,
  1020. }));
  1021. }
  1022. },
  1023. /**
  1024. * 添加debug信息
  1025. * 在debug模式下,debug信息将传输到浏览器并打印
  1026. *
  1027. * @param {String}key
  1028. * @param {*}data
  1029. */
  1030. addDebugInfo(key, ...data) {
  1031. if (!this.ctx.debugInfo) {
  1032. this.ctx.debugInfo = { key: {}, other: [] };
  1033. }
  1034. if (key) {
  1035. this.ctx.debugInfo.key[key] = data;
  1036. } else {
  1037. this.ctx.debugInfo.other.push(data);
  1038. }
  1039. },
  1040. /**
  1041. * 深拷贝
  1042. * @param obj
  1043. * @return {*}
  1044. */
  1045. clone(obj) {
  1046. if (obj === null) return null;
  1047. const o = obj instanceof Array ? [] : {};
  1048. for (const i in obj) {
  1049. o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === 'object' ? this.clone(obj[i]) : obj[i]);
  1050. }
  1051. return o;
  1052. },
  1053. /**
  1054. * 短链接生成
  1055. * @param url
  1056. * @return {*}
  1057. */
  1058. async urlToShort(url) {
  1059. const apiUrl = 'http://scn.ink/api/shorturl';
  1060. const data = {
  1061. url: encodeURI(url),
  1062. };
  1063. const result = await this.sendRequest(apiUrl, data, 'get');
  1064. return result && result.code === 200 && result.url ? result.url : url;
  1065. },
  1066. /**
  1067. * 判断是否wap访问
  1068. * @param request
  1069. * @return {*}
  1070. */
  1071. isWap(request) {
  1072. return request.url.indexOf('/wap/') !== -1;
  1073. },
  1074. getDefaultCheckResult() {
  1075. return {
  1076. error: [],
  1077. source: {
  1078. bills: [],
  1079. pos: [],
  1080. },
  1081. };
  1082. },
  1083. checkBillsWithPos(bills, pos, fields) {
  1084. const result = this.getDefaultCheckResult();
  1085. for (const b of bills) {
  1086. const pr = _.remove(pos, { lid: b.id });
  1087. const checkData = {},
  1088. calcData = {};
  1089. if (pr && pr.length > 0) {
  1090. for (const field of fields) {
  1091. checkData[field] = b[field] ? b[field] : 0;
  1092. }
  1093. for (const p of pr) {
  1094. for (const field of fields) {
  1095. calcData[field] = this.add(calcData[field], p[field]);
  1096. }
  1097. }
  1098. if (!_.isMatch(checkData, calcData)) {
  1099. result.error.push({
  1100. ledger_id: b.ledger_id,
  1101. b_code: b.b_code,
  1102. name: b.name,
  1103. error: { checkData, calcData },
  1104. });
  1105. result.source.bills.push(b);
  1106. for (const p of pr) {
  1107. result.source.pos.push(p);
  1108. }
  1109. }
  1110. }
  1111. }
  1112. return result;
  1113. },
  1114. checkBillsOverRange(bills, posRange, isTz) {
  1115. if (isTz && posRange.length > 0) {
  1116. for (const p of posRange) {
  1117. const end_contract_qty = this.add(p.pre_contract_qty, p.contract_qty);
  1118. if (end_contract_qty > p.quantity) return true;
  1119. }
  1120. return false;
  1121. } else {
  1122. const end_qc_qty = this.add(bills.qc_qty, bills.pre_qc_qty);
  1123. const end_qc_tp = this.add(bills.qc_tp, bills.pre_qc_tp);
  1124. const end_gather_qty = this.sum([bills.contract_qty, bills.pre_contract_qty, end_qc_qty]);
  1125. const end_gather_tp = this.sum([bills.contract_tp, bills.pre_contract_tp, end_qc_tp]);
  1126. if (isTz) {
  1127. if (end_gather_qty) {
  1128. return !bills.quantity || Math.abs(end_gather_qty) > Math.abs(this.add(bills.quantity, end_qc_qty));
  1129. } else if (end_gather_tp) {
  1130. return !bills.total_price || Math.abs(end_gather_tp) > Math.abs(this.add(bills.total_price, end_qc_tp));
  1131. }
  1132. } else {
  1133. if (end_gather_qty) {
  1134. return !bills.deal_qty || Math.abs(end_gather_qty) > Math.abs(this.add(bills.deal_qty, end_qc_qty));
  1135. } else if (end_gather_tp) {
  1136. return !bills.deal_tp || Math.abs(end_gather_tp) > Math.abs(this.add(bills.deal_tp, end_qc_tp));
  1137. }
  1138. }
  1139. }
  1140. },
  1141. checkBillsWithPos2(bills, pos, fields, checkOver, isTz) {
  1142. const result = this.getDefaultCheckResult(), overResult = this.getDefaultCheckResult();
  1143. for (const b of bills) {
  1144. let hasSource = false;
  1145. const pr = _.remove(pos, { lid: b.id });
  1146. const checkData = {},
  1147. calcData = {};
  1148. if (pr && pr.length > 0) {
  1149. for (const field of fields) {
  1150. checkData[field] = b[field] ? b[field] : 0;
  1151. }
  1152. for (const p of pr) {
  1153. for (const field of fields) {
  1154. calcData[field] = this.add(calcData[field], p[field]);
  1155. }
  1156. }
  1157. if (!_.isMatch(checkData, calcData)) {
  1158. hasSource = true;
  1159. result.error.push({
  1160. ledger_id: b.ledger_id,
  1161. b_code: b.b_code,
  1162. name: b.name,
  1163. error: { checkData, calcData },
  1164. });
  1165. result.source.bills.push(b);
  1166. for (const p of pr) {
  1167. result.source.pos.push(p);
  1168. }
  1169. }
  1170. }
  1171. if (checkOver && this.checkBillsOverRange(b, pr, isTz)) {
  1172. overResult.error.push({
  1173. ledger_id: b.ledger_id,
  1174. b_code: b.b_code,
  1175. name: b.name,
  1176. });
  1177. if (!hasSource) {
  1178. overResult.source.bills.push(b);
  1179. for (const p of pr) {
  1180. overResult.source.pos.push(p);
  1181. }
  1182. }
  1183. }
  1184. }
  1185. return [result, overResult];
  1186. },
  1187. checkBillsTp(bills, field, decimal) {
  1188. const result = this.getDefaultCheckResult();
  1189. for (const b of bills) {
  1190. if (!b.check_calc) continue;
  1191. const checkData = {}, calcData = {};
  1192. for (const f of field) {
  1193. checkData[f.tp] = b[f.tp] || 0;
  1194. calcData[f.tp] = this.mul(b.unit_price, b[f.qty], decimal.tp) || 0;
  1195. }
  1196. if (!this._.isMatch(checkData, calcData)) {
  1197. result.error.push({
  1198. ledger_id: b.ledger_id,
  1199. b_code: b.b_code,
  1200. name: b.name,
  1201. error: { checkData, calcData },
  1202. });
  1203. result.source.bills.push(b);
  1204. }
  1205. }
  1206. return result;
  1207. },
  1208. check18MainCode(code) {
  1209. return /^([0-9]([0-9][0-9])*)?(GD[0-9]{3}([0-9][0-9])*)?$/.test(code);
  1210. },
  1211. check18SubCode(code) {
  1212. return /^(GD)?G?[A-Z]{2}[A-Z]{0,2}([0-9]{2})+$/.test(code);
  1213. },
  1214. /**
  1215. * 判断是否是移动端访问
  1216. * @param request
  1217. * @return {*}
  1218. */
  1219. isMobile(agent) {
  1220. return agent.match(/(iphone|ipod|android)/i);
  1221. },
  1222. /**
  1223. * 删除文件
  1224. * @param {Array} fileList 文件数组(格式为数据库查询出来的结果集,且文件字段必须为filepath)
  1225. * @return {void}
  1226. */
  1227. async delFiles(fileList) {
  1228. if (fileList.length) {
  1229. for (const att of fileList) {
  1230. if (att.filepath && fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
  1231. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  1232. }
  1233. }
  1234. }
  1235. },
  1236. /**
  1237. * 匹配图片、pdf(用于预览)
  1238. * @param {String} ext 后缀名
  1239. * @return {Boolean} 匹配结果
  1240. */
  1241. canPreview(ext) {
  1242. const reg = /(.png)|(.gif)|(.txt)|(.jpg)|(.jpeg)|(.pdf)/;
  1243. return reg.test(ext);
  1244. },
  1245. /**
  1246. * 查找数组中某个字符的个数
  1247. * @param {Array} array 数组
  1248. * @param {string} val 字符串
  1249. * @return {Boolean} 匹配结果
  1250. */
  1251. arrayCount(array, val) {
  1252. const counts = (arr, value) => arr.reduce((a, v) => { return value.indexOf(v) !== -1 ? a + 1 : a + 0; }, 0);
  1253. return counts(array, val);
  1254. },
  1255. filterLastestData(data, keyFields) {
  1256. const dataIndex = {};
  1257. for (const d of data) {
  1258. let key = 'd';
  1259. for (const kf of keyFields) {
  1260. key = key + '.' + (d[kf] || '');
  1261. }
  1262. const di = dataIndex[key];
  1263. if (di) {
  1264. if ((di.times * timesLen + di.order) < (d.times * timesLen + d.order)) dataIndex[key] = d;
  1265. } else {
  1266. dataIndex[key] = d;
  1267. }
  1268. }
  1269. const result = [];
  1270. for (const prop in dataIndex) {
  1271. result.push(dataIndex[prop]);
  1272. }
  1273. return result;
  1274. },
  1275. calcExpr(expr) {
  1276. const validExpr = expr.replace('=', '').replace('%', '/100');
  1277. return math.eval(validExpr);
  1278. },
  1279. /**
  1280. * 创建登录日志
  1281. * @return {Boolean} 日志是否创建成功
  1282. * @param {Number} type - 登录类型
  1283. * @param {Number} status - 是否显示记录
  1284. */
  1285. async getUserIPMsg() {
  1286. const { ctx } = this;
  1287. const ip = ctx.request.ip ? ctx.request.ip : '';
  1288. const ipInfo = await this.getIpInfoFromApi(ip);
  1289. const parser = new UAParser(ctx.header['user-agent']);
  1290. const osInfo = parser.getOS();
  1291. const cpuInfo = parser.getCPU();
  1292. const browserInfo = parser.getBrowser();
  1293. const ipMsg = {
  1294. os: `${osInfo.name} ${osInfo.version} ${cpuInfo.architecture}`,
  1295. browser: `${browserInfo.name} ${browserInfo.version}`,
  1296. ip,
  1297. address: ipInfo,
  1298. };
  1299. return ipMsg;
  1300. },
  1301. /**
  1302. * 根据ip请求获取详细地址
  1303. * @param {String} a_ip - ip地址
  1304. * @return {String} 详细地址
  1305. */
  1306. async getIpInfoFromApi(a_ip = '') {
  1307. if (!a_ip) return '';
  1308. if (a_ip === '127.0.0.1' || a_ip === '::1' || a_ip.indexOf('192.168') !== -1) return '服务器本机访问';
  1309. const { ip = '', region = '', city = '', isp = '' } = await this.sendIpRequest(a_ip);
  1310. let address = '';
  1311. region && (address += region + '省');
  1312. city && (address += city + '市 ');
  1313. isp && (address += isp + ' ');
  1314. ip && (address += `(${ip})`);
  1315. return address;
  1316. },
  1317. /**
  1318. * 发送请求获取详细地址
  1319. * @param {String} ip - ip地址
  1320. * @return {Object} the result of request
  1321. * @private
  1322. */
  1323. async sendIpRequest(ip) {
  1324. return new Promise(resolve => {
  1325. this.ctx.curl(`https://api01.aliyun.venuscn.com/ip?ip=${ip}`, {
  1326. dateType: 'json',
  1327. encoding: 'utf8',
  1328. timeout: 2000,
  1329. headers: {
  1330. Authorization: 'APPCODE 85c64bffe70445c4af9df7ae31c7bfcc',
  1331. },
  1332. }).then(({ status, data }) => {
  1333. if (status === 200) {
  1334. const result = JSON.parse(data.toString()).data;
  1335. if (!result.ip) {
  1336. resolve({});
  1337. } else {
  1338. resolve(result);
  1339. }
  1340. } else {
  1341. resolve({});
  1342. }
  1343. }).catch(() => {
  1344. resolve({});
  1345. });
  1346. });
  1347. },
  1348. };