helper.js 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788
  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. } else if (codePath.length >= 2 && reg.test(codePath[1])) {
  462. const numReg = /[0-9]{3,4}$/;
  463. const result = codePath[1].match(numReg);
  464. const num = parseInt(result[0]);
  465. return this.mul(this.div(num, 100, 0), 100) + '';
  466. }
  467. return '10000';
  468. },
  469. /**
  470. * 树结构节点排序,要求最顶层节点须在同一父节点下
  471. * @param treeNodes
  472. * @param idField
  473. * @param pidField
  474. */
  475. sortTreeNodes(treeNodes, idField, pidField) {
  476. const result = [];
  477. const getFirstLevel = function(nodes) {
  478. let result;
  479. for (const node of nodes) {
  480. if (!result || result > node.level) {
  481. result = node.level;
  482. }
  483. }
  484. return result;
  485. };
  486. const getLevelNodes = function(nodes, level) {
  487. const children = nodes.filter(function(a) {
  488. return a.level = level;
  489. });
  490. children.sort(function(a, b) {
  491. return a.order - b.order;
  492. });
  493. return children;
  494. };
  495. const getChildren = function(nodes, node) {
  496. const children = nodes.filter(function(a) {
  497. return a[pidField] = node[idField];
  498. });
  499. children.sort(function(a, b) {
  500. return a.order - b.order;
  501. });
  502. return children;
  503. };
  504. const addSortNodes = function(nodes) {
  505. for (let i = 0; i < nodes.length; i++) {
  506. result.push(nodes[i]);
  507. addSortNodes(getChildren(nodes[i]));
  508. }
  509. };
  510. const firstLevel = getFirstLevel(treeNodes);
  511. addSortNodes(getLevelNodes(treeNodes, firstLevel));
  512. },
  513. /**
  514. * 判断当前用户是否有指定权限
  515. *
  516. * @param {Number|Array} permission - 权限id
  517. * @return {Boolean} - 返回判断结果
  518. */
  519. hasPermission(permission) {
  520. let result = false;
  521. try {
  522. const sessionUser = this.ctx.session.sessionUser;
  523. if (sessionUser.permission === undefined) {
  524. throw '不存在权限数据';
  525. }
  526. let currentPermission = sessionUser.permission;
  527. if (currentPermission === '') {
  528. throw '权限数据为空';
  529. }
  530. // 管理员则直接返回结果
  531. if (currentPermission === 'all') {
  532. return true;
  533. }
  534. currentPermission = currentPermission.split(',');
  535. permission = permission instanceof Array ? permission : [permission];
  536. let counter = 0;
  537. for (const tmp of permission) {
  538. if (currentPermission[tmp] !== undefined) {
  539. counter++;
  540. }
  541. }
  542. result = counter === permission.length;
  543. } catch (error) {
  544. result = false;
  545. }
  546. return result;
  547. },
  548. /**
  549. * 递归创建文件夹(fs.mkdirSync需要上一层文件夹已存在)
  550. * @param pathName
  551. * @return {Promise<void>}
  552. */
  553. async recursiveMkdirSync(pathName) {
  554. if (!fs.existsSync(pathName)) {
  555. const upperPath = path.dirname(pathName);
  556. if (!fs.existsSync(upperPath)) {
  557. await this.recursiveMkdirSync(upperPath);
  558. }
  559. await fs.mkdirSync(pathName);
  560. }
  561. },
  562. /**
  563. * 字节 保存至 本地文件
  564. * @param buffer - 字节
  565. * @param fileName - 文件名
  566. * @return {Promise<void>}
  567. */
  568. async saveBufferFile(buffer, fileName) {
  569. // 检查文件夹是否存在,不存在则直接创建文件夹
  570. const pathName = path.dirname(fileName);
  571. if (!fs.existsSync(pathName)) {
  572. await this.recursiveMkdirSync(pathName);
  573. }
  574. await fs.writeFileSync(fileName, buffer);
  575. },
  576. /**
  577. * 将文件流的数据保存至本地文件
  578. * @param stream
  579. * @param fileName
  580. * @return {Promise<void>}
  581. */
  582. async saveStreamFile(stream, fileName) {
  583. // 读取字节流
  584. const parts = await streamToArray(stream);
  585. // 转化为buffer
  586. const buffer = Buffer.concat(parts);
  587. // 写入文件
  588. await this.saveBufferFile(buffer, fileName);
  589. },
  590. async copyFileSync(source, target) {
  591. const pathName = path.dirname(target);
  592. if (!fs.existsSync(pathName)) {
  593. await this.recursiveMkdirSync(pathName);
  594. }
  595. await fs.copyFileSync(source, target);
  596. },
  597. /**
  598. * 检查code是否是指标模板数据
  599. * @param {String} code
  600. * @return {boolean}
  601. */
  602. validBillsCode(code) {
  603. const reg1 = /(^[0-9]+)([a-z0-9\-]*)/i;
  604. const reg2 = /([a-z0-9]+$)/i;
  605. return reg1.test(code) && reg2.test(code);
  606. },
  607. getNumberFormatter(decimal) {
  608. if (decimal <= 0) {
  609. return '0';
  610. }
  611. let pre = '0.';
  612. for (let i = 0; i < decimal; i++) {
  613. pre += '#';
  614. }
  615. return pre;
  616. },
  617. /**
  618. * 根据单位查找对应的清单精度
  619. * @param {tenderInfo.precision} list - 清单精度列表
  620. * @param {String} unit - 单位
  621. * @return {number}
  622. */
  623. findPrecision(list, unit) {
  624. if (unit) {
  625. for (const p in list) {
  626. if (list[p].unit && list[p].unit === unit) {
  627. return list[p];
  628. }
  629. }
  630. }
  631. return list.other;
  632. },
  633. /**
  634. * 检查数据中的精度
  635. * @param {Object} Obj - 检查的数据
  636. * @param {Array} fields - 检查的属性
  637. * @param {Number} precision - 精度
  638. * @class
  639. */
  640. checkFieldPrecision(Obj, fields, precision = 2) {
  641. if (Obj) {
  642. for (const field of fields) {
  643. if (Obj[field]) {
  644. Obj[field] = this.round(Obj[field], precision);
  645. }
  646. }
  647. }
  648. },
  649. checkDgnQtyPrecision(data, precision = 3) {
  650. const datas = data instanceof Array ? data : [data];
  651. for (const d of datas) {
  652. for (const prop in d) {
  653. if (prop.indexOf('dgn_qty') >= 0) d[prop] = this.round(d[prop], precision);
  654. }
  655. }
  656. },
  657. /**
  658. * 过滤无效数据
  659. *
  660. * @param obj
  661. * @param fields - 有效数据的数组
  662. */
  663. filterValidFields(data, fields) {
  664. if (data) {
  665. const result = {};
  666. for (const prop in data) {
  667. if (fields.indexOf(prop) !== -1) {
  668. result[prop] = data[prop];
  669. }
  670. }
  671. return result;
  672. }
  673. return data;
  674. },
  675. // 加减乘除方法,为方便调用,兼容num为空的情况
  676. // 加减法使用base_calc,乘除法使用Decimal(原因详见demo/calc_test)
  677. /**
  678. * 加法 num1 + num2
  679. * @param num1
  680. * @param num2
  681. * @return {number}
  682. */
  683. add(num1, num2) {
  684. return bc.add(num1 ? num1 : 0, num2 ? num2 : 0);
  685. },
  686. /**
  687. * 减法 num1 - num2
  688. * @param num1
  689. * @param num2
  690. * @return {number}
  691. */
  692. sub(num1, num2) {
  693. return bc.sub(num1 ? num1 : 0, num2 ? num2 : 0);
  694. },
  695. /**
  696. * 乘法 num1 * num2
  697. * @param num1
  698. * @param num2
  699. * @return {*}
  700. */
  701. mul(num1, num2, digit = 6) {
  702. if (num1 === '' || num1 === null || num2 === '' || num2 === null) {
  703. return 0;
  704. }
  705. return Decimal.mul(num1 ? num1 : 0, num2 ? num2 : 0).toDecimalPlaces(digit).toNumber();
  706. },
  707. /**
  708. * 除法 num1 / num2
  709. * @param num1 - 被除数
  710. * @param num2 - 除数
  711. * @return {*}
  712. */
  713. div(num1, num2, digit = 6) {
  714. if (num2 && !this.checkZero(num2)) {
  715. return Decimal.div(num1 ? num1 : 0, num2).toDecimalPlaces(digit).toNumber();
  716. }
  717. return null;
  718. },
  719. /**
  720. * 四舍五入(统一,方便以后万一需要置换)
  721. * @param {Number} value - 舍入的数字
  722. * @param {Number} decimal - 要保留的小数位数
  723. * @return {*}
  724. */
  725. round(value, decimal) {
  726. return value ? new Decimal(value.toString()).toDecimalPlaces(decimal).toNumber() : 0;
  727. },
  728. /**
  729. * 汇总
  730. * @param array
  731. * @return {number}
  732. */
  733. sum(array) {
  734. let result = 0;
  735. for (const a of array) {
  736. result = this.add(result, a);
  737. }
  738. return result;
  739. },
  740. /**
  741. * 使用正则替换字符
  742. * @param str
  743. * @param reg
  744. * @param subStr
  745. * @return {*}
  746. */
  747. replaceStr(str, reg, subStr) {
  748. return str ? str.replace(reg, subStr) : str;
  749. },
  750. /**
  751. * 替换字符串中的 换行符回车符
  752. * @param str
  753. * @return {*}
  754. */
  755. replaceReturn(str) {
  756. // return str
  757. // ? (typeof str === 'string') ? str.replace(/[\r\n]/g, '') : str + ''
  758. // : str;
  759. return (str && typeof str === 'string')
  760. ? str.replace(/[\r\n]/g, '')
  761. : !_.isNil(str) ? str + '' : str;
  762. },
  763. /**
  764. * 替换字符串中的 换行符回车符为换行符<br>
  765. * @param str
  766. * @return {*}
  767. */
  768. replaceRntoBr(str) {
  769. // return str
  770. // ? (typeof str === 'string') ? str.replace(/[\r\n]/g, '') : str + ''
  771. // : str;
  772. return (str && typeof str === 'string')
  773. ? str.replace(/[\r\n]/g, '<br>')
  774. : !_.isNil(str) ? str + '' : str;
  775. },
  776. /**
  777. * 获取 字符串 数组的 mysql 筛选条件
  778. *
  779. * @param arr
  780. * @return {*}
  781. */
  782. getInArrStrSqlFilter(arr) {
  783. let result = '';
  784. for (const a of arr) {
  785. if (result !== '') {
  786. result = result + ',';
  787. }
  788. result = result + this.ctx.app.mysql.escape(a);
  789. }
  790. return result;
  791. },
  792. _getOptionsSql(options) {
  793. const optionSql = [];
  794. for (const key in options) {
  795. if (options.hasOwnProperty(key)) {
  796. optionSql.push(key + ' = ' + this.ctx.app.mysql.escape(options[key]));
  797. }
  798. }
  799. return optionSql.join(' AND ');
  800. },
  801. /**
  802. * 合并 相关数据
  803. * @param {Array} main - 主数据
  804. * @param {Array[]}rela - 相关数据 {data, fields, prefix, relaId}
  805. */
  806. assignRelaData(main, rela, mainKey = 'id', clear = false) {
  807. const index = {},
  808. indexPre = 'id_';
  809. const loadFields = function(datas, fields, prefix, relaId) {
  810. for (const d of datas) {
  811. const key = indexPre + d[relaId];
  812. const m = index[key];
  813. if (m) {
  814. for (const f of fields) {
  815. if (d[f] !== undefined) {
  816. m[prefix + f] = d[f];
  817. }
  818. }
  819. }
  820. }
  821. };
  822. for (const m of main) {
  823. index[indexPre + m[mainKey]] = m;
  824. for (const r of rela) {
  825. if (r.defaultData) _.assignIn(m, r.defaultData);
  826. }
  827. if (clear) {
  828. rela.forEach(r => {
  829. r.fields.forEach(f => {
  830. delete m[r.prefix + f];
  831. });
  832. })
  833. }
  834. }
  835. for (const r of rela) {
  836. loadFields(r.data, r.fields, r.prefix, r.relaId);
  837. }
  838. },
  839. /**
  840. * 合并(并汇总) 相关数据
  841. * @param {Array} main - 主数据
  842. * @param {Array[]}rela - 相关数据 {data, fields, relaField}
  843. *
  844. * { data, fields}
  845. */
  846. assignSumRelaData(main, keyField, rela) {
  847. const index = {},
  848. indexPre = 'id_';
  849. const addFun = this.add;
  850. const loadFields = function(datas, fields, relaId) {
  851. for (const d of datas) {
  852. const key = indexPre + d[relaId];
  853. const m = index[key];
  854. if (!m) continue;
  855. for (const f of fields) {
  856. if (d[f.source]) m[f.target] = addFun(m[f.target], d[f.source]);
  857. }
  858. }
  859. };
  860. for (const m of main) {
  861. index[indexPre + m[keyField]] = m;
  862. }
  863. for (const r of rela) {
  864. loadFields(r.data, r.fields, r.relaField);
  865. }
  866. },
  867. whereSql(where, as) {
  868. if (!where) {
  869. return '';
  870. }
  871. const wheres = [];
  872. const values = [];
  873. for (const key in where) {
  874. const value = where[key];
  875. if (Array.isArray(value)) {
  876. wheres.push('?? IN (?)');
  877. } else {
  878. wheres.push('?? = ?');
  879. }
  880. values.push((as && as !== '') ? as + '.' + key : key);
  881. values.push(value);
  882. }
  883. if (wheres.length > 0) {
  884. return this.ctx.app.mysql.format(' WHERE ' + wheres.join(' AND '), values);
  885. }
  886. return '';
  887. },
  888. formatMoney(s = 0, dot = ',', decimal = 2) {
  889. if (!s) {
  890. s = 0;
  891. return s.toFixed(decimal);
  892. }
  893. s = decimal === 0 ? parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(decimal) + '' : (Math.round(parseFloat((s + '').replace(/[^\d\.-]/g, '')) * Math.pow(10, decimal)) / Math.pow(10, decimal)).toFixed(decimal) + '';
  894. if (!decimal) {
  895. s += '.';
  896. }
  897. const l = s.split('.')[0].split('').reverse(),
  898. r = s.split('.')[1];
  899. let t = '';
  900. for (let i = 0; i < l.length; i++) {
  901. t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? dot : '');
  902. }
  903. const num = t.split('').reverse().join('') + (decimal === 0 ? '' : '.' + r);
  904. return num.replace('-,', '-');
  905. },
  906. transFormToChinese(num) {
  907. const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  908. const unit = ['', '十', '百', '千', '万'];
  909. num = parseInt(num);
  910. const getWan = temp => {
  911. const strArr = temp.toString().split('').reverse();
  912. let newNum = '';
  913. for (let i = 0; i < strArr.length; i++) {
  914. 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;
  915. }
  916. return strArr.length === 2 && newNum.indexOf('一十') !== -1 ? newNum.replace('一十', '十') : newNum;
  917. };
  918. const overWan = Math.floor(num / 10000);
  919. let noWan = num % 10000;
  920. if (noWan.toString().length < 4) noWan = '0' + noWan;
  921. return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num);
  922. },
  923. formatNum(num, pattern) {
  924. const minus = num > 0 ? '' : '-'
  925. const strarr = num ? Math.abs(num).toString().split('.') : ['0'];
  926. const fmtarr = pattern ? pattern.split('.') : [''];
  927. let retstr = '';
  928. // 整数部分
  929. let str = strarr[0];
  930. let fmt = fmtarr[0];
  931. let i = str.length - 1;
  932. let comma = false;
  933. for (var f = fmt.length - 1; f >= 0; f--) {
  934. switch (fmt.substr(f, 1)) {
  935. case '#':
  936. if (i >= 0) retstr = str.substr(i--, 1) + retstr;
  937. break;
  938. case '0':
  939. if (i >= 0) retstr = str.substr(i--, 1) + retstr;
  940. else retstr = '0' + retstr;
  941. break;
  942. case ',':
  943. comma = true;
  944. retstr = ',' + retstr;
  945. break;
  946. }
  947. }
  948. if (i >= 0) {
  949. if (comma) {
  950. const l = str.length;
  951. for (;i >= 0; i--) {
  952. retstr = str.substr(i, 1) + retstr;
  953. if (i > 0 && ((l - i) % 3) == 0) retstr = ',' + retstr;
  954. }
  955. } else retstr = str.substr(0, i + 1) + retstr;
  956. }
  957. retstr = retstr + '.';
  958. // 处理小数部分
  959. str = strarr.length > 1 ? strarr[1] : '';
  960. fmt = fmtarr.length > 1 ? fmtarr[1] : '';
  961. i = 0;
  962. for (var f = 0; f < fmt.length; f++) {
  963. switch (fmt.substr(f, 1)) {
  964. case '#':
  965. if (i < str.length) retstr += str.substr(i++, 1);
  966. break;
  967. case '0':
  968. if (i < str.length) retstr += str.substr(i++, 1);
  969. else retstr += '0';
  970. break;
  971. }
  972. }
  973. return minus + retstr.replace(/^,+/, '').replace(/\.$/, '');
  974. },
  975. dateTran(time, style = 'YYYY年MM月DD日 HH:mm') {
  976. return moment(time).format(style);
  977. },
  978. dateTranChinese(day) {
  979. const dateParts = day.split('-');
  980. return dateParts[0] + '年' + dateParts[1] + '月' + dateParts[2] + '日';
  981. },
  982. // 审批日期格式:2020-5-7 9:40:30
  983. formatFullDate(time) {
  984. return moment(time).format('YYYY-MM-DD HH:mm:ss');
  985. },
  986. calcDayNum(startTime, endTime = '') {
  987. const dateStart = new Date(startTime);
  988. const dateEnd = endTime ? new Date(endTime) : new Date();
  989. return parseInt((dateEnd.getTime() - dateStart.getTime()) / (1000 * 60 * 60 * 24));
  990. },
  991. // 预付款详情页时间线所需格式
  992. formatDate(date) {
  993. if (!date) return '';
  994. const year = date.getFullYear();
  995. let mon = date.getMonth() + 1;
  996. let day = date.getDate();
  997. let hour = date.getHours();
  998. let minute = date.getMinutes();
  999. let scond = date.getSeconds();
  1000. if (mon < 10) {
  1001. mon = '0' + mon.toString();
  1002. }
  1003. if (day < 10) {
  1004. day = '0' + day.toString();
  1005. }
  1006. if (hour < 10) {
  1007. hour = '0' + hour.toString();
  1008. }
  1009. if (minute < 10) {
  1010. minute = '0' + minute.toString();
  1011. }
  1012. if (scond < 10) {
  1013. scond = '0' + scond.toString();
  1014. }
  1015. return `${year}<span>${mon}-${day}</span><span>${hour}:${minute}:${scond}</span>`;
  1016. },
  1017. timeAdd(duration) {
  1018. const d = parseInt(duration);
  1019. let time = 0;
  1020. if (d === 1) {
  1021. time = 60 * 15 * 1000;
  1022. } else if (d === 2) {
  1023. time = 60 * 30 * 1000;
  1024. } else if (d === 3) {
  1025. time = 3600 * 1000;
  1026. } else if (d === 4) {
  1027. time = 3600 * 2 * 1000;
  1028. }
  1029. return time;
  1030. },
  1031. async sendUserSms(userId, type, judge, msg) {
  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. const smsType = JSON.parse(su.sms_type);
  1039. if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
  1040. mobiles.push(su.auth_mobile);
  1041. }
  1042. }
  1043. if (mobiles.length > 0) {
  1044. const sms = new SMS(this.ctx);
  1045. const tenderName = await sms.contentChange(this.ctx.tender.data.name);
  1046. const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
  1047. const ptmsg = projectName !== '' ? '项目「' + projectName + '」标段「' + tenderName + '」' : tenderName;
  1048. const content = '【纵横计量支付】' + ptmsg + msg;
  1049. sms.send(mobiles, content);
  1050. }
  1051. },
  1052. async sendAliSms(userId, type, judge, code, data = {}) {
  1053. // const mobiles = [];
  1054. // if (!userId || (userId instanceof Array && userId.length === 0)) return;
  1055. // const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  1056. // for (const su of smsUser) {
  1057. // if (!su.auth_mobile || su.auth_mobile === '') continue;
  1058. // if (!su.sms_type || su.sms_type === '') continue;
  1059. //
  1060. // const smsType = JSON.parse(su.sms_type);
  1061. // if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
  1062. // mobiles.push(su.auth_mobile);
  1063. // }
  1064. // }
  1065. //
  1066. // if (mobiles.length > 0) {
  1067. // const sms = new SMS(this.ctx);
  1068. // const tenderName = await sms.contentChange(this.ctx.tender.data.name);
  1069. // const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
  1070. // const param = {
  1071. // project: projectName,
  1072. // number: tenderName,
  1073. // };
  1074. // const postParam = Object.assign(param, data);
  1075. // sms.aliSend(mobiles, postParam, code);
  1076. // }
  1077. },
  1078. // 企业微信和公众号微信通知共用
  1079. async sendWechat(userId, type, judge, template, data = {}, tender = this.ctx.tender, ctx = this.ctx) {
  1080. const wechats = [];
  1081. const qywxs = {};
  1082. if (!userId || (userId instanceof Array && userId.length === 0)) return;
  1083. const wxUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  1084. for (const user of wxUser) {
  1085. if ((!user.wx_openid || user.wx_openid === '') && !user.qywx_userid) continue;
  1086. if (!user.wx_type || user.wx_type === '') continue;
  1087. const wxType = JSON.parse(user.wx_type);
  1088. if (wxType[type] && wxType[type].indexOf(judge) !== -1) {
  1089. if (user.wx_openid) wechats.push(user.wx_openid);
  1090. if (user.qywx_userid && user.qywx_corpid) {
  1091. _.has(qywxs, user.qywx_corpid) ? qywxs[user.qywx_corpid].push(user.qywx_userid) : qywxs[user.qywx_corpid] = [user.qywx_userid];
  1092. }
  1093. }
  1094. }
  1095. if (wechats.length > 0 || !_.isEmpty(qywxs)) {
  1096. const wx = new WX(this.ctx);
  1097. const tenderName = await wx.contentChange(tender.data.name);
  1098. const projectName = await wx.contentChange(tender.info.deal_info.buildName);
  1099. const param = {
  1100. projectName,
  1101. tenderName,
  1102. };
  1103. const postParam = Object.assign(param, data);
  1104. const originUrl = ctx.protocol + '://' + ctx.host;
  1105. if (wechats.length > 0) wx.Send(wechats, template, postParam, originUrl);
  1106. if (!_.isEmpty(qywxs)) wx.Send4Work(qywxs, template, postParam, originUrl);
  1107. }
  1108. },
  1109. /**
  1110. *
  1111. * @param setting
  1112. * @param data
  1113. * @return {{} & any & {"!ref": string} & {"!cols"}}
  1114. */
  1115. simpleXlsxSheetData(setting, data) {
  1116. const headerStyle = {
  1117. font: { sz: 10, bold: true },
  1118. alignment: { horizontal: 'center' },
  1119. };
  1120. const sHeader = setting.header
  1121. .map((v, i) => Object.assign({}, { v, s: headerStyle, position: String.fromCharCode(65 + i) + 1 }))
  1122. .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v, s: next.s } }), {});
  1123. const sData = data
  1124. .map((v, i) => v.map((k, j) => Object.assign({}, {
  1125. v: k ? k : '',
  1126. s: { font: { sz: 10 }, alignment: { horizontal: setting.hAlign[j] } },
  1127. position: String.fromCharCode(65 + j) + (i + 2) })))
  1128. .reduce((prev, next) => prev.concat(next))
  1129. .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v, s: next.s } }), {});
  1130. const output = Object.assign({}, sHeader, sData);
  1131. const outputPos = Object.keys(output);
  1132. const result = Object.assign({}, output,
  1133. { '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] },
  1134. { '!cols': setting.width.map(w => Object.assign({}, { wpx: w })) });
  1135. return result;
  1136. },
  1137. log(error) {
  1138. if (error.stack) {
  1139. this.ctx.logger.error(error);
  1140. } else {
  1141. this.ctx.getLogger('fail').info(JSON.stringify({
  1142. error,
  1143. project: this.ctx.session.sessionProject,
  1144. user: this.ctx.session.sessionUser,
  1145. body: this.ctx.session.body,
  1146. }));
  1147. }
  1148. },
  1149. /**
  1150. * 添加debug信息
  1151. * 在debug模式下,debug信息将传输到浏览器并打印
  1152. *
  1153. * @param {String}key
  1154. * @param {*}data
  1155. */
  1156. addDebugInfo(key, ...data) {
  1157. if (!this.ctx.debugInfo) {
  1158. this.ctx.debugInfo = { key: {}, other: [] };
  1159. }
  1160. if (key) {
  1161. this.ctx.debugInfo.key[key] = data;
  1162. } else {
  1163. this.ctx.debugInfo.other.push(data);
  1164. }
  1165. },
  1166. /**
  1167. * 深拷贝
  1168. * @param obj
  1169. * @return {*}
  1170. */
  1171. clone(obj) {
  1172. if (obj === null) return null;
  1173. const o = obj instanceof Array ? [] : {};
  1174. for (const i in obj) {
  1175. o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === 'object' ? this.clone(obj[i]) : obj[i]);
  1176. }
  1177. return o;
  1178. },
  1179. /**
  1180. * 短链接生成(暂停生成)
  1181. * @param url
  1182. * @return {*}
  1183. */
  1184. async urlToShort(url) {
  1185. // const apiUrl = 'http://scn.ink/api/shorturl';
  1186. // const data = {
  1187. // url: encodeURI(url),
  1188. // };
  1189. // const result = await this.sendRequest(apiUrl, data, 'get');
  1190. // return result && result.code === 200 && result.url ? result.url : url;
  1191. return url;
  1192. },
  1193. /**
  1194. * 判断是否wap访问
  1195. * @param request
  1196. * @return {*}
  1197. */
  1198. isWap(request) {
  1199. return request.url.indexOf('/wap/') !== -1;
  1200. },
  1201. check18MainCode(code) {
  1202. return /^([0-9]([0-9][0-9])*)?(GD[0-9]{3}([0-9][0-9])*)?$/.test(code);
  1203. },
  1204. check18SubCode(code) {
  1205. return /^(GD)?G?[A-Z]{2}[A-Z]{0,2}([0-9]{2})+$/.test(code);
  1206. },
  1207. /**
  1208. * 判断是否是移动端访问
  1209. * @param request
  1210. * @return {*}
  1211. */
  1212. isMobile(agent) {
  1213. const ua = new UAParser(agent);
  1214. const osInfo = ua.getOS();
  1215. return (agent ? agent.match(/(iphone|ipod|android)/i) : false) || osInfo.name === 'Android' || osInfo.name === 'iOS';
  1216. },
  1217. /**
  1218. * 删除文件
  1219. * @param {Array} fileList 文件数组(格式为数据库查询出来的结果集,且文件字段必须为filepath)
  1220. * @return {void}
  1221. */
  1222. async delFiles(fileList) {
  1223. if (fileList.length) {
  1224. for (const att of fileList) {
  1225. if (att.filepath && fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
  1226. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  1227. } else if (att.filepath) {
  1228. await this.ctx.app.fujianOss.delete(this.ctx.app.config.fujianOssFolder + att.filepath);
  1229. }
  1230. }
  1231. }
  1232. },
  1233. /**
  1234. * 匹配图片、pdf(用于预览)
  1235. * @param {String} ext 后缀名
  1236. * @return {Boolean} 匹配结果
  1237. */
  1238. canPreview(ext) {
  1239. const reg = /(.png)|(.gif)|(.txt)|(.jpg)|(.jpeg)|(.pdf)/i;
  1240. return reg.test(ext);
  1241. },
  1242. fileExtStr(ext) {
  1243. const ExtStr = [
  1244. { text: '图片', ext: ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.cad', '.dwg',] },
  1245. { text: '压缩包', ext: ['.zip', '.rar', '.7z',] },
  1246. { text: '音频', ext: ['.mp3'] },
  1247. { text: '视频', ext: ['.mp4'] },
  1248. { text: '文档', ext: ['.json', '.txt', '.xls', '.xlsx', '.doc', '.docx', '.pdf', '.ppt', '.pptx',]},
  1249. ];
  1250. for (const es of ExtStr) {
  1251. if (es.ext.indexOf(ext) >= 0) return es.text;
  1252. }
  1253. return '';
  1254. },
  1255. /**
  1256. * 查找数组中某个字符的个数
  1257. * @param {Array} array 数组
  1258. * @param {string} val 字符串
  1259. * @return {Boolean} 匹配结果
  1260. */
  1261. arrayCount(array, val) {
  1262. const counts = (arr, value) => arr.reduce((a, v) => { return value.indexOf(v) !== -1 ? a + 1 : a + 0; }, 0);
  1263. return counts(array, val);
  1264. },
  1265. filterTimesOrderData(data, keyFields, timesField, orderField, times, order) {
  1266. const dataIndex = {};
  1267. for (const d of data) {
  1268. if (d[timesField] > times || (d[timesField] = times && d[orderField] > order)) continue;
  1269. let key = 'd';
  1270. for (const kf of keyFields) {
  1271. key = key + '.' + (d[kf] || '');
  1272. }
  1273. const di = dataIndex[key];
  1274. if (di) {
  1275. if ((di[timesField] * timesLen + di[orderField]) < (d[timesField] * timesLen + d[orderField])) dataIndex[key] = d;
  1276. } else {
  1277. dataIndex[key] = d;
  1278. }
  1279. }
  1280. const result = [];
  1281. for (const prop in dataIndex) {
  1282. result.push(dataIndex[prop]);
  1283. }
  1284. return result;
  1285. },
  1286. filterLastestData(data, keyFields, timesField = 'times', orderField = 'order') {
  1287. const dataIndex = {};
  1288. for (const d of data) {
  1289. let key = 'd';
  1290. for (const kf of keyFields) {
  1291. key = key + '.' + (d[kf] || '');
  1292. }
  1293. const di = dataIndex[key];
  1294. if (di) {
  1295. if ((di[timesField] * timesLen + di[orderField]) < (d[timesField] * timesLen + d[orderField])) dataIndex[key] = d;
  1296. } else {
  1297. dataIndex[key] = d;
  1298. }
  1299. }
  1300. const result = [];
  1301. for (const prop in dataIndex) {
  1302. result.push(dataIndex[prop]);
  1303. }
  1304. return result;
  1305. },
  1306. filterLastestData2(data, keyFields, timesField = 'times', orderField = 'order') {
  1307. const dataIndex = {};
  1308. for (const d of data) {
  1309. let key = 'd';
  1310. for (const kf of keyFields) {
  1311. key = key + '.' + (d[kf] || '');
  1312. }
  1313. if (!dataIndex[key]) dataIndex[key] = { index: 0, source: [] };
  1314. const di = dataIndex[key];
  1315. const curIndex = d[timesField] * timesLen + d[orderField];
  1316. if (curIndex === di.index) {
  1317. di.source.push(d);
  1318. } else if (curIndex > di.index) {
  1319. di.index = curIndex;
  1320. di.source = [d];
  1321. }
  1322. }
  1323. const result = [];
  1324. for (const prop in dataIndex) {
  1325. result.push(...dataIndex[prop].source);
  1326. }
  1327. return result;
  1328. },
  1329. calcExpr(expr) {
  1330. const validExpr = expr.replace('=', '').replace(new RegExp('%', 'gm'), '/100');
  1331. return parseFloat(math.eval(validExpr));
  1332. },
  1333. /**
  1334. * 创建登录日志
  1335. * @return {Boolean} 日志是否创建成功
  1336. * @param {Number} type - 登录类型
  1337. * @param {Number} status - 是否显示记录
  1338. */
  1339. async getUserIPMsg() {
  1340. const { ctx } = this;
  1341. const ip = ctx.request.ip ? ctx.request.ip : '';
  1342. const ipInfo = await this.getIpInfoFromApi(ip);
  1343. const parser = new UAParser(ctx.header['user-agent']);
  1344. const osInfo = parser.getOS();
  1345. const cpuInfo = parser.getCPU();
  1346. const browserInfo = parser.getBrowser();
  1347. const ipMsg = {
  1348. os: `${osInfo.name} ${osInfo.version} ${cpuInfo.architecture}`,
  1349. browser: `${browserInfo.name} ${browserInfo.version}`,
  1350. ip,
  1351. address: ipInfo,
  1352. };
  1353. return ipMsg;
  1354. },
  1355. /**
  1356. * 根据ip请求获取详细地址
  1357. * @param {String} a_ip - ip地址
  1358. * @return {String} 详细地址
  1359. */
  1360. async getIpInfoFromApi(a_ip = '') {
  1361. if (!a_ip) return '';
  1362. if (a_ip === '127.0.0.1' || a_ip === '::1' || a_ip.indexOf('192.168') !== -1) return '服务器本机访问';
  1363. const { ip = '', region = '', city = '', isp = '' } = await this.sendIpRequest(a_ip);
  1364. let address = '';
  1365. region && (address += region + '省');
  1366. city && (address += city + '市 ');
  1367. isp && (address += isp + ' ');
  1368. ip && (address += `(${ip})`);
  1369. return address;
  1370. },
  1371. /**
  1372. * 发送请求获取详细地址
  1373. * @param {String} ip - ip地址
  1374. * @return {Object} the result of request
  1375. * @private
  1376. */
  1377. async sendIpRequest(ip) {
  1378. return new Promise(resolve => {
  1379. this.ctx.curl(`https://api01.aliyun.venuscn.com/ip?ip=${ip}`, {
  1380. dateType: 'json',
  1381. encoding: 'utf8',
  1382. timeout: 2000,
  1383. headers: {
  1384. Authorization: 'APPCODE 85c64bffe70445c4af9df7ae31c7bfcc',
  1385. },
  1386. }).then(({ status, data }) => {
  1387. if (status === 200) {
  1388. const result = JSON.parse(data.toString()).data;
  1389. if (!result.ip) {
  1390. resolve({});
  1391. } else {
  1392. resolve(result);
  1393. }
  1394. } else {
  1395. resolve({});
  1396. }
  1397. }).catch(() => {
  1398. resolve({});
  1399. });
  1400. });
  1401. },
  1402. /**
  1403. * 发送请求获取详细地址
  1404. * @param {String} type - 通知类型
  1405. * @param {String} datas - 请求发送数据
  1406. * @return {Object} the result of request
  1407. * @private
  1408. */
  1409. async syncNoticeSend(type, datas) {
  1410. const key = this.ctx.session.sessionProject.code;
  1411. const time = new Date().getTime();
  1412. const projectData = await this.ctx.service.project.getDataById(this.ctx.session.sessionProject.id);
  1413. const sign = crypto.createHash('md5').update(key + projectData.secret + time.toString()).digest('hex').toString();
  1414. const res = await this.ctx.curl(this.ctx.app.config.syncUrl + syncApiConst.api_url.notice, {
  1415. method: 'POST',
  1416. contentType: 'json',
  1417. data: {
  1418. projectCode: key,
  1419. key,
  1420. time,
  1421. sign,
  1422. customType: type,
  1423. base_data: datas,
  1424. },
  1425. dateType: 'json',
  1426. timeout: [30000, 60000],
  1427. timing: true,
  1428. });
  1429. },
  1430. async ossFileGet(path) {
  1431. // 判断开头是否带app,否则加上
  1432. if (!_.includes(path, 'app/') && !_.includes(path, 'sp/contract/') && !_.includes(path, 'sp/financial/')) {
  1433. path = 'app/' + path;
  1434. }
  1435. const result = await this.ctx.app.fujianOss.get(this.ctx.app.config.fujianOssFolder + path);
  1436. if (result.res.status !== 200) {
  1437. throw '该文件不存在';
  1438. }
  1439. return result.content;
  1440. },
  1441. getStartEndMonth(month) {
  1442. const startMonth = moment(month).startOf('month').format('YYYY-MM-DD HH:mm:ss');
  1443. const endMonth = moment(month).endOf('month').format('YYYY-MM-DD HH:mm:ss');
  1444. return [startMonth, endMonth];
  1445. },
  1446. /**
  1447. * 创建json web token
  1448. * @param {Object} data - 签名数据
  1449. * @return {String} token
  1450. */
  1451. createJWT(data) {
  1452. return jwt.sign({ data }, sign.managementApiSecretKey, { expiresIn: '15s' });
  1453. },
  1454. async loadLedgerDataFromOss(url) {
  1455. const File = await this.ctx.hisOss.get(this.ctx.hisOssPath + url);
  1456. if (File.res.status !== 200) return '获取修订台账有误';
  1457. const result = JSON.parse(File.content);
  1458. return result;
  1459. },
  1460. hpackArr(data) {
  1461. const keyIndex = {}, key = [];
  1462. const result = [];
  1463. for (const d of data) {
  1464. const r = [];
  1465. for (const prop in d) {
  1466. if (keyIndex[prop] === undefined) {
  1467. key.push(prop);
  1468. keyIndex[prop] = key.indexOf(prop);
  1469. }
  1470. r[keyIndex[prop]] = d[prop];
  1471. }
  1472. result.push(r);
  1473. }
  1474. if (result.length > 0) result.unshift(key);
  1475. return result;
  1476. },
  1477. // 把一个 xml 格式化成一个 json
  1478. async parseXML(xml) {
  1479. const result = await xml2js.parseStringPromise(xml, { trim: true });
  1480. return this.formatMessage(result.xml);
  1481. },
  1482. // 将xml2js解析出来的对象转换成直接可访问的对象
  1483. formatMessage(result) {
  1484. const message = {};
  1485. if (typeof result === 'object') {
  1486. for (const key in result) {
  1487. if (!(result[key] instanceof Array) || result[key].length === 0) {
  1488. continue;
  1489. }
  1490. if (result[key].length === 1) {
  1491. const val = result[key][0];
  1492. if (typeof val === 'object') {
  1493. message[key] = this.formatMessage(val);
  1494. } else {
  1495. message[key] = (val || '').trim();
  1496. }
  1497. } else {
  1498. message[key] = result[key].map(function(item) {
  1499. return this.formatMessage(item);
  1500. });
  1501. }
  1502. }
  1503. }
  1504. return message;
  1505. },
  1506. mapAllSubField(obj, field) {
  1507. const result = [];
  1508. for (const prop in obj) {
  1509. result.push(obj[prop][field]);
  1510. }
  1511. return result;
  1512. },
  1513. groupAuditors(auditors, orderField = 'order', noYb = false) {
  1514. auditors.sort((x, y) => {
  1515. return x[orderField] - y[orderField];
  1516. });
  1517. const newAuditors = noYb ? auditors.filter(x => { return x.audit_order !== 0; }) : auditors;
  1518. const Group = [];
  1519. for (const a of newAuditors) {
  1520. if (a[orderField] !== undefined) {
  1521. if (Group.length === 0) {
  1522. Group.push([a])
  1523. } else {
  1524. if (Group[Group.length-1][0][orderField] === a[orderField]) {
  1525. Group[Group.length-1].push(a);
  1526. } else {
  1527. Group.push([a]);
  1528. }
  1529. }
  1530. } else {
  1531. Group.push([a]);
  1532. }
  1533. }
  1534. return Group;
  1535. },
  1536. groupAuditorsUniq(group, key = 'audit_order') {
  1537. const uniqGroup = [];
  1538. for (const g of group) {
  1539. uniqGroup[g[0][key]] = g;
  1540. }
  1541. return uniqGroup.filter(x => { return !!x });
  1542. },
  1543. async getOssToken(oss) {
  1544. try {
  1545. const { STS } = require('ali-oss');
  1546. let sts = new STS({
  1547. accessKeyId: 'LTAI5tSoKgJ9Ze5VcgMQcM3m',
  1548. accessKeySecret: '34sj51AEUpeDzr5V6DYjrxWOatw7Zr',
  1549. });
  1550. const token = {
  1551. bucket: oss.options.bucket,
  1552. endpoint: this.ctx.app.config.fujianOssPath,
  1553. cname: true,
  1554. };
  1555. const result = await sts.assumeRole('acs:ram::31196920:role/oss-readonly', '', '3000', this.ctx.app.uuid.v4());
  1556. token.accessKeyId = result.credentials.AccessKeyId;
  1557. token.accessKeySecret = result.credentials.AccessKeySecret;
  1558. token.stsToken = result.credentials.SecurityToken;
  1559. return token;
  1560. } catch (err) {
  1561. console.log(err);
  1562. }
  1563. },
  1564. getQtySource(qty_source, no_qc_qty = 0) {
  1565. let qty = '';
  1566. switch (qty_source) {
  1567. case qtySourceValueConst.gather_qty: qty = '`gather_qty`'; break;
  1568. case qtySourceValueConst.contract_qty: qty = '`contract_qty`'; break;
  1569. case qtySourceValueConst.gather_minus_qty: qty = '(`gather_qty`+`qc_minus_qty`)'; break;
  1570. default: throw '未配置计量来源出错';
  1571. }
  1572. if (qty_source !== qtySourceValueConst.contract_qty && no_qc_qty) {
  1573. qty = '`contract_qty`';
  1574. }
  1575. return qty;
  1576. },
  1577. resetQtys(qtys) {
  1578. qtys.gather_qty = qtys.gather_qty ? qtys.gather_qty : null;
  1579. qtys.contract_qty = qtys.contract_qty ? qtys.contract_qty : null;
  1580. qtys.qc_qty = qtys.qc_qty ? qtys.qc_qty : null;
  1581. qtys.qc_minus_qty = qtys.qc_minus_qty ? qtys.qc_minus_qty : null;
  1582. return qtys;
  1583. },
  1584. contentChange(content) {
  1585. let str = content.replace(/【/g, '(');
  1586. str = str.replace(/】/g, ')');
  1587. str = str.replace(/工程款/g, '***');
  1588. str = str.length > 20 ? str.substring(0, 17) + '...' : str;
  1589. return str;
  1590. },
  1591. calculateNextSendTime(startTime, intervalHours = 6, quietStart = 0, quietEnd = 8) {
  1592. function parseTime(stime, timeStr, day = 0) {
  1593. const [hours, minutes] = timeStr.split(':').map(Number);
  1594. const date = new Date();
  1595. date.setFullYear(stime.getFullYear());
  1596. date.setMonth(stime.getMonth());
  1597. date.setDate(stime.getDate() + day);
  1598. date.setHours(hours, minutes, 0, 0); // Set hours and minutes, reset seconds and milliseconds
  1599. return date;
  1600. }
  1601. function calculateHoursBetween(start, end) {
  1602. // 将时间字符串转换为 Date 对象
  1603. const startTime = new Date(`2000-01-01T${start}`);
  1604. const endTime = new Date(`2000-01-01T${end}`);
  1605. // 检查是否跨越了当前日期和隔天日期
  1606. if (endTime < startTime) {
  1607. endTime.setDate(endTime.getDate() + 1); // 将结束时间调整到隔天
  1608. }
  1609. // 计算两个时间之间的毫秒数差距
  1610. const timeDifference = endTime - startTime;
  1611. // 将毫秒数转换为小时并返回
  1612. const hours = timeDifference / (1000 * 60 * 60);
  1613. return 24 - hours;
  1614. }
  1615. // let startDateTime = parseTime(startTime);
  1616. let startDateTime = startTime;
  1617. let endDateTime = new Date(startDateTime.getTime() + intervalHours * 60 * 60 * 1000);
  1618. if (quietStart && quietEnd) {
  1619. quietStart = (quietStart < 10 ? '0' + quietStart : quietStart) + ':00';
  1620. quietEnd = (quietEnd < 10 ? '0' + quietEnd : quietEnd) + ':00';
  1621. let quietStartDateTime = parseTime(startDateTime, quietStart);
  1622. let quietEndDateTime = parseTime(startDateTime, quietEnd);
  1623. if (quietEndDateTime <= quietStartDateTime) {
  1624. quietEndDateTime.setDate(quietEndDateTime.getDate() + 1);
  1625. }
  1626. // 判断非屏蔽时间内是否大于间隔时间,大于则要再隔天发送
  1627. const hours = calculateHoursBetween(quietStart, quietEnd);
  1628. if (hours < intervalHours) {
  1629. // 除法算出差的天数
  1630. const days = Math.floor(intervalHours / hours);
  1631. quietStartDateTime = parseTime(startDateTime, quietStart, days);
  1632. quietEndDateTime = parseTime(startDateTime, quietEnd, days);
  1633. intervalHours %= hours;
  1634. startDateTime.setDate(startDateTime.getDate() + days);
  1635. } else if (startDateTime >= quietEndDateTime) {
  1636. quietStartDateTime = parseTime(startDateTime, quietStart, 1);
  1637. }
  1638. if (quietEndDateTime <= quietStartDateTime) {
  1639. quietEndDateTime.setDate(quietEndDateTime.getDate() + 1);
  1640. }
  1641. if (startDateTime >= quietStartDateTime) {
  1642. startDateTime = quietEndDateTime;
  1643. }
  1644. endDateTime = new Date(startDateTime.getTime() + intervalHours * 60 * 60 * 1000);
  1645. if (endDateTime >= quietStartDateTime && endDateTime < quietEndDateTime) {
  1646. const timeIntoQuiet = (quietStartDateTime - startDateTime) / (60 * 60 * 1000);
  1647. const remainingTime = intervalHours - timeIntoQuiet;
  1648. endDateTime = new Date(quietEndDateTime.getTime() + remainingTime * 60 * 60 * 1000);
  1649. }
  1650. }
  1651. // return endDateTime.getHours().toString().padStart(2, '0') + ':' +
  1652. // endDateTime.getMinutes().toString().padStart(2, '0');
  1653. return endDateTime;
  1654. },
  1655. showCol4ObjArray(objArray, colName, key = 'value', showKey = 'name') {
  1656. if (!colName) return '';
  1657. const info = _.find(objArray, { [key]: colName });
  1658. return info ? info[showKey] : '';
  1659. },
  1660. getTimePeriod() {
  1661. const hour = new Date().getHours();
  1662. if (hour >= 6 && hour < 12) {
  1663. return '上午';
  1664. } else if (hour >= 12 && hour < 14) {
  1665. return '中午';
  1666. } else if (hour >= 14 && hour < 18) {
  1667. return '下午';
  1668. }
  1669. return '晚上';
  1670. },
  1671. calculateDaysBetween(end, start) {
  1672. // 两个时间比较并得出相差天数,取整不考虑时分秒
  1673. if (!start) return 0;
  1674. const startDateTime = new Date(start);
  1675. const endDateTime = new Date(end);
  1676. const timeDifference = endDateTime - startDateTime;
  1677. return Math.floor(timeDifference / (1000 * 60 * 60 * 24));
  1678. },
  1679. addKeyValue4ObjArray(objArray, key, value) {
  1680. return objArray.map(item => {
  1681. item[key] = value;
  1682. return item;
  1683. });
  1684. },
  1685. };