| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244 | 'use strict';/** * * * @author Mai * @date 2019/2/27 * @version */const auditConst = require('../const/audit').stage;const smsTypeConst = require('../const/sms_type');const SMS = require('../lib/sms');const SmsAliConst = require('../const/sms_alitemplate');const wxConst = require('../const/wechat_template');const payConst = require('../const/deal_pay');const pushType = require('../const/audit').pushType;module.exports = app => {    class StageAudit extends app.BaseService {        /**         * 构造函数         *         * @param {Object} ctx - egg全局变量         * @return {void}         */        constructor(ctx) {            super(ctx);            this.tableName = 'stage_audit';        }        /**         * 获取 审核人信息         *         * @param {Number} stageId - 期id         * @param {Number} auditorId - 审核人id         * @param {Number} times - 第几次审批         * @return {Promise<*>}         */        async getAuditor(stageId, auditorId, times = 1) {            const sql =                'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`, la.`times`, la.`order`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time` ' +                'FROM ?? AS la, ?? AS pa ' +                'WHERE la.`sid` = ? and la.`aid` = ? and la.`times` = ?' +                '    and la.`aid` = pa.`id`';            const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, stageId, auditorId, times];            return await this.db.queryOne(sql, sqlParam);        }        async getAuditorByOrder(stageId, order, times) {            const sql =                'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`,' +                '    la.`times`, la.`order`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time` ' +                '    FROM ' + this.tableName + ' AS la' +                '    Left Join ' + this.ctx.service.projectAccount.tableName + ' AS pa ON la.`aid` = pa.`id`' +                '  WHERE la.`sid` = ? and la.`order` = ? and la.`times` = ?' +                '  ORDER BY `order` DESC';            const sqlParam = [stageId, order, times ? times: 1];            return await this.db.queryOne(sql, sqlParam);        }        async getLastestAuditor(stageId, times, status) {            const sql =                'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`,' +                '    la.`times`, la.`order`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time` ' +                '    FROM ' + this.tableName + ' AS la' +                '    Left Join ' + this.ctx.service.projectAccount.tableName + ' AS pa ON la.`aid` = pa.`id`' +                '  WHERE la.`sid` = ? and la.`status` = ? and la.`times` = ?' +                '  ORDER BY `order` DESC';            const sqlParam = [stageId, status, times ? times: 1];            return await this.db.queryOne(sql, sqlParam);        }        /**         * 获取 审核列表信息         *         * @param {Number} stageId - 期id         * @param {Number} times - 第几次审批         * @param {Number} order_sort - 列表排序方式         * @return {Promise<*>}         */        async getAuditors(stageId, times = 1, order_sort = 'asc') {            const sql =                'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`, la.`times`, la.`order`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time`, g.`sort` ' +                'FROM ?? AS la, ?? AS pa, (SELECT `aid`,(@i:=@i+1) as `sort` FROM ??, (select @i:=0) as it WHERE `sid` = ? AND `times` = ? GROUP BY `aid`) as g ' +                'WHERE la.`sid` = ? and la.`times` = ? and la.`aid` = pa.`id` and g.`aid` = la.`aid` order by la.`order` ' +                order_sort;            const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, this.tableName, stageId, times, stageId, times];            const result = await this.db.query(sql, sqlParam);            const sql2 = 'SELECT COUNT(a.`aid`) as num FROM (SELECT `aid` FROM ?? WHERE `sid` = ? AND `times` = ? GROUP BY `aid`) as a';            const sqlParam2 = [this.tableName, stageId, times];            const count = await this.db.queryOne(sql2, sqlParam2);            for (const i in result) {                result[i].max_sort = count.num;            }            return result;        }        async getAllAuditors(tenderId) {            const sql =                'SELECT sa.aid, sa.tid FROM ' + this.tableName + ' sa' +                '  LEFT JOIN ' + this.ctx.service.tender.tableName + ' t On sa.tid = t.id' +                '  WHERE t.id = ?' +                '  GROUP BY  sa.aid';            const sqlParam = [tenderId];            return this.db.query(sql, sqlParam);        }        /**         * 获取标段审核人最后一位的名称         *         * @param {Number} tenderId - 标段id         * @param {Number} auditorId - 审核人id         * @param {Number} times - 第几次审批         * @return {Promise<*>}         */        async getStatusName(stageId) {            const sql =                'SELECT pa.`name` ' +                'FROM ?? AS sa, ?? AS pa ' +                'WHERE sa.`sid` = ?' +                '    and sa.`aid` = pa.`id` and sa.`status` != ? ORDER BY sa.`times` DESC, sa.`order` DESC';            const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, stageId, auditConst.status.uncheck];            return await this.db.queryOne(sql, sqlParam);        }        /**         * 获取 当前审核人         *         * @param {Number} stageId - 期id         * @param {Number} times - 第几次审批         * @return {Promise<*>}         */        async getCurAuditor(stageId, times = 1) {            const sql =                'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`, la.`times`, la.`order`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time` ' +                'FROM ?? AS la, ?? AS pa ' +                'WHERE la.`sid` = ? and la.`status` = ? and la.`times` = ?' +                '    and la.`aid` = pa.`id`';            const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, stageId, auditConst.status.checking, times];            return await this.db.queryOne(sql, sqlParam);        }        /**         * 获取 最新审核顺序         *         * @param {Number} stageId - 期id         * @param {Number} times - 第几次审批         * @return {Promise<number>}         */        async getNewOrder(stageId, times = 1) {            const sql = 'SELECT Max(??) As max_order FROM ?? Where `sid` = ? and `times` = ?';            const sqlParam = ['order', this.tableName, stageId, times];            const result = await this.db.queryOne(sql, sqlParam);            return result && result.max_order ? result.max_order + 1 : 1;        }        /**         * 新增审核人         *         * @param {Number} stageId - 期id         * @param {Number} auditorId - 审核人id         * @param {Number} times - 第几次审批         * @return {Promise<number>}         */        async addAuditor(stageId, auditorId, times = 1) {            const newOrder = await this.getNewOrder(stageId, times);            const data = {                tid: this.ctx.tender.id,                sid: stageId,                aid: auditorId,                times,                order: newOrder,                status: auditConst.status.uncheck,            };            const result = await this.db.insert(this.tableName, data);            return (result.effectRows = 1);        }        /**         * 移除审核人时,同步其后审核人order         * @param transaction - 事务         * @param {Number} stageId - 标段id         * @param {Number} auditorId - 审核人id         * @param {Number} times - 第几次审批         * @return {Promise<*>}         * @private         */        async _syncOrderByDelete(transaction, stageId, order, times) {            this.initSqlBuilder();            this.sqlBuilder.setAndWhere('sid', {                value: stageId,                operate: '=',            });            this.sqlBuilder.setAndWhere('order', {                value: order,                operate: '>=',            });            this.sqlBuilder.setAndWhere('times', {                value: times,                operate: '=',            });            this.sqlBuilder.setUpdateData('order', {                value: 1,                selfOperate: '-',            });            const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');            const data = await transaction.query(sql, sqlParam);            return data;        }        /**         * 移除审核人         *         * @param {Number} stageId - 期id         * @param {Number} auditorId - 审核人id         * @param {Number} times - 第几次审批         * @return {Promise<boolean>}         */        async deleteAuditor(stageId, auditorId, times = 1) {            const transaction = await this.db.beginTransaction();            try {                const condition = { sid: stageId, aid: auditorId, times };                const auditor = await this.getDataByCondition(condition);                if (!auditor) {                    throw '该审核人不存在';                }                await this._syncOrderByDelete(transaction, stageId, auditor.order, times);                await transaction.delete(this.tableName, condition);                await transaction.commit();            } catch (err) {                await transaction.rollback();                throw err;            }            return true;        }        /**         * 开始审批         *         * @param {Number} stageId - 期id         * @param {Number} times - 第几次审批         * @return {Promise<boolean>}         */        async start(stageId, times = 1) {            const audit = await this.getDataByCondition({ sid: stageId, times, order: 1 });            if (!audit) {                throw '请先选择审批人,再上报数据';            }            const transaction = await this.db.beginTransaction();            try {                await transaction.update(this.tableName, {                    id: audit.id,                    status: auditConst.status.checking,                    begin_time: new Date(),                });                // 计算原报最终数据                const [yfPay, sfPay] = await this.ctx.service.stagePay.calcAllStagePays(this.ctx.stage, transaction);                // 复制一份下一审核人数据                await this.ctx.service.stagePay.copyAuditStagePays(this.ctx.stage, this.ctx.stage.times, 1, transaction);                await this.ctx.service.stageJgcl.updateHistory(this.ctx.stage, transaction);                await this.ctx.service.stageBonus.updateHistory(this.ctx.stage, transaction);                await this.ctx.service.stageOther.updateHistory(this.ctx.stage, transaction);                // 更新期数据                const tpData = await this.ctx.service.stageBills.getSumTotalPrice(this.ctx.stage);                this.ctx.stage.tp_history.push({                    times: this.ctx.stage.curTimes,                    order: 0,                    contract_tp: tpData.contract_tp,                    qc_tp: tpData.qc_tp,                    yf_tp: yfPay.tp,                    sf_tp: sfPay.tp,                });                await transaction.update(this.ctx.service.stage.tableName, {                    id: stageId,                    status: auditConst.status.checking,                    contract_tp: tpData.contract_tp,                    qc_tp: tpData.qc_tp,                    yf_tp: yfPay.tp,                    sf_tp: sfPay.tp,                    tp_history: JSON.stringify(this.ctx.stage.tp_history),                    cache_time_r: this.ctx.stage.cache_time_l,                });                // 添加短信通知-需要审批提醒功能                // const smsUser = await this.ctx.service.projectAccount.getDataById(audit.aid);                // if (smsUser.auth_mobile !== '' && smsUser.auth_mobile !== undefined && smsUser.sms_type !== '' && smsUser.sms_type !== null) {                //     const smsType = JSON.parse(smsUser.sms_type);                //     if (smsType[smsTypeConst.const.JL] !== undefined && smsType[smsTypeConst.const.JL].indexOf(smsTypeConst.judge.approval.toString()) !== -1) {                //         const tenderInfo = await this.ctx.service.tender.getDataById(audit.tid);                //         const stageInfo = await this.ctx.service.stage.getDataById(audit.sid);                //         const sms = new SMS(this.ctx);                //         const tenderName = await sms.contentChange(tenderInfo.name);                //         const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);                //         const ptmsg = projectName !== '' ? '项目「' + projectName + '」标段「' + tenderName + '」' : tenderName;                //         const result = await this.ctx.helper.urlToShort('http://' + this.ctx.request.header.host + '/wap/tender/' + this.ctx.tender.id + '/stage/' + stageInfo.order);                //         const content = '【纵横计量支付】' + ptmsg + '第' + stageInfo.order + '期,需要您审批。' + result;                //         sms.send(smsUser.auth_mobile, content);                //     }                // }                const stageInfo = await this.ctx.service.stage.getDataById(audit.sid);                const shenpiUrl = await this.ctx.helper.urlToShort(this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/stage/' + stageInfo.order);                await this.ctx.helper.sendAliSms(audit.aid, smsTypeConst.const.JL, smsTypeConst.judge.approval.toString(), SmsAliConst.template.stage_check, {                    qi: stageInfo.order,                    code: shenpiUrl,                });                // 微信模板通知                const wechatData = {                    wap_url: shenpiUrl,                    qi: stageInfo.order,                    status: wxConst.status.check,                    tips: wxConst.tips.check,                    code: this.ctx.session.sessionProject.code,                };                await this.ctx.helper.sendWechat(audit.aid, smsTypeConst.const.JL, smsTypeConst.judge.approval.toString(), wxConst.template.stage, wechatData);                // todo 更新标段tender状态 ?                await transaction.commit();            } catch (err) {                await transaction.rollback();                throw err;            }            return true;        }        async _checked(pid, stageId, checkData, times) {            const time = new Date();            // 整理当前流程审核人状态更新            const audit = await this.getDataByCondition({ sid: stageId, times, status: auditConst.status.checking });            if (!audit) {                throw '审核数据错误';            }            const nextAudit = await this.getDataByCondition({ sid: stageId, times, order: audit.order + 1 });            const tpData = await this.ctx.service.stageBills.getSumTotalPrice(this.ctx.stage);            const transaction = await this.db.beginTransaction();            try {                // 添加推送                const noticeContent = await this.getNoticeContent(pid, audit.tid, stageId, audit.aid);                const auditors = await this.getAuditGroupByListWithOwner(stageId, times);                const records = [];                auditors.forEach(audit => {                    records.push({                        pid,                        type: pushType.stage,                        uid: audit.aid,                        status: auditConst.status.checked,                        content: noticeContent,                    });                });                await transaction.insert('zh_notice', records);                await transaction.update(this.tableName, {                    id: audit.id,                    status: checkData.checkType,                    opinion: checkData.opinion,                    end_time: time,                });                // 计算并合同支付最终数据                const [yfPay, sfPay] = await this.ctx.service.stagePay.calcAllStagePays(this.ctx.stage, transaction);                this.ctx.stage.tp_history.push({                    times,                    order: audit.order,                    contract_tp: tpData.contract_tp,                    qc_tp: tpData.qc_tp,                    yf_tp: yfPay.tp,                    sf_tp: sfPay.tp,                });                // 无下一审核人表示,审核结束                if (nextAudit) {                    // 复制一份下一审核人数据                    await this.ctx.service.stagePay.copyAuditStagePays(this.ctx.stage, this.ctx.stage.times, nextAudit.order, transaction);                    await this.ctx.service.stageJgcl.updateHistory(this.ctx.stage, transaction);                    await this.ctx.service.stageBonus.updateHistory(this.ctx.stage, transaction);                    await this.ctx.service.stageOther.updateHistory(this.ctx.stage, transaction);                    // 流程至下一审批人                    await transaction.update(this.tableName, {                        id: nextAudit.id,                        status: auditConst.status.checking,                        begin_time: time,                    });                    // 同步 期信息                    await transaction.update(this.ctx.service.stage.tableName, {                        id: stageId,                        status: auditConst.status.checking,                        contract_tp: tpData.contract_tp,                        qc_tp: tpData.qc_tp,                        yf_tp: yfPay.tp,                        sf_tp: sfPay.tp,                        tp_history: JSON.stringify(this.ctx.stage.tp_history),                        cache_time_r: this.ctx.stage.cache_time_l,                    });                    // 添加短信通知-需要审批提醒功能                    // const smsUser = await this.ctx.service.projectAccount.getDataById(nextAudit.aid);                    // if (smsUser.auth_mobile !== '' && smsUser.auth_mobile !== undefined && smsUser.sms_type !== '' && smsUser.sms_type !== null) {                    //     const smsType = JSON.parse(smsUser.sms_type);                    //     if (smsType[smsTypeConst.const.JL] !== undefined && smsType[smsTypeConst.const.JL].indexOf(smsTypeConst.judge.approval.toString()) !== -1) {                    //         const tenderInfo = await this.ctx.service.tender.getDataById(nextAudit.tid);                    //         const stageInfo = await this.ctx.service.stage.getDataById(nextAudit.sid);                    //         const sms = new SMS(this.ctx);                    //         const tenderName = await sms.contentChange(tenderInfo.name);                    //         const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);                    //         const result = await this.ctx.helper.urlToShort('http://' + this.ctx.request.header.host + '/wap/tender/' + this.ctx.tender.id + '/stage/' + stageInfo.order);                    //         // const result = '';                    //         const ptmsg = projectName !== '' ? '项目「' + projectName + '」标段「' + tenderName + '」' : tenderName;                    //         const content = '【纵横计量支付】' + ptmsg + '第' + stageInfo.order + '期,需要您审批。' + result;                    //         sms.send(smsUser.auth_mobile, content);                    //     }                    // }                    const stageInfo = await this.ctx.service.stage.getDataById(nextAudit.sid);                    const shenpiUrl = await this.ctx.helper.urlToShort(this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/stage/' + stageInfo.order);                    await this.ctx.helper.sendAliSms(nextAudit.aid, smsTypeConst.const.JL, smsTypeConst.judge.approval.toString(), SmsAliConst.template.stage_check, {                        qi: stageInfo.order,                        code: shenpiUrl,                    });                    // 微信模板通知                    const wechatData = {                        wap_url: shenpiUrl,                        qi: stageInfo.order,                        status: wxConst.status.check,                        tips: wxConst.tips.check,                        code: this.ctx.session.sessionProject.code,                    };                    await this.ctx.helper.sendWechat(nextAudit.aid, smsTypeConst.const.JL, smsTypeConst.judge.approval.toString(), wxConst.template.stage, wechatData);                } else {                    // 本期结束                    // 生成截止本期数据 final数据                    await this.ctx.service.stageBillsFinal.generateFinalData(transaction, this.ctx.tender, this.ctx.stage);                    await this.ctx.service.stagePosFinal.generateFinalData(transaction, this.ctx.tender, this.ctx.stage);                    // 同步 期信息                    await transaction.update(this.ctx.service.stage.tableName, {                        id: stageId,                        status: checkData.checkType,                        contract_tp: tpData.contract_tp,                        qc_tp: tpData.qc_tp,                        yf_tp: yfPay.tp,                        sf_tp: sfPay.tp,                        tp_history: JSON.stringify(this.ctx.stage.tp_history),                        cache_time_r: this.ctx.stage.cache_time_l,                    });                    // 添加短信通知-审批通过提醒功能                    // const mobile_array = [];                    const stageInfo = await this.ctx.service.stage.getDataById(stageId);                    const auditList = await this.getAuditors(stageId, stageInfo.times);                    // const smsUser1 = await this.ctx.service.projectAccount.getDataById(stageInfo.user_id);                    // if (smsUser1.auth_mobile !== undefined && smsUser1.sms_type !== '' && smsUser1.sms_type !== null) {                    //     const smsType = JSON.parse(smsUser1.sms_type);                    //     if (smsType[smsTypeConst.const.JL] !== undefined && smsType[smsTypeConst.const.JL].indexOf(smsTypeConst.judge.result.toString()) !== -1) {                    //         mobile_array.push(smsUser1.auth_mobile);                    //     }                    // }                    // for (const user of auditList) {                    //     const smsUser = await this.ctx.service.projectAccount.getDataById(user.aid);                    //     if (smsUser.auth_mobile !== '' && smsUser.auth_mobile !== undefined && smsUser.sms_type !== '' && smsUser.sms_type !== null) {                    //         const smsType = JSON.parse(smsUser.sms_type);                    //         if (mobile_array.indexOf(smsUser.auth_mobile) === -1 && smsType[smsTypeConst.const.JL] !== undefined && smsType[smsTypeConst.const.JL].indexOf(smsTypeConst.judge.result.toString()) !== -1) {                    //             mobile_array.push(smsUser.auth_mobile);                    //         }                    //     }                    // }                    // if (mobile_array.length > 0) {                    //     const tenderInfo = await this.ctx.service.tender.getDataById(stageInfo.tid);                    //     const sms = new SMS(this.ctx);                    //     const tenderName = await sms.contentChange(tenderInfo.name);                    //     const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);                    //     const ptmsg = projectName !== '' ? '项目「' + projectName + '」标段「' + tenderName + '」' : tenderName;                    //     const content = '【纵横计量支付】' + ptmsg + '第' + stageInfo.order + '期,审批通过。';                    //     sms.send(mobile_array, content);                    // }                    const users = this._.uniq(this._.concat(this._.map(auditList, 'aid'), stageInfo.user_id));                    await this.ctx.helper.sendAliSms(users, smsTypeConst.const.JL, smsTypeConst.judge.result.toString(), SmsAliConst.template.stage_result, {                        qi: stageInfo.order,                        status: SmsAliConst.status.success,                    });                    // 微信模板通知                    const shenpiUrl = await this.ctx.helper.urlToShort(this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/stage/' + stageInfo.order);                    const wechatData = {                        wap_url: shenpiUrl,                        qi: stageInfo.order,                        status: wxConst.status.success,                        tips: wxConst.tips.success,                        code: this.ctx.session.sessionProject.code,                    };                    await this.ctx.helper.sendWechat(users, smsTypeConst.const.JL, smsTypeConst.judge.result.toString(), wxConst.template.stage, wechatData);                }                await transaction.commit();            } catch (err) {                await transaction.rollback();                throw err;            }        }        async _checkNo(pid, stageId, checkData, times) {            const time = new Date();            // 整理当前流程审核人状态更新            const audit = await this.getDataByCondition({ sid: stageId, times, status: auditConst.status.checking });            if (!audit) {                throw '审核数据错误';            }            const tpData = await this.ctx.service.stageBills.getSumTotalPrice(this.ctx.stage);            const sql = 'SELECT `tid`, `sid`, `aid`, `order` FROM ?? WHERE `sid` = ? and `times` = ? GROUP BY `aid` ORDER BY `id` ASC';            const sqlParam = [this.tableName, stageId, times];            const auditors = await this.db.query(sql, sqlParam);            let order = 1;            for (const a of auditors) {                a.times = times + 1;                a.order = order;                a.status = auditConst.status.uncheck;                order++;            }            const transaction = await this.db.beginTransaction();            try {                // 添加推送                const noticeContent = await this.getNoticeContent(pid, audit.tid, stageId, audit.aid);                const records = [                    {                        pid,                        type: pushType.stage,                        uid: this.ctx.stage.user_id,                        status: auditConst.status.checkNo,                        content: noticeContent,                    },                ];                auditors.forEach(audit => {                    records.push({                        pid,                        type: pushType.stage,                        uid: audit.aid,                        status: auditConst.status.checkNo,                        content: noticeContent,                    });                });                await transaction.insert(this.ctx.service.noticePush.tableName, records);                // 计算并合同支付最终数据                const [yfPay, sfPay] = await this.ctx.service.stagePay.calcAllStagePays(this.ctx.stage, transaction);                this.ctx.stage.tp_history.push({                    times,                    order: audit.order,                    contract_tp: tpData.contract_tp,                    qc_tp: tpData.qc_tp,                    yf_tp: yfPay.tp,                    sf_tp: sfPay.tp,                });                await transaction.update(this.tableName, {                    id: audit.id,                    status: checkData.checkType,                    opinion: checkData.opinion,                    end_time: time,                });                // 同步 期信息                await transaction.update(this.ctx.service.stage.tableName, {                    id: stageId,                    status: checkData.checkType,                    contract_tp: tpData.contract_tp,                    qc_tp: tpData.qc_tp,                    times: times + 1,                    yf_tp: yfPay.tp,                    sf_tp: sfPay.tp,                    tp_history: JSON.stringify(this.ctx.stage.tp_history),                    cache_time_r: this.ctx.stage.cache_time_l,                });                // 拷贝新一次审核流程列表                await transaction.insert(this.tableName, auditors);                // 计算该审批人最终数据                await this.ctx.service.stagePay.calcAllStagePays(this.ctx.stage, transaction);                // 复制一份最新数据给原报                await this.ctx.service.stagePay.copyAuditStagePays(this.ctx.stage, this.ctx.stage.times + 1, 0, transaction);                await this.ctx.service.stageJgcl.updateHistory(this.ctx.stage, transaction);                await this.ctx.service.stageBonus.updateHistory(this.ctx.stage, transaction);                // 添加短信通知-审批退回提醒功能                // const mobile_array = [];                const stageInfo = await this.ctx.service.stage.getDataById(stageId);                const auditList = await this.getAuditors(stageId, stageInfo.times);                // const smsUser1 = await this.ctx.service.projectAccount.getDataById(stageInfo.user_id);                // if (smsUser1.auth_mobile !== '' && smsUser1.auth_mobile !== undefined && smsUser1.sms_type !== '' && smsUser1.sms_type !== null) {                //     const smsType = JSON.parse(smsUser1.sms_type);                //     if (smsType[smsTypeConst.const.JL] !== undefined && smsType[smsTypeConst.const.JL].indexOf(smsTypeConst.judge.result.toString()) !== -1) {                //         mobile_array.push(smsUser1.auth_mobile);                //     }                // }                // for (const user of auditList) {                //     const smsUser = await this.ctx.service.projectAccount.getDataById(user.aid);                //     if (smsUser.auth_mobile !== '' && smsUser.auth_mobile !== undefined && smsUser.sms_type !== '' && smsUser.sms_type !== null) {                //         const smsType = JSON.parse(smsUser.sms_type);                //         if (mobile_array.indexOf(smsUser.auth_mobile) === -1 && smsType[smsTypeConst.const.JL] !== undefined && smsType[smsTypeConst.const.JL].indexOf(smsTypeConst.judge.result.toString()) !== -1) {                //             mobile_array.push(smsUser.auth_mobile);                //         }                //     }                // }                // if (mobile_array.length > 0) {                //     const tenderInfo = await this.ctx.service.tender.getDataById(stageInfo.tid);                //     const sms = new SMS(this.ctx);                //     const tenderName = await sms.contentChange(tenderInfo.name);                //     const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);                //     const ptmsg = projectName !== '' ? '项目「' + projectName + '」标段「' + tenderName + '」' : tenderName;                //     const content = '【纵横计量支付】' + ptmsg + '第' + stageInfo.order + '期,审批退回。';                //     sms.send(mobile_array, content);                // }                const users = this._.uniq(this._.concat(this._.map(auditList, 'aid'), stageInfo.user_id));                await this.ctx.helper.sendAliSms(users, smsTypeConst.const.JL, smsTypeConst.judge.result.toString(), SmsAliConst.template.stage_result, {                    qi: stageInfo.order,                    status: SmsAliConst.status.back,                });                // 微信模板通知                const shenpiUrl = await this.ctx.helper.urlToShort(this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/stage/' + stageInfo.order);                const wechatData = {                    wap_url: shenpiUrl,                    qi: stageInfo.order,                    status: wxConst.status.back,                    tips: wxConst.tips.back,                    code: this.ctx.session.sessionProject.code,                };                await this.ctx.helper.sendWechat(users, smsTypeConst.const.JL, smsTypeConst.judge.result.toString(), wxConst.template.stage, wechatData);                await transaction.commit();            } catch (err) {                await transaction.rollback();                throw err;            }        }        async _checkNoPre(pid, stageId, checkData, times) {            const time = new Date();            // 整理当前流程审核人状态更新            const audit = await this.getDataByCondition({ sid: stageId, times, status: auditConst.status.checking });            if (!audit || audit.order <= 1) {                throw '审核数据错误';            }            // 添加重新审批后,不能用order-1,取groupby值里的上一个才对            // const preAuditor = await this.getDataByCondition({sid: stageId, times: times, order: audit.order - 1});            const auditors2 = await this.getAuditGroupByList(stageId, times);            const auditorIndex = await auditors2.findIndex(function(item) {                return item.aid === audit.aid;            });            const preAuditor = auditors2[auditorIndex - 1];            const tpData = await this.ctx.service.stageBills.getSumTotalPrice(this.ctx.stage);            const transaction = await this.db.beginTransaction();            try {                // 添加推送                const noticeContent = await this.getNoticeContent(pid, audit.tid, stageId, audit.aid);                const records = [                    {                        pid,                        type: pushType.stage,                        uid: this.ctx.stage.user_id,                        status: auditConst.status.checkNoPre,                        content: noticeContent,                    },                ];                auditors2.forEach(audit => {                    records.push({                        pid,                        type: pushType.stage,                        uid: audit.aid,                        status: auditConst.status.checkNoPre,                        content: noticeContent,                    });                });                await transaction.insert('zh_notice', records);                // 计算并合同支付最终数据                const [yfPay, sfPay] = await this.ctx.service.stagePay.calcAllStagePays(this.ctx.stage, transaction);                this.ctx.stage.tp_history.push({                    times,                    order: audit.order,                    contract_tp: tpData.contract_tp,                    qc_tp: tpData.qc_tp,                    yf_tp: yfPay.tp,                    sf_tp: sfPay.tp,                });                // 同步 期信息                await transaction.update(this.ctx.service.stage.tableName, {                    id: stageId,                    contract_tp: tpData.contract_tp,                    qc_tp: tpData.qc_tp,                    times,                    yf_tp: yfPay.tp,                    sf_tp: sfPay.tp,                    tp_history: JSON.stringify(this.ctx.stage.tp_history),                    cache_time_r: this.ctx.stage.cache_time_l,                });                await transaction.update(this.tableName, {                    id: audit.id,                    status: checkData.checkType,                    opinion: checkData.opinion,                    end_time: time,                });                // 顺移气候审核人流程顺序                this.initSqlBuilder();                this.sqlBuilder.setAndWhere('sid', { value: this.ctx.stage.id, operate: '=' });                this.sqlBuilder.setAndWhere('order', { value: audit.order, operate: '>' });                this.sqlBuilder.setUpdateData('order', { value: 2, selfOperate: '+' });                const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');                const data = await transaction.query(sql, sqlParam);                // 上一审批人,当前审批人 再次添加至流程                const newAuditors = [];                newAuditors.push({                    tid: audit.tid,                    sid: audit.sid,                    aid: preAuditor.aid,                    times: audit.times,                    order: audit.order + 1,                    status: auditConst.status.checking,                    begin_time: time,                });                newAuditors.push({                    tid: audit.tid,                    sid: audit.sid,                    aid: audit.aid,                    times: audit.times,                    order: audit.order + 2,                    status: auditConst.status.uncheck,                });                await transaction.insert(this.tableName, newAuditors);                // 计算该审批人最终数据                await this.ctx.service.stagePay.calcAllStagePays(this.ctx.stage, transaction);                // 复制一份最新数据给下一人                await this.ctx.service.stagePay.copyAuditStagePays(this.ctx.stage, this.ctx.stage.times, audit.order + 1, transaction);                await this.ctx.service.stageJgcl.updateHistory(this.ctx.stage, transaction);                await this.ctx.service.stageBonus.updateHistory(this.ctx.stage, transaction);                await this.ctx.service.stageOther.updateHistory(this.ctx.stage, transaction);                // 同步 期信息                await transaction.update(this.ctx.service.stage.tableName, {                    id: stageId,                    status: checkData.checkType,                    cache_time_r: this.ctx.stage.cache_time_l,                });                // 添加短信通知-需要审批提醒功能                // const smsUser = await this.ctx.service.projectAccount.getDataById(preAuditor.aid);                // if (smsUser.auth_mobile !== '' && smsUser.auth_mobile !== undefined && smsUser.sms_type !== '' && smsUser.sms_type !== null) {                //     const smsType = JSON.parse(smsUser.sms_type);                //     if (smsType[smsTypeConst.const.JL] !== undefined && smsType[smsTypeConst.const.JL].indexOf(smsTypeConst.judge.approval.toString()) !== -1) {                //         const tenderInfo = await this.ctx.service.tender.getDataById(audit.tid);                //         const stageInfo = await this.ctx.service.stage.getDataById(audit.sid);                //         const sms = new SMS(this.ctx);                //         const tenderName = await sms.contentChange(tenderInfo.name);                //         const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);                //         const ptmsg = projectName !== '' ? '项目「' + projectName + '」标段「' + tenderName + '」' : tenderName;                //         const result = await this.ctx.helper.urlToShort('http://' + this.ctx.request.header.host + '/wap/tender/' + this.ctx.tender.id + '/stage/' + stageInfo.order);                //         // const result = '';                //         const content = '【纵横计量支付】' + ptmsg + '第' + stageInfo.order + '期,需要您审批。' + result;                //         sms.send(smsUser.auth_mobile, content);                //     }                // }                const stageInfo = await this.ctx.service.stage.getDataById(audit.sid);                const shenpiUrl = await this.ctx.helper.urlToShort(this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/stage/' + stageInfo.order);                await this.ctx.helper.sendAliSms(preAuditor.aid, smsTypeConst.const.JL, smsTypeConst.judge.approval.toString(), SmsAliConst.template.stage_check, {                    qi: stageInfo.order,                    code: shenpiUrl,                });                // 微信模板通知                const wechatData = {                    wap_url: shenpiUrl,                    qi: stageInfo.order,                    status: wxConst.status.check,                    tips: wxConst.tips.check,                    code: this.ctx.session.sessionProject.code,                };                await this.ctx.helper.sendWechat(preAuditor.aid, smsTypeConst.const.JL, smsTypeConst.judge.approval.toString(), wxConst.template.stage, wechatData);                await transaction.commit();            } catch (err) {                await transaction.rollback();                throw err;            }        }        /**         * 审批         * @param {Number} stageId - 标段id         * @param {auditConst.status.checked|auditConst.status.checkNo} checkType - 审批结果         * @param {Number} times - 第几次审批         * @return {Promise<void>}         */        async check(stageId, checkData, times = 1) {            if (checkData.checkType !== auditConst.status.checked && checkData.checkType !== auditConst.status.checkNo && checkData.checkType !== auditConst.status.checkNoPre) {                throw '提交数据错误';            }            // // 整理当前流程审核人状态更新            // const audit = await this.getDataByCondition({sid: stageId, times: times, status: auditConst.status.checking});            // if (!audit) {            //     throw '审核数据错误';            // }            // const time = new Date();            const pid = this.ctx.session.sessionProject.id;            switch (checkData.checkType) {                case auditConst.status.checked:                    await this._checked(pid, stageId, checkData, times);                    break;                case auditConst.status.checkNo:                    await this._checkNo(pid, stageId, checkData, times);                    break;                case auditConst.status.checkNoPre:                    await this._checkNoPre(pid, stageId, checkData, times);                    break;                default:                    throw '无效审批操作';            }        }        /**         * 审批         * @param {Number} stageId - 标段id         * @param {Number} times - 第几次审批         * @return {Promise<void>}         */        async checkAgain(stageId, times = 1) {            const time = new Date();            // 整理当前流程审核人状态更新            const audit = (                await this.getAllDataByCondition({                    where: { sid: stageId, times },                    orders: [['order', 'desc']],                    limit: 1,                    offset: 0,                })            )[0];            if (!audit || audit.order < 1) {                throw '审核数据错误';            }            const transaction = await this.db.beginTransaction();            try {                // 当前审批人2次添加至流程中                const newAuditors = [];                newAuditors.push({                    tid: audit.tid,                    sid: audit.sid,                    aid: audit.aid,                    times: audit.times,                    order: audit.order + 1,                    status: auditConst.status.checkAgain,                    begin_time: time,                    end_time: time,                    opinion: '',                });                newAuditors.push({                    tid: audit.tid,                    sid: audit.sid,                    aid: audit.aid,                    times: audit.times,                    order: audit.order + 2,                    status: auditConst.status.checking,                    begin_time: time,                });                await transaction.insert(this.tableName, newAuditors);                // 复制一份最新数据给下一人                await this.ctx.service.stagePay.copyAuditStagePays(this.ctx.stage, this.ctx.stage.times, audit.order + 1, transaction);                await this.ctx.service.stagePay.copyAuditStagePays(this.ctx.stage, this.ctx.stage.times, audit.order + 2, transaction);                await this.ctx.service.stageJgcl.updateHistory(this.ctx.stage, transaction);                await this.ctx.service.stageBonus.updateHistory(this.ctx.stage, transaction);                await this.ctx.service.stageOther.updateHistory(this.ctx.stage, transaction);                // 本期结束                // 生成截止本期数据 final数据                await this.ctx.service.stageBillsFinal.delGenerateFinalData(transaction, this.ctx.tender, this.ctx.stage);                await this.ctx.service.stagePosFinal.delGenerateFinalData(transaction, this.ctx.tender, this.ctx.stage);                // 同步 期信息                await transaction.update(this.ctx.service.stage.tableName, {                    id: stageId,                    status: auditConst.status.checking,                    cache_time_r: this.ctx.stage.cache_time_l,                });                // 添加短信通知-需要审批提醒功能                // const smsUser = await this.ctx.service.projectAccount.getDataById(audit.aid);                // if (smsUser.auth_mobile !== undefined && smsUser.sms_type !== '' && smsUser.sms_type !== null) {                //     const smsType = JSON.parse(smsUser.sms_type);                //     if (smsType[smsTypeConst.const.JL] !== undefined && smsType[smsTypeConst.const.JL].indexOf(smsTypeConst.judge.approval.toString()) !== -1) {                //         const tenderInfo = await this.ctx.service.tender.getDataById(audit.tid);                //         const stageInfo = await this.ctx.service.stage.getDataById(audit.sid);                //         const sms = new SMS(this.ctx);                //         const tenderName = await sms.contentChange(tenderInfo.name);                //         const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);                //         const ptmsg = projectName !== '' ? '项目「' + projectName + '」标段「' + tenderName + '」' : tenderName;                //         const result = await this.ctx.helper.urlToShort('http://' + this.ctx.request.header.host + '/wap/tender/' + this.ctx.tender.id + '/stage/' + stageInfo.order);                //         const content = '【纵横计量支付】' + ptmsg + '第' + stageInfo.order + '期,需要您审批。' + result;                //         sms.send(smsUser.auth_mobile, content);                //     }                // }                const stageInfo = await this.ctx.service.stage.getDataById(audit.sid);                const shenpiUrl = await this.ctx.helper.urlToShort(this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/stage/' + stageInfo.order);                await this.ctx.helper.sendAliSms(audit.aid, smsTypeConst.const.JL, smsTypeConst.judge.approval.toString(), SmsAliConst.template.stage_check, {                    qi: stageInfo.order,                    code: shenpiUrl,                });                // 微信模板通知                const wechatData = {                    wap_url: shenpiUrl,                    qi: stageInfo.order,                    status: wxConst.status.check,                    tips: wxConst.tips.check,                    code: this.ctx.session.sessionProject.code,                };                await this.ctx.helper.sendWechat(audit.aid, smsTypeConst.const.JL, smsTypeConst.judge.approval.toString(), wxConst.template.stage, wechatData);                await transaction.commit();            } catch (err) {                await transaction.rollback();                throw err;            }        }        /**         * 获取审核人需要审核的期列表         *         * @param auditorId         * @return {Promise<*>}         */        async getAuditStage(auditorId) {            const sql =                'SELECT sa.`aid`, sa.`times`, sa.`order`, sa.`begin_time`, sa.`end_time`, sa.`tid`, sa.`sid`,' +                '    s.`order` As `sorder`, s.`status` As `sstatus`,' +                '    t.`name`, t.`project_id`, t.`type`, t.`user_id` ' +                '  FROM ?? AS sa, ?? AS s, ?? As t ' +                '  WHERE ((sa.`aid` = ? and sa.`status` = ?) OR (s.`user_id` = ? and sa.`status` = ? and s.`status` = ? and sa.`times` = (s.`times`-1)))' +                '    and sa.`sid` = s.`id` and sa.`tid` = t.`id` ORDER BY sa.`begin_time` DESC';            const sqlParam = [                this.tableName,                this.ctx.service.stage.tableName,                this.ctx.service.tender.tableName,                auditorId,                auditConst.status.checking,                auditorId,                auditConst.status.checkNo,                auditConst.status.checkNo,            ];            return await this.db.query(sql, sqlParam);        }        /**         * 获取 某时间后 审批进度 更新的期         * @param {Number} pid - 查询标段         * @param {Number} uid - 查询人         * @param {Date} time - 查询时间         * @return {Promise<*>}         */        async getNoticeStage(pid, uid, time) {            // const sql = 'SELECT * FROM (SELECT t.`name`, t.`project_id`, t.`type`, t.`user_id`, ' +            //             '    s.`order` As `s_order`, s.`status` As `s_status`, ' +            //             '    sa.`aid`, sa.`times`, sa.`order`, sa.`end_time`, sa.`tid`, sa.`sid`, sa.`status`, ' +            //             '    pa.`name` As `su_name`, pa.role As `su_role`, pa.company As `su_company`' +            //             '  FROM (SELECT * FROM ?? WHERE `user_id` = ? OR `id` in (SELECT `tid` FROM ?? WHERE `aid` = ? GROUP BY `tid`)) As t' +            //             '  LEFT JOIN ?? As s On t.`id` = s.`tid`' +            //             '  LEFT JOIN ?? As sa ON s.`id` = sa.`sid`' +            //             '  LEFT JOIN ?? As pa ON sa.`aid` = pa.`id`' +            //             '  WHERE sa.`end_time` > ? and t.`project_id` = ?' +            //             '  ORDER By sa.`end_time` DESC LIMIT 1000) as new_t GROUP BY new_t.`tid`' +            //             '  ORDER By new_t.`end_time`';            // const sqlParam = [this.ctx.service.tender.tableName, uid, this.tableName, uid, this.ctx.service.stage.tableName, this.tableName,            //     this.ctx.service.projectAccount.tableName, time, pid];            // return await this.db.query(sql, sqlParam);            let notice = await this.db.select('zh_notice', {                where: { pid, type: pushType.stage, uid },                orders: [['create_time', 'desc']],                limit: 10,                offset: 0,            });            notice = notice.map(v => {                const extra = JSON.parse(v.content);                delete v.content;                return { ...v, ...extra };            });            return notice;        }        /**         * 用于添加推送所需的content内容         * @param {Number} pid 项目id         * @param {Number} tid 台账id         * @param {Number} sid 期id         * @param {Number} uid 审核人id         */        async getNoticeContent(pid, tid, sid, uid) {            const noticeSql =                'SELECT * FROM (SELECT ' +                '  t.`id` As `tid`, t.`name`, s.`order`, pa.`name` As `su_name`, pa.role As `su_role`' +                '  FROM (SELECT * FROM ?? WHERE `id` = ? ) As t' +                '  LEFT JOIN ?? As s On s.`id` =  ?' +                '  LEFT JOIN ?? As pa ON pa.`id` = ?' +                '  WHERE  t.`project_id` = ? ) as new_t GROUP BY new_t.`tid`';            const noticeSqlParam = [this.ctx.service.tender.tableName, tid, this.ctx.service.stage.tableName, sid, this.ctx.service.projectAccount.tableName, uid, pid];            const content = await this.db.query(noticeSql, noticeSqlParam);            return content.length ? JSON.stringify(content[0]) : '';        }        /**         * 获取审核人流程列表         *         * @param auditorId         * @return {Promise<*>}         */        async getAuditGroupByList(stageId, times) {            const sql =                'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`sid`, la.`aid`, la.`order` ' +                'FROM ?? AS la, ?? AS pa ' +                'WHERE la.`sid` = ? and la.`times` = ? and la.`aid` = pa.`id` GROUP BY la.`aid` ORDER BY la.`order`';            const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, stageId, times];            return await this.db.query(sql, sqlParam);            // const sql = 'SELECT `tid`, `sid`, `aid`, `order` FROM ?? WHERE `sid` = ? and `times` = ? GROUP BY `aid`';            // const sqlParam = [this.tableName, stageId, times];            // return await this.db.query(sql, sqlParam);        }        /**         * 获取审核人流程列表         *         * @param auditorId         * @return {Promise<*>}         */        async getAuditGroupByListWithOwner(stageId, times) {            const result = await this.getAuditGroupByList(stageId, times);            const sql =                'SELECT pa.`id` As aid, pa.`name`, pa.`company`, pa.`role`, ? As times, ? As sid, 0 As `order`' +                '  FROM ' +                this.ctx.service.stage.tableName +                ' As s' +                '  LEFT JOIN ' +                this.ctx.service.projectAccount.tableName +                ' As pa' +                '  ON s.user_id = pa.id' +                '  WHERE s.id = ?';            const sqlParam = [times, stageId, stageId];            const user = await this.db.queryOne(sql, sqlParam);            result.unshift(user);            return result;        }        /**         * 复制上一期的审批人列表给最新一期         *         * @param transaction - 新增一期的事务         * @param {Object} preStage - 上一期         * @param {Object} newStage - 最新一期         * @return {Promise<*>}         */        async copyPreStageAuditors(transaction, preStage, newStage) {            const auditors = await this.getAuditGroupByList(preStage.id, preStage.times);            const newAuditors = [];            for (const a of auditors) {                const na = {                    tid: preStage.tid,                    sid: newStage.id,                    aid: a.aid,                    times: newStage.times,                    order: newAuditors.length + 1,                    status: auditConst.status.uncheck,                };                newAuditors.push(na);            }            const result = await transaction.insert(this.tableName, newAuditors);            return (result.effectRows = auditors.length);        }        /**         * 移除审核人         *         * @param {Number} stageId - 期id         * @param {Number} status - 期状态         * @param {Number} status - 期次数         * @return {Promise<boolean>}         */        async getAuditorByStatus(stageId, status, times = 1) {            let auditor = null;            let sql = '';            let sqlParam = '';            switch (status) {                case auditConst.status.checking:                case auditConst.status.checked:                case auditConst.status.checkNoPre:                    sql =                        'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`sid`, la.`order` ' +                        'FROM ?? AS la, ?? AS pa ' +                        'WHERE la.`sid` = ? and la.`status` = ? and la.`aid` = pa.`id` order by la.`times` desc, la.`order` desc';                    sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, stageId, status];                    auditor = await this.db.queryOne(sql, sqlParam);                    break;                case auditConst.status.checkNo:                    sql =                        'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`sid`, la.`order` ' +                        'FROM ?? AS la, ?? AS pa ' +                        'WHERE la.`sid` = ? and la.`status` = ? and la.`times` = ? and la.`aid` = pa.`id` order by la.`times` desc, la.`order` desc';                    sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, stageId, auditConst.status.checkNo, parseInt(times) - 1];                    auditor = await this.db.queryOne(sql, sqlParam);                    break;                case auditConst.status.uncheck:                default:                    break;            }            return auditor;        }        /**         * 取某一期已批准审核信息(报表用)         *         * @param {Number} stageId - 期id         * @param {Number} times - 期次数         * @return {Promise<boolean>}         */        async getStageAudit(stageId, times = 1) {            const sql = 'SELECT a1.aid, a1.begin_time, a1.end_time, a1.status, a1.opinion ' + 'FROM ?? AS a1 ' + 'WHERE a1.`sid` = ? and a1.`times` = ? ' + 'ORDER BY a1.order';            const sqlParam = [this.tableName, stageId, times];            const rst = await this.db.query(sql, sqlParam);            return rst;        }        /**         * 取待审批期列表(wap用)         *         * @param auditorId         * @return {Promise<*>}         */        async getAuditStageByWap(auditorId) {            const sql =                'SELECT sa.`aid`, sa.`times`, sa.`begin_time`, sa.`end_time`, sa.`tid`, sa.`sid`,' +                // '    s.`order` As `sorder`, s.`status` As `sstatus`, s.`s_time`, s.`contract_tp`, s.`qc_tp`, s.`pre_contract_tp`, s.`pre_qc_tp`, s.`yf_tp`, s.`pre_yf_tp`, ' +                '    s.*,' +                '    t.`name`, t.`project_id`, t.`type`, t.`user_id`,' +                '    ti.`deal_info` ' +                '  FROM ?? AS sa, ?? AS s, ?? As t, ?? AS ti ' +                '  WHERE sa.`aid` = ? and sa.`status` = ?' +                '    and sa.`sid` = s.`id` and sa.`tid` = t.`id` and ti.`tid` = t.`id`';            const sqlParam = [                this.tableName,                this.ctx.service.stage.tableName,                this.ctx.service.tender.tableName,                this.ctx.service.tenderInfo.tableName,                auditorId,                auditConst.status.checking,            ];            return await this.db.query(sql, sqlParam);        }        /**         * 删除 某期 某次 全审批流程         * 私有,不做判断,不补全最新一轮审批人数据,不计算缓存         * @param {Number} sid - 标段id         * @param {Number} times - 第几次审批         * @param transaction - 删除事务         * @return {Promise<void>}         */        async _timesDelete(sid, times, transaction) {            // 审批流程            await transaction.delete(this.tableName, { sid, times });            await transaction.delete(this.ctx.service.pos.tableName, { add_stage: sid, add_times: times });            await transaction.delete(this.ctx.service.stageBills.tableName, { sid, times });            await transaction.delete(this.ctx.service.stagePos.tableName, { sid, times });            await transaction.delete(this.ctx.service.stageDetail.tableName, { sid, times });            await transaction.delete(this.ctx.service.stageChange.tableName, { sid, stimes: times });            await transaction.delete(this.ctx.service.stagePay.tableName, { sid, stimes: times });            await transaction.delete(this.ctx.service.pay.tableName, { csid: sid, cstimes: times });            // 其他台账            await this.ctx.service.stageJgcl.deleteStageTimesData(sid, times, transaction);            await this.ctx.service.stageOther.deleteStageTimesData(sid, times, transaction);            await this.ctx.service.stageBonus.deleteStageTimesData(sid, times, transaction);        }        /**         * 删除本次审批流程         * @param {Number} stageId - 标段id         * @param {Number} times - 第几次审批         * @return {Promise<void>}         */        async timesDelete() {            const transaction = await this.db.beginTransaction();            try {                // 删除最新一次数据                await this._timesDelete(this.ctx.stage.id, this.ctx.stage.times, transaction);                // 审批退回,未重新上报时,需删除最新两次数据                const isCheckNo = this.ctx.stage.status === auditConst.status.checkNo;                const nowTimes = isCheckNo ? this.ctx.stage.times - 1 : this.ctx.stage.times;                if (isCheckNo) {                    await this._timesDelete(this.ctx.stage.id, nowTimes, transaction);                }                // 添加上一次审批人                const sql = 'SELECT `tid`, `sid`, `aid`, `order` FROM ?? WHERE `sid` = ? and `times` = ? GROUP BY `aid` ORDER BY `id` ASC';                const sqlParam = [this.tableName, this.ctx.stage.id, nowTimes - 1];                const auditors = await this.db.query(sql, sqlParam);                let order = 1;                for (const a of auditors) {                    a.times = nowTimes;                    a.order = order;                    a.status = auditConst.status.uncheck;                    order++;                }                // 拷贝新一次审核流程列表                await transaction.insert(this.tableName, auditors);                // 计算缓存                const tpData = await this.ctx.service.stageBills.getSumTotalPrice(this.ctx.stage);                // 计算并合同支付最终数据                const lastAudit = await this.getDataByCondition({                    sid: this.ctx.stage.id,                    times: nowTimes - 1,                    status: auditConst.status.checkNo,                });                if (!lastAudit) throw '审批数据错误';                await this.ctx.service.stagePay.copyStagePays4DeleteTimes(this.ctx.stage, nowTimes, 0, lastAudit.times, lastAudit.order, transaction);                const stagePay = await this.ctx.service.stagePay.getAuditorStageData(this.ctx.stage.id, lastAudit.times, lastAudit.order);                const yfPay = stagePay.find(function(x) {                    return x.ptype === payConst.payType.yf;                });                const sfPay = stagePay.find(function(x) {                    return x.ptype === payConst.payType.sf;                });                // 同步 期信息                const time = new Date();                await transaction.update(this.ctx.service.stage.tableName, {                    id: this.ctx.stage.id,                    status: auditConst.status.checkNo,                    contract_tp: tpData.contract_tp,                    qc_tp: tpData.qc_tp,                    times: nowTimes,                    yf_tp: yfPay.tp,                    sf_tp: sfPay.tp,                    tp_history: JSON.stringify(this.ctx.stage.tp_history),                    cache_time_l: time,                    cache_time_r: time,                });                await transaction.commit();            } catch (err) {                await transaction.rollback();                throw err;            }        }    }    return StageAudit;};
 |