helper.js 46 KB

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