| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633 | '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');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 doCheckStage(stage) {            const status = auditConst.status;            stage.auditors = await this.ctx.service.stageAudit.getAuditors(stage.id, stage.times);            stage.curAuditor = await this.ctx.service.stageAudit.getCurAuditor(stage.id, stage.times);            const accountId = this.ctx.session.sessionUser.accountId,                auditorIds = this._.map(stage.auditors, 'aid'),                shareIds = [];            const permission = this.ctx.session.sessionUser.permission;            if (accountId === stage.user_id) { // 原报                if (stage.curAuditor) {                    stage.readOnly = stage.curAuditor.aid !== accountId;                } else {                    stage.readOnly = stage.status !== status.uncheck && stage.status !== status.checkNo;                }                stage.curTimes = stage.times;                if (stage.status === status.uncheck || stage.status === status.checkNo) {                    stage.curOrder = 0;                } else if (stage.status === status.checked) {                    stage.curOrder = this._.max(this._.map(stage.auditors, 'order'));                } else {                    stage.curOrder = stage.curAuditor.aid === accountId ? stage.curAuditor.order : stage.curAuditor.order - 1;                }            } else if (auditorIds.indexOf(accountId) !== -1) { // 审批人                if (stage.status === status.uncheck) {                    throw '您无权查看该数据';                }                stage.curTimes = stage.status === status.checkNo ? stage.times - 1 : stage.times;                if (stage.status === status.checked) {                    stage.curOrder = this._.max(this._.map(stage.auditors, 'order'));                } else if (stage.status === status.checkNo) {                    const audit = await this.service.stageAudit.getDataByCondition({                        sid: stage.id, times: stage.times - 1, status: status.checkNo,                    });                    stage.curOrder = audit.order;                } else {                    stage.curOrder = accountId === stage.curAuditor.aid ? stage.curAuditor.order : stage.curAuditor.order - 1;                }                stage.readOnly = (stage.status !== status.checking && stage.status !== status.checkNoPre) || accountId !== stage.curAuditor.aid;            } else if (shareIds.indexOf(accountId) !== -1 || (permission !== null && permission.tender !== undefined && permission.tender.indexOf('2') !== -1)) { // 分享人                if (stage.status === status.uncheck) {                    throw '您无权查看该数据';                }                stage.readOnly = true;                stage.curTimes = stage.status === status.checkNo ? stage.times - 1 : stage.times;                if (stage.status === status.checkNo) {                    const audit = await this.service.stageAudit.getDataByCondition({                        sid: stage.id, times: stage.times - 1, status: status.checkNo,                    });                    stage.curOrder = audit.order;                } else {                    stage.curOrder = stage.status === status.checked ? this._.max(this._.map(stage.auditors, 'order')) : stage.curAuditor.order - 1;                }            }            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();// this.ctx.stage.readOnly ? (this.ctx.stage.cache_time_r).getTime(): (this.ctx.stage.cache_time_l).getTime();            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) {            // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算            if (stage.status !== auditConst.status.checked) {                await this.doCheckStage(stage);                if (!stage.readOnly && stage.check_calc) {                    const tpData = await this.ctx.service.stageBills.getSumTotalPrice(stage);                    stage.contract_tp = tpData.contract_tp;                    stage.qc_tp = tpData.qc_tp;                    const tp = await this.ctx.service.stagePay.getSpecialTotalPrice(stage);                    stage.yf_tp = tp.yf;                    stage.sf_tp = tp.sf;                    await this.update({                        check_calc: false,                        contract_tp: stage.contract_tp, qc_tp: stage.qc_tp,                        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 });                    // console.log(his);                    if (his) {                        stage.contract_tp = his.contract_tp;                        stage.qc_tp = his.qc_tp;                        stage.yf_tp = his.yf_tp;                        stage.sf_tp = his.sf_tp;                        stage.tp = this.ctx.helper.add(stage.contract_tp, stage.qc_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.add(s.contract_tp, s.qc_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) {                const lastStage = stages[0];                if (lastStage.status === auditConst.status.uncheck && lastStage.user_id !== this.ctx.session.sessionUser.accountId) {                    stages.splice(0, 1);                }            }            // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算            if (stages.length === 0) return stages;            if (stages[0].status !== auditConst.status.checked) {                const stage = stages[0];                await this.doCheckStage(stage);                if (!stage.readOnly) {                    const tpData = await this.ctx.service.stageBills.getSumTotalPrice(stage);                    stage.contract_tp = tpData.contract_tp;                    stage.qc_tp = tpData.qc_tp;                    const tp = await this.ctx.service.stagePay.getSpecialTotalPrice(stage);                    stage.yf_tp = tp.yf;                    stage.sf_tp = tp.sf;                    stage.tp = this.ctx.helper.add(stage.contract_tp, stage.qc_tp);                    stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);                } else {                    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.yf_tp = his.yf_tp;                        stage.sf_tp = his.sf_tp;                        stage.tp = this.ctx.helper.add(stage.contract_tp, stage.qc_tp);                        stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);                    }                }            }            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.add(preStage.pre_contract_tp, preStage.contract_tp);                newStage.pre_qc_tp = this.ctx.helper.add(preStage.pre_qc_tp, preStage.qc_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;                }            }            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 '初始化其他台账数据失败';                }                // 新增期拷贝报表相关配置/签名角色 等                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();                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 }, { where: { tid: tenderId, order } });                // to do 生成中间计量数据                await conn.commit();            } catch (err) {                await conn.rollback();                throw err;            }        }        /**         * 获取 当期的 计算基数         * @return {Promise<any>}         */        async getStagePayCalcBase(stage, tenderInfo) {            const calcBase = JSON.parse(JSON.stringify(payConst.calcBase));            const param = tenderInfo.deal_param;            for (const cb of calcBase) {                const sum = await this.ctx.service.stageBills.getSumTotalPrice(stage);                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.add(sum.contract_tp, sum.qc_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.getSumTotalPriceGcl(stage, '^[^0-9]*1[0-9]{2}-');                        cb.value = this.ctx.helper.add(sumGcl.contract_tp, sumGcl.qc_tp);                        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);                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.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 });                // 删除计量合同支付附件                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 transaction.delete(this.ctx.service.pay.tableName, { csid: id });                // 删除计量附件文件                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 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);            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.add(sum.contract_tp, sum.qc_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;        }        async getSumbqyfByMaterial(stage) {        }        /**         * 获取必要的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.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;        }    }    return Stage;};
 |