helper.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  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. module.exports = {
  20. _: _,
  21. /**
  22. * 生成随机字符串
  23. *
  24. * @param {Number} length - 需要生成字符串的长度
  25. * @param {Number} type - 1为数字和字符 2为纯数字 3为纯字母
  26. * @return {String} - 返回生成结果
  27. */
  28. generateRandomString(length, type = 1) {
  29. length = parseInt(length);
  30. length = isNaN(length) ? 1 : length;
  31. let randSeed = [];
  32. let numberSeed = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  33. let stringSeed = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
  34. 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
  35. 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
  36. switch (type) {
  37. case 1:
  38. randSeed = stringSeed.concat(numberSeed);
  39. stringSeed = numberSeed = null;
  40. break;
  41. case 2:
  42. randSeed = numberSeed;
  43. break;
  44. case 3:
  45. randSeed = stringSeed;
  46. break;
  47. default:
  48. break;
  49. }
  50. const seedLength = randSeed.length - 1;
  51. let result = '';
  52. for (let i = 0; i < length; i++) {
  53. const index = Math.ceil(Math.random() * seedLength);
  54. result += randSeed[index];
  55. }
  56. return result;
  57. },
  58. /**
  59. * 字节转换
  60. * @param {number} bytes - 字节
  61. * @return {string} - 大小
  62. */
  63. bytesToSize(bytes) {
  64. if (parseInt(bytes) === 0) return '0 B';
  65. const k = 1024;
  66. const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  67. const i = Math.floor(Math.log(bytes) / Math.log(k));
  68. // return (bytes / Math.pow(k, i)) + ' ' + sizes[i];
  69. return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
  70. },
  71. /**
  72. * 浮点乘法计算
  73. * @param {number} arg1 - 乘数
  74. * @param {number} arg2 - 被乘数
  75. * @return {string} - 结果
  76. */
  77. accMul(arg1, arg2) {
  78. if (arg1 === '' || arg1 === null || arg1 === undefined || arg2 === '' || arg2 === null || arg2 === undefined) {
  79. return '';
  80. }
  81. let m = 0;
  82. const s1 = arg1.toString();
  83. const s2 = arg2.toString();
  84. try {
  85. m += s1.split('.')[1] !== undefined ? s1.split('.')[1].length : 0;
  86. } catch (e) {
  87. throw e;
  88. }
  89. try {
  90. m += s2.split('.')[1] !== undefined ? s2.split('.')[1].length : 0;
  91. } catch (e) {
  92. throw e;
  93. }
  94. return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m);
  95. },
  96. accAdd(arg1, arg2) {
  97. let r1;
  98. let r2;
  99. try {
  100. r1 = arg1.toString().split('.')[1].length;
  101. } catch (e) {
  102. r1 = 0;
  103. }
  104. try {
  105. r2 = arg2.toString().split('.')[1].length;
  106. } catch (e) {
  107. r2 = 0;
  108. }
  109. const c = Math.abs(r1 - r2);
  110. const m = Math.pow(10, Math.max(r1, r2));
  111. if (c > 0) {
  112. const cm = Math.pow(10, c);
  113. if (r1 > r2) {
  114. arg1 = Number(arg1.toString().replace('.', ''));
  115. arg2 = Number(arg2.toString().replace('.', '')) * cm;
  116. } else {
  117. arg1 = Number(arg1.toString().replace('.', '')) * cm;
  118. arg2 = Number(arg2.toString().replace('.', ''));
  119. }
  120. } else {
  121. arg1 = Number(arg1.toString().replace('.', ''));
  122. arg2 = Number(arg2.toString().replace('.', ''));
  123. }
  124. return (arg1 + arg2) / m;
  125. },
  126. // 四舍五入或末尾加零,实现类似php的 sprintf("%.".decimal."f", val);
  127. roundNum(val, decimals) {
  128. if (val === '' || val === null) {
  129. return '';
  130. }
  131. if (val !== '') {
  132. val = parseFloat(val);
  133. if (decimals < 1) {
  134. val = (Math.round(val)).toString();
  135. } else {
  136. let num = val.toString();
  137. if (num.lastIndexOf('.') === -1) {
  138. // num += '.';
  139. // num += this.makezero(decimals);
  140. val = num;
  141. } else {
  142. const valdecimals = num.split('.')[1].length;
  143. if (parseInt(valdecimals) < parseInt(decimals)) {
  144. // num += this.makezero(parseInt(decimals) - parseInt(valdecimals));
  145. val = num;
  146. } else if (parseInt(valdecimals) > parseInt(decimals)) {
  147. val = parseFloat(val) !== 0 ? Math.round(this.accMul(val, this.makemultiple(decimals))) / this.makemultiple(decimals) : this.makedecimalzero(decimals);
  148. let num = val.toString();
  149. if (num.lastIndexOf('.') === -1) {
  150. // num += '.';
  151. // num += this.makezero(decimals);
  152. val = num;
  153. } else {
  154. const valdecimals = num.split('.')[1].length;
  155. if (parseInt(valdecimals) < parseInt(decimals)) {
  156. // num += this.makezero(parseInt(decimals) - parseInt(valdecimals));
  157. val = num;
  158. }
  159. }
  160. }
  161. }
  162. }
  163. }
  164. return val;
  165. },
  166. // 生成num位的0
  167. makezero(num) {
  168. const arr = new Array(num);
  169. for (let i = 0; i < num; i++) {
  170. arr[i] = 0;
  171. }
  172. return arr.join('');
  173. },
  174. // 生成num位的10倍数
  175. makemultiple(num) {
  176. return Math.pow(10, parseInt(num));
  177. },
  178. // 根据单位获取小数位数
  179. findDecimal(unit) {
  180. let value = 3;
  181. if (unit !== '') {
  182. value = this.ctx.tender.info.precision.other.value;
  183. const changeUnits = this.ctx.tender.info.precision;
  184. for (const d in changeUnits) {
  185. if (changeUnits[d].unit !== undefined && changeUnits[d].unit === unit) {
  186. value = changeUnits[d].value;
  187. break;
  188. }
  189. }
  190. }
  191. return value;
  192. },
  193. /**
  194. * 显示排序符号
  195. *
  196. * @param {String} field - 字段名称
  197. * @return {String} - 返回字段排序的符号
  198. */
  199. showSortFlag(field) {
  200. const sort = this.ctx.sort;
  201. if (!(sort instanceof Array) || sort.length !== 2) {
  202. return '';
  203. }
  204. sort[1] = sort[1].toUpperCase();
  205. return (sort[0] === field && sort[1] === 'DESC') ? '' : '-';
  206. },
  207. /**
  208. * 判断是否为ajax请求
  209. *
  210. * @param {Object} request - 请求数据
  211. * @return {boolean} 判断结果
  212. */
  213. isAjax(request) {
  214. let headerInfo = request.headers['x-requested-with'] === undefined ? '' : request.headers['x-requested-with'];
  215. headerInfo = headerInfo.toLowerCase();
  216. return headerInfo === 'xmlhttprequest';
  217. },
  218. /**
  219. * 模拟发送请求
  220. *
  221. * @param {String} url - 请求地址
  222. * @param {Object} data - 请求数据
  223. * @param {String} type - 请求类型(POST) POST | GET
  224. * @param {String} dataType - 数据类型 json|text
  225. * @return {Object} - 请求结果
  226. */
  227. async sendRequest(url, data, type = 'POST', dataType = 'json') {
  228. // 发起请求
  229. try {
  230. const response = await this.ctx.curl(url, {
  231. method: type,
  232. data,
  233. dataType,
  234. });
  235. if (response.status !== 200) {
  236. throw '请求失败';
  237. }
  238. return response.data;
  239. } catch (err) {
  240. throw '请求失败';
  241. }
  242. },
  243. /**
  244. * 深度验证数据
  245. *
  246. * @param {Object} rule - 数据规则
  247. * @return {void}
  248. */
  249. validate(rule) {
  250. // 先用内置的验证器验证数据
  251. this.ctx.validate(rule);
  252. // 然后再验证是否有多余的数据
  253. const postData = this.ctx.request.body;
  254. delete postData._csrf;
  255. const postDataKey = Object.keys(postData);
  256. const ruleKey = Object.keys(rule);
  257. // 自动增加字段则填充上,以防判断出错
  258. if (postData.create_time !== undefined) {
  259. ruleKey.push('create_time');
  260. }
  261. for (const tmp of postDataKey) {
  262. // 规则里面没有定义则抛出异常
  263. if (ruleKey.indexOf(tmp) < 0) {
  264. throw '参数不正确';
  265. }
  266. }
  267. },
  268. /**
  269. * 拆分path
  270. *
  271. * @param {String|Array} paths - 拆分字符
  272. * @param {String} symbol - 拆分符号
  273. * @return {Array} - 拆分结果
  274. */
  275. explodePath(paths, symbol = '-') {
  276. const result = [];
  277. paths = paths instanceof Array ? paths : [paths];
  278. for (const path of paths) {
  279. // 拆分数据
  280. const pathArray = path.split(symbol);
  281. // 用户缓存循环的数据
  282. const tmpArray = [];
  283. for (const tmp of pathArray) {
  284. // 每次循环都追加一个数据进去
  285. tmpArray.push(tmp);
  286. const tmpPathString = tmpArray.join(symbol);
  287. // 判断是否已经存在有对应数据
  288. if (result.indexOf(tmpPathString) >= 0) {
  289. continue;
  290. }
  291. result.push(tmpPathString);
  292. }
  293. }
  294. return result;
  295. },
  296. /**
  297. * 基于obj, 拷贝sObj中的内容
  298. * obj = {a: 1, b: 2}, sObj = {a: 0, c: 3}, 返回{a: 0, b: 2, c: 3}
  299. * @param obj
  300. * @param sObj
  301. * @returns {any}
  302. */
  303. updateObj(obj, sObj) {
  304. if (!obj) {
  305. return JSON.parse(JSON.stringify(sObj));
  306. }
  307. const result = JSON.parse(JSON.stringify(obj));
  308. if (sObj) {
  309. for (const prop in sObj) {
  310. result[prop] = sObj[prop];
  311. }
  312. }
  313. return result;
  314. },
  315. /**
  316. * 在数组中查找
  317. * @param {Array} arr
  318. * @param name -
  319. * @param value
  320. * @returns {*}
  321. */
  322. findData(arr, name, value) {
  323. if (!arr instanceof Array) {
  324. throw '该方法仅用于数组查找';
  325. }
  326. if (arr.length === 0) { return undefined; }
  327. for (const data of arr) {
  328. if (data[name] == value) {
  329. return data;
  330. }
  331. }
  332. return undefined;
  333. },
  334. /**
  335. * 检查数字是否为0
  336. * @param {Number} value
  337. * @return {boolean}
  338. */
  339. checkZero(value) {
  340. return value === undefined || value === null || (this._.isNumber(value) && Math.abs(value) < zeroRange);
  341. },
  342. /**
  343. * 检查数字是否相等
  344. * @param {Number} value1
  345. * @param {Number} value2
  346. * @returns {boolean}
  347. */
  348. checkNumberEqual(value1, value2) {
  349. if (value1 && value2) {
  350. return Math.abs(value2 - value1) > zeroRange;
  351. } else {
  352. return (!value1 && !value2)
  353. }
  354. },
  355. /**
  356. * 比较编码
  357. * @param str1
  358. * @param str2
  359. * @param symbol
  360. * @returns {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. } else {
  373. return -1
  374. }
  375. } else {
  376. if (numReg.test(code2)) {
  377. return 1;
  378. } else {
  379. return code1 === code2 ? 0 : (code1 < code2 ? -1 : 1); //code1.localeCompare(code2);
  380. }
  381. }
  382. }
  383. const numReg = /^[0-9]+$/;
  384. const aCodes = str1.split(symbol), 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. * @returns {string}
  398. */
  399. getChapterCode(code, symbol = '-') {
  400. if (!code || code === '') return '';
  401. const codePath = code.split(symbol);
  402. const reg = /^[0-9]*$/;
  403. if (reg.test(codePath[0])) {
  404. const num = parseInt(codePath[0]);
  405. return this.mul(this.div(num, 100, 0), 100) + '';
  406. } else {
  407. return '10000';
  408. }
  409. },
  410. /**
  411. * 树结构节点排序,要求最顶层节点须在同一父节点下
  412. * @param treeNodes
  413. * @param idField
  414. * @param pidField
  415. */
  416. sortTreeNodes (treeNodes, idField, pidField) {
  417. const result = [];
  418. const getFirstLevel = function (nodes) {
  419. let result;
  420. for (const node of nodes) {
  421. if (!result || result > node.level) {
  422. result = node.level;
  423. }
  424. }
  425. return result;
  426. };
  427. const getLevelNodes = function (nodes, level) {
  428. const children = nodes.filter(function (a) {
  429. return a.level = level;
  430. });
  431. children.sort(function (a, b) {
  432. return a.order - b.order;
  433. });
  434. return children;
  435. };
  436. const getChildren = function (nodes, node) {
  437. const children = nodes.filter(function (a) {
  438. return a[pidField] = node[idField];
  439. });
  440. children.sort(function (a, b) {
  441. return a.order - b.order;
  442. });
  443. return children;
  444. };
  445. const addSortNodes = function (nodes) {
  446. for (let i = 0; i< nodes.length; i++) {
  447. result.push(nodes[i]);
  448. addSortNodes(getChildren(nodes[i]));
  449. }
  450. };
  451. const firstLevel = getFirstLevel(treeNodes);
  452. addSortNodes(getLevelNodes(treeNodes, firstLevel));
  453. },
  454. /**
  455. * 判断当前用户是否有指定权限
  456. *
  457. * @param {Number|Array} permission - 权限id
  458. * @return {Boolean} - 返回判断结果
  459. */
  460. hasPermission(permission) {
  461. let result = false;
  462. try {
  463. const sessionUser = this.ctx.session.sessionUser;
  464. if (sessionUser.permission === undefined) {
  465. throw '不存在权限数据';
  466. }
  467. let currentPermission = sessionUser.permission;
  468. if (currentPermission === '') {
  469. throw '权限数据为空';
  470. }
  471. // 管理员则直接返回结果
  472. if (currentPermission === 'all') {
  473. return true;
  474. }
  475. currentPermission = currentPermission.split(',');
  476. permission = permission instanceof Array ? permission : [permission];
  477. let counter = 0;
  478. for (const tmp of permission) {
  479. if (currentPermission[tmp] !== undefined) {
  480. counter++;
  481. }
  482. }
  483. result = counter === permission.length;
  484. } catch (error) {
  485. result = false;
  486. }
  487. return result;
  488. },
  489. /**
  490. * 递归创建文件夹(fs.mkdirSync需要上一层文件夹已存在)
  491. * @param pathName
  492. * @returns {Promise<void>}
  493. */
  494. async recursiveMkdirSync(pathName) {
  495. if (!fs.existsSync(pathName)) {
  496. const upperPath = path.dirname(pathName);
  497. if (!fs.existsSync(upperPath)) {
  498. await this.recursiveMkdirSync(upperPath);
  499. }
  500. await fs.mkdirSync(pathName);
  501. }
  502. },
  503. /**
  504. * 字节 保存至 本地文件
  505. * @param buffer - 字节
  506. * @param fileName - 文件名
  507. * @returns {Promise<void>}
  508. */
  509. async saveBufferFile(buffer, fileName) {
  510. // 检查文件夹是否存在,不存在则直接创建文件夹
  511. const pathName = path.dirname(fileName);
  512. if (!fs.existsSync(pathName)) {
  513. await this.recursiveMkdirSync(pathName);
  514. }
  515. await fs.writeFileSync(fileName, buffer);
  516. },
  517. /**
  518. * 将文件流的数据保存至本地文件
  519. * @param stream
  520. * @param fileName
  521. * @returns {Promise<void>}
  522. */
  523. async saveStreamFile(stream, fileName) {
  524. // 读取字节流
  525. const parts = await streamToArray(stream);
  526. // 转化为buffer
  527. const buffer = Buffer.concat(parts);
  528. // 写入文件
  529. await this.saveBufferFile(buffer, fileName);
  530. },
  531. /**
  532. * 检查code是否是指标模板数据
  533. * @param {String} code
  534. * @returns {boolean}
  535. */
  536. validBillsCode(code) {
  537. const reg1 = /(^[0-9]+)([a-z0-9\-]*)/i;
  538. const reg2 = /([a-z0-9]+$)/i;
  539. return reg1.test(code) && reg2.test(code);
  540. },
  541. getNumberFormatter(decimal) {
  542. if (decimal <= 0) {
  543. return "0";
  544. }
  545. let pre = "0.";
  546. for (let i = 0; i < decimal; i++) {
  547. pre += "#"
  548. }
  549. return pre;
  550. },
  551. /**
  552. * 根据单位查找对应的清单精度
  553. * @param {tenderInfo.precision} list - 清单精度列表
  554. * @param {String} unit - 单位
  555. * @returns {number}
  556. */
  557. findPrecision(list, unit) {
  558. if (unit) {
  559. for (const p in list) {
  560. if (list[p].unit && list[p].unit === unit) {
  561. return list[p];
  562. }
  563. }
  564. }
  565. return list.other;
  566. },
  567. /**
  568. * 检查数据中的精度
  569. * @param {Object} Obj - 检查的数据
  570. * @param {Array} fields - 检查的属性
  571. * @param {Number} precision - 精度
  572. * @constructor
  573. */
  574. checkFieldPrecision(Obj, fields, precision = 2) {
  575. if (Obj) {
  576. for (const field of fields) {
  577. if (Obj[field]) {
  578. Obj[field] = this.round(Obj[field], precision);
  579. }
  580. }
  581. }
  582. },
  583. /**
  584. * 过滤无效数据
  585. *
  586. * @param obj
  587. * @param fields - 有效数据的数组
  588. */
  589. filterValidFields(data, fields) {
  590. if (data) {
  591. const result = {};
  592. for (const prop in data) {
  593. if (fields.indexOf(prop) !== -1) {
  594. result[prop] = data[prop];
  595. }
  596. }
  597. return result;
  598. } else {
  599. return data;
  600. }
  601. },
  602. // 加减乘除方法,为方便调用,兼容num为空的情况
  603. // 加减法使用base_calc,乘除法使用Decimal(原因详见demo/calc_test)
  604. /**
  605. * 加法 num1 + num2
  606. * @param num1
  607. * @param num2
  608. * @returns {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. * @returns {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. * @returns {*}
  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. * @returns {*}
  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. } else {
  644. return null;
  645. }
  646. },
  647. /**
  648. * 四舍五入(统一,方便以后万一需要置换)
  649. * @param {Number} value - 舍入的数字
  650. * @param {Number} decimal - 要保留的小数位数
  651. * @returns {*}
  652. */
  653. round(value, decimal) {
  654. //return value ? bc.round(value, decimal) : null;
  655. return value ? new Decimal(value).toDecimalPlaces(decimal).toNumber() : null;
  656. },
  657. /**
  658. * 汇总
  659. * @param array
  660. * @returns {number}
  661. */
  662. sum(array) {
  663. let result = 0;
  664. for (const a of array) {
  665. result = this.add(result, a);
  666. }
  667. return result;
  668. },
  669. /**
  670. * 使用正则替换字符
  671. * @param str
  672. * @param reg
  673. * @param subStr
  674. * @returns {*}
  675. */
  676. replaceStr(str, reg, subStr) {
  677. return str ? str.replace(reg, subStr) : str;
  678. },
  679. /**
  680. * 替换字符串中的 换行符回车符
  681. * @param str
  682. * @returns {*}
  683. */
  684. replaceReturn(str) {
  685. // return str
  686. // ? (typeof str === 'string') ? str.replace(/[\r\n]/g, '') : str + ''
  687. // : str;
  688. return (str && typeof str === 'string')
  689. ? str.replace(/[\r\n]/g, '')
  690. : !_.isNil(str) ? str + '' : str;
  691. },
  692. /**
  693. * 替换字符串中的 换行符回车符为换行符<br>
  694. * @param str
  695. * @returns {*}
  696. */
  697. replaceRntoBr(str) {
  698. // return str
  699. // ? (typeof str === 'string') ? str.replace(/[\r\n]/g, '') : str + ''
  700. // : str;
  701. return (str && typeof str === 'string')
  702. ? str.replace(/[\r\n]/g, '<br>')
  703. : !_.isNil(str) ? str + '' : str;
  704. },
  705. /**
  706. * 获取 字符串 数组的 mysql 筛选条件
  707. *
  708. * @param arr
  709. * @returns {*}
  710. */
  711. getInArrStrSqlFilter(arr) {
  712. let result = '';
  713. for (const a of arr) {
  714. if (result !== '') {
  715. result = result + ','
  716. }
  717. result = result + this.ctx.app.mysql.escape(a);
  718. }
  719. return result;
  720. },
  721. /**
  722. * 合并相关数据
  723. * @param {Array} main - 主数据
  724. * @param {Array[]}rela - 相关数据 {data, fields, prefix, relaId}
  725. */
  726. assignRelaData(main, rela) {
  727. const index = {}, 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. }
  744. for (const r of rela) {
  745. loadFields(r.data, r.fields, r.prefix, r.relaId);
  746. }
  747. },
  748. whereSql (where, as) {
  749. if (!where) {
  750. return '';
  751. }
  752. const wheres = [];
  753. const values = [];
  754. for (const key in where) {
  755. const value = where[key];
  756. if (Array.isArray(value)) {
  757. wheres.push('?? IN (?)');
  758. } else {
  759. wheres.push('?? = ?');
  760. }
  761. values.push((as && as !== '') ? as + '.' + key : key);
  762. values.push(value);
  763. }
  764. if (wheres.length > 0) {
  765. return this.ctx.app.mysql.format(' WHERE ' + wheres.join(' AND '), values);
  766. }
  767. return '';
  768. },
  769. formatMoney(s, dot = ',') {
  770. if (!s) return '0.00';
  771. s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(2) + "";
  772. var l = s.split(".")[0].split("").reverse(),
  773. r = s.split(".")[1];
  774. let t = "";
  775. for(let i = 0; i < l.length; i ++ ) {
  776. t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? dot : "");
  777. }
  778. return t.split("").reverse().join("") + "." + r;
  779. },
  780. transFormToChinese(num) {
  781. const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  782. const unit = ["", "十", "百", "千", "万"];
  783. num = parseInt(num);
  784. let getWan = (temp) => {
  785. let strArr = temp.toString().split("").reverse();
  786. let newNum = "";
  787. for (var i = 0; i < strArr.length; i++) {
  788. 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;
  789. }
  790. return strArr.length === 2 && newNum.indexOf("一十") !== -1 ? newNum.replace('一十', '十') : newNum;
  791. }
  792. let overWan = Math.floor(num / 10000);
  793. let noWan = num % 10000;
  794. if (noWan.toString().length < 4) noWan = "0" + noWan;
  795. return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
  796. },
  797. dateTran(time) {
  798. return moment(time).format('YYYY年MM月DD日 HH:mm');
  799. },
  800. async sendUserSms(userId, type, judge, msg) {
  801. const mobiles = [];
  802. if (!userId || (userId instanceof Array && userId.length === 0)) return;
  803. const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({where: {id: userId}});
  804. for (const su of smsUser) {
  805. if (!su.auth_mobile || su.auth_mobile === '') continue;
  806. if (!su.sms_type || su.sms_type === '') continue;
  807. const smsType = JSON.parse(su.sms_type);
  808. if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
  809. mobiles.push(su.auth_mobile);
  810. }
  811. }
  812. if (mobiles.length > 0) {
  813. const sms = new SMS(this.ctx);
  814. const tenderName = await sms.contentChange(this.ctx.tender.data.name);
  815. const content = '【纵横计量支付】' + tenderName + msg;
  816. sms.send(mobiles, content);
  817. }
  818. },
  819. /**
  820. *
  821. * @param setting
  822. * @param data
  823. * @returns {{} & any & {"!ref": string} & {"!cols"}}
  824. */
  825. simpleXlsxSheetData (setting, data) {
  826. const headerStyle = {
  827. font: { sz: 10, bold: true },
  828. alignment: {horizontal: 'center'},
  829. };
  830. const sHeader = setting.header
  831. .map((v, i) => Object.assign({}, {v: v, s: headerStyle, position: String.fromCharCode(65+i) + 1 }))
  832. .reduce((prev, next) => Object.assign({}, prev, {[next.position]: {v: next.v, s: next.s}}), {});
  833. const sData = data
  834. .map((v, i) => v.map((k, j) => Object.assign({}, {
  835. v: k ? k : '',
  836. s: { font: { sz: 10 }, alignment: {horizontal: setting.hAlign[j]}},
  837. position: String.fromCharCode(65+j) + (i+2) })))
  838. .reduce((prev, next) => prev.concat(next))
  839. .reduce((prev, next) => Object.assign({}, prev, {[next.position]: {v: next.v, s: next.s}}), {});
  840. const output = Object.assign({}, sHeader, sData);
  841. const outputPos = Object.keys(output);
  842. const result = Object.assign({}, output,
  843. {'!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1]},
  844. {'!cols': setting.width.map((w) => Object.assign({}, {wpx: w}))});
  845. return result;
  846. },
  847. log(error) {
  848. if (error.stack) {
  849. this.ctx.logger.error(error);
  850. } else {
  851. this.ctx.getLogger('fail').info(JSON.stringify({
  852. error: error,
  853. project: this.ctx.session.sessionProject,
  854. user: this.ctx.session.sessionUser,
  855. body: this.ctx.session.body,
  856. }));
  857. }
  858. },
  859. /**
  860. * 添加debug信息
  861. * 在debug模式下,debug信息将传输到浏览器并打印
  862. *
  863. * @param {String}key
  864. * @param {*}data
  865. */
  866. addDebugInfo(key, ...data) {
  867. if (!this.ctx.debugInfo) {
  868. this.ctx.debugInfo = { key: {}, other: [] };
  869. }
  870. if (key) {
  871. this.ctx.debugInfo.key[key] = data;
  872. } else {
  873. this.ctx.debugInfo.other.push(data);
  874. }
  875. }
  876. };