helper.js 60 KB

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