stage_change.js 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. 'use strict';
  2. /**
  3. * 期 - 变更数据
  4. *
  5. * @author Mai
  6. * @date
  7. * @version
  8. */
  9. const defaultPid = -1; // 非pid
  10. const audit = require('../const/audit');
  11. const timesLen = audit.stage.timesLen;
  12. const changeConst = require('../const/change');
  13. class autoUseChange {
  14. constructor(helper, info, settleStatus) {
  15. this.helper = helper;
  16. this.info = info;
  17. this.precision = info.precision;
  18. this.decimal = info.decimal;
  19. this.settleStatus = settleStatus;
  20. this.insertBills = [];
  21. this.insertPos = [];
  22. this.updateBills = [];
  23. this.updatePos = [];
  24. this.insertChange = [];
  25. this.updateChange = [];
  26. this.changeBills = {};
  27. this.changePos = {};
  28. this.changeDetail = [];
  29. }
  30. init(source) {
  31. this.default = source.default;
  32. const LedgerModel = require('../lib/ledger');
  33. this.ledgerTree = new LedgerModel.billsTree(this.ctx, {
  34. id: 'ledger_id', pid: 'ledger_pid', order: 'order', level: 'level', rootId: -1, calcFields: [],
  35. });
  36. this.pos = new LedgerModel.pos({ id: 'id', ledgerId: 'lid' });
  37. this.ledgerTree.loadDatas(source.ledgerData);
  38. this.pos.loadDatas(source.posData);
  39. this.stageBills = source.stageBills;
  40. this.stagePos = source.stagePos;
  41. this.stageChange = source.stageChange || [];
  42. this.preStageBills = source.preStageBills || [];
  43. }
  44. findBillsPos(changeBills){
  45. if (changeBills.gcl_id) {
  46. const node = this.ledgerTree.datas.find(x => {return x.id === changeBills.gcl_id});
  47. if (node.settle_status === this.settleStatus.finish) return null;
  48. const posData = this.pos.getLedgerPos(node.id) || [];
  49. const changePos = posData.find(x => { return x.name === changeBills.bwmx; });
  50. if (changePos && changePos.settle_status) return null;
  51. let defaultPos;
  52. if (posData.length > 0) {
  53. defaultPos = posData.length > 0 ? posData.find(x => { return !x.settle_status}) : null;
  54. if (!defaultPos) return null;
  55. } else {
  56. defaultPos = { id: '-1' };
  57. }
  58. return { bills: node, lid: node.id, pid: changePos ? changePos.id : defaultPos.id };
  59. } else {
  60. const cb = {
  61. b_code: changeBills.code || '',
  62. name: changeBills.name || '',
  63. unit: changeBills.unit || '',
  64. unit_price: changeBills.unit_price || 0,
  65. is_tp: false,
  66. };
  67. for (const node of this.ledgerTree.nodes) {
  68. if (node.children && node.children.length > 0) continue;
  69. if (node.settle_status === this.settleStatus.finish) return null;
  70. const b = {
  71. b_code: node.b_code || '',
  72. name: node.name || '',
  73. unit: node.unit || '',
  74. unit_price: node.unit_price || 0,
  75. is_tp: !!node.is_tp,
  76. };
  77. if (this.helper._.isMatch(cb, b)) {
  78. const posData = this.pos.getLedgerPos(node.id) || [];
  79. let defaultPos;
  80. if (posData.length > 0) {
  81. defaultPos = posData.length > 0 ? posData.find(x => { return !x.settle_status}) : null;
  82. if (!defaultPos) return null;
  83. } else {
  84. defaultPos = { id: '-1' };
  85. }
  86. return { bills: node, lid: node.id, pid: defaultPos.id };
  87. }
  88. }
  89. return null;
  90. }
  91. }
  92. _calculateQty(detail, minus, bills) {
  93. if (bills.is_valuation) {
  94. detail.qty = this.helper.add(detail.qty, bills.valid_qty);
  95. if (minus) {
  96. detail.negative_qc_qty = this.helper.add(detail.negative_qc_qty, bills.valid_qty);
  97. } else {
  98. detail.positive_qc_qty = this.helper.add(detail.positive_qc_qty, bills.valid_qty);
  99. }
  100. } else {
  101. detail.qc_minus_qty = this.helper.add(detail.qc_minus_qty, bills.valid_qty);
  102. }
  103. }
  104. _calculateUsedQty(detail, bills) {
  105. if (!bills.no_value) {
  106. detail.qty = this.helper.add(detail.qty, bills.qty);
  107. if (detail.minus) {
  108. detail.negative_qc_qty = this.helper.add(detail.negative_qc_qty, bills.qty);
  109. } else {
  110. detail.positive_qc_qty = this.helper.add(detail.positive_qc_qty, bills.qty);
  111. }
  112. } else {
  113. detail.qc_minus_qty = this.helper.add(detail.qc_minus_qty, bills.qty);
  114. }
  115. }
  116. useBills(bills) {
  117. if (bills.billsPos) bills.billsPos.bills = this.ledgerTree.datas.find(x => {return x.id === bills.billsPos.lid; });
  118. const billsPos = bills.billsPos || this.findBillsPos(bills);
  119. if (!billsPos) return;
  120. if (!this.minusNoValue && !bills.is_valuation) return;
  121. const bamount = parseFloat(bills.samount);
  122. const minus = bamount < 0;
  123. this.changeDetail.push({
  124. tid: this.default.tid, sid: this.default.sid,
  125. lid: billsPos.lid, pid: billsPos.pid + '', cid: bills.cid, cbid: bills.id,
  126. qty: bills.valid_qty, stimes: 1, sorder: 0, unit_price: bills.unit_price, minus, no_value: !bills.is_valuation,
  127. });
  128. if (billsPos.pid !== '-1') {
  129. let cp = this.changePos[billsPos.pid];
  130. if (!cp) {
  131. cp = { lid: billsPos.lid, pid: billsPos.pid, qty: 0, negative_qc_qty: 0, positive_qc_qty: 0, qc_minus_qty: 0, bills: billsPos.bills };
  132. this.changePos[billsPos.pid] = cp;
  133. }
  134. this._calculateQty(cp, minus, bills);
  135. } else {
  136. let cb = this.changeBills[billsPos.lid];
  137. if (!cb) {
  138. cb = { lid: billsPos.lid, qty: 0, bills: billsPos.bills };
  139. this.changeBills[billsPos.lid] = cb;
  140. }
  141. this._calculateQty(cb, minus, bills);
  142. }
  143. }
  144. calcContractTp(bills, contract_qty, qc_minus_qty) {
  145. const preSb = this.preStageBills.find(x => { return x.lid === bills.id; });
  146. let activeQty = this.helper.add(bills.quantity, qc_minus_qty);
  147. let end_contract_qty = contract_qty;
  148. if (preSb) {
  149. activeQty = this.helper.add(activeQty, preSb.qc_minus_qty);
  150. end_contract_qty = this.helper.add(end_contract_qty, preSb.contract_qty);
  151. }
  152. const end_contract_tp = this.helper.mul(this.helper.div(end_contract_qty, activeQty), bills.total_price, this.decimal.tp);
  153. return preSb ? this.helper.sub(end_contract_tp, preSb.pre_contract_tp) : end_contract_tp;
  154. }
  155. calculateAll() {
  156. for (const cd of this.changeDetail) {
  157. const sci = this.stageChange.findIndex(x => {
  158. return x.lid === cd.lid && x.pid === cd.pid && x.cbid === cd.cbid;
  159. });
  160. const sc = this.stageChange[sci];
  161. if (sc) {
  162. this.updateChange.push({ id: sc.id, qty: cd.qty });
  163. this.stageChange.splice(sci, 1);
  164. } else {
  165. this.insertChange.push(cd);
  166. }
  167. }
  168. for (const sc of this.stageChange) {
  169. const cp = this.changePos[sc.pid];
  170. if (cp) this._calculateUsedQty(cp, sc);
  171. }
  172. for (const pid in this.changePos) {
  173. const cp = this.changePos[pid];
  174. if (!cp) continue;
  175. const precision = this.helper.findPrecision(this.precision, cp.bills.unit);
  176. const qc_qty = this.helper.round(cp.qty, precision.value);
  177. const positive_qc_qty = this.helper.round(cp.positive_qc_qty || 0, precision.value);
  178. const negative_qc_qty = this.helper.round(cp.negative_qc_qty || 0, precision.value);
  179. const qc_minus_qty = this.helper.round(cp.qc_minus_qty || 0, precision.value);
  180. const sp = this.stagePos.find(x => {return x.pid === pid});
  181. if (sp) {
  182. this.updatePos.push({ id: sp.id, qc_qty, positive_qc_qty, negative_qc_qty, qc_minus_qty });
  183. } else {
  184. this.insertPos.push({
  185. tid: this.default.tid, sid: this.default.sid, said: this.default.said,
  186. lid: cp.lid, pid, qc_qty, positive_qc_qty, negative_qc_qty, qc_minus_qty, times: 1, order: 0
  187. });
  188. }
  189. const cb = this.changeBills[cp.lid];
  190. if (!cb) {
  191. this.changeBills[cp.lid] = { lid: cp.lid, qty: qc_qty, positive_qc_qty, negative_qc_qty, qc_minus_qty, bills: cp.bills };
  192. } else {
  193. cb.qty = this.helper.add(cb.qty, qc_qty);
  194. cb.positive_qc_qty = this.helper.add(cb.positive_qc_qty, positive_qc_qty);
  195. cb.negative_qc_qty = this.helper.add(cb.negative_qc_qty, negative_qc_qty);
  196. cb.qc_minus_qty = this.helper.add(cb.qc_minus_qty, qc_minus_qty);
  197. }
  198. }
  199. for (const sc of this.stageChange) {
  200. const cp = this.changePos[sc.pid];
  201. if (cp) continue;
  202. const cb = this.changeBills[sc.lid];
  203. if (cb) this._calculateUsedQty(cb, sc);
  204. }
  205. for (const lid in this.changeBills) {
  206. const cb = this.changeBills[lid];
  207. if (!cb) continue;
  208. const precision = this.helper.findPrecision(this.precision, cb.bills.unit);
  209. const qc_qty = this.helper.round(cb.qty, precision.value);
  210. const qc_tp = this.helper.mul(cb.qty, cb.bills.unit_price, this.decimal.tp);
  211. const positive_qc_qty = this.helper.round(cb.positive_qc_qty || 0, precision.value);
  212. const positive_qc_tp = this.helper.mul(positive_qc_qty, cb.bills.unit_price, this.decimal.tp);
  213. const negative_qc_qty = this.helper.round(cb.negative_qc_qty || 0, precision.value);
  214. const negative_qc_tp = this.helper.mul(negative_qc_qty, cb.bills.unit_price, this.decimal.tp);
  215. const qc_minus_qty = this.helper.round(cb.qc_minus_qty || 0, precision.value);
  216. const sb = this.stageBills.find(x => {return x.lid === lid});
  217. if (sb) {
  218. const contract_tp = qc_minus_qty && this.info.calc_type === 'tp' && sb.contract_qty ? this.calcContractTp(cb.bills, sb.contract_qty, qc_minus_qty) : 0;
  219. 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, contract_tp });
  220. } else {
  221. this.insertBills.push({
  222. tid: this.default.tid, sid: this.default.sid, said: this.default.said,
  223. lid, qc_qty, qc_tp, positive_qc_qty, positive_qc_tp, negative_qc_qty, negative_qc_tp, qc_minus_qty, times: 1, order: 0
  224. });
  225. }
  226. }
  227. }
  228. use(source, validChangeBills, minusNoValue) {
  229. this.init(source);
  230. this.minusNoValue = minusNoValue;
  231. for (const bills of validChangeBills) {
  232. this.useBills(bills);
  233. }
  234. this.calculateAll();
  235. }
  236. }
  237. module.exports = app => {
  238. class StageChange extends app.BaseService {
  239. /**
  240. * 构造函数
  241. *
  242. * @param {Object} ctx - egg全局变量
  243. * @return {void}
  244. */
  245. constructor(ctx) {
  246. super(ctx);
  247. this.tableName = 'stage_change';
  248. }
  249. /**
  250. * 查询 调用的变更令 最新数据
  251. * @param {Number} tid - 标段id
  252. * @param {Number} sid - 期id
  253. * @param {Number} lid - 台账节点id
  254. * @param {Number} pid - 部位明细id
  255. * @return {Promise<*>}
  256. */
  257. async getLastestStageData(tid, sid, lid, pid, noValue) {
  258. const filter = noValue !== undefined ? ' And no_value = ?' : '';
  259. const sql = 'SELECT c.*,' +
  260. ' oc.p_code As c_code, oc.new_code As c_new_code' +
  261. ' FROM ' + this.tableName + ' As c ' +
  262. ' INNER JOIN ( ' +
  263. ' SELECT MAX(`stimes` * ' + timesLen + ' + `sorder`) As `progress`, `lid`, `pid`, `sid`, `cid`, `cbid`, `no_value` From ' + this.tableName +
  264. ' WHERE tid = ? And sid = ? And lid = ? And pid = ?' + filter +
  265. ' GROUP By `lid`, `pid`, `cbid`, `no_value`' +
  266. ' ) As m ' +
  267. ' 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`' +
  268. ' LEFT JOIN ' + this.ctx.service.change.tableName + ' As oc' +
  269. ' ON c.cid = oc.cid' +
  270. ' LEFT JOIN ' + this.ctx.service.changeAuditList.tableName + ' As ocb' +
  271. ' ON c.cbid = ocb.id' +
  272. ' WHERE not ISNULL(ocb.id)';
  273. const sqlParam = [tid, sid, lid, pid ? pid : -1];
  274. if (noValue !== undefined) sqlParam.push(noValue);
  275. return await this.db.query(sql, sqlParam);
  276. }
  277. /**
  278. * 查询 调用的变更令 某轮 某人的数据
  279. * @param {Number} tid - 标段id
  280. * @param {Number} sid - 期id
  281. * @param {Number} times - 第几轮
  282. * @param {Number} order - 第几人
  283. * @param {Number} lid - 台账节点id
  284. * @param {Number} pid - 部位明细id
  285. * @return {Promise<*>}
  286. */
  287. async getAuditorStageData(tid, sid, times, order, lid, pid, noValue) {
  288. const filter = noValue !== undefined ? ' And no_value = ?' : '';
  289. const sql = 'SELECT c.*,' +
  290. ' oc.p_code As c_code, oc.new_code As c_new_code, oc.quality, ocb.code as b_code, ocb.name, ocb.unit' +
  291. ' FROM ' + this.tableName + ' As c ' +
  292. ' INNER JOIN ( ' +
  293. ' SELECT MAX(`stimes` * ' + timesLen + ' + `sorder`) As `progress`, `lid`, `pid`, `sid`, `cid`, `cbid`, `no_value` From ' + this.tableName +
  294. ' WHERE tid = ? And sid = ? And (`stimes` < ? OR (`stimes` = ? AND `sorder` <= ?)) And lid = ? And pid = ?' + filter +
  295. ' GROUP By `lid`, `pid`, cbid, no_value' +
  296. ' ) As m ' +
  297. ' 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`' +
  298. ' LEFT JOIN ' + this.ctx.service.change.tableName + ' As oc' +
  299. ' ON c.cid = oc.cid' +
  300. ' LEFT JOIN ' + this.ctx.service.changeAuditList.tableName + ' As ocb' +
  301. ' ON c.cbid = ocb.id' +
  302. ' WHERE not ISNULL(ocb.id)';
  303. const sqlParam = [tid, sid, times, times, order, lid, pid ? pid : -1];
  304. if (noValue !== undefined) sqlParam.push(noValue);
  305. return await this.db.query(sql, sqlParam);
  306. }
  307. async getLastestAllStageData(tid, sid) {
  308. const sql = 'SELECT c.*,' +
  309. ' oc.p_code As c_code, oc.new_code As c_new_code, oc.quality, ocb.code as b_code, ocb.name, ocb.unit' +
  310. ' FROM ' + this.tableName + ' As c ' +
  311. ' INNER JOIN ( ' +
  312. ' SELECT MAX(`stimes` * ' + timesLen + ' + `sorder`) As `progress`, `lid`, `pid`, `sid`, `cid`, `cbid`, `no_value` From ' + this.tableName +
  313. ' WHERE tid = ? And sid = ?' +
  314. ' GROUP By `lid`, `pid`, cbid, no_value' +
  315. ' ) As m ' +
  316. ' 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`' +
  317. ' LEFT JOIN ' + this.ctx.service.change.tableName + ' As oc' +
  318. ' ON c.cid = oc.cid' +
  319. ' LEFT JOIN ' + this.ctx.service.changeAuditList.tableName + ' As ocb' +
  320. ' ON c.cbid = ocb.id' +
  321. ' WHERE not ISNULL(ocb.id)';
  322. const sqlParam = [tid, sid];
  323. return await this.db.query(sql, sqlParam);
  324. }
  325. async getAuditorAllStageData(tid, sid, times, order) {
  326. const sql = 'SELECT c.*, ' +
  327. ' oc.p_code As c_code, oc.new_code As c_new_code, oc.quality, ocb.code as b_code, ocb.name, ocb.unit' +
  328. ' FROM ' + this.tableName + ' As c ' +
  329. ' INNER JOIN ( ' +
  330. ' SELECT MAX(`stimes` * ' + timesLen + ' + `sorder`) As `progress`, `lid`, `pid`, `sid`, `cid`, `cbid`, `no_value` From ' + this.tableName +
  331. ' WHERE tid = ? And sid = ? And (`stimes` < ? OR (`stimes` = ? AND `sorder` <= ?))' +
  332. ' GROUP By `lid`, `pid`, cbid, no_value' +
  333. ' ) As m ' +
  334. ' 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`' +
  335. ' LEFT JOIN ' + this.ctx.service.change.tableName + ' As oc' +
  336. ' ON c.cid = oc.cid' +
  337. ' LEFT JOIN ' + this.ctx.service.changeAuditList.tableName + ' As ocb' +
  338. ' ON c.cbid = ocb.id' +
  339. ' WHERE not ISNULL(ocb.id)';
  340. const sqlParam = [tid, sid, times, times, order];
  341. return await this.db.query(sql, sqlParam);
  342. }
  343. /**
  344. * 台账,调用变更令
  345. *
  346. * @param {Object} bills - 台账节点数据
  347. * @param {Array} changes - 调用的变更令
  348. * @return {Promise<void>}
  349. */
  350. async billsChange(bills, noValue, changes) {
  351. const self = this;
  352. function getNewChange(cid, cbid, times, order, qty, minus, no_value) {
  353. return {
  354. tid: self.ctx.tender.id, sid: self.ctx.stage.id,
  355. lid: bills.id, pid: -1,
  356. cid, cbid,
  357. stimes: times, sorder: order,
  358. qty, minus, no_value,
  359. };
  360. }
  361. const ledgerBills = await this.ctx.service.ledger.getCompleteDataById(bills.id);
  362. if (!ledgerBills || ledgerBills.tender_id !== this.ctx.tender.id) {
  363. throw '提交数据错误';
  364. }
  365. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, ledgerBills.unit);
  366. // 获取原变更令
  367. const oldChanges = await this.getLastestStageData(this.ctx.tender.id, this.ctx.stage.id, bills.id, -1, noValue);
  368. // 获取更新数据
  369. const updateChanges = [],
  370. newChanges = [];
  371. let billsQty = 0, billsPositiveQty = 0, billsNegativeQty = 0;
  372. for (const oc of oldChanges) {
  373. const nc = this._.find(changes, { cid: oc.cid, cbid: oc.cbid });
  374. if (!nc || nc.qty !== oc.qty) {
  375. const qty = nc ? this.round(nc.qty, precision.value) : null;
  376. const change = getNewChange(oc.cid, oc.cbid, this.ctx.stage.curTimes, this.ctx.stage.curOrder, qty, nc ? nc.minus : oc.minus, noValue);
  377. change.unit_price = ledgerBills.unit_price;
  378. billsQty = this.ctx.helper.add(billsQty, change.qty);
  379. if (change.minus) {
  380. billsNegativeQty = this.ctx.helper.add(billsNegativeQty, change.qty);
  381. } else {
  382. billsPositiveQty = this.ctx.helper.add(billsPositiveQty, change.qty);
  383. }
  384. if (oc.stimes === this.ctx.stage.curTimes && oc.sorder === this.ctx.stage.curOrder) {
  385. change.id = oc.id;
  386. updateChanges.push(change);
  387. } else {
  388. newChanges.push(change);
  389. }
  390. } else {
  391. billsQty = this.ctx.helper.add(billsQty, oc.qty);
  392. if (oc.minus) {
  393. billsNegativeQty = this.ctx.helper.add(billsNegativeQty, oc.qty);
  394. } else {
  395. billsPositiveQty = this.ctx.helper.add(billsPositiveQty, oc.qty);
  396. }
  397. }
  398. }
  399. for (const c of changes) {
  400. const nc = this._.find(oldChanges, { cid: c.cid, cbid: c.cbid });
  401. if (!nc) {
  402. const change = getNewChange(c.cid, c.cbid, this.ctx.stage.curTimes, this.ctx.stage.curOrder, this.round(c.qty, precision.value), c.minus, noValue);
  403. change.unit_price = ledgerBills.unit_price;
  404. billsQty = this.ctx.helper.add(billsQty, change.qty);
  405. if (change.minus) {
  406. billsNegativeQty = this.ctx.helper.add(billsNegativeQty, change.qty);
  407. } else {
  408. billsPositiveQty = this.ctx.helper.add(billsPositiveQty, change.qty);
  409. }
  410. newChanges.push(change);
  411. }
  412. }
  413. // 更新数据
  414. const transaction = await this.db.beginTransaction();
  415. try {
  416. if (newChanges.length > 0) await transaction.insert(this.tableName, newChanges);
  417. if (updateChanges.length > 0) await transaction.updateRows(this.tableName, updateChanges);
  418. const stageBills = await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, bills.id);
  419. const sbUpdate = noValue
  420. ? { qc_minus_qty: billsQty }
  421. : { qc_qty: billsQty, positive_qc_qty: billsPositiveQty, negative_qc_qty: billsNegativeQty };
  422. await this.ctx.service.stageBills.updateStageBillsQty(transaction, ledgerBills, stageBills, sbUpdate);
  423. await transaction.commit();
  424. } catch (err) {
  425. await transaction.rollback();
  426. throw err;
  427. }
  428. const result = await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, [bills.id]);
  429. return { bills: { curStageData: result } };
  430. }
  431. /**
  432. * 部位明细,调用变更令
  433. *
  434. * @param {Object} pos - 部位明细数据
  435. * @param {Array} changes - 调用的变更令
  436. * @return {Promise<{}>}
  437. */
  438. async posChange(pos, noValue, changes) {
  439. const self = this;
  440. function getNewChange(cid, cbid, times, order, qty, minus, no_value) {
  441. return {
  442. tid: self.ctx.tender.id, sid: self.ctx.stage.id,
  443. lid: pos.lid, pid: pos.id,
  444. cid, cbid,
  445. stimes: times, sorder: order,
  446. qty, minus, no_value,
  447. };
  448. }
  449. const ledgerBills = await this.ctx.service.ledger.getCompleteDataById(pos.lid);
  450. if (!ledgerBills || ledgerBills.tender_id !== this.ctx.tender.id) {
  451. throw '提交数据错误';
  452. }
  453. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, ledgerBills.unit);
  454. // 获取原变更令
  455. const oldChanges = await this.getLastestStageData(this.ctx.tender.id, this.ctx.stage.id, pos.lid, pos.id, noValue);
  456. const updateChanges = [],
  457. newChanges = [];
  458. let posQty = 0, posPositiveQty = 0, posNegativeQty = 0;
  459. for (const oc of oldChanges) {
  460. const nc = this._.find(changes, { cid: oc.cid, cbid: oc.cbid });
  461. if (!nc || nc.qty !== oc.qty) {
  462. const qty = nc ? this.round(nc.qty, precision.value) : null;
  463. const change = getNewChange(oc.cid, oc.cbid, this.ctx.stage.curTimes, this.ctx.stage.curOrder, qty, nc ? nc.minus : oc.minus, noValue);
  464. change.unit_price = ledgerBills.unit_price;
  465. posQty = this.ctx.helper.add(posQty, change.qty);
  466. if (change.minus) {
  467. posNegativeQty = this.ctx.helper.add(posNegativeQty, change.qty);
  468. } else {
  469. posPositiveQty = this.ctx.helper.add(posPositiveQty, change.qty);
  470. }
  471. if (oc.stimes === this.ctx.stage.curTimes && oc.sorder === this.ctx.stage.curOrder) {
  472. change.id = oc.id;
  473. updateChanges.push(change);
  474. } else {
  475. newChanges.push(change);
  476. }
  477. } else {
  478. posQty = this.ctx.helper.add(posQty, oc.qty);
  479. if (oc.minus) {
  480. posNegativeQty = this.ctx.helper.add(posNegativeQty, oc.qty);
  481. } else {
  482. posPositiveQty = this.ctx.helper.add(posPositiveQty, oc.qty);
  483. }
  484. }
  485. }
  486. for (const c of changes) {
  487. const nc = this._.find(oldChanges, { cid: c.cid, cbid: c.cbid });
  488. if (!nc) {
  489. const change = getNewChange(c.cid, c.cbid, this.ctx.stage.curTimes, this.ctx.stage.curOrder, this.round(c.qty, precision.value), c.minus, noValue);
  490. change.unit_price = ledgerBills.unit_price;
  491. posQty = this.ctx.helper.add(posQty, change.qty);
  492. if (change.minus) {
  493. posNegativeQty = this.ctx.helper.add(posNegativeQty, change.qty);
  494. } else {
  495. posPositiveQty = this.ctx.helper.add(posPositiveQty, change.qty);
  496. }
  497. newChanges.push(change);
  498. }
  499. }
  500. // 更新数据
  501. const transaction = await this.db.beginTransaction();
  502. try {
  503. if (newChanges.length > 0) await transaction.insert(this.tableName, newChanges);
  504. if (updateChanges.length > 0) await transaction.updateRows(this.tableName, updateChanges);
  505. await this.ctx.service.stagePos.updateChangeQuantity(transaction, pos, posQty, noValue, posPositiveQty, posNegativeQty);
  506. await transaction.commit();
  507. } catch (err) {
  508. await transaction.rollback();
  509. throw err;
  510. }
  511. // 获取返回数据
  512. try {
  513. const data = { bills: {}, pos: {} };
  514. data.bills.curStageData = await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, [pos.lid]);
  515. data.pos.curStageData = await this.ctx.service.stagePos.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, { pid: pos.id });
  516. return data;
  517. } catch (err) {
  518. throw '获取数据错误,请刷新页面';
  519. }
  520. }
  521. /**
  522. * 获取 变更令 - 变更清单 使用情况
  523. * @param {Number} sid - 查询期id
  524. * @param {uuid} cid - 变更令id
  525. * @return {Promise<void>}
  526. */
  527. async getUsedData(tid, cid) {
  528. if (this.ctx.stage.status === audit.stage.status.checked) {
  529. const sql = 'SELECT scf.* ' +
  530. ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
  531. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
  532. ' WHERE scf.tid = ? And scf.cid = ? And s.order <= ?';
  533. const result = await this.db.query(sql, [tid, cid, this.ctx.stage.order]);
  534. return result;
  535. } else {
  536. const preSql = 'SELECT scf.* ' +
  537. ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
  538. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
  539. ' WHERE scf.tid = ? And scf.cid = ? And s.order < ?';
  540. const pre = await this.db.query(preSql, [tid, cid, this.ctx.stage.order]);
  541. const sql = 'SELECT * FROM ' + this.tableName + ' WHERE sid = ?';
  542. const curAll = await this.db.query(sql, [this.ctx.stage.id]);
  543. const cur = this.ctx.helper.filterLastestData(curAll, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  544. return [...pre, ...cur];
  545. }
  546. }
  547. async getFinalUsedData(tid, cid) {
  548. const stage = await this.ctx.service.stage.getFlowLatestStage(tid, true);
  549. if (!stage) { // 防止未创建期时调用
  550. return [];
  551. }
  552. if (stage.status === audit.stage.status.checked) {
  553. const sql = 'SELECT scf.* ' +
  554. ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
  555. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
  556. this.ctx.helper.whereSql({ tid, cid }, 'scf') + ' And s.order <= ?';
  557. const result = await this.db.query(sql, [stage.order]);
  558. return result;
  559. } else {
  560. const preSql = 'SELECT scf.* ' +
  561. ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
  562. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
  563. this.ctx.helper.whereSql({ tid, cid }, 'scf') + ' And s.order < ?';
  564. const pre = await this.db.query(preSql, [stage.order]);
  565. const sql = 'SELECT * FROM ' + this.tableName + this.ctx.helper.whereSql({ sid: stage.id, cid });
  566. const curAll = await this.db.query(sql);
  567. const cur = this.ctx.helper.filterLastestData(curAll, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  568. return [...pre, ...cur];
  569. }
  570. }
  571. async getAllFinalUsedData(tid, cid) {
  572. const result = [];
  573. const stages = await this.ctx.service.stage.getAllDataByCondition({ where: { tid: tid }, orders: [['order', 'desc']] });
  574. for (const stage of stages) {
  575. if (stage.status === audit.stage.status.checked) {
  576. const sql = `SELECT * FROM ${this.ctx.service.stageChangeFinal.tableName} WHERE tid = ? and cid = ? AND sorder <= ?`;
  577. const pre = await this.db.query(sql, [tid, cid, stage.order]);
  578. result.push(...pre);
  579. break;
  580. } else {
  581. const sql = 'SELECT * FROM ' + this.tableName + this.ctx.helper.whereSql({ sid: stage.id, cid });
  582. const curAll = await this.db.query(sql);
  583. const cur = this.ctx.helper.filterLastestData(curAll, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  584. result.push(...cur);
  585. }
  586. }
  587. return result;
  588. }
  589. /**
  590. * 获取 变更令 - 变更清单 当期使用情况
  591. * @param {Number} sid - 查询期id
  592. * @param {uuid} cid - 变更令id
  593. * @return {Promise<*>}
  594. */
  595. async getStageUsedData(sid, cid) {
  596. const data = await this.getAllDataByCondition({ where: { sid, cid } });
  597. const _ = this.ctx.helper._;
  598. const filter = this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  599. if (filter.length === 0) return filter;
  600. const bills = await this.ctx.service.ledger.getAllDataByCondition({
  601. where: { id: _.uniq(_.map(filter, 'lid')) }
  602. });
  603. const pos = await this.ctx.service.pos.getAllDataByCondition({
  604. where: { id: _.uniq(_.map(filter, 'pid')) }
  605. });
  606. return filter.map(x => {
  607. const b = bills.find(y => { return y.id === x.lid });
  608. const rela_b = b
  609. ? {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,
  610. 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}
  611. : { 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: '' };
  612. const p = pos.find(y => { return y.id === x.pid });
  613. 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 };
  614. return { ...x, ...rela_b, ...rela_p };
  615. });
  616. }
  617. /**
  618. * 获取 本期 使用的变更令
  619. * @param sid
  620. * @return {Promise<void>}
  621. */
  622. async getStageUsedChangeId(sid) {
  623. const sql = 'SELECT lid, pid, cid, cbid, qty, stimes, sorder, no_value FROM ' + this.tableName + ' WHERE sid = ?';
  624. const curAll = await this.db.query(sql, [sid]);
  625. const cur = this.ctx.helper.filterLastestData(curAll, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  626. return this._.map(this._.filter(cur, 'qty'), 'cid');
  627. }
  628. async getCurStageData(tid, sid, stimes, sorder) {
  629. const sql = `SELECT * From ${this.tableName} WHERE tid = ? AND sid = ? AND (stimes < ? OR (stimes = ? AND sorder < ?))`;
  630. const data = await this.db.query(sql, [tid, sid, stimes, stimes, sorder]);
  631. return this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  632. }
  633. async getFinalStageData(tid, sid) {
  634. const data = await this.getAllDataByCondition({ where: { tid, sid } });
  635. return this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  636. }
  637. async getSumLoadFinalData(sid) {
  638. 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' +
  639. ' FROM ' + this.tableName + ' cf' +
  640. ' Left Join ' + this.ctx.service.change.tableName + ' c ON cf.cid = c.cid' +
  641. ' Where cf.sid = ?';
  642. const result = await this.db.query(sql, [sid]);
  643. return this.ctx.helper.filterLastestData(result, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  644. }
  645. async _getTender(stage) {
  646. if (this.ctx.tender) return this.ctx.tender;
  647. const tender = { id: stage.tid };
  648. tender.data = await this.ctx.service.tender.getTender(stage.tid);
  649. tender.info = await this.service.tenderInfo.getTenderInfo(tender.id);
  650. return tender;
  651. }
  652. async getSubtotal(stage) {
  653. const helper = this.ctx.helper;
  654. const tender = await this._getTender(stage);
  655. const sql = 'SELECT sc.*, c.quality FROM ' + this.tableName + ' sc' +
  656. ' LEFT JOIN ' + this.ctx.service.change.tableName + ' c ON sc.cid = c.cid' +
  657. ' WHERE sid = ? ' + (stage.readOnly ? ` and (stimes < ${stage.curTimes} or (stimes = ${stage.curTimes} and sorder <= ${stage.curOrder}))` : '');
  658. let data = await this.db.query(sql, [stage.id]);
  659. data = helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  660. const bqData = [];
  661. for (const d of data) {
  662. if (!d.qty || d.no_value) continue;
  663. let bd = bqData.find(x => { return x.lid === d.lid && x.quality === d.quality; });
  664. if (!bd) {
  665. bd = { lid: d.lid, quality: d.quality, unit_price: d.unit_price };
  666. bqData.push(bd);
  667. }
  668. const tp = this.ctx.helper.mul(d.qty, bd.unit_price, tender.info.decimal.tp);
  669. bd.tp = this.ctx.helper.add(bd.tp, tp);
  670. }
  671. const result = {};
  672. result.common = helper.sum(helper._.map(bqData.filter(x => {return x.quality === changeConst.quality.common.value; }), 'tp'));
  673. result.more = helper.sum(helper._.map(bqData.filter(x => {return x.quality === changeConst.quality.more.value; }), 'tp'));
  674. result.great = helper.sum(helper._.map(bqData.filter(x => {return x.quality === changeConst.quality.great.value; }), 'tp'));
  675. return result;
  676. }
  677. async getChangeBillsWithUsedInfo(stage) {
  678. if (stage.status === audit.stage.status.checked) {
  679. const sql = 'SELECT scf.* ' +
  680. ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
  681. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
  682. ' WHERE scf.tid = ? And s.order <= ?';
  683. const result = await this.db.query(sql, [stage.tid, stage.order]);
  684. return result;
  685. } else {
  686. const preSql = 'SELECT scf.* ' +
  687. ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
  688. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
  689. ' WHERE scf.tid = ? And s.order < ?';
  690. const pre = await this.db.query(preSql, [stage.tid, stage.order]);
  691. const sql = 'SELECT * FROM ' + this.tableName + ' WHERE sid = ? AND (stimes * 100 + sorder) <= (? * 100 + ?)';
  692. const curAll = await this.db.query(sql, [stage.id, stage.curTimes, stage.curOrder]);
  693. const cur = this.ctx.helper.filterLastestData(curAll, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  694. return [...pre, ...cur];
  695. }
  696. }
  697. async getChangeWithUsedInfo(stage) {
  698. const change = await this.ctx.service.change.getAllDataByCondition({
  699. where: { tid: stage.tid, status: audit.flow.status.checked },
  700. orders: [['code', 'asc']],
  701. });
  702. if (change.length === 0) return [];
  703. const changeBills = await this.ctx.service.changeAuditList.getAllDataByCondition({
  704. where: { cid: change.map(x => { return x.cid; }) }
  705. });
  706. const changeBillsIndex = {}, changeBillsPart = {};
  707. for (const cb of changeBills) {
  708. changeBillsIndex[cb.id] = cb;
  709. if (!changeBillsPart[cb.cid]) changeBillsPart[cb.cid] = [];
  710. changeBillsPart[cb.cid].push(cb);
  711. }
  712. const stageChangeBills = await this.getChangeBillsWithUsedInfo(stage);
  713. for (const scb of stageChangeBills) {
  714. if (!scb.qty) continue;
  715. const cb = changeBillsIndex[scb.cbid];
  716. if (cb) cb.used_qty = this.ctx.helper.add(cb.used_qty, scb.qty);
  717. }
  718. for (const cid in changeBillsPart) {
  719. const c = change.find(x => { return x.cid === cid });
  720. if (!c) continue;
  721. const sumBills = [];
  722. for (const cb of changeBillsPart[cid]) {
  723. let sb;
  724. if (cb.gcl_id) {
  725. sb = sumBills.find(x => { return x.gcl_id === cb.gcl_id; });
  726. }
  727. if (!cb.gcl_id || !sb) {
  728. sb = { gcl_id: cb.gcl_id, unit_price: cb.unit_price, used_qty: 0, p_used_qty: 0, n_used_qty: 0 };
  729. sumBills.push(sb);
  730. }
  731. sb.used_qty = this.ctx.helper.add(sb.used_qty, cb.used_qty);
  732. if (cb.spamount > 0) {
  733. sb.p_used_qty = this.ctx.helper.add(sb.p_used_qty, cb.used_qty);
  734. } else {
  735. sb.n_used_qty = this.ctx.helper.add(sb.n_used_qty, cb.used_qty);
  736. }
  737. cb.tp = this.ctx.helper.mul(cb.spamount, cb.unit_price, c.tp_decimal || this.ctx.tender.info.decimal.tp);
  738. cb.used_tp = this.ctx.helper.mul(cb.used_qty, cb.unit_price, this.ctx.tender.info.decimal.tp);
  739. }
  740. for (const sb of sumBills) {
  741. sb.used_tp = this.ctx.helper.mul(sb.used_qty, sb.unit_price, this.ctx.tender.info.decimal.tp);
  742. sb.p_used_tp = this.ctx.helper.mul(sb.p_used_qty, sb.unit_price, this.ctx.tender.info.decimal.tp);
  743. sb.n_used_tp = this.ctx.helper.mul(sb.n_used_qty, sb.unit_price, this.ctx.tender.info.decimal.tp);
  744. c.used_tp = this.ctx.helper.add(c.used_tp, sb.used_tp);
  745. c.p_used_tp = this.ctx.helper.add(c.p_used_tp, sb.p_used_tp);
  746. c.n_used_tp = this.ctx.helper.add(c.n_used_tp, sb.n_used_tp);
  747. }
  748. c.p_tp = c.positive_tp;
  749. c.n_tp = c.negative_tp;
  750. c.used_pt = c.total_price ? this.ctx.helper.mul(this.ctx.helper.div(c.used_tp, c.total_price, 4), 100) : 0;
  751. c.p_used_pt = c.positive_tp ? this.ctx.helper.mul(this.ctx.helper.div(c.p_used_tp, c.positive_tp, 4), 100) : 0;
  752. c.n_used_pt = c.negative_tp ? this.ctx.helper.mul(this.ctx.helper.div(c.n_used_tp, c.negative_tp, 4), 100) : 0;
  753. }
  754. return change;
  755. }
  756. async getStageMinusChange(stage) {
  757. const data = await this.getAllDataByCondition({ where: { sid: stage.id, minus: 1 } });
  758. return this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  759. };
  760. async getBillsMinusQty(stage, lid) {
  761. const data = await this.getAllDataByCondition({ where: { sid: stage.id, lid, minus: 1 } });
  762. const filter = this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  763. return { lid, qty: this.ctx.helper.sum(filter.map(x => { return x.qty; })) };
  764. };
  765. async getPosMinusQty(stage, pid) {
  766. const data = await this.getAllDataByCondition({ where: { sid: stage.id, pid, minus: 1 } });
  767. const filter = this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  768. return { pid, qty: this.ctx.helper.sum(filter.map(x => { return x.qty; })) };
  769. };
  770. async autoUseChangeBills(tender, stage, data) {
  771. const lid = [], cbid = [];
  772. data.forEach(x => {
  773. lid.push(x.lid);
  774. cbid.push(x.cbid);
  775. });
  776. const validChangeBills = await this.ctx.service.stageChangeFinal.getListChangeBillsValidQty(tender.id, cbid);
  777. validChangeBills.forEach(x => {
  778. x.billsPos = data.find(y => { return x.id === y.cbid; });
  779. });
  780. const ledgerData = await this.ctx.service.ledger.getAllDataByCondition({
  781. columns: ['id', 'ledger_id', 'ledger_pid', 'level', 'order', 'full_path', 'is_leaf', 'code', 'b_code', 'name', 'unit', 'unit_price', 'quantity', 'total_price'],
  782. where: { id: lid },
  783. });
  784. const extraData = await this.ctx.service.ledgerExtra.getData(this.ctx.tender.id, ['is_tp']);
  785. this.ctx.helper.assignRelaData(ledgerData, [
  786. { data: extraData, fields: ['is_tp'], prefix: '', relaId: 'id' },
  787. ]);
  788. const posData = await this.ctx.service.pos.getAllDataByCondition({
  789. columns: ['id', 'lid', 'name', 'porder'],
  790. where: { lid },
  791. });
  792. const stageBills = await this.ctx.service.stageBills.getAllDataByCondition({ where: { sid: stage.id } });
  793. const stagePos = await this.ctx.service.stagePos.getAllDataByCondition({ where: { sid: stage.id } });
  794. const stageChange = await this.ctx.service.stageChange.getAllDataByCondition({ where: { sid: stage.id, lid }});
  795. const preStageBills = stage.preCheckedStage ? await this.ctx.service.stageBillsFinal.getFinalData(stage.tid, stage.preCheckedStage.order) : [];
  796. const useModal = new autoUseChange(this.ctx.helper, tender.info);
  797. const projectFunInfo = this.ctx.subProject.fun_rela;
  798. const minusNoValue = projectFunInfo.minusNoValue && tender.info.fun_rela.stage_change.minusNoValue;
  799. useModal.use({ledgerData, posData, stageBills, stagePos, stageChange, preStageBills, default: { tid: stage.tid, sid: stage.id, said: this.ctx.session.sessionUser.accountId } }, validChangeBills, minusNoValue);
  800. const conn = await this.db.beginTransaction();
  801. try {
  802. if (useModal.insertBills.length > 0) await conn.insert(this.ctx.service.stageBills.tableName, useModal.insertBills);
  803. if (useModal.updateBills.length > 0) await conn.updateRows(this.ctx.service.stageBills.tableName, useModal.updateBills);
  804. if (useModal.insertPos.length > 0) await conn.insert(this.ctx.service.stagePos.tableName, useModal.insertPos);
  805. if (useModal.updatePos.length > 0) await conn.updateRows(this.ctx.service.stagePos.tableName, useModal.updatePos);
  806. if (useModal.insertChange.length > 0) await conn.insert(this.tableName, useModal.insertChange);
  807. if (useModal.updateChange.length > 0) await conn.updateRows(this.tableName, useModal.updateChange);
  808. await conn.commit();
  809. } catch (err) {
  810. await conn.rollback();
  811. this.ctx.log(err);
  812. throw '保存导入数据失败';
  813. }
  814. const rst = { bills: {}, pos: {} };
  815. rst.bills.curStageData = await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, lid);
  816. rst.pos.curStageData = await this.ctx.service.stagePos.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, { lid });
  817. return rst;
  818. };
  819. async autoUseAllChange(tender, stage) {
  820. const validChangeBills = await this.ctx.service.stageChangeFinal.getAllChangeBillsValidQty(tender.id);
  821. const ledgerData = await this.ctx.service.ledger.getAllDataByCondition({
  822. columns: ['id', 'ledger_id', 'ledger_pid', 'level', 'order', 'full_path', 'is_leaf', 'code', 'b_code', 'name', 'unit', 'unit_price', 'quantity', 'total_price'],
  823. where: { tender_id: stage.tid },
  824. });
  825. const extraData = await this.ctx.service.ledgerExtra.getData(this.ctx.tender.id, ['is_tp']);
  826. const settleStatusBills = stage.readySettle ? await this.ctx.service.settleBills.getAllDataByCondition({ where: { settle_id: stage.readySettle.id }}) : [];
  827. this.ctx.helper.assignRelaData(ledgerData, [
  828. { data: extraData, fields: ['is_tp'], prefix: '', relaId: 'id' },
  829. { data: settleStatusBills, fields: ['settle_status'], prefix: '', relaId: 'lid' },
  830. ]);
  831. const posData = await this.ctx.service.pos.getAllDataByCondition({
  832. columns: ['id', 'lid', 'name', 'porder'],
  833. where: { tid: stage.tid },
  834. });
  835. const settleStatusPos = stage.readySettle ? await this.ctx.service.settlePos.getAllDataByCondition({ where: { settle_id: stage.readySettle.id }}) : [];
  836. this.ctx.helper.assignRelaData(posData, [
  837. { data: settleStatusPos, fields: ['settle_status'], prefix: '', relaId: 'pid' },
  838. ]);
  839. const stageBills = await this.ctx.service.stageBills.getAllDataByCondition({ where: { sid: stage.id } });
  840. const stagePos = await this.ctx.service.stagePos.getAllDataByCondition({ where: { sid: stage.id } });
  841. const preStageBills = stage.preCheckedStage ? await this.ctx.service.stageBillsFinal.getFinalData(stage.tid, stage.preCheckedStage.order) : [];
  842. const useModal = new autoUseChange(this.ctx.helper, tender.info, this.ctx.service.settle.settleStatus);
  843. const projectFunInfo = this.ctx.subProject.fun_rela;
  844. const minusNoValue = projectFunInfo.minusNoValue && tender.info.fun_rela.stage_change.minusNoValue;
  845. useModal.use({ledgerData, posData, stageBills, stagePos, preStageBills, default: { tid: stage.tid, sid: stage.id, said: this.ctx.session.sessionUser.accountId } }, validChangeBills, minusNoValue);
  846. // if (useModal.insertChange.length === 0) return '无可调用的清单或计量单元';
  847. const conn = await this.db.beginTransaction();
  848. try {
  849. if (useModal.insertBills.length > 0) await conn.insert(this.ctx.service.stageBills.tableName, useModal.insertBills);
  850. if (useModal.updateBills.length > 0) await conn.updateRows(this.ctx.service.stageBills.tableName, useModal.updateBills);
  851. if (useModal.insertPos.length > 0) await conn.insert(this.ctx.service.stagePos.tableName, useModal.insertPos);
  852. if (useModal.updatePos.length > 0) await conn.updateRows(this.ctx.service.stagePos.tableName, useModal.updatePos);
  853. await conn.delete(this.tableName, { sid: stage.id });
  854. if (useModal.insertChange.length > 0) await conn.insert(this.tableName, useModal.insertChange);
  855. await conn.commit();
  856. } catch (err) {
  857. await conn.rollback();
  858. this.ctx.log(err);
  859. throw '保存导入数据失败';
  860. }
  861. }
  862. async updateStageChange4CheckCancel(sid, newTimes, newOrder, oldTimes, oldOrder, transaction) {
  863. const oldSBLists = await this.getAllDataByCondition({ where: { sid, stimes: oldTimes, sorder: oldOrder } });
  864. const newSBLists = await this.getAllDataByCondition({ where: { sid, stimes: newTimes, sorder: newOrder } });
  865. const delidList = [];
  866. for (const o of oldSBLists) {
  867. const newSBInfo = this._.find(newSBLists, { lid: o.lid });
  868. if (newSBInfo) {
  869. // 删除
  870. delidList.push(newSBInfo.id);
  871. }
  872. }
  873. if (delidList.length > 0) await transaction.delete(this.tableName, { id: delidList });
  874. if (oldSBLists.length > 0) {
  875. await transaction.update(this.tableName, {
  876. stimes: newTimes,
  877. sorder: newOrder,
  878. }, { where: { id: this._.map(oldSBLists, 'id') } });
  879. }
  880. }
  881. }
  882. return StageChange;
  883. };