helper.js 50 KB

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