123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473 |
- '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<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
- * @returns {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 && 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<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);
- }
- 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<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: 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<void>}
- */
- 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<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: order } });
- // to do 生成中间计量数据
- await conn.commit();
- } catch (err) {
- await conn.rollback();
- throw err;
- }
- }
- /**
- * 获取 当期的 计算基数
- * @returns {Promise<any>}
- */
- 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<void>}
- */
- 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<any>}
- */
- 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<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;
- };
|