| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960 | 'use strict';/** * * * @author Mai * @date 2018/8/14 * @version */const auditConst = require('../const/audit').changeApply;const pushType = require('../const/audit').pushType;const shenpiConst = require('../const/shenpi');const smsTypeConst = require('../const/sms_type');const SMS = require('../lib/sms');const SmsAliConst = require('../const/sms_alitemplate');const wxConst = require('../const/wechat_template');module.exports = app => {    class ChangeApplyAudit extends app.BaseService {        /**         * 构造函数         *         * @param {Object} ctx - egg全局变量         * @return {void}         */        constructor(ctx) {            super(ctx);            this.tableName = 'change_apply_audit';        }        /**         * 获取 审核列表信息         *         * @param {Number} caId - 变更立项id         * @param {Number} times - 第几次审批         * @return {Promise<*>}         */        async getAuditors(caId, 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`, g.`sort` ' +                'FROM ?? AS la, ?? AS pa, (SELECT t1.`aid`,(@i:=@i+1) as `sort` FROM (SELECT t.`aid`, t.`order` FROM (select `aid`, `order` from ?? WHERE `caid` = ? AND `times` = ? ORDER BY `order` LIMIT 200) t GROUP BY t.`aid` ORDER BY t.`order`) t1, (select @i:=0) as it) as g ' +                'WHERE la.`caid` = ? and la.`times` = ? and la.`aid` = pa.`id` and g.`aid` = la.`aid` order by la.`order`';            const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, this.tableName, caId, times, caId, times];            const result = await this.db.query(sql, sqlParam);            const sql2 = 'SELECT COUNT(a.`aid`) as num FROM (SELECT `aid` FROM ?? WHERE `caid` = ? AND `times` = ? GROUP BY `aid`) as a';            const sqlParam2 = [this.tableName, caId, times];            const count = await this.db.queryOne(sql2, sqlParam2);            for (const i in result) {                result[i].max_sort = count.num;            }            return result;        }        /**         * 获取 当前审核人         *         * @param {Number} caId - 变更立项id         * @param {Number} times - 第几次审批         * @return {Promise<*>}         */        async getCurAuditor(caId, 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 Left Join ?? AS pa On la.`aid` = pa.`id` ' +                '  WHERE la.`caid` = ? and la.`status` = ? and la.`times` = ?';            const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, caId, auditConst.status.checking, times];            return await this.db.queryOne(sql, sqlParam);        }        /**         * 获取审核人流程列表         *         * @param auditorId         * @return {Promise<*>}         */        async getAuditGroupByList(changeId, times) {            const sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`caid`, la.`aid`, la.`order` ' +                '  FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id`' +                '  WHERE la.`caid` = ? and la.`times` = ? and la.`status` != ? and la.`status` != ? GROUP BY la.`aid` ORDER BY la.`order`';            const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, changeId, times, auditConst.status.revise, auditConst.status.cancelRevise];            return await this.db.query(sql, sqlParam);        }        /**         * 移除审核人         *         * @param {Number} materialId - 材料调差期id         * @param {Number} status - 期状态         * @param {Number} status - 期次数         * @return {Promise<boolean>}         */        async getAuditorByStatus(caId, status, times = 1) {            let auditor = null;            let sql = '';            let sqlParam = '';            switch (status) {                case auditConst.status.checking :                case auditConst.status.checked :                case auditConst.status.revise :                    sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`caid`, la.`aid`, la.`order` ' +                        '  FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +                        '  WHERE la.`caid` = ? and la.`status` = ? ' +                        '  ORDER BY la.`times` desc, la.`order` desc';                    sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, caId, 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.`caid`, la.`aid`, la.`order` ' +                        '  FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id`' +                        '  WHERE la.`caid` = ? and la.`status` = ? and la.`times` = ?' +                        '  ORDER BY la.`times` desc, la.`order` desc';                    sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, caId, auditConst.status.checkNo, parseInt(times) - 1];                    auditor = await this.db.queryOne(sql, sqlParam);                    break;                case auditConst.status.uncheck :                    break;                default:break;            }            return auditor;        }        async getLastAudit(caid, times, transaction = null) {            const sql = 'SELECT * FROM ?? WHERE `caid` = ? AND `times` = ? ORDER BY `order` DESC';            const sqlParam = [this.tableName, caid, times];            return transaction ? await transaction.queryOne(sql, sqlParam) : await this.db.queryOne(sql, sqlParam);        }        /**         * 获取审核人流程列表(包括原报)         * @param {Number} materialId 调差id         * @param {Number} times 审核次数         * @return {Promise<Array>} 查询结果集(包括原报)         */        async getAuditorsWithOwner(caId, times = 1) {            const result = await this.getAuditGroupByList(caId, times);            const sql =                'SELECT pa.`id` As aid, pa.`name`, pa.`company`, pa.`role`, ? As times, ? As caid, 0 As `order`' +                '  FROM ' +                this.ctx.service.changeApply.tableName +                ' As s' +                '  LEFT JOIN ' +                this.ctx.service.projectAccount.tableName +                ' As pa' +                '  ON s.uid = pa.id' +                '  WHERE s.id = ?';            const sqlParam = [times, caId, caId];            const user = await this.db.queryOne(sql, sqlParam);            result.unshift(user);            return result;        }        /**         * 新增审核人         *         * @param {Number} caId - 立项书id         * @param {Number} auditorId - 审核人id         * @param {Number} times - 第几次审批         * @return {Promise<number>}         */        async addAuditor(caId, auditorId, times = 1, is_gdzs = 0) {            const transaction = await this.db.beginTransaction();            let flag = false;            try {                let newOrder = await this.getNewOrder(caId, times);                // 判断是否存在固定终审,存在则newOrder - 1并使终审order+1                newOrder = is_gdzs === 1 ? newOrder - 1 : newOrder;                if (is_gdzs) await this._syncOrderByDelete(transaction, caId, newOrder, times, '+');                const data = {                    tid: this.ctx.tender.id,                    caid: caId,                    aid: auditorId,                    times,                    order: newOrder,                    status: auditConst.status.uncheck,                };                const result = await transaction.insert(this.tableName, data);                await transaction.commit();                flag = result.effectRows = 1;            } catch (err) {                await transaction.rollback();                throw err;            }            return flag;        }        /**         * 获取 最新审核顺序         *         * @param {Number} caId - 立项书id         * @param {Number} times - 第几次审批         * @return {Promise<number>}         */        async getNewOrder(caId, times = 1) {            const sql = 'SELECT Max(??) As max_order FROM ?? Where `caid` = ? and `times` = ?';            const sqlParam = ['order', this.tableName, caId, times];            const result = await this.db.queryOne(sql, sqlParam);            return result && result.max_order ? result.max_order + 1 : 1;        }        /**         * 移除审核人         *         * @param {Number} caId - 变更立项书id         * @param {Number} auditorId - 审核人id         * @param {Number} times - 第几次审批         * @return {Promise<boolean>}         */        async deleteAuditor(caId, auditorId, times = 1) {            const transaction = await this.db.beginTransaction();            try {                const condition = { caid: caId, aid: auditorId, times };                const auditor = await this.getDataByCondition(condition);                if (!auditor) {                    throw '该审核人不存在';                }                await this._syncOrderByDelete(transaction, caId, auditor.order, times);                await transaction.delete(this.tableName, condition);                await transaction.commit();            } catch (err) {                await transaction.rollback();                throw err;            }            return true;        }        /**         * 移除审核人时,同步其后审核人order         * @param transaction - 事务         * @param {Number} caId - 变更立项书id         * @param {Number} auditorId - 审核人id         * @param {Number} times - 第几次审批         * @return {Promise<*>}         * @private         */        async _syncOrderByDelete(transaction, caId, order, times, selfOperate = '-') {            this.initSqlBuilder();            this.sqlBuilder.setAndWhere('caid', {                value: caId,                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} caId - 立项书id         * @param {Number} times - 第几次审批         * @return {Promise<boolean>}         */        async start(caId, times = 1) {            const audit = await this.getDataByCondition({ caid: caId, times, order: 1 });            if (!audit) {                // if (this.ctx.tender.info.shenpi.material === shenpiConst.sp_status.gdspl) {                //     throw '请联系管理员添加审批人';                // } else {                throw '请先选择审批人,再上报数据';                // }            }            const transaction = await this.db.beginTransaction();            try {                await transaction.update(this.tableName, { id: audit.id, status: auditConst.status.checking, begin_time: new Date() });                await transaction.update(this.ctx.service.changeApply.tableName, {                    id: caId, status: auditConst.status.checking,                });                // 微信模板通知                const wechatData = {                    type: 'apply',                    status: wxConst.status.check,                    tips: wxConst.tips.check,                    code: this.ctx.session.sessionProject.code,                    c_name: this.ctx.change.name,                };                await this.ctx.helper.sendWechat(audit.aid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);                await transaction.delete(this.ctx.service.changeApplyHistory.tableName, { caid: caId });                // todo 更新标段tender状态 ?                await transaction.commit();            } catch (err) {                await transaction.rollback();                throw err;            }            return true;        }        /**         * 获取审核人需要审核的期列表         *         * @param auditorId         * @return {Promise<*>}         */        async getAuditChangeApply(auditorId) {            const sql = 'SELECT ma.`aid`, ma.`times`, ma.`order`, ma.`begin_time`, ma.`end_time`, ma.`tid`, ma.`caid`,' +                '    m.`status` As `mstatus`, m.`code` As `mcode`,' +                '    t.`name`, t.`project_id`, t.`type`, t.`user_id` ' +                '  FROM ?? AS ma, ?? AS m, ?? As t ' +                '  WHERE ((ma.`aid` = ? and ma.`status` = ?) OR (m.`uid` = ? and ma.`status` = ? and m.`status` = ? and ma.`times` = (m.`times`-1)))' +                '    and ma.`caid` = m.`id` and ma.`tid` = t.`id` ORDER BY ma.`begin_time` DESC';            const sqlParam = [this.tableName, this.ctx.service.changeApply.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 auditorId         * @return {Promise<*>}         */        async getCountByChecked(auditorId) {            return await this.db.count(this.tableName, { aid: auditorId, status: [auditConst.status.checked, auditConst.status.checkNo] });        }        /**         * 获取最近一次审批结束时间         *         * @param auditorId         * @return {Promise<*>}         */        async getLastEndTimeByChecked(auditorId) {            const sql = 'SELECT `end_time` FROM ?? WHERE `aid` = ? ' +                'AND `status` in (' + this.ctx.helper.getInArrStrSqlFilter([auditConst.status.checked, auditConst.status.checkNo]) + ') ORDER BY `end_time` DESC';            const sqlParam = [this.tableName, auditorId];            const result = await this.db.queryOne(sql, sqlParam);            return result ? result.end_time : null;        }        /**         * 用于添加推送所需的content内容         * @param {Number} pid 项目id         * @param {Number} tid 台账id         * @param {Number} caId 立项书id         * @param {Number} uid 审批人id         */        async getNoticeContent(pid, tid, caId, uid, opinion = '') {            const noticeSql = 'SELECT * FROM (SELECT ' +                '  t.`id` As `tid`, ma.`caid`, m.`code` as `c_code`, t.`name`, pa.`name` As `su_name`, pa.role As `su_role`' +                '  FROM (SELECT * FROM ?? WHERE `id` = ? ) As t' +                '  LEFT JOIN ?? As m On t.`id` = m.`tid` AND m.`id` = ?' +                '  LEFT JOIN ?? As ma ON m.`id` = ma.`caid`' +                '  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.changeApply.tableName, caId, this.tableName, this.ctx.service.projectAccount.tableName, uid, pid];            const content = await this.db.query(noticeSql, noticeSqlParam);            if (content.length) {                content[0].opinion = opinion;            }            return content.length ? JSON.stringify(content[0]) : '';        }        /**         * 审批         * @param {Number} caId - 立项书id         * @param {auditConst.status.checked|auditConst.status.checkNo} checkType - 审批结果         * @param {Number} times - 第几次审批         * @return {Promise<void>}         */        async check(caId, checkData, times = 1) {            if (checkData.checkType !== auditConst.status.checked && checkData.checkType !== auditConst.status.checkNo) {                throw '提交数据错误';            }            const pid = this.ctx.session.sessionProject.id;            switch (checkData.checkType) {                case auditConst.status.checked:                    await this._checked(pid, caId, checkData, times);                    break;                case auditConst.status.checkNo:                    await this._checkNo(pid, caId, checkData, times);                    break;                default:                    throw '无效审批操作';            }        }        async _checked(pid, caId, checkData, times) {            const time = new Date();            // 整理当前流程审核人状态更新            const audit = await this.getDataByCondition({ caid: caId, times, status: auditConst.status.checking });            if (!audit) {                throw '审核数据错误';            }            // 获取审核人列表            const sql = 'SELECT `tid`, `caid`, `aid`, `order` FROM ?? WHERE `caid` = ? and `times` = ? GROUP BY `aid` ORDER BY `id` ASC';            const sqlParam = [this.tableName, caId, times];            const auditors = await this.db.query(sql, sqlParam);            const nextAudit = await this.getDataByCondition({ caid: caId, times, order: audit.order + 1 });            const transaction = await this.db.beginTransaction();            try {                await transaction.update(this.tableName, { id: audit.id, status: checkData.checkType, opinion: checkData.opinion, end_time: time });                // 获取推送必要信息                const noticeContent = await this.getNoticeContent(pid, audit.tid, caId, audit.aid, checkData.opinion);                // 添加推送                const records = [{ pid, type: pushType.changeApply, uid: this.ctx.change.uid, status: auditConst.status.checked, content: noticeContent }];                auditors.forEach(audit => {                    records.push({ pid, type: pushType.changeApply, uid: audit.aid, status: auditConst.status.checked, content: noticeContent });                });                await transaction.insert('zh_notice', records);                // 无下一审核人表示,审核结束                if (nextAudit) {                    // 流程至下一审批人                    await transaction.update(this.tableName, { id: nextAudit.id, status: auditConst.status.checking, begin_time: time });                    // 同步 期信息                    await transaction.update(this.ctx.service.changeApply.tableName, {                        id: caId, status: auditConst.status.checking,                    });                    // 微信模板通知                    const wechatData = {                        type: 'apply',                        status: wxConst.status.check,                        tips: wxConst.tips.check,                        code: this.ctx.session.sessionProject.code,                        c_name: this.ctx.change.name,                    };                    await this.ctx.helper.sendWechat(nextAudit.aid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);                } else {                    // 本期结束                    // 生成截止本期数据 final数据                    // 同步 期信息                    await transaction.update(this.ctx.service.changeApply.tableName, {                        id: caId, status: checkData.checkType,                        notice_code: checkData.notice_code,                        notice_uid: checkData.notice_uid,                        decimal: JSON.stringify(this.ctx.change.decimal),                    });                    // 微信模板通知                    const users = this._.uniq(this._.concat(this._.map(auditors, 'aid'), this.ctx.change.uid));                    const wechatData = {                        type: 'apply',                        status: wxConst.status.success,                        tips: wxConst.tips.success,                        code: this.ctx.session.sessionProject.code,                        c_name: this.ctx.change.name,                    };                    await this.ctx.helper.sendWechat(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), wxConst.template.change, wechatData);                }                await transaction.commit();            } catch (err) {                await transaction.rollback();                throw err;            }        }        async _checkNo(pid, caId, checkData, times) {            const time = new Date();            const changeData = await this.ctx.service.changeApply.getDataById(caId);            // 整理当前流程审核人状态更新            const audit = await this.getDataByCondition({ caid: caId, times, status: auditConst.status.checking });            if (!audit) {                throw '审核数据错误';            }            // const sql = 'SELECT `tid`, `caid`, `aid`, `order` FROM ?? WHERE `caid` = ? and `times` = ? GROUP BY `aid` ORDER BY `id` ASC';            // const sqlParam = [this.tableName, caId, times];            // const auditors = await this.db.query(sql, sqlParam);            const auditors = await this.getAuditGroupByList(caId, times);            let order = 1;            const newAuditors = [];            for (const a of auditors) {                a.times = times + 1;                a.order = order;                a.status = auditConst.status.uncheck;                order++;                newAuditors.push({                    tid: a.tid,                    caid: caId,                    times: a.times,                    order: a.order,                    status: a.status,                    aid: a.aid,                });            }            const transaction = await this.db.beginTransaction();            try {                await transaction.update(this.tableName, { id: audit.id, status: checkData.checkType, opinion: checkData.opinion, end_time: time });                // 添加到消息推送表                const noticeContent = await this.getNoticeContent(pid, audit.tid, caId, audit.aid, checkData.opinion);                const records = [{ pid, type: pushType.changeApply, uid: this.ctx.change.uid, status: auditConst.status.checkNo, content: noticeContent }];                auditors.forEach(audit => {                    records.push({ pid, type: pushType.changeApply, uid: audit.aid, status: auditConst.status.checkNo, content: noticeContent });                });                await transaction.insert(this.ctx.service.noticePush.tableName, records);                // 同步期信息                await transaction.update(this.ctx.service.changeApply.tableName, {                    id: caId, status: checkData.checkType,                    times: times + 1,                });                // 拷贝新一次审核流程列表                await transaction.insert(this.tableName, newAuditors);                // 微信模板通知                // const begin_audit = await this.getDataByCondition({                //     mid: materialId,                //     order: 1,                // });                // 微信模板通知                const users = this._.uniq(this._.concat(this._.map(auditors, 'aid'), this.ctx.change.uid));                const wechatData = {                    type: 'apply',                    status: wxConst.status.back,                    tips: wxConst.tips.back,                    code: this.ctx.session.sessionProject.code,                    c_name: this.ctx.change.name,                };                await this.ctx.helper.sendWechat(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), wxConst.template.change, wechatData);                // 生成内容保存表至zh_change_project_history中,用于撤回                // 回退spamount值数据                const changeList = await this.ctx.service.changeApplyList.getAllDataByCondition({                    where: { caid: caId },                });                await this.ctx.service.changeApplyHistory.saveHistory(transaction, changeData, changeList);                await transaction.commit();            } catch (err) {                await transaction.rollback();                throw err;            }        }        /**         * 复制上一期的审批人列表给最新一期         *         * @param transaction - 新增一期的事务         * @param {Object} preMaterial - 上一期         * @param {Object} newaMaterial - 最新一期         * @return {Promise<*>}         */        async copyPreChangeApplyAuditors(transaction, preChange, newChange) {            const auditors = await this.getAuditGroupByList(preChange.id, preChange.times);            const newAuditors = [];            for (const a of auditors) {                const na = {                    tid: preChange.tid,                    caid: newChange.id,                    aid: a.aid,                    times: newChange.times,                    order: newAuditors.length + 1,                    status: auditConst.status.uncheck,                };                newAuditors.push(na);            }            const result = newAuditors.length > 0 ? await transaction.insert(this.tableName, newAuditors) : null;            return result ? result.affectedRows === auditors.length : true;        }        async getAllAuditors(tenderId) {            const sql = 'SELECT ma.aid, ma.tid FROM ' + this.tableName + ' ma' +                '  LEFT JOIN ' + this.ctx.service.tender.tableName + ' t On ma.tid = t.id' +                '  WHERE t.id = ?' +                '  GROUP BY  ma.aid';            const sqlParam = [tenderId];            return this.db.query(sql, sqlParam);        }        /**         * 审批撤回         * @param {Number} stageId - 标段id         * @param {Number} times - 第几次审批         * @return {Promise<void>}         */        async checkCancel(change) {            // 分3种情况,根据ctx.cancancel值判断:            // 1.原报发起撤回,当前流程删除,并回到待上报            // 2.审批人撤回审批通过,增加流程,并回到它审批中            // 4.审批人撤回退回原报操作,删除新增的审批流,增加流程,回滚到它审批中            switch (change.cancancel) {                case 1: await this._userCheckCancel(change); break;                case 2: await this._auditCheckCancel(change); break;                case 4: await this._auditCheckCancelNo(change); break;                default: throw '不可撤回,请刷新页面重试';            }        }        /**         * 原报撤回,直接改动审批人状态         * 如果存在审批人数据,将其改为原报流程数据,但保留原提交人         *         * 一审 1 A checking  ->  A uncheck status改   pay/jl:删0(jl为增量数据,只删重复部分) 1->0 删1         * ...         *         * @param stage         * @returns {Promise<void>}         * @private         */        async _userCheckCancel(change) {            const transaction = await this.db.beginTransaction();            try {                // 整理当前流程审核人状态更新                const curAudit = await this.getDataByCondition({ caid: change.id, times: change.times, status: auditConst.status.checking });                // 审批人变成待审批状态                await transaction.update(this.tableName, {                    id: curAudit.id,                    status: auditConst.status.uncheck,                    begin_time: null,                    opinion: null,                });                // 变成待上报状态                await transaction.update(this.ctx.service.changeApply.tableName, {                    id: change.id,                    status: change.times === 1 ? auditConst.status.uncheck : auditConst.status.checkNo,                });                await transaction.commit();            } catch (err) {                await transaction.rollback();                throw err;            }        }        /**         * 审批人撤回审批通过,插入两条数据         *         * 一审 1 A checked             一审 1 A checked         * 二审 2 B checked   pre ->    二审 2 B checked         * 三审 3 C checking  cur       二审 3 B checkCancel  增                增extra_his     增tp_his         * 四审 4 D uncheck             二审 4 B checking     增                增pay_cur         *                             三审 5 C uncheck      order、status改         *                             四审 6 D uncheck      order改         *         * @param stage         * @returns {Promise<void>}         * @private         */        async _auditCheckCancel(change) {            const time = new Date();            const transaction = await this.db.beginTransaction();            try {                // 整理当前流程审核人状态更新                const curAudit = await this.getDataByCondition({ caid: change.id, times: change.times, status: auditConst.status.checking });                const preAudit = change.preAudit;                if (!curAudit || curAudit.order <= 1 || !preAudit) {                    throw '撤回用户数据错误';                }                // 顺移其后审核人流程顺序                const sql = 'UPDATE ' + this.tableName + ' SET `order` = `order` + 2 WHERE caid = ? AND times = ? AND `order` > ?';                await transaction.query(sql, [change.id, change.times, curAudit.order]);                // 当前审批人2次添加至流程中                const newAuditors = [];                // 先入撤回记录                newAuditors.push({                    tid: change.tid,                    caid: change.id,                    aid: preAudit.aid,                    times: change.times,                    order: curAudit.order,                    status: auditConst.status.checkCancel,                    begin_time: time,                    end_time: time,                    opinion: '',                });                newAuditors.push({                    tid: change.tid,                    caid: change.id,                    aid: preAudit.aid,                    times: change.times,                    order: curAudit.order + 1,                    status: auditConst.status.checking,                    begin_time: time,                });                await transaction.insert(this.tableName, newAuditors);                // 当前审批人变成待审批                await transaction.update(this.tableName, { id: curAudit.id, order: curAudit.order + 2, begin_time: null, status: auditConst.status.uncheck });                await transaction.commit();            } catch (err) {                await transaction.rollback();                throw err;            }        }        /**         * 审批人撤回审批退回原报         *         * 1# 一审 1 A checked              1# 一审 1 A checked         *    二审 2 B checkNo   pre   ->      二审 2 B checkNo         *    三审 3 C uncheck                 二审 3 B checkCancel    增       pay: 2#0 -> 1#3   jl: 2#0 -> 1#3   增tp_his   增extra_his         *                                    二审 4 B checking       增       pay: 2#0 -> 1#4         *                                    三审 5 C uncheck        order改         *         * 2# 一审 1 A uncheck              2#                        删       pay: 2#0删   jl: 2#0删         *    二审 2 B uncheck         *    三审 3 C uncheck         *         * @param stage         * @returns {Promise<void>}         * @private         */        async _auditCheckCancelNo(change) {            const time = new Date();            const transaction = await this.db.beginTransaction();            try {                // const curAudit = await this.getDataByCondition({ cpid: change.id, times: change.times - 1, status: auditConst.status.back });                const curAudit = await this.getAuditorByStatus(change.id, auditConst.status.checkNo, change.times);                // 整理上一个流程审核人状态更新                // 顺移其后审核人流程顺序                const sql = 'UPDATE ' + this.tableName + ' SET `order` = `order` + 2 WHERE caid = ? AND times = ? AND `order` > ?';                await transaction.query(sql, [change.id, change.times - 1, curAudit.order]);                // 当前审批人2次添加至流程中                const newAuditors = [];                newAuditors.push({                    tid: change.tid,                    caid: change.id,                    aid: curAudit.aid,                    times: curAudit.times,                    order: curAudit.order + 1,                    status: auditConst.status.checkCancel,                    begin_time: time,                    end_time: time,                    opinion: '',                });                newAuditors.push({                    tid: change.tid,                    caid: change.id,                    aid: curAudit.aid,                    times: curAudit.times,                    order: curAudit.order + 2,                    status: auditConst.status.checking,                    begin_time: time,                });                await transaction.insert(this.tableName, newAuditors);                // 删除当前次审批流                await transaction.delete(this.tableName, { caid: change.id, times: change.times });                // 回退数据                await this.ctx.service.changeApplyHistory.returnHistory(transaction, change.id);                await transaction.delete(this.ctx.service.changeApplyHistory.tableName, { caid: change.id });                // // 设置变更立项为审批中                // await transaction.update(this.ctx.service.changeProject.tableName, {                //     id: change.id,                //     time: change.times - 1,                //     status: auditConst.status.checking,                // });                await transaction.commit();            } catch (err) {                await transaction.rollback();                throw err;            }        }        /**         * 重新审批变更令         * @param { string } cid - 查询的清单         * @return {Promise<*>} - 可用的变更令列表         */        async checkRevise(change) {            const time = new Date();            // 初始化事务            const transaction = await this.db.beginTransaction();            let result = false;            try {                const pid = this.ctx.session.sessionProject.id;                // 获取审核人列表                const sql = 'SELECT `tid`, `caid`, `aid`, `order` FROM ?? WHERE `caid` = ? and `times` = ? GROUP BY `aid` ORDER BY `id` ASC';                const sqlParam = [this.tableName, change.id, change.times];                const auditors = await this.db.query(sql, sqlParam);                // 添加到消息推送表                const noticeContent = await this.getNoticeContent(pid, change.tid, change.id, this.ctx.session.sessionUser.accountId, '发起修订');                const records = [];                auditors.forEach(auditor => {                    records.push({                        pid,                        type: pushType.changeApply,                        uid: auditor.aid,                        status: auditConst.status.revise,                        content: noticeContent,                    });                });                await transaction.insert('zh_notice', records);                // 获取当前次数审批人列表                const auditList = await this.getAuditGroupByList(change.id, change.times);                const lastAudit = await this.getLastAudit(change.id, change.times);                const insert_audit_array = [];                // 新增一个发起修订状态到审批流程中                const revise_audit = {                    tid: change.tid,                    caid: change.id,                    aid: change.uid,                    times: change.times,                    order: lastAudit.order + 1,                    status: auditConst.status.revise,                    begin_time: time,                    end_time: time,                    opinion: '',                };                insert_audit_array.push(revise_audit);                // 新增新一次的审批人列表                let order = 1;                for (const al of auditList) {                    const insert_audit = {                        tid: change.tid,                        caid: change.id,                        aid: al.aid,                        times: change.times + 1,                        order,                        status: auditConst.status.uncheck,                    };                    insert_audit_array.push(insert_audit);                    order++;                }                await transaction.insert(this.tableName, insert_audit_array);                // 生成内容保存表至zh_change_history中,用于撤销修订回退                const changeData = await transaction.get(this.ctx.service.changeApply.tableName, { id: change.id });                const changeList = await this.ctx.service.changeApplyList.getAllDataByCondition({                    where: { caid: change.id },                });                await this.ctx.service.changeApplyHistory.saveHistory(transaction, changeData, changeList);                // 设置变更立项修订状态                await transaction.update(this.ctx.service.changeApply.tableName, {                    id: change.id,                    notice_code: null,                    notice_uid: null,                    decimal: null,                    status: auditConst.status.revise,                    times: change.times + 1,                });                await transaction.commit();                result = true;            } catch (error) {                console.log(error);                await transaction.rollback();                result = false;            }            return result;        }        /**         * 撤销修订变更令         * @param { string } cid - 查询的清单         * @return {Promise<*>} - 可用的变更令列表         */        async cancelRevise(change) {            const time = new Date();            // 初始化事务            const transaction = await this.db.beginTransaction();            let result = false;            try {                const pid = this.ctx.session.sessionProject.id;                // 获取审核人列表                const sql = 'SELECT `tid`, `caid`, `aid`, `order` FROM ?? WHERE `caid` = ? and `times` = ? GROUP BY `aid` ORDER BY `id` ASC';                const sqlParam = [this.tableName, change.id, change.times - 1];                const auditors = await this.db.query(sql, sqlParam);                // 添加到消息推送表                const noticeContent = await this.getNoticeContent(pid, change.tid, change.id, this.ctx.session.sessionUser.accountId, '撤销修订');                const records = [];                auditors.forEach(auditor => {                    records.push({                        pid,                        type: pushType.changeApply,                        uid: auditor.aid,                        status: auditConst.status.cancelRevise,                        content: noticeContent,                    });                });                await transaction.insert('zh_notice', records);                const lastAudit = await this.getLastAudit(change.id, change.times - 1);                // 新增一个撤销修订状态到审批流程中                const revise_audit = {                    tid: change.tid,                    caid: change.id,                    aid: this.ctx.session.sessionUser.accountId,                    times: change.times - 1,                    order: lastAudit.order + 1,                    status: auditConst.status.cancelRevise,                    begin_time: time,                    end_time: time,                    opinion: '',                };                await transaction.insert(this.ctx.service.changeApplyAudit.tableName, revise_audit);                await transaction.delete(this.ctx.service.changeApplyAudit.tableName, { caid: change.id, times: change.times });                await this.ctx.service.changeApplyHistory.returnHistory(transaction, change.id);                await transaction.delete(this.ctx.service.changeApplyHistory.tableName, { caid: change.id });                await transaction.commit();                result = true;            } catch (error) {                console.log(error);                await transaction.rollback();                result = false;            }            return result;        }        /**         * 重新审批变更申请         * @param { string } cid - 查询的清单         * @return {Promise<*>} - 可用的变更令列表         */        async checkAgain(change) {            // 初始化事务            const time = new Date();            const transaction = await this.db.beginTransaction();            let result = false;            try {                // 获取终审                const zsAudit = await this.getAuditorByStatus(change.id, auditConst.status.checked);                const lastAudit = await this.getLastAudit(change.id, change.times);                const insert_audit_array = [];                // 新增2个审批状态到审批列表中                insert_audit_array.push({                    tid: change.tid,                    caid: change.id,                    aid: zsAudit.aid,                    times: zsAudit.times,                    order: lastAudit.order + 1,                    status: auditConst.status.checkAgain,                    begin_time: time,                    end_time: time,                    opinion: '',                });                // 新增2个审批人到审批列表中                insert_audit_array.push({                    tid: change.tid,                    caid: change.id,                    aid: zsAudit.aid,                    times: zsAudit.times,                    order: lastAudit.order + 2,                    status: auditConst.status.checking,                    begin_time: time,                });                await transaction.insert(this.tableName, insert_audit_array);                // 设置变更令审批中                await transaction.update(this.ctx.service.changeApply.tableName, {                    id: change.id,                    status: auditConst.status.checking,                    notice_code: null,                    notice_uid: null,                    decimal: null,                });                await transaction.commit();                result = true;            } catch (error) {                await transaction.rollback();                result = false;            }            return result;        }    }    return ChangeApplyAudit;};
 |