helper.js 18 KB

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