helper.js 24 KB

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