helper.js 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755
  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. _getOptionsSql(options) {
  788. const optionSql = [];
  789. for (const key in options) {
  790. if (options.hasOwnProperty(key)) {
  791. optionSql.push(key + ' = ' + this.ctx.app.mysql.escape(options[key]));
  792. }
  793. }
  794. return optionSql.join(' AND ');
  795. },
  796. /**
  797. * 合并 相关数据
  798. * @param {Array} main - 主数据
  799. * @param {Array[]}rela - 相关数据 {data, fields, prefix, relaId}
  800. */
  801. assignRelaData(main, rela, mainKey = 'id', clear = false) {
  802. const index = {},
  803. indexPre = 'id_';
  804. const loadFields = function(datas, fields, prefix, relaId) {
  805. for (const d of datas) {
  806. const key = indexPre + d[relaId];
  807. const m = index[key];
  808. if (m) {
  809. for (const f of fields) {
  810. if (d[f] !== undefined) {
  811. m[prefix + f] = d[f];
  812. }
  813. }
  814. }
  815. }
  816. };
  817. for (const m of main) {
  818. index[indexPre + m[mainKey]] = m;
  819. for (const r of rela) {
  820. if (r.defaultData) _.assignIn(m, r.defaultData);
  821. }
  822. if (clear) {
  823. rela.forEach(r => {
  824. r.fields.forEach(f => {
  825. delete m[r.prefix + f];
  826. });
  827. })
  828. }
  829. }
  830. for (const r of rela) {
  831. loadFields(r.data, r.fields, r.prefix, r.relaId);
  832. }
  833. },
  834. /**
  835. * 合并(并汇总) 相关数据
  836. * @param {Array} main - 主数据
  837. * @param {Array[]}rela - 相关数据 {data, fields, relaField}
  838. *
  839. * { data, fields}
  840. */
  841. assignSumRelaData(main, keyField, rela) {
  842. const index = {},
  843. indexPre = 'id_';
  844. const addFun = this.add;
  845. const loadFields = function(datas, fields, relaId) {
  846. for (const d of datas) {
  847. const key = indexPre + d[relaId];
  848. const m = index[key];
  849. if (!m) continue;
  850. for (const f of fields) {
  851. if (d[f.source]) m[f.target] = addFun(m[f.target], d[f.source]);
  852. }
  853. }
  854. };
  855. for (const m of main) {
  856. index[indexPre + m[keyField]] = m;
  857. }
  858. for (const r of rela) {
  859. loadFields(r.data, r.fields, r.relaField);
  860. }
  861. },
  862. whereSql(where, as) {
  863. if (!where) {
  864. return '';
  865. }
  866. const wheres = [];
  867. const values = [];
  868. for (const key in where) {
  869. const value = where[key];
  870. if (Array.isArray(value)) {
  871. wheres.push('?? IN (?)');
  872. } else {
  873. wheres.push('?? = ?');
  874. }
  875. values.push((as && as !== '') ? as + '.' + key : key);
  876. values.push(value);
  877. }
  878. if (wheres.length > 0) {
  879. return this.ctx.app.mysql.format(' WHERE ' + wheres.join(' AND '), values);
  880. }
  881. return '';
  882. },
  883. formatMoney(s = 0, dot = ',', decimal = 2) {
  884. if (!s) {
  885. s = 0;
  886. return s.toFixed(decimal);
  887. }
  888. s = parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(decimal) + '';
  889. if (!decimal) {
  890. s += '.';
  891. }
  892. const l = s.split('.')[0].split('').reverse(),
  893. r = s.split('.')[1];
  894. let t = '';
  895. for (let i = 0; i < l.length; i++) {
  896. t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? dot : '');
  897. }
  898. const num = t.split('').reverse().join('') + (decimal === 0 ? '' : '.' + r);
  899. return num.replace('-,', '-');
  900. },
  901. transFormToChinese(num) {
  902. const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  903. const unit = ['', '十', '百', '千', '万'];
  904. num = parseInt(num);
  905. const getWan = temp => {
  906. const strArr = temp.toString().split('').reverse();
  907. let newNum = '';
  908. for (let i = 0; i < strArr.length; i++) {
  909. 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;
  910. }
  911. return strArr.length === 2 && newNum.indexOf('一十') !== -1 ? newNum.replace('一十', '十') : newNum;
  912. };
  913. const overWan = Math.floor(num / 10000);
  914. let noWan = num % 10000;
  915. if (noWan.toString().length < 4) noWan = '0' + noWan;
  916. return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num);
  917. },
  918. formatNum(num, pattern) {
  919. const minus = num > 0 ? '' : '-'
  920. const strarr = num ? Math.abs(num).toString().split('.') : ['0'];
  921. const fmtarr = pattern ? pattern.split('.') : [''];
  922. let retstr = '';
  923. // 整数部分
  924. let str = strarr[0];
  925. let fmt = fmtarr[0];
  926. let i = str.length - 1;
  927. let comma = false;
  928. for (var f = fmt.length - 1; f >= 0; f--) {
  929. switch (fmt.substr(f, 1)) {
  930. case '#':
  931. if (i >= 0) retstr = str.substr(i--, 1) + retstr;
  932. break;
  933. case '0':
  934. if (i >= 0) retstr = str.substr(i--, 1) + retstr;
  935. else retstr = '0' + retstr;
  936. break;
  937. case ',':
  938. comma = true;
  939. retstr = ',' + retstr;
  940. break;
  941. }
  942. }
  943. if (i >= 0) {
  944. if (comma) {
  945. const l = str.length;
  946. for (;i >= 0; i--) {
  947. retstr = str.substr(i, 1) + retstr;
  948. if (i > 0 && ((l - i) % 3) == 0) retstr = ',' + retstr;
  949. }
  950. } else retstr = str.substr(0, i + 1) + retstr;
  951. }
  952. retstr = retstr + '.';
  953. // 处理小数部分
  954. str = strarr.length > 1 ? strarr[1] : '';
  955. fmt = fmtarr.length > 1 ? fmtarr[1] : '';
  956. i = 0;
  957. for (var f = 0; f < fmt.length; f++) {
  958. switch (fmt.substr(f, 1)) {
  959. case '#':
  960. if (i < str.length) retstr += str.substr(i++, 1);
  961. break;
  962. case '0':
  963. if (i < str.length) retstr += str.substr(i++, 1);
  964. else retstr += '0';
  965. break;
  966. }
  967. }
  968. return minus + retstr.replace(/^,+/, '').replace(/\.$/, '');
  969. },
  970. dateTran(time, style = 'YYYY年MM月DD日 HH:mm') {
  971. return moment(time).format(style);
  972. },
  973. dateTranChinese(day) {
  974. const dateParts = day.split('-');
  975. return dateParts[0] + '年' + dateParts[1] + '月' + dateParts[2] + '日';
  976. },
  977. // 审批日期格式:2020-5-7 9:40:30
  978. formatFullDate(time) {
  979. return moment(time).format('YYYY-MM-DD HH:mm:ss');
  980. },
  981. calcDayNum(startTime, endTime = '') {
  982. const dateStart = new Date(startTime);
  983. const dateEnd = endTime ? new Date(endTime) : new Date();
  984. return parseInt((dateEnd.getTime() - dateStart.getTime()) / (1000 * 60 * 60 * 24));
  985. },
  986. // 预付款详情页时间线所需格式
  987. formatDate(date) {
  988. if (!date) return '';
  989. const year = date.getFullYear();
  990. let mon = date.getMonth() + 1;
  991. let day = date.getDate();
  992. let hour = date.getHours();
  993. let minute = date.getMinutes();
  994. let scond = date.getSeconds();
  995. if (mon < 10) {
  996. mon = '0' + mon.toString();
  997. }
  998. if (day < 10) {
  999. day = '0' + day.toString();
  1000. }
  1001. if (hour < 10) {
  1002. hour = '0' + hour.toString();
  1003. }
  1004. if (minute < 10) {
  1005. minute = '0' + minute.toString();
  1006. }
  1007. if (scond < 10) {
  1008. scond = '0' + scond.toString();
  1009. }
  1010. return `${year}<span>${mon}-${day}</span><span>${hour}:${minute}:${scond}</span>`;
  1011. },
  1012. timeAdd(duration) {
  1013. const d = parseInt(duration);
  1014. let time = 0;
  1015. if (d === 1) {
  1016. time = 60 * 15 * 1000;
  1017. } else if (d === 2) {
  1018. time = 60 * 30 * 1000;
  1019. } else if (d === 3) {
  1020. time = 3600 * 1000;
  1021. } else if (d === 4) {
  1022. time = 3600 * 2 * 1000;
  1023. }
  1024. return time;
  1025. },
  1026. async sendUserSms(userId, type, judge, msg) {
  1027. const mobiles = [];
  1028. if (!userId || (userId instanceof Array && userId.length === 0)) return;
  1029. const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  1030. for (const su of smsUser) {
  1031. if (!su.auth_mobile || su.auth_mobile === '') continue;
  1032. if (!su.sms_type || su.sms_type === '') continue;
  1033. const smsType = JSON.parse(su.sms_type);
  1034. if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
  1035. mobiles.push(su.auth_mobile);
  1036. }
  1037. }
  1038. if (mobiles.length > 0) {
  1039. const sms = new SMS(this.ctx);
  1040. const tenderName = await sms.contentChange(this.ctx.tender.data.name);
  1041. const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
  1042. const ptmsg = projectName !== '' ? '项目「' + projectName + '」标段「' + tenderName + '」' : tenderName;
  1043. const content = '【纵横计量支付】' + ptmsg + msg;
  1044. sms.send(mobiles, content);
  1045. }
  1046. },
  1047. async sendAliSms(userId, type, judge, code, data = {}) {
  1048. // const mobiles = [];
  1049. // if (!userId || (userId instanceof Array && userId.length === 0)) return;
  1050. // const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  1051. // for (const su of smsUser) {
  1052. // if (!su.auth_mobile || su.auth_mobile === '') continue;
  1053. // if (!su.sms_type || su.sms_type === '') continue;
  1054. //
  1055. // const smsType = JSON.parse(su.sms_type);
  1056. // if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
  1057. // mobiles.push(su.auth_mobile);
  1058. // }
  1059. // }
  1060. //
  1061. // if (mobiles.length > 0) {
  1062. // const sms = new SMS(this.ctx);
  1063. // const tenderName = await sms.contentChange(this.ctx.tender.data.name);
  1064. // const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
  1065. // const param = {
  1066. // project: projectName,
  1067. // number: tenderName,
  1068. // };
  1069. // const postParam = Object.assign(param, data);
  1070. // sms.aliSend(mobiles, postParam, code);
  1071. // }
  1072. },
  1073. // 企业微信和公众号微信通知共用
  1074. async sendWechat(userId, type, judge, template, data = {}, tender = this.ctx.tender, ctx = this.ctx) {
  1075. const wechats = [];
  1076. const qywxs = {};
  1077. if (!userId || (userId instanceof Array && userId.length === 0)) return;
  1078. const wxUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  1079. for (const user of wxUser) {
  1080. if ((!user.wx_openid || user.wx_openid === '') && !user.qywx_userid) continue;
  1081. if (!user.wx_type || user.wx_type === '') continue;
  1082. const wxType = JSON.parse(user.wx_type);
  1083. if (wxType[type] && wxType[type].indexOf(judge) !== -1) {
  1084. if (user.wx_openid) wechats.push(user.wx_openid);
  1085. if (user.qywx_userid && user.qywx_corpid) {
  1086. _.has(qywxs, user.qywx_corpid) ? qywxs[user.qywx_corpid].push(user.qywx_userid) : qywxs[user.qywx_corpid] = [user.qywx_userid];
  1087. }
  1088. }
  1089. }
  1090. if (wechats.length > 0 || !_.isEmpty(qywxs)) {
  1091. const wx = new WX(this.ctx);
  1092. const tenderName = await wx.contentChange(tender.data.name);
  1093. const projectName = await wx.contentChange(tender.info.deal_info.buildName);
  1094. const param = {
  1095. projectName,
  1096. tenderName,
  1097. };
  1098. const postParam = Object.assign(param, data);
  1099. const originUrl = ctx.protocol + '://' + ctx.host;
  1100. if (wechats.length > 0) wx.Send(wechats, template, postParam, originUrl);
  1101. if (!_.isEmpty(qywxs)) wx.Send4Work(qywxs, template, postParam, originUrl);
  1102. }
  1103. },
  1104. /**
  1105. *
  1106. * @param setting
  1107. * @param data
  1108. * @return {{} & any & {"!ref": string} & {"!cols"}}
  1109. */
  1110. simpleXlsxSheetData(setting, data) {
  1111. const headerStyle = {
  1112. font: { sz: 10, bold: true },
  1113. alignment: { horizontal: 'center' },
  1114. };
  1115. const sHeader = setting.header
  1116. .map((v, i) => Object.assign({}, { v, s: headerStyle, position: String.fromCharCode(65 + i) + 1 }))
  1117. .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v, s: next.s } }), {});
  1118. const sData = data
  1119. .map((v, i) => v.map((k, j) => Object.assign({}, {
  1120. v: k ? k : '',
  1121. s: { font: { sz: 10 }, alignment: { horizontal: setting.hAlign[j] } },
  1122. position: String.fromCharCode(65 + j) + (i + 2) })))
  1123. .reduce((prev, next) => prev.concat(next))
  1124. .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v, s: next.s } }), {});
  1125. const output = Object.assign({}, sHeader, sData);
  1126. const outputPos = Object.keys(output);
  1127. const result = Object.assign({}, output,
  1128. { '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] },
  1129. { '!cols': setting.width.map(w => Object.assign({}, { wpx: w })) });
  1130. return result;
  1131. },
  1132. log(error) {
  1133. if (error.stack) {
  1134. this.ctx.logger.error(error);
  1135. } else {
  1136. this.ctx.getLogger('fail').info(JSON.stringify({
  1137. error,
  1138. project: this.ctx.session.sessionProject,
  1139. user: this.ctx.session.sessionUser,
  1140. body: this.ctx.session.body,
  1141. }));
  1142. }
  1143. },
  1144. /**
  1145. * 添加debug信息
  1146. * 在debug模式下,debug信息将传输到浏览器并打印
  1147. *
  1148. * @param {String}key
  1149. * @param {*}data
  1150. */
  1151. addDebugInfo(key, ...data) {
  1152. if (!this.ctx.debugInfo) {
  1153. this.ctx.debugInfo = { key: {}, other: [] };
  1154. }
  1155. if (key) {
  1156. this.ctx.debugInfo.key[key] = data;
  1157. } else {
  1158. this.ctx.debugInfo.other.push(data);
  1159. }
  1160. },
  1161. /**
  1162. * 深拷贝
  1163. * @param obj
  1164. * @return {*}
  1165. */
  1166. clone(obj) {
  1167. if (obj === null) return null;
  1168. const o = obj instanceof Array ? [] : {};
  1169. for (const i in obj) {
  1170. o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === 'object' ? this.clone(obj[i]) : obj[i]);
  1171. }
  1172. return o;
  1173. },
  1174. /**
  1175. * 短链接生成(暂停生成)
  1176. * @param url
  1177. * @return {*}
  1178. */
  1179. async urlToShort(url) {
  1180. // const apiUrl = 'http://scn.ink/api/shorturl';
  1181. // const data = {
  1182. // url: encodeURI(url),
  1183. // };
  1184. // const result = await this.sendRequest(apiUrl, data, 'get');
  1185. // return result && result.code === 200 && result.url ? result.url : url;
  1186. return url;
  1187. },
  1188. /**
  1189. * 判断是否wap访问
  1190. * @param request
  1191. * @return {*}
  1192. */
  1193. isWap(request) {
  1194. return request.url.indexOf('/wap/') !== -1;
  1195. },
  1196. check18MainCode(code) {
  1197. return /^([0-9]([0-9][0-9])*)?(GD[0-9]{3}([0-9][0-9])*)?$/.test(code);
  1198. },
  1199. check18SubCode(code) {
  1200. return /^(GD)?G?[A-Z]{2}[A-Z]{0,2}([0-9]{2})+$/.test(code);
  1201. },
  1202. /**
  1203. * 判断是否是移动端访问
  1204. * @param request
  1205. * @return {*}
  1206. */
  1207. isMobile(agent) {
  1208. const ua = new UAParser(agent);
  1209. const osInfo = ua.getOS();
  1210. return (agent ? agent.match(/(iphone|ipod|android)/i) : false) || osInfo.name === 'Android' || osInfo.name === 'iOS';
  1211. },
  1212. /**
  1213. * 删除文件
  1214. * @param {Array} fileList 文件数组(格式为数据库查询出来的结果集,且文件字段必须为filepath)
  1215. * @return {void}
  1216. */
  1217. async delFiles(fileList) {
  1218. if (fileList.length) {
  1219. for (const att of fileList) {
  1220. if (att.filepath && fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
  1221. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  1222. } else if (att.filepath) {
  1223. await this.ctx.app.fujianOss.delete(this.ctx.app.config.fujianOssFolder + att.filepath);
  1224. }
  1225. }
  1226. }
  1227. },
  1228. /**
  1229. * 匹配图片、pdf(用于预览)
  1230. * @param {String} ext 后缀名
  1231. * @return {Boolean} 匹配结果
  1232. */
  1233. canPreview(ext) {
  1234. const reg = /(.png)|(.gif)|(.txt)|(.jpg)|(.jpeg)|(.pdf)/i;
  1235. return reg.test(ext);
  1236. },
  1237. fileExtStr(ext) {
  1238. const ExtStr = [
  1239. { text: '图片', ext: ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.cad', '.dwg',] },
  1240. { text: '压缩包', ext: ['.zip', '.rar', '.7z',] },
  1241. { text: '音频', ext: ['.mp3'] },
  1242. { text: '视频', ext: ['.mp4'] },
  1243. { text: '文档', ext: ['.json', '.txt', '.xls', '.xlsx', '.doc', '.docx', '.pdf', '.ppt', '.pptx',]},
  1244. ];
  1245. for (const es of ExtStr) {
  1246. if (es.ext.indexOf(ext) >= 0) return es.text;
  1247. }
  1248. return '';
  1249. },
  1250. /**
  1251. * 查找数组中某个字符的个数
  1252. * @param {Array} array 数组
  1253. * @param {string} val 字符串
  1254. * @return {Boolean} 匹配结果
  1255. */
  1256. arrayCount(array, val) {
  1257. const counts = (arr, value) => arr.reduce((a, v) => { return value.indexOf(v) !== -1 ? a + 1 : a + 0; }, 0);
  1258. return counts(array, val);
  1259. },
  1260. filterTimesOrderData(data, keyFields, timesField, orderField, times, order) {
  1261. const dataIndex = {};
  1262. for (const d of data) {
  1263. if (d[timesField] > times || (d[timesField] = times && d[orderField] > order)) continue;
  1264. let key = 'd';
  1265. for (const kf of keyFields) {
  1266. key = key + '.' + (d[kf] || '');
  1267. }
  1268. const di = dataIndex[key];
  1269. if (di) {
  1270. if ((di[timesField] * timesLen + di[orderField]) < (d[timesField] * timesLen + d[orderField])) dataIndex[key] = d;
  1271. } else {
  1272. dataIndex[key] = d;
  1273. }
  1274. }
  1275. const result = [];
  1276. for (const prop in dataIndex) {
  1277. result.push(dataIndex[prop]);
  1278. }
  1279. return result;
  1280. },
  1281. filterLastestData(data, keyFields, timesField = 'times', orderField = 'order') {
  1282. const dataIndex = {};
  1283. for (const d of data) {
  1284. let key = 'd';
  1285. for (const kf of keyFields) {
  1286. key = key + '.' + (d[kf] || '');
  1287. }
  1288. const di = dataIndex[key];
  1289. if (di) {
  1290. if ((di[timesField] * timesLen + di[orderField]) < (d[timesField] * timesLen + d[orderField])) dataIndex[key] = d;
  1291. } else {
  1292. dataIndex[key] = d;
  1293. }
  1294. }
  1295. const result = [];
  1296. for (const prop in dataIndex) {
  1297. result.push(dataIndex[prop]);
  1298. }
  1299. return result;
  1300. },
  1301. filterLastestData2(data, keyFields, timesField = 'times', orderField = 'order') {
  1302. const dataIndex = {};
  1303. for (const d of data) {
  1304. let key = 'd';
  1305. for (const kf of keyFields) {
  1306. key = key + '.' + (d[kf] || '');
  1307. }
  1308. if (!dataIndex[key]) dataIndex[key] = { index: 0, source: [] };
  1309. const di = dataIndex[key];
  1310. const curIndex = d[timesField] * timesLen + d[orderField];
  1311. if (curIndex === di.index) {
  1312. di.source.push(d);
  1313. } else if (curIndex > di.index) {
  1314. di.index = curIndex;
  1315. di.source = [d];
  1316. }
  1317. }
  1318. const result = [];
  1319. for (const prop in dataIndex) {
  1320. result.push(...dataIndex[prop].source);
  1321. }
  1322. return result;
  1323. },
  1324. calcExpr(expr) {
  1325. const validExpr = expr.replace('=', '').replace(new RegExp('%', 'gm'), '/100');
  1326. return parseFloat(math.eval(validExpr));
  1327. },
  1328. /**
  1329. * 创建登录日志
  1330. * @return {Boolean} 日志是否创建成功
  1331. * @param {Number} type - 登录类型
  1332. * @param {Number} status - 是否显示记录
  1333. */
  1334. async getUserIPMsg() {
  1335. const { ctx } = this;
  1336. const ip = ctx.request.ip ? ctx.request.ip : '';
  1337. const ipInfo = await this.getIpInfoFromApi(ip);
  1338. const parser = new UAParser(ctx.header['user-agent']);
  1339. const osInfo = parser.getOS();
  1340. const cpuInfo = parser.getCPU();
  1341. const browserInfo = parser.getBrowser();
  1342. const ipMsg = {
  1343. os: `${osInfo.name} ${osInfo.version} ${cpuInfo.architecture}`,
  1344. browser: `${browserInfo.name} ${browserInfo.version}`,
  1345. ip,
  1346. address: ipInfo,
  1347. };
  1348. return ipMsg;
  1349. },
  1350. /**
  1351. * 根据ip请求获取详细地址
  1352. * @param {String} a_ip - ip地址
  1353. * @return {String} 详细地址
  1354. */
  1355. async getIpInfoFromApi(a_ip = '') {
  1356. if (!a_ip) return '';
  1357. if (a_ip === '127.0.0.1' || a_ip === '::1' || a_ip.indexOf('192.168') !== -1) return '服务器本机访问';
  1358. const { ip = '', region = '', city = '', isp = '' } = await this.sendIpRequest(a_ip);
  1359. let address = '';
  1360. region && (address += region + '省');
  1361. city && (address += city + '市 ');
  1362. isp && (address += isp + ' ');
  1363. ip && (address += `(${ip})`);
  1364. return address;
  1365. },
  1366. /**
  1367. * 发送请求获取详细地址
  1368. * @param {String} ip - ip地址
  1369. * @return {Object} the result of request
  1370. * @private
  1371. */
  1372. async sendIpRequest(ip) {
  1373. return new Promise(resolve => {
  1374. this.ctx.curl(`https://api01.aliyun.venuscn.com/ip?ip=${ip}`, {
  1375. dateType: 'json',
  1376. encoding: 'utf8',
  1377. timeout: 2000,
  1378. headers: {
  1379. Authorization: 'APPCODE 85c64bffe70445c4af9df7ae31c7bfcc',
  1380. },
  1381. }).then(({ status, data }) => {
  1382. if (status === 200) {
  1383. const result = JSON.parse(data.toString()).data;
  1384. if (!result.ip) {
  1385. resolve({});
  1386. } else {
  1387. resolve(result);
  1388. }
  1389. } else {
  1390. resolve({});
  1391. }
  1392. }).catch(() => {
  1393. resolve({});
  1394. });
  1395. });
  1396. },
  1397. /**
  1398. * 发送请求获取详细地址
  1399. * @param {String} type - 通知类型
  1400. * @param {String} datas - 请求发送数据
  1401. * @return {Object} the result of request
  1402. * @private
  1403. */
  1404. async syncNoticeSend(type, datas) {
  1405. const key = this.ctx.session.sessionProject.code;
  1406. const time = new Date().getTime();
  1407. const projectData = await this.ctx.service.project.getDataById(this.ctx.session.sessionProject.id);
  1408. const sign = crypto.createHash('md5').update(key + projectData.secret + time.toString()).digest('hex').toString();
  1409. const res = await this.ctx.curl(this.ctx.app.config.syncUrl + syncApiConst.api_url.notice, {
  1410. method: 'POST',
  1411. contentType: 'json',
  1412. data: {
  1413. projectCode: key,
  1414. key,
  1415. time,
  1416. sign,
  1417. customType: type,
  1418. base_data: datas,
  1419. },
  1420. dateType: 'json',
  1421. timeout: [30000, 60000],
  1422. timing: true,
  1423. });
  1424. },
  1425. async ossFileGet(path) {
  1426. // 判断开头是否带app,否则加上
  1427. if (!_.includes(path, 'app/') && !_.includes(path, 'sp/contract/') && !_.includes(path, 'sp/financial/')) {
  1428. path = 'app/' + path;
  1429. }
  1430. const result = await this.ctx.app.fujianOss.get(this.ctx.app.config.fujianOssFolder + path);
  1431. if (result.res.status !== 200) {
  1432. throw '该文件不存在';
  1433. }
  1434. return result.content;
  1435. },
  1436. getStartEndMonth(month) {
  1437. const startMonth = moment(month).startOf('month').format('YYYY-MM-DD HH:mm:ss');
  1438. const endMonth = moment(month).endOf('month').format('YYYY-MM-DD HH:mm:ss');
  1439. return [startMonth, endMonth];
  1440. },
  1441. /**
  1442. * 创建json web token
  1443. * @param {Object} data - 签名数据
  1444. * @return {String} token
  1445. */
  1446. createJWT(data) {
  1447. return jwt.sign({ data }, sign.managementApiSecretKey, { expiresIn: '15s' });
  1448. },
  1449. async loadLedgerDataFromOss(url) {
  1450. const File = await this.ctx.hisOss.get(this.ctx.hisOssPath + url);
  1451. if (File.res.status !== 200) return '获取修订台账有误';
  1452. const result = JSON.parse(File.content);
  1453. return result;
  1454. },
  1455. hpackArr(data) {
  1456. const keyIndex = {}, key = [];
  1457. const result = [];
  1458. for (const d of data) {
  1459. const r = [];
  1460. for (const prop in d) {
  1461. if (keyIndex[prop] === undefined) {
  1462. key.push(prop);
  1463. keyIndex[prop] = key.indexOf(prop);
  1464. }
  1465. r[keyIndex[prop]] = d[prop];
  1466. }
  1467. result.push(r);
  1468. }
  1469. if (result.length > 0) result.unshift(key);
  1470. return result;
  1471. },
  1472. // 把一个 xml 格式化成一个 json
  1473. async parseXML(xml) {
  1474. const result = await xml2js.parseStringPromise(xml, { trim: true });
  1475. return this.formatMessage(result.xml);
  1476. },
  1477. // 将xml2js解析出来的对象转换成直接可访问的对象
  1478. formatMessage(result) {
  1479. const message = {};
  1480. if (typeof result === 'object') {
  1481. for (const key in result) {
  1482. if (!(result[key] instanceof Array) || result[key].length === 0) {
  1483. continue;
  1484. }
  1485. if (result[key].length === 1) {
  1486. const val = result[key][0];
  1487. if (typeof val === 'object') {
  1488. message[key] = this.formatMessage(val);
  1489. } else {
  1490. message[key] = (val || '').trim();
  1491. }
  1492. } else {
  1493. message[key] = result[key].map(function(item) {
  1494. return this.formatMessage(item);
  1495. });
  1496. }
  1497. }
  1498. }
  1499. return message;
  1500. },
  1501. mapAllSubField(obj, field) {
  1502. const result = [];
  1503. for (const prop in obj) {
  1504. result.push(obj[prop][field]);
  1505. }
  1506. return result;
  1507. },
  1508. groupAuditors(auditors, orderField = 'order', noYb = false) {
  1509. auditors.sort((x, y) => {
  1510. return x[orderField] - y[orderField];
  1511. });
  1512. const newAuditors = noYb ? auditors.filter(x => { return x.audit_order !== 0; }) : auditors;
  1513. const Group = [];
  1514. for (const a of newAuditors) {
  1515. if (a[orderField] !== undefined) {
  1516. if (Group.length === 0) {
  1517. Group.push([a])
  1518. } else {
  1519. if (Group[Group.length-1][0][orderField] === a[orderField]) {
  1520. Group[Group.length-1].push(a);
  1521. } else {
  1522. Group.push([a]);
  1523. }
  1524. }
  1525. } else {
  1526. Group.push([a]);
  1527. }
  1528. }
  1529. return Group;
  1530. },
  1531. groupAuditorsUniq(group, key = 'audit_order') {
  1532. const uniqGroup = [];
  1533. for (const g of group) {
  1534. uniqGroup[g[0][key]] = g;
  1535. }
  1536. return uniqGroup.filter(x => { return !!x });
  1537. },
  1538. async getOssToken(oss) {
  1539. try {
  1540. const { STS } = require('ali-oss');
  1541. let sts = new STS({
  1542. accessKeyId: 'LTAI5tSoKgJ9Ze5VcgMQcM3m',
  1543. accessKeySecret: '34sj51AEUpeDzr5V6DYjrxWOatw7Zr',
  1544. });
  1545. const token = {
  1546. bucket: oss.options.bucket,
  1547. endpoint: this.ctx.app.config.fujianOssPath,
  1548. cname: true,
  1549. };
  1550. const result = await sts.assumeRole('acs:ram::31196920:role/oss-readonly', '', '3000', this.ctx.app.uuid.v4());
  1551. token.accessKeyId = result.credentials.AccessKeyId;
  1552. token.accessKeySecret = result.credentials.AccessKeySecret;
  1553. token.stsToken = result.credentials.SecurityToken;
  1554. return token;
  1555. } catch (err) {
  1556. console.log(err);
  1557. }
  1558. },
  1559. getQtySource(qty_source, no_qc_qty = 0) {
  1560. let qty = '';
  1561. switch (qty_source) {
  1562. case qtySourceValueConst.gather_qty: qty = '`gather_qty`'; break;
  1563. case qtySourceValueConst.contract_qty: qty = '`contract_qty`'; break;
  1564. case qtySourceValueConst.gather_minus_qty: qty = '(`gather_qty`+`qc_minus_qty`)'; break;
  1565. default: throw '未配置计量来源出错';
  1566. }
  1567. if (qty_source !== qtySourceValueConst.contract_qty && no_qc_qty) {
  1568. qty = '`contract_qty`';
  1569. }
  1570. return qty;
  1571. },
  1572. resetQtys(qtys) {
  1573. qtys.gather_qty = qtys.gather_qty ? qtys.gather_qty : null;
  1574. qtys.contract_qty = qtys.contract_qty ? qtys.contract_qty : null;
  1575. qtys.qc_qty = qtys.qc_qty ? qtys.qc_qty : null;
  1576. qtys.qc_minus_qty = qtys.qc_minus_qty ? qtys.qc_minus_qty : null;
  1577. return qtys;
  1578. },
  1579. contentChange(content) {
  1580. let str = content.replace(/【/g, '(');
  1581. str = str.replace(/】/g, ')');
  1582. str = str.replace(/工程款/g, '***');
  1583. str = str.length > 20 ? str.substring(0, 17) + '...' : str;
  1584. return str;
  1585. },
  1586. calculateNextSendTime(startTime, intervalHours = 6, quietStart = 0, quietEnd = 8) {
  1587. function parseTime(stime, timeStr, day = 0) {
  1588. const [hours, minutes] = timeStr.split(':').map(Number);
  1589. const date = new Date();
  1590. date.setFullYear(stime.getFullYear());
  1591. date.setMonth(stime.getMonth());
  1592. date.setDate(stime.getDate() + day);
  1593. date.setHours(hours, minutes, 0, 0); // Set hours and minutes, reset seconds and milliseconds
  1594. return date;
  1595. }
  1596. function calculateHoursBetween(start, end) {
  1597. // 将时间字符串转换为 Date 对象
  1598. const startTime = new Date(`2000-01-01T${start}`);
  1599. const endTime = new Date(`2000-01-01T${end}`);
  1600. // 检查是否跨越了当前日期和隔天日期
  1601. if (endTime < startTime) {
  1602. endTime.setDate(endTime.getDate() + 1); // 将结束时间调整到隔天
  1603. }
  1604. // 计算两个时间之间的毫秒数差距
  1605. const timeDifference = endTime - startTime;
  1606. // 将毫秒数转换为小时并返回
  1607. const hours = timeDifference / (1000 * 60 * 60);
  1608. return 24 - hours;
  1609. }
  1610. // let startDateTime = parseTime(startTime);
  1611. let startDateTime = startTime;
  1612. let endDateTime = new Date(startDateTime.getTime() + intervalHours * 60 * 60 * 1000);
  1613. if (quietStart && quietEnd) {
  1614. quietStart = (quietStart < 10 ? '0' + quietStart : quietStart) + ':00';
  1615. quietEnd = (quietEnd < 10 ? '0' + quietEnd : quietEnd) + ':00';
  1616. let quietStartDateTime = parseTime(startDateTime, quietStart);
  1617. let quietEndDateTime = parseTime(startDateTime, quietEnd);
  1618. if (quietEndDateTime <= quietStartDateTime) {
  1619. quietEndDateTime.setDate(quietEndDateTime.getDate() + 1);
  1620. }
  1621. // 判断非屏蔽时间内是否大于间隔时间,大于则要再隔天发送
  1622. const hours = calculateHoursBetween(quietStart, quietEnd);
  1623. if (hours < intervalHours) {
  1624. // 除法算出差的天数
  1625. const days = Math.floor(intervalHours / hours);
  1626. quietStartDateTime = parseTime(startDateTime, quietStart, days);
  1627. quietEndDateTime = parseTime(startDateTime, quietEnd, days);
  1628. intervalHours %= hours;
  1629. startDateTime.setDate(startDateTime.getDate() + days);
  1630. } else if (startDateTime >= quietEndDateTime) {
  1631. quietStartDateTime = parseTime(startDateTime, quietStart, 1);
  1632. }
  1633. if (quietEndDateTime <= quietStartDateTime) {
  1634. quietEndDateTime.setDate(quietEndDateTime.getDate() + 1);
  1635. }
  1636. if (startDateTime >= quietStartDateTime) {
  1637. startDateTime = quietEndDateTime;
  1638. }
  1639. endDateTime = new Date(startDateTime.getTime() + intervalHours * 60 * 60 * 1000);
  1640. if (endDateTime >= quietStartDateTime && endDateTime < quietEndDateTime) {
  1641. const timeIntoQuiet = (quietStartDateTime - startDateTime) / (60 * 60 * 1000);
  1642. const remainingTime = intervalHours - timeIntoQuiet;
  1643. endDateTime = new Date(quietEndDateTime.getTime() + remainingTime * 60 * 60 * 1000);
  1644. }
  1645. }
  1646. // return endDateTime.getHours().toString().padStart(2, '0') + ':' +
  1647. // endDateTime.getMinutes().toString().padStart(2, '0');
  1648. return endDateTime;
  1649. },
  1650. showCol4ObjArray(objArray, colName, key = 'value', showKey = 'name') {
  1651. if (!colName) return '';
  1652. const info = _.find(objArray, { [key]: colName });
  1653. return info ? info[showKey] : '';
  1654. },
  1655. };