helper.js 41 KB

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