helper.js 57 KB

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