| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783 | 'use strict';/** * 期计量 数据模型 * * @author Mai * @date 2018/8/13 * @version */const auditConst = require('../const/audit').stage;const payConst = require('../const/deal_pay.js');const roleRelSvr = require('./role_rpt_rel');const fs = require('fs');const path = require('path');const _ = require('lodash');const projectLogConst = require('../const/project_log');const syncApiConst = require('../const/sync_api');const RevisePrice = require('../lib/revise_price');module.exports = app => {    class Stage extends app.BaseService {        /**         * 构造函数         *         * @param {Object} ctx - egg全局变量         * @return {void}         */        constructor(ctx) {            super(ctx);            this.tableName = 'stage';        }        /**         * 根据id查找数据         *         * @param {Number} id - 数据库中的id         * @return {Object} - 返回单条数据         */        async getDataById(id) {            const result = await this.db.get(this.tableName, { id });            if (result) { result.tp_history = result.tp_history ? JSON.parse(result.tp_history) : []; }            return result;        }        /**         * 根据条件查找单条数据         *         * @param {Object} condition - 筛选条件         * @return {Object} - 返回单条数据         */        async getDataByCondition(condition) {            const result = await this.db.get(this.tableName, condition);            if (result) { result.tp_history = result.tp_history ? JSON.parse(result.tp_history) : []; }            return result;        }        /**         * 根据条件查找列表数据         *         * @param {Object} condition - 筛选条件         * @return {Array} - 返回数据         */        async getAllDataByCondition(condition) {            const result = await this.db.select(this.tableName, condition);            for (const r of result) {                r.tp_history = r.tp_history ? JSON.parse(r.tp_history) : [];            }            return result;        }        async loadStageUser(stage) {            const status = auditConst.status;            const accountId = this.ctx.session.sessionUser.accountId;            stage.auditors = await this.ctx.service.stageAudit.getAuditors(stage.id, stage.times);            stage.curAuditor = await this.ctx.service.stageAudit.getCurAuditor(stage.id, stage.times);            stage.assists = await this.service.stageAuditAss.getData(stage);            stage.userAssists = stage.assists.filter(x => { return x.user_id === stage.user_id; }); // 原报协同人            stage.auditAssists = stage.assists.filter(x => { return x.user_id !== stage.user_id; }); // 审批协同人            stage.relaAssists = stage.assists.filter(x => { return x.user_id === accountId });            stage.auditorIds = this._.map(stage.auditors, 'aid');            stage.userAssistIds = this._.map(stage.userAssists, 'ass_user_id');            stage.auditAssistIds = this._.map(stage.auditAssists, 'ass_user_id');            stage.users = stage.status === status.uncheck                ? [stage.user_id, ...stage.userAssistIds]                : [stage.user_id, ...stage.userAssistIds, ...stage.auditorIds, ...stage.auditAssistIds];        }        async doCheckStage(stage, force = false) {            const status = auditConst.status;            await this.loadStageUser(stage);            const accountId = this.ctx.session.sessionUser.accountId, shareIds = [];            const isTenderTourist = await this.service.tenderTourist.getDataByCondition({ tid: stage.tid, user_id: accountId });            const permission = this.ctx.session.sessionUser.permission;            if (stage.status === status.uncheck) {                stage.readOnly = accountId !== stage.user_id && stage.userAssistIds.indexOf(accountId) < 0;                if (!stage.readOnly) {                    stage.assist = stage.userAssists.find(x => { return x.ass_user_id === accountId; });                }                stage.curTimes = stage.times;                stage.curOrder = 0;            } else if (stage.status === status.checkNo) {                stage.readOnly = accountId !== stage.user_id && stage.userAssistIds.indexOf(accountId) < 0;                const checkNoAudit = await this.service.stageAudit.getDataByCondition({                    sid: stage.id, times: stage.times - 1, status: status.checkNo,                });                if (!stage.readOnly) {                    stage.assist = stage.userAssists.find(x => { return x.ass_user_id === accountId; });                    stage.curTimes = stage.times;                    stage.curOrder = 0;                } else {                    stage.curTimes = stage.times - 1;                    stage.curOrder = checkNoAudit.order;                }            } else if (stage.status === status.checked) {                stage.readOnly = true;                stage.curTimes = stage.times;                stage.curOrder = _.max(_.map(stage.auditors, 'order'));            } else {                const ass = stage.auditAssists.find(x => { return x.user_id === stage.curAuditor.aid && x.ass_user_id === accountId; });                stage.readOnly = stage.curAuditor.aid !== accountId && !ass;                stage.curTimes = stage.times;                if (!stage.readOnly) {                    stage.assist = ass;                    stage.curOrder = stage.curAuditor.order;                } else {                    stage.curOrder = stage.curAuditor.order - 1;                }            }            if (stage.readOnly) {                stage.assist = accountId === stage.user_id || stage.auditorIds.indexOf(accountId) >= 0                    ? null                    : stage.assists.find(x => { return x.ass_user_id === accountId});            }            if (stage.users.indexOf(accountId) >= 0) {                stage.filePermission = true;            } else if (!!isTenderTourist || force) {                stage.filePermission = this.tender && this.tender.touristPermission ? this.tender.touristPermission.file : false;            } else {                stage.filePermission = false;            }            // } else {            //     if (shareIds.indexOf(accountId) !== -1 || (permission !== null && permission.tender !== undefined && permission.tender.indexOf('2') !== -1)) {// 分享人            //         if (stage.status === status.uncheck) {            //             throw '您无权查看该数据';            //         }            //         stage.filePermission = false;            //     } else {            //         throw '您无权查看该数据';            //     }            // }            let time = stage.readOnly ? stage.cache_time_r : stage.cache_time_l;            if (!time) time = stage.in_time ? stage.in_time : new Date();            stage.cacheTime = time.getTime();            // 历史台账            if (stage.status === status.checked) {                stage.ledgerHis = await this.service.ledgerHistory.getDataById(stage.his_id);            }            return stage;        }        async checkStage(sid) {            if (!this.ctx.stage) {                const stage = await this.ctx.service.stage.getDataById(sid);                if (!stage) throw '校验的期数据不存在';                await this.doCheckStage(stage);                this.ctx.stage = stage;            }        }        /**         * 获取 最新一期 期计量         * @param tenderId         * @param includeUnCheck         * @return {Promise<*>}         */        async getLastestStage(tenderId, includeUnCheck = false) {            this.initSqlBuilder();            this.sqlBuilder.setAndWhere('tid', {                value: tenderId,                operate: '=',            });            if (!includeUnCheck) {                this.sqlBuilder.setAndWhere('status', {                    value: auditConst.status.uncheck,                    operate: '!=',                });            }            this.sqlBuilder.orderBy = [['order', 'desc']];            const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);            const stage = await this.db.queryOne(sql, sqlParam);            if (stage) stage.tp_history = stage.tp_history ? JSON.parse(stage.tp_history) : [];            return stage;        }        /**         * 获取 最新一期 审批完成的 期计量         * @param tenderId         * @return {Promise<*>}         */        async getLastestCompleteStage(tenderId) {            this.initSqlBuilder();            this.sqlBuilder.setAndWhere('tid', {                value: tenderId,                operate: '=',            });            this.sqlBuilder.setAndWhere('status', {                value: auditConst.status.checked,                operate: '=',            });            this.sqlBuilder.orderBy = [['order', 'desc']];            const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);            const stage = await this.db.queryOne(sql, sqlParam);            if (stage) stage.tp_history = stage.tp_history ? JSON.parse(stage.tp_history) : [];            return stage;        }        /**         * 获取标段下的期列表(报表选择用,只需要一些key信息,不需要计算详细数据,也懒得一个个字段写了,用*来处理)         * @param tenderId         * @return {Promise<void>}         */        async getValidStagesShort(tenderId) {            const sql = 'select * from zh_stage where tid = ? order by zh_stage.order';            const sqlParam = [tenderId];            return await this.db.query(sql, sqlParam);        }        /**         * 获取某一期信息(报表用)         * @param stageId         * @return {Promise<void>}         */        async getStageById(stageId) {            const sql = 'select * from zh_stage where id = ? order by zh_stage.order';            const sqlParam = [stageId];            return await this.db.query(sql, sqlParam);        }        async checkStageGatherData(stage, force = false) {            // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算            if (stage.status !== auditConst.status.checked) {                await this.doCheckStage(stage, force);                if (!stage.readOnly && stage.check_calc) {                    const tpData = await this.ctx.service.stageBills.getSumTotalPrice(stage);                    const pcSum = await this.ctx.service.stageBillsPc.getSumTotalPrice(stage);                    stage.contract_tp = tpData.contract_tp;                    stage.qc_tp = tpData.qc_tp;                    stage.positive_qc_tp = tpData.positive_qc_tp;                    stage.negative_qc_tp = tpData.negative_qc_tp;                    stage.contract_pc_tp = pcSum.contract_pc_tp;                    stage.qc_pc_tp = pcSum.qc_pc_tp;                    stage.pc_tp = pcSum.pc_tp;                    stage.positive_qc_pc_tp = pcSum.positive_qc_pc_tp;                    stage.negative_qc_pc_tp = pcSum.negative_qc_pc_tp;                    stage.tp = this.ctx.helper.sum([stage.contract_tp, stage.qc_tp, stage.pc_tp]);                    const tp = await this.ctx.service.stagePay.getSpecialTotalPrice(stage);                    stage.yf_tp = tp.yf;                    stage.sf_tp = tp.sf;                    stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);                    await this.update({                        check_calc: false,                        contract_tp: stage.contract_tp, qc_tp: stage.qc_tp,                        positive_qc_tp: stage.positive_qc_tp, negative_qc_tp: stage.negative_qc_tp,                        contract_pc_tp: stage.contract_pc_tp || 0, qc_pc_tp: stage.qc_pc_tp || 0, pc_tp: stage.pc_tp || 0,                        positive_qc_pc_tp: stage.positive_qc_pc_tp || 0, negative_qc_pc_tp: stage.negative_qc_pc_tp || 0,                        yf_tp: stage.yf_tp, sf_tp: stage.sf_tp,                    }, { id: stage.id });                } else if (stage.tp_history) {                    const his = this.ctx.helper._.find(stage.tp_history, { times: stage.curTimes, order: stage.curOrder });                    if (his) {                        stage.contract_tp = his.contract_tp;                        stage.qc_tp = his.qc_tp;                        stage.positive_qc_tp = his.positive_qc_tp;                        stage.negative_qc_tp = his.negative_qc_tp;                        stage.yf_tp = his.yf_tp;                        stage.sf_tp = his.sf_tp;                        stage.tp = this.ctx.helper.sum([stage.contract_tp, stage.qc_tp, stage.pc_tp]);                        stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);                    }                }            }        }        /**         * 获取标段下的全部计量期,按倒序         * @param tenderId         * @return {Promise<void>}         */        async getValidStages(tenderId) {            const stages = await this.db.select(this.tableName, {                where: { tid: tenderId },                orders: [['order', 'desc']],            });            for (const s of stages) {                s.tp = this.ctx.helper.sum([s.contract_tp, s.qc_tp, s.pc_tp]);                s.pre_tp = this.ctx.helper.add(s.pre_contract_tp, s.pre_qc_tp);                s.end_tp = this.ctx.helper.add(s.pre_tp, s.tp);                s.tp_history = s.tp_history ? JSON.parse(s.tp_history) : [];            }            if (stages.length !== 0 && !this.ctx.session.sessionUser.is_admin) {                const lastStage = stages[0];                if (lastStage.status === auditConst.status.uncheck && !this.ctx.tender.isTourist) {                    const assist = await this.ctx.service.auditAss.getAllDataByCondition({ where: { tid: tenderId, user_id: lastStage.user_id } });                    const assistId = assist.map(x => { return x.ass_user_id });                    if (lastStage.user_id !== this.ctx.session.sessionUser.accountId && assistId.indexOf(this.ctx.session.sessionUser.accountId) < 0) {                        stages.splice(0, 1);                    }                }            }            // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算            if (stages.length === 0) return stages;            await this.checkStageGatherData(stages[0], true);            for (const s of stages) {                if (s.yf_tp && s.sf_tp === 0) {                    const sf = await this.ctx.service.stagePay.getHistorySf(s);                    if (sf && s.readOnly) {                        await this.ctx.service.stage.update({ sf_tp: sf.tp, pre_sf_tp: sf.pre_tp }, { id: s.id });                    }                    s.sf_tp = sf.tp;                }            }            return stages;        }        async _getSumTp(condition, ...field) {            const fieldSql = [];            for (const f of field) {                fieldSql.push('SUM(`' + f + '`) as ' + '`' + f + '`');            }            const sql = 'SELECT ' + fieldSql.join(', ') + ' FROM ' + this.tableName + ' ' + this.ctx.helper.whereSql(condition);            return await this.db.queryOne(sql);        }        /**         *         * @param tenderId - 标段id         * @param date - 计量年月         * @param period - 开始-截止日期         * @return {Promise<void>}         */        async addStage(tenderId, date, period) {            const stages = await this.getAllDataByCondition({                where: { tid: tenderId },                order: ['order'],            });            const preStage = stages[stages.length - 1];            if (stages.length > 0 && stages[stages.length - 1].status !== auditConst.status.checked) {                throw '上一期未审批通过,请等待上一期审批通过后,再新增数据';            }            const order = stages.length + 1;            const newStage = {                sid: this.uuid.v4(),                tid: tenderId,                order,                in_time: new Date(),                s_time: date,                period,                times: 1,                status: auditConst.status.uncheck,                user_id: this.ctx.session.sessionUser.accountId,                check_calc: false,            };            newStage.cache_time_l = newStage.in_time;            newStage.cache_time_r = newStage.in_time;            if (preStage) {                newStage.im_type = preStage.im_type;                newStage.im_pre = preStage.im_pre;                newStage.im_gather = preStage.im_gather;                newStage.im_gather_node = preStage.im_gather_node;                newStage.pre_contract_tp = this.ctx.helper.sum([preStage.pre_contract_tp, preStage.contract_tp, preStage.contract_pc_tp]);                newStage.pre_qc_tp = this.ctx.helper.sum([preStage.pre_qc_tp, preStage.qc_tp, preStage.qc_pc_tp]);                newStage.pre_positive_qc_tp = this.ctx.helper.sum([preStage.pre_positive_qc_tp, preStage.positive_qc_tp, preStage.positive_qc_pc_tp]);                newStage.pre_negative_qc_tp = this.ctx.helper.sum([preStage.pre_negative_qc_tp, preStage.negative_qc_tp, preStage.negative_qc_pc_tp]);                newStage.pre_yf_tp = this.ctx.helper.add(preStage.pre_yf_tp, preStage.yf_tp);                if (preStage.order === 1 || preStage.pre_sf_tp) {                    newStage.pre_sf_tp = this.ctx.helper.add(preStage.pre_sf_tp, preStage.sf_tp);                } else {                    const sumTp = await this._getSumTp({tid: preStage.tid}, 'sf_tp');                    newStage.pre_sf_tp = sumTp.sf_tp || 0;                }            } else {                const projFunRela = await this.ctx.service.project.getFunRela(this.ctx.session.sessionProject.id);                newStage.im_type = projFunRela.imType;            }            const transaction = await this.db.beginTransaction();            try {                // 新增期记录                const result = await transaction.insert(this.tableName, newStage);                if (result.affectedRows === 1) {                    newStage.id = result.insertId;                } else {                    throw '新增期数据失败';                }                // 存在上一期时,复制上一期审批流程                if (preStage) {                    const auditResult = await this.ctx.service.stageAudit.copyPreStageAuditors(transaction, preStage, newStage);                    if (!auditResult) {                        throw '复制上一期审批流程失败';                    }                }                // 新增期合同支付数据                const dealResult = await this.ctx.service.stagePay.addInitialStageData(newStage, transaction);                if (!dealResult) {                    throw '新增期合同支付数据失败';                }                // 新增期其他台账数据                if (preStage) {                    const jgclResult = await this.ctx.service.stageJgcl.addInitialStageData(newStage, preStage, transaction);                    if (!jgclResult) throw '初始化甲供材料数据失败';                    const otherResult = await this.ctx.service.stageOther.addInitialStageData(newStage, preStage, transaction);                    if (!otherResult) throw '初始化其他台账数据失败';                    const safeResult = await this.ctx.service.stageSafeProd.addInitialStageData(newStage, preStage, transaction);                    if (!safeResult) throw '初始化其他台账数据失败';                    const tempResult = await this.ctx.service.stageTempLand.addInitialStageData(newStage, preStage, transaction);                    if (!tempResult) throw '初始化其他台账数据失败';                    const priceCalc = new RevisePrice(this.ctx);                    await priceCalc.newStagePriceChange(newStage, preStage, transaction);                }                // 新增期拷贝报表相关配置/签名角色 等                if (preStage) {                    const rptResult = await this.ctx.service.rptCustomDefine.addInitialStageData(newStage, preStage, transaction);                    await this.ctx.service.roleRptRel.addInitialStageData(tenderId, newStage, preStage);                }                await transaction.commit();                // 通知发送 - 第三方更新                if (this.ctx.session.sessionProject.custom && syncApiConst.notice_type.indexOf(this.ctx.session.sessionProject.customType) !== -1) {                    const base_data = {                        tid: tenderId,                        sid: result.insertId,                        op: 'insert',                    };                    this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));                    // 存在上一期时                    base_data.op = preStage ? 'update' : 'insert';                    base_data.sid = -1;                    this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));                }                return newStage;            } catch (err) {                await transaction.rollback();                throw err;            }        }        /**         * 编辑计量期         *         * @param {Number} tenderId - 标段Id         * @param {Number} order - 第N期         * @param {String} date - 计量年月         * @param {String} period - 开始-截止时间         * @return {Promise<void>}         */        async saveStage(tenderId, order, date, period) {            await this.db.update(this.tableName, {                s_time: date,                period,            }, { where: { tid: tenderId, order } });        }        /**         * 设置 中间计量 生成规则,并生成数据         * @param {Number} tenderId - 标段id         * @param {Number} order - 期序号         * @param {Number} data - 中间计量生成规则         * @return {Promise<void>}         */        async buildDetailData(tenderId, order, data) {            const conn = await this.db.beginTransaction();            try {                await conn.update(this.tableName, { im_type: data.im_type, im_pre: data.im_pre , im_start_num: data.im_start_num }, { where: { tid: tenderId, order } });                // to do 生成中间计量数据                await conn.commit();            } catch (err) {                await conn.rollback();                throw err;            }        }        async getChangeSubtotal(stage) {            const result = {};            const bg = await this.ctx.service.stageChange.getSubtotal(stage);            const importBg = await this.ctx.service.stageImportChange.getSubtotal(stage);            result.common = this.ctx.helper.add(bg.common, importBg.common);            result.great = this.ctx.helper.add(bg.great, importBg.great);            result.more = this.ctx.helper.add(bg.more, importBg.more);            return result;        }        /**         * 获取 当期的 计算基数         * @return {Promise<any>}         */        async getStagePayCalcBase(stage, tenderInfo) {            const calcBase = JSON.parse(JSON.stringify(payConst.calcBase));            const param = tenderInfo.deal_param;            const sum = await this.ctx.service.stageBills.getSumTotalPrice(stage);            const pcSum = await this.ctx.service.stageBillsPc.getSumTotalPrice(stage);            const bg = await this.getChangeSubtotal(stage);            for (const cb of calcBase) {                switch (cb.code) {                    case 'htj':                        cb.value = param.contractPrice;                        break;                    case 'zlje':                        cb.value = param.zanLiePrice;                        break;                    case 'htjszl':                        cb.value = this.ctx.helper.sub(param.contractPrice, param.zanLiePrice);                        break;                    case 'kgyfk':                        cb.value = param.startAdvance;                        break;                    case 'clyfk':                        cb.value = param.materialAdvance;                        break;                    case 'bqwc':                        cb.value = this.ctx.helper.sum([sum.contract_tp, sum.qc_tp, pcSum.pc_tp]);                        break;                    case 'bqht':                        cb.value = sum.contract_tp; //this.ctx.helper.add(sum.contract_tp, pcSum.contract_pc_tp);                        break;                    case 'bqbg':                        cb.value = sum.qc_tp; //this.ctx.helper.add(sum.qc_tp, pcSum.qc_pc_tp);                        break;                    case 'ybbqwc':                        const sumGcl = await this.ctx.service.stageBills.getSumTotalPriceGcl(stage, '^[^0-9]*1[0-9]{2}(-|$)');                        cb.value = this.ctx.helper.add(sumGcl.contract_tp, sumGcl.qc_tp);                        break;                    case 'ybbqbg':                        cb.value = bg.common;                        break;                    case 'jdbqbg':                        cb.value = bg.more;                        break;                    case 'zdbqbg':                        cb.value = bg.great;                        break;                    default:                        cb.value = 0;                }            }            return calcBase;        }        async updateCheckCalcFlag(stage, check) {            const result = await this.db.update(this.tableName, { id: stage.id, check_calc: check });            return result.affectedRows === 1;        }        async updateCacheTime(sid) {            const result = await this.db.update(this.tableName, { id: sid, cache_time_l: new Date() });            return result.affectedRows === 1;        }        /**         * 删除计量期         *         * @param {Number} id - 期Id         * @return {Promise<void>}         */        async deleteStage(id) {            const transaction = await this.db.beginTransaction();            try {                const stageInfo = await this.getDataById(id);                // 通知发送 - 第三方更新                // if (this.ctx.session.sessionProject.custom && syncApiConst.notice_type.indexOf(this.ctx.session.sessionProject.customType) !== -1) {                //     const base_data = {                //         tid: this.ctx.tender.id,                //         sid: id,                //         op: 'delete',                //     };                //     await this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));                //     // 是否还存在其他期                //     base_data.op = stageInfo.order === 1 ? 'delete' : 'update';                //     base_data.sid = -1;                //     await this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));                // }                await transaction.delete(this.tableName, { id });                await transaction.delete(this.ctx.service.pos.tableName, { add_stage: id });                await transaction.delete(this.ctx.service.stageAudit.tableName, { sid: id });                await transaction.delete(this.ctx.service.stageBills.tableName, { sid: id });                await transaction.delete(this.ctx.service.stageChange.tableName, { sid: id });                await transaction.delete(this.ctx.service.stageChangeFinal.tableName, { sid: id });                await transaction.delete(this.ctx.service.stageImportChange.tableName, { sid: id });                await transaction.delete(this.ctx.service.stagePos.tableName, { sid: id });                await transaction.delete(this.ctx.service.stageDetail.tableName, { sid: id });                await transaction.delete(this.ctx.service.stagePosFinal.tableName, { sid: id });                await transaction.delete(this.ctx.service.stageBillsFinal.tableName, { sid: id });                await transaction.delete(this.ctx.service.stageRela.tableName, { sid: id });                await transaction.delete(this.ctx.service.stageRelaBills.tableName, { sid: id });                await transaction.delete(this.ctx.service.stageRelaBillsFinal.tableName, { sid: id });                await transaction.delete(this.ctx.service.stageRelaIm.tableName, { sid: id });                await transaction.delete(this.ctx.service.stageRelaImBills.tableName, { sid: id });                await transaction.delete(this.ctx.service.stageAuditAss.tableName, { sid: id });                // 删除计量合同支付附件                const payList = await this.ctx.service.stagePay.getAllDataByCondition({ where: { sid: id } });                if (payList) {                    for (const pt of payList) {                        if (pt.attachment !== null && pt.attachment !== '') {                            const payAttList = JSON.parse(pt.attachment);                            for (const pat of payAttList) {                                if (fs.existsSync(path.join(this.app.baseDir, pat.filepath))) {                                    await fs.unlinkSync(path.join(this.app.baseDir, pat.filepath));                                }                            }                        }                    }                }                await transaction.delete(this.ctx.service.stagePay.tableName, { sid: id });                await this.ctx.service.pay.doDeleteStage(stageInfo, transaction);                // 删除计量附件文件                const attList = await this.ctx.service.stageAtt.getAllDataByCondition({ where: { tid: stageInfo.tid, sid: stageInfo.order } });                if (attList.length !== 0) {                    for (const att of attList) {                        if (fs.existsSync(path.join(this.app.baseDir, att.filepath))) {                            await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));                        }                    }                }                await transaction.delete(this.ctx.service.stageAtt.tableName, { tid: stageInfo.tid, sid: stageInfo.order });                // 其他台账                await transaction.delete(this.ctx.service.stageJgcl.tableName, { sid: id });                const bonus = await this.ctx.service.stageBonus.getStageData(id);                if (bonus && bonus.length > 0) {                    for (const b of bonus) {                        for (const f of b.proof_file) {                            if (fs.existsSync(path.join(this.app.baseDir, f.filepath))) {                                await fs.unlinkSync(path.join(this.app.baseDir, f.filepath));                            }                        }                    }                }                await transaction.delete(this.ctx.service.stageBonus.tableName, { sid: id });                await transaction.delete(this.ctx.service.stageOther.tableName, { sid: id });                // 同步删除进度里所选的期                await transaction.delete(this.ctx.service.scheduleStage.tableName, { tid: stageInfo.tid, order: stageInfo.order });                const detailAtt = await this.ctx.service.stageDetailAtt.getAllDataByCondition({ where: { sid: id } });                if (detailAtt && detailAtt.length > 0) {                    for (const da of detailAtt) {                        da.attachment = da.attachment ? JSON.parse(da.attachment) : [];                        for (const daa of da.attachment) {                            if (fs.existsSync(path.join(this.app.baseDir, daa.filepath))) {                                await fs.unlinkSync(path.join(this.app.baseDir, daa.filepath));                            }                        }                    }                }                await transaction.delete(this.ctx.service.stageDetailAtt.tableName, { sid: id });                // 重算进度计量总金额                await this.ctx.service.scheduleStage.calcStageSjTp(transaction, stageInfo.tid);                // 删除收方单及附件                const shoufangAttList = await this.ctx.service.stageShoufangAtt.getAllDataByCondition({ where: { sid: id } });                if (shoufangAttList.length !== 0) {                    for (const att of shoufangAttList) {                        if (fs.existsSync(path.join(this.app.baseDir, att.filepath))) {                            await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));                        }                    }                }                await transaction.delete(this.ctx.service.stageShoufangAtt.tableName, { sid: id });                const shoufangList = await this.ctx.service.stageShoufang.getAllDataByCondition({ where: { sid: id } });                if (shoufangList.length !== 0) {                    for (const att of shoufangList) {                        if (fs.existsSync(path.join(this.app.baseDir, 'app/' + att.qrcode))) {                            await fs.unlinkSync(path.join(this.app.baseDir, 'app/' + att.qrcode));                        }                    }                }                await transaction.delete(this.ctx.service.stageShoufang.tableName, { sid: id });                await transaction.delete(this.ctx.service.cooperationConfirm.tableName, { sid: id });                // 记录删除日志                await this.ctx.service.projectLog.addProjectLog(transaction, projectLogConst.type.stage, projectLogConst.status.delete, '第' + stageInfo.order + '期');                await transaction.commit();                return true;            } catch (err) {                await transaction.rollback();                throw err;            }        }        /**         * 获取 多期的 计算基数 -(材料调差调用)         * @return {Promise<any>}         */        async getMaterialCalcBase(stage_list, tenderInfo) {            const calcBase = JSON.parse(JSON.stringify(payConst.calcBase));            const param = tenderInfo.deal_param;            const sum = await this.ctx.service.stageBills.getSumTotalPriceByMaterial(stage_list);            const pcSum = await this.ctx.service.stageBillsPc.getSumTotalPriceByMaterial(stage_list);            for (const cb of calcBase) {                switch (cb.code) {                    case 'htj':                        cb.value = param.contractPrice;                        break;                    case 'zlje':                        cb.value = param.zanLiePrice;                        break;                    case 'htjszl':                        cb.value = this.ctx.helper.sub(param.contractPrice, param.zanLiePrice);                        break;                    case 'kgyfk':                        cb.value = param.startAdvance;                        break;                    case 'clyfk':                        cb.value = param.materialAdvance;                        break;                    case 'bqwc':                        cb.value = this.ctx.helper.sum([sum.contract_tp, sum.qc_tp, pcSum.pc_tp]);                        break;                    case 'bqht':                        cb.value = sum.contract_tp;                        break;                    case 'bqbg':                        cb.value = sum.qc_tp;                        break;                    case 'ybbqwc':                        const sumGcl = await this.ctx.service.stageBills.getSumTotalPriceGclByMaterial(stage_list, '^[^0-9]*1[0-9]{2}(-|$)');                        cb.value = this.ctx.helper.add(sumGcl.contract_tp, sumGcl.qc_tp);                        break;                    case 'bqyf':                        cb.value = this.ctx.helper.roundNum(this._.sumBy(stage_list, 'yf_tp'), 2);                        break;                    default:                        cb.value = 0;                }            }            return calcBase;        }        /**         * 获取必要的stage信息调用curTimes, curOrder, id , times, curAuditor(材料调差)         * @param stage_id_list         * @return {Promise<void>}         */        async getStageMsgByStageId(stage_id_list) {            const list = [];            stage_id_list = stage_id_list.toString().split(',');            for (const sid of stage_id_list) {                const stage = await this.getDataById(sid);                stage.auditors = await this.service.stageAudit.getAuditors(stage.id, stage.times);                stage.curAuditor = await this.service.stageAudit.getCurAuditor(stage.id, stage.times);                stage.curOrder = _.max(_.map(stage.auditors, 'order'));                stage.curTimes = stage.times;                list.push(stage);            }            return list;        }        async getStageByDataCollect(tenderId) {            const stages = await this.db.select(this.tableName, {                columns: ['s_time', 'contract_tp', 'qc_tp', 'pc_tp', 'pre_contract_tp', 'pre_qc_tp'],                where: { tid: tenderId },                orders: [['order', 'desc']],            });            for (const s of stages) {                s.tp = this.ctx.helper.sum([s.contract_tp, s.qc_tp, s.pc_tp]);                s.pre_tp = this.ctx.helper.add(s.pre_contract_tp, s.pre_qc_tp);                s.end_tp = this.ctx.helper.add(s.pre_tp, s.tp);            }            return stages;        }        async isLastStage(tid, sid) {            const lastStage = await this.ctx.service.stage.getLastestStage(tid, true);            return lastStage ? lastStage.id === sid : false;        }    }    return Stage;};
 |