helper.js 19 KB

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