helper.js 53 KB

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