helper.js 35 KB

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