123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910 |
- 'use strict';
- /**
- * 期 - 变更数据
- *
- * @author Mai
- * @date
- * @version
- */
- const defaultPid = -1; // 非pid
- const audit = require('../const/audit');
- const timesLen = audit.stage.timesLen;
- const changeConst = require('../const/change');
- class autoUseChange {
- constructor(helper, info, settleStatus) {
- this.helper = helper;
- this.precision = info.precision;
- this.decimal = info.decimal;
- this.settleStatus = settleStatus;
- this.insertBills = [];
- this.insertPos = [];
- this.updateBills = [];
- this.updatePos = [];
- this.insertChange = [];
- this.updateChange = [];
- this.changeBills = {};
- this.changePos = {};
- this.changeDetail = [];
- }
- init(source) {
- this.default = source.default;
- const LedgerModel = require('../lib/ledger');
- this.ledgerTree = new LedgerModel.billsTree(this.ctx, {
- id: 'ledger_id', pid: 'ledger_pid', order: 'order', level: 'level', rootId: -1, calcFields: [],
- });
- this.pos = new LedgerModel.pos({ id: 'id', ledgerId: 'lid' });
- this.ledgerTree.loadDatas(source.ledgerData);
- this.pos.loadDatas(source.posData);
- this.stageBills = source.stageBills;
- this.stagePos = source.stagePos;
- this.stageChange = source.stageChange || [];
- }
- findBillsPos(changeBills){
- if (changeBills.gcl_id) {
- const node = this.ledgerTree.datas.find(x => {return x.id === changeBills.gcl_id});
- if (node.settle_status === this.settleStatus.finish) return null;
- const posData = this.pos.getLedgerPos(node.id) || [];
- const changePos = posData.find(x => { return x.name === changeBills.bwmx; });
- if (changePos && changePos.settle_status) return null;
- let defaultPos;
- if (posData.length > 0) {
- defaultPos = posData.length > 0 ? posData.find(x => { return !x.settle_status}) : null;
- if (!defaultPos) return null;
- } else {
- defaultPos = { id: '-1' };
- }
- return { bills: node, lid: node.id, pid: changePos ? changePos.id : defaultPos.id };
- } else {
- const cb = {
- b_code: changeBills.code || '',
- name: changeBills.name || '',
- unit: changeBills.unit || '',
- unit_price: changeBills.unit_price || 0,
- is_tp: false,
- };
- for (const node of this.ledgerTree.nodes) {
- if (node.children && node.children.length > 0) continue;
- if (node.settle_status === this.settleStatus.finish) return null;
- const b = {
- b_code: node.b_code || '',
- name: node.name || '',
- unit: node.unit || '',
- unit_price: node.unit_price || 0,
- is_tp: !!node.is_tp,
- };
- if (this.helper._.isMatch(cb, b)) {
- const posData = this.pos.getLedgerPos(node.id) || [];
- let defaultPos;
- if (posData.length > 0) {
- defaultPos = posData.length > 0 ? posData.find(x => { return !x.settle_status}) : null;
- if (!defaultPos) return null;
- } else {
- defaultPos = { id: '-1' };
- }
- return { bills: node, lid: node.id, pid: defaultPos.id };
- }
- }
- return null;
- }
- }
- _calculateQty(detail, minus, bills) {
- if (bills.is_valuation) {
- detail.qty = this.helper.add(detail.qty, bills.valid_qty);
- if (minus) {
- detail.negative_qc_qty = this.helper.add(detail.negative_qc_qty, bills.valid_qty);
- } else {
- detail.positive_qc_qty = this.helper.add(detail.positive_qc_qty, bills.valid_qty);
- }
- } else {
- detail.qc_minus_qty = this.helper.add(detail.qc_minus_qty, bills.valid_qty);
- }
- }
- _calculateUsedQty(detail, bills) {
- if (!bills.no_value) {
- detail.qty = this.helper.add(detail.qty, bills.qty);
- if (detail.minus) {
- detail.negative_qc_qty = this.helper.add(detail.negative_qc_qty, bills.qty);
- } else {
- detail.positive_qc_qty = this.helper.add(detail.positive_qc_qty, bills.qty);
- }
- } else {
- detail.qc_minus_qty = this.helper.add(detail.qc_minus_qty, bills.qty);
- }
- }
- useBills(bills) {
- if (bills.billsPos) bills.billsPos.bills = this.ledgerTree.datas.find(x => {return x.id === bills.billsPos.lid; });
- const billsPos = bills.billsPos || this.findBillsPos(bills);
- if (!billsPos) return;
- if (!this.minusNoValue && !bills.is_valuation) return;
- const bamount = parseFloat(bills.samount);
- const minus = bamount < 0;
- this.changeDetail.push({
- tid: this.default.tid, sid: this.default.sid,
- lid: billsPos.lid, pid: billsPos.pid + '', cid: bills.cid, cbid: bills.id,
- qty: bills.valid_qty, stimes: 1, sorder: 0, unit_price: bills.unit_price, minus, no_value: !bills.is_valuation,
- });
- if (billsPos.pid !== '-1') {
- let cp = this.changePos[billsPos.pid];
- if (!cp) {
- cp = { lid: billsPos.lid, pid: billsPos.pid, qty: 0, negative_qc_qty: 0, positive_qc_qty: 0, qc_minus_qty: 0, bills: billsPos.bills };
- this.changePos[billsPos.pid] = cp;
- }
- this._calculateQty(cp, minus, bills);
- } else {
- let cb = this.changeBills[billsPos.lid];
- if (!cb) {
- cb = { lid: billsPos.lid, qty: 0, bills: billsPos.bills };
- this.changeBills[billsPos.lid] = cb;
- }
- this._calculateQty(cb, minus, bills);
- }
- }
- calculateAll() {
- for (const cd of this.changeDetail) {
- const sci = this.stageChange.findIndex(x => {
- return x.lid === cd.lid && x.pid === cd.pid && x.cbid === cd.cbid;
- });
- const sc = this.stageChange[sci];
- if (sc) {
- this.updateChange.push({ id: sc.id, qty: cd.qty });
- this.stageChange.splice(sci, 1);
- } else {
- this.insertChange.push(cd);
- }
- }
- for (const sc of this.stageChange) {
- const cp = this.changePos[sc.pid];
- if (cp) this._calculateUsedQty(cp, sc);
- }
- for (const pid in this.changePos) {
- const cp = this.changePos[pid];
- if (!cp) continue;
- const precision = this.helper.findPrecision(this.precision, cp.bills.unit);
- const qc_qty = this.helper.round(cp.qty, precision.value);
- const positive_qc_qty = this.helper.round(cp.positive_qc_qty || 0, precision.value);
- const negative_qc_qty = this.helper.round(cp.negative_qc_qty || 0, precision.value);
- const qc_minus_qty = this.helper.round(cp.qc_minus_qty || 0, precision.value);
- const sp = this.stagePos.find(x => {return x.pid === pid});
- if (sp) {
- this.updatePos.push({ id: sp.id, qc_qty, positive_qc_qty, negative_qc_qty, qc_minus_qty });
- } else {
- this.insertPos.push({
- tid: this.default.tid, sid: this.default.sid, said: this.default.said,
- lid: cp.lid, pid, qc_qty, positive_qc_qty, negative_qc_qty, qc_minus_qty, times: 1, order: 0
- });
- }
- const cb = this.changeBills[cp.lid];
- if (!cb) {
- this.changeBills[cp.lid] = { lid: cp.lid, qty: qc_qty, positive_qc_qty, negative_qc_qty, qc_minus_qty, bills: cp.bills };
- } else {
- cb.qty = this.helper.add(cb.qty, qc_qty);
- cb.positive_qc_qty = this.helper.add(cb.positive_qc_qty, positive_qc_qty);
- cb.negative_qc_qty = this.helper.add(cb.negative_qc_qty, negative_qc_qty);
- cb.qc_minus_qty = this.helper.add(cb.qc_minus_qty, qc_minus_qty);
- }
- }
- for (const sc of this.stageChange) {
- const cp = this.changePos[sc.pid];
- if (cp) continue;
- const cb = this.changeBills[sc.lid];
- if (cb) this._calculateUsedQty(cb, sc);
- }
- for (const lid in this.changeBills) {
- const cb = this.changeBills[lid];
- if (!cb) continue;
- const precision = this.helper.findPrecision(this.precision, cb.bills.unit);
- const qc_qty = this.helper.round(cb.qty, precision.value);
- const qc_tp = this.helper.mul(cb.qty, cb.bills.unit_price, this.decimal.tp);
- const positive_qc_qty = this.helper.round(cb.positive_qc_qty || 0, precision.value);
- const positive_qc_tp = this.helper.mul(positive_qc_qty, cb.bills.unit_price, this.decimal.tp);
- const negative_qc_qty = this.helper.round(cb.negative_qc_qty || 0, precision.value);
- const negative_qc_tp = this.helper.mul(negative_qc_qty, cb.bills.unit_price, this.decimal.tp);
- const qc_minus_qty = this.helper.round(cb.qc_minus_qty || 0, precision.value);
- const sb = this.stageBills.find(x => {return x.lid === lid});
- if (sb) {
- this.updateBills.push({ id: sb.id, qc_qty, qc_tp, positive_qc_qty, positive_qc_tp, negative_qc_qty, negative_qc_tp, qc_minus_qty });
- } else {
- this.insertBills.push({
- tid: this.default.tid, sid: this.default.sid, said: this.default.said,
- lid, qc_qty, qc_tp, positive_qc_qty, positive_qc_tp, negative_qc_qty, negative_qc_tp, qc_minus_qty, times: 1, order: 0
- });
- }
- }
- }
- use(source, validChangeBills, minusNoValue) {
- this.init(source);
- this.minusNoValue = minusNoValue;
- for (const bills of validChangeBills) {
- this.useBills(bills);
- }
- this.calculateAll();
- }
- }
- module.exports = app => {
- class StageChange extends app.BaseService {
- /**
- * 构造函数
- *
- * @param {Object} ctx - egg全局变量
- * @return {void}
- */
- constructor(ctx) {
- super(ctx);
- this.tableName = 'stage_change';
- }
- /**
- * 查询 调用的变更令 最新数据
- * @param {Number} tid - 标段id
- * @param {Number} sid - 期id
- * @param {Number} lid - 台账节点id
- * @param {Number} pid - 部位明细id
- * @return {Promise<*>}
- */
- async getLastestStageData(tid, sid, lid, pid, noValue) {
- const filter = noValue !== undefined ? ' And no_value = ?' : '';
- const sql = 'SELECT c.*,' +
- ' oc.p_code As c_code, oc.new_code As c_new_code' +
- ' FROM ' + this.tableName + ' As c ' +
- ' INNER JOIN ( ' +
- ' SELECT MAX(`stimes` * ' + timesLen + ' + `sorder`) As `progress`, `lid`, `pid`, `sid`, `cid`, `cbid`, `no_value` From ' + this.tableName +
- ' WHERE tid = ? And sid = ? And lid = ? And pid = ?' + filter +
- ' GROUP By `lid`, `pid`, `cbid`, `no_value`' +
- ' ) As m ' +
- ' ON (c.stimes * ' + timesLen + ' + c.sorder) = m.progress And c.lid = m.lid And c.pid = m.pid And c.`sid` = m.`sid` And c.`cbid` = m.`cbid` And c.`no_value` = m.`no_value`' +
- ' LEFT JOIN ' + this.ctx.service.change.tableName + ' As oc' +
- ' ON c.cid = oc.cid' +
- ' LEFT JOIN ' + this.ctx.service.changeAuditList.tableName + ' As ocb' +
- ' ON c.cbid = ocb.id' +
- ' WHERE not ISNULL(ocb.id)';
- const sqlParam = [tid, sid, lid, pid ? pid : -1];
- if (noValue !== undefined) sqlParam.push(noValue);
- return await this.db.query(sql, sqlParam);
- }
- /**
- * 查询 调用的变更令 某轮 某人的数据
- * @param {Number} tid - 标段id
- * @param {Number} sid - 期id
- * @param {Number} times - 第几轮
- * @param {Number} order - 第几人
- * @param {Number} lid - 台账节点id
- * @param {Number} pid - 部位明细id
- * @return {Promise<*>}
- */
- async getAuditorStageData(tid, sid, times, order, lid, pid, noValue) {
- const filter = noValue !== undefined ? ' And no_value = ?' : '';
- const sql = 'SELECT c.*,' +
- ' oc.p_code As c_code, oc.new_code As c_new_code, oc.quality, ocb.code as b_code, ocb.name, ocb.unit' +
- ' FROM ' + this.tableName + ' As c ' +
- ' INNER JOIN ( ' +
- ' SELECT MAX(`stimes` * ' + timesLen + ' + `sorder`) As `progress`, `lid`, `pid`, `sid`, `cid`, `cbid`, `no_value` From ' + this.tableName +
- ' WHERE tid = ? And sid = ? And (`stimes` < ? OR (`stimes` = ? AND `sorder` <= ?)) And lid = ? And pid = ?' + filter +
- ' GROUP By `lid`, `pid`, cbid, no_value' +
- ' ) As m ' +
- ' ON (c.stimes * ' + timesLen + ' + c.sorder) = m.progress And c.lid = m.lid And c.pid = m.pid And c.`sid` = m.`sid` And c.`cbid` = m.`cbid` And c.`no_value` = m.`no_value`' +
- ' LEFT JOIN ' + this.ctx.service.change.tableName + ' As oc' +
- ' ON c.cid = oc.cid' +
- ' LEFT JOIN ' + this.ctx.service.changeAuditList.tableName + ' As ocb' +
- ' ON c.cbid = ocb.id' +
- ' WHERE not ISNULL(ocb.id)';
- const sqlParam = [tid, sid, times, times, order, lid, pid ? pid : -1];
- if (noValue !== undefined) sqlParam.push(noValue);
- return await this.db.query(sql, sqlParam);
- }
- async getLastestAllStageData(tid, sid) {
- const sql = 'SELECT c.*,' +
- ' oc.p_code As c_code, oc.new_code As c_new_code, oc.quality, ocb.code as b_code, ocb.name, ocb.unit' +
- ' FROM ' + this.tableName + ' As c ' +
- ' INNER JOIN ( ' +
- ' SELECT MAX(`stimes` * ' + timesLen + ' + `sorder`) As `progress`, `lid`, `pid`, `sid`, `cid`, `cbid`, `no_value` From ' + this.tableName +
- ' WHERE tid = ? And sid = ?' +
- ' GROUP By `lid`, `pid`, cbid, no_value' +
- ' ) As m ' +
- ' ON (c.stimes * ' + timesLen + ' + c.sorder) = m.progress And c.lid = m.lid And c.pid = m.pid And c.`sid` = m.`sid` And c.`cbid` = m.`cbid` And c.`no_value` = m.`no_value`' +
- ' LEFT JOIN ' + this.ctx.service.change.tableName + ' As oc' +
- ' ON c.cid = oc.cid' +
- ' LEFT JOIN ' + this.ctx.service.changeAuditList.tableName + ' As ocb' +
- ' ON c.cbid = ocb.id' +
- ' WHERE not ISNULL(ocb.id)';
- const sqlParam = [tid, sid];
- return await this.db.query(sql, sqlParam);
- }
- async getAuditorAllStageData(tid, sid, times, order) {
- const sql = 'SELECT c.*, ' +
- ' oc.p_code As c_code, oc.new_code As c_new_code, oc.quality, ocb.code as b_code, ocb.name, ocb.unit' +
- ' FROM ' + this.tableName + ' As c ' +
- ' INNER JOIN ( ' +
- ' SELECT MAX(`stimes` * ' + timesLen + ' + `sorder`) As `progress`, `lid`, `pid`, `sid`, `cid`, `cbid`, `no_value` From ' + this.tableName +
- ' WHERE tid = ? And sid = ? And (`stimes` < ? OR (`stimes` = ? AND `sorder` <= ?))' +
- ' GROUP By `lid`, `pid`, cbid, no_value' +
- ' ) As m ' +
- ' ON (c.stimes * ' + timesLen + ' + c.sorder) = m.progress And c.lid = m.lid And c.pid = m.pid And c.`sid` = m.`sid` And c.`cbid` = m.`cbid` And c.`no_value` = m.`no_value`' +
- ' LEFT JOIN ' + this.ctx.service.change.tableName + ' As oc' +
- ' ON c.cid = oc.cid' +
- ' LEFT JOIN ' + this.ctx.service.changeAuditList.tableName + ' As ocb' +
- ' ON c.cbid = ocb.id' +
- ' WHERE not ISNULL(ocb.id)';
- const sqlParam = [tid, sid, times, times, order];
- return await this.db.query(sql, sqlParam);
- }
- /**
- * 台账,调用变更令
- *
- * @param {Object} bills - 台账节点数据
- * @param {Array} changes - 调用的变更令
- * @return {Promise<void>}
- */
- async billsChange(bills, noValue, changes) {
- const self = this;
- function getNewChange(cid, cbid, times, order, qty, minus, no_value) {
- return {
- tid: self.ctx.tender.id, sid: self.ctx.stage.id,
- lid: bills.id, pid: -1,
- cid, cbid,
- stimes: times, sorder: order,
- qty, minus, no_value,
- };
- }
- const ledgerBills = await this.ctx.service.ledger.getCompleteDataById(bills.id);
- if (!ledgerBills || ledgerBills.tender_id !== this.ctx.tender.id) {
- throw '提交数据错误';
- }
- const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, ledgerBills.unit);
- // 获取原变更令
- const oldChanges = await this.getLastestStageData(this.ctx.tender.id, this.ctx.stage.id, bills.id, -1, noValue);
- // 获取更新数据
- const updateChanges = [],
- newChanges = [];
- let billsQty = 0, billsPositiveQty = 0, billsNegativeQty = 0;
- for (const oc of oldChanges) {
- const nc = this._.find(changes, { cid: oc.cid, cbid: oc.cbid });
- if (!nc || nc.qty !== oc.qty) {
- const qty = nc ? this.round(nc.qty, precision.value) : null;
- const change = getNewChange(oc.cid, oc.cbid, this.ctx.stage.curTimes, this.ctx.stage.curOrder, qty, nc ? nc.minus : oc.minus, noValue);
- change.unit_price = ledgerBills.unit_price;
- billsQty = this.ctx.helper.add(billsQty, change.qty);
- if (change.minus) {
- billsNegativeQty = this.ctx.helper.add(billsNegativeQty, change.qty);
- } else {
- billsPositiveQty = this.ctx.helper.add(billsPositiveQty, change.qty);
- }
- if (oc.stimes === this.ctx.stage.curTimes && oc.sorder === this.ctx.stage.curOrder) {
- change.id = oc.id;
- updateChanges.push(change);
- } else {
- newChanges.push(change);
- }
- } else {
- billsQty = this.ctx.helper.add(billsQty, oc.qty);
- if (oc.minus) {
- billsNegativeQty = this.ctx.helper.add(billsNegativeQty, oc.qty);
- } else {
- billsPositiveQty = this.ctx.helper.add(billsPositiveQty, oc.qty);
- }
- }
- }
- for (const c of changes) {
- const nc = this._.find(oldChanges, { cid: c.cid, cbid: c.cbid });
- if (!nc) {
- const change = getNewChange(c.cid, c.cbid, this.ctx.stage.curTimes, this.ctx.stage.curOrder, this.round(c.qty, precision.value), c.minus, noValue);
- change.unit_price = ledgerBills.unit_price;
- billsQty = this.ctx.helper.add(billsQty, change.qty);
- if (change.minus) {
- billsNegativeQty = this.ctx.helper.add(billsNegativeQty, change.qty);
- } else {
- billsPositiveQty = this.ctx.helper.add(billsPositiveQty, change.qty);
- }
- newChanges.push(change);
- }
- }
- // 更新数据
- const transaction = await this.db.beginTransaction();
- try {
- if (newChanges.length > 0) await transaction.insert(this.tableName, newChanges);
- if (updateChanges.length > 0) await transaction.updateRows(this.tableName, updateChanges);
- const stageBills = await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, bills.id);
- const sbUpdate = noValue
- ? { qc_minus_qty: billsQty }
- : { qc_qty: billsQty, positive_qc_qty: billsPositiveQty, negative_qc_qty: billsNegativeQty };
- await this.ctx.service.stageBills.updateStageBillsQty(transaction, ledgerBills, stageBills, sbUpdate);
- await transaction.commit();
- } catch (err) {
- await transaction.rollback();
- throw err;
- }
- const result = await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, [bills.id]);
- return { bills: { curStageData: result } };
- }
- /**
- * 部位明细,调用变更令
- *
- * @param {Object} pos - 部位明细数据
- * @param {Array} changes - 调用的变更令
- * @return {Promise<{}>}
- */
- async posChange(pos, noValue, changes) {
- const self = this;
- function getNewChange(cid, cbid, times, order, qty, minus, no_value) {
- return {
- tid: self.ctx.tender.id, sid: self.ctx.stage.id,
- lid: pos.lid, pid: pos.id,
- cid, cbid,
- stimes: times, sorder: order,
- qty, minus, no_value,
- };
- }
- const ledgerBills = await this.ctx.service.ledger.getCompleteDataById(pos.lid);
- if (!ledgerBills || ledgerBills.tender_id !== this.ctx.tender.id) {
- throw '提交数据错误';
- }
- const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, ledgerBills.unit);
- // 获取原变更令
- const oldChanges = await this.getLastestStageData(this.ctx.tender.id, this.ctx.stage.id, pos.lid, pos.id, noValue);
- const updateChanges = [],
- newChanges = [];
- let posQty = 0, posPositiveQty = 0, posNegativeQty = 0;
- for (const oc of oldChanges) {
- const nc = this._.find(changes, { cid: oc.cid, cbid: oc.cbid });
- if (!nc || nc.qty !== oc.qty) {
- const qty = nc ? this.round(nc.qty, precision.value) : null;
- const change = getNewChange(oc.cid, oc.cbid, this.ctx.stage.curTimes, this.ctx.stage.curOrder, qty, nc ? nc.minus : oc.minus, noValue);
- change.unit_price = ledgerBills.unit_price;
- posQty = this.ctx.helper.add(posQty, change.qty);
- if (change.minus) {
- posNegativeQty = this.ctx.helper.add(posNegativeQty, change.qty);
- } else {
- posPositiveQty = this.ctx.helper.add(posPositiveQty, change.qty);
- }
- if (oc.stimes === this.ctx.stage.curTimes && oc.sorder === this.ctx.stage.curOrder) {
- change.id = oc.id;
- updateChanges.push(change);
- } else {
- newChanges.push(change);
- }
- } else {
- posQty = this.ctx.helper.add(posQty, oc.qty);
- if (oc.minus) {
- posNegativeQty = this.ctx.helper.add(posNegativeQty, oc.qty);
- } else {
- posPositiveQty = this.ctx.helper.add(posPositiveQty, oc.qty);
- }
- }
- }
- for (const c of changes) {
- const nc = this._.find(oldChanges, { cid: c.cid, cbid: c.cbid });
- if (!nc) {
- const change = getNewChange(c.cid, c.cbid, this.ctx.stage.curTimes, this.ctx.stage.curOrder, this.round(c.qty, precision.value), c.minus, noValue);
- change.unit_price = ledgerBills.unit_price;
- posQty = this.ctx.helper.add(posQty, change.qty);
- if (change.minus) {
- posNegativeQty = this.ctx.helper.add(posNegativeQty, change.qty);
- } else {
- posPositiveQty = this.ctx.helper.add(posPositiveQty, change.qty);
- }
- newChanges.push(change);
- }
- }
- // 更新数据
- const transaction = await this.db.beginTransaction();
- try {
- if (newChanges.length > 0) await transaction.insert(this.tableName, newChanges);
- if (updateChanges.length > 0) await transaction.updateRows(this.tableName, updateChanges);
- await this.ctx.service.stagePos.updateChangeQuantity(transaction, pos, posQty, noValue, posPositiveQty, posNegativeQty);
- await transaction.commit();
- } catch (err) {
- await transaction.rollback();
- throw err;
- }
- // 获取返回数据
- try {
- const data = { bills: {}, pos: {} };
- data.bills.curStageData = await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, [pos.lid]);
- data.pos.curStageData = await this.ctx.service.stagePos.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, { pid: pos.id });
- return data;
- } catch (err) {
- throw '获取数据错误,请刷新页面';
- }
- }
- /**
- * 获取 变更令 - 变更清单 使用情况
- * @param {Number} sid - 查询期id
- * @param {uuid} cid - 变更令id
- * @return {Promise<void>}
- */
- async getUsedData(tid, cid) {
- if (this.ctx.stage.status === audit.stage.status.checked) {
- const sql = 'SELECT scf.* ' +
- ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
- ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
- ' WHERE scf.tid = ? And scf.cid = ? And s.order <= ?';
- const result = await this.db.query(sql, [tid, cid, this.ctx.stage.order]);
- return result;
- } else {
- const preSql = 'SELECT scf.* ' +
- ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
- ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
- ' WHERE scf.tid = ? And scf.cid = ? And s.order < ?';
- const pre = await this.db.query(preSql, [tid, cid, this.ctx.stage.order]);
- const sql = 'SELECT * FROM ' + this.tableName + ' WHERE sid = ?';
- const curAll = await this.db.query(sql, [this.ctx.stage.id]);
- const cur = this.ctx.helper.filterLastestData(curAll, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
- return [...pre, ...cur];
- }
- }
- async getFinalUsedData(tid, cid) {
- const stage = await this.ctx.service.stage.getFlowLatestStage(tid, true);
- if (!stage) { // 防止未创建期时调用
- return [];
- }
- if (stage.status === audit.stage.status.checked) {
- const sql = 'SELECT scf.* ' +
- ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
- ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
- this.ctx.helper.whereSql({ tid, cid }, 'scf') + ' And s.order <= ?';
- const result = await this.db.query(sql, [stage.order]);
- return result;
- } else {
- const preSql = 'SELECT scf.* ' +
- ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
- ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
- this.ctx.helper.whereSql({ tid, cid }, 'scf') + ' And s.order < ?';
- const pre = await this.db.query(preSql, [stage.order]);
- const sql = 'SELECT * FROM ' + this.tableName + this.ctx.helper.whereSql({ sid: stage.id, cid });
- const curAll = await this.db.query(sql);
- const cur = this.ctx.helper.filterLastestData(curAll, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
- return [...pre, ...cur];
- }
- }
- async getAllFinalUsedData(tid, cid) {
- const result = [];
- const stages = await this.ctx.service.stage.getAllDataByCondition({ where: { tid: tid }, orders: [['order', 'desc']] });
- for (const stage of stages) {
- if (stage.status === audit.stage.status.checked) {
- const sql = `SELECT * FROM ${this.ctx.service.stageChangeFinal.tableName} WHERE tid = ? and cid = ? AND sorder <= ?`;
- const pre = await this.db.query(sql, [tid, cid, stage.order]);
- result.push(...pre);
- break;
- } else {
- const sql = 'SELECT * FROM ' + this.tableName + this.ctx.helper.whereSql({ sid: stage.id, cid });
- const curAll = await this.db.query(sql);
- const cur = this.ctx.helper.filterLastestData(curAll, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
- result.push(...cur);
- }
- }
- return result;
- }
- /**
- * 获取 变更令 - 变更清单 当期使用情况
- * @param {Number} sid - 查询期id
- * @param {uuid} cid - 变更令id
- * @return {Promise<*>}
- */
- async getStageUsedData(sid, cid) {
- const data = await this.getAllDataByCondition({ where: { sid, cid } });
- const _ = this.ctx.helper._;
- const filter = this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
- if (filter.length === 0) return filter;
- const bills = await this.ctx.service.ledger.getAllDataByCondition({
- where: { id: _.uniq(_.map(filter, 'lid')) }
- });
- const pos = await this.ctx.service.pos.getAllDataByCondition({
- where: { id: _.uniq(_.map(filter, 'pid')) }
- });
- return filter.map(x => {
- const b = bills.find(y => { return y.id === x.lid });
- const rela_b = b
- ? {ledger_id: b ? b.ledger_id : -1, l_code: b.b_code, l_name: b.name, l_unit: b.unit, l_up: b.unit_price,
- l_deal_qty: b.deal_qty, l_deal_tp: b.deal_tp, l_qty: b.quantity, l_tp: b.total_price, l_drawing_code: b.drawing_code}
- : { ledger_id: -1, l_code: '', l_name: '', l_unit: '', l_up: 0, l_deal_qty: 0, l_deal_tp: 0, l_qty: 0, l_tp: 0, l_drawing_code: '' };
- const p = pos.find(y => { return y.id === x.pid });
- const rela_p = p ? { p_name: p.name, p_drawing_code: p.drawing_code, p_qty: p.quantity } : { p_name: '', p_drawing_code: '', p_qty: 0 };
- return { ...x, ...rela_b, ...rela_p };
- });
- }
- /**
- * 获取 本期 使用的变更令
- * @param sid
- * @return {Promise<void>}
- */
- async getStageUsedChangeId(sid) {
- const sql = 'SELECT lid, pid, cid, cbid, qty, stimes, sorder, no_value FROM ' + this.tableName + ' WHERE sid = ?';
- const curAll = await this.db.query(sql, [sid]);
- const cur = this.ctx.helper.filterLastestData(curAll, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
- return this._.map(this._.filter(cur, 'qty'), 'cid');
- }
- async getCurStageData(tid, sid, stimes, sorder) {
- const sql = `SELECT * From ${this.tableName} WHERE tid = ? AND sid = ? AND (stimes < ? OR (stimes = ? AND sorder < ?))`;
- const data = await this.db.query(sql, [tid, sid, stimes, stimes, sorder]);
- return this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
- }
- async getFinalStageData(tid, sid) {
- const data = await this.getAllDataByCondition({ where: { tid, sid } });
- return this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
- }
- async getSumLoadFinalData(sid) {
- const sql = 'Select cf.tid, cf.sid, cf.lid, cf.pid, cf.cid, cf.cbid, cf.qty, cf.stimes, cf.sorder, cf.minus, cf.no_value, c.code As c_code' +
- ' FROM ' + this.tableName + ' cf' +
- ' Left Join ' + this.ctx.service.change.tableName + ' c ON cf.cid = c.cid' +
- ' Where cf.sid = ?';
- const result = await this.db.query(sql, [sid]);
- return this.ctx.helper.filterLastestData(result, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
- }
- async _getTender(stage) {
- if (this.ctx.tender) return this.ctx.tender;
- const tender = { id: stage.tid };
- tender.data = await this.ctx.service.tender.getTender(stage.tid);
- tender.info = await this.service.tenderInfo.getTenderInfo(tender.id);
- return tender;
- }
- async getSubtotal(stage) {
- const helper = this.ctx.helper;
- const tender = await this._getTender(stage);
- const sql = 'SELECT sc.*, c.quality FROM ' + this.tableName + ' sc' +
- ' LEFT JOIN ' + this.ctx.service.change.tableName + ' c ON sc.cid = c.cid' +
- ' WHERE sid = ? ' + (stage.readOnly ? ` and (stimes < ${stage.curTimes} or (stimes = ${stage.curTimes} and sorder <= ${stage.curOrder}))` : '');
- let data = await this.db.query(sql, [stage.id]);
- data = helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
- const bqData = [];
- for (const d of data) {
- if (!d.qty || d.no_value) continue;
- let bd = bqData.find(x => { return x.lid === d.lid && x.quality === d.quality; });
- if (!bd) {
- bd = { lid: d.lid, quality: d.quality, unit_price: d.unit_price };
- bqData.push(bd);
- }
- const tp = this.ctx.helper.mul(d.qty, bd.unit_price, tender.info.decimal.tp);
- bd.tp = this.ctx.helper.add(bd.tp, tp);
- }
- const result = {};
- result.common = helper.sum(helper._.map(bqData.filter(x => {return x.quality === changeConst.quality.common.value; }), 'tp'));
- result.more = helper.sum(helper._.map(bqData.filter(x => {return x.quality === changeConst.quality.more.value; }), 'tp'));
- result.great = helper.sum(helper._.map(bqData.filter(x => {return x.quality === changeConst.quality.great.value; }), 'tp'));
- return result;
- }
- async getChangeBillsWithUsedInfo(stage) {
- if (stage.status === audit.stage.status.checked) {
- const sql = 'SELECT scf.* ' +
- ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
- ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
- ' WHERE scf.tid = ? And s.order <= ?';
- const result = await this.db.query(sql, [stage.tid, stage.order]);
- return result;
- } else {
- const preSql = 'SELECT scf.* ' +
- ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
- ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
- ' WHERE scf.tid = ? And s.order < ?';
- const pre = await this.db.query(preSql, [stage.tid, stage.order]);
- const sql = 'SELECT * FROM ' + this.tableName + ' WHERE sid = ? AND (stimes * 100 + sorder) <= (? * 100 + ?)';
- const curAll = await this.db.query(sql, [stage.id, stage.curTimes, stage.curOrder]);
- const cur = this.ctx.helper.filterLastestData(curAll, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
- return [...pre, ...cur];
- }
- }
- async getChangeWithUsedInfo(stage) {
- const change = await this.ctx.service.change.getAllDataByCondition({
- where: { tid: stage.tid, status: audit.flow.status.checked },
- orders: [['code', 'asc']],
- });
- if (change.length === 0) return [];
- const changeBills = await this.ctx.service.changeAuditList.getAllDataByCondition({
- where: { cid: change.map(x => { return x.cid; }) }
- });
- const changeBillsIndex = {}, changeBillsPart = {};
- for (const cb of changeBills) {
- changeBillsIndex[cb.id] = cb;
- if (!changeBillsPart[cb.cid]) changeBillsPart[cb.cid] = [];
- changeBillsPart[cb.cid].push(cb);
- }
- const stageChangeBills = await this.getChangeBillsWithUsedInfo(stage);
- for (const scb of stageChangeBills) {
- if (!scb.qty) continue;
- const cb = changeBillsIndex[scb.cbid];
- if (cb) cb.used_qty = this.ctx.helper.add(cb.used_qty, scb.qty);
- }
- for (const cid in changeBillsPart) {
- const c = change.find(x => { return x.cid === cid });
- if (!c) continue;
- for (const cb of changeBillsPart[cid]) {
- cb.tp = this.ctx.helper.mul(cb.spamount, cb.unit_price, c.tp_decimal || this.ctx.tender.info.decimal.tp);
- cb.used_tp = this.ctx.helper.mul(cb.used_qty, cb.unit_price, this.ctx.tender.info.decimal.tp);
- c.used_tp = this.ctx.helper.add(c.used_tp, cb.used_tp);
- if (cb.spamount > 0) {
- c.p_tp = this.ctx.helper.add(c.p_tp, cb.tp);
- c.p_used_tp = this.ctx.helper.add(c.p_used_tp, cb.used_tp);
- } else if (cb.spamount < 0){
- c.n_tp = this.ctx.helper.add(c.n_tp, cb.tp);
- c.n_used_tp = this.ctx.helper.add(c.n_used_tp, cb.used_tp);
- }
- }
- c.used_pt = c.total_price ? this.ctx.helper.mul(this.ctx.helper.div(c.used_tp, c.total_price, 4), 100) : 0;
- c.p_used_pt = c.p_tp ? this.ctx.helper.mul(this.ctx.helper.div(c.p_used_tp, c.p_tp, 4), 100) : 0;
- c.n_used_pt = c.n_tp ? this.ctx.helper.mul(this.ctx.helper.div(c.n_used_tp, c.n_tp, 4), 100) : 0;
- }
- return change;
- }
- async getStageMinusChange(stage) {
- const data = await this.getAllDataByCondition({ where: { sid: stage.id, minus: 1 } });
- return this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
- };
- async getBillsMinusQty(stage, lid) {
- const data = await this.getAllDataByCondition({ where: { sid: stage.id, lid, minus: 1 } });
- const filter = this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
- return { lid, qty: this.ctx.helper.sum(filter.map(x => { return x.qty; })) };
- };
- async getPosMinusQty(stage, pid) {
- const data = await this.getAllDataByCondition({ where: { sid: stage.id, pid, minus: 1 } });
- const filter = this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
- return { pid, qty: this.ctx.helper.sum(filter.map(x => { return x.qty; })) };
- };
- async autoUseChangeBills(tender, stage, data) {
- const lid = [], cbid = [];
- data.forEach(x => {
- lid.push(x.lid);
- cbid.push(x.cbid);
- });
- const validChangeBills = await this.ctx.service.stageChangeFinal.getListChangeBillsValidQty(tender.id, cbid);
- validChangeBills.forEach(x => {
- x.billsPos = data.find(y => { return x.id === y.cbid; });
- });
- const ledgerData = await this.ctx.service.ledger.getAllDataByCondition({
- columns: ['id', 'ledger_id', 'ledger_pid', 'level', 'order', 'full_path', 'is_leaf', 'code', 'b_code', 'name', 'unit', 'unit_price'],
- where: { id: lid },
- });
- const extraData = await this.ctx.service.ledgerExtra.getData(this.ctx.tender.id, ['is_tp']);
- this.ctx.helper.assignRelaData(ledgerData, [
- { data: extraData, fields: ['is_tp'], prefix: '', relaId: 'id' },
- ]);
- const posData = await this.ctx.service.pos.getAllDataByCondition({
- columns: ['id', 'lid', 'name', 'porder'],
- where: { lid },
- });
- const stageBills = await this.ctx.service.stageBills.getAllDataByCondition({ where: { sid: stage.id } });
- const stagePos = await this.ctx.service.stagePos.getAllDataByCondition({ where: { sid: stage.id } });
- const stageChange = await this.ctx.service.stageChange.getAllDataByCondition({ where: { sid: stage.id, lid }});
- const useModal = new autoUseChange(this.ctx.helper, tender.info);
- const projectFunInfo = this.ctx.subProject.fun_rela;
- const minusNoValue = projectFunInfo.minusNoValue && tender.info.fun_rela.stage_change.minusNoValue;
- useModal.use({ledgerData, posData, stageBills, stagePos, stageChange, default: { tid: stage.tid, sid: stage.id, said: this.ctx.session.sessionUser.accountId } }, validChangeBills, minusNoValue);
- const conn = await this.db.beginTransaction();
- try {
- if (useModal.insertBills.length > 0) await conn.insert(this.ctx.service.stageBills.tableName, useModal.insertBills);
- if (useModal.updateBills.length > 0) await conn.updateRows(this.ctx.service.stageBills.tableName, useModal.updateBills);
- if (useModal.insertPos.length > 0) await conn.insert(this.ctx.service.stagePos.tableName, useModal.insertPos);
- if (useModal.updatePos.length > 0) await conn.updateRows(this.ctx.service.stagePos.tableName, useModal.updatePos);
- if (useModal.insertChange.length > 0) await conn.insert(this.tableName, useModal.insertChange);
- if (useModal.updateChange.length > 0) await conn.updateRows(this.tableName, useModal.updateChange);
- await conn.commit();
- } catch (err) {
- await conn.rollback();
- this.ctx.log(err);
- throw '保存导入数据失败';
- }
- const rst = { bills: {}, pos: {} };
- rst.bills.curStageData = await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, lid);
- rst.pos.curStageData = await this.ctx.service.stagePos.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, { lid });
- return rst;
- };
- async autoUseAllChange(tender, stage) {
- const validChangeBills = await this.ctx.service.stageChangeFinal.getAllChangeBillsValidQty(tender.id);
- const ledgerData = await this.ctx.service.ledger.getAllDataByCondition({
- columns: ['id', 'ledger_id', 'ledger_pid', 'level', 'order', 'full_path', 'is_leaf', 'code', 'b_code', 'name', 'unit', 'unit_price'],
- where: { tender_id: stage.tid },
- });
- const extraData = await this.ctx.service.ledgerExtra.getData(this.ctx.tender.id, ['is_tp']);
- const settleStatusBills = stage.readySettle ? await this.ctx.service.settleBills.getAllDataByCondition({ where: { settle_id: stage.readySettle.id }}) : [];
- this.ctx.helper.assignRelaData(ledgerData, [
- { data: extraData, fields: ['is_tp'], prefix: '', relaId: 'id' },
- { data: settleStatusBills, fields: ['settle_status'], prefix: '', relaId: 'lid' },
- ]);
- const posData = await this.ctx.service.pos.getAllDataByCondition({
- columns: ['id', 'lid', 'name', 'porder'],
- where: { tid: stage.tid },
- });
- const settleStatusPos = stage.readySettle ? await this.ctx.service.settlePos.getAllDataByCondition({ where: { settle_id: stage.readySettle.id }}) : [];
- this.ctx.helper.assignRelaData(posData, [
- { data: settleStatusPos, fields: ['settle_status'], prefix: '', relaId: 'pid' },
- ]);
- const stageBills = await this.ctx.service.stageBills.getAllDataByCondition({ where: { sid: stage.id } });
- const stagePos = await this.ctx.service.stagePos.getAllDataByCondition({ where: { sid: stage.id } });
- const useModal = new autoUseChange(this.ctx.helper, tender.info, this.ctx.service.settle.settleStatus);
- const projectFunInfo = this.ctx.subProject.fun_rela;
- const minusNoValue = projectFunInfo.minusNoValue && tender.info.fun_rela.stage_change.minusNoValue;
- useModal.use({ledgerData, posData, stageBills, stagePos, default: { tid: stage.tid, sid: stage.id, said: this.ctx.session.sessionUser.accountId } }, validChangeBills, minusNoValue);
- // if (useModal.insertChange.length === 0) return '无可调用的清单或计量单元';
- const conn = await this.db.beginTransaction();
- try {
- if (useModal.insertBills.length > 0) await conn.insert(this.ctx.service.stageBills.tableName, useModal.insertBills);
- if (useModal.updateBills.length > 0) await conn.updateRows(this.ctx.service.stageBills.tableName, useModal.updateBills);
- if (useModal.insertPos.length > 0) await conn.insert(this.ctx.service.stagePos.tableName, useModal.insertPos);
- if (useModal.updatePos.length > 0) await conn.updateRows(this.ctx.service.stagePos.tableName, useModal.updatePos);
- await conn.delete(this.tableName, { sid: stage.id });
- if (useModal.insertChange.length > 0) await conn.insert(this.tableName, useModal.insertChange);
- await conn.commit();
- } catch (err) {
- await conn.rollback();
- this.ctx.log(err);
- throw '保存导入数据失败';
- }
- }
- async updateStageChange4CheckCancel(sid, newTimes, newOrder, oldTimes, oldOrder, transaction) {
- const oldSBLists = await this.getAllDataByCondition({ where: { sid, stimes: oldTimes, sorder: oldOrder } });
- const newSBLists = await this.getAllDataByCondition({ where: { sid, stimes: newTimes, sorder: newOrder } });
- const delidList = [];
- for (const o of oldSBLists) {
- const newSBInfo = this._.find(newSBLists, { lid: o.lid });
- if (newSBInfo) {
- // 删除
- delidList.push(newSBInfo.id);
- }
- }
- if (delidList.length > 0) await transaction.delete(this.tableName, { id: delidList });
- if (oldSBLists.length > 0) {
- await transaction.update(this.tableName, {
- stimes: newTimes,
- sorder: newOrder,
- }, { where: { id: this._.map(oldSBLists, 'id') } });
- }
- }
- }
- return StageChange;
- };
|