helper.js 27 KB

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