helper.js 39 KB

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