helper.js 37 KB

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