'use strict'; /** * * * @author Mai * @date * @version */ const measureType = require('../const/tender').measureType; const timesLen = require('../const/audit').stage.timesLen; module.exports = app => { class StagePos extends app.BaseService { /** * 构造函数 * * @param {Object} ctx - egg全局变量 * @return {void} */ constructor(ctx) { super(ctx); this.tableName = 'stage_pos'; this.qtyFields = ['contract_qty', 'qc_qty'] } _getPosFilterSql(where, asTable = '') { let whereSql = ''; if (!where) return whereSql; if (where.pid) { if (where.pid instanceof Array) { whereSql += ' And ' + asTable + 'pid in (' + this.ctx.helper.getInArrStrSqlFilter(where.pid) + ')'; } else if (typeof where.pid === "string") { whereSql += ' And ' + asTable + 'pid = ' + this.db.escape(where.pid); } } if (where.lid) { if (where.lid instanceof Array) { whereSql += ' And ' + asTable + 'lid in (' + this.ctx.helper.getInArrStrSqlFilter(where.lid) + ')'; } else if (typeof where.pid === "string") { whereSql += ' And ' + asTable + 'lid = ' + this.db.escape(where.lid); } } return whereSql; } /** * 查询期计量最后审核人数据 * @param {Number} tid - 标段id * @param {Number} sid - 期id * @param {Number|Array} pid - 部位明细id(可以为空) * @returns {Promise<*>} */ async getLastestStageData(tid, sid, where) { const filterSql = this._getPosFilterSql(where); const sql = 'SELECT Pos.id, Pos.tid, Pos.sid, Pos.lid, Pos.pid, Pos.contract_qty, Pos.qc_qty, Pos.postil, Pos.times, Pos.order FROM ' + ' (SELECT * FROM ' + this.tableName + ' WHERE tid = ? And sid = ?) As Pos ' + ' INNER JOIN ( ' + ' SELECT MAX(`times` * ' + timesLen + ' + `order`) As `flow`, `tid`, `sid`, `pid` From ' + this.tableName + ' WHERE `tid` = ? And sid = ?' + filterSql + ' GROUP BY `pid`' + ' ) As MaxFilter ' + ' ON (Pos.times * ' + timesLen + ' + Pos.order) = MaxFilter.flow And Pos.pid = MaxFilter.pid And Pos.sid = MaxFilter.sid'; const sqlParam = [tid, sid, tid, sid]; return await this.db.query(sql, sqlParam); } /** * 查询 某期 某轮审批 某审核人数据 * @param {Number} tid - 标段id * @param {Number} sid - 期id * @param {Number} times - 期第几轮审批 * @param {Number} order - 审核人顺序 * @param {Number|Array|Null} pid - 部位明细id - 为空则查询全部 * @returns {Promise<*>} */ async getAuditorStageData(tid, sid, times, order, where) { const filterSql = this._getPosFilterSql(where); const sql = 'SELECT Pos.id, Pos.tid, Pos.sid, Pos.pid, Pos.lid, Pos.contract_qty, Pos.qc_qty, Pos.postil, Pos.times, Pos.order FROM ' + ' (SELECT * FROM '+ this.tableName + ' WHERE tid = ? And sid = ?) As Pos ' + ' INNER JOIN ( ' + ' SELECT MAX(`times` * ' + timesLen + ' + `order`) As `flow`, `pid`, `sid` From ' + this.tableName + ' WHERE (`times` < ? OR (`times` = ? AND `order` <= ?)) And tid = ? And sid = ?' + filterSql + ' GROUP BY `pid`' + ' ) As MaxFilter ' + ' ON (Pos.times * ' + timesLen + ' + Pos.order) = MaxFilter.flow And Pos.pid = MaxFilter.pid And Pos.sid = MaxFilter.sid'; const sqlParam = [tid, sid, times, times, order, tid, sid]; return await this.db.query(sql, sqlParam); } async _filterLastestData(stagePos) { const stagePosIndex = {}; for (const sp of stagePos) { const key = 'sp-' + sp.pid; const spi = stagePosIndex[key]; if (spi) { if ((spi.times * timesLen + spi.order) < (sp.times * timesLen + sp.order)) stagePosIndex[key] = sp; } else { stagePosIndex[key] = sp; } } const result = []; for (const prop in stagePosIndex) { result.push(stagePosIndex[prop]); } return result; } async getLastestStageData2(tid, sid, where) { const filterSql = this._getPosFilterSql(where); const sql = 'SELECT id, tid, sid, pid, lid, contract_qty, qc_qty, postil, `times`, `order`' + ' FROM ' + this.tableName + ' WHERE tid = ? And sid = ? ' + filterSql; const sqlParam = [tid, sid]; const stagePos = await this.db.query(sql, sqlParam); return this._filterLastestData(stagePos); } async getAuditorStageData2(tid, sid, times, order, where) { const filterSql = this._getPosFilterSql(where); const sql = 'SELECT id, tid, sid, pid, lid, contract_qty, qc_qty, postil, `times`, `order`' + ' FROM ' + this.tableName + ' WHERE tid = ? And sid = ? And (`times` < ? OR (`times` = ? AND `order` <= ?)) ' + filterSql; const sqlParam = [tid, sid, times, times, order]; const stagePos = await this.db.query(sql, sqlParam); return this._filterLastestData(stagePos); } async getStageUsedPos(tid, sid, where) { const self = this; const stagePos = await this.getLastestStageData2(tid, sid, where); const pids = this._.map(stagePos, function (sp) { if (self.ctx.helper.checkZero(sp.contract_qty) || self.ctx.helper.checkZero(sp.qc_qty)) { return sp.pid; } else { return -1; } }); return this._.pull(pids, -1); } /** * 新增部位明细数据(仅供updateStageData调用) * * @param transaction - 事务 * @param data - 新增数据 * @returns {Promise<{}>} * @private */ async _addStagePosData(data) { let bills , precision; const result = {pos: [], ledger: []}; const datas = data instanceof Array ? data : [data], calcBills = [], calcStageBills = []; const transaction = await this.db.beginTransaction(); try { for (const d of datas) { if (d.sgfh_qty !== undefined || d.sjcl_qty !== undefined || d.qtcl_qty !== undefined) { if (!bills || bills.id !== data.lid) { bills = await this.ctx.service.ledger.getDataById(d.lid); precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, bills.unit); } } // 在主表pos中新增数据 const p = { id: this.uuid.v4(), tid: this.ctx.tender.id, lid: d.lid, name: d.name, porder: d.porder, add_stage: this.ctx.stage.id, add_times: this.ctx.stage.curTimes, add_user: this.ctx.session.sessionUser.accountId, }; if (d.sgfh_qty) p.sgfh_qty = this.round(d.sgfh_qty, precision.value); if (d.sjcl_qty) p.sjcl_qty = this.round(d.sjcl_qty, precision.value); if (d.qtcl_qty) p.qtcl_qty = this.round(d.qtcl_qty, precision.value); p.quantity = this.ctx.helper.sum([p.sgfh_qty, p.sjcl_qty, p.qtcl_qty]); const addRst = await transaction.insert(this.ctx.service.pos.tableName, p); result.pos.push(p.id); // 如果存在复核数据,更新计算主表清单 if (p.sgfh_qty || p.sjcl_qty || p.qtcl_qty) { calcBills.push(p.lid); result.ledger.push(p.lid); } // 如果存在本期计算数据,更新计算清单本期计量数据 if (d.contract_qty || d.qc_qty || d.postil) { const ps = { pid: p.id, lid: d.lid, tid: this.ctx.tender.id, sid: this.ctx.stage.id, said: this.ctx.session.sessionUser.accountId, times: this.ctx.stage.curTimes, order: this.ctx.stage.curOrder, }; if (d.contract_qty) ps.contract_qty = this.round(d.contract_qty, precision.value); if (d.qc_qty) ps.qc_qty = this.round(d.qc_qty, precision.value); if (d.postil) ps.postil = d.postil; await transaction.insert(this.tableName, ps); if ((d.contract_qty || d.qc_qty) && calcStageBills.indexOf(ps.lid) === -1) { calcStageBills.push(ps.lid); } result.stageUpdate = true; } } for (const lid of calcBills) { await this.ctx.service.ledger.calc(this.ctx.tender.id, lid, transaction); } for (const lid of calcStageBills) { await this.ctx.service.stageBills.calc(this.ctx.tender.id, this.ctx.stage.id, lid, transaction); } await transaction.commit(); return result; } catch(err) { await transaction.rollback(); throw err; } } /** * 更新部位明细数据(仅供updateStageData调用) * * @param transaction - 事务 * @param data - 更新数据(允许一次性提交多条) * @returns {Promise<{ledger: Array, pos: Array}>} * @private */ async _updateStagePosData(data) { let bills, precision; const result = {ledger: [], pos: [], stageUpdate: true}, ledgerCalc = []; const datas = data instanceof Array ? data : [data]; const orgPos = await this.ctx.service.pos.getPosDataByIds(this._.map(datas, 'pid')); const orgStagePos = await this.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, {pid: this._.map(datas, 'pid')}); const transaction = await this.db.beginTransaction(); try { for (const d of datas) { if (d.sgfh_qty !== undefined || d.qtcl_qty !== undefined || d.sjcl_qty !== undefined || d.contract_qty !== undefined || d.qc_qty !== undefined) { if (!bills || bills.id !== data.lid) { bills = await this.ctx.service.ledger.getDataById(d.lid); precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, bills.unit); } } if (d.name !== undefined || d.sgfh_qty !== undefined || d.qtcl_qty !== undefined || d.sjcl_qty !== undefined || d.drawing_code !== undefined) { const op = this._.find(orgPos, {id: d.pid}); if (op.add_stage !== this.ctx.stage.id) throw '不可修改数据'; const p = {id: d.pid}; if (d.name !== undefined) p.name = d.name; if (d.sgfh_qty !== undefined || d.qtcl_qty !== undefined || d.sjcl_qty !== undefined) { p.sgfh_qty = d.sgfh_qty !== undefined ? d.sgfh_qty : op.sgfh_qty; p.sjcl_qty = d.sjcl_qty !== undefined ? d.sjcl_qty : op.sjcl_qty; p.qtcl_qty = d.qtcl_qty !== undefined ? d.qtcl_qty : op.qtcl_qty; p.quantity = this.ctx.helper.sum([p.sgfh_qty, p.sjcl_qty, p.qtcl_qty]); if (ledgerCalc.indexOf(op.lid) === -1) { ledgerCalc.push(op.lid); } } if (d.drawing_code !== undefined) p.drawing_code = d.drawing_code; await transaction.update(this.ctx.service.pos.tableName, p); } if (d.contract_qty !== undefined || d.qc_qty !== undefined || d.postil !== undefined) { const osp = this._.find(orgStagePos, function (p) { return p.pid === d.pid; }); if (osp && osp.times === this.ctx.stage.curTimes && osp.order === this.ctx.stage.curOrder) { const sp = {}; if (d.contract_qty !== undefined) { sp.contract_qty = this.ctx.helper.round(d.contract_qty, precision.value); } if (d.qc_qty !== undefined) { sp.qc_qty = this.ctx.helper.round(d.qc_qty, precision.value); } if (d.postil !== undefined) { sp.postil = d.postil; } await transaction.update(this.tableName, sp, {where: {id: osp.id}}); } else { const sp = { pid: d.pid, lid: d.lid, tid: this.ctx.tender.id, sid: this.ctx.stage.id, said: this.ctx.session.sessionUser.accountId, times: this.ctx.stage.curTimes, order: this.ctx.stage.curOrder }; if (d.contract_qty !== undefined || osp) { sp.contract_qty = d.contract_qty === undefined && osp ? osp.contract_qty : this.ctx.helper.round(d.contract_qty, precision.value); } if (d.qc_qty || osp) { sp.qc_qty = d.qc_qty === undefined && osp ? osp.qc_qty : this.ctx.helper.round(d.qc_qty, precision.value); } if (d.postil || osp) { sp.postil = d.postil === undefined && osp ? osp.postil : d.postil; } await transaction.insert(this.tableName, sp); } } result.pos.push(d.pid); if ((d.sgfh_qty !== undefined || d.qtcl_qty !== undefined || d.sjcl_qty !== undefined || d.contract_qty === undefined || d.qc_qty === undefined) && (result.ledger.indexOf(d.lid) === -1)) { result.ledger.push(d.lid); } } for (const lid of ledgerCalc) { await this.ctx.service.ledger.calc(this.ctx.tender.id, lid, transaction); } for (const lid of result.ledger) { await this.ctx.service.stageBills.calc(this.ctx.tender.id, this.ctx.stage.id, lid, transaction); } await transaction.commit(); return result; } catch (err) { await transaction.rollback(); throw err; } } /** * 删除部位明细数据(仅供updateStageData调用) * * @param transaction - 事务 * @param data - 删除的部位明细(允许一次提醒多条,也允许跨清单(但前端操作不允许)) * @returns {Promise<{}>} * @private */ async _deleteStagePosData(data) { const pos = await this.ctx.service.pos.getPosData({tid: this.ctx.tender.id, id: data}); const result = { pos: data, isDeletePos: true}; if (pos instanceof Array) { for (const p of pos) { if (p.add_stage !== this.ctx.stage.id /*|| p.add_times !== this.ctx.stage.curTimes || p.add_user !== this.ctx.session.sessionUser.accountId*/) { throw '不可删除该数据'; } } } else if (pos.add_stage !== this.ctx.stage.id /*|| pos.add_times !== this.ctx.stage.curTimes || pos.add_user !== this.ctx.session.sessionUser.accountId*/) { throw '不可删除该数据'; } const ledgerIds = this._.map(pos, 'lid'); const transaction = await this.db.beginTransaction(); try { // 删除部位明细 await transaction.delete(this.ctx.service.pos.tableName, {tid: this.ctx.tender.id, id: data}); for (const lid of ledgerIds) { await this.ctx.service.ledger.calc(this.ctx.tender.id, lid, transaction); } // 删除部位明细计量数据 await transaction.delete(this.tableName, {tid: this.ctx.tender.id, lid: data}); for (const lid of ledgerIds) { await this.ctx.service.stageBills.calc(this.ctx.tender.id, this.ctx.stage.id, lid, transaction); } await transaction.commit(); // 获取需要更新的数据 result.ledger = ledgerIds; result.stageUpdate = true; return result; } catch (err) { await transaction.rollback(); throw err; } } /** * 根据前端提交数据,更新并计算 * * @param data * @returns {Promise<{ledger: {}, pos: {}}>} */ async updateStageData(data) { if ((data.updateType === 'add' || data.upateType === 'delete') && this.ctx.tender.measure_type === measureType.tz) { throw '台账模式下,不可在计量中新增或删除部位明细,如需操作,请进行台账修订'; } let refreshData; if (data.updateType === 'add') { refreshData = await this._addStagePosData(data.updateData); } else if (data.updateType === 'update') { refreshData = await this._updateStagePosData(data.updateData); } else if (data.updateType === 'delete') { if (!data.updateData || data.updateData.length === 0) { throw '提交数据错误'; } refreshData = await this._deleteStagePosData(data.updateData); } else { throw '提交数据错误'; } try { const result = {ledger: {}, pos: {}}; if (refreshData.ledger && refreshData.ledger.length > 0) { result.ledger.bills = await this.ctx.service.ledger.getDataByIds(refreshData.ledger); if (refreshData.stageUpdate) { result.ledger.curStageData = await this.ctx.service.stageBills.getLastestStageData(this.ctx.tender.id, this.ctx.stage.id, refreshData.ledger); } } if (refreshData.pos) { if (refreshData.isDeletePos) { result.pos.pos = refreshData.pos; } else if (refreshData.pos.length > 0) { result.pos.pos = await this.ctx.service.pos.getPosDataWithAddStageOrder({id: refreshData.pos}); if (refreshData.stageUpdate) { result.pos.curStageData = await this.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, {pid: refreshData.pos}); } } } return result; } catch(err) { throw '获取数据异常,请刷新页面。'; } } async updateChangeQuantity(transaction, pos, qty) { let orgPos = await this.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, {pid: pos.id}); if (orgPos.length > 1) { throw '数据错误'; } else { orgPos = orgPos[0]; } if (orgPos && orgPos.times === this.ctx.stage.curTimes && orgPos.order === this.ctx.stage.curOrder) { await transaction.update(this.tableName, {id: orgPos.id, qc_qty: qty}); } else { await transaction.insert(this.tableName, { tid: this.ctx.tender.id, sid: this.ctx.stage.id, lid: pos.lid, pid: pos.id, said: this.ctx.session.sessionUser.accountId, times: this.ctx.stage.curTimes, order: this.ctx.stage.curOrder, contract_qty: orgPos ? orgPos.contract_qty : 0, qc_qty: qty, }); } await this.ctx.service.stageBills.calc(this.ctx.tender.id, this.ctx.stage.id, pos.lid, transaction); } /** * 统计清单下部位明细合计 * @param {Number} tid - 标段id * @param {Number} sid - 期id * @param {Number} lid - 清单节点id * @param transaction - 事务(不为空则在事务中查询,反之在数据库中查询) * @returns {Promise<*>} */ async getPosGather(tid, sid, lid, transaction) { const calcQtySql = 'SELECT SUM(`contract_qty`) As `contract_qty`, SUM(`qc_qty`) As `qc_qty` FROM (' + ' SELECT `contract_qty`, `qc_qty` FROM ' + this.ctx.service.stagePos.tableName + ' As Pos ' + ' INNER JOIN (' + ' SELECT MAX(`times` * ' + timesLen + ' + `order`) As `flow`, `pid` ' + ' FROM ' + this.ctx.service.stagePos.tableName + ' WHERE `tid` = ? And sid = ? And `lid` = ? ' + ' GROUP BY `pid`' + ' ) As MaxFilter ' + ' ON (Pos.times * ' + timesLen + ' + Pos.order) = MaxFilter.flow And Pos.pid = MaxFilter.pid ' + ' WHERE Pos.tid = ? And Pos.sid = ? And Pos.lid = ?' + ' ) As Gather'; const param = [tid, sid, lid]; const sqlParam = param.concat(param); if (transaction) { return await transaction.queryOne(calcQtySql, sqlParam); } else { return await this.db.queryOne(calcQtySql, sqlParam); } } /** * 多期清单数据整合 (材料调差调用) * @param {Number} tid - 标段id * @param {String} stage_id_list - 期id列表 * @returns {Promise} */ async getStagesData(tid, stage_id_list) { let stage_id_listSql = ''; stage_id_list = stage_id_list.indexOf(',') !== -1 ? stage_id_list.split(',') : stage_id_list; if (stage_id_list) { if (stage_id_list instanceof Array) { stage_id_listSql = stage_id_list.length > 0 ? ' And sid in (' + this.ctx.helper.getInArrStrSqlFilter(stage_id_list) + ')' : ''; } else { stage_id_listSql = ' And sid in (' + this.db.escape(stage_id_list) + ')'; } } const sql = 'SELECT `id`, `tid`, `sid`, `pid`, `lid`, SUM(`contract_qty`) as `contract_qty`, SUM(`qc_qty`) as `qc_qty`' + ' FROM ' + this.tableName + ' WHERE `tid` = ? ' + stage_id_listSql + 'GROUP BY `pid`'; const sqlParam = [tid]; const result = await this.db.query(sql, sqlParam); return result; } /** * 获取多期(合同和数量变更相加)计量-小计(材料调差调用) * @param {Number} tid - 标段id * @param {String} stage_id_list - 期id列表 * @param {String} lid - 台账id * @param {String} pid - 部位id * @returns {Promise} */ async getGatherQtyByMaterial(tid, stage_id_list, lid, pid) { stage_id_list = stage_id_list !== null ? stage_id_list.split(',') : []; let gather_qty = 0; for (const sid of stage_id_list) { const sql = 'SELECT Pos.contract_qty, Pos.qc_qty FROM ' + ' (SELECT * FROM ' + this.tableName + ' WHERE tid = ? AND sid = ?) As Pos ' + ' INNER JOIN ( ' + ' SELECT MAX(`times` * ' + timesLen + ' + `order`) As `flow`, `tid`, `sid`, `pid` From ' + this.tableName + ' WHERE `tid` = ? AND sid = ?' + ' GROUP BY `pid`' + ' ) As MaxFilter ' + ' ON (Pos.times * ' + timesLen + ' + Pos.order) = MaxFilter.flow And Pos.pid = MaxFilter.pid And Pos.sid = MaxFilter.sid' + ' WHERE Pos.lid = ? AND Pos.pid = ?'; const sqlParam = [tid, sid, tid, sid, lid, pid]; const result = await this.db.queryOne(sql, sqlParam); if (result) { gather_qty = this.ctx.helper.add(gather_qty, this.ctx.helper.add(result.contract_qty, result.qc_qty)); } } return gather_qty !== 0 ? gather_qty : null; } } return StagePos; };