helper.js 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360
  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. const UAParser = require('ua-parser-js');
  22. const math = require('mathjs');
  23. module.exports = {
  24. _,
  25. /**
  26. * 生成随机字符串
  27. *
  28. * @param {Number} length - 需要生成字符串的长度
  29. * @param {Number} type - 1为数字和字符 2为纯数字 3为纯字母
  30. * @return {String} - 返回生成结果
  31. */
  32. generateRandomString(length, type = 1) {
  33. length = parseInt(length);
  34. length = isNaN(length) ? 1 : length;
  35. let randSeed = [];
  36. let numberSeed = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  37. let stringSeed = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
  38. 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
  39. 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
  40. switch (type) {
  41. case 1:
  42. randSeed = stringSeed.concat(numberSeed);
  43. stringSeed = numberSeed = null;
  44. break;
  45. case 2:
  46. randSeed = numberSeed;
  47. break;
  48. case 3:
  49. randSeed = stringSeed;
  50. break;
  51. default:
  52. break;
  53. }
  54. const seedLength = randSeed.length - 1;
  55. let result = '';
  56. for (let i = 0; i < length; i++) {
  57. const index = Math.ceil(Math.random() * seedLength);
  58. result += randSeed[index];
  59. }
  60. return result;
  61. },
  62. /**
  63. * 字节转换
  64. * @param {number} bytes - 字节
  65. * @return {string} - 大小
  66. */
  67. bytesToSize(bytes) {
  68. if (parseInt(bytes) === 0) return '0 B';
  69. const k = 1024;
  70. const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  71. const i = Math.floor(Math.log(bytes) / Math.log(k));
  72. // return (bytes / Math.pow(k, i)) + ' ' + sizes[i];
  73. return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
  74. },
  75. /**
  76. * 浮点乘法计算
  77. * @param {number} arg1 - 乘数
  78. * @param {number} arg2 - 被乘数
  79. * @return {string} - 结果
  80. */
  81. accMul(arg1, arg2) {
  82. if (arg1 === '' || arg1 === null || arg1 === undefined || arg2 === '' || arg2 === null || arg2 === undefined) {
  83. return '';
  84. }
  85. let m = 0;
  86. const s1 = arg1.toString();
  87. const s2 = arg2.toString();
  88. try {
  89. m += s1.split('.')[1] !== undefined ? s1.split('.')[1].length : 0;
  90. } catch (e) {
  91. throw e;
  92. }
  93. try {
  94. m += s2.split('.')[1] !== undefined ? s2.split('.')[1].length : 0;
  95. } catch (e) {
  96. throw e;
  97. }
  98. return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m);
  99. },
  100. accAdd(arg1, arg2) {
  101. let r1;
  102. let r2;
  103. try {
  104. r1 = arg1.toString().split('.')[1].length;
  105. } catch (e) {
  106. r1 = 0;
  107. }
  108. try {
  109. r2 = arg2.toString().split('.')[1].length;
  110. } catch (e) {
  111. r2 = 0;
  112. }
  113. const c = Math.abs(r1 - r2);
  114. const m = Math.pow(10, Math.max(r1, r2));
  115. if (c > 0) {
  116. const cm = Math.pow(10, c);
  117. if (r1 > r2) {
  118. arg1 = Number(arg1.toString().replace('.', ''));
  119. arg2 = Number(arg2.toString().replace('.', '')) * cm;
  120. } else {
  121. arg1 = Number(arg1.toString().replace('.', '')) * cm;
  122. arg2 = Number(arg2.toString().replace('.', ''));
  123. }
  124. } else {
  125. arg1 = Number(arg1.toString().replace('.', ''));
  126. arg2 = Number(arg2.toString().replace('.', ''));
  127. }
  128. return (arg1 + arg2) / m;
  129. },
  130. // 四舍五入或末尾加零,实现类似php的 sprintf("%.".decimal."f", val);
  131. roundNum(val, decimals) {
  132. if (val === '' || val === null) {
  133. return '';
  134. }
  135. if (val !== '') {
  136. val = parseFloat(val);
  137. if (decimals < 1) {
  138. val = (Math.round(val)).toString();
  139. } else {
  140. const num = val.toString();
  141. if (num.lastIndexOf('.') === -1) {
  142. // num += '.';
  143. // num += this.makezero(decimals);
  144. val = num;
  145. } else {
  146. const valdecimals = num.split('.')[1].length;
  147. if (parseInt(valdecimals) < parseInt(decimals)) {
  148. // num += this.makezero(parseInt(decimals) - parseInt(valdecimals));
  149. val = num;
  150. } else if (parseInt(valdecimals) > parseInt(decimals)) {
  151. val = parseFloat(val) !== 0 ? Math.round(this.accMul(val, this.makemultiple(decimals))) / this.makemultiple(decimals) : this.makedecimalzero(decimals);
  152. const num = val.toString();
  153. if (num.lastIndexOf('.') === -1) {
  154. // num += '.';
  155. // num += this.makezero(decimals);
  156. val = num;
  157. } else {
  158. const valdecimals = num.split('.')[1].length;
  159. if (parseInt(valdecimals) < parseInt(decimals)) {
  160. // num += this.makezero(parseInt(decimals) - parseInt(valdecimals));
  161. val = num;
  162. }
  163. }
  164. }
  165. }
  166. }
  167. }
  168. return val;
  169. },
  170. // 生成num位的0
  171. makezero(num) {
  172. const arr = new Array(num);
  173. for (let i = 0; i < num; i++) {
  174. arr[i] = 0;
  175. }
  176. return arr.join('');
  177. },
  178. // 生成num位的10倍数
  179. makemultiple(num) {
  180. return Math.pow(10, parseInt(num));
  181. },
  182. // 根据单位获取小数位数
  183. findDecimal(unit) {
  184. let value = 3;
  185. if (unit !== '') {
  186. value = this.ctx.tender.info.precision.other.value;
  187. const changeUnits = this.ctx.tender.info.precision;
  188. for (const d in changeUnits) {
  189. if (changeUnits[d].unit !== undefined && changeUnits[d].unit === unit) {
  190. value = changeUnits[d].value;
  191. break;
  192. }
  193. }
  194. }
  195. return value;
  196. },
  197. /**
  198. * 显示排序符号
  199. *
  200. * @param {String} field - 字段名称
  201. * @return {String} - 返回字段排序的符号
  202. */
  203. showSortFlag(field) {
  204. const sort = this.ctx.sort;
  205. if (!(sort instanceof Array) || sort.length !== 2) {
  206. return '';
  207. }
  208. sort[1] = sort[1].toUpperCase();
  209. return (sort[0] === field && sort[1] === 'DESC') ? '' : '-';
  210. },
  211. /**
  212. * 判断是否为ajax请求
  213. *
  214. * @param {Object} request - 请求数据
  215. * @return {boolean} 判断结果
  216. */
  217. isAjax(request) {
  218. let headerInfo = request.headers['x-requested-with'] === undefined ? '' : request.headers['x-requested-with'];
  219. headerInfo = headerInfo.toLowerCase();
  220. return headerInfo === 'xmlhttprequest';
  221. },
  222. /**
  223. * 模拟发送请求
  224. *
  225. * @param {String} url - 请求地址
  226. * @param {Object} data - 请求数据
  227. * @param {String} type - 请求类型(POST) POST | GET
  228. * @param {String} dataType - 数据类型 json|text
  229. * @return {Object} - 请求结果
  230. */
  231. async sendRequest(url, data, type = 'POST', dataType = 'json') {
  232. // 发起请求
  233. try {
  234. const response = await this.ctx.curl(url, {
  235. method: type,
  236. data,
  237. dataType,
  238. });
  239. if (response.status !== 200) {
  240. throw '请求失败';
  241. }
  242. return response.data;
  243. } catch (err) {
  244. throw '请求失败';
  245. }
  246. },
  247. /**
  248. * 深度验证数据
  249. *
  250. * @param {Object} rule - 数据规则
  251. * @return {void}
  252. */
  253. validate(rule) {
  254. // 先用内置的验证器验证数据
  255. this.ctx.validate(rule);
  256. // 然后再验证是否有多余的数据
  257. const postData = this.ctx.request.body;
  258. delete postData._csrf;
  259. const postDataKey = Object.keys(postData);
  260. const ruleKey = Object.keys(rule);
  261. // 自动增加字段则填充上,以防判断出错
  262. if (postData.create_time !== undefined) {
  263. ruleKey.push('create_time');
  264. }
  265. for (const tmp of postDataKey) {
  266. // 规则里面没有定义则抛出异常
  267. if (ruleKey.indexOf(tmp) < 0) {
  268. throw '参数不正确';
  269. }
  270. }
  271. },
  272. /**
  273. * 拆分path
  274. *
  275. * @param {String|Array} paths - 拆分字符
  276. * @param {String} symbol - 拆分符号
  277. * @return {Array} - 拆分结果
  278. */
  279. explodePath(paths, symbol = '-') {
  280. const result = [];
  281. paths = paths instanceof Array ? paths : [paths];
  282. for (const path of paths) {
  283. // 拆分数据
  284. const pathArray = path.split(symbol);
  285. // 用户缓存循环的数据
  286. const tmpArray = [];
  287. for (const tmp of pathArray) {
  288. // 每次循环都追加一个数据进去
  289. tmpArray.push(tmp);
  290. const tmpPathString = tmpArray.join(symbol);
  291. // 判断是否已经存在有对应数据
  292. if (result.indexOf(tmpPathString) >= 0) {
  293. continue;
  294. }
  295. result.push(tmpPathString);
  296. }
  297. }
  298. return result;
  299. },
  300. /**
  301. * 基于obj, 拷贝sObj中的内容
  302. * obj = {a: 1, b: 2}, sObj = {a: 0, c: 3}, 返回{a: 0, b: 2, c: 3}
  303. * @param obj
  304. * @param sObj
  305. * @return {any}
  306. */
  307. updateObj(obj, sObj) {
  308. if (!obj) {
  309. return JSON.parse(JSON.stringify(sObj));
  310. }
  311. const result = JSON.parse(JSON.stringify(obj));
  312. if (sObj) {
  313. for (const prop in sObj) {
  314. result[prop] = sObj[prop];
  315. }
  316. }
  317. return result;
  318. },
  319. /**
  320. * 在数组中查找
  321. * @param {Array} arr
  322. * @param name -
  323. * @param value
  324. * @return {*}
  325. */
  326. findData(arr, name, value) {
  327. if (!arr instanceof Array) {
  328. throw '该方法仅用于数组查找';
  329. }
  330. if (arr.length === 0) { return undefined; }
  331. for (const data of arr) {
  332. if (data[name] == value) {
  333. return data;
  334. }
  335. }
  336. return undefined;
  337. },
  338. /**
  339. * 检查数字是否为0
  340. * @param {Number} value
  341. * @return {boolean}
  342. */
  343. checkZero(value) {
  344. return value === undefined || value === null || (this._.isNumber(value) && Math.abs(value) < zeroRange);
  345. },
  346. /**
  347. * 检查数字是否相等
  348. * @param {Number} value1
  349. * @param {Number} value2
  350. * @return {boolean}
  351. */
  352. checkNumberEqual(value1, value2) {
  353. if (value1 && value2) {
  354. return Math.abs(value2 - value1) > zeroRange;
  355. }
  356. return (!value1 && !value2);
  357. },
  358. /**
  359. * 比较编码
  360. * @param str1
  361. * @param str2
  362. * @param symbol
  363. * @return {number}
  364. */
  365. compareCode(str1, str2, symbol = '-') {
  366. if (!str1) {
  367. return 1;
  368. } else if (!str2) {
  369. return -1;
  370. }
  371. function compareSubCode(code1, code2) {
  372. if (numReg.test(code1)) {
  373. if (numReg.test(code2)) {
  374. return parseInt(code1) - parseInt(code2);
  375. }
  376. return -1;
  377. }
  378. if (numReg.test(code2)) {
  379. return 1;
  380. }
  381. return code1 === code2 ? 0 : (code1 < code2 ? -1 : 1); // code1.localeCompare(code2);
  382. }
  383. const numReg = /^[0-9]+$/;
  384. const aCodes = str1.split(symbol),
  385. bCodes = str2.split(symbol);
  386. for (let i = 0, iLength = Math.min(aCodes.length, bCodes.length); i < iLength; ++i) {
  387. const iCompare = compareSubCode(aCodes[i], bCodes[i]);
  388. if (iCompare !== 0) {
  389. return iCompare;
  390. }
  391. }
  392. return aCodes.length - bCodes.length;
  393. },
  394. /**
  395. * 根据 清单编号 获取 章级编号
  396. * @param code
  397. * @param symbol
  398. * @return {string}
  399. */
  400. getChapterCode(code, symbol = '-') {
  401. if (!code || code === '') return '';
  402. const codePath = code.split(symbol);
  403. const reg = /^[^0-9]*[0-9]{3,4}$/;
  404. if (reg.test(codePath[0])) {
  405. const numReg = /[0-9]{3,4}$/;
  406. const result = codePath[0].match(numReg);
  407. const num = parseInt(result[0]);
  408. return this.mul(this.div(num, 100, 0), 100) + '';
  409. }
  410. return '10000';
  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. * @return {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. * @return {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. * @return {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. * @return {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. * @return {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. * @class
  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. }
  601. return data;
  602. },
  603. // 加减乘除方法,为方便调用,兼容num为空的情况
  604. // 加减法使用base_calc,乘除法使用Decimal(原因详见demo/calc_test)
  605. /**
  606. * 加法 num1 + num2
  607. * @param num1
  608. * @param num2
  609. * @return {number}
  610. */
  611. add(num1, num2) {
  612. return bc.add(num1 ? num1 : 0, num2 ? num2 : 0);
  613. },
  614. /**
  615. * 减法 num1 - num2
  616. * @param num1
  617. * @param num2
  618. * @return {number}
  619. */
  620. sub(num1, num2) {
  621. return bc.sub(num1 ? num1 : 0, num2 ? num2 : 0);
  622. },
  623. /**
  624. * 乘法 num1 * num2
  625. * @param num1
  626. * @param num2
  627. * @return {*}
  628. */
  629. mul(num1, num2, digit = 6) {
  630. if (num1 === '' || num1 === null || num2 === '' || num2 === null) {
  631. return 0;
  632. }
  633. return Decimal.mul(num1 ? num1 : 0, num2 ? num2 : 0).toDecimalPlaces(digit).toNumber();
  634. },
  635. /**
  636. * 除法 num1 / num2
  637. * @param num1 - 被除数
  638. * @param num2 - 除数
  639. * @return {*}
  640. */
  641. div(num1, num2, digit = 6) {
  642. if (num2 && !this.checkZero(num2)) {
  643. return Decimal.div(num1 ? num1 : 0, num2).toDecimalPlaces(digit).toNumber();
  644. }
  645. return null;
  646. },
  647. /**
  648. * 四舍五入(统一,方便以后万一需要置换)
  649. * @param {Number} value - 舍入的数字
  650. * @param {Number} decimal - 要保留的小数位数
  651. * @return {*}
  652. */
  653. round(value, decimal) {
  654. // return value ? bc.round(value, decimal) : null;
  655. return value ? new Decimal(value).toDecimalPlaces(decimal).toNumber() : null;
  656. },
  657. /**
  658. * 汇总
  659. * @param array
  660. * @return {number}
  661. */
  662. sum(array) {
  663. let result = 0;
  664. for (const a of array) {
  665. result = this.add(result, a);
  666. }
  667. return result;
  668. },
  669. /**
  670. * 使用正则替换字符
  671. * @param str
  672. * @param reg
  673. * @param subStr
  674. * @return {*}
  675. */
  676. replaceStr(str, reg, subStr) {
  677. return str ? str.replace(reg, subStr) : str;
  678. },
  679. /**
  680. * 替换字符串中的 换行符回车符
  681. * @param str
  682. * @return {*}
  683. */
  684. replaceReturn(str) {
  685. // return str
  686. // ? (typeof str === 'string') ? str.replace(/[\r\n]/g, '') : str + ''
  687. // : str;
  688. return (str && typeof str === 'string')
  689. ? str.replace(/[\r\n]/g, '')
  690. : !_.isNil(str) ? str + '' : str;
  691. },
  692. /**
  693. * 替换字符串中的 换行符回车符为换行符<br>
  694. * @param str
  695. * @return {*}
  696. */
  697. replaceRntoBr(str) {
  698. // return str
  699. // ? (typeof str === 'string') ? str.replace(/[\r\n]/g, '') : str + ''
  700. // : str;
  701. return (str && typeof str === 'string')
  702. ? str.replace(/[\r\n]/g, '<br>')
  703. : !_.isNil(str) ? str + '' : str;
  704. },
  705. /**
  706. * 获取 字符串 数组的 mysql 筛选条件
  707. *
  708. * @param arr
  709. * @return {*}
  710. */
  711. getInArrStrSqlFilter(arr) {
  712. let result = '';
  713. for (const a of arr) {
  714. if (result !== '') {
  715. result = result + ',';
  716. }
  717. result = result + this.ctx.app.mysql.escape(a);
  718. }
  719. return result;
  720. },
  721. /**
  722. * 合并 相关数据
  723. * @param {Array} main - 主数据
  724. * @param {Array[]}rela - 相关数据 {data, fields, prefix, relaId}
  725. */
  726. assignRelaData(main, rela) {
  727. const index = {},
  728. indexPre = 'id_';
  729. const loadFields = function(datas, fields, prefix, relaId) {
  730. for (const d of datas) {
  731. const key = indexPre + d[relaId];
  732. const m = index[key];
  733. if (m) {
  734. for (const f of fields) {
  735. if (d[f] !== undefined) {
  736. m[prefix + f] = d[f];
  737. }
  738. }
  739. }
  740. }
  741. };
  742. for (const m of main) {
  743. index[indexPre + m.id] = m;
  744. for (const r of rela) {
  745. if (r.defaultData) _.assignIn(m, r.defaultData);
  746. }
  747. }
  748. for (const r of rela) {
  749. loadFields(r.data, r.fields, r.prefix, r.relaId);
  750. }
  751. },
  752. whereSql(where, as) {
  753. if (!where) {
  754. return '';
  755. }
  756. const wheres = [];
  757. const values = [];
  758. for (const key in where) {
  759. const value = where[key];
  760. if (Array.isArray(value)) {
  761. wheres.push('?? IN (?)');
  762. } else {
  763. wheres.push('?? = ?');
  764. }
  765. values.push((as && as !== '') ? as + '.' + key : key);
  766. values.push(value);
  767. }
  768. if (wheres.length > 0) {
  769. return this.ctx.app.mysql.format(' WHERE ' + wheres.join(' AND '), values);
  770. }
  771. return '';
  772. },
  773. formatMoney(s = 0, dot = ',', decimal = 2) {
  774. if (!s) {
  775. s = 0;
  776. return s.toFixed(decimal);
  777. }
  778. s = parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(decimal) + '';
  779. if (!decimal) {
  780. s += '.';
  781. }
  782. const l = s.split('.')[0].split('').reverse(),
  783. r = s.split('.')[1];
  784. let t = '';
  785. for (let i = 0; i < l.length; i++) {
  786. t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? dot : '');
  787. }
  788. return t.split('').reverse().join('') + (decimal === 0 ? '' : '.' + r);
  789. },
  790. transFormToChinese(num) {
  791. const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  792. const unit = ['', '十', '百', '千', '万'];
  793. num = parseInt(num);
  794. const getWan = temp => {
  795. const strArr = temp.toString().split('').reverse();
  796. let newNum = '';
  797. for (let i = 0; i < strArr.length; i++) {
  798. 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;
  799. }
  800. return strArr.length === 2 && newNum.indexOf('一十') !== -1 ? newNum.replace('一十', '十') : newNum;
  801. };
  802. const overWan = Math.floor(num / 10000);
  803. let noWan = num % 10000;
  804. if (noWan.toString().length < 4) noWan = '0' + noWan;
  805. return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num);
  806. },
  807. formatNum(num, pattern) {
  808. const strarr = num ? num.toString().split('.') : ['0'];
  809. const fmtarr = pattern ? pattern.split('.') : [''];
  810. let retstr = '';
  811. // 整数部分
  812. let str = strarr[0];
  813. let fmt = fmtarr[0];
  814. let i = str.length - 1;
  815. let comma = false;
  816. for (var f = fmt.length - 1; f >= 0; f--) {
  817. switch (fmt.substr(f, 1)) {
  818. case '#':
  819. if (i >= 0) retstr = str.substr(i--, 1) + retstr;
  820. break;
  821. case '0':
  822. if (i >= 0) retstr = str.substr(i--, 1) + retstr;
  823. else retstr = '0' + retstr;
  824. break;
  825. case ',':
  826. comma = true;
  827. retstr = ',' + retstr;
  828. break;
  829. }
  830. }
  831. if (i >= 0) {
  832. if (comma) {
  833. const l = str.length;
  834. for (;i >= 0; i--) {
  835. retstr = str.substr(i, 1) + retstr;
  836. if (i > 0 && ((l - i) % 3) == 0) retstr = ',' + retstr;
  837. }
  838. } else retstr = str.substr(0, i + 1) + retstr;
  839. }
  840. retstr = retstr + '.';
  841. // 处理小数部分
  842. str = strarr.length > 1 ? strarr[1] : '';
  843. fmt = fmtarr.length > 1 ? fmtarr[1] : '';
  844. i = 0;
  845. for (var f = 0; f < fmt.length; f++) {
  846. switch (fmt.substr(f, 1)) {
  847. case '#':
  848. if (i < str.length) retstr += str.substr(i++, 1);
  849. break;
  850. case '0':
  851. if (i < str.length) retstr += str.substr(i++, 1);
  852. else retstr += '0';
  853. break;
  854. }
  855. }
  856. return retstr.replace(/^,+/, '').replace(/\.$/, '');
  857. },
  858. dateTran(time) {
  859. return moment(time).format('YYYY年MM月DD日 HH:mm');
  860. },
  861. // 审批日期格式:2020-5-7 9:40:30
  862. formatFullDate(time) {
  863. return moment(time).format('YYYY-MM-DD HH:mm:ss');
  864. },
  865. // 预付款详情页时间线所需格式
  866. formatDate(date) {
  867. if (!date) return '';
  868. const year = date.getFullYear();
  869. let mon = date.getMonth() + 1;
  870. let day = date.getDate();
  871. let hour = date.getHours();
  872. let minute = date.getMinutes();
  873. let scond = date.getSeconds();
  874. if (mon < 10) {
  875. mon = '0' + mon.toString();
  876. }
  877. if (day < 10) {
  878. day = '0' + day.toString();
  879. }
  880. if (hour < 10) {
  881. hour = '0' + hour.toString();
  882. }
  883. if (minute < 10) {
  884. minute = '0' + minute.toString();
  885. }
  886. if (scond < 10) {
  887. scond = '0' + scond.toString();
  888. }
  889. return `${year}<span>${mon}-${day}</span><span>${hour}:${minute}:${scond}</span>`;
  890. },
  891. timeAdd(duration) {
  892. const d = parseInt(duration);
  893. let time = 0;
  894. if (d === 1) {
  895. time = 60 * 15 * 1000;
  896. } else if (d === 2) {
  897. time = 60 * 30 * 1000;
  898. } else if (d === 3) {
  899. time = 3600 * 1000;
  900. } else if (d === 4) {
  901. time = 3600 * 2 * 1000;
  902. }
  903. return time;
  904. },
  905. async sendUserSms(userId, type, judge, msg) {
  906. const mobiles = [];
  907. if (!userId || (userId instanceof Array && userId.length === 0)) return;
  908. const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  909. for (const su of smsUser) {
  910. if (!su.auth_mobile || su.auth_mobile === '') continue;
  911. if (!su.sms_type || su.sms_type === '') continue;
  912. const smsType = JSON.parse(su.sms_type);
  913. if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
  914. mobiles.push(su.auth_mobile);
  915. }
  916. }
  917. if (mobiles.length > 0) {
  918. const sms = new SMS(this.ctx);
  919. const tenderName = await sms.contentChange(this.ctx.tender.data.name);
  920. const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
  921. const ptmsg = projectName !== '' ? '项目「' + projectName + '」标段「' + tenderName + '」' : tenderName;
  922. const content = '【纵横计量支付】' + ptmsg + msg;
  923. sms.send(mobiles, content);
  924. }
  925. },
  926. async sendAliSms(userId, type, judge, code, data = {}) {
  927. // const mobiles = [];
  928. // if (!userId || (userId instanceof Array && userId.length === 0)) return;
  929. // const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  930. // for (const su of smsUser) {
  931. // if (!su.auth_mobile || su.auth_mobile === '') continue;
  932. // if (!su.sms_type || su.sms_type === '') continue;
  933. //
  934. // const smsType = JSON.parse(su.sms_type);
  935. // if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
  936. // mobiles.push(su.auth_mobile);
  937. // }
  938. // }
  939. //
  940. // if (mobiles.length > 0) {
  941. // const sms = new SMS(this.ctx);
  942. // const tenderName = await sms.contentChange(this.ctx.tender.data.name);
  943. // const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
  944. // const param = {
  945. // project: projectName,
  946. // number: tenderName,
  947. // };
  948. // const postParam = Object.assign(param, data);
  949. // sms.aliSend(mobiles, postParam, code);
  950. // }
  951. },
  952. async sendWechat(userId, type, judge, template, data = {}) {
  953. const wechats = [];
  954. if (!userId || (userId instanceof Array && userId.length === 0)) return;
  955. const wxUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  956. for (const user of wxUser) {
  957. if (!user.wx_openid || user.wx_openid === '') continue;
  958. if (!user.wx_type || user.wx_type === '') continue;
  959. const wxType = JSON.parse(user.wx_type);
  960. if (wxType[type] && wxType[type].indexOf(judge) !== -1) {
  961. wechats.push(user.wx_openid);
  962. }
  963. }
  964. if (wechats.length > 0) {
  965. const wx = new WX(this.ctx);
  966. const tenderName = await wx.contentChange(this.ctx.tender.data.name);
  967. const projectName = await wx.contentChange(this.ctx.tender.info.deal_info.buildName);
  968. const param = {
  969. projectName,
  970. tenderName,
  971. };
  972. const postParam = Object.assign(param, data);
  973. wx.Send(wechats, template, postParam);
  974. }
  975. },
  976. /**
  977. *
  978. * @param setting
  979. * @param data
  980. * @return {{} & any & {"!ref": string} & {"!cols"}}
  981. */
  982. simpleXlsxSheetData(setting, data) {
  983. const headerStyle = {
  984. font: { sz: 10, bold: true },
  985. alignment: { horizontal: 'center' },
  986. };
  987. const sHeader = setting.header
  988. .map((v, i) => Object.assign({}, { v, s: headerStyle, position: String.fromCharCode(65 + i) + 1 }))
  989. .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v, s: next.s } }), {});
  990. const sData = data
  991. .map((v, i) => v.map((k, j) => Object.assign({}, {
  992. v: k ? k : '',
  993. s: { font: { sz: 10 }, alignment: { horizontal: setting.hAlign[j] } },
  994. position: String.fromCharCode(65 + j) + (i + 2) })))
  995. .reduce((prev, next) => prev.concat(next))
  996. .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v, s: next.s } }), {});
  997. const output = Object.assign({}, sHeader, sData);
  998. const outputPos = Object.keys(output);
  999. const result = Object.assign({}, output,
  1000. { '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] },
  1001. { '!cols': setting.width.map(w => Object.assign({}, { wpx: w })) });
  1002. return result;
  1003. },
  1004. log(error) {
  1005. if (error.stack) {
  1006. this.ctx.logger.error(error);
  1007. } else {
  1008. this.ctx.getLogger('fail').info(JSON.stringify({
  1009. error,
  1010. project: this.ctx.session.sessionProject,
  1011. user: this.ctx.session.sessionUser,
  1012. body: this.ctx.session.body,
  1013. }));
  1014. }
  1015. },
  1016. /**
  1017. * 添加debug信息
  1018. * 在debug模式下,debug信息将传输到浏览器并打印
  1019. *
  1020. * @param {String}key
  1021. * @param {*}data
  1022. */
  1023. addDebugInfo(key, ...data) {
  1024. if (!this.ctx.debugInfo) {
  1025. this.ctx.debugInfo = { key: {}, other: [] };
  1026. }
  1027. if (key) {
  1028. this.ctx.debugInfo.key[key] = data;
  1029. } else {
  1030. this.ctx.debugInfo.other.push(data);
  1031. }
  1032. },
  1033. /**
  1034. * 深拷贝
  1035. * @param obj
  1036. * @return {*}
  1037. */
  1038. clone(obj) {
  1039. if (obj === null) return null;
  1040. const o = obj instanceof Array ? [] : {};
  1041. for (const i in obj) {
  1042. o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === 'object' ? this.clone(obj[i]) : obj[i]);
  1043. }
  1044. return o;
  1045. },
  1046. /**
  1047. * 短链接生成
  1048. * @param url
  1049. * @return {*}
  1050. */
  1051. async urlToShort(url) {
  1052. const apiUrl = 'http://scn.ink/api/shorturl';
  1053. const data = {
  1054. url: encodeURI(url),
  1055. };
  1056. const result = await this.sendRequest(apiUrl, data, 'get');
  1057. return result && result.code === 200 && result.url ? result.url : url;
  1058. },
  1059. /**
  1060. * 判断是否wap访问
  1061. * @param request
  1062. * @return {*}
  1063. */
  1064. isWap(request) {
  1065. return request.url.indexOf('/wap/') !== -1;
  1066. },
  1067. checkBillsWithPos(bills, pos, fields) {
  1068. const result = {
  1069. error: [],
  1070. source: {
  1071. bills: [],
  1072. pos: [],
  1073. },
  1074. };
  1075. for (const b of bills) {
  1076. const pr = _.remove(pos, { lid: b.id });
  1077. const checkData = {},
  1078. calcData = {};
  1079. if (pr && pr.length > 0) {
  1080. for (const field of fields) {
  1081. checkData[field] = b[field] ? b[field] : 0;
  1082. }
  1083. for (const p of pr) {
  1084. for (const field of fields) {
  1085. calcData[field] = this.add(calcData[field], p[field]);
  1086. }
  1087. }
  1088. if (!_.isMatch(checkData, calcData)) {
  1089. result.error.push({
  1090. ledger_id: b.ledger_id,
  1091. b_code: b.b_code,
  1092. name: b.name,
  1093. error: { checkData, calcData },
  1094. });
  1095. result.source.bills.push(b);
  1096. for (const p of pr) {
  1097. result.source.pos.push(p);
  1098. }
  1099. }
  1100. }
  1101. }
  1102. return result;
  1103. },
  1104. checkBillsTp(bills, field, decimal) {
  1105. const result = {
  1106. error: [],
  1107. source: {
  1108. bills: [],
  1109. pos: [],
  1110. },
  1111. };
  1112. for (const b of bills) {
  1113. if (!b.check_calc) continue;
  1114. const checkData = {}, calcData = {};
  1115. for (const f of field) {
  1116. checkData[f.tp] = b[f.tp] || 0;
  1117. calcData[f.tp] = this.mul(b.unit_price, b[f.qty], decimal.tp) || 0;
  1118. }
  1119. if (!this._.isMatch(checkData, calcData)) {
  1120. result.error.push({
  1121. ledger_id: b.ledger_id,
  1122. b_code: b.b_code,
  1123. name: b.name,
  1124. error: { checkData, calcData },
  1125. });
  1126. result.source.bills.push(b);
  1127. }
  1128. }
  1129. return result;
  1130. },
  1131. check18MainCode(code) {
  1132. return /^([0-9]([0-9][0-9])*)?(GD[0-9]{3}([0-9][0-9])*)?$/.test(code);
  1133. },
  1134. check18SubCode(code) {
  1135. return /^(GD)?G?[A-Z]{2}[A-Z]{0,2}([0-9]{2})+$/.test(code);
  1136. },
  1137. /**
  1138. * 判断是否是移动端访问
  1139. * @param request
  1140. * @return {*}
  1141. */
  1142. isMobile(agent) {
  1143. return agent.match(/(iphone|ipod|android)/i);
  1144. },
  1145. /**
  1146. * 删除文件
  1147. * @param {Array} fileList 文件数组(格式为数据库查询出来的结果集,且文件字段必须为filepath)
  1148. * @return {void}
  1149. */
  1150. async delFiles(fileList) {
  1151. if (fileList.length) {
  1152. for (const att of fileList) {
  1153. if (att.filepath && fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
  1154. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  1155. }
  1156. }
  1157. }
  1158. },
  1159. /**
  1160. * 匹配图片、pdf(用于预览)
  1161. * @param {String} ext 后缀名
  1162. * @return {Boolean} 匹配结果
  1163. */
  1164. canPreview(ext) {
  1165. const reg = /(.png)|(.gif)|(.txt)|(.jpg)|(.jpeg)|(.pdf)/;
  1166. return reg.test(ext);
  1167. },
  1168. /**
  1169. * 查找数组中某个字符的个数
  1170. * @param {Array} array 数组
  1171. * @param {string} val 字符串
  1172. * @return {Boolean} 匹配结果
  1173. */
  1174. arrayCount(array, val) {
  1175. const counts = (arr, value) => arr.reduce((a, v) => { return value.indexOf(v) !== -1 ? a + 1 : a + 0; }, 0);
  1176. return counts(array, val);
  1177. },
  1178. filterLastestData(data, keyFields) {
  1179. const dataIndex = {};
  1180. for (const d of data) {
  1181. let key = 'd';
  1182. for (const kf of keyFields) {
  1183. key = key + '.' + (d[kf] || '');
  1184. }
  1185. const di = dataIndex[key];
  1186. if (di) {
  1187. if ((di.times * timesLen + di.order) < (d.times * timesLen + d.order)) dataIndex[key] = d;
  1188. } else {
  1189. dataIndex[key] = d;
  1190. }
  1191. }
  1192. const result = [];
  1193. for (const prop in dataIndex) {
  1194. result.push(dataIndex[prop]);
  1195. }
  1196. return result;
  1197. },
  1198. calcExpr(expr) {
  1199. const validExpr = expr.replace('=', '').replace('%', '/100');
  1200. return math.eval(validExpr);
  1201. },
  1202. /**
  1203. * 创建登录日志
  1204. * @return {Boolean} 日志是否创建成功
  1205. * @param {Number} type - 登录类型
  1206. * @param {Number} status - 是否显示记录
  1207. */
  1208. async getUserIPMsg() {
  1209. const { ctx } = this;
  1210. const ip = ctx.request.ip ? ctx.request.ip : '';
  1211. const ipInfo = await this.getIpInfoFromApi(ip);
  1212. const parser = new UAParser(ctx.header['user-agent']);
  1213. const osInfo = parser.getOS();
  1214. const cpuInfo = parser.getCPU();
  1215. const browserInfo = parser.getBrowser();
  1216. const ipMsg = {
  1217. os: `${osInfo.name} ${osInfo.version} ${cpuInfo.architecture}`,
  1218. browser: `${browserInfo.name} ${browserInfo.version}`,
  1219. ip,
  1220. address: ipInfo,
  1221. };
  1222. return ipMsg;
  1223. },
  1224. /**
  1225. * 根据ip请求获取详细地址
  1226. * @param {String} a_ip - ip地址
  1227. * @return {String} 详细地址
  1228. */
  1229. async getIpInfoFromApi(a_ip = '') {
  1230. if (!a_ip) return '';
  1231. if (a_ip === '127.0.0.1' || a_ip === '::1' || a_ip.indexOf('192.168') !== -1) return '服务器本机访问';
  1232. const { ip = '', region = '', city = '', isp = '' } = await this.sendIpRequest(a_ip);
  1233. let address = '';
  1234. region && (address += region + '省');
  1235. city && (address += city + '市 ');
  1236. isp && (address += isp + ' ');
  1237. ip && (address += `(${ip})`);
  1238. return address;
  1239. },
  1240. /**
  1241. * 发送请求获取详细地址
  1242. * @param {String} ip - ip地址
  1243. * @return {Object} the result of request
  1244. * @private
  1245. */
  1246. async sendIpRequest(ip) {
  1247. return new Promise(resolve => {
  1248. this.ctx.curl(`https://api01.aliyun.venuscn.com/ip?ip=${ip}`, {
  1249. dateType: 'json',
  1250. encoding: 'utf8',
  1251. timeout: 2000,
  1252. headers: {
  1253. Authorization: 'APPCODE 85c64bffe70445c4af9df7ae31c7bfcc',
  1254. },
  1255. }).then(({ status, data }) => {
  1256. if (status === 200) {
  1257. const result = JSON.parse(data.toString()).data;
  1258. if (!result.ip) {
  1259. resolve({});
  1260. } else {
  1261. resolve(result);
  1262. }
  1263. } else {
  1264. resolve({});
  1265. }
  1266. }).catch(() => {
  1267. resolve({});
  1268. });
  1269. });
  1270. },
  1271. };