| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737 | 
							- 'use strict';
 
- /**
 
-  * 辅助方法扩展
 
-  *
 
-  * @author CaiAoLin
 
-  * @date 2017/9/28
 
-  * @version
 
-  */
 
- const moment = require('moment');
 
- const zeroRange = 0.0000000001;
 
- const fs = require('fs');
 
- const path = require('path');
 
- const streamToArray = require('stream-to-array');
 
- const _ = require('lodash');
 
- const bc = require('../lib/base_calc.js');
 
- const Decimal = require('decimal.js');
 
- Decimal.set({ precision: 50, defaults: true });
 
- const SMS = require('../lib/sms');
 
- const WX = require('../lib/wechat');
 
- const timesLen = 100;
 
- const UAParser = require('ua-parser-js');
 
- const math = require('mathjs');
 
- const syncApiConst = require('../const/sync_api');
 
- const crypto = require('crypto');
 
- const jwt = require('jsonwebtoken');
 
- const sign = require('../const/sign');
 
- const xml2js = require('xml2js');
 
- const qtySourceValueConst = require('../const/material').qty_source_value;
 
- module.exports = {
 
-     _,
 
-     /**
 
-      * 生成随机字符串
 
-      *
 
-      * @param {Number} length - 需要生成字符串的长度
 
-      * @param {Number} type - 1为数字和字符 2为纯数字 3为纯字母
 
-      * @return {String} - 返回生成结果
 
-      */
 
-     generateRandomString(length, type = 1) {
 
-         length = parseInt(length);
 
-         length = isNaN(length) ? 1 : length;
 
-         let randSeed = [];
 
-         let numberSeed = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
 
-         let stringSeed = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
 
-             'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
 
-             'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
 
-         switch (type) {
 
-             case 1:
 
-                 randSeed = stringSeed.concat(numberSeed);
 
-                 stringSeed = numberSeed = null;
 
-                 break;
 
-             case 2:
 
-                 randSeed = numberSeed;
 
-                 break;
 
-             case 3:
 
-                 randSeed = stringSeed;
 
-                 break;
 
-             default:
 
-                 break;
 
-         }
 
-         const seedLength = randSeed.length - 1;
 
-         let result = '';
 
-         for (let i = 0; i < length; i++) {
 
-             const index = Math.ceil(Math.random() * seedLength);
 
-             result += randSeed[index];
 
-         }
 
-         return result;
 
-     },
 
-     /**
 
-      * 字节转换
 
-      * @param {number} bytes - 字节
 
-      * @return {string} - 大小
 
-      */
 
-     bytesToSize(bytes) {
 
-         if (parseInt(bytes) === 0) return '0 B';
 
-         const k = 1024;
 
-         const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
 
-         const i = Math.floor(Math.log(bytes) / Math.log(k));
 
-         // return (bytes / Math.pow(k, i)) + ' ' + sizes[i];
 
-         return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
 
-     },
 
-     sizeToBytes(size) {
 
-         const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
 
-         const sizesConverse = sizes.reverse();
 
-         let index, matchSize;
 
-         for (const [i, s] of sizesConverse.entries()) {
 
-             if (size.indexOf(s) > 0) {
 
-                 matchSize = s;
 
-                 index = sizes.length - i;
 
-                 break;
 
-             }
 
-         }
 
-         const num = parseFloat(_.trim(size.replace(matchSize, '')));
 
-         const k = 1024;
 
-         return Math.ceil(num * Math.pow(k, index - 1));
 
-     },
 
-     /**
 
-      * 浮点乘法计算
 
-      * @param {number} arg1 - 乘数
 
-      * @param {number} arg2 - 被乘数
 
-      * @return {string} - 结果
 
-      */
 
-     accMul(arg1, arg2) {
 
-         if (arg1 === '' || arg1 === null || arg1 === undefined || arg2 === '' || arg2 === null || arg2 === undefined) {
 
-             return '';
 
-         }
 
-         let m = 0;
 
-         const s1 = arg1.toString();
 
-         const s2 = arg2.toString();
 
-         try {
 
-             m += s1.split('.')[1] !== undefined ? s1.split('.')[1].length : 0;
 
-         } catch (e) {
 
-             throw e;
 
-         }
 
-         try {
 
-             m += s2.split('.')[1] !== undefined ? s2.split('.')[1].length : 0;
 
-         } catch (e) {
 
-             throw e;
 
-         }
 
-         return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m);
 
-     },
 
-     accAdd(arg1, arg2) {
 
-         let r1;
 
-         let r2;
 
-         try {
 
-             r1 = arg1.toString().split('.')[1].length;
 
-         } catch (e) {
 
-             r1 = 0;
 
-         }
 
-         try {
 
-             r2 = arg2.toString().split('.')[1].length;
 
-         } catch (e) {
 
-             r2 = 0;
 
-         }
 
-         const c = Math.abs(r1 - r2);
 
-         const m = Math.pow(10, Math.max(r1, r2));
 
-         if (c > 0) {
 
-             const cm = Math.pow(10, c);
 
-             if (r1 > r2) {
 
-                 arg1 = Number(arg1.toString().replace('.', ''));
 
-                 arg2 = Number(arg2.toString().replace('.', '')) * cm;
 
-             } else {
 
-                 arg1 = Number(arg1.toString().replace('.', '')) * cm;
 
-                 arg2 = Number(arg2.toString().replace('.', ''));
 
-             }
 
-         } else {
 
-             arg1 = Number(arg1.toString().replace('.', ''));
 
-             arg2 = Number(arg2.toString().replace('.', ''));
 
-         }
 
-         return (arg1 + arg2) / m;
 
-     },
 
-     // 四舍五入或末尾加零,实现类似php的 sprintf("%.".decimal."f", val);
 
-     roundNum(val, decimals) {
 
-         if (val === '' || val === null) {
 
-             return '';
 
-         }
 
-         if (val !== '') {
 
-             val = parseFloat(val);
 
-             if (decimals < 1) {
 
-                 val = (Math.round(val)).toString();
 
-             } else {
 
-                 const num = val.toString();
 
-                 if (num.lastIndexOf('.') === -1) {
 
-                     // num += '.';
 
-                     // num += this.makezero(decimals);
 
-                     val = num;
 
-                 } else {
 
-                     const valdecimals = num.split('.')[1].length;
 
-                     if (parseInt(valdecimals) < parseInt(decimals)) {
 
-                         // num += this.makezero(parseInt(decimals) - parseInt(valdecimals));
 
-                         val = num;
 
-                     } else if (parseInt(valdecimals) > parseInt(decimals)) {
 
-                         val = parseFloat(val) !== 0 ? Math.round(this.accMul(val, this.makemultiple(decimals))) / this.makemultiple(decimals) : this.makedecimalzero(decimals);
 
-                         const num = val.toString();
 
-                         if (num.lastIndexOf('.') === -1) {
 
-                             // num += '.';
 
-                             // num += this.makezero(decimals);
 
-                             val = num;
 
-                         } else {
 
-                             const valdecimals = num.split('.')[1].length;
 
-                             if (parseInt(valdecimals) < parseInt(decimals)) {
 
-                                 // num += this.makezero(parseInt(decimals) - parseInt(valdecimals));
 
-                                 val = num;
 
-                             }
 
-                         }
 
-                     }
 
-                 }
 
-             }
 
-         }
 
-         return val;
 
-     },
 
-     // 生成num位的0
 
-     makezero(num) {
 
-         const arr = new Array(num);
 
-         for (let i = 0; i < num; i++) {
 
-             arr[i] = 0;
 
-         }
 
-         return arr.join('');
 
-     },
 
-     // 生成num位的10倍数
 
-     makemultiple(num) {
 
-         return Math.pow(10, parseInt(num));
 
-     },
 
-     // 根据单位获取小数位数
 
-     findDecimal(unit) {
 
-         let value = 3;
 
-         if (unit !== '') {
 
-             value = this.ctx.tender.info.precision.other.value;
 
-             const changeUnits = this.ctx.tender.info.precision;
 
-             for (const d in changeUnits) {
 
-                 if (changeUnits[d].unit !== undefined && changeUnits[d].unit === unit) {
 
-                     value = changeUnits[d].value;
 
-                     break;
 
-                 }
 
-             }
 
-         }
 
-         return value;
 
-     },
 
-     /**
 
-      * 显示排序符号
 
-      *
 
-      * @param {String} field - 字段名称
 
-      * @return {String} - 返回字段排序的符号
 
-      */
 
-     showSortFlag(field) {
 
-         const sort = this.ctx.sort;
 
-         if (!(sort instanceof Array) || sort.length !== 2) {
 
-             return '';
 
-         }
 
-         sort[1] = sort[1].toUpperCase();
 
-         return (sort[0] === field && sort[1] === 'DESC') ? '' : '-';
 
-     },
 
-     /**
 
-      * 判断是否为ajax请求
 
-      *
 
-      * @param {Object} request - 请求数据
 
-      * @return {boolean} 判断结果
 
-      */
 
-     isAjax(request) {
 
-         let headerInfo = request.headers['x-requested-with'] === undefined ? '' : request.headers['x-requested-with'];
 
-         headerInfo = headerInfo.toLowerCase();
 
-         return headerInfo === 'xmlhttprequest';
 
-     },
 
-     /**
 
-      * 模拟发送请求
 
-      *
 
-      * @param {String} url - 请求地址
 
-      * @param {Object} data - 请求数据
 
-      * @param {String} type - 请求类型(POST) POST | GET
 
-      * @param {String} dataType - 数据类型 json|text
 
-      * @return {Object} - 请求结果
 
-      */
 
-     async sendRequest(url, data, type = 'POST', dataType = 'json') {
 
-         // 发起请求
 
-         try {
 
-             const response = await this.ctx.curl(url, {
 
-                 method: type,
 
-                 data,
 
-                 dataType,
 
-             });
 
-             if (response.status !== 200) {
 
-                 throw '请求失败';
 
-             }
 
-             return response.data;
 
-         } catch (err) {
 
-             throw '请求失败';
 
-         }
 
-     },
 
-     /**
 
-      * 模拟多次发送请求(失败后再获取)
 
-      *
 
-      * @param {String} url - 请求地址
 
-      * @param {Object} data - 失败请求次数
 
-      * @param {String} type - 请求类型(POST) POST | GET
 
-      * @param {String} dataType - 数据类型 json|text
 
-      * @param {String} count - 重复次数
 
-      * @return {Object} - 请求结果
 
-      */
 
-     async sendMoreRequest(url, data = null, type = 'POST', dataType = 'json', count = 3) {
 
-         // 发起请求
 
-         try {
 
-             let response = data ? await this.ctx.curl(url, {
 
-                 method: type,
 
-                 data,
 
-                 dataType,
 
-             }) : await this.ctx.curl(url);
 
-             if (response.status !== 200) {
 
-                 if (count > 0) {
 
-                     count = count - 1;
 
-                     response = await this.sendMoreRequest(url, data, type, dataType, count);
 
-                 } else {
 
-                     throw '请求失败';
 
-                 }
 
-             }
 
-             return response.data;
 
-         } catch (err) {
 
-             throw '请求失败';
 
-         }
 
-     },
 
-     /**
 
-      * 深度验证数据
 
-      *
 
-      * @param {Object} rule - 数据规则
 
-      * @return {void}
 
-      */
 
-     validate(rule) {
 
-         // 先用内置的验证器验证数据
 
-         this.ctx.validate(rule);
 
-         // 然后再验证是否有多余的数据
 
-         const postData = this.ctx.request.body;
 
-         delete postData._csrf_j;
 
-         const postDataKey = Object.keys(postData);
 
-         const ruleKey = Object.keys(rule);
 
-         // 自动增加字段则填充上,以防判断出错
 
-         if (postData.create_time !== undefined) {
 
-             ruleKey.push('create_time');
 
-         }
 
-         for (const tmp of postDataKey) {
 
-             // 规则里面没有定义则抛出异常
 
-             if (ruleKey.indexOf(tmp) < 0) {
 
-                 throw '参数不正确';
 
-             }
 
-         }
 
-     },
 
-     /**
 
-      * 拆分path
 
-      *
 
-      * @param {String|Array} paths - 拆分字符
 
-      * @param {String} symbol - 拆分符号
 
-      * @return {Array} - 拆分结果
 
-      */
 
-     explodePath(paths, symbol = '-') {
 
-         const result = [];
 
-         paths = paths instanceof Array ? paths : [paths];
 
-         for (const path of paths) {
 
-             // 拆分数据
 
-             const pathArray = path.split(symbol);
 
-             // 用户缓存循环的数据
 
-             const tmpArray = [];
 
-             for (const tmp of pathArray) {
 
-                 // 每次循环都追加一个数据进去
 
-                 tmpArray.push(tmp);
 
-                 const tmpPathString = tmpArray.join(symbol);
 
-                 // 判断是否已经存在有对应数据
 
-                 if (result.indexOf(tmpPathString) >= 0) {
 
-                     continue;
 
-                 }
 
-                 result.push(tmpPathString);
 
-             }
 
-         }
 
-         return result;
 
-     },
 
-     /**
 
-      * 基于obj, 拷贝sObj中的内容
 
-      * obj = {a: 1, b: 2}, sObj = {a: 0, c: 3}, 返回{a: 0, b: 2, c: 3}
 
-      * @param obj
 
-      * @param sObj
 
-      * @return {any}
 
-      */
 
-     updateObj(obj, sObj) {
 
-         if (!obj) {
 
-             return JSON.parse(JSON.stringify(sObj));
 
-         }
 
-         const result = JSON.parse(JSON.stringify(obj));
 
-         if (sObj) {
 
-             for (const prop in sObj) {
 
-                 result[prop] = sObj[prop];
 
-             }
 
-         }
 
-         return result;
 
-     },
 
-     /**
 
-      * 在数组中查找
 
-      * @param {Array} arr
 
-      * @param name -
 
-      * @param value
 
-      * @return {*}
 
-      */
 
-     findData(arr, name, value) {
 
-         if (!arr instanceof Array) {
 
-             throw '该方法仅用于数组查找';
 
-         }
 
-         if (arr.length === 0) { return undefined; }
 
-         for (const data of arr) {
 
-             if (data[name] == value) {
 
-                 return data;
 
-             }
 
-         }
 
-         return undefined;
 
-     },
 
-     /**
 
-      * 检查数字是否为0
 
-      * @param {Number} value
 
-      * @return {boolean}
 
-      */
 
-     checkZero(value) {
 
-         return value === undefined || value === null || (this._.isNumber(value) && Math.abs(value) < zeroRange);
 
-     },
 
-     /**
 
-      * 检查数字是否相等
 
-      * @param {Number} value1
 
-      * @param {Number} value2
 
-      * @return {boolean}
 
-      */
 
-     numEqual(value1, value2) {
 
-         if (value1 && value2) {
 
-             return Math.abs(value2 - value1) < zeroRange;
 
-         }
 
-         return (!value1 && !value2);
 
-     },
 
-     /**
 
-      * 比较编码
 
-      * @param str1
 
-      * @param str2
 
-      * @param symbol
 
-      * @return {number}
 
-      */
 
-     compareCode(str1, str2, symbol = '-') {
 
-         if (!str1) {
 
-             return 1;
 
-         } else if (!str2) {
 
-             return -1;
 
-         }
 
-         const numReg = /^[0-9]+$/;
 
-         function compareSubCode(code1, code2) {
 
-             if (numReg.test(code1)) {
 
-                 if (numReg.test(code2)) {
 
-                     return parseInt(code1) - parseInt(code2);
 
-                 }
 
-                 return -1;
 
-             }
 
-             if (numReg.test(code2)) {
 
-                 return 1;
 
-             }
 
-             return code1 === code2 ? 0 : (code1 < code2 ? -1 : 1); // code1.localeCompare(code2);
 
-         }
 
-         const aCodes = str1.split(symbol),
 
-             bCodes = str2.split(symbol);
 
-         for (let i = 0, iLength = Math.min(aCodes.length, bCodes.length); i < iLength; ++i) {
 
-             const iCompare = compareSubCode(aCodes[i], bCodes[i]);
 
-             if (iCompare !== 0) {
 
-                 return iCompare;
 
-             }
 
-         }
 
-         return aCodes.length - bCodes.length;
 
-     },
 
-     /**
 
-      * 根据 清单编号 获取 章级编号
 
-      * @param code
 
-      * @param symbol
 
-      * @return {string}
 
-      */
 
-     getChapterCode(code, symbol = '-') {
 
-         if (!code || code === '') return '';
 
-         const codePath = code.split(symbol);
 
-         const reg = /^[^0-9]*[0-9]{3,4}$/;
 
-         if (reg.test(codePath[0])) {
 
-             const numReg = /[0-9]{3,4}$/;
 
-             const result = codePath[0].match(numReg);
 
-             const num = parseInt(result[0]);
 
-             return this.mul(this.div(num, 100, 0), 100) + '';
 
-         }
 
-         return '10000';
 
-     },
 
-     /**
 
-      * 树结构节点排序,要求最顶层节点须在同一父节点下
 
-      * @param treeNodes
 
-      * @param idField
 
-      * @param pidField
 
-      */
 
-     sortTreeNodes(treeNodes, idField, pidField) {
 
-         const result = [];
 
-         const getFirstLevel = function(nodes) {
 
-             let result;
 
-             for (const node of nodes) {
 
-                 if (!result || result > node.level) {
 
-                     result = node.level;
 
-                 }
 
-             }
 
-             return result;
 
-         };
 
-         const getLevelNodes = function(nodes, level) {
 
-             const children = nodes.filter(function(a) {
 
-                 return a.level = level;
 
-             });
 
-             children.sort(function(a, b) {
 
-                 return a.order - b.order;
 
-             });
 
-             return children;
 
-         };
 
-         const getChildren = function(nodes, node) {
 
-             const children = nodes.filter(function(a) {
 
-                 return a[pidField] = node[idField];
 
-             });
 
-             children.sort(function(a, b) {
 
-                 return a.order - b.order;
 
-             });
 
-             return children;
 
-         };
 
-         const addSortNodes = function(nodes) {
 
-             for (let i = 0; i < nodes.length; i++) {
 
-                 result.push(nodes[i]);
 
-                 addSortNodes(getChildren(nodes[i]));
 
-             }
 
-         };
 
-         const firstLevel = getFirstLevel(treeNodes);
 
-         addSortNodes(getLevelNodes(treeNodes, firstLevel));
 
-     },
 
-     /**
 
-      * 判断当前用户是否有指定权限
 
-      *
 
-      * @param {Number|Array} permission - 权限id
 
-      * @return {Boolean} - 返回判断结果
 
-      */
 
-     hasPermission(permission) {
 
-         let result = false;
 
-         try {
 
-             const sessionUser = this.ctx.session.sessionUser;
 
-             if (sessionUser.permission === undefined) {
 
-                 throw '不存在权限数据';
 
-             }
 
-             let currentPermission = sessionUser.permission;
 
-             if (currentPermission === '') {
 
-                 throw '权限数据为空';
 
-             }
 
-             // 管理员则直接返回结果
 
-             if (currentPermission === 'all') {
 
-                 return true;
 
-             }
 
-             currentPermission = currentPermission.split(',');
 
-             permission = permission instanceof Array ? permission : [permission];
 
-             let counter = 0;
 
-             for (const tmp of permission) {
 
-                 if (currentPermission[tmp] !== undefined) {
 
-                     counter++;
 
-                 }
 
-             }
 
-             result = counter === permission.length;
 
-         } catch (error) {
 
-             result = false;
 
-         }
 
-         return result;
 
-     },
 
-     /**
 
-      * 递归创建文件夹(fs.mkdirSync需要上一层文件夹已存在)
 
-      * @param pathName
 
-      * @return {Promise<void>}
 
-      */
 
-     async recursiveMkdirSync(pathName) {
 
-         if (!fs.existsSync(pathName)) {
 
-             const upperPath = path.dirname(pathName);
 
-             if (!fs.existsSync(upperPath)) {
 
-                 await this.recursiveMkdirSync(upperPath);
 
-             }
 
-             await fs.mkdirSync(pathName);
 
-         }
 
-     },
 
-     /**
 
-      * 字节 保存至 本地文件
 
-      * @param buffer - 字节
 
-      * @param fileName - 文件名
 
-      * @return {Promise<void>}
 
-      */
 
-     async saveBufferFile(buffer, fileName) {
 
-         // 检查文件夹是否存在,不存在则直接创建文件夹
 
-         const pathName = path.dirname(fileName);
 
-         if (!fs.existsSync(pathName)) {
 
-             await this.recursiveMkdirSync(pathName);
 
-         }
 
-         await fs.writeFileSync(fileName, buffer);
 
-     },
 
-     /**
 
-      * 将文件流的数据保存至本地文件
 
-      * @param stream
 
-      * @param fileName
 
-      * @return {Promise<void>}
 
-      */
 
-     async saveStreamFile(stream, fileName) {
 
-         // 读取字节流
 
-         const parts = await streamToArray(stream);
 
-         // 转化为buffer
 
-         const buffer = Buffer.concat(parts);
 
-         // 写入文件
 
-         await this.saveBufferFile(buffer, fileName);
 
-     },
 
-     async copyFileSync(source, target) {
 
-         const pathName = path.dirname(target);
 
-         if (!fs.existsSync(pathName)) {
 
-             await this.recursiveMkdirSync(pathName);
 
-         }
 
-         await fs.copyFileSync(source, target);
 
-     },
 
-     /**
 
-      * 检查code是否是指标模板数据
 
-      * @param {String} code
 
-      * @return {boolean}
 
-      */
 
-     validBillsCode(code) {
 
-         const reg1 = /(^[0-9]+)([a-z0-9\-]*)/i;
 
-         const reg2 = /([a-z0-9]+$)/i;
 
-         return reg1.test(code) && reg2.test(code);
 
-     },
 
-     getNumberFormatter(decimal) {
 
-         if (decimal <= 0) {
 
-             return '0';
 
-         }
 
-         let pre = '0.';
 
-         for (let i = 0; i < decimal; i++) {
 
-             pre += '#';
 
-         }
 
-         return pre;
 
-     },
 
-     /**
 
-      * 根据单位查找对应的清单精度
 
-      * @param {tenderInfo.precision} list - 清单精度列表
 
-      * @param {String} unit - 单位
 
-      * @return {number}
 
-      */
 
-     findPrecision(list, unit) {
 
-         if (unit) {
 
-             for (const p in list) {
 
-                 if (list[p].unit && list[p].unit === unit) {
 
-                     return list[p];
 
-                 }
 
-             }
 
-         }
 
-         return list.other;
 
-     },
 
-     /**
 
-      * 检查数据中的精度
 
-      * @param {Object} Obj - 检查的数据
 
-      * @param {Array} fields - 检查的属性
 
-      * @param {Number} precision - 精度
 
-      * @class
 
-      */
 
-     checkFieldPrecision(Obj, fields, precision = 2) {
 
-         if (Obj) {
 
-             for (const field of fields) {
 
-                 if (Obj[field]) {
 
-                     Obj[field] = this.round(Obj[field], precision);
 
-                 }
 
-             }
 
-         }
 
-     },
 
-     checkDgnQtyPrecision(data, precision = 3) {
 
-         const datas = data instanceof Array ? data : [data];
 
-         for (const d of datas) {
 
-             for (const prop in d) {
 
-                 if (prop.indexOf('dgn_qty') >= 0) d[prop] = this.round(d[prop], precision);
 
-             }
 
-         }
 
-     },
 
-     /**
 
-      * 过滤无效数据
 
-      *
 
-      * @param obj
 
-      * @param fields - 有效数据的数组
 
-      */
 
-     filterValidFields(data, fields) {
 
-         if (data) {
 
-             const result = {};
 
-             for (const prop in data) {
 
-                 if (fields.indexOf(prop) !== -1) {
 
-                     result[prop] = data[prop];
 
-                 }
 
-             }
 
-             return result;
 
-         }
 
-         return data;
 
-     },
 
-     // 加减乘除方法,为方便调用,兼容num为空的情况
 
-     // 加减法使用base_calc,乘除法使用Decimal(原因详见demo/calc_test)
 
-     /**
 
-      * 加法 num1 + num2
 
-      * @param num1
 
-      * @param num2
 
-      * @return {number}
 
-      */
 
-     add(num1, num2) {
 
-         return bc.add(num1 ? num1 : 0, num2 ? num2 : 0);
 
-     },
 
-     /**
 
-      * 减法 num1 - num2
 
-      * @param num1
 
-      * @param num2
 
-      * @return {number}
 
-      */
 
-     sub(num1, num2) {
 
-         return bc.sub(num1 ? num1 : 0, num2 ? num2 : 0);
 
-     },
 
-     /**
 
-      * 乘法 num1 * num2
 
-      * @param num1
 
-      * @param num2
 
-      * @return {*}
 
-      */
 
-     mul(num1, num2, digit = 6) {
 
-         if (num1 === '' || num1 === null || num2 === '' || num2 === null) {
 
-             return 0;
 
-         }
 
-         return Decimal.mul(num1 ? num1 : 0, num2 ? num2 : 0).toDecimalPlaces(digit).toNumber();
 
-     },
 
-     /**
 
-      * 除法 num1 / num2
 
-      * @param num1 - 被除数
 
-      * @param num2 - 除数
 
-      * @return {*}
 
-      */
 
-     div(num1, num2, digit = 6) {
 
-         if (num2 && !this.checkZero(num2)) {
 
-             return Decimal.div(num1 ? num1 : 0, num2).toDecimalPlaces(digit).toNumber();
 
-         }
 
-         return null;
 
-     },
 
-     /**
 
-      * 四舍五入(统一,方便以后万一需要置换)
 
-      * @param {Number} value - 舍入的数字
 
-      * @param {Number} decimal - 要保留的小数位数
 
-      * @return {*}
 
-      */
 
-     round(value, decimal) {
 
-         return value ? new Decimal(value.toString()).toDecimalPlaces(decimal).toNumber() : 0;
 
-     },
 
-     /**
 
-      * 汇总
 
-      * @param array
 
-      * @return {number}
 
-      */
 
-     sum(array) {
 
-         let result = 0;
 
-         for (const a of array) {
 
-             result = this.add(result, a);
 
-         }
 
-         return result;
 
-     },
 
-     /**
 
-      * 使用正则替换字符
 
-      * @param str
 
-      * @param reg
 
-      * @param subStr
 
-      * @return {*}
 
-      */
 
-     replaceStr(str, reg, subStr) {
 
-         return str ? str.replace(reg, subStr) : str;
 
-     },
 
-     /**
 
-      * 替换字符串中的 换行符回车符
 
-      * @param str
 
-      * @return {*}
 
-      */
 
-     replaceReturn(str) {
 
-         // return str
 
-         //     ? (typeof str === 'string') ? str.replace(/[\r\n]/g, '') : str + ''
 
-         //     : str;
 
-         return (str && typeof str === 'string')
 
-             ? str.replace(/[\r\n]/g, '')
 
-             : !_.isNil(str) ? str + '' : str;
 
-     },
 
-     /**
 
-      * 替换字符串中的 换行符回车符为换行符<br>
 
-      * @param str
 
-      * @return {*}
 
-      */
 
-     replaceRntoBr(str) {
 
-         // return str
 
-         //     ? (typeof str === 'string') ? str.replace(/[\r\n]/g, '') : str + ''
 
-         //     : str;
 
-         return (str && typeof str === 'string')
 
-             ? str.replace(/[\r\n]/g, '<br>')
 
-             : !_.isNil(str) ? str + '' : str;
 
-     },
 
-     /**
 
-      * 获取 字符串 数组的 mysql 筛选条件
 
-      *
 
-      * @param arr
 
-      * @return {*}
 
-      */
 
-     getInArrStrSqlFilter(arr) {
 
-         let result = '';
 
-         for (const a of arr) {
 
-             if (result !== '') {
 
-                 result = result + ',';
 
-             }
 
-             result = result + this.ctx.app.mysql.escape(a);
 
-         }
 
-         return result;
 
-     },
 
-     /**
 
-      * 合并 相关数据
 
-      * @param {Array} main - 主数据
 
-      * @param {Array[]}rela - 相关数据 {data, fields, prefix, relaId}
 
-      */
 
-     assignRelaData(main, rela, mainKey = 'id') {
 
-         const index = {},
 
-             indexPre = 'id_';
 
-         const loadFields = function(datas, fields, prefix, relaId) {
 
-             for (const d of datas) {
 
-                 const key = indexPre + d[relaId];
 
-                 const m = index[key];
 
-                 if (m) {
 
-                     for (const f of fields) {
 
-                         if (d[f] !== undefined) {
 
-                             m[prefix + f] = d[f];
 
-                         }
 
-                     }
 
-                 }
 
-             }
 
-         };
 
-         for (const m of main) {
 
-             index[indexPre + m[mainKey]] = m;
 
-             for (const r of rela) {
 
-                 if (r.defaultData) _.assignIn(m, r.defaultData);
 
-             }
 
-         }
 
-         for (const r of rela) {
 
-             loadFields(r.data, r.fields, r.prefix, r.relaId);
 
-         }
 
-     },
 
-     /**
 
-      * 合并(并汇总) 相关数据
 
-      * @param {Array} main - 主数据
 
-      * @param {Array[]}rela - 相关数据 {data, fields, relaField}
 
-      *
 
-      * { data, fields}
 
-      */
 
-     assignSumRelaData(main, keyField, rela) {
 
-         const index = {},
 
-             indexPre = 'id_';
 
-         const addFun = this.add;
 
-         const loadFields = function(datas, fields, relaId) {
 
-             for (const d of datas) {
 
-                 const key = indexPre + d[relaId];
 
-                 const m = index[key];
 
-                 if (!m) continue;
 
-                 for (const f of fields) {
 
-                     if (d[f.source]) m[f.target] = addFun(m[f.target], d[f.source]);
 
-                 }
 
-             }
 
-         };
 
-         for (const m of main) {
 
-             index[indexPre + m[keyField]] = m;
 
-         }
 
-         for (const r of rela) {
 
-             loadFields(r.data, r.fields, r.relaField);
 
-         }
 
-     },
 
-     whereSql(where, as) {
 
-         if (!where) {
 
-             return '';
 
-         }
 
-         const wheres = [];
 
-         const values = [];
 
-         for (const key in where) {
 
-             const value = where[key];
 
-             if (Array.isArray(value)) {
 
-                 wheres.push('?? IN (?)');
 
-             } else {
 
-                 wheres.push('?? = ?');
 
-             }
 
-             values.push((as && as !== '') ? as + '.' + key : key);
 
-             values.push(value);
 
-         }
 
-         if (wheres.length > 0) {
 
-             return this.ctx.app.mysql.format(' WHERE ' + wheres.join(' AND '), values);
 
-         }
 
-         return '';
 
-     },
 
-     formatMoney(s = 0, dot = ',', decimal = 2) {
 
-         if (!s) {
 
-             s = 0;
 
-             return s.toFixed(decimal);
 
-         }
 
-         s = parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(decimal) + '';
 
-         if (!decimal) {
 
-             s += '.';
 
-         }
 
-         const l = s.split('.')[0].split('').reverse(),
 
-             r = s.split('.')[1];
 
-         let t = '';
 
-         for (let i = 0; i < l.length; i++) {
 
-             t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? dot : '');
 
-         }
 
-         const num = t.split('').reverse().join('') + (decimal === 0 ? '' : '.' + r);
 
-         return num.replace('-,', '-');
 
-     },
 
-     transFormToChinese(num) {
 
-         const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
 
-         const unit = ['', '十', '百', '千', '万'];
 
-         num = parseInt(num);
 
-         const getWan = temp => {
 
-             const strArr = temp.toString().split('').reverse();
 
-             let newNum = '';
 
-             for (let i = 0; i < strArr.length; i++) {
 
-                 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;
 
-             }
 
-             return strArr.length === 2 && newNum.indexOf('一十') !== -1 ? newNum.replace('一十', '十') : newNum;
 
-         };
 
-         const overWan = Math.floor(num / 10000);
 
-         let noWan = num % 10000;
 
-         if (noWan.toString().length < 4) noWan = '0' + noWan;
 
-         return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num);
 
-     },
 
-     formatNum(num, pattern) {
 
-         const minus = num > 0 ? '' : '-'
 
-         const strarr = num ? Math.abs(num).toString().split('.') : ['0'];
 
-         const fmtarr = pattern ? pattern.split('.') : [''];
 
-         let retstr = '';
 
-         // 整数部分
 
-         let str = strarr[0];
 
-         let fmt = fmtarr[0];
 
-         let i = str.length - 1;
 
-         let comma = false;
 
-         for (var f = fmt.length - 1; f >= 0; f--) {
 
-             switch (fmt.substr(f, 1)) {
 
-                 case '#':
 
-                     if (i >= 0) retstr = str.substr(i--, 1) + retstr;
 
-                     break;
 
-                 case '0':
 
-                     if (i >= 0) retstr = str.substr(i--, 1) + retstr;
 
-                     else retstr = '0' + retstr;
 
-                     break;
 
-                 case ',':
 
-                     comma = true;
 
-                     retstr = ',' + retstr;
 
-                     break;
 
-             }
 
-         }
 
-         if (i >= 0) {
 
-             if (comma) {
 
-                 const l = str.length;
 
-                 for (;i >= 0; i--) {
 
-                     retstr = str.substr(i, 1) + retstr;
 
-                     if (i > 0 && ((l - i) % 3) == 0) retstr = ',' + retstr;
 
-                 }
 
-             } else retstr = str.substr(0, i + 1) + retstr;
 
-         }
 
-         retstr = retstr + '.';
 
-         // 处理小数部分
 
-         str = strarr.length > 1 ? strarr[1] : '';
 
-         fmt = fmtarr.length > 1 ? fmtarr[1] : '';
 
-         i = 0;
 
-         for (var f = 0; f < fmt.length; f++) {
 
-             switch (fmt.substr(f, 1)) {
 
-                 case '#':
 
-                     if (i < str.length) retstr += str.substr(i++, 1);
 
-                     break;
 
-                 case '0':
 
-                     if (i < str.length) retstr += str.substr(i++, 1);
 
-                     else retstr += '0';
 
-                     break;
 
-             }
 
-         }
 
-         return minus + retstr.replace(/^,+/, '').replace(/\.$/, '');
 
-     },
 
-     dateTran(time, style = 'YYYY年MM月DD日 HH:mm') {
 
-         return moment(time).format(style);
 
-     },
 
-     dateTranChinese(day) {
 
-         const dateParts = day.split('-');
 
-         return dateParts[0] + '年' + dateParts[1] + '月' + dateParts[2] + '日';
 
-     },
 
-     // 审批日期格式:2020-5-7 9:40:30
 
-     formatFullDate(time) {
 
-         return moment(time).format('YYYY-MM-DD HH:mm:ss');
 
-     },
 
-     calcDayNum(startTime, endTime = '') {
 
-         const dateStart = new Date(startTime);
 
-         const dateEnd = endTime ? new Date(endTime) : new Date();
 
-         return parseInt((dateEnd.getTime() - dateStart.getTime()) / (1000 * 60 * 60 * 24));
 
-     },
 
-     // 预付款详情页时间线所需格式
 
-     formatDate(date) {
 
-         if (!date) return '';
 
-         const year = date.getFullYear();
 
-         let mon = date.getMonth() + 1;
 
-         let day = date.getDate();
 
-         let hour = date.getHours();
 
-         let minute = date.getMinutes();
 
-         let scond = date.getSeconds();
 
-         if (mon < 10) {
 
-             mon = '0' + mon.toString();
 
-         }
 
-         if (day < 10) {
 
-             day = '0' + day.toString();
 
-         }
 
-         if (hour < 10) {
 
-             hour = '0' + hour.toString();
 
-         }
 
-         if (minute < 10) {
 
-             minute = '0' + minute.toString();
 
-         }
 
-         if (scond < 10) {
 
-             scond = '0' + scond.toString();
 
-         }
 
-         return `${year}<span>${mon}-${day}</span><span>${hour}:${minute}:${scond}</span>`;
 
-     },
 
-     timeAdd(duration) {
 
-         const d = parseInt(duration);
 
-         let time = 0;
 
-         if (d === 1) {
 
-             time = 60 * 15 * 1000;
 
-         } else if (d === 2) {
 
-             time = 60 * 30 * 1000;
 
-         } else if (d === 3) {
 
-             time = 3600 * 1000;
 
-         } else if (d === 4) {
 
-             time = 3600 * 2 * 1000;
 
-         }
 
-         return time;
 
-     },
 
-     async sendUserSms(userId, type, judge, msg) {
 
-         const mobiles = [];
 
-         if (!userId || (userId instanceof Array && userId.length === 0)) return;
 
-         const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
 
-         for (const su of smsUser) {
 
-             if (!su.auth_mobile || su.auth_mobile === '') continue;
 
-             if (!su.sms_type || su.sms_type === '') continue;
 
-             const smsType = JSON.parse(su.sms_type);
 
-             if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
 
-                 mobiles.push(su.auth_mobile);
 
-             }
 
-         }
 
-         if (mobiles.length > 0) {
 
-             const sms = new SMS(this.ctx);
 
-             const tenderName = await sms.contentChange(this.ctx.tender.data.name);
 
-             const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
 
-             const ptmsg = projectName !== '' ? '项目「' + projectName + '」标段「' + tenderName + '」' : tenderName;
 
-             const content = '【纵横计量支付】' + ptmsg + msg;
 
-             sms.send(mobiles, content);
 
-         }
 
-     },
 
-     async sendAliSms(userId, type, judge, code, data = {}) {
 
-         // const mobiles = [];
 
-         // if (!userId || (userId instanceof Array && userId.length === 0)) return;
 
-         // const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
 
-         // for (const su of smsUser) {
 
-         //     if (!su.auth_mobile || su.auth_mobile === '') continue;
 
-         //     if (!su.sms_type || su.sms_type === '') continue;
 
-         //
 
-         //     const smsType = JSON.parse(su.sms_type);
 
-         //     if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
 
-         //         mobiles.push(su.auth_mobile);
 
-         //     }
 
-         // }
 
-         //
 
-         // if (mobiles.length > 0) {
 
-         //     const sms = new SMS(this.ctx);
 
-         //     const tenderName = await sms.contentChange(this.ctx.tender.data.name);
 
-         //     const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
 
-         //     const param = {
 
-         //         project: projectName,
 
-         //         number: tenderName,
 
-         //     };
 
-         //     const postParam = Object.assign(param, data);
 
-         //     sms.aliSend(mobiles, postParam, code);
 
-         // }
 
-     },
 
-     // 企业微信和公众号微信通知共用
 
-     async sendWechat(userId, type, judge, template, data = {}, tender = this.ctx.tender, ctx = this.ctx) {
 
-         const wechats = [];
 
-         const qywxs = {};
 
-         if (!userId || (userId instanceof Array && userId.length === 0)) return;
 
-         const wxUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
 
-         for (const user of wxUser) {
 
-             if ((!user.wx_openid || user.wx_openid === '') && !user.qywx_userid) continue;
 
-             if (!user.wx_type || user.wx_type === '') continue;
 
-             const wxType = JSON.parse(user.wx_type);
 
-             if (wxType[type] && wxType[type].indexOf(judge) !== -1) {
 
-                 if (user.wx_openid) wechats.push(user.wx_openid);
 
-                 if (user.qywx_userid && user.qywx_corpid) {
 
-                     _.has(qywxs, user.qywx_corpid) ? qywxs[user.qywx_corpid].push(user.qywx_userid) : qywxs[user.qywx_corpid] = [user.qywx_userid];
 
-                 }
 
-             }
 
-         }
 
-         if (wechats.length > 0 || !_.isEmpty(qywxs)) {
 
-             const wx = new WX(this.ctx);
 
-             const tenderName = await wx.contentChange(tender.data.name);
 
-             const projectName = await wx.contentChange(tender.info.deal_info.buildName);
 
-             const param = {
 
-                 projectName,
 
-                 tenderName,
 
-             };
 
-             const postParam = Object.assign(param, data);
 
-             const originUrl = ctx.protocol + '://' + ctx.host;
 
-             if (wechats.length > 0) wx.Send(wechats, template, postParam, originUrl);
 
-             if (!_.isEmpty(qywxs)) wx.Send4Work(qywxs, template, postParam, originUrl);
 
-         }
 
-     },
 
-     /**
 
-      *
 
-      * @param setting
 
-      * @param data
 
-      * @return {{} & any & {"!ref": string} & {"!cols"}}
 
-      */
 
-     simpleXlsxSheetData(setting, data) {
 
-         const headerStyle = {
 
-             font: { sz: 10, bold: true },
 
-             alignment: { horizontal: 'center' },
 
-         };
 
-         const sHeader = setting.header
 
-             .map((v, i) => Object.assign({}, { v, s: headerStyle, position: String.fromCharCode(65 + i) + 1 }))
 
-             .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v, s: next.s } }), {});
 
-         const sData = data
 
-             .map((v, i) => v.map((k, j) => Object.assign({}, {
 
-                 v: k ? k : '',
 
-                 s: { font: { sz: 10 }, alignment: { horizontal: setting.hAlign[j] } },
 
-                 position: String.fromCharCode(65 + j) + (i + 2) })))
 
-             .reduce((prev, next) => prev.concat(next))
 
-             .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v, s: next.s } }), {});
 
-         const output = Object.assign({}, sHeader, sData);
 
-         const outputPos = Object.keys(output);
 
-         const result = Object.assign({}, output,
 
-             { '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] },
 
-             { '!cols': setting.width.map(w => Object.assign({}, { wpx: w })) });
 
-         return result;
 
-     },
 
-     log(error) {
 
-         if (error.stack) {
 
-             this.ctx.logger.error(error);
 
-         } else {
 
-             this.ctx.getLogger('fail').info(JSON.stringify({
 
-                 error,
 
-                 project: this.ctx.session.sessionProject,
 
-                 user: this.ctx.session.sessionUser,
 
-                 body: this.ctx.session.body,
 
-             }));
 
-         }
 
-     },
 
-     /**
 
-      * 添加debug信息
 
-      * 在debug模式下,debug信息将传输到浏览器并打印
 
-      *
 
-      * @param {String}key
 
-      * @param {*}data
 
-      */
 
-     addDebugInfo(key, ...data) {
 
-         if (!this.ctx.debugInfo) {
 
-             this.ctx.debugInfo = { key: {}, other: [] };
 
-         }
 
-         if (key) {
 
-             this.ctx.debugInfo.key[key] = data;
 
-         } else {
 
-             this.ctx.debugInfo.other.push(data);
 
-         }
 
-     },
 
-     /**
 
-      * 深拷贝
 
-      * @param obj
 
-      * @return {*}
 
-      */
 
-     clone(obj) {
 
-         if (obj === null) return null;
 
-         const o = obj instanceof Array ? [] : {};
 
-         for (const i in obj) {
 
-             o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === 'object' ? this.clone(obj[i]) : obj[i]);
 
-         }
 
-         return o;
 
-     },
 
-     /**
 
-      * 短链接生成(暂停生成)
 
-      * @param url
 
-      * @return {*}
 
-      */
 
-     async urlToShort(url) {
 
-         // const apiUrl = 'http://scn.ink/api/shorturl';
 
-         // const data = {
 
-         //     url: encodeURI(url),
 
-         // };
 
-         // const result = await this.sendRequest(apiUrl, data, 'get');
 
-         // return result && result.code === 200 && result.url ? result.url : url;
 
-         return url;
 
-     },
 
-     /**
 
-      * 判断是否wap访问
 
-      * @param request
 
-      * @return {*}
 
-      */
 
-     isWap(request) {
 
-         return request.url.indexOf('/wap/') !== -1;
 
-     },
 
-     check18MainCode(code) {
 
-         return /^([0-9]([0-9][0-9])*)?(GD[0-9]{3}([0-9][0-9])*)?$/.test(code);
 
-     },
 
-     check18SubCode(code) {
 
-         return /^(GD)?G?[A-Z]{2}[A-Z]{0,2}([0-9]{2})+$/.test(code);
 
-     },
 
-     /**
 
-      * 判断是否是移动端访问
 
-      * @param request
 
-      * @return {*}
 
-      */
 
-     isMobile(agent) {
 
-         const ua = new UAParser(agent);
 
-         const osInfo = ua.getOS();
 
-         return (agent ? agent.match(/(iphone|ipod|android)/i) : false) || osInfo.name === 'Android' || osInfo.name === 'iOS';
 
-     },
 
-     /**
 
-      * 删除文件
 
-      * @param {Array} fileList 文件数组(格式为数据库查询出来的结果集,且文件字段必须为filepath)
 
-      * @return {void}
 
-      */
 
-     async delFiles(fileList) {
 
-         if (fileList.length) {
 
-             for (const att of fileList) {
 
-                 if (att.filepath && fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
 
-                     await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
 
-                 } else if (att.filepath) {
 
-                     await this.ctx.app.fujianOss.delete(this.ctx.app.config.fujianOssFolder + att.filepath);
 
-                 }
 
-             }
 
-         }
 
-     },
 
-     /**
 
-      * 匹配图片、pdf(用于预览)
 
-      * @param {String} ext 后缀名
 
-      * @return {Boolean} 匹配结果
 
-      */
 
-     canPreview(ext) {
 
-         const reg = /(.png)|(.gif)|(.txt)|(.jpg)|(.jpeg)|(.pdf)/i;
 
-         return reg.test(ext);
 
-     },
 
-     fileExtStr(ext) {
 
-         const ExtStr = [
 
-             { text: '图片', ext: ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.cad', '.dwg',] },
 
-             { text: '压缩包', ext: ['.zip', '.rar', '.7z',] },
 
-             { text: '音频', ext: ['.mp3'] },
 
-             { text: '视频', ext: ['.mp4'] },
 
-             { text: '文档', ext: ['.json', '.txt', '.xls', '.xlsx', '.doc', '.docx', '.pdf', '.ppt', '.pptx',]},
 
-         ];
 
-         for (const es of ExtStr) {
 
-             if (es.ext.indexOf(ext) >= 0) return es.text;
 
-         }
 
-         return '';
 
-     },
 
-     /**
 
-      * 查找数组中某个字符的个数
 
-      * @param {Array} array 数组
 
-      * @param {string} val 字符串
 
-      * @return {Boolean} 匹配结果
 
-      */
 
-     arrayCount(array, val) {
 
-         const counts = (arr, value) => arr.reduce((a, v) => { return value.indexOf(v) !== -1 ? a + 1 : a + 0; }, 0);
 
-         return counts(array, val);
 
-     },
 
-     filterTimesOrderData(data, keyFields, timesField, orderField, times, order) {
 
-         const dataIndex = {};
 
-         for (const d of data) {
 
-             if (d[timesField] > times || (d[timesField] = times && d[orderField] > order)) continue;
 
-             let key = 'd';
 
-             for (const kf of keyFields) {
 
-                 key = key + '.' + (d[kf] || '');
 
-             }
 
-             const di = dataIndex[key];
 
-             if (di) {
 
-                 if ((di[timesField] * timesLen + di[orderField]) < (d[timesField] * timesLen + d[orderField])) dataIndex[key] = d;
 
-             } else {
 
-                 dataIndex[key] = d;
 
-             }
 
-         }
 
-         const result = [];
 
-         for (const prop in dataIndex) {
 
-             result.push(dataIndex[prop]);
 
-         }
 
-         return result;
 
-     },
 
-     filterLastestData(data, keyFields, timesField = 'times', orderField = 'order') {
 
-         const dataIndex = {};
 
-         for (const d of data) {
 
-             let key = 'd';
 
-             for (const kf of keyFields) {
 
-                 key = key + '.' + (d[kf] || '');
 
-             }
 
-             const di = dataIndex[key];
 
-             if (di) {
 
-                 if ((di[timesField] * timesLen + di[orderField]) < (d[timesField] * timesLen + d[orderField])) dataIndex[key] = d;
 
-             } else {
 
-                 dataIndex[key] = d;
 
-             }
 
-         }
 
-         const result = [];
 
-         for (const prop in dataIndex) {
 
-             result.push(dataIndex[prop]);
 
-         }
 
-         return result;
 
-     },
 
-     filterLastestData2(data, keyFields, timesField = 'times', orderField = 'order') {
 
-         const dataIndex = {};
 
-         for (const d of data) {
 
-             let key = 'd';
 
-             for (const kf of keyFields) {
 
-                 key = key + '.' + (d[kf] || '');
 
-             }
 
-             if (!dataIndex[key]) dataIndex[key] = { index: 0, source: [] };
 
-             const di = dataIndex[key];
 
-             const curIndex = d[timesField] * timesLen + d[orderField];
 
-             if (curIndex === di.index) {
 
-                 di.source.push(d);
 
-             } else if (curIndex > di.index) {
 
-                 di.index = curIndex;
 
-                 di.source = [d];
 
-             }
 
-         }
 
-         const result = [];
 
-         for (const prop in dataIndex) {
 
-             result.push(...dataIndex[prop].source);
 
-         }
 
-         return result;
 
-     },
 
-     calcExpr(expr) {
 
-         const validExpr = expr.replace('=', '').replace('%', '/100');
 
-         return parseFloat(math.eval(validExpr));
 
-     },
 
-     /**
 
-      * 创建登录日志
 
-      * @return {Boolean} 日志是否创建成功
 
-      * @param {Number} type - 登录类型
 
-      * @param {Number} status - 是否显示记录
 
-      */
 
-     async getUserIPMsg() {
 
-         const { ctx } = this;
 
-         const ip = ctx.request.ip ? ctx.request.ip : '';
 
-         const ipInfo = await this.getIpInfoFromApi(ip);
 
-         const parser = new UAParser(ctx.header['user-agent']);
 
-         const osInfo = parser.getOS();
 
-         const cpuInfo = parser.getCPU();
 
-         const browserInfo = parser.getBrowser();
 
-         const ipMsg = {
 
-             os: `${osInfo.name} ${osInfo.version} ${cpuInfo.architecture}`,
 
-             browser: `${browserInfo.name} ${browserInfo.version}`,
 
-             ip,
 
-             address: ipInfo,
 
-         };
 
-         return ipMsg;
 
-     },
 
-     /**
 
-      * 根据ip请求获取详细地址
 
-      * @param {String} a_ip - ip地址
 
-      * @return {String} 详细地址
 
-      */
 
-     async getIpInfoFromApi(a_ip = '') {
 
-         if (!a_ip) return '';
 
-         if (a_ip === '127.0.0.1' || a_ip === '::1' || a_ip.indexOf('192.168') !== -1) return '服务器本机访问';
 
-         const { ip = '', region = '', city = '', isp = '' } = await this.sendIpRequest(a_ip);
 
-         let address = '';
 
-         region && (address += region + '省');
 
-         city && (address += city + '市 ');
 
-         isp && (address += isp + ' ');
 
-         ip && (address += `(${ip})`);
 
-         return address;
 
-     },
 
-     /**
 
-      * 发送请求获取详细地址
 
-      * @param {String} ip - ip地址
 
-      * @return {Object} the result of request
 
-      * @private
 
-      */
 
-     async sendIpRequest(ip) {
 
-         return new Promise(resolve => {
 
-             this.ctx.curl(`https://api01.aliyun.venuscn.com/ip?ip=${ip}`, {
 
-                 dateType: 'json',
 
-                 encoding: 'utf8',
 
-                 timeout: 2000,
 
-                 headers: {
 
-                     Authorization: 'APPCODE 85c64bffe70445c4af9df7ae31c7bfcc',
 
-                 },
 
-             }).then(({ status, data }) => {
 
-                 if (status === 200) {
 
-                     const result = JSON.parse(data.toString()).data;
 
-                     if (!result.ip) {
 
-                         resolve({});
 
-                     } else {
 
-                         resolve(result);
 
-                     }
 
-                 } else {
 
-                     resolve({});
 
-                 }
 
-             }).catch(() => {
 
-                 resolve({});
 
-             });
 
-         });
 
-     },
 
-     /**
 
-      * 发送请求获取详细地址
 
-      * @param {String} type - 通知类型
 
-      * @param {String} datas - 请求发送数据
 
-      * @return {Object} the result of request
 
-      * @private
 
-      */
 
-     async syncNoticeSend(type, datas) {
 
-         const key = this.ctx.session.sessionProject.code;
 
-         const time = new Date().getTime();
 
-         const projectData = await this.ctx.service.project.getDataById(this.ctx.session.sessionProject.id);
 
-         const sign = crypto.createHash('md5').update(key + projectData.secret + time.toString()).digest('hex').toString();
 
-         const res = await this.ctx.curl(this.ctx.app.config.syncUrl + syncApiConst.api_url.notice, {
 
-             method: 'POST',
 
-             contentType: 'json',
 
-             data: {
 
-                 projectCode: key,
 
-                 key,
 
-                 time,
 
-                 sign,
 
-                 customType: type,
 
-                 base_data: datas,
 
-             },
 
-             dateType: 'json',
 
-             timeout: [30000, 60000],
 
-             timing: true,
 
-         });
 
-     },
 
-     async ossFileGet(path) {
 
-         // 判断开头是否带app,否则加上
 
-         if (!_.includes(path, 'app/')) {
 
-             path = 'app/' + path;
 
-         }
 
-         const result = await this.ctx.app.fujianOss.get(this.ctx.app.config.fujianOssFolder + path);
 
-         if (result.res.status !== 200) {
 
-             throw '该文件不存在';
 
-         }
 
-         return result.content;
 
-     },
 
-     getStartEndMonth(month) {
 
-         const startMonth = moment(month).startOf('month').format('YYYY-MM-DD HH:mm:ss');
 
-         const endMonth = moment(month).endOf('month').format('YYYY-MM-DD HH:mm:ss');
 
-         return [startMonth, endMonth];
 
-     },
 
-     /**
 
-      * 创建json web token
 
-      * @param {Object} data - 签名数据
 
-      * @return {String} token
 
-      */
 
-     createJWT(data) {
 
-         return jwt.sign({ data }, sign.managementApiSecretKey, { expiresIn: '15s' });
 
-     },
 
-     async loadLedgerDataFromOss(url) {
 
-         const File = await this.ctx.hisOss.get(this.ctx.hisOssPath + url);
 
-         if (File.res.status !== 200) return '获取修订台账有误';
 
-         const result = JSON.parse(File.content);
 
-         return result;
 
-     },
 
-     hpackArr(data) {
 
-         const keyIndex = {}, key = [];
 
-         const result = [];
 
-         for (const d of data) {
 
-             const r = [];
 
-             for (const prop in d) {
 
-                 if (keyIndex[prop] === undefined) {
 
-                     key.push(prop);
 
-                     keyIndex[prop] = key.indexOf(prop);
 
-                 }
 
-                 r[keyIndex[prop]] = d[prop];
 
-             }
 
-             result.push(r);
 
-         }
 
-         if (result.length > 0) result.unshift(key);
 
-         return result;
 
-     },
 
-     // 把一个 xml 格式化成一个 json
 
-     async parseXML(xml) {
 
-         const result = await xml2js.parseStringPromise(xml, { trim: true });
 
-         return this.formatMessage(result.xml);
 
-     },
 
-     // 将xml2js解析出来的对象转换成直接可访问的对象
 
-     formatMessage(result) {
 
-         const message = {};
 
-         if (typeof result === 'object') {
 
-             for (const key in result) {
 
-                 if (!(result[key] instanceof Array) || result[key].length === 0) {
 
-                     continue;
 
-                 }
 
-                 if (result[key].length === 1) {
 
-                     const val = result[key][0];
 
-                     if (typeof val === 'object') {
 
-                         message[key] = this.formatMessage(val);
 
-                     } else {
 
-                         message[key] = (val || '').trim();
 
-                     }
 
-                 } else {
 
-                     message[key] = result[key].map(function(item) {
 
-                         return this.formatMessage(item);
 
-                     });
 
-                 }
 
-             }
 
-         }
 
-         return message;
 
-     },
 
-     mapAllSubField(obj, field) {
 
-         const result = [];
 
-         for (const prop in obj) {
 
-             result.push(obj[prop][field]);
 
-         }
 
-         return result;
 
-     },
 
-     groupAuditors(auditors, orderField = 'order') {
 
-         auditors.sort((x, y) => {
 
-             return x[orderField] - y[orderField];
 
-         });
 
-         const Group = [];
 
-         for (const a of auditors) {
 
-             if (a[orderField] !== undefined) {
 
-                 if (Group.length === 0) {
 
-                     Group.push([a])
 
-                 } else {
 
-                     if (Group[Group.length-1][0][orderField] === a[orderField]) {
 
-                         Group[Group.length-1].push(a);
 
-                     } else {
 
-                         Group.push([a]);
 
-                     }
 
-                 }
 
-             } else {
 
-                 Group.push([a]);
 
-             }
 
-         }
 
-         return Group;
 
-     },
 
-     groupAuditorsUniq(group, key = 'audit_order') {
 
-         const uniqGroup = [];
 
-         for (const g of group) {
 
-             uniqGroup[g[0][key]] = g;
 
-         }
 
-         return uniqGroup.filter(x => { return !!x });
 
-     },
 
-     async getOssToken(oss) {
 
-         try {
 
-             const { STS } = require('ali-oss');
 
-             let sts = new STS({
 
-                 accessKeyId: 'LTAI5tSoKgJ9Ze5VcgMQcM3m',
 
-                 accessKeySecret: '34sj51AEUpeDzr5V6DYjrxWOatw7Zr',
 
-             });
 
-             const token = {
 
-                 bucket: oss.options.bucket,
 
-                 endpoint: this.ctx.app.config.fujianOssPath,
 
-                 cname: true,
 
-             };
 
-             const result = await sts.assumeRole('acs:ram::31196920:role/oss-readonly', '', '3000', this.ctx.app.uuid.v4());
 
-             token.accessKeyId = result.credentials.AccessKeyId;
 
-             token.accessKeySecret = result.credentials.AccessKeySecret;
 
-             token.stsToken = result.credentials.SecurityToken;
 
-             return token;
 
-         } catch (err) {
 
-             console.log(err);
 
-         }
 
-     },
 
-     getQtySource(qty_source, no_qc_qty = 0) {
 
-         let qty = '';
 
-         switch (qty_source) {
 
-             case qtySourceValueConst.gather_qty: qty = '`gather_qty`'; break;
 
-             case qtySourceValueConst.contract_qty: qty = '`contract_qty`'; break;
 
-             case qtySourceValueConst.gather_minus_qty: qty = '(`gather_qty`+`qc_minus_qty`)'; break;
 
-             default: throw '未配置计量来源出错';
 
-         }
 
-         if (qty_source !== qtySourceValueConst.contract_qty && no_qc_qty) {
 
-             qty = '`contract_qty`';
 
-         }
 
-         return qty;
 
-     },
 
-     resetQtys(qtys) {
 
-         qtys.gather_qty = qtys.gather_qty ? qtys.gather_qty : null;
 
-         qtys.contract_qty = qtys.contract_qty ? qtys.contract_qty : null;
 
-         qtys.qc_qty = qtys.qc_qty ? qtys.qc_qty : null;
 
-         qtys.qc_minus_qty = qtys.qc_minus_qty ? qtys.qc_minus_qty : null;
 
-         return qtys;
 
-     },
 
-     contentChange(content) {
 
-         let str = content.replace(/【/g, '(');
 
-         str = str.replace(/】/g, ')');
 
-         str = str.replace(/工程款/g, '***');
 
-         str = str.length > 20 ? str.substring(0, 17) + '...' : str;
 
-         return str;
 
-     },
 
-     calculateNextSendTime(startTime, intervalHours = 6, quietStart = 0, quietEnd = 8) {
 
-         function parseTime(stime, timeStr, day = 0) {
 
-             const [hours, minutes] = timeStr.split(':').map(Number);
 
-             const date = new Date();
 
-             date.setFullYear(stime.getFullYear());
 
-             date.setMonth(stime.getMonth());
 
-             date.setDate(stime.getDate() + day);
 
-             date.setHours(hours, minutes, 0, 0); // Set hours and minutes, reset seconds and milliseconds
 
-             return date;
 
-         }
 
-         function calculateHoursBetween(start, end) {
 
-             // 将时间字符串转换为 Date 对象
 
-             const startTime = new Date(`2000-01-01T${start}`);
 
-             const endTime = new Date(`2000-01-01T${end}`);
 
-             // 检查是否跨越了当前日期和隔天日期
 
-             if (endTime < startTime) {
 
-                 endTime.setDate(endTime.getDate() + 1); // 将结束时间调整到隔天
 
-             }
 
-             // 计算两个时间之间的毫秒数差距
 
-             const timeDifference = endTime - startTime;
 
-             // 将毫秒数转换为小时并返回
 
-             const hours = timeDifference / (1000 * 60 * 60);
 
-             return 24 - hours;
 
-         }
 
-         // let startDateTime = parseTime(startTime);
 
-         let startDateTime = startTime;
 
-         let endDateTime = new Date(startDateTime.getTime() + intervalHours * 60 * 60 * 1000);
 
-         if (quietStart && quietEnd) {
 
-             quietStart = (quietStart < 10 ? '0' + quietStart : quietStart) + ':00';
 
-             quietEnd = (quietEnd < 10 ? '0' + quietEnd : quietEnd) + ':00';
 
-             let quietStartDateTime = parseTime(startDateTime, quietStart);
 
-             let quietEndDateTime = parseTime(startDateTime, quietEnd);
 
-             if (quietEndDateTime <= quietStartDateTime) {
 
-                 quietEndDateTime.setDate(quietEndDateTime.getDate() + 1);
 
-             }
 
-             // 判断非屏蔽时间内是否大于间隔时间,大于则要再隔天发送
 
-             const hours = calculateHoursBetween(quietStart, quietEnd);
 
-             if (hours < intervalHours) {
 
-                 // 除法算出差的天数
 
-                 const days = Math.floor(intervalHours / hours);
 
-                 quietStartDateTime = parseTime(startDateTime, quietStart, days);
 
-                 quietEndDateTime = parseTime(startDateTime, quietEnd, days);
 
-                 intervalHours %= hours;
 
-                 startDateTime.setDate(startDateTime.getDate() + days);
 
-             } else if (startDateTime >= quietEndDateTime) {
 
-                 quietStartDateTime = parseTime(startDateTime, quietStart, 1);
 
-             }
 
-             if (quietEndDateTime <= quietStartDateTime) {
 
-                 quietEndDateTime.setDate(quietEndDateTime.getDate() + 1);
 
-             }
 
-             if (startDateTime >= quietStartDateTime) {
 
-                 startDateTime = quietEndDateTime;
 
-             }
 
-             endDateTime = new Date(startDateTime.getTime() + intervalHours * 60 * 60 * 1000);
 
-             if (endDateTime >= quietStartDateTime && endDateTime < quietEndDateTime) {
 
-                 const timeIntoQuiet = (quietStartDateTime - startDateTime) / (60 * 60 * 1000);
 
-                 const remainingTime = intervalHours - timeIntoQuiet;
 
-                 endDateTime = new Date(quietEndDateTime.getTime() + remainingTime * 60 * 60 * 1000);
 
-             }
 
-         }
 
-         // return endDateTime.getHours().toString().padStart(2, '0') + ':' +
 
-         //     endDateTime.getMinutes().toString().padStart(2, '0');
 
-         return endDateTime;
 
-     },
 
-     showCol4ObjArray(objArray, colName, key = 'value', showKey = 'name') {
 
-         if (!colName) return '';
 
-         const info = _.find(objArray, { [key]: colName });
 
-         return info ? info[showKey] : '';
 
-     },
 
- };
 
 
  |