helper.js 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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. }
  741. for (const r of rela) {
  742. loadFields(r.data, r.fields, r.prefix, r.relaId);
  743. }
  744. },
  745. whereSql(where, as) {
  746. if (!where) {
  747. return '';
  748. }
  749. const wheres = [];
  750. const values = [];
  751. for (const key in where) {
  752. const value = where[key];
  753. if (Array.isArray(value)) {
  754. wheres.push('?? IN (?)');
  755. } else {
  756. wheres.push('?? = ?');
  757. }
  758. values.push((as && as !== '') ? as + '.' + key : key);
  759. values.push(value);
  760. }
  761. if (wheres.length > 0) {
  762. return this.ctx.app.mysql.format(' WHERE ' + wheres.join(' AND '), values);
  763. }
  764. return '';
  765. },
  766. formatMoney(s, dot = ',') {
  767. if (!s) return '0.00';
  768. s = parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(2) + '';
  769. let l = s.split('.')[0].split('').reverse(),
  770. r = s.split('.')[1];
  771. let t = '';
  772. for (let i = 0; i < l.length; i++) {
  773. t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? dot : '');
  774. }
  775. return t.split('').reverse().join('') + '.' + r;
  776. },
  777. transFormToChinese(num) {
  778. const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  779. const unit = ['', '十', '百', '千', '万'];
  780. num = parseInt(num);
  781. const getWan = temp => {
  782. const strArr = temp.toString().split('').reverse();
  783. let newNum = '';
  784. for (let i = 0; i < strArr.length; i++) {
  785. 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;
  786. }
  787. return strArr.length === 2 && newNum.indexOf('一十') !== -1 ? newNum.replace('一十', '十') : newNum;
  788. };
  789. const overWan = Math.floor(num / 10000);
  790. let noWan = num % 10000;
  791. if (noWan.toString().length < 4) noWan = '0' + noWan;
  792. return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num);
  793. },
  794. dateTran(time) {
  795. return moment(time).format('YYYY年MM月DD日 HH:mm');
  796. },
  797. timeAdd(duration) {
  798. const d = parseInt(duration);
  799. let time = 0;
  800. if (d === 1) {
  801. time = 60 * 15 * 1000;
  802. } else if (d === 2) {
  803. time = 60 * 30 * 1000;
  804. } else if (d === 3) {
  805. time = 3600 * 1000;
  806. } else if (d === 4) {
  807. time = 3600 * 2 * 1000;
  808. }
  809. return time;
  810. },
  811. async sendUserSms(userId, type, judge, msg) {
  812. const mobiles = [];
  813. if (!userId || (userId instanceof Array && userId.length === 0)) return;
  814. const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  815. for (const su of smsUser) {
  816. if (!su.auth_mobile || su.auth_mobile === '') continue;
  817. if (!su.sms_type || su.sms_type === '') continue;
  818. const smsType = JSON.parse(su.sms_type);
  819. if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
  820. mobiles.push(su.auth_mobile);
  821. }
  822. }
  823. if (mobiles.length > 0) {
  824. const sms = new SMS(this.ctx);
  825. const tenderName = await sms.contentChange(this.ctx.tender.data.name);
  826. const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
  827. const ptmsg = projectName !== '' ? '项目「' + projectName + '」标段「' + tenderName + '」' : tenderName;
  828. const content = '【纵横计量支付】' + ptmsg + msg;
  829. sms.send(mobiles, content);
  830. }
  831. },
  832. async sendAliSms(userId, type, judge, code, data = {}) {
  833. const mobiles = [];
  834. if (!userId || (userId instanceof Array && userId.length === 0)) return;
  835. const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  836. for (const su of smsUser) {
  837. if (!su.auth_mobile || su.auth_mobile === '') continue;
  838. if (!su.sms_type || su.sms_type === '') continue;
  839. const smsType = JSON.parse(su.sms_type);
  840. if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
  841. mobiles.push(su.auth_mobile);
  842. }
  843. }
  844. if (mobiles.length > 0) {
  845. const sms = new SMS(this.ctx);
  846. const tenderName = await sms.contentChange(this.ctx.tender.data.name);
  847. const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
  848. const param = {
  849. project: projectName,
  850. number: tenderName,
  851. };
  852. const postParam = Object.assign(param, data);
  853. sms.aliSend(mobiles, postParam, code);
  854. }
  855. },
  856. /**
  857. *
  858. * @param setting
  859. * @param data
  860. * @returns {{} & any & {"!ref": string} & {"!cols"}}
  861. */
  862. simpleXlsxSheetData(setting, data) {
  863. const headerStyle = {
  864. font: { sz: 10, bold: true },
  865. alignment: { horizontal: 'center' },
  866. };
  867. const sHeader = setting.header
  868. .map((v, i) => Object.assign({}, { v, s: headerStyle, position: String.fromCharCode(65 + i) + 1 }))
  869. .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v, s: next.s } }), {});
  870. const sData = data
  871. .map((v, i) => v.map((k, j) => Object.assign({}, {
  872. v: k ? k : '',
  873. s: { font: { sz: 10 }, alignment: { horizontal: setting.hAlign[j] } },
  874. position: String.fromCharCode(65 + j) + (i + 2) })))
  875. .reduce((prev, next) => prev.concat(next))
  876. .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v, s: next.s } }), {});
  877. const output = Object.assign({}, sHeader, sData);
  878. const outputPos = Object.keys(output);
  879. const result = Object.assign({}, output,
  880. { '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] },
  881. { '!cols': setting.width.map(w => Object.assign({}, { wpx: w })) });
  882. return result;
  883. },
  884. log(error) {
  885. if (error.stack) {
  886. this.ctx.logger.error(error);
  887. } else {
  888. this.ctx.getLogger('fail').info(JSON.stringify({
  889. error,
  890. project: this.ctx.session.sessionProject,
  891. user: this.ctx.session.sessionUser,
  892. body: this.ctx.session.body,
  893. }));
  894. }
  895. },
  896. /**
  897. * 添加debug信息
  898. * 在debug模式下,debug信息将传输到浏览器并打印
  899. *
  900. * @param {String}key
  901. * @param {*}data
  902. */
  903. addDebugInfo(key, ...data) {
  904. if (!this.ctx.debugInfo) {
  905. this.ctx.debugInfo = { key: {}, other: [] };
  906. }
  907. if (key) {
  908. this.ctx.debugInfo.key[key] = data;
  909. } else {
  910. this.ctx.debugInfo.other.push(data);
  911. }
  912. },
  913. /**
  914. * 深拷贝
  915. * @param obj
  916. * @return {*}
  917. */
  918. clone(obj) {
  919. if (obj === null) return null;
  920. const o = obj instanceof Array ? [] : {};
  921. for (const i in obj) {
  922. o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === 'object' ? this.clone(obj[i]) : obj[i]);
  923. }
  924. return o;
  925. },
  926. /**
  927. * 短链接生成
  928. * @param url
  929. * @return {*}
  930. */
  931. async urlToShort(url) {
  932. const apiUrl = 'http://scn.ink/api/shorturl';
  933. const data = {
  934. url: encodeURI(url),
  935. };
  936. const result = await this.sendRequest(apiUrl, data, 'get');
  937. return result && result.code === 200 && result.url ? result.url : url;
  938. },
  939. /**
  940. * 判断是否wap访问
  941. * @param request
  942. * @return {*}
  943. */
  944. isWap(request) {
  945. return request.url.indexOf('/wap/') !== -1;
  946. },
  947. checkBillsWithPos(bills, pos, fields) {
  948. const result = {
  949. error: [],
  950. source: {
  951. bills: [],
  952. pos: [],
  953. },
  954. };
  955. for (const b of bills) {
  956. const pr = _.remove(pos, { lid: b.id });
  957. const checkData = {},
  958. calcData = {};
  959. if (pr && pr.length > 0) {
  960. for (const field of fields) {
  961. checkData[field] = b[field] ? b[field] : 0;
  962. }
  963. for (const p of pr) {
  964. for (const field of fields) {
  965. calcData[field] = this.add(calcData[field], p[field]);
  966. }
  967. }
  968. if (!_.isMatch(checkData, calcData)) {
  969. result.error.push({
  970. ledger_id: b.ledger_id,
  971. b_code: b.b_code,
  972. name: b.name,
  973. error: { checkData, calcData },
  974. });
  975. result.source.bills.push(b);
  976. for (const p of pr) {
  977. result.source.pos.push(p);
  978. }
  979. }
  980. }
  981. }
  982. return result;
  983. },
  984. check18MainCode(code) {
  985. return /^([0-9]([0-9][0-9])*)?(GD[0-9]{3}([0-9][0-9])*)?$/.test(code);
  986. },
  987. check18SubCode(code) {
  988. return /^(GD)?G?[A-Z]{2}[A-Z]{0,2}([0-9]{2})+$/.test(code);
  989. },
  990. /**
  991. * 判断是否是移动端访问
  992. * @param request
  993. * @return {*}
  994. */
  995. isMobile(agent) {
  996. return agent.match(/(iphone|ipod|android)/i);
  997. },
  998. /**
  999. * 删除文件
  1000. * @param {Array} fileList 文件数组(格式为数据库查询出来的结果集,且文件字段必须为filepath)
  1001. * @return {void}
  1002. */
  1003. async delFiles(fileList) {
  1004. if (fileList.length !== 0) {
  1005. for (const att of fileList) {
  1006. if (fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
  1007. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  1008. }
  1009. }
  1010. }
  1011. },
  1012. };