helper.js 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529
  1. 'use strict';
  2. /**
  3. * 辅助方法扩展
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/9/28
  7. * @version
  8. */
  9. const moment = require('moment');
  10. const zeroRange = 0.0000000001;
  11. const fs = require('fs');
  12. const path = require('path');
  13. const streamToArray = require('stream-to-array');
  14. const _ = require('lodash');
  15. const bc = require('../lib/base_calc.js');
  16. const Decimal = require('decimal.js');
  17. Decimal.set({ precision: 50, defaults: true });
  18. const SMS = require('../lib/sms');
  19. const WX = require('../lib/wechat');
  20. const timesLen = 100;
  21. const UAParser = require('ua-parser-js');
  22. const math = require('mathjs');
  23. const syncApiConst = require('../const/sync_api');
  24. const crypto = require('crypto');
  25. const jwt = require('jsonwebtoken');
  26. const sign = require('../const/sign');
  27. module.exports = {
  28. _,
  29. /**
  30. * 生成随机字符串
  31. *
  32. * @param {Number} length - 需要生成字符串的长度
  33. * @param {Number} type - 1为数字和字符 2为纯数字 3为纯字母
  34. * @return {String} - 返回生成结果
  35. */
  36. generateRandomString(length, type = 1) {
  37. length = parseInt(length);
  38. length = isNaN(length) ? 1 : length;
  39. let randSeed = [];
  40. let numberSeed = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  41. let stringSeed = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
  42. 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
  43. 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
  44. switch (type) {
  45. case 1:
  46. randSeed = stringSeed.concat(numberSeed);
  47. stringSeed = numberSeed = null;
  48. break;
  49. case 2:
  50. randSeed = numberSeed;
  51. break;
  52. case 3:
  53. randSeed = stringSeed;
  54. break;
  55. default:
  56. break;
  57. }
  58. const seedLength = randSeed.length - 1;
  59. let result = '';
  60. for (let i = 0; i < length; i++) {
  61. const index = Math.ceil(Math.random() * seedLength);
  62. result += randSeed[index];
  63. }
  64. return result;
  65. },
  66. /**
  67. * 字节转换
  68. * @param {number} bytes - 字节
  69. * @return {string} - 大小
  70. */
  71. bytesToSize(bytes) {
  72. if (parseInt(bytes) === 0) return '0 B';
  73. const k = 1024;
  74. const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  75. const i = Math.floor(Math.log(bytes) / Math.log(k));
  76. // return (bytes / Math.pow(k, i)) + ' ' + sizes[i];
  77. return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
  78. },
  79. /**
  80. * 浮点乘法计算
  81. * @param {number} arg1 - 乘数
  82. * @param {number} arg2 - 被乘数
  83. * @return {string} - 结果
  84. */
  85. accMul(arg1, arg2) {
  86. if (arg1 === '' || arg1 === null || arg1 === undefined || arg2 === '' || arg2 === null || arg2 === undefined) {
  87. return '';
  88. }
  89. let m = 0;
  90. const s1 = arg1.toString();
  91. const s2 = arg2.toString();
  92. try {
  93. m += s1.split('.')[1] !== undefined ? s1.split('.')[1].length : 0;
  94. } catch (e) {
  95. throw e;
  96. }
  97. try {
  98. m += s2.split('.')[1] !== undefined ? s2.split('.')[1].length : 0;
  99. } catch (e) {
  100. throw e;
  101. }
  102. return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m);
  103. },
  104. accAdd(arg1, arg2) {
  105. let r1;
  106. let r2;
  107. try {
  108. r1 = arg1.toString().split('.')[1].length;
  109. } catch (e) {
  110. r1 = 0;
  111. }
  112. try {
  113. r2 = arg2.toString().split('.')[1].length;
  114. } catch (e) {
  115. r2 = 0;
  116. }
  117. const c = Math.abs(r1 - r2);
  118. const m = Math.pow(10, Math.max(r1, r2));
  119. if (c > 0) {
  120. const cm = Math.pow(10, c);
  121. if (r1 > r2) {
  122. arg1 = Number(arg1.toString().replace('.', ''));
  123. arg2 = Number(arg2.toString().replace('.', '')) * cm;
  124. } else {
  125. arg1 = Number(arg1.toString().replace('.', '')) * cm;
  126. arg2 = Number(arg2.toString().replace('.', ''));
  127. }
  128. } else {
  129. arg1 = Number(arg1.toString().replace('.', ''));
  130. arg2 = Number(arg2.toString().replace('.', ''));
  131. }
  132. return (arg1 + arg2) / m;
  133. },
  134. // 四舍五入或末尾加零,实现类似php的 sprintf("%.".decimal."f", val);
  135. roundNum(val, decimals) {
  136. if (val === '' || val === null) {
  137. return '';
  138. }
  139. if (val !== '') {
  140. val = parseFloat(val);
  141. if (decimals < 1) {
  142. val = (Math.round(val)).toString();
  143. } else {
  144. const num = val.toString();
  145. if (num.lastIndexOf('.') === -1) {
  146. // num += '.';
  147. // num += this.makezero(decimals);
  148. val = num;
  149. } else {
  150. const valdecimals = num.split('.')[1].length;
  151. if (parseInt(valdecimals) < parseInt(decimals)) {
  152. // num += this.makezero(parseInt(decimals) - parseInt(valdecimals));
  153. val = num;
  154. } else if (parseInt(valdecimals) > parseInt(decimals)) {
  155. val = parseFloat(val) !== 0 ? Math.round(this.accMul(val, this.makemultiple(decimals))) / this.makemultiple(decimals) : this.makedecimalzero(decimals);
  156. const num = val.toString();
  157. if (num.lastIndexOf('.') === -1) {
  158. // num += '.';
  159. // num += this.makezero(decimals);
  160. val = num;
  161. } else {
  162. const valdecimals = num.split('.')[1].length;
  163. if (parseInt(valdecimals) < parseInt(decimals)) {
  164. // num += this.makezero(parseInt(decimals) - parseInt(valdecimals));
  165. val = num;
  166. }
  167. }
  168. }
  169. }
  170. }
  171. }
  172. return val;
  173. },
  174. // 生成num位的0
  175. makezero(num) {
  176. const arr = new Array(num);
  177. for (let i = 0; i < num; i++) {
  178. arr[i] = 0;
  179. }
  180. return arr.join('');
  181. },
  182. // 生成num位的10倍数
  183. makemultiple(num) {
  184. return Math.pow(10, parseInt(num));
  185. },
  186. // 根据单位获取小数位数
  187. findDecimal(unit) {
  188. let value = 3;
  189. if (unit !== '') {
  190. value = this.ctx.tender.info.precision.other.value;
  191. const changeUnits = this.ctx.tender.info.precision;
  192. for (const d in changeUnits) {
  193. if (changeUnits[d].unit !== undefined && changeUnits[d].unit === unit) {
  194. value = changeUnits[d].value;
  195. break;
  196. }
  197. }
  198. }
  199. return value;
  200. },
  201. /**
  202. * 显示排序符号
  203. *
  204. * @param {String} field - 字段名称
  205. * @return {String} - 返回字段排序的符号
  206. */
  207. showSortFlag(field) {
  208. const sort = this.ctx.sort;
  209. if (!(sort instanceof Array) || sort.length !== 2) {
  210. return '';
  211. }
  212. sort[1] = sort[1].toUpperCase();
  213. return (sort[0] === field && sort[1] === 'DESC') ? '' : '-';
  214. },
  215. /**
  216. * 判断是否为ajax请求
  217. *
  218. * @param {Object} request - 请求数据
  219. * @return {boolean} 判断结果
  220. */
  221. isAjax(request) {
  222. let headerInfo = request.headers['x-requested-with'] === undefined ? '' : request.headers['x-requested-with'];
  223. headerInfo = headerInfo.toLowerCase();
  224. return headerInfo === 'xmlhttprequest';
  225. },
  226. /**
  227. * 模拟发送请求
  228. *
  229. * @param {String} url - 请求地址
  230. * @param {Object} data - 请求数据
  231. * @param {String} type - 请求类型(POST) POST | GET
  232. * @param {String} dataType - 数据类型 json|text
  233. * @return {Object} - 请求结果
  234. */
  235. async sendRequest(url, data, type = 'POST', dataType = 'json') {
  236. // 发起请求
  237. try {
  238. const response = await this.ctx.curl(url, {
  239. method: type,
  240. data,
  241. dataType,
  242. });
  243. if (response.status !== 200) {
  244. throw '请求失败';
  245. }
  246. return response.data;
  247. } catch (err) {
  248. throw '请求失败';
  249. }
  250. },
  251. /**
  252. * 模拟多次发送请求(失败后再获取)
  253. *
  254. * @param {String} url - 请求地址
  255. * @param {Object} data - 失败请求次数
  256. * @param {String} type - 请求类型(POST) POST | GET
  257. * @param {String} dataType - 数据类型 json|text
  258. * @param {String} count - 重复次数
  259. * @return {Object} - 请求结果
  260. */
  261. async sendMoreRequest(url, data = null, type = 'POST', dataType = 'json', count = 3) {
  262. // 发起请求
  263. try {
  264. let response = data ? await this.ctx.curl(url, {
  265. method: type,
  266. data,
  267. dataType,
  268. }) : await this.ctx.curl(url);
  269. if (response.status !== 200) {
  270. if (count > 0) {
  271. count = count - 1;
  272. response = await this.sendMoreRequest(url, data, type, dataType, count);
  273. } else {
  274. throw '请求失败';
  275. }
  276. }
  277. return response.data;
  278. } catch (err) {
  279. throw '请求失败';
  280. }
  281. },
  282. /**
  283. * 深度验证数据
  284. *
  285. * @param {Object} rule - 数据规则
  286. * @return {void}
  287. */
  288. validate(rule) {
  289. // 先用内置的验证器验证数据
  290. this.ctx.validate(rule);
  291. // 然后再验证是否有多余的数据
  292. const postData = this.ctx.request.body;
  293. delete postData._csrf_j;
  294. const postDataKey = Object.keys(postData);
  295. const ruleKey = Object.keys(rule);
  296. // 自动增加字段则填充上,以防判断出错
  297. if (postData.create_time !== undefined) {
  298. ruleKey.push('create_time');
  299. }
  300. for (const tmp of postDataKey) {
  301. // 规则里面没有定义则抛出异常
  302. if (ruleKey.indexOf(tmp) < 0) {
  303. throw '参数不正确';
  304. }
  305. }
  306. },
  307. /**
  308. * 拆分path
  309. *
  310. * @param {String|Array} paths - 拆分字符
  311. * @param {String} symbol - 拆分符号
  312. * @return {Array} - 拆分结果
  313. */
  314. explodePath(paths, symbol = '-') {
  315. const result = [];
  316. paths = paths instanceof Array ? paths : [paths];
  317. for (const path of paths) {
  318. // 拆分数据
  319. const pathArray = path.split(symbol);
  320. // 用户缓存循环的数据
  321. const tmpArray = [];
  322. for (const tmp of pathArray) {
  323. // 每次循环都追加一个数据进去
  324. tmpArray.push(tmp);
  325. const tmpPathString = tmpArray.join(symbol);
  326. // 判断是否已经存在有对应数据
  327. if (result.indexOf(tmpPathString) >= 0) {
  328. continue;
  329. }
  330. result.push(tmpPathString);
  331. }
  332. }
  333. return result;
  334. },
  335. /**
  336. * 基于obj, 拷贝sObj中的内容
  337. * obj = {a: 1, b: 2}, sObj = {a: 0, c: 3}, 返回{a: 0, b: 2, c: 3}
  338. * @param obj
  339. * @param sObj
  340. * @return {any}
  341. */
  342. updateObj(obj, sObj) {
  343. if (!obj) {
  344. return JSON.parse(JSON.stringify(sObj));
  345. }
  346. const result = JSON.parse(JSON.stringify(obj));
  347. if (sObj) {
  348. for (const prop in sObj) {
  349. result[prop] = sObj[prop];
  350. }
  351. }
  352. return result;
  353. },
  354. /**
  355. * 在数组中查找
  356. * @param {Array} arr
  357. * @param name -
  358. * @param value
  359. * @return {*}
  360. */
  361. findData(arr, name, value) {
  362. if (!arr instanceof Array) {
  363. throw '该方法仅用于数组查找';
  364. }
  365. if (arr.length === 0) { return undefined; }
  366. for (const data of arr) {
  367. if (data[name] == value) {
  368. return data;
  369. }
  370. }
  371. return undefined;
  372. },
  373. /**
  374. * 检查数字是否为0
  375. * @param {Number} value
  376. * @return {boolean}
  377. */
  378. checkZero(value) {
  379. return value === undefined || value === null || (this._.isNumber(value) && Math.abs(value) < zeroRange);
  380. },
  381. /**
  382. * 检查数字是否相等
  383. * @param {Number} value1
  384. * @param {Number} value2
  385. * @return {boolean}
  386. */
  387. numEqual(value1, value2) {
  388. if (value1 && value2) {
  389. return Math.abs(value2 - value1) < zeroRange;
  390. }
  391. return (!value1 && !value2);
  392. },
  393. /**
  394. * 比较编码
  395. * @param str1
  396. * @param str2
  397. * @param symbol
  398. * @return {number}
  399. */
  400. compareCode(str1, str2, symbol = '-') {
  401. if (!str1) {
  402. return 1;
  403. } else if (!str2) {
  404. return -1;
  405. }
  406. const numReg = /^[0-9]+$/;
  407. function compareSubCode(code1, code2) {
  408. if (numReg.test(code1)) {
  409. if (numReg.test(code2)) {
  410. return parseInt(code1) - parseInt(code2);
  411. }
  412. return -1;
  413. }
  414. if (numReg.test(code2)) {
  415. return 1;
  416. }
  417. return code1 === code2 ? 0 : (code1 < code2 ? -1 : 1); // code1.localeCompare(code2);
  418. }
  419. const aCodes = str1.split(symbol),
  420. bCodes = str2.split(symbol);
  421. for (let i = 0, iLength = Math.min(aCodes.length, bCodes.length); i < iLength; ++i) {
  422. const iCompare = compareSubCode(aCodes[i], bCodes[i]);
  423. if (iCompare !== 0) {
  424. return iCompare;
  425. }
  426. }
  427. return aCodes.length - bCodes.length;
  428. },
  429. /**
  430. * 根据 清单编号 获取 章级编号
  431. * @param code
  432. * @param symbol
  433. * @return {string}
  434. */
  435. getChapterCode(code, symbol = '-') {
  436. if (!code || code === '') return '';
  437. const codePath = code.split(symbol);
  438. const reg = /^[^0-9]*[0-9]{3,4}$/;
  439. if (reg.test(codePath[0])) {
  440. const numReg = /[0-9]{3,4}$/;
  441. const result = codePath[0].match(numReg);
  442. const num = parseInt(result[0]);
  443. return this.mul(this.div(num, 100, 0), 100) + '';
  444. }
  445. return '10000';
  446. },
  447. /**
  448. * 树结构节点排序,要求最顶层节点须在同一父节点下
  449. * @param treeNodes
  450. * @param idField
  451. * @param pidField
  452. */
  453. sortTreeNodes(treeNodes, idField, pidField) {
  454. const result = [];
  455. const getFirstLevel = function(nodes) {
  456. let result;
  457. for (const node of nodes) {
  458. if (!result || result > node.level) {
  459. result = node.level;
  460. }
  461. }
  462. return result;
  463. };
  464. const getLevelNodes = function(nodes, level) {
  465. const children = nodes.filter(function(a) {
  466. return a.level = level;
  467. });
  468. children.sort(function(a, b) {
  469. return a.order - b.order;
  470. });
  471. return children;
  472. };
  473. const getChildren = function(nodes, node) {
  474. const children = nodes.filter(function(a) {
  475. return a[pidField] = node[idField];
  476. });
  477. children.sort(function(a, b) {
  478. return a.order - b.order;
  479. });
  480. return children;
  481. };
  482. const addSortNodes = function(nodes) {
  483. for (let i = 0; i < nodes.length; i++) {
  484. result.push(nodes[i]);
  485. addSortNodes(getChildren(nodes[i]));
  486. }
  487. };
  488. const firstLevel = getFirstLevel(treeNodes);
  489. addSortNodes(getLevelNodes(treeNodes, firstLevel));
  490. },
  491. /**
  492. * 判断当前用户是否有指定权限
  493. *
  494. * @param {Number|Array} permission - 权限id
  495. * @return {Boolean} - 返回判断结果
  496. */
  497. hasPermission(permission) {
  498. let result = false;
  499. try {
  500. const sessionUser = this.ctx.session.sessionUser;
  501. if (sessionUser.permission === undefined) {
  502. throw '不存在权限数据';
  503. }
  504. let currentPermission = sessionUser.permission;
  505. if (currentPermission === '') {
  506. throw '权限数据为空';
  507. }
  508. // 管理员则直接返回结果
  509. if (currentPermission === 'all') {
  510. return true;
  511. }
  512. currentPermission = currentPermission.split(',');
  513. permission = permission instanceof Array ? permission : [permission];
  514. let counter = 0;
  515. for (const tmp of permission) {
  516. if (currentPermission[tmp] !== undefined) {
  517. counter++;
  518. }
  519. }
  520. result = counter === permission.length;
  521. } catch (error) {
  522. result = false;
  523. }
  524. return result;
  525. },
  526. /**
  527. * 递归创建文件夹(fs.mkdirSync需要上一层文件夹已存在)
  528. * @param pathName
  529. * @return {Promise<void>}
  530. */
  531. async recursiveMkdirSync(pathName) {
  532. if (!fs.existsSync(pathName)) {
  533. const upperPath = path.dirname(pathName);
  534. if (!fs.existsSync(upperPath)) {
  535. await this.recursiveMkdirSync(upperPath);
  536. }
  537. await fs.mkdirSync(pathName);
  538. }
  539. },
  540. /**
  541. * 字节 保存至 本地文件
  542. * @param buffer - 字节
  543. * @param fileName - 文件名
  544. * @return {Promise<void>}
  545. */
  546. async saveBufferFile(buffer, fileName) {
  547. // 检查文件夹是否存在,不存在则直接创建文件夹
  548. const pathName = path.dirname(fileName);
  549. if (!fs.existsSync(pathName)) {
  550. await this.recursiveMkdirSync(pathName);
  551. }
  552. await fs.writeFileSync(fileName, buffer);
  553. },
  554. /**
  555. * 将文件流的数据保存至本地文件
  556. * @param stream
  557. * @param fileName
  558. * @return {Promise<void>}
  559. */
  560. async saveStreamFile(stream, fileName) {
  561. // 读取字节流
  562. const parts = await streamToArray(stream);
  563. // 转化为buffer
  564. const buffer = Buffer.concat(parts);
  565. // 写入文件
  566. await this.saveBufferFile(buffer, fileName);
  567. },
  568. async copyFileSync(source, target) {
  569. const pathName = path.dirname(target);
  570. if (!fs.existsSync(pathName)) {
  571. await this.recursiveMkdirSync(pathName);
  572. }
  573. await fs.copyFileSync(source, target);
  574. },
  575. /**
  576. * 检查code是否是指标模板数据
  577. * @param {String} code
  578. * @return {boolean}
  579. */
  580. validBillsCode(code) {
  581. const reg1 = /(^[0-9]+)([a-z0-9\-]*)/i;
  582. const reg2 = /([a-z0-9]+$)/i;
  583. return reg1.test(code) && reg2.test(code);
  584. },
  585. getNumberFormatter(decimal) {
  586. if (decimal <= 0) {
  587. return '0';
  588. }
  589. let pre = '0.';
  590. for (let i = 0; i < decimal; i++) {
  591. pre += '#';
  592. }
  593. return pre;
  594. },
  595. /**
  596. * 根据单位查找对应的清单精度
  597. * @param {tenderInfo.precision} list - 清单精度列表
  598. * @param {String} unit - 单位
  599. * @return {number}
  600. */
  601. findPrecision(list, unit) {
  602. if (unit) {
  603. for (const p in list) {
  604. if (list[p].unit && list[p].unit === unit) {
  605. return list[p];
  606. }
  607. }
  608. }
  609. return list.other;
  610. },
  611. /**
  612. * 检查数据中的精度
  613. * @param {Object} Obj - 检查的数据
  614. * @param {Array} fields - 检查的属性
  615. * @param {Number} precision - 精度
  616. * @class
  617. */
  618. checkFieldPrecision(Obj, fields, precision = 2) {
  619. if (Obj) {
  620. for (const field of fields) {
  621. if (Obj[field]) {
  622. Obj[field] = this.round(Obj[field], precision);
  623. }
  624. }
  625. }
  626. },
  627. checkDgnQtyPrecision(data, precision = 3) {
  628. const datas = data instanceof Array ? data : [data];
  629. for (const d of datas) {
  630. for (const prop in d) {
  631. if (prop.indexOf('dgn_qty') >= 0) d[prop] = this.round(d[prop], precision);
  632. }
  633. }
  634. },
  635. /**
  636. * 过滤无效数据
  637. *
  638. * @param obj
  639. * @param fields - 有效数据的数组
  640. */
  641. filterValidFields(data, fields) {
  642. if (data) {
  643. const result = {};
  644. for (const prop in data) {
  645. if (fields.indexOf(prop) !== -1) {
  646. result[prop] = data[prop];
  647. }
  648. }
  649. return result;
  650. }
  651. return data;
  652. },
  653. // 加减乘除方法,为方便调用,兼容num为空的情况
  654. // 加减法使用base_calc,乘除法使用Decimal(原因详见demo/calc_test)
  655. /**
  656. * 加法 num1 + num2
  657. * @param num1
  658. * @param num2
  659. * @return {number}
  660. */
  661. add(num1, num2) {
  662. return bc.add(num1 ? num1 : 0, num2 ? num2 : 0);
  663. },
  664. /**
  665. * 减法 num1 - num2
  666. * @param num1
  667. * @param num2
  668. * @return {number}
  669. */
  670. sub(num1, num2) {
  671. return bc.sub(num1 ? num1 : 0, num2 ? num2 : 0);
  672. },
  673. /**
  674. * 乘法 num1 * num2
  675. * @param num1
  676. * @param num2
  677. * @return {*}
  678. */
  679. mul(num1, num2, digit = 6) {
  680. if (num1 === '' || num1 === null || num2 === '' || num2 === null) {
  681. return 0;
  682. }
  683. return Decimal.mul(num1 ? num1 : 0, num2 ? num2 : 0).toDecimalPlaces(digit).toNumber();
  684. },
  685. /**
  686. * 除法 num1 / num2
  687. * @param num1 - 被除数
  688. * @param num2 - 除数
  689. * @return {*}
  690. */
  691. div(num1, num2, digit = 6) {
  692. if (num2 && !this.checkZero(num2)) {
  693. return Decimal.div(num1 ? num1 : 0, num2).toDecimalPlaces(digit).toNumber();
  694. }
  695. return null;
  696. },
  697. /**
  698. * 四舍五入(统一,方便以后万一需要置换)
  699. * @param {Number} value - 舍入的数字
  700. * @param {Number} decimal - 要保留的小数位数
  701. * @return {*}
  702. */
  703. round(value, decimal) {
  704. return value ? new Decimal(value.toString()).toDecimalPlaces(decimal).toNumber() : 0;
  705. },
  706. /**
  707. * 汇总
  708. * @param array
  709. * @return {number}
  710. */
  711. sum(array) {
  712. let result = 0;
  713. for (const a of array) {
  714. result = this.add(result, a);
  715. }
  716. return result;
  717. },
  718. /**
  719. * 使用正则替换字符
  720. * @param str
  721. * @param reg
  722. * @param subStr
  723. * @return {*}
  724. */
  725. replaceStr(str, reg, subStr) {
  726. return str ? str.replace(reg, subStr) : str;
  727. },
  728. /**
  729. * 替换字符串中的 换行符回车符
  730. * @param str
  731. * @return {*}
  732. */
  733. replaceReturn(str) {
  734. // return str
  735. // ? (typeof str === 'string') ? str.replace(/[\r\n]/g, '') : str + ''
  736. // : str;
  737. return (str && typeof str === 'string')
  738. ? str.replace(/[\r\n]/g, '')
  739. : !_.isNil(str) ? str + '' : str;
  740. },
  741. /**
  742. * 替换字符串中的 换行符回车符为换行符<br>
  743. * @param str
  744. * @return {*}
  745. */
  746. replaceRntoBr(str) {
  747. // return str
  748. // ? (typeof str === 'string') ? str.replace(/[\r\n]/g, '') : str + ''
  749. // : str;
  750. return (str && typeof str === 'string')
  751. ? str.replace(/[\r\n]/g, '<br>')
  752. : !_.isNil(str) ? str + '' : str;
  753. },
  754. /**
  755. * 获取 字符串 数组的 mysql 筛选条件
  756. *
  757. * @param arr
  758. * @return {*}
  759. */
  760. getInArrStrSqlFilter(arr) {
  761. let result = '';
  762. for (const a of arr) {
  763. if (result !== '') {
  764. result = result + ',';
  765. }
  766. result = result + this.ctx.app.mysql.escape(a);
  767. }
  768. return result;
  769. },
  770. /**
  771. * 合并 相关数据
  772. * @param {Array} main - 主数据
  773. * @param {Array[]}rela - 相关数据 {data, fields, prefix, relaId}
  774. */
  775. assignRelaData(main, rela) {
  776. const index = {},
  777. indexPre = 'id_';
  778. const loadFields = function(datas, fields, prefix, relaId) {
  779. for (const d of datas) {
  780. const key = indexPre + d[relaId];
  781. const m = index[key];
  782. if (m) {
  783. for (const f of fields) {
  784. if (d[f] !== undefined) {
  785. m[prefix + f] = d[f];
  786. }
  787. }
  788. }
  789. }
  790. };
  791. for (const m of main) {
  792. index[indexPre + m.id] = m;
  793. for (const r of rela) {
  794. if (r.defaultData) _.assignIn(m, r.defaultData);
  795. }
  796. }
  797. for (const r of rela) {
  798. loadFields(r.data, r.fields, r.prefix, r.relaId);
  799. }
  800. },
  801. /**
  802. * 合并(并汇总) 相关数据
  803. * @param {Array} main - 主数据
  804. * @param {Array[]}rela - 相关数据 {data, fields, relaField}
  805. *
  806. * { data, fields}
  807. */
  808. assignSumRelaData(main, keyField, rela) {
  809. const index = {},
  810. indexPre = 'id_';
  811. const addFun = this.add;
  812. const loadFields = function(datas, fields, relaId) {
  813. for (const d of datas) {
  814. const key = indexPre + d[relaId];
  815. const m = index[key];
  816. if (!m) continue;
  817. for (const f of fields) {
  818. if (d[f.source]) m[f.target] = addFun(m[f.target], d[f.source]);
  819. }
  820. }
  821. };
  822. for (const m of main) {
  823. index[indexPre + m[keyField]] = m;
  824. }
  825. for (const r of rela) {
  826. loadFields(r.data, r.fields, r.relaField);
  827. }
  828. },
  829. whereSql(where, as) {
  830. if (!where) {
  831. return '';
  832. }
  833. const wheres = [];
  834. const values = [];
  835. for (const key in where) {
  836. const value = where[key];
  837. if (Array.isArray(value)) {
  838. wheres.push('?? IN (?)');
  839. } else {
  840. wheres.push('?? = ?');
  841. }
  842. values.push((as && as !== '') ? as + '.' + key : key);
  843. values.push(value);
  844. }
  845. if (wheres.length > 0) {
  846. return this.ctx.app.mysql.format(' WHERE ' + wheres.join(' AND '), values);
  847. }
  848. return '';
  849. },
  850. formatMoney(s = 0, dot = ',', decimal = 2) {
  851. if (!s) {
  852. s = 0;
  853. return s.toFixed(decimal);
  854. }
  855. s = parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(decimal) + '';
  856. if (!decimal) {
  857. s += '.';
  858. }
  859. const l = s.split('.')[0].split('').reverse(),
  860. r = s.split('.')[1];
  861. let t = '';
  862. for (let i = 0; i < l.length; i++) {
  863. t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? dot : '');
  864. }
  865. const num = t.split('').reverse().join('') + (decimal === 0 ? '' : '.' + r);
  866. return num.replace('-,', '-');
  867. },
  868. transFormToChinese(num) {
  869. const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  870. const unit = ['', '十', '百', '千', '万'];
  871. num = parseInt(num);
  872. const getWan = temp => {
  873. const strArr = temp.toString().split('').reverse();
  874. let newNum = '';
  875. for (let i = 0; i < strArr.length; i++) {
  876. 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;
  877. }
  878. return strArr.length === 2 && newNum.indexOf('一十') !== -1 ? newNum.replace('一十', '十') : newNum;
  879. };
  880. const overWan = Math.floor(num / 10000);
  881. let noWan = num % 10000;
  882. if (noWan.toString().length < 4) noWan = '0' + noWan;
  883. return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num);
  884. },
  885. formatNum(num, pattern) {
  886. const strarr = num ? num.toString().split('.') : ['0'];
  887. const fmtarr = pattern ? pattern.split('.') : [''];
  888. let retstr = '';
  889. // 整数部分
  890. let str = strarr[0];
  891. let fmt = fmtarr[0];
  892. let i = str.length - 1;
  893. let comma = false;
  894. for (var f = fmt.length - 1; f >= 0; f--) {
  895. switch (fmt.substr(f, 1)) {
  896. case '#':
  897. if (i >= 0) retstr = str.substr(i--, 1) + retstr;
  898. break;
  899. case '0':
  900. if (i >= 0) retstr = str.substr(i--, 1) + retstr;
  901. else retstr = '0' + retstr;
  902. break;
  903. case ',':
  904. comma = true;
  905. retstr = ',' + retstr;
  906. break;
  907. }
  908. }
  909. if (i >= 0) {
  910. if (comma) {
  911. const l = str.length;
  912. for (;i >= 0; i--) {
  913. retstr = str.substr(i, 1) + retstr;
  914. if (i > 0 && ((l - i) % 3) == 0) retstr = ',' + retstr;
  915. }
  916. } else retstr = str.substr(0, i + 1) + retstr;
  917. }
  918. retstr = retstr + '.';
  919. // 处理小数部分
  920. str = strarr.length > 1 ? strarr[1] : '';
  921. fmt = fmtarr.length > 1 ? fmtarr[1] : '';
  922. i = 0;
  923. for (var f = 0; f < fmt.length; f++) {
  924. switch (fmt.substr(f, 1)) {
  925. case '#':
  926. if (i < str.length) retstr += str.substr(i++, 1);
  927. break;
  928. case '0':
  929. if (i < str.length) retstr += str.substr(i++, 1);
  930. else retstr += '0';
  931. break;
  932. }
  933. }
  934. return retstr.replace(/^,+/, '').replace(/\.$/, '');
  935. },
  936. dateTran(time, style = 'YYYY年MM月DD日 HH:mm') {
  937. return moment(time).format(style);
  938. },
  939. // 审批日期格式:2020-5-7 9:40:30
  940. formatFullDate(time) {
  941. return moment(time).format('YYYY-MM-DD HH:mm:ss');
  942. },
  943. calcDayNum(startTime, endTime = '') {
  944. const dateStart = new Date(startTime);
  945. const dateEnd = endTime ? new Date(endTime) : new Date();
  946. return parseInt((dateEnd.getTime() - dateStart.getTime()) / (1000 * 60 * 60 * 24));
  947. },
  948. // 预付款详情页时间线所需格式
  949. formatDate(date) {
  950. if (!date) return '';
  951. const year = date.getFullYear();
  952. let mon = date.getMonth() + 1;
  953. let day = date.getDate();
  954. let hour = date.getHours();
  955. let minute = date.getMinutes();
  956. let scond = date.getSeconds();
  957. if (mon < 10) {
  958. mon = '0' + mon.toString();
  959. }
  960. if (day < 10) {
  961. day = '0' + day.toString();
  962. }
  963. if (hour < 10) {
  964. hour = '0' + hour.toString();
  965. }
  966. if (minute < 10) {
  967. minute = '0' + minute.toString();
  968. }
  969. if (scond < 10) {
  970. scond = '0' + scond.toString();
  971. }
  972. return `${year}<span>${mon}-${day}</span><span>${hour}:${minute}:${scond}</span>`;
  973. },
  974. timeAdd(duration) {
  975. const d = parseInt(duration);
  976. let time = 0;
  977. if (d === 1) {
  978. time = 60 * 15 * 1000;
  979. } else if (d === 2) {
  980. time = 60 * 30 * 1000;
  981. } else if (d === 3) {
  982. time = 3600 * 1000;
  983. } else if (d === 4) {
  984. time = 3600 * 2 * 1000;
  985. }
  986. return time;
  987. },
  988. async sendUserSms(userId, type, judge, msg) {
  989. const mobiles = [];
  990. if (!userId || (userId instanceof Array && userId.length === 0)) return;
  991. const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  992. for (const su of smsUser) {
  993. if (!su.auth_mobile || su.auth_mobile === '') continue;
  994. if (!su.sms_type || su.sms_type === '') continue;
  995. const smsType = JSON.parse(su.sms_type);
  996. if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
  997. mobiles.push(su.auth_mobile);
  998. }
  999. }
  1000. if (mobiles.length > 0) {
  1001. const sms = new SMS(this.ctx);
  1002. const tenderName = await sms.contentChange(this.ctx.tender.data.name);
  1003. const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
  1004. const ptmsg = projectName !== '' ? '项目「' + projectName + '」标段「' + tenderName + '」' : tenderName;
  1005. const content = '【纵横计量支付】' + ptmsg + msg;
  1006. sms.send(mobiles, content);
  1007. }
  1008. },
  1009. async sendAliSms(userId, type, judge, code, data = {}) {
  1010. // const mobiles = [];
  1011. // if (!userId || (userId instanceof Array && userId.length === 0)) return;
  1012. // const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  1013. // for (const su of smsUser) {
  1014. // if (!su.auth_mobile || su.auth_mobile === '') continue;
  1015. // if (!su.sms_type || su.sms_type === '') continue;
  1016. //
  1017. // const smsType = JSON.parse(su.sms_type);
  1018. // if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
  1019. // mobiles.push(su.auth_mobile);
  1020. // }
  1021. // }
  1022. //
  1023. // if (mobiles.length > 0) {
  1024. // const sms = new SMS(this.ctx);
  1025. // const tenderName = await sms.contentChange(this.ctx.tender.data.name);
  1026. // const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
  1027. // const param = {
  1028. // project: projectName,
  1029. // number: tenderName,
  1030. // };
  1031. // const postParam = Object.assign(param, data);
  1032. // sms.aliSend(mobiles, postParam, code);
  1033. // }
  1034. },
  1035. async sendWechat(userId, type, judge, template, data = {}) {
  1036. const wechats = [];
  1037. if (!userId || (userId instanceof Array && userId.length === 0)) return;
  1038. const wxUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  1039. for (const user of wxUser) {
  1040. if (!user.wx_openid || user.wx_openid === '') continue;
  1041. if (!user.wx_type || user.wx_type === '') continue;
  1042. const wxType = JSON.parse(user.wx_type);
  1043. if (wxType[type] && wxType[type].indexOf(judge) !== -1) {
  1044. wechats.push(user.wx_openid);
  1045. }
  1046. }
  1047. if (wechats.length > 0) {
  1048. const wx = new WX(this.ctx);
  1049. const tenderName = await wx.contentChange(this.ctx.tender.data.name);
  1050. const projectName = await wx.contentChange(this.ctx.tender.info.deal_info.buildName);
  1051. const param = {
  1052. projectName,
  1053. tenderName,
  1054. };
  1055. const postParam = Object.assign(param, data);
  1056. wx.Send(wechats, template, postParam);
  1057. }
  1058. },
  1059. /**
  1060. *
  1061. * @param setting
  1062. * @param data
  1063. * @return {{} & any & {"!ref": string} & {"!cols"}}
  1064. */
  1065. simpleXlsxSheetData(setting, data) {
  1066. const headerStyle = {
  1067. font: { sz: 10, bold: true },
  1068. alignment: { horizontal: 'center' },
  1069. };
  1070. const sHeader = setting.header
  1071. .map((v, i) => Object.assign({}, { v, s: headerStyle, position: String.fromCharCode(65 + i) + 1 }))
  1072. .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v, s: next.s } }), {});
  1073. const sData = data
  1074. .map((v, i) => v.map((k, j) => Object.assign({}, {
  1075. v: k ? k : '',
  1076. s: { font: { sz: 10 }, alignment: { horizontal: setting.hAlign[j] } },
  1077. position: String.fromCharCode(65 + j) + (i + 2) })))
  1078. .reduce((prev, next) => prev.concat(next))
  1079. .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v, s: next.s } }), {});
  1080. const output = Object.assign({}, sHeader, sData);
  1081. const outputPos = Object.keys(output);
  1082. const result = Object.assign({}, output,
  1083. { '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] },
  1084. { '!cols': setting.width.map(w => Object.assign({}, { wpx: w })) });
  1085. return result;
  1086. },
  1087. log(error) {
  1088. if (error.stack) {
  1089. this.ctx.logger.error(error);
  1090. } else {
  1091. this.ctx.getLogger('fail').info(JSON.stringify({
  1092. error,
  1093. project: this.ctx.session.sessionProject,
  1094. user: this.ctx.session.sessionUser,
  1095. body: this.ctx.session.body,
  1096. }));
  1097. }
  1098. },
  1099. /**
  1100. * 添加debug信息
  1101. * 在debug模式下,debug信息将传输到浏览器并打印
  1102. *
  1103. * @param {String}key
  1104. * @param {*}data
  1105. */
  1106. addDebugInfo(key, ...data) {
  1107. if (!this.ctx.debugInfo) {
  1108. this.ctx.debugInfo = { key: {}, other: [] };
  1109. }
  1110. if (key) {
  1111. this.ctx.debugInfo.key[key] = data;
  1112. } else {
  1113. this.ctx.debugInfo.other.push(data);
  1114. }
  1115. },
  1116. /**
  1117. * 深拷贝
  1118. * @param obj
  1119. * @return {*}
  1120. */
  1121. clone(obj) {
  1122. if (obj === null) return null;
  1123. const o = obj instanceof Array ? [] : {};
  1124. for (const i in obj) {
  1125. o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === 'object' ? this.clone(obj[i]) : obj[i]);
  1126. }
  1127. return o;
  1128. },
  1129. /**
  1130. * 短链接生成(暂停生成)
  1131. * @param url
  1132. * @return {*}
  1133. */
  1134. async urlToShort(url) {
  1135. // const apiUrl = 'http://scn.ink/api/shorturl';
  1136. // const data = {
  1137. // url: encodeURI(url),
  1138. // };
  1139. // const result = await this.sendRequest(apiUrl, data, 'get');
  1140. // return result && result.code === 200 && result.url ? result.url : url;
  1141. return url;
  1142. },
  1143. /**
  1144. * 判断是否wap访问
  1145. * @param request
  1146. * @return {*}
  1147. */
  1148. isWap(request) {
  1149. return request.url.indexOf('/wap/') !== -1;
  1150. },
  1151. check18MainCode(code) {
  1152. return /^([0-9]([0-9][0-9])*)?(GD[0-9]{3}([0-9][0-9])*)?$/.test(code);
  1153. },
  1154. check18SubCode(code) {
  1155. return /^(GD)?G?[A-Z]{2}[A-Z]{0,2}([0-9]{2})+$/.test(code);
  1156. },
  1157. /**
  1158. * 判断是否是移动端访问
  1159. * @param request
  1160. * @return {*}
  1161. */
  1162. isMobile(agent) {
  1163. return agent.match(/(iphone|ipod|android)/i);
  1164. },
  1165. /**
  1166. * 删除文件
  1167. * @param {Array} fileList 文件数组(格式为数据库查询出来的结果集,且文件字段必须为filepath)
  1168. * @return {void}
  1169. */
  1170. async delFiles(fileList) {
  1171. if (fileList.length) {
  1172. for (const att of fileList) {
  1173. if (att.filepath && fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
  1174. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  1175. } else if (att.filepath) {
  1176. await this.ctx.app.fujianOss.delete(this.ctx.app.config.fujianOssFolder + att.filepath);
  1177. }
  1178. }
  1179. }
  1180. },
  1181. /**
  1182. * 匹配图片、pdf(用于预览)
  1183. * @param {String} ext 后缀名
  1184. * @return {Boolean} 匹配结果
  1185. */
  1186. canPreview(ext) {
  1187. const reg = /(.png)|(.gif)|(.txt)|(.jpg)|(.jpeg)|(.pdf)/i;
  1188. return reg.test(ext);
  1189. },
  1190. /**
  1191. * 查找数组中某个字符的个数
  1192. * @param {Array} array 数组
  1193. * @param {string} val 字符串
  1194. * @return {Boolean} 匹配结果
  1195. */
  1196. arrayCount(array, val) {
  1197. const counts = (arr, value) => arr.reduce((a, v) => { return value.indexOf(v) !== -1 ? a + 1 : a + 0; }, 0);
  1198. return counts(array, val);
  1199. },
  1200. filterTimesOrderData(data, keyFields, timesField, orderField, times, order) {
  1201. const dataIndex = {};
  1202. for (const d of data) {
  1203. if (d[timesField] > times || (d[timesField] = times && d[orderField] > order)) continue;
  1204. let key = 'd';
  1205. for (const kf of keyFields) {
  1206. key = key + '.' + (d[kf] || '');
  1207. }
  1208. const di = dataIndex[key];
  1209. if (di) {
  1210. if ((di[timesField] * timesLen + di[orderField]) < (d[timesField] * timesLen + d[orderField])) dataIndex[key] = d;
  1211. } else {
  1212. dataIndex[key] = d;
  1213. }
  1214. }
  1215. const result = [];
  1216. for (const prop in dataIndex) {
  1217. result.push(dataIndex[prop]);
  1218. }
  1219. return result;
  1220. },
  1221. filterLastestData(data, keyFields, timesField = 'times', orderField = 'order') {
  1222. const dataIndex = {};
  1223. for (const d of data) {
  1224. let key = 'd';
  1225. for (const kf of keyFields) {
  1226. key = key + '.' + (d[kf] || '');
  1227. }
  1228. const di = dataIndex[key];
  1229. if (di) {
  1230. if ((di[timesField] * timesLen + di[orderField]) < (d[timesField] * timesLen + d[orderField])) dataIndex[key] = d;
  1231. } else {
  1232. dataIndex[key] = d;
  1233. }
  1234. }
  1235. const result = [];
  1236. for (const prop in dataIndex) {
  1237. result.push(dataIndex[prop]);
  1238. }
  1239. return result;
  1240. },
  1241. filterLastestData2(data, keyFields, timesField = 'times', orderField = 'order') {
  1242. const dataIndex = {};
  1243. for (const d of data) {
  1244. let key = 'd';
  1245. for (const kf of keyFields) {
  1246. key = key + '.' + (d[kf] || '');
  1247. }
  1248. if (!dataIndex[key]) dataIndex[key] = { index: 0, source: [] };
  1249. const di = dataIndex[key];
  1250. const curIndex = d[timesField] * timesLen + d[orderField];
  1251. if (curIndex === di.index) {
  1252. di.source.push(d);
  1253. } else if (curIndex > di.index) {
  1254. di.index = curIndex;
  1255. di.source = [d];
  1256. }
  1257. }
  1258. const result = [];
  1259. for (const prop in dataIndex) {
  1260. result.push(...dataIndex[prop].source);
  1261. }
  1262. return result;
  1263. },
  1264. calcExpr(expr) {
  1265. const validExpr = expr.replace('=', '').replace('%', '/100');
  1266. return parseFloat(math.eval(validExpr));
  1267. },
  1268. /**
  1269. * 创建登录日志
  1270. * @return {Boolean} 日志是否创建成功
  1271. * @param {Number} type - 登录类型
  1272. * @param {Number} status - 是否显示记录
  1273. */
  1274. async getUserIPMsg() {
  1275. const { ctx } = this;
  1276. const ip = ctx.request.ip ? ctx.request.ip : '';
  1277. const ipInfo = await this.getIpInfoFromApi(ip);
  1278. const parser = new UAParser(ctx.header['user-agent']);
  1279. const osInfo = parser.getOS();
  1280. const cpuInfo = parser.getCPU();
  1281. const browserInfo = parser.getBrowser();
  1282. const ipMsg = {
  1283. os: `${osInfo.name} ${osInfo.version} ${cpuInfo.architecture}`,
  1284. browser: `${browserInfo.name} ${browserInfo.version}`,
  1285. ip,
  1286. address: ipInfo,
  1287. };
  1288. return ipMsg;
  1289. },
  1290. /**
  1291. * 根据ip请求获取详细地址
  1292. * @param {String} a_ip - ip地址
  1293. * @return {String} 详细地址
  1294. */
  1295. async getIpInfoFromApi(a_ip = '') {
  1296. if (!a_ip) return '';
  1297. if (a_ip === '127.0.0.1' || a_ip === '::1' || a_ip.indexOf('192.168') !== -1) return '服务器本机访问';
  1298. const { ip = '', region = '', city = '', isp = '' } = await this.sendIpRequest(a_ip);
  1299. let address = '';
  1300. region && (address += region + '省');
  1301. city && (address += city + '市 ');
  1302. isp && (address += isp + ' ');
  1303. ip && (address += `(${ip})`);
  1304. return address;
  1305. },
  1306. /**
  1307. * 发送请求获取详细地址
  1308. * @param {String} ip - ip地址
  1309. * @return {Object} the result of request
  1310. * @private
  1311. */
  1312. async sendIpRequest(ip) {
  1313. return new Promise(resolve => {
  1314. this.ctx.curl(`https://api01.aliyun.venuscn.com/ip?ip=${ip}`, {
  1315. dateType: 'json',
  1316. encoding: 'utf8',
  1317. timeout: 2000,
  1318. headers: {
  1319. Authorization: 'APPCODE 85c64bffe70445c4af9df7ae31c7bfcc',
  1320. },
  1321. }).then(({ status, data }) => {
  1322. if (status === 200) {
  1323. const result = JSON.parse(data.toString()).data;
  1324. if (!result.ip) {
  1325. resolve({});
  1326. } else {
  1327. resolve(result);
  1328. }
  1329. } else {
  1330. resolve({});
  1331. }
  1332. }).catch(() => {
  1333. resolve({});
  1334. });
  1335. });
  1336. },
  1337. refreshSpreadShow(sjsRela, sjsSetting) {
  1338. function removeFieldCols(setting, cols) {
  1339. _.remove(setting.cols, function(c) {
  1340. return cols.indexOf(c.field) > -1;
  1341. });
  1342. }
  1343. const sjsSettings = sjsSetting instanceof Array ? sjsSetting : [sjsSetting];
  1344. for (const field of sjsRela) {
  1345. if (field.show) {
  1346. for (const ss of sjsSettings) {
  1347. const lCol = ss.cols.find(x => {
  1348. return x.field === field.field;
  1349. });
  1350. if (lCol) lCol.title = field.alias || field.name;
  1351. }
  1352. } else {
  1353. for (const ss of sjsSettings) {
  1354. removeFieldCols(ss, [field.field]);
  1355. }
  1356. }
  1357. }
  1358. },
  1359. /**
  1360. * 发送请求获取详细地址
  1361. * @param {String} type - 通知类型
  1362. * @param {String} datas - 请求发送数据
  1363. * @return {Object} the result of request
  1364. * @private
  1365. */
  1366. async syncNoticeSend(type, datas) {
  1367. const key = this.ctx.session.sessionProject.code;
  1368. const time = new Date().getTime();
  1369. const projectData = await this.ctx.service.project.getDataById(this.ctx.session.sessionProject.id);
  1370. const sign = crypto.createHash('md5').update(key + projectData.secret + time.toString()).digest('hex').toString();
  1371. const res = await this.ctx.curl(this.ctx.app.config.syncUrl + syncApiConst.api_url.notice, {
  1372. method: 'POST',
  1373. contentType: 'json',
  1374. data: {
  1375. projectCode: key,
  1376. key,
  1377. time,
  1378. sign,
  1379. customType: type,
  1380. base_data: datas,
  1381. },
  1382. dateType: 'json',
  1383. timeout: [30000, 60000],
  1384. timing: true,
  1385. });
  1386. },
  1387. async ossFileGet(path) {
  1388. // 判断开头是否带app,否则加上
  1389. if (!_.includes(path, 'app/')) {
  1390. path = 'app/' + path;
  1391. }
  1392. const result = await this.ctx.app.fujianOss.get(this.ctx.app.config.fujianOssFolder + path);
  1393. if (result.res.status !== 200) {
  1394. throw '该文件不存在';
  1395. }
  1396. return result.content;
  1397. },
  1398. getStartEndMonth(month) {
  1399. const startMonth = moment(month).startOf('month').format('YYYY-MM-DD HH:mm:ss');
  1400. const endMonth = moment(month).endOf('month').format('YYYY-MM-DD HH:mm:ss');
  1401. return [startMonth, endMonth];
  1402. },
  1403. /**
  1404. * 创建json web token
  1405. * @param {Object} data - 签名数据
  1406. * @return {String} token
  1407. */
  1408. createJWT(data) {
  1409. return jwt.sign({ data }, sign.managementApiSecretKey, { expiresIn: '15s' });
  1410. },
  1411. async loadLedgerDataFromOss(url) {
  1412. const File = await this.ctx.hisOss.get(this.ctx.hisOssPath + url);
  1413. if (File.res.status !== 200) return '获取修订台账有误';
  1414. const result = JSON.parse(File.content);
  1415. return result;
  1416. },
  1417. hpackArr(data) {
  1418. const keyIndex = {}, key = [];
  1419. const result = [];
  1420. for (const d of data) {
  1421. const r = [];
  1422. for (const prop in d) {
  1423. if (keyIndex[prop] === undefined) {
  1424. key.push(prop);
  1425. keyIndex[prop] = key.indexOf(prop);
  1426. }
  1427. r[keyIndex[prop]] = d[prop];
  1428. }
  1429. result.push(r);
  1430. }
  1431. if (result.length > 0) result.unshift(key);
  1432. return result;
  1433. }
  1434. };