helper.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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 bc = require('../lib/base_calc.js');
  15. const Decimal = require('decimal.js');
  16. Decimal.set({precision: 50, defaults: true});
  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. try {
  219. const response = await this.ctx.curl(url, {
  220. method: type,
  221. data,
  222. dataType,
  223. });
  224. if (response.status !== 200) {
  225. throw '请求失败';
  226. }
  227. return response.data;
  228. } catch(err) {
  229. throw '请求失败';
  230. }
  231. },
  232. /**
  233. * 深度验证数据
  234. *
  235. * @param {Object} rule - 数据规则
  236. * @return {void}
  237. */
  238. validate(rule) {
  239. // 先用内置的验证器验证数据
  240. this.ctx.validate(rule);
  241. // 然后再验证是否有多余的数据
  242. const postData = this.ctx.request.body;
  243. delete postData._csrf;
  244. const postDataKey = Object.keys(postData);
  245. const ruleKey = Object.keys(rule);
  246. // 自动增加字段则填充上,以防判断出错
  247. if (postData.create_time !== undefined) {
  248. ruleKey.push('create_time');
  249. }
  250. for (const tmp of postDataKey) {
  251. // 规则里面没有定义则抛出异常
  252. if (ruleKey.indexOf(tmp) < 0) {
  253. throw '参数不正确';
  254. }
  255. }
  256. },
  257. /**
  258. * 拆分path
  259. *
  260. * @param {String|Array} paths - 拆分字符
  261. * @param {String} symbol - 拆分符号
  262. * @return {Array} - 拆分结果
  263. */
  264. explodePath(paths, symbol = '.') {
  265. const result = [];
  266. paths = paths instanceof Array ? paths : [paths];
  267. for (const path of paths) {
  268. // 拆分数据
  269. const pathArray = path.split(symbol);
  270. // 用户缓存循环的数据
  271. const tmpArray = [];
  272. for (const tmp of pathArray) {
  273. // 每次循环都追加一个数据进去
  274. tmpArray.push(tmp);
  275. const tmpPathString = tmpArray.join(symbol);
  276. // 判断是否已经存在有对应数据
  277. if (result.indexOf(tmpPathString) >= 0) {
  278. continue;
  279. }
  280. result.push(tmpPathString);
  281. }
  282. }
  283. return result;
  284. },
  285. /**
  286. * 基于obj, 拷贝sObj中的内容
  287. * obj = {a: 1, b: 2}, sObj = {a: 0, c: 3}, 返回{a: 0, b: 2, c: 3}
  288. * @param obj
  289. * @param sObj
  290. * @returns {any}
  291. */
  292. updateObj(obj, sObj) {
  293. if (!obj) {
  294. return JSON.parse(JSON.stringify(sObj));
  295. }
  296. const result = JSON.parse(JSON.stringify(obj));
  297. if (sObj) {
  298. for (const prop in sObj) {
  299. result[prop] = sObj[prop];
  300. }
  301. }
  302. return result;
  303. },
  304. /**
  305. * 在数组中查找
  306. * @param {Array} arr
  307. * @param name -
  308. * @param value
  309. * @returns {*}
  310. */
  311. findData(arr, name, value) {
  312. if (!arr instanceof Array) {
  313. throw '该方法仅用于数组查找';
  314. }
  315. if (arr.length === 0) { return undefined; }
  316. for (const data of arr) {
  317. if (data[name] == value) {
  318. return data;
  319. }
  320. }
  321. return undefined;
  322. },
  323. /**
  324. * 检查数字是否为0
  325. * @param {Number} value
  326. * @return {boolean}
  327. */
  328. checkZero(value) {
  329. return !(value && Math.abs(value) > zeroRange);
  330. },
  331. /**
  332. * 检查数字是否相等
  333. * @param {Number} value1
  334. * @param {Number} value2
  335. * @returns {boolean}
  336. */
  337. checkNumberEqual(value1, value2) {
  338. if (value1 && value2) {
  339. return Math.abs(value2 - value1) > zeroRange;
  340. } else {
  341. return (!value1 && !value2)
  342. }
  343. },
  344. /**
  345. * 比较编码
  346. * @param str1
  347. * @param str2
  348. * @param symbol
  349. * @returns {number}
  350. */
  351. compareCode(str1, str2, symbol = '-') {
  352. if (!str1) {
  353. return -1;
  354. } else if (!str2) {
  355. return 1;
  356. }
  357. const path1 = str1.split(symbol);
  358. const path2 = str2.split(symbol);
  359. for (let i = 0, iLen = Math.min(path1.length, path2.length); i < iLen; i++) {
  360. if (path1 < path2) {
  361. return -1;
  362. } else if (path1 > path2) {
  363. return 1;
  364. }
  365. }
  366. return path1.length - path2.length;
  367. },
  368. /**
  369. * 树结构节点排序,要求最顶层节点须在同一父节点下
  370. * @param treeNodes
  371. * @param idField
  372. * @param pidField
  373. */
  374. sortTreeNodes (treeNodes, idField, pidField) {
  375. const result = [];
  376. const getFirstLevel = function (nodes) {
  377. let result;
  378. for (const node of nodes) {
  379. if (!result || result > node.level) {
  380. result = node.level;
  381. }
  382. }
  383. return result;
  384. };
  385. const getLevelNodes = function (nodes, level) {
  386. const children = nodes.filter(function (a) {
  387. return a.level = level;
  388. });
  389. children.sort(function (a, b) {
  390. return a.order - b.order;
  391. });
  392. return children;
  393. };
  394. const getChildren = function (nodes, node) {
  395. const children = nodes.filter(function (a) {
  396. return a[pidField] = node[idField];
  397. });
  398. children.sort(function (a, b) {
  399. return a.order - b.order;
  400. });
  401. return children;
  402. };
  403. const addSortNodes = function (nodes) {
  404. for (let i = 0; i< nodes.length; i++) {
  405. result.push(nodes[i]);
  406. addSortNodes(getChildren(nodes[i]));
  407. }
  408. };
  409. const firstLevel = getFirstLevel(treeNodes);
  410. addSortNodes(getLevelNodes(treeNodes, firstLevel));
  411. },
  412. /**
  413. * 判断当前用户是否有指定权限
  414. *
  415. * @param {Number|Array} permission - 权限id
  416. * @return {Boolean} - 返回判断结果
  417. */
  418. hasPermission(permission) {
  419. let result = false;
  420. try {
  421. const sessionUser = this.ctx.session.sessionUser;
  422. if (sessionUser.permission === undefined) {
  423. throw '不存在权限数据';
  424. }
  425. let currentPermission = sessionUser.permission;
  426. if (currentPermission === '') {
  427. throw '权限数据为空';
  428. }
  429. // 管理员则直接返回结果
  430. if (currentPermission === 'all') {
  431. return true;
  432. }
  433. currentPermission = currentPermission.split(',');
  434. permission = permission instanceof Array ? permission : [permission];
  435. let counter = 0;
  436. for (const tmp of permission) {
  437. if (currentPermission[tmp] !== undefined) {
  438. counter++;
  439. }
  440. }
  441. result = counter === permission.length;
  442. } catch (error) {
  443. result = false;
  444. }
  445. return result;
  446. },
  447. /**
  448. * 递归创建文件夹(fs.mkdirSync需要上一层文件夹已存在)
  449. * @param pathName
  450. * @returns {Promise<void>}
  451. */
  452. async recursiveMkdirSync(pathName) {
  453. const upperPath = path.dirname(pathName);
  454. if (!fs.existsSync(upperPath)) {
  455. await this.recursiveMkdirSync(upperPath);
  456. }
  457. await fs.mkdirSync(pathName);
  458. },
  459. /**
  460. * 字节 保存至 本地文件
  461. * @param buffer - 字节
  462. * @param fileName - 文件名
  463. * @returns {Promise<void>}
  464. */
  465. async saveBufferFile(buffer, fileName) {
  466. // 检查文件夹是否存在,不存在则直接创建文件夹
  467. const pathName = path.dirname(fileName);
  468. if (!fs.existsSync(pathName)) {
  469. await this.recursiveMkdirSync(pathName);
  470. }
  471. await fs.writeFileSync(fileName, buffer);
  472. },
  473. /**
  474. * 将文件流的数据保存至本地文件
  475. * @param stream
  476. * @param fileName
  477. * @returns {Promise<void>}
  478. */
  479. async saveStreamFile(stream, fileName) {
  480. // 读取字节流
  481. const parts = await streamToArray(stream);
  482. // 转化为buffer
  483. const buffer = Buffer.concat(parts);
  484. // 写入文件
  485. await this.saveBufferFile(buffer, fileName);
  486. },
  487. /**
  488. * 检查code是否是指标模板数据
  489. * @param {String} code
  490. * @returns {boolean}
  491. */
  492. validBillsCode(code) {
  493. const reg1 = /(^[0-9]+)([a-z0-9\-]*)/i;
  494. const reg2 = /([a-z0-9]+$)/i;
  495. return reg1.test(code) && reg2.test(code);
  496. },
  497. getNumberFormatter(decimal) {
  498. if (decimal <= 0) {
  499. return "0";
  500. }
  501. let pre = "0.";
  502. for (let i = 0; i < decimal; i++) {
  503. pre += "#"
  504. }
  505. return pre;
  506. },
  507. /**
  508. * 根据单位查找对应的清单精度
  509. * @param {tenderInfo.precision} list - 清单精度列表
  510. * @param {String} unit - 单位
  511. * @returns {number}
  512. */
  513. findPrecision(list, unit) {
  514. if (unit) {
  515. for (const p in list) {
  516. if (list[p].unit && list[p].unit === unit) {
  517. return list[p];
  518. }
  519. }
  520. }
  521. return list.other;
  522. },
  523. /**
  524. * 检查数据中的精度
  525. * @param {Object} Obj - 检查的数据
  526. * @param {Array} fields - 检查的属性
  527. * @param {Number} precision - 精度
  528. * @constructor
  529. */
  530. checkFieldPrecision(Obj, fields, precision = 2) {
  531. if (Obj) {
  532. for (const field of fields) {
  533. if (Obj[field]) {
  534. Obj[field] = this.round(Obj[field], precision);
  535. }
  536. }
  537. }
  538. },
  539. /**
  540. * 过滤无效数据
  541. *
  542. * @param obj
  543. * @param fields - 有效数据的数组
  544. */
  545. filterValidFields(data, fields) {
  546. if (data) {
  547. const result = {};
  548. for (const prop in data) {
  549. if (fields.indexOf(prop) !== -1) {
  550. result[prop] = data[prop];
  551. }
  552. }
  553. return result;
  554. } else {
  555. return data;
  556. }
  557. },
  558. // 加减乘除方法,为方便调用,兼容num为空的情况
  559. // 加减法使用base_calc,乘除法使用Decimal(原因详见demo/calc_test)
  560. /**
  561. * 加法 num1 + num2
  562. * @param num1
  563. * @param num2
  564. * @returns {number}
  565. */
  566. add(num1, num2) {
  567. return bc.add(num1 ? num1 : 0, num2 ? num2: 0);
  568. },
  569. /**
  570. * 减法 num1 - num2
  571. * @param num1
  572. * @param num2
  573. * @returns {number}
  574. */
  575. sub(num1, num2) {
  576. return bc.sub(num1 ? num1 : 0, num2 ? num2 : 0);
  577. },
  578. /**
  579. * 乘法 num1 * num2
  580. * @param num1
  581. * @param num2
  582. * @returns {*}
  583. */
  584. mul(num1, num2, digit = 6) {
  585. return Decimal.mul(num1 ? num1 : 0, num2 ? num2 : 0).toDecimalPlaces(digit).toNumber();
  586. },
  587. /**
  588. * 除法 num1 / num2
  589. * @param num1 - 被除数
  590. * @param num2 - 除数
  591. * @returns {*}
  592. */
  593. div(num1, num2, digit = 6) {
  594. if (num2 && !this.checkZero(num2)) {
  595. return Decimal.div(num1 ? num1: 0, num2).toDecimalPlaces(digit).toNumber();
  596. } else {
  597. return null;
  598. }
  599. },
  600. /**
  601. * 四舍五入(统一,方便以后万一需要置换)
  602. * @param {Number} value - 舍入的数字
  603. * @param {Number} decimal - 要保留的小数位数
  604. * @returns {*}
  605. */
  606. round(value, decimal) {
  607. //return value ? bc.round(value, decimal) : null;
  608. return value ? new Decimal(value).toDecimalPlaces(decimal).toNumber() : null;
  609. },
  610. /**
  611. * 汇总
  612. * @param array
  613. * @returns {number}
  614. */
  615. sum(array) {
  616. let result = 0;
  617. for (const a of array) {
  618. result = this.add(result, a);
  619. }
  620. return result;
  621. },
  622. };