helper.js 26 KB

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