stage_change.js 51 KB

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