'use strict'; /** * 期计量 数据模型 * * @author Mai * @date 2018/8/13 * @version */ const auditConst = require('../const/audit'); 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.stage.status; const accountId = this.ctx.session.sessionUser.accountId; stage.user = await this.ctx.service.projectAccount.getAccountInfoById(stage.user_id); stage.auditors = await this.ctx.service.stageAudit.getAuditors(stage.id, stage.times); // 全部参与的审批人 stage.auditorIds = this._.map(stage.auditors, 'aid'); stage.curAuditors = stage.auditors.filter(x => { return x.status === status.checking; }); // 当前流程中审批中的审批人 stage.curAuditorIds = this._.map(stage.curAuditors, 'aid'); stage.flowAuditors = stage.curAuditors.length > 0 ? stage.auditors.filter(x => { return x.order === stage.curAuditors[0].order; }) : []; // 当前流程中参与的审批人(包含会签时,审批通过的人) stage.flowAuditorIds = this._.map(stage.flowAuditors, 'aid'); stage.nextAuditors = stage.curAuditors.length > 0 ? stage.auditors.filter(x => { return x.order === stage.curAuditors[0].order + 1; }) : []; stage.nextAuditorIds = this._.map(stage.nextAuditors, 'aid'); stage.auditorGroups = this.ctx.helper.groupAuditors(stage.auditors); stage.userGroups = this.ctx.helper.groupAuditorsUniq(stage.auditorGroups); stage.userGroups.unshift([{ aid: stage.user.id, order: 0, times: stage.times, audit_order: 0, audit_type: auditConst.auditType.key.common, name: stage.user.name, role: stage.user.role, company: stage.user.company }]); stage.finalAuditorIds = stage.userGroups[stage.userGroups.length - 1].map(x => { return x.aid; }); stage.relaAuditor = this._.findLast(stage.auditors, x => { return x.aid === accountId }); stage.assists = await this.service.stageAuditAss.getData(stage); // 全部协同人 stage.assists = stage.assists.filter(x => { return x.user_id === stage.user_id || stage.auditorIds.indexOf(x.user_id) >= 0; }); // 过滤无效协同人 stage.userAssists = stage.assists.filter(x => { return x.user_id === stage.user_id; }); // 原报协同人 stage.userAssistIds = this._.map(stage.userAssists, 'ass_user_id'); stage.auditAssists = stage.assists.filter(x => { return x.user_id !== stage.user_id; }); // 审批协同人 stage.auditAssistIds = this._.map(stage.auditAssists, 'ass_user_id'); stage.relaAssists = stage.assists.filter(x => { return x.user_id === accountId }); // 登录人的协同人 stage.userIds = stage.status === status.uncheck // 当前流程下全部参与人id ? [stage.user_id, ...stage.userAssistIds] : [stage.user_id, ...stage.userAssistIds, ...stage.auditorIds, ...stage.auditAssistIds]; } async loadStageAuditViewData(stage) { const times = stage.status === auditConst.stage.status.checkNo ? stage.times - 1 : stage.times; if (!stage.user) stage.user = await this.ctx.service.projectAccount.getAccountInfoById(stage.user_id); stage.auditHistory = await this.ctx.service.stageAudit.getAuditorHistory(stage.id, times); // 获取审批流程中左边列表 if (stage.status === auditConst.stage.status.checkNo && stage.user_id !== this.ctx.session.sessionUser.accountId) { const auditors = await this.ctx.service.stageAudit.getAuditors(stage.id, times); // 全部参与的审批人 const auditorGroups = this.ctx.helper.groupAuditors(auditors); stage.auditors2 = this.ctx.helper.groupAuditorsUniq(auditorGroups); stage.auditors2.unshift([{ aid: stage.user.id, order: 0, times: stage.times - 1, audit_order: 0, audit_type: auditConst.auditType.key.common, name: stage.user.name, role: stage.user.role, company: stage.user.company }]); } else { stage.auditors2 = stage.userGroups; } if (stage.status === auditConst.stage.status.uncheck || stage.status === auditConst.stage.status.checkNo) { stage.auditorList = await this.ctx.service.stageAudit.getAuditors(stage.id, stage.times); } } async loadPreCheckedStage(stage) { if (stage.order > 1) { if (stage.status === auditConst.stage.status.checked) { stage.preCheckedStage = await this.getDataByCondition({ tid: stage.tid, order: stage.order - 1 }); } else { const preCheckedStages = await this.getAllDataByCondition({ where: { tid: stage.tid, status: auditConst.stage.status.checked }, orders: [['order', 'desc']], }); stage.preCheckedStage = preCheckedStages[0]; } stage.isCheckFirst = stage.order > 1 ? (stage.preCheckedStage ? stage.preCheckedStage.order === stage.order - 1 : false) : true; } else { stage.preCheckedStage = undefined; stage.isCheckFirst = true; } } async doCheckStage(stage, force = false) { const status = auditConst.stage.status; await this.loadStageUser(stage); await this.loadPreCheckedStage(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 stage.flowAuditorIds.indexOf(x.user_id) >= 0 && x.ass_user_id === accountId; }); stage.readOnly = stage.flowAuditorIds.indexOf(accountId) < 0 && !ass; stage.curTimes = stage.times; if (!stage.readOnly) { stage.assist = ass; stage.curOrder = stage.curAuditors[0].order; } else { stage.curOrder = stage.curAuditors[0].order - 1; } // 会签,会签人审批通过时,只读,但是curOrder需按原来的取值 if (!stage.readOnly) { stage.readOnly = !_.isEqual(stage.flowAuditorIds, stage.curAuditorIds); stage.canCheck = true; } } 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.userIds.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; } 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); } // 是否台账修订中 const lastRevise = await this.service.ledgerRevise.getLastestRevise(stage.tid); stage.revising = (lastRevise && lastRevise.status !== auditConst.revise.status.checked) || false; return stage; } async doCheckStageCanCancel(stage) { // 获取当前审批人的上一个审批人,判断是否是当前登录人,并赋予撤回功能,(当审批人存在有审批过时,上一人不允许再撤回) const status = auditConst.stage.status; const accountId = this.ctx.session.sessionUser.accountId; stage.cancancel = 0; if (stage.status !== status.checked && stage.status !== status.uncheck) { if (stage.status !== status.checkNo) { // 找出当前操作人上一个审批人,包括审批完成的和退回上一个审批人的,同时当前操作人为第一人时,就是则为原报 if (stage.flowAuditors.find(x => { return x.status !== auditConst.stage.status.checking}) && stage.flowAuditorIds.indexOf(accountId) < 0) return; // 当前流程存在审批人审批通过时,不可撤回 const flowAssists = stage.auditAssists.filter(x => { return stage.flowAuditorIds.indexOf(x.user_id) >= 0; }); if (flowAssists.find(x => { return x.confirm; })) return; //当前流程存在协审人确认时,不可撤回 if (stage.curAuditorIds.indexOf(accountId) < 0 && stage.flowAuditorIds.indexOf(accountId) >= 0) { stage.cancancel = 5; // 会签/协同 未全部审批通过时,审批人撤回审批通过 return; } const preAuditors = stage.curAuditors[0].order !== 1 ? stage.auditors.filter(x => { return x.order === stage.curAuditors[0].order - 1; }) : []; const preAuditorCheckAgain = preAuditors.find(pa => { return pa.status === status.checkAgain; }); const preAuditorCheckCancel = preAuditors.find(pa => { return pa.status === status.checkCancel; }); const preAuditorHasOld = preAuditors.find(pa => { return pa.is_old === 1; }); const preAuditorIds = (preAuditorCheckAgain ? [] : preAuditors.map(x => { return x.aid })); // 重审不可撤回 if ((this._.isEqual(stage.flowAuditorIds, preAuditorIds) && preAuditorCheckCancel) || preAuditorHasOld) { return; // 不可以多次撤回 } const preAuditChecked = preAuditors.find(pa => { return pa.status === status.checked && pa.aid === accountId; }); const preAuditCheckNoPre = preAuditors.find(pa => { return pa.status === status.checkNoPre && pa.aid === accountId; }); if (preAuditorIds.indexOf(accountId) >= 0) { if (preAuditChecked) { stage.cancancel = 2;// 审批人撤回审批通过 } else if (preAuditCheckNoPre) { stage.cancancel = 3;// 审批人撤回审批退回上一人 } stage.preAuditors = preAuditors; } else if (preAuditors.length === 0 && accountId === stage.user_id) { stage.cancancel = 1;// 原报撤回 } } else { const lastAuditors = await this.service.stageAudit.getAuditors(stage.id, stage.times - 1); const onAuditor = _.findLast(lastAuditors, { status: status.checkNo }); if (onAuditor.aid === accountId) { stage.cancancel = 4;// 审批人撤回退回原报 stage.preAuditors = lastAuditors.filter(x => { return x.order === onAuditor.order }); } } } } 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.stage.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 * @param includeUnCheck * @return {Promise<*>} */ async getFlowLatestStage(tenderId, includeUnCheck = false) { const stages = await this.getAllDataByCondition({ where: {tid: tenderId}, orders: [['order', 'desc']] }); const flowStages = []; for (const s of stages) { if (s.status !== auditConst.stage.status.checked) flowStages.push(s); } let stage; if (flowStages.length === 0) { stage = stages[0]; } else { const firstFlowStage = flowStages[flowStages.length - 1]; if (includeUnCheck) { stage = firstFlowStage; } else { stage = firstFlowStage.status === auditConst.stage.status.uncheck ? stages[flowStages.length] : firstFlowStage; } } return stage; } async getUnCompleteStages(tenderId) { return this.db.query(`SELECT * From ${this.tableName} WHERE tid = ? and status <> ?`, [tenderId, auditConst.stage.status.checked]); } /** * 获取 最新一期 审批完成的 期计量 * @param tenderId * @return {Promise<*>} */ async getLastestCompleteStage(tenderId) { this.initSqlBuilder(); this.sqlBuilder.setAndWhere('tid', { value: tenderId, operate: '=', }); this.sqlBuilder.setAndWhere('status', { value: auditConst.stage.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} */ 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); } async getListByArchives(tid, ids) { if (ids.length === 0) return []; const sql = 'SELECT c.* FROM ?? as c LEFT JOIN (SELECT sid, MAX(end_time) as end_time FROM ?? WHERE ' + 'tid = ? AND sid in (' + this.ctx.helper.getInArrStrSqlFilter(ids) + ') GROUP BY sid) as ca ON c.id = ca.sid WHERE' + ' c.tid = ? AND c.id in (' + this.ctx.helper.getInArrStrSqlFilter(ids) + ') AND c.status = ? ORDER BY c.order ASC'; const params = [this.tableName, this.ctx.service.stageAudit.tableName, tid, tid, auditConst.stage.status.checked]; const list = await this.db.query(sql, params); return list; } /** * 获取某一期信息(报表用) * @param stageId * @return {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, force = false) { // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算 if (stage.status !== auditConst.stage.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); } } } } async _checkStageValid(stage) { if (stage.status === auditConst.stage.status.uncheck && !this.ctx.tender.isTourist) { const assist = await this.ctx.service.auditAss.getAllDataByCondition({ where: { tid: stage.tid, user_id: stage.user_id } }); const assistId = assist.map(x => { return x.ass_user_id }); return stage.user_id === this.ctx.session.sessionUser.accountId || assistId.indexOf(this.ctx.session.sessionUser.accountId) >= 0; } else { return true; } } /** * 获取标段下的全部计量期,按倒序 * @param tenderId * @return {Promise} */ async getValidStages(tenderId, force = false) { let stages = await this.db.select(this.tableName, { where: { tid: tenderId }, orders: [['order', 'desc']], }); for (const s of stages) { s.tp_history = s.tp_history ? JSON.parse(s.tp_history) : []; s.valid = await this._checkStageValid(s); } if (stages.length !== 0 && !this.ctx.session.sessionUser.is_admin) { stages = stages.filter(x => { return x.valid; }); } // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算 if (stages.length === 0) return stages; for (const s of stages) { if (s.status !== auditConst.stage.status.checked) await this.checkStageGatherData(s, force); 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); 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 ? sf.tp : 0; } } return stages; } async getNextStages(tenderId, order) { const sql = 'SELECT * FROM ?? WHERE tid = ? AND `order` > ?'; return await this.db.query(sql, [this.tableName, tenderId, order]); } 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} */ async addStage(tender, date, period) { const stages = await this.getAllDataByCondition({ where: { tid: tender.id }, orders: [['order', 'DESC']], }); const preStage = stages[0]; const preCheckedStage = stages.find(x => { return x.status === auditConst.stage.status.checked; }); const order = stages.length + 1; const newStage = { sid: this.uuid.v4(), tid: tender.id, order, in_time: new Date(), s_time: date, period, times: 1, status: auditConst.stage.status.uncheck, user_id: tender.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; if (preCheckedStage) { newStage.pre_contract_tp = this.ctx.helper.sum([preCheckedStage.pre_contract_tp, preCheckedStage.contract_tp, preCheckedStage.contract_pc_tp]); newStage.pre_qc_tp = this.ctx.helper.sum([preCheckedStage.pre_qc_tp, preCheckedStage.qc_tp, preCheckedStage.qc_pc_tp]); newStage.pre_positive_qc_tp = this.ctx.helper.sum([preCheckedStage.pre_positive_qc_tp, preCheckedStage.positive_qc_tp, preCheckedStage.positive_qc_pc_tp]); newStage.pre_negative_qc_tp = this.ctx.helper.sum([preCheckedStage.pre_negative_qc_tp, preCheckedStage.negative_qc_tp, preCheckedStage.negative_qc_pc_tp]); newStage.pre_yf_tp = this.ctx.helper.add(preCheckedStage.pre_yf_tp, preCheckedStage.yf_tp); if (preCheckedStage.order === 1 || preCheckedStage.pre_sf_tp) { newStage.pre_sf_tp = this.ctx.helper.add(preCheckedStage.pre_sf_tp, preCheckedStage.sf_tp); } else { const sumTp = await this._getSumTp({tid: preCheckedStage.tid}, 'sf_tp'); newStage.pre_sf_tp = sumTp.sf_tp || 0; } } } else { const projFunRela = this.ctx.subProject.fun_rela; 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; newStage.preCheckedStage = preCheckedStage; } 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 '新增期合同支付数据失败'; } // 新增期其他台账数据 let pcTp = { contract_pc_tp: 0, qc_pc_tp: 0, pc_tp: 0, positive_qc_pc_tp: 0, negative_qc_pc_tp: 0 }; if (preCheckedStage) { const jgclResult = await this.ctx.service.stageJgcl.addInitialStageData(newStage, preCheckedStage, transaction); if (!jgclResult) throw '初始化甲供材料数据失败'; const yjclResult = await this.ctx.service.stageYjcl.addInitialStageData(newStage, preCheckedStage, transaction); if (!yjclResult) throw '初始化甲供材料数据失败'; const otherResult = await this.ctx.service.stageOther.addInitialStageData(newStage, preCheckedStage, transaction); if (!otherResult) throw '初始化其他台账数据失败'; const safeResult = await this.ctx.service.stageSafeProd.addInitialStageData(newStage, preCheckedStage, transaction); if (!safeResult) throw '初始化其他台账数据失败'; const tempResult = await this.ctx.service.stageTempLand.addInitialStageData(newStage, preCheckedStage, transaction); if (!tempResult) throw '初始化其他台账数据失败'; } if (preStage && preCheckedStage && preStage.order === preCheckedStage.order) { const priceCalc = new RevisePrice(this.ctx); pcTp = await priceCalc.newStagePriceChange(newStage, preStage, transaction); } if (order === 1 || (preStage && preCheckedStage && preStage.order === preCheckedStage.order)) { await this.ctx.service.tenderCache.updateStageCache4Add(transaction, newStage, pcTp); } // 新增期拷贝报表相关配置/签名角色 等 if (preStage) { const rptResult = await this.ctx.service.rptCustomDefine.addInitialStageData(newStage, preStage, transaction); await this.ctx.service.roleRptRel.addInitialStageData(tender.id, 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: tender.id, 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} */ 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} */ 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} */ 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 qdSum = await this.ctx.service.stageBills.getSumTotalPriceGcl(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 'bqqdwc': cb.value = this.ctx.helper.sum([qdSum.contract_tp, qdSum.qc_tp, pcSum.pc_tp]); break; case 'bqqdht': cb.value = qdSum.contract_tp; break; case 'bqqdbg': cb.value = qdSum.qc_tp; break; case 'ybbqwc': const sumGcl = await this.ctx.service.stageBills.getSumTotalPriceGcl(stage, '^[^0-9]*1[0-9]{2}(-|$)'); const sumPc = await this.ctx.service.stageBillsPc.getSumTotalPriceGcl(stage, '^[^0-9]*1[0-9]{2}(-|$)'); cb.value = this.ctx.helper.sum([sumGcl.contract_tp, sumGcl.qc_tp, sumPc.pc_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} */ async deleteStage(id) { const stageInfo = await this.getDataById(id); await this.loadPreCheckedStage(stageInfo); const transaction = await this.db.beginTransaction(); try { // 通知发送 - 第三方更新 // 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 }); if (stageInfo.isCheckFirst) await this.ctx.service.tenderCache.updateStageCache4Del(transaction, stageInfo); 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.stageYjcl.tableName, {sid: id}); 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} */ async getMaterialCalcBase(stage_list, tenderInfo) { const calcBase = JSON.parse(JSON.stringify(payConst.materialCalcBase)); 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 'yib': case 'erb': case 'sanb': case 'sib': case 'wub': case 'liub': case 'qib': case 'bab': case 'jiub': const sumGcl = await this.ctx.service.stageBills.getSumTotalPriceGclByMaterial(stage_list, cb.filter); const sumPc = await this.ctx.service.stageBillsPc.getSumTotalPriceGclByMaterial(stage_list, cb.filter); cb.value = this.ctx.helper.sum([sumGcl.contract_tp, sumGcl.qc_tp, sumPc.pc_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} */ 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); // todo 不确定是否使用,暂时注释,待测试验证 // 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, stage_tp) { const allStages = await this.db.select(this.tableName, { columns: ['id', 'user_id', 'times', 'status', 's_time', 'contract_tp', 'qc_tp', 'pc_tp', 'pre_contract_tp', 'pre_qc_tp', 'pre_yf_tp', 'yf_tp', 'pre_sf_tp', 'sf_tp', 'tp_history'], where: { tid: tenderId }, orders: [['order', 'desc']], }); const stages = this._.filter(allStages, function(s) { return s.status !== auditConst.stage.status.uncheck; }); // if (stages.length > 0 && stages[0].status === auditConst.stage.status.uncheck) { // stages.splice(0, 1); // } // 最新一期计量(未审批完成),取上一个人的期详细数据,应实时计算 const stage = stages[0]; if (stages.length === 0) return stages; // await this.checkStageGatherDataByDataCollect(stage); if (stage.status !== auditConst.stage.status.checked) { // 批量把stage_tp的值赋值给stage _.forEach(stage_tp, function(value, key) { stage[key] = stage_tp[key] ? stage_tp[key] : null; }); } 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.yf_tp = this.ctx.helper.add(s.pre_yf_tp, s.yf_tp); // s.sf_tp = this.ctx.helper.add(s.pre_sf_tp, s.sf_tp); } return stages; } async doCheckStageByDataCollect(stage) { const status = auditConst.stage.status; await this.loadStageUser(stage); if (stage.status === status.checkNo) { stage.readOnly = false; const checkNoAudit = await this.service.stageAudit.getDataByCondition({ sid: stage.id, times: stage.times - 1, status: status.checkNo, }); 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 { stage.readOnly = false; stage.curTimes = stage.times; stage.curOrder = stage.curAuditors[0].order - 1; } return stage; } async checkStageGatherDataByDataCollect(stage) { // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算 if (stage.status !== auditConst.stage.status.checked) { await this.doCheckStageByDataCollect(stage); 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); } 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); } } } } async isLastStage(tid, sid) { const lastStage = await this.ctx.service.stage.getLastestStage(tid, true); return lastStage ? lastStage.id === sid : false; } } return Stage; };