helper.js 47 KB

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