'use strict'; /** * 期计量 数据模型 * * @author Mai * @date 2018/8/13 * @version */ const auditConst = require('../const/audit').stage; const payConst = require('../const/deal_pay.js'); const fs = require('fs'); const path = require('path'); const _ = require('lodash'); module.exports = app => { class Stage extends app.BaseService { /** * 构造函数 * * @param {Object} ctx - egg全局变量 * @return {void} */ constructor(ctx) { super(ctx); this.tableName = 'stage'; } async checkStage(sid) { if (!this.ctx.stage) { const status = auditConst.status; const stage = await this.ctx.service.stage.getDataById(sid); 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 = []; 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; } } else if (shareIds.indexOf(accountId) !== -1) { // 分享人 if (stage.status === status.uncheck) { throw '您无权查看该数据'; } stage.curTimes = stage.status === status.checkNo ? stage.times - 1 : stage.times; stage.curOrder = stage.status === status.checked ? this._.max(this._.map(stage.auditors, 'order')) : stage.curAuditor.order - 1; } this.ctx.stage = stage; let time = this.ctx.stage.readOnly ? this.ctx.stage.cache_time_r : this.ctx.stage.cache_time_l; if (!time) { time = this.ctx.stage.in_time ? this.ctx.stage.in_time : new Date(); } this.ctx.stage.cacheTime = time.getTime();//this.ctx.stage.readOnly ? (this.ctx.stage.cache_time_r).getTime(): (this.ctx.stage.cache_time_l).getTime(); } } /** * 获取 最新一期 期计量 * @param tenderId * @param includeUnCheck * @returns {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); return stage; } /** * 获取 最新一期 审批完成的 期计量 * @param tenderId * @returns {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); return stage; } /** * 获取标段下的期列表(报表选择用,只需要一些key信息,不需要计算详细数据,也懒得一个个字段写了,用*来处理) * @param tenderId * @returns {Promise} */ 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 * @returns {Promise} */ 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 && stage.check_calc) { const curAuditor = await this.ctx.service.stageAudit.getCurAuditor(stage.id, stage.times); const isActive = curAuditor ? curAuditor.id === this.ctx.session.sessionUser.accountId : stage.user_id === this.ctx.session.sessionUser.accountId; stage.curTimes = stage.status === auditConst.status.checkNo ? stage.times - 1 : stage.times; stage.curOrder = curAuditor ? curAuditor.order : 0; if (isActive) { const tpData = await this.ctx.service.stageBills.getSumTotalPrice(stage); stage.contract_tp = tpData.contract_tp; stage.qc_tp = tpData.qc_tp; stage.yf_tp = await this.ctx.service.stagePay.getYfTotalPrice(stage); } } } /** * 获取标段下的全部计量期,按倒序 * @param tenderId * @returns {Promise} */ 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); } if (stages.length !== 0) { const lastStage = stages[stages.length - 1]; if (lastStage.status === auditConst.status.uncheck && lastStage.user_id !== this.ctx.session.sessionUser.accountId) { stages.splice(stages.length - 1, 1); } } // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算 if (stages.length > 0 && stages[0].status !== auditConst.status.checked) { const stage = stages[0]; const curAuditor = await this.ctx.service.stageAudit.getCurAuditor(stage.id, stage.times); const isActive = curAuditor ? curAuditor.id === this.ctx.session.sessionUser.accountId : stage.user_id === this.ctx.session.sessionUser.accountId; if (isActive) { stage.curTimes = stage.times; stage.curOrder = curAuditor ? curAuditor.order : 0; const tpData = await this.ctx.service.stageBills.getSumTotalPrice(stage); stage.contract_tp = tpData.contract_tp; stage.qc_tp = tpData.qc_tp; stage.yf_tp = await this.ctx.service.stagePay.getYfTotalPrice(stage); stage.tp = this.ctx.helper.add(stage.contract_tp, stage.qc_tp); stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp); } } return stages; } /** * * @param tenderId - 标段id * @param date - 计量年月 * @param period - 开始-截止日期 * @returns {Promise} */ 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: order, in_time: new Date(), s_time: date, period: 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); } 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 '新增期合同支付数据失败'; } 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 - 开始-截止时间 * @returns {Promise} */ async saveStage(tenderId, order, date, period) { await this.db.update(this.tableName, { s_time: date, period: period, }, { where: { tid: tenderId, order: order } }); } /** * 设置 中间计量 生成规则,并生成数据 * @param {Number} tenderId - 标段id * @param {Number} order - 期序号 * @param {Number} data - 中间计量生成规则 * @returns {Promise} */ 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: order } }); // to do 生成中间计量数据 await conn.commit(); } catch (err) { await conn.rollback(); throw err; } } /** * 获取 当期的 计算基数 * @returns {Promise} */ async getStagePayCalcBase(stage, tenderInfo) { const calcBase = JSON.parse(JSON.stringify(payConst.calcBase)); const param = tenderInfo.deal_param; 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': const sum = await this.ctx.service.stageBills.getSumTotalPrice(stage); cb.value = this.ctx.helper.add(sum.contract_tp, sum.qc_tp); break; case 'ybbqwc': const sumGcl = await this.ctx.service.stageBills.getSumTotalPriceGcl(stage, '^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(sid, check) { const result = await this.db.update(this.tableName, {id: sid, 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 * @returns {Promise} */ async deleteStage(id) { const transaction = await this.db.beginTransaction(); try { await transaction.delete(this.tableName, { 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: { sid: id } }); 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, { sid: id }); await transaction.commit(); return true; } catch (err) { await transaction.rollback(); throw err; } } /** * 获取 多期的 计算基数 -(材料调差调用) * @returns {Promise} */ async getMaterialCalcBase(stage_list, tenderInfo) { const calcBase = JSON.parse(JSON.stringify(payConst.calcBase)); const param = tenderInfo.deal_param; 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': const sum = await this.ctx.service.stageBills.getSumTotalPriceByMaterial(stage_list); cb.value = this.ctx.helper.add(sum.contract_tp, sum.qc_tp); break; case 'ybbqwc': const sumGcl = await this.ctx.service.stageBills.getSumTotalPriceGclByMaterial(stage_list, '^1[0-9]{2}-'); cb.value = this.ctx.helper.add(sumGcl.contract_tp, sumGcl.qc_tp); break; default: cb.value = 0; } } return calcBase; } /** * 获取必要的stage信息调用curTimes, curOrder, id , times, curAuditor(材料调差) * @param stage_id_list * @returns {Promise} */ 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; };