stage_change.js 47 KB

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