helper.js 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  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. let 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. let 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. * @returns {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. * @returns {*}
  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. * @returns {boolean}
  347. */
  348. checkNumberEqual(value1, value2) {
  349. if (value1 && value2) {
  350. return Math.abs(value2 - value1) > zeroRange;
  351. } else {
  352. return (!value1 && !value2)
  353. }
  354. },
  355. /**
  356. * 比较编码
  357. * @param str1
  358. * @param str2
  359. * @param symbol
  360. * @returns {number}
  361. */
  362. compareCode(str1, str2, symbol = '-') {
  363. if (!str1) {
  364. return 1;
  365. } else if (!str2) {
  366. return -1;
  367. }
  368. function compareSubCode(code1, code2) {
  369. if (numReg.test(code1)) {
  370. if (numReg.test(code2)) {
  371. return parseInt(code1) - parseInt(code2);
  372. } else {
  373. return -1
  374. }
  375. } else {
  376. if (numReg.test(code2)) {
  377. return 1;
  378. } else {
  379. return code1 === code2 ? 0 : (code1 < code2 ? -1 : 1); //code1.localeCompare(code2);
  380. }
  381. }
  382. }
  383. const numReg = /^[0-9]+$/;
  384. const aCodes = str1.split(symbol), bCodes = str2.split(symbol);
  385. for (let i = 0, iLength = Math.min(aCodes.length, bCodes.length); i < iLength; ++i) {
  386. const iCompare = compareSubCode(aCodes[i], bCodes[i]);
  387. if (iCompare !== 0) {
  388. return iCompare;
  389. }
  390. }
  391. return aCodes.length - bCodes.length;
  392. },
  393. /**
  394. * 根据 清单编号 获取 章级编号
  395. * @param code
  396. * @param symbol
  397. * @returns {string}
  398. */
  399. getChapterCode(code, symbol = '-') {
  400. if (!code || code === '') return '';
  401. const codePath = code.split(symbol);
  402. const reg = /^[^0-9]*[0-9]{3,4}$/;
  403. if (reg.test(codePath[0])) {
  404. const numReg = /[0-9]{3,4}$/;
  405. const result = codePath[0].match(numReg);
  406. const num = parseInt(result[0]);
  407. return this.mul(this.div(num, 100, 0), 100) + '';
  408. } else {
  409. return '10000';
  410. }
  411. },
  412. /**
  413. * 树结构节点排序,要求最顶层节点须在同一父节点下
  414. * @param treeNodes
  415. * @param idField
  416. * @param pidField
  417. */
  418. sortTreeNodes (treeNodes, idField, pidField) {
  419. const result = [];
  420. const getFirstLevel = function (nodes) {
  421. let result;
  422. for (const node of nodes) {
  423. if (!result || result > node.level) {
  424. result = node.level;
  425. }
  426. }
  427. return result;
  428. };
  429. const getLevelNodes = function (nodes, level) {
  430. const children = nodes.filter(function (a) {
  431. return a.level = level;
  432. });
  433. children.sort(function (a, b) {
  434. return a.order - b.order;
  435. });
  436. return children;
  437. };
  438. const getChildren = function (nodes, node) {
  439. const children = nodes.filter(function (a) {
  440. return a[pidField] = node[idField];
  441. });
  442. children.sort(function (a, b) {
  443. return a.order - b.order;
  444. });
  445. return children;
  446. };
  447. const addSortNodes = function (nodes) {
  448. for (let i = 0; i< nodes.length; i++) {
  449. result.push(nodes[i]);
  450. addSortNodes(getChildren(nodes[i]));
  451. }
  452. };
  453. const firstLevel = getFirstLevel(treeNodes);
  454. addSortNodes(getLevelNodes(treeNodes, firstLevel));
  455. },
  456. /**
  457. * 判断当前用户是否有指定权限
  458. *
  459. * @param {Number|Array} permission - 权限id
  460. * @return {Boolean} - 返回判断结果
  461. */
  462. hasPermission(permission) {
  463. let result = false;
  464. try {
  465. const sessionUser = this.ctx.session.sessionUser;
  466. if (sessionUser.permission === undefined) {
  467. throw '不存在权限数据';
  468. }
  469. let currentPermission = sessionUser.permission;
  470. if (currentPermission === '') {
  471. throw '权限数据为空';
  472. }
  473. // 管理员则直接返回结果
  474. if (currentPermission === 'all') {
  475. return true;
  476. }
  477. currentPermission = currentPermission.split(',');
  478. permission = permission instanceof Array ? permission : [permission];
  479. let counter = 0;
  480. for (const tmp of permission) {
  481. if (currentPermission[tmp] !== undefined) {
  482. counter++;
  483. }
  484. }
  485. result = counter === permission.length;
  486. } catch (error) {
  487. result = false;
  488. }
  489. return result;
  490. },
  491. /**
  492. * 递归创建文件夹(fs.mkdirSync需要上一层文件夹已存在)
  493. * @param pathName
  494. * @returns {Promise<void>}
  495. */
  496. async recursiveMkdirSync(pathName) {
  497. if (!fs.existsSync(pathName)) {
  498. const upperPath = path.dirname(pathName);
  499. if (!fs.existsSync(upperPath)) {
  500. await this.recursiveMkdirSync(upperPath);
  501. }
  502. await fs.mkdirSync(pathName);
  503. }
  504. },
  505. /**
  506. * 字节 保存至 本地文件
  507. * @param buffer - 字节
  508. * @param fileName - 文件名
  509. * @returns {Promise<void>}
  510. */
  511. async saveBufferFile(buffer, fileName) {
  512. // 检查文件夹是否存在,不存在则直接创建文件夹
  513. const pathName = path.dirname(fileName);
  514. if (!fs.existsSync(pathName)) {
  515. await this.recursiveMkdirSync(pathName);
  516. }
  517. await fs.writeFileSync(fileName, buffer);
  518. },
  519. /**
  520. * 将文件流的数据保存至本地文件
  521. * @param stream
  522. * @param fileName
  523. * @returns {Promise<void>}
  524. */
  525. async saveStreamFile(stream, fileName) {
  526. // 读取字节流
  527. const parts = await streamToArray(stream);
  528. // 转化为buffer
  529. const buffer = Buffer.concat(parts);
  530. // 写入文件
  531. await this.saveBufferFile(buffer, fileName);
  532. },
  533. /**
  534. * 检查code是否是指标模板数据
  535. * @param {String} code
  536. * @returns {boolean}
  537. */
  538. validBillsCode(code) {
  539. const reg1 = /(^[0-9]+)([a-z0-9\-]*)/i;
  540. const reg2 = /([a-z0-9]+$)/i;
  541. return reg1.test(code) && reg2.test(code);
  542. },
  543. getNumberFormatter(decimal) {
  544. if (decimal <= 0) {
  545. return "0";
  546. }
  547. let pre = "0.";
  548. for (let i = 0; i < decimal; i++) {
  549. pre += "#"
  550. }
  551. return pre;
  552. },
  553. /**
  554. * 根据单位查找对应的清单精度
  555. * @param {tenderInfo.precision} list - 清单精度列表
  556. * @param {String} unit - 单位
  557. * @returns {number}
  558. */
  559. findPrecision(list, unit) {
  560. if (unit) {
  561. for (const p in list) {
  562. if (list[p].unit && list[p].unit === unit) {
  563. return list[p];
  564. }
  565. }
  566. }
  567. return list.other;
  568. },
  569. /**
  570. * 检查数据中的精度
  571. * @param {Object} Obj - 检查的数据
  572. * @param {Array} fields - 检查的属性
  573. * @param {Number} precision - 精度
  574. * @constructor
  575. */
  576. checkFieldPrecision(Obj, fields, precision = 2) {
  577. if (Obj) {
  578. for (const field of fields) {
  579. if (Obj[field]) {
  580. Obj[field] = this.round(Obj[field], precision);
  581. }
  582. }
  583. }
  584. },
  585. /**
  586. * 过滤无效数据
  587. *
  588. * @param obj
  589. * @param fields - 有效数据的数组
  590. */
  591. filterValidFields(data, fields) {
  592. if (data) {
  593. const result = {};
  594. for (const prop in data) {
  595. if (fields.indexOf(prop) !== -1) {
  596. result[prop] = data[prop];
  597. }
  598. }
  599. return result;
  600. } else {
  601. return data;
  602. }
  603. },
  604. // 加减乘除方法,为方便调用,兼容num为空的情况
  605. // 加减法使用base_calc,乘除法使用Decimal(原因详见demo/calc_test)
  606. /**
  607. * 加法 num1 + num2
  608. * @param num1
  609. * @param num2
  610. * @returns {number}
  611. */
  612. add(num1, num2) {
  613. return bc.add(num1 ? num1 : 0, num2 ? num2: 0);
  614. },
  615. /**
  616. * 减法 num1 - num2
  617. * @param num1
  618. * @param num2
  619. * @returns {number}
  620. */
  621. sub(num1, num2) {
  622. return bc.sub(num1 ? num1 : 0, num2 ? num2 : 0);
  623. },
  624. /**
  625. * 乘法 num1 * num2
  626. * @param num1
  627. * @param num2
  628. * @returns {*}
  629. */
  630. mul(num1, num2, digit = 6) {
  631. if (num1 === '' || num1 === null || num2 === '' || num2 === null) {
  632. return 0;
  633. }
  634. return Decimal.mul(num1 ? num1 : 0, num2 ? num2 : 0).toDecimalPlaces(digit).toNumber();
  635. },
  636. /**
  637. * 除法 num1 / num2
  638. * @param num1 - 被除数
  639. * @param num2 - 除数
  640. * @returns {*}
  641. */
  642. div(num1, num2, digit = 6) {
  643. if (num2 && !this.checkZero(num2)) {
  644. return Decimal.div(num1 ? num1: 0, num2).toDecimalPlaces(digit).toNumber();
  645. } else {
  646. return null;
  647. }
  648. },
  649. /**
  650. * 四舍五入(统一,方便以后万一需要置换)
  651. * @param {Number} value - 舍入的数字
  652. * @param {Number} decimal - 要保留的小数位数
  653. * @returns {*}
  654. */
  655. round(value, decimal) {
  656. //return value ? bc.round(value, decimal) : null;
  657. return value ? new Decimal(value).toDecimalPlaces(decimal).toNumber() : null;
  658. },
  659. /**
  660. * 汇总
  661. * @param array
  662. * @returns {number}
  663. */
  664. sum(array) {
  665. let result = 0;
  666. for (const a of array) {
  667. result = this.add(result, a);
  668. }
  669. return result;
  670. },
  671. /**
  672. * 使用正则替换字符
  673. * @param str
  674. * @param reg
  675. * @param subStr
  676. * @returns {*}
  677. */
  678. replaceStr(str, reg, subStr) {
  679. return str ? str.replace(reg, subStr) : str;
  680. },
  681. /**
  682. * 替换字符串中的 换行符回车符
  683. * @param str
  684. * @returns {*}
  685. */
  686. replaceReturn(str) {
  687. // return str
  688. // ? (typeof str === 'string') ? str.replace(/[\r\n]/g, '') : str + ''
  689. // : str;
  690. return (str && typeof str === 'string')
  691. ? str.replace(/[\r\n]/g, '')
  692. : !_.isNil(str) ? str + '' : str;
  693. },
  694. /**
  695. * 替换字符串中的 换行符回车符为换行符<br>
  696. * @param str
  697. * @returns {*}
  698. */
  699. replaceRntoBr(str) {
  700. // return str
  701. // ? (typeof str === 'string') ? str.replace(/[\r\n]/g, '') : str + ''
  702. // : str;
  703. return (str && typeof str === 'string')
  704. ? str.replace(/[\r\n]/g, '<br>')
  705. : !_.isNil(str) ? str + '' : str;
  706. },
  707. /**
  708. * 获取 字符串 数组的 mysql 筛选条件
  709. *
  710. * @param arr
  711. * @returns {*}
  712. */
  713. getInArrStrSqlFilter(arr) {
  714. let result = '';
  715. for (const a of arr) {
  716. if (result !== '') {
  717. result = result + ','
  718. }
  719. result = result + this.ctx.app.mysql.escape(a);
  720. }
  721. return result;
  722. },
  723. /**
  724. * 合并 相关数据
  725. * @param {Array} main - 主数据
  726. * @param {Array[]}rela - 相关数据 {data, fields, prefix, relaId}
  727. */
  728. assignRelaData(main, rela) {
  729. const index = {}, indexPre = 'id_';
  730. const loadFields = function (datas, fields, prefix, relaId) {
  731. for (const d of datas) {
  732. const key = indexPre + d[relaId];
  733. const m = index[key];
  734. if (m) {
  735. for (const f of fields) {
  736. if (d[f] !== undefined) {
  737. m[prefix + f] = d[f];
  738. }
  739. }
  740. }
  741. }
  742. };
  743. for (const m of main) {
  744. index[indexPre + m.id] = m;
  745. }
  746. for (const r of rela) {
  747. loadFields(r.data, r.fields, r.prefix, r.relaId);
  748. }
  749. },
  750. whereSql (where, as) {
  751. if (!where) {
  752. return '';
  753. }
  754. const wheres = [];
  755. const values = [];
  756. for (const key in where) {
  757. const value = where[key];
  758. if (Array.isArray(value)) {
  759. wheres.push('?? IN (?)');
  760. } else {
  761. wheres.push('?? = ?');
  762. }
  763. values.push((as && as !== '') ? as + '.' + key : key);
  764. values.push(value);
  765. }
  766. if (wheres.length > 0) {
  767. return this.ctx.app.mysql.format(' WHERE ' + wheres.join(' AND '), values);
  768. }
  769. return '';
  770. },
  771. formatMoney(s, dot = ',') {
  772. if (!s) return '0.00';
  773. s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(2) + "";
  774. var l = s.split(".")[0].split("").reverse(),
  775. r = s.split(".")[1];
  776. let t = "";
  777. for(let i = 0; i < l.length; i ++ ) {
  778. t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? dot : "");
  779. }
  780. return t.split("").reverse().join("") + "." + r;
  781. },
  782. transFormToChinese(num) {
  783. const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  784. const unit = ["", "十", "百", "千", "万"];
  785. num = parseInt(num);
  786. let getWan = (temp) => {
  787. let strArr = temp.toString().split("").reverse();
  788. let newNum = "";
  789. for (var i = 0; i < strArr.length; i++) {
  790. 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;
  791. }
  792. return strArr.length === 2 && newNum.indexOf("一十") !== -1 ? newNum.replace('一十', '十') : newNum;
  793. }
  794. let overWan = Math.floor(num / 10000);
  795. let noWan = num % 10000;
  796. if (noWan.toString().length < 4) noWan = "0" + noWan;
  797. return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
  798. },
  799. dateTran(time) {
  800. return moment(time).format('YYYY年MM月DD日 HH:mm');
  801. },
  802. timeAdd(duration) {
  803. const d = parseInt(duration);
  804. let time = 0;
  805. if (d === 1) {
  806. time = 60 * 15 * 1000;
  807. } else if (d === 2) {
  808. time = 60 * 30 * 1000;
  809. } else if (d === 3) {
  810. time = 3600 * 1000;
  811. } else if (d === 4) {
  812. time = 3600 * 2 * 1000;
  813. }
  814. return time;
  815. },
  816. async sendUserSms(userId, type, judge, msg) {
  817. const mobiles = [];
  818. if (!userId || (userId instanceof Array && userId.length === 0)) return;
  819. const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  820. for (const su of smsUser) {
  821. if (!su.auth_mobile || su.auth_mobile === '') continue;
  822. if (!su.sms_type || su.sms_type === '') continue;
  823. const smsType = JSON.parse(su.sms_type);
  824. if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
  825. mobiles.push(su.auth_mobile);
  826. }
  827. }
  828. if (mobiles.length > 0) {
  829. const sms = new SMS(this.ctx);
  830. const tenderName = await sms.contentChange(this.ctx.tender.data.name);
  831. const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
  832. const ptmsg = projectName !== '' ? '项目「' + projectName + '」标段「' + tenderName + '」' : tenderName;
  833. const content = '【纵横计量支付】' + ptmsg + msg;
  834. sms.send(mobiles, content);
  835. }
  836. },
  837. async sendAliSms(userId, type, judge, code, data = {}) {
  838. const mobiles = [];
  839. if (!userId || (userId instanceof Array && userId.length === 0)) return;
  840. const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  841. for (const su of smsUser) {
  842. if (!su.auth_mobile || su.auth_mobile === '') continue;
  843. if (!su.sms_type || su.sms_type === '') continue;
  844. const smsType = JSON.parse(su.sms_type);
  845. if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
  846. mobiles.push(su.auth_mobile);
  847. }
  848. }
  849. if (mobiles.length > 0) {
  850. const sms = new SMS(this.ctx);
  851. const tenderName = await sms.contentChange(this.ctx.tender.data.name);
  852. const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
  853. const param = {
  854. project: projectName,
  855. number: tenderName,
  856. };
  857. const postParam = Object.assign(param, data);
  858. sms.aliSend(mobiles, postParam, code);
  859. }
  860. },
  861. /**
  862. *
  863. * @param setting
  864. * @param data
  865. * @returns {{} & any & {"!ref": string} & {"!cols"}}
  866. */
  867. simpleXlsxSheetData(setting, data) {
  868. const headerStyle = {
  869. font: { sz: 10, bold: true },
  870. alignment: { horizontal: 'center' },
  871. };
  872. const sHeader = setting.header
  873. .map((v, i) => Object.assign({}, { v: v, s: headerStyle, position: String.fromCharCode(65+i) + 1 }))
  874. .reduce((prev, next) => Object.assign({}, prev, {[next.position]: {v: next.v, s: next.s}}), {});
  875. const sData = data
  876. .map((v, i) => v.map((k, j) => Object.assign({}, {
  877. v: k ? k : '',
  878. s: { font: { sz: 10 }, alignment: {horizontal: setting.hAlign[j]}},
  879. position: String.fromCharCode(65+j) + (i+2) })))
  880. .reduce((prev, next) => prev.concat(next))
  881. .reduce((prev, next) => Object.assign({}, prev, {[next.position]: {v: next.v, s: next.s}}), {});
  882. const output = Object.assign({}, sHeader, sData);
  883. const outputPos = Object.keys(output);
  884. const result = Object.assign({}, output,
  885. {'!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1]},
  886. {'!cols': setting.width.map((w) => Object.assign({}, {wpx: w}))});
  887. return result;
  888. },
  889. log(error) {
  890. if (error.stack) {
  891. this.ctx.logger.error(error);
  892. } else {
  893. this.ctx.getLogger('fail').info(JSON.stringify({
  894. error: error,
  895. project: this.ctx.session.sessionProject,
  896. user: this.ctx.session.sessionUser,
  897. body: this.ctx.session.body,
  898. }));
  899. }
  900. },
  901. /**
  902. * 添加debug信息
  903. * 在debug模式下,debug信息将传输到浏览器并打印
  904. *
  905. * @param {String}key
  906. * @param {*}data
  907. */
  908. addDebugInfo(key, ...data) {
  909. if (!this.ctx.debugInfo) {
  910. this.ctx.debugInfo = { key: {}, other: [] };
  911. }
  912. if (key) {
  913. this.ctx.debugInfo.key[key] = data;
  914. } else {
  915. this.ctx.debugInfo.other.push(data);
  916. }
  917. },
  918. /**
  919. * 深拷贝
  920. * @param obj
  921. * @returns {*}
  922. */
  923. clone: function (obj) {
  924. if (obj === null) return null;
  925. var o = obj instanceof Array ? [] : {};
  926. for (var i in obj) {
  927. o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === "object" ? this.clone(obj[i]) : obj[i]);
  928. }
  929. return o;
  930. },
  931. /**
  932. * 短链接生成
  933. * @param url
  934. * @returns {*}
  935. */
  936. async urlToShort(url) {
  937. const apiUrl = 'http://scn.ink/api/shorturl';
  938. const data = {
  939. url: encodeURI(url),
  940. };
  941. const result = await this.sendRequest(apiUrl, data, 'get');
  942. return result && result.code === 200 && result.url ? result.url : url;
  943. },
  944. /**
  945. * 判断是否wap访问
  946. * @param request
  947. * @returns {*}
  948. */
  949. isWap(request) {
  950. return request.url.indexOf('/wap/') !== -1;
  951. },
  952. checkBillsWithPos(bills, pos, fields) {
  953. const result = {
  954. error: [],
  955. source: {
  956. bills: [],
  957. pos: [],
  958. }
  959. };
  960. for (const b of bills) {
  961. const pr = _.remove(pos, {lid: b.id});
  962. const checkData = {}, calcData = {};
  963. if (pr && pr.length > 0) {
  964. for (const field of fields) {
  965. checkData[field] = b[field] ? b[field] : 0;
  966. }
  967. for (const p of pr) {
  968. for (const field of fields) {
  969. calcData[field] = this.add(calcData[field], p[field]);
  970. }
  971. }
  972. if (!_.isMatch(checkData, calcData)) {
  973. result.error.push({
  974. ledger_id: b.ledger_id,
  975. b_code: b.b_code,
  976. name: b.name,
  977. error: {checkData: checkData, calcData: calcData}
  978. });
  979. result.source.bills.push(b);
  980. for (const p of pr) {
  981. result.source.pos.push(p);
  982. }
  983. }
  984. }
  985. }
  986. return result;
  987. },
  988. check18MainCode(code) {
  989. return /^([0-9]([0-9][0-9])*)?(GD[0-9]{3}([0-9][0-9])*)?$/.test(code);
  990. },
  991. check18SubCode(code) {
  992. return /^(GD)?G?[A-Z]{2}[A-Z]{0,2}([0-9]{2})+$/.test(code);
  993. },
  994. /**
  995. * 判断是否是移动端访问
  996. * @param request
  997. * @returns {*}
  998. */
  999. isMobile(agent) {
  1000. return agent.match(/(iphone|ipod|android)/i);
  1001. },
  1002. }