helper.js 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368
  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. async copyFileSync(source, target) {
  534. const pathName = path.dirname(target);
  535. if (!fs.existsSync(pathName)) {
  536. await this.recursiveMkdirSync(pathName);
  537. }
  538. await fs.copyFileSync(source, target);
  539. },
  540. /**
  541. * 检查code是否是指标模板数据
  542. * @param {String} code
  543. * @return {boolean}
  544. */
  545. validBillsCode(code) {
  546. const reg1 = /(^[0-9]+)([a-z0-9\-]*)/i;
  547. const reg2 = /([a-z0-9]+$)/i;
  548. return reg1.test(code) && reg2.test(code);
  549. },
  550. getNumberFormatter(decimal) {
  551. if (decimal <= 0) {
  552. return '0';
  553. }
  554. let pre = '0.';
  555. for (let i = 0; i < decimal; i++) {
  556. pre += '#';
  557. }
  558. return pre;
  559. },
  560. /**
  561. * 根据单位查找对应的清单精度
  562. * @param {tenderInfo.precision} list - 清单精度列表
  563. * @param {String} unit - 单位
  564. * @return {number}
  565. */
  566. findPrecision(list, unit) {
  567. if (unit) {
  568. for (const p in list) {
  569. if (list[p].unit && list[p].unit === unit) {
  570. return list[p];
  571. }
  572. }
  573. }
  574. return list.other;
  575. },
  576. /**
  577. * 检查数据中的精度
  578. * @param {Object} Obj - 检查的数据
  579. * @param {Array} fields - 检查的属性
  580. * @param {Number} precision - 精度
  581. * @class
  582. */
  583. checkFieldPrecision(Obj, fields, precision = 2) {
  584. if (Obj) {
  585. for (const field of fields) {
  586. if (Obj[field]) {
  587. Obj[field] = this.round(Obj[field], precision);
  588. }
  589. }
  590. }
  591. },
  592. /**
  593. * 过滤无效数据
  594. *
  595. * @param obj
  596. * @param fields - 有效数据的数组
  597. */
  598. filterValidFields(data, fields) {
  599. if (data) {
  600. const result = {};
  601. for (const prop in data) {
  602. if (fields.indexOf(prop) !== -1) {
  603. result[prop] = data[prop];
  604. }
  605. }
  606. return result;
  607. }
  608. return data;
  609. },
  610. // 加减乘除方法,为方便调用,兼容num为空的情况
  611. // 加减法使用base_calc,乘除法使用Decimal(原因详见demo/calc_test)
  612. /**
  613. * 加法 num1 + num2
  614. * @param num1
  615. * @param num2
  616. * @return {number}
  617. */
  618. add(num1, num2) {
  619. return bc.add(num1 ? num1 : 0, num2 ? num2 : 0);
  620. },
  621. /**
  622. * 减法 num1 - num2
  623. * @param num1
  624. * @param num2
  625. * @return {number}
  626. */
  627. sub(num1, num2) {
  628. return bc.sub(num1 ? num1 : 0, num2 ? num2 : 0);
  629. },
  630. /**
  631. * 乘法 num1 * num2
  632. * @param num1
  633. * @param num2
  634. * @return {*}
  635. */
  636. mul(num1, num2, digit = 6) {
  637. if (num1 === '' || num1 === null || num2 === '' || num2 === null) {
  638. return 0;
  639. }
  640. return Decimal.mul(num1 ? num1 : 0, num2 ? num2 : 0).toDecimalPlaces(digit).toNumber();
  641. },
  642. /**
  643. * 除法 num1 / num2
  644. * @param num1 - 被除数
  645. * @param num2 - 除数
  646. * @return {*}
  647. */
  648. div(num1, num2, digit = 6) {
  649. if (num2 && !this.checkZero(num2)) {
  650. return Decimal.div(num1 ? num1 : 0, num2).toDecimalPlaces(digit).toNumber();
  651. }
  652. return null;
  653. },
  654. /**
  655. * 四舍五入(统一,方便以后万一需要置换)
  656. * @param {Number} value - 舍入的数字
  657. * @param {Number} decimal - 要保留的小数位数
  658. * @return {*}
  659. */
  660. round(value, decimal) {
  661. // return value ? bc.round(value, decimal) : null;
  662. return value ? new Decimal(value).toDecimalPlaces(decimal).toNumber() : null;
  663. },
  664. /**
  665. * 汇总
  666. * @param array
  667. * @return {number}
  668. */
  669. sum(array) {
  670. let result = 0;
  671. for (const a of array) {
  672. result = this.add(result, a);
  673. }
  674. return result;
  675. },
  676. /**
  677. * 使用正则替换字符
  678. * @param str
  679. * @param reg
  680. * @param subStr
  681. * @return {*}
  682. */
  683. replaceStr(str, reg, subStr) {
  684. return str ? str.replace(reg, subStr) : str;
  685. },
  686. /**
  687. * 替换字符串中的 换行符回车符
  688. * @param str
  689. * @return {*}
  690. */
  691. replaceReturn(str) {
  692. // return str
  693. // ? (typeof str === 'string') ? str.replace(/[\r\n]/g, '') : str + ''
  694. // : str;
  695. return (str && typeof str === 'string')
  696. ? str.replace(/[\r\n]/g, '')
  697. : !_.isNil(str) ? str + '' : str;
  698. },
  699. /**
  700. * 替换字符串中的 换行符回车符为换行符<br>
  701. * @param str
  702. * @return {*}
  703. */
  704. replaceRntoBr(str) {
  705. // return str
  706. // ? (typeof str === 'string') ? str.replace(/[\r\n]/g, '') : str + ''
  707. // : str;
  708. return (str && typeof str === 'string')
  709. ? str.replace(/[\r\n]/g, '<br>')
  710. : !_.isNil(str) ? str + '' : str;
  711. },
  712. /**
  713. * 获取 字符串 数组的 mysql 筛选条件
  714. *
  715. * @param arr
  716. * @return {*}
  717. */
  718. getInArrStrSqlFilter(arr) {
  719. let result = '';
  720. for (const a of arr) {
  721. if (result !== '') {
  722. result = result + ',';
  723. }
  724. result = result + this.ctx.app.mysql.escape(a);
  725. }
  726. return result;
  727. },
  728. /**
  729. * 合并 相关数据
  730. * @param {Array} main - 主数据
  731. * @param {Array[]}rela - 相关数据 {data, fields, prefix, relaId}
  732. */
  733. assignRelaData(main, rela) {
  734. const index = {},
  735. indexPre = 'id_';
  736. const loadFields = function(datas, fields, prefix, relaId) {
  737. for (const d of datas) {
  738. const key = indexPre + d[relaId];
  739. const m = index[key];
  740. if (m) {
  741. for (const f of fields) {
  742. if (d[f] !== undefined) {
  743. m[prefix + f] = d[f];
  744. }
  745. }
  746. }
  747. }
  748. };
  749. for (const m of main) {
  750. index[indexPre + m.id] = m;
  751. for (const r of rela) {
  752. if (r.defaultData) _.assignIn(m, r.defaultData);
  753. }
  754. }
  755. for (const r of rela) {
  756. loadFields(r.data, r.fields, r.prefix, r.relaId);
  757. }
  758. },
  759. whereSql(where, as) {
  760. if (!where) {
  761. return '';
  762. }
  763. const wheres = [];
  764. const values = [];
  765. for (const key in where) {
  766. const value = where[key];
  767. if (Array.isArray(value)) {
  768. wheres.push('?? IN (?)');
  769. } else {
  770. wheres.push('?? = ?');
  771. }
  772. values.push((as && as !== '') ? as + '.' + key : key);
  773. values.push(value);
  774. }
  775. if (wheres.length > 0) {
  776. return this.ctx.app.mysql.format(' WHERE ' + wheres.join(' AND '), values);
  777. }
  778. return '';
  779. },
  780. formatMoney(s = 0, dot = ',', decimal = 2) {
  781. if (!s) {
  782. s = 0;
  783. return s.toFixed(decimal);
  784. }
  785. s = parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(decimal) + '';
  786. if (!decimal) {
  787. s += '.';
  788. }
  789. const l = s.split('.')[0].split('').reverse(),
  790. r = s.split('.')[1];
  791. let t = '';
  792. for (let i = 0; i < l.length; i++) {
  793. t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? dot : '');
  794. }
  795. return t.split('').reverse().join('') + (decimal === 0 ? '' : '.' + r);
  796. },
  797. transFormToChinese(num) {
  798. const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  799. const unit = ['', '十', '百', '千', '万'];
  800. num = parseInt(num);
  801. const getWan = temp => {
  802. const strArr = temp.toString().split('').reverse();
  803. let newNum = '';
  804. for (let i = 0; i < strArr.length; i++) {
  805. 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;
  806. }
  807. return strArr.length === 2 && newNum.indexOf('一十') !== -1 ? newNum.replace('一十', '十') : newNum;
  808. };
  809. const overWan = Math.floor(num / 10000);
  810. let noWan = num % 10000;
  811. if (noWan.toString().length < 4) noWan = '0' + noWan;
  812. return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num);
  813. },
  814. formatNum(num, pattern) {
  815. const strarr = num ? num.toString().split('.') : ['0'];
  816. const fmtarr = pattern ? pattern.split('.') : [''];
  817. let retstr = '';
  818. // 整数部分
  819. let str = strarr[0];
  820. let fmt = fmtarr[0];
  821. let i = str.length - 1;
  822. let comma = false;
  823. for (var f = fmt.length - 1; f >= 0; f--) {
  824. switch (fmt.substr(f, 1)) {
  825. case '#':
  826. if (i >= 0) retstr = str.substr(i--, 1) + retstr;
  827. break;
  828. case '0':
  829. if (i >= 0) retstr = str.substr(i--, 1) + retstr;
  830. else retstr = '0' + retstr;
  831. break;
  832. case ',':
  833. comma = true;
  834. retstr = ',' + retstr;
  835. break;
  836. }
  837. }
  838. if (i >= 0) {
  839. if (comma) {
  840. const l = str.length;
  841. for (;i >= 0; i--) {
  842. retstr = str.substr(i, 1) + retstr;
  843. if (i > 0 && ((l - i) % 3) == 0) retstr = ',' + retstr;
  844. }
  845. } else retstr = str.substr(0, i + 1) + retstr;
  846. }
  847. retstr = retstr + '.';
  848. // 处理小数部分
  849. str = strarr.length > 1 ? strarr[1] : '';
  850. fmt = fmtarr.length > 1 ? fmtarr[1] : '';
  851. i = 0;
  852. for (var f = 0; f < fmt.length; f++) {
  853. switch (fmt.substr(f, 1)) {
  854. case '#':
  855. if (i < str.length) retstr += str.substr(i++, 1);
  856. break;
  857. case '0':
  858. if (i < str.length) retstr += str.substr(i++, 1);
  859. else retstr += '0';
  860. break;
  861. }
  862. }
  863. return retstr.replace(/^,+/, '').replace(/\.$/, '');
  864. },
  865. dateTran(time) {
  866. return moment(time).format('YYYY年MM月DD日 HH:mm');
  867. },
  868. // 审批日期格式:2020-5-7 9:40:30
  869. formatFullDate(time) {
  870. return moment(time).format('YYYY-MM-DD HH:mm:ss');
  871. },
  872. // 预付款详情页时间线所需格式
  873. formatDate(date) {
  874. if (!date) return '';
  875. const year = date.getFullYear();
  876. let mon = date.getMonth() + 1;
  877. let day = date.getDate();
  878. let hour = date.getHours();
  879. let minute = date.getMinutes();
  880. let scond = date.getSeconds();
  881. if (mon < 10) {
  882. mon = '0' + mon.toString();
  883. }
  884. if (day < 10) {
  885. day = '0' + day.toString();
  886. }
  887. if (hour < 10) {
  888. hour = '0' + hour.toString();
  889. }
  890. if (minute < 10) {
  891. minute = '0' + minute.toString();
  892. }
  893. if (scond < 10) {
  894. scond = '0' + scond.toString();
  895. }
  896. return `${year}<span>${mon}-${day}</span><span>${hour}:${minute}:${scond}</span>`;
  897. },
  898. timeAdd(duration) {
  899. const d = parseInt(duration);
  900. let time = 0;
  901. if (d === 1) {
  902. time = 60 * 15 * 1000;
  903. } else if (d === 2) {
  904. time = 60 * 30 * 1000;
  905. } else if (d === 3) {
  906. time = 3600 * 1000;
  907. } else if (d === 4) {
  908. time = 3600 * 2 * 1000;
  909. }
  910. return time;
  911. },
  912. async sendUserSms(userId, type, judge, msg) {
  913. const mobiles = [];
  914. if (!userId || (userId instanceof Array && userId.length === 0)) return;
  915. const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  916. for (const su of smsUser) {
  917. if (!su.auth_mobile || su.auth_mobile === '') continue;
  918. if (!su.sms_type || su.sms_type === '') continue;
  919. const smsType = JSON.parse(su.sms_type);
  920. if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
  921. mobiles.push(su.auth_mobile);
  922. }
  923. }
  924. if (mobiles.length > 0) {
  925. const sms = new SMS(this.ctx);
  926. const tenderName = await sms.contentChange(this.ctx.tender.data.name);
  927. const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
  928. const ptmsg = projectName !== '' ? '项目「' + projectName + '」标段「' + tenderName + '」' : tenderName;
  929. const content = '【纵横计量支付】' + ptmsg + msg;
  930. sms.send(mobiles, content);
  931. }
  932. },
  933. async sendAliSms(userId, type, judge, code, data = {}) {
  934. // const mobiles = [];
  935. // if (!userId || (userId instanceof Array && userId.length === 0)) return;
  936. // const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  937. // for (const su of smsUser) {
  938. // if (!su.auth_mobile || su.auth_mobile === '') continue;
  939. // if (!su.sms_type || su.sms_type === '') continue;
  940. //
  941. // const smsType = JSON.parse(su.sms_type);
  942. // if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
  943. // mobiles.push(su.auth_mobile);
  944. // }
  945. // }
  946. //
  947. // if (mobiles.length > 0) {
  948. // const sms = new SMS(this.ctx);
  949. // const tenderName = await sms.contentChange(this.ctx.tender.data.name);
  950. // const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
  951. // const param = {
  952. // project: projectName,
  953. // number: tenderName,
  954. // };
  955. // const postParam = Object.assign(param, data);
  956. // sms.aliSend(mobiles, postParam, code);
  957. // }
  958. },
  959. async sendWechat(userId, type, judge, template, data = {}) {
  960. const wechats = [];
  961. if (!userId || (userId instanceof Array && userId.length === 0)) return;
  962. const wxUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  963. for (const user of wxUser) {
  964. if (!user.wx_openid || user.wx_openid === '') continue;
  965. if (!user.wx_type || user.wx_type === '') continue;
  966. const wxType = JSON.parse(user.wx_type);
  967. if (wxType[type] && wxType[type].indexOf(judge) !== -1) {
  968. wechats.push(user.wx_openid);
  969. }
  970. }
  971. if (wechats.length > 0) {
  972. const wx = new WX(this.ctx);
  973. const tenderName = await wx.contentChange(this.ctx.tender.data.name);
  974. const projectName = await wx.contentChange(this.ctx.tender.info.deal_info.buildName);
  975. const param = {
  976. projectName,
  977. tenderName,
  978. };
  979. const postParam = Object.assign(param, data);
  980. wx.Send(wechats, template, postParam);
  981. }
  982. },
  983. /**
  984. *
  985. * @param setting
  986. * @param data
  987. * @return {{} & any & {"!ref": string} & {"!cols"}}
  988. */
  989. simpleXlsxSheetData(setting, data) {
  990. const headerStyle = {
  991. font: { sz: 10, bold: true },
  992. alignment: { horizontal: 'center' },
  993. };
  994. const sHeader = setting.header
  995. .map((v, i) => Object.assign({}, { v, s: headerStyle, position: String.fromCharCode(65 + i) + 1 }))
  996. .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v, s: next.s } }), {});
  997. const sData = data
  998. .map((v, i) => v.map((k, j) => Object.assign({}, {
  999. v: k ? k : '',
  1000. s: { font: { sz: 10 }, alignment: { horizontal: setting.hAlign[j] } },
  1001. position: String.fromCharCode(65 + j) + (i + 2) })))
  1002. .reduce((prev, next) => prev.concat(next))
  1003. .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v, s: next.s } }), {});
  1004. const output = Object.assign({}, sHeader, sData);
  1005. const outputPos = Object.keys(output);
  1006. const result = Object.assign({}, output,
  1007. { '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] },
  1008. { '!cols': setting.width.map(w => Object.assign({}, { wpx: w })) });
  1009. return result;
  1010. },
  1011. log(error) {
  1012. if (error.stack) {
  1013. this.ctx.logger.error(error);
  1014. } else {
  1015. this.ctx.getLogger('fail').info(JSON.stringify({
  1016. error,
  1017. project: this.ctx.session.sessionProject,
  1018. user: this.ctx.session.sessionUser,
  1019. body: this.ctx.session.body,
  1020. }));
  1021. }
  1022. },
  1023. /**
  1024. * 添加debug信息
  1025. * 在debug模式下,debug信息将传输到浏览器并打印
  1026. *
  1027. * @param {String}key
  1028. * @param {*}data
  1029. */
  1030. addDebugInfo(key, ...data) {
  1031. if (!this.ctx.debugInfo) {
  1032. this.ctx.debugInfo = { key: {}, other: [] };
  1033. }
  1034. if (key) {
  1035. this.ctx.debugInfo.key[key] = data;
  1036. } else {
  1037. this.ctx.debugInfo.other.push(data);
  1038. }
  1039. },
  1040. /**
  1041. * 深拷贝
  1042. * @param obj
  1043. * @return {*}
  1044. */
  1045. clone(obj) {
  1046. if (obj === null) return null;
  1047. const o = obj instanceof Array ? [] : {};
  1048. for (const i in obj) {
  1049. o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === 'object' ? this.clone(obj[i]) : obj[i]);
  1050. }
  1051. return o;
  1052. },
  1053. /**
  1054. * 短链接生成
  1055. * @param url
  1056. * @return {*}
  1057. */
  1058. async urlToShort(url) {
  1059. const apiUrl = 'http://scn.ink/api/shorturl';
  1060. const data = {
  1061. url: encodeURI(url),
  1062. };
  1063. const result = await this.sendRequest(apiUrl, data, 'get');
  1064. return result && result.code === 200 && result.url ? result.url : url;
  1065. },
  1066. /**
  1067. * 判断是否wap访问
  1068. * @param request
  1069. * @return {*}
  1070. */
  1071. isWap(request) {
  1072. return request.url.indexOf('/wap/') !== -1;
  1073. },
  1074. checkBillsWithPos(bills, pos, fields) {
  1075. const result = {
  1076. error: [],
  1077. source: {
  1078. bills: [],
  1079. pos: [],
  1080. },
  1081. };
  1082. for (const b of bills) {
  1083. const pr = _.remove(pos, { lid: b.id });
  1084. const checkData = {},
  1085. calcData = {};
  1086. if (pr && pr.length > 0) {
  1087. for (const field of fields) {
  1088. checkData[field] = b[field] ? b[field] : 0;
  1089. }
  1090. for (const p of pr) {
  1091. for (const field of fields) {
  1092. calcData[field] = this.add(calcData[field], p[field]);
  1093. }
  1094. }
  1095. if (!_.isMatch(checkData, calcData)) {
  1096. result.error.push({
  1097. ledger_id: b.ledger_id,
  1098. b_code: b.b_code,
  1099. name: b.name,
  1100. error: { checkData, calcData },
  1101. });
  1102. result.source.bills.push(b);
  1103. for (const p of pr) {
  1104. result.source.pos.push(p);
  1105. }
  1106. }
  1107. }
  1108. }
  1109. return result;
  1110. },
  1111. checkBillsTp(bills, field, decimal) {
  1112. const result = {
  1113. error: [],
  1114. source: {
  1115. bills: [],
  1116. pos: [],
  1117. },
  1118. };
  1119. for (const b of bills) {
  1120. if (!b.check_calc) continue;
  1121. const checkData = {}, calcData = {};
  1122. for (const f of field) {
  1123. checkData[f.tp] = b[f.tp] || 0;
  1124. calcData[f.tp] = this.mul(b.unit_price, b[f.qty], decimal.tp) || 0;
  1125. }
  1126. if (!this._.isMatch(checkData, calcData)) {
  1127. result.error.push({
  1128. ledger_id: b.ledger_id,
  1129. b_code: b.b_code,
  1130. name: b.name,
  1131. error: { checkData, calcData },
  1132. });
  1133. result.source.bills.push(b);
  1134. }
  1135. }
  1136. return result;
  1137. },
  1138. check18MainCode(code) {
  1139. return /^([0-9]([0-9][0-9])*)?(GD[0-9]{3}([0-9][0-9])*)?$/.test(code);
  1140. },
  1141. check18SubCode(code) {
  1142. return /^(GD)?G?[A-Z]{2}[A-Z]{0,2}([0-9]{2})+$/.test(code);
  1143. },
  1144. /**
  1145. * 判断是否是移动端访问
  1146. * @param request
  1147. * @return {*}
  1148. */
  1149. isMobile(agent) {
  1150. return agent.match(/(iphone|ipod|android)/i);
  1151. },
  1152. /**
  1153. * 删除文件
  1154. * @param {Array} fileList 文件数组(格式为数据库查询出来的结果集,且文件字段必须为filepath)
  1155. * @return {void}
  1156. */
  1157. async delFiles(fileList) {
  1158. if (fileList.length) {
  1159. for (const att of fileList) {
  1160. if (att.filepath && fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
  1161. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  1162. }
  1163. }
  1164. }
  1165. },
  1166. /**
  1167. * 匹配图片、pdf(用于预览)
  1168. * @param {String} ext 后缀名
  1169. * @return {Boolean} 匹配结果
  1170. */
  1171. canPreview(ext) {
  1172. const reg = /(.png)|(.gif)|(.txt)|(.jpg)|(.jpeg)|(.pdf)/;
  1173. return reg.test(ext);
  1174. },
  1175. /**
  1176. * 查找数组中某个字符的个数
  1177. * @param {Array} array 数组
  1178. * @param {string} val 字符串
  1179. * @return {Boolean} 匹配结果
  1180. */
  1181. arrayCount(array, val) {
  1182. const counts = (arr, value) => arr.reduce((a, v) => { return value.indexOf(v) !== -1 ? a + 1 : a + 0; }, 0);
  1183. return counts(array, val);
  1184. },
  1185. filterLastestData(data, keyFields) {
  1186. const dataIndex = {};
  1187. for (const d of data) {
  1188. let key = 'd';
  1189. for (const kf of keyFields) {
  1190. key = key + '.' + (d[kf] || '');
  1191. }
  1192. const di = dataIndex[key];
  1193. if (di) {
  1194. if ((di.times * timesLen + di.order) < (d.times * timesLen + d.order)) dataIndex[key] = d;
  1195. } else {
  1196. dataIndex[key] = d;
  1197. }
  1198. }
  1199. const result = [];
  1200. for (const prop in dataIndex) {
  1201. result.push(dataIndex[prop]);
  1202. }
  1203. return result;
  1204. },
  1205. calcExpr(expr) {
  1206. const validExpr = expr.replace('=', '').replace('%', '/100');
  1207. return math.eval(validExpr);
  1208. },
  1209. /**
  1210. * 创建登录日志
  1211. * @return {Boolean} 日志是否创建成功
  1212. * @param {Number} type - 登录类型
  1213. * @param {Number} status - 是否显示记录
  1214. */
  1215. async getUserIPMsg() {
  1216. const { ctx } = this;
  1217. const ip = ctx.request.ip ? ctx.request.ip : '';
  1218. const ipInfo = await this.getIpInfoFromApi(ip);
  1219. const parser = new UAParser(ctx.header['user-agent']);
  1220. const osInfo = parser.getOS();
  1221. const cpuInfo = parser.getCPU();
  1222. const browserInfo = parser.getBrowser();
  1223. const ipMsg = {
  1224. os: `${osInfo.name} ${osInfo.version} ${cpuInfo.architecture}`,
  1225. browser: `${browserInfo.name} ${browserInfo.version}`,
  1226. ip,
  1227. address: ipInfo,
  1228. };
  1229. return ipMsg;
  1230. },
  1231. /**
  1232. * 根据ip请求获取详细地址
  1233. * @param {String} a_ip - ip地址
  1234. * @return {String} 详细地址
  1235. */
  1236. async getIpInfoFromApi(a_ip = '') {
  1237. if (!a_ip) return '';
  1238. if (a_ip === '127.0.0.1' || a_ip === '::1' || a_ip.indexOf('192.168') !== -1) return '服务器本机访问';
  1239. const { ip = '', region = '', city = '', isp = '' } = await this.sendIpRequest(a_ip);
  1240. let address = '';
  1241. region && (address += region + '省');
  1242. city && (address += city + '市 ');
  1243. isp && (address += isp + ' ');
  1244. ip && (address += `(${ip})`);
  1245. return address;
  1246. },
  1247. /**
  1248. * 发送请求获取详细地址
  1249. * @param {String} ip - ip地址
  1250. * @return {Object} the result of request
  1251. * @private
  1252. */
  1253. async sendIpRequest(ip) {
  1254. return new Promise(resolve => {
  1255. this.ctx.curl(`https://api01.aliyun.venuscn.com/ip?ip=${ip}`, {
  1256. dateType: 'json',
  1257. encoding: 'utf8',
  1258. timeout: 2000,
  1259. headers: {
  1260. Authorization: 'APPCODE 85c64bffe70445c4af9df7ae31c7bfcc',
  1261. },
  1262. }).then(({ status, data }) => {
  1263. if (status === 200) {
  1264. const result = JSON.parse(data.toString()).data;
  1265. if (!result.ip) {
  1266. resolve({});
  1267. } else {
  1268. resolve(result);
  1269. }
  1270. } else {
  1271. resolve({});
  1272. }
  1273. }).catch(() => {
  1274. resolve({});
  1275. });
  1276. });
  1277. },
  1278. };