helper.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. 'use strict';
  2. /**
  3. * 辅助方法扩展
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/9/28
  7. * @version
  8. */
  9. const zeroRange = 0.0000000001;
  10. const fs = require('fs');
  11. const path = require('path');
  12. const streamToArray = require('stream-to-array');
  13. const _ = require('lodash');
  14. const np = require('number-precision');
  15. np.enableBoundaryChecking(false);
  16. const math = require('mathjs');
  17. module.exports = {
  18. _: _,
  19. /**
  20. * 生成随机字符串
  21. *
  22. * @param {Number} length - 需要生成字符串的长度
  23. * @param {Number} type - 1为数字和字符 2为纯数字 3为纯字母
  24. * @return {String} - 返回生成结果
  25. */
  26. generateRandomString(length, type = 1) {
  27. length = parseInt(length);
  28. length = isNaN(length) ? 1 : length;
  29. let randSeed = [];
  30. let numberSeed = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  31. let stringSeed = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
  32. 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
  33. 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
  34. switch (type) {
  35. case 1:
  36. randSeed = stringSeed.concat(numberSeed);
  37. stringSeed = numberSeed = null;
  38. break;
  39. case 2:
  40. randSeed = numberSeed;
  41. break;
  42. case 3:
  43. randSeed = stringSeed;
  44. break;
  45. default:
  46. break;
  47. }
  48. const seedLength = randSeed.length - 1;
  49. let result = '';
  50. for (let i = 0; i < length; i++) {
  51. const index = Math.ceil(Math.random() * seedLength);
  52. result += randSeed[index];
  53. }
  54. return result;
  55. },
  56. /**
  57. * 字节转换
  58. * @param {number} bytes - 字节
  59. * @return {string} - 大小
  60. */
  61. bytesToSize(bytes) {
  62. if (parseInt(bytes) === 0) return '0 B';
  63. const k = 1024;
  64. const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  65. const i = Math.floor(Math.log(bytes) / Math.log(k));
  66. // return (bytes / Math.pow(k, i)) + ' ' + sizes[i];
  67. return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
  68. },
  69. /**
  70. * 浮点乘法计算
  71. * @param {number} arg1 - 乘数
  72. * @param {number} arg2 - 被乘数
  73. * @return {string} - 结果
  74. */
  75. accMul(arg1, arg2) {
  76. let m = 0;
  77. const s1 = arg1.toString();
  78. const s2 = arg2.toString();
  79. try {
  80. m += s1.split('.')[1] !== undefined ? s1.split('.')[1].length : 0;
  81. } catch (e) {
  82. throw e;
  83. }
  84. try {
  85. m += s2.split('.')[1] !== undefined ? s2.split('.')[1].length : 0;
  86. } catch (e) {
  87. throw e;
  88. }
  89. return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m);
  90. },
  91. accAdd(arg1, arg2) {
  92. let r1;
  93. let r2;
  94. try {
  95. r1 = arg1.toString().split('.')[1].length;
  96. } catch (e) {
  97. r1 = 0;
  98. }
  99. try {
  100. r2 = arg2.toString().split('.')[1].length;
  101. } catch (e) {
  102. r2 = 0;
  103. }
  104. const c = Math.abs(r1 - r2);
  105. const m = Math.pow(10, Math.max(r1, r2));
  106. if (c > 0) {
  107. const cm = Math.pow(10, c);
  108. if (r1 > r2) {
  109. arg1 = Number(arg1.toString().replace('.', ''));
  110. arg2 = Number(arg2.toString().replace('.', '')) * cm;
  111. } else {
  112. arg1 = Number(arg1.toString().replace('.', '')) * cm;
  113. arg2 = Number(arg2.toString().replace('.', ''));
  114. }
  115. } else {
  116. arg1 = Number(arg1.toString().replace('.', ''));
  117. arg2 = Number(arg2.toString().replace('.', ''));
  118. }
  119. return (arg1 + arg2) / m;
  120. },
  121. // 四舍五入或末尾加零,实现类似php的 sprintf("%.".decimal."f", val);
  122. roundNum(val, decimals) {
  123. if (val !== '') {
  124. val = parseFloat(val);
  125. if (decimals < 1) {
  126. val = (Math.round(val)).toString();
  127. } else {
  128. let num = val.toString();
  129. if (num.lastIndexOf('.') === -1) {
  130. num += '.';
  131. num += this.makezero(decimals);
  132. val = num;
  133. } else {
  134. const valdecimals = num.split('.')[1].length;
  135. if (parseInt(valdecimals) < parseInt(decimals)) {
  136. num += this.makezero(parseInt(decimals) - parseInt(valdecimals));
  137. val = num;
  138. } else if (parseInt(valdecimals) > parseInt(decimals)) {
  139. val = parseFloat(val) !== 0 ? Math.round(this.accMul(val, this.makemultiple(decimals))) / this.makemultiple(decimals) : this.makedecimalzero(decimals);
  140. let 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. }
  151. }
  152. }
  153. }
  154. }
  155. }
  156. return val;
  157. },
  158. // 生成num位的0
  159. makezero(num) {
  160. const arr = new Array(num);
  161. for (let i = 0; i < num; i++) {
  162. arr[i] = 0;
  163. }
  164. return arr.join('');
  165. },
  166. // 生成num位的10倍数
  167. makemultiple(num) {
  168. return Math.pow(10, parseInt(num));
  169. },
  170. // 根据单位获取小数位数
  171. findDecimal(unit) {
  172. let value = this.ctx.tender.info.precision.other.value;
  173. const changeUnits = this.ctx.tender.info.precision;
  174. for (const d in changeUnits) {
  175. if (changeUnits[d].unit !== undefined && changeUnits[d].unit === unit) {
  176. value = changeUnits[d].value;
  177. break;
  178. }
  179. }
  180. return value;
  181. },
  182. /**
  183. * 显示排序符号
  184. *
  185. * @param {String} field - 字段名称
  186. * @return {String} - 返回字段排序的符号
  187. */
  188. showSortFlag(field) {
  189. const sort = this.ctx.sort;
  190. if (!(sort instanceof Array) || sort.length !== 2) {
  191. return '';
  192. }
  193. sort[1] = sort[1].toUpperCase();
  194. return (sort[0] === field && sort[1] === 'DESC') ? '' : '-';
  195. },
  196. /**
  197. * 判断是否为ajax请求
  198. *
  199. * @param {Object} request - 请求数据
  200. * @return {boolean} 判断结果
  201. */
  202. isAjax(request) {
  203. let headerInfo = request.headers['x-requested-with'] === undefined ? '' : request.headers['x-requested-with'];
  204. headerInfo = headerInfo.toLowerCase();
  205. return headerInfo === 'xmlhttprequest';
  206. },
  207. /**
  208. * 模拟发送请求
  209. *
  210. * @param {String} url - 请求地址
  211. * @param {Object} data - 请求数据
  212. * @param {String} type - 请求类型(POST) POST | GET
  213. * @param {String} dataType - 数据类型 json|text
  214. * @return {Object} - 请求结果
  215. */
  216. async sendRequest(url, data, type = 'POST', dataType = 'json') {
  217. // 发起请求
  218. const response = await this.ctx.curl(url, {
  219. method: type,
  220. data,
  221. dataType,
  222. });
  223. if (response.status !== 200) {
  224. throw '请求失败';
  225. }
  226. return response.data;
  227. },
  228. /**
  229. * 深度验证数据
  230. *
  231. * @param {Object} rule - 数据规则
  232. * @return {void}
  233. */
  234. validate(rule) {
  235. // 先用内置的验证器验证数据
  236. this.ctx.validate(rule);
  237. // 然后再验证是否有多余的数据
  238. const postData = this.ctx.request.body;
  239. delete postData._csrf;
  240. const postDataKey = Object.keys(postData);
  241. const ruleKey = Object.keys(rule);
  242. // 自动增加字段则填充上,以防判断出错
  243. if (postData.create_time !== undefined) {
  244. ruleKey.push('create_time');
  245. }
  246. for (const tmp of postDataKey) {
  247. // 规则里面没有定义则抛出异常
  248. if (ruleKey.indexOf(tmp) < 0) {
  249. throw '参数不正确';
  250. }
  251. }
  252. },
  253. /**
  254. * 拆分path
  255. *
  256. * @param {String|Array} paths - 拆分字符
  257. * @param {String} symbol - 拆分符号
  258. * @return {Array} - 拆分结果
  259. */
  260. explodePath(paths, symbol = '.') {
  261. const result = [];
  262. paths = paths instanceof Array ? paths : [paths];
  263. for (const path of paths) {
  264. // 拆分数据
  265. const pathArray = path.split(symbol);
  266. // 用户缓存循环的数据
  267. const tmpArray = [];
  268. for (const tmp of pathArray) {
  269. // 每次循环都追加一个数据进去
  270. tmpArray.push(tmp);
  271. const tmpPathString = tmpArray.join(symbol);
  272. // 判断是否已经存在有对应数据
  273. if (result.indexOf(tmpPathString) >= 0) {
  274. continue;
  275. }
  276. result.push(tmpPathString);
  277. }
  278. }
  279. return result;
  280. },
  281. /**
  282. * 基于obj, 拷贝sObj中的内容
  283. * obj = {a: 1, b: 2}, sObj = {a: 0, c: 3}, 返回{a: 0, b: 2, c: 3}
  284. * @param obj
  285. * @param sObj
  286. * @returns {any}
  287. */
  288. updateObj(obj, sObj) {
  289. if (!obj) {
  290. return JSON.parse(JSON.stringify(sObj));
  291. }
  292. const result = JSON.parse(JSON.stringify(obj));
  293. if (sObj) {
  294. for (const prop in sObj) {
  295. result[prop] = sObj[prop];
  296. }
  297. }
  298. return result;
  299. },
  300. /**
  301. * 在数组中查找
  302. * @param {Array} arr
  303. * @param name -
  304. * @param value
  305. * @returns {*}
  306. */
  307. findData(arr, name, value) {
  308. if (!arr instanceof Array) {
  309. throw '该方法仅用于数组查找';
  310. }
  311. if (arr.length === 0) { return undefined; }
  312. for (const data of arr) {
  313. if (data[name] == value) {
  314. return data;
  315. }
  316. }
  317. return undefined;
  318. },
  319. /**
  320. * 检查数字是否为0
  321. * @param {Number} value
  322. * @return {boolean}
  323. */
  324. checkZero(value) {
  325. return !(value && Math.abs(value) > zeroRange);
  326. },
  327. /**
  328. * 检查数字是否相等
  329. * @param {Number} value1
  330. * @param {Number} value2
  331. * @returns {boolean}
  332. */
  333. checkNumberEqual(value1, value2) {
  334. if (value1 && value2) {
  335. return Math.abs(value2 - value1) > zeroRange;
  336. } else {
  337. return (!value1 && !value2)
  338. }
  339. },
  340. /**
  341. * 比较编码
  342. * @param str1
  343. * @param str2
  344. * @param symbol
  345. * @returns {number}
  346. */
  347. compareCode(str1, str2, symbol = '-') {
  348. if (!str1) {
  349. return -1;
  350. } else if (!str2) {
  351. return 1;
  352. }
  353. const path1 = str1.split(symbol);
  354. const path2 = str2.split(symbol);
  355. for (let i = 0, iLen = Math.min(path1.length, path2.length); i < iLen; i++) {
  356. if (path1 < path2) {
  357. return -1;
  358. } else if (path1 > path2) {
  359. return 1;
  360. }
  361. }
  362. return path1.length - path2.length;
  363. },
  364. /**
  365. * 树结构节点排序,要求最顶层节点须在同一父节点下
  366. * @param treeNodes
  367. * @param idField
  368. * @param pidField
  369. */
  370. sortTreeNodes (treeNodes, idField, pidField) {
  371. const result = [];
  372. const getFirstLevel = function (nodes) {
  373. let result;
  374. for (const node of nodes) {
  375. if (!result || result > node.level) {
  376. result = node.level;
  377. }
  378. }
  379. return result;
  380. };
  381. const getLevelNodes = function (nodes, level) {
  382. const children = nodes.filter(function (a) {
  383. return a.level = level;
  384. });
  385. children.sort(function (a, b) {
  386. return a.order - b.order;
  387. })
  388. return children;
  389. };
  390. const getChildren = function (nodes, node) {
  391. const children = nodes.filter(function (a) {
  392. return a[pidField] = node[idField];
  393. });
  394. children.sort(function (a, b) {
  395. return a.order - b.order;
  396. });
  397. return children;
  398. };
  399. const addSortNodes = function (nodes) {
  400. for (let i = 0; i< nodes.length; i++) {
  401. result.push(nodes[i]);
  402. addSortNodes(getChildren(nodes[i]));
  403. }
  404. };
  405. const firstLevel = getFirstLevel(treeNodes);
  406. addSortNodes(getLevelNodes(treeNodes, firstLevel));
  407. },
  408. /**
  409. * 判断当前用户是否有指定权限
  410. *
  411. * @param {Number|Array} permission - 权限id
  412. * @return {Boolean} - 返回判断结果
  413. */
  414. hasPermission(permission) {
  415. let result = false;
  416. try {
  417. const sessionUser = this.ctx.session.sessionUser;
  418. if (sessionUser.permission === undefined) {
  419. throw '不存在权限数据';
  420. }
  421. let currentPermission = sessionUser.permission;
  422. if (currentPermission === '') {
  423. throw '权限数据为空';
  424. }
  425. // 管理员则直接返回结果
  426. if (currentPermission === 'all') {
  427. return true;
  428. }
  429. currentPermission = currentPermission.split(',');
  430. permission = permission instanceof Array ? permission : [permission];
  431. let counter = 0;
  432. for (const tmp of permission) {
  433. if (currentPermission[tmp] !== undefined) {
  434. counter++;
  435. }
  436. }
  437. result = counter === permission.length;
  438. } catch (error) {
  439. result = false;
  440. }
  441. return result;
  442. },
  443. /**
  444. * 递归创建文件夹(fs.mkdirSync需要上一层文件夹已存在)
  445. * @param pathName
  446. * @returns {Promise<void>}
  447. */
  448. async recursiveMkdirSync(pathName) {
  449. const upperPath = path.dirname(pathName);
  450. if (!fs.existsSync(upperPath)) {
  451. await this.recursiveMkdirSync(upperPath);
  452. }
  453. await fs.mkdirSync(pathName);
  454. },
  455. /**
  456. * 字节 保存至 本地文件
  457. * @param buffer - 字节
  458. * @param fileName - 文件名
  459. * @returns {Promise<void>}
  460. */
  461. async saveBufferFile(buffer, fileName) {
  462. // 检查文件夹是否存在,不存在则直接创建文件夹
  463. const pathName = path.dirname(fileName);
  464. if (!fs.existsSync(pathName)) {
  465. await this.recursiveMkdirSync(pathName);
  466. }
  467. await fs.writeFileSync(fileName, buffer);
  468. },
  469. /**
  470. * 将文件流的数据保存至本地文件
  471. * @param stream
  472. * @param fileName
  473. * @returns {Promise<void>}
  474. */
  475. async saveStreamFile(stream, fileName) {
  476. // 读取字节流
  477. const parts = await streamToArray(stream);
  478. // 转化为buffer
  479. const buffer = Buffer.concat(parts);
  480. // 写入文件
  481. await this.saveBufferFile(buffer, fileName);
  482. },
  483. /**
  484. * 检查code是否是指标模板数据
  485. * @param {String} code
  486. * @returns {boolean}
  487. */
  488. validBillsCode(code) {
  489. const reg1 = /(^[0-9]+)([a-z0-9\-]*)/i;
  490. const reg2 = /([a-z0-9]+$)/i;
  491. return reg1.test(code) && reg2.test(code);
  492. },
  493. getNumberFormatter(decimal) {
  494. if (decimal <= 0) {
  495. return "0";
  496. }
  497. let pre = "0.";
  498. for (let i = 0; i < decimal; i++) {
  499. pre += "#"
  500. }
  501. return pre;
  502. },
  503. /**
  504. * 根据单位查找对应的清单精度
  505. * @param {tenderInfo.precision} list - 清单精度列表
  506. * @param {String} unit - 单位
  507. * @returns {number}
  508. */
  509. findPrecision(list, unit) {
  510. if (unit) {
  511. for (const p in list) {
  512. if (list[p].unit && list[p].unit === unit) {
  513. return list[p];
  514. }
  515. }
  516. }
  517. return list.other;
  518. },
  519. /**
  520. * 检查数据中的精度
  521. * @param {Object} Obj - 检查的数据
  522. * @param {Array} fields - 检查的属性
  523. * @param {Number} precision - 精度
  524. * @constructor
  525. */
  526. checkFieldPrecision(Obj, fields, precision = 2) {
  527. if (Obj) {
  528. for (const field of fields) {
  529. if (Obj[field]) {
  530. Obj[field] = this.round(Obj[field], precision);
  531. }
  532. }
  533. }
  534. },
  535. /**
  536. * 过滤无效数据
  537. *
  538. * @param obj
  539. * @param fields - 有效数据的数组
  540. */
  541. filterValidFields(data, fields) {
  542. if (data) {
  543. const result = {};
  544. for (const prop in data) {
  545. if (fields.indexOf(prop) !== -1) {
  546. result[prop] = data[prop];
  547. }
  548. }
  549. return result;
  550. } else {
  551. return data;
  552. }
  553. },
  554. // 以下方法均调用number-precision处理
  555. // 加减乘除方法,为方便调用,兼容num为空的情况
  556. /**
  557. * 加法 num1 + num2
  558. * @param num1
  559. * @param num2
  560. * @returns {number}
  561. */
  562. plus(num1, num2) {
  563. return np.plus(num1 ? num1 : 0, num2 ? num2: 0);
  564. },
  565. /**
  566. * 减法 num1 - num2
  567. * @param num1
  568. * @param num2
  569. * @returns {number}
  570. */
  571. minus(num1, num2) {
  572. return np.minus(num1 ? num1 : 0, num2 ? num2 : 0);
  573. },
  574. /**
  575. * 乘法 num1 * num2
  576. * @param num1
  577. * @param num2
  578. * @returns {*}
  579. */
  580. times(num1, num2) {
  581. return np.times(num1 ? num1 : 0, num2 ? num2 : 0);
  582. },
  583. /**
  584. * 除法 num1 / num2
  585. * @param num1 - 被除数
  586. * @param num2 - 除数
  587. * @returns {*}
  588. */
  589. divide(num1, num2) {
  590. if (num2 && !this.checkZero(num2)) {
  591. return np.divide(num1 ? num1: 0, num2);
  592. } else {
  593. return null;
  594. }
  595. },
  596. /**
  597. * 四舍五入(统一,方便以后万一需要置换)
  598. * @param {Number} value - 舍入的数字
  599. * @param {Number} decimal - 要保留的小数位数
  600. * @returns {*}
  601. */
  602. round(value, decimal) {
  603. return value ? np.round(value, decimal) : null;
  604. },
  605. /**
  606. * 汇总
  607. * @param array
  608. * @returns {number}
  609. */
  610. sum(array) {
  611. let result = 0;
  612. for (const a of array) {
  613. result = this.plus(result, a);
  614. }
  615. return result;
  616. },
  617. // // 以下方法均使用js自有方法,保留10位小数
  618. // /**
  619. // * 加法 num1 + num2
  620. // * @param num1
  621. // * @param num2
  622. // * @returns {number}
  623. // */
  624. // plus(num1, num2) {
  625. // return _.round((num1 ? num1 : 0) + (num2 ? num2: 0), 10);
  626. // },
  627. // /**
  628. // * 减法 num1 - num2
  629. // * @param num1
  630. // * @param num2
  631. // * @returns {number}
  632. // */
  633. // minus(num1, num2) {
  634. // return _.round((num1 ? num1 : 0) - (num2 ? num2: 0), 10);
  635. // },
  636. // /**
  637. // * 乘法 num1 * num2
  638. // * @param num1
  639. // * @param num2
  640. // * @returns {*}
  641. // */
  642. // times(num1, num2) {
  643. // return _.round((num1 ? num1 : 0) * (num2 ? num2: 0), 10);
  644. // },
  645. // /**
  646. // * 除法 num1 / num2
  647. // * @param num1 - 被除数
  648. // * @param num2 - 除数
  649. // * @returns {*}
  650. // */
  651. // divide(num1, num2) {
  652. // if (num2 && !this.checkZero(num2)) {
  653. // return _.round((num1 ? num1 : 0) / (num2 ? num2: 0), 10);
  654. // } else {
  655. // return null;
  656. // }
  657. // },
  658. // /**
  659. // * 四舍五入(统一,方便以后万一需要置换)
  660. // * @param {Number} value - 舍入的数字
  661. // * @param {Number} decimal - 要保留的小数位数
  662. // * @returns {*}
  663. // */
  664. // round(value, decimal) {
  665. // return value ? _.round(value, decimal) : null;
  666. // },
  667. // /**
  668. // * 汇总
  669. // * @param array
  670. // * @returns {number}
  671. // */
  672. // sum(array) {
  673. // let result = 0;
  674. // for (const a of array) {
  675. // result = this.plus(result, a);
  676. // }
  677. // return result;
  678. // }
  679. };