stage_change.js 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  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 ? this.calcContractTp(this.info, cb.bills, sb.contract_qty || 0, qc_minus_qty) : sb.contract_tp;
  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. const contract_tp = qc_minus_qty ? this.calcContractTp(this.info, cb.bills, 0, qc_minus_qty) : 0;
  239. this.insertBills.push({
  240. tid: this.default.tid, sid: this.default.sid, said: this.default.said,
  241. lid, contract_tp, qc_qty, qc_tp, positive_qc_qty, positive_qc_tp, negative_qc_qty, negative_qc_tp, qc_minus_qty, times: 1, order: 0
  242. });
  243. }
  244. }
  245. }
  246. use(source, validChangeBills, minusNoValue) {
  247. this.init(source);
  248. this.minusNoValue = minusNoValue;
  249. for (const bills of validChangeBills) {
  250. this.useBills(bills);
  251. }
  252. this.calculateAll();
  253. }
  254. }
  255. module.exports = app => {
  256. class StageChange extends app.BaseService {
  257. /**
  258. * 构造函数
  259. *
  260. * @param {Object} ctx - egg全局变量
  261. * @return {void}
  262. */
  263. constructor(ctx) {
  264. super(ctx);
  265. this.tableName = 'stage_change';
  266. }
  267. /**
  268. * 查询 调用的变更令 最新数据
  269. * @param {Number} tid - 标段id
  270. * @param {Number} sid - 期id
  271. * @param {Number} lid - 台账节点id
  272. * @param {Number} pid - 部位明细id
  273. * @return {Promise<*>}
  274. */
  275. async getLastestStageData(tid, sid, lid, pid, noValue) {
  276. const filter = noValue !== undefined ? ' And no_value = ?' : '';
  277. const sql = 'SELECT c.*,' +
  278. ' oc.p_code As c_code, oc.new_code As c_new_code' +
  279. ' FROM ' + this.tableName + ' As c ' +
  280. ' INNER JOIN ( ' +
  281. ' SELECT MAX(`stimes` * ' + timesLen + ' + `sorder`) As `progress`, `lid`, `pid`, `sid`, `cid`, `cbid`, `no_value` From ' + this.tableName +
  282. ' WHERE tid = ? And sid = ? And lid = ? And pid = ?' + filter +
  283. ' GROUP By `lid`, `pid`, `cbid`, `no_value`' +
  284. ' ) As m ' +
  285. ' 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`' +
  286. ' LEFT JOIN ' + this.ctx.service.change.tableName + ' As oc' +
  287. ' ON c.cid = oc.cid' +
  288. ' LEFT JOIN ' + this.ctx.service.changeAuditList.tableName + ' As ocb' +
  289. ' ON c.cbid = ocb.id' +
  290. ' WHERE not ISNULL(ocb.id)';
  291. const sqlParam = [tid, sid, lid, pid ? pid : -1];
  292. if (noValue !== undefined) sqlParam.push(noValue);
  293. return await this.db.query(sql, sqlParam);
  294. }
  295. /**
  296. * 查询 调用的变更令 某轮 某人的数据
  297. * @param {Number} tid - 标段id
  298. * @param {Number} sid - 期id
  299. * @param {Number} times - 第几轮
  300. * @param {Number} order - 第几人
  301. * @param {Number} lid - 台账节点id
  302. * @param {Number} pid - 部位明细id
  303. * @return {Promise<*>}
  304. */
  305. async getAuditorStageData(tid, sid, times, order, lid, pid, noValue) {
  306. const filter = noValue !== undefined ? ' And no_value = ?' : '';
  307. const sql = 'SELECT c.*,' +
  308. ' oc.p_code As c_code, oc.new_code As c_new_code, oc.quality, ocb.code as b_code, ocb.name, ocb.unit' +
  309. ' FROM ' + this.tableName + ' As c ' +
  310. ' INNER JOIN ( ' +
  311. ' SELECT MAX(`stimes` * ' + timesLen + ' + `sorder`) As `progress`, `lid`, `pid`, `sid`, `cid`, `cbid`, `no_value` From ' + this.tableName +
  312. ' WHERE tid = ? And sid = ? And (`stimes` < ? OR (`stimes` = ? AND `sorder` <= ?)) And lid = ? And pid = ?' + filter +
  313. ' GROUP By `lid`, `pid`, cbid, no_value' +
  314. ' ) As m ' +
  315. ' 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`' +
  316. ' LEFT JOIN ' + this.ctx.service.change.tableName + ' As oc' +
  317. ' ON c.cid = oc.cid' +
  318. ' LEFT JOIN ' + this.ctx.service.changeAuditList.tableName + ' As ocb' +
  319. ' ON c.cbid = ocb.id' +
  320. ' WHERE not ISNULL(ocb.id)';
  321. const sqlParam = [tid, sid, times, times, order, lid, pid ? pid : -1];
  322. if (noValue !== undefined) sqlParam.push(noValue);
  323. return await this.db.query(sql, sqlParam);
  324. }
  325. async getLastestAllStageData(tid, sid) {
  326. const sql = 'SELECT c.*,' +
  327. ' oc.p_code As c_code, oc.new_code As c_new_code, oc.quality, ocb.code as b_code, ocb.name, ocb.unit' +
  328. ' FROM ' + this.tableName + ' As c ' +
  329. ' INNER JOIN ( ' +
  330. ' SELECT MAX(`stimes` * ' + timesLen + ' + `sorder`) As `progress`, `lid`, `pid`, `sid`, `cid`, `cbid`, `no_value` From ' + this.tableName +
  331. ' WHERE tid = ? And sid = ?' +
  332. ' GROUP By `lid`, `pid`, cbid, no_value' +
  333. ' ) As m ' +
  334. ' ON (c.stimes * ' + timesLen + ' + c.sorder) = m.progress And c.lid = m.lid And c.pid = m.pid And c.`sid` = m.`sid` And c.`cbid` = m.`cbid` And c.`no_value` = m.`no_value`' +
  335. ' LEFT JOIN ' + this.ctx.service.change.tableName + ' As oc' +
  336. ' ON c.cid = oc.cid' +
  337. ' LEFT JOIN ' + this.ctx.service.changeAuditList.tableName + ' As ocb' +
  338. ' ON c.cbid = ocb.id' +
  339. ' WHERE not ISNULL(ocb.id)';
  340. const sqlParam = [tid, sid];
  341. return await this.db.query(sql, sqlParam);
  342. }
  343. async getAuditorAllStageData(tid, sid, times, order) {
  344. const sql = 'SELECT c.*, ' +
  345. ' oc.p_code As c_code, oc.new_code As c_new_code, oc.quality, ocb.code as b_code, ocb.name, ocb.unit' +
  346. ' FROM ' + this.tableName + ' As c ' +
  347. ' INNER JOIN ( ' +
  348. ' SELECT MAX(`stimes` * ' + timesLen + ' + `sorder`) As `progress`, `lid`, `pid`, `sid`, `cid`, `cbid`, `no_value` From ' + this.tableName +
  349. ' WHERE tid = ? And sid = ? And (`stimes` < ? OR (`stimes` = ? AND `sorder` <= ?))' +
  350. ' GROUP By `lid`, `pid`, cbid, no_value' +
  351. ' ) As m ' +
  352. ' 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`' +
  353. ' LEFT JOIN ' + this.ctx.service.change.tableName + ' As oc' +
  354. ' ON c.cid = oc.cid' +
  355. ' LEFT JOIN ' + this.ctx.service.changeAuditList.tableName + ' As ocb' +
  356. ' ON c.cbid = ocb.id' +
  357. ' WHERE not ISNULL(ocb.id)';
  358. const sqlParam = [tid, sid, times, times, order];
  359. return await this.db.query(sql, sqlParam);
  360. }
  361. /**
  362. * 台账,调用变更令
  363. *
  364. * @param {Object} bills - 台账节点数据
  365. * @param {Array} changes - 调用的变更令
  366. * @return {Promise<void>}
  367. */
  368. async billsChange(bills, noValue, changes) {
  369. const self = this;
  370. function getNewChange(cid, cbid, times, order, qty, minus, no_value) {
  371. return {
  372. tid: self.ctx.tender.id, sid: self.ctx.stage.id,
  373. lid: bills.id, pid: -1,
  374. cid, cbid,
  375. stimes: times, sorder: order,
  376. qty, minus, no_value,
  377. };
  378. }
  379. const ledgerBills = await this.ctx.service.ledger.getCompleteDataById(bills.id);
  380. if (!ledgerBills || ledgerBills.tender_id !== this.ctx.tender.id) {
  381. throw '提交数据错误';
  382. }
  383. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, ledgerBills.unit);
  384. // 获取原变更令
  385. const oldChanges = await this.getLastestStageData(this.ctx.tender.id, this.ctx.stage.id, bills.id, -1, noValue);
  386. // 获取更新数据
  387. const updateChanges = [],
  388. newChanges = [];
  389. let billsQty = 0, billsPositiveQty = 0, billsNegativeQty = 0;
  390. for (const oc of oldChanges) {
  391. const nc = this._.find(changes, { cid: oc.cid, cbid: oc.cbid });
  392. if (!nc || nc.qty !== oc.qty) {
  393. const qty = nc ? this.round(nc.qty, precision.value) : null;
  394. const change = getNewChange(oc.cid, oc.cbid, this.ctx.stage.curTimes, this.ctx.stage.curOrder, qty, nc ? nc.minus : oc.minus, noValue);
  395. change.unit_price = ledgerBills.unit_price;
  396. billsQty = this.ctx.helper.add(billsQty, change.qty);
  397. if (change.minus) {
  398. billsNegativeQty = this.ctx.helper.add(billsNegativeQty, change.qty);
  399. } else {
  400. billsPositiveQty = this.ctx.helper.add(billsPositiveQty, change.qty);
  401. }
  402. if (oc.stimes === this.ctx.stage.curTimes && oc.sorder === this.ctx.stage.curOrder) {
  403. change.id = oc.id;
  404. updateChanges.push(change);
  405. } else {
  406. newChanges.push(change);
  407. }
  408. } else {
  409. billsQty = this.ctx.helper.add(billsQty, oc.qty);
  410. if (oc.minus) {
  411. billsNegativeQty = this.ctx.helper.add(billsNegativeQty, oc.qty);
  412. } else {
  413. billsPositiveQty = this.ctx.helper.add(billsPositiveQty, oc.qty);
  414. }
  415. }
  416. }
  417. for (const c of changes) {
  418. const nc = this._.find(oldChanges, { cid: c.cid, cbid: c.cbid });
  419. if (!nc) {
  420. const change = getNewChange(c.cid, c.cbid, this.ctx.stage.curTimes, this.ctx.stage.curOrder, this.round(c.qty, precision.value), c.minus, noValue);
  421. change.unit_price = ledgerBills.unit_price;
  422. billsQty = this.ctx.helper.add(billsQty, change.qty);
  423. if (change.minus) {
  424. billsNegativeQty = this.ctx.helper.add(billsNegativeQty, change.qty);
  425. } else {
  426. billsPositiveQty = this.ctx.helper.add(billsPositiveQty, change.qty);
  427. }
  428. newChanges.push(change);
  429. }
  430. }
  431. // 更新数据
  432. const transaction = await this.db.beginTransaction();
  433. try {
  434. if (newChanges.length > 0) await transaction.insert(this.tableName, newChanges);
  435. if (updateChanges.length > 0) await transaction.updateRows(this.tableName, updateChanges);
  436. const stageBills = await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, bills.id);
  437. const sbUpdate = noValue
  438. ? { qc_minus_qty: billsQty }
  439. : { qc_qty: billsQty, positive_qc_qty: billsPositiveQty, negative_qc_qty: billsNegativeQty };
  440. await this.ctx.service.stageBills.updateStageBillsQty(transaction, ledgerBills, stageBills, sbUpdate);
  441. await transaction.commit();
  442. } catch (err) {
  443. await transaction.rollback();
  444. throw err;
  445. }
  446. const result = await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, [bills.id]);
  447. return { bills: { curStageData: result } };
  448. }
  449. /**
  450. * 部位明细,调用变更令
  451. *
  452. * @param {Object} pos - 部位明细数据
  453. * @param {Array} changes - 调用的变更令
  454. * @return {Promise<{}>}
  455. */
  456. async posChange(pos, noValue, changes) {
  457. const self = this;
  458. function getNewChange(cid, cbid, times, order, qty, minus, no_value) {
  459. return {
  460. tid: self.ctx.tender.id, sid: self.ctx.stage.id,
  461. lid: pos.lid, pid: pos.id,
  462. cid, cbid,
  463. stimes: times, sorder: order,
  464. qty, minus, no_value,
  465. };
  466. }
  467. const ledgerBills = await this.ctx.service.ledger.getCompleteDataById(pos.lid);
  468. if (!ledgerBills || ledgerBills.tender_id !== this.ctx.tender.id) {
  469. throw '提交数据错误';
  470. }
  471. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, ledgerBills.unit);
  472. // 获取原变更令
  473. const oldChanges = await this.getLastestStageData(this.ctx.tender.id, this.ctx.stage.id, pos.lid, pos.id, noValue);
  474. const updateChanges = [],
  475. newChanges = [];
  476. let posQty = 0, posPositiveQty = 0, posNegativeQty = 0;
  477. for (const oc of oldChanges) {
  478. const nc = this._.find(changes, { cid: oc.cid, cbid: oc.cbid });
  479. if (!nc || nc.qty !== oc.qty) {
  480. const qty = nc ? this.round(nc.qty, precision.value) : null;
  481. const change = getNewChange(oc.cid, oc.cbid, this.ctx.stage.curTimes, this.ctx.stage.curOrder, qty, nc ? nc.minus : oc.minus, noValue);
  482. change.unit_price = ledgerBills.unit_price;
  483. posQty = this.ctx.helper.add(posQty, change.qty);
  484. if (change.minus) {
  485. posNegativeQty = this.ctx.helper.add(posNegativeQty, change.qty);
  486. } else {
  487. posPositiveQty = this.ctx.helper.add(posPositiveQty, change.qty);
  488. }
  489. if (oc.stimes === this.ctx.stage.curTimes && oc.sorder === this.ctx.stage.curOrder) {
  490. change.id = oc.id;
  491. updateChanges.push(change);
  492. } else {
  493. newChanges.push(change);
  494. }
  495. } else {
  496. posQty = this.ctx.helper.add(posQty, oc.qty);
  497. if (oc.minus) {
  498. posNegativeQty = this.ctx.helper.add(posNegativeQty, oc.qty);
  499. } else {
  500. posPositiveQty = this.ctx.helper.add(posPositiveQty, oc.qty);
  501. }
  502. }
  503. }
  504. for (const c of changes) {
  505. const nc = this._.find(oldChanges, { cid: c.cid, cbid: c.cbid });
  506. if (!nc) {
  507. const change = getNewChange(c.cid, c.cbid, this.ctx.stage.curTimes, this.ctx.stage.curOrder, this.round(c.qty, precision.value), c.minus, noValue);
  508. change.unit_price = ledgerBills.unit_price;
  509. posQty = this.ctx.helper.add(posQty, change.qty);
  510. if (change.minus) {
  511. posNegativeQty = this.ctx.helper.add(posNegativeQty, change.qty);
  512. } else {
  513. posPositiveQty = this.ctx.helper.add(posPositiveQty, change.qty);
  514. }
  515. newChanges.push(change);
  516. }
  517. }
  518. // 更新数据
  519. const transaction = await this.db.beginTransaction();
  520. try {
  521. if (newChanges.length > 0) await transaction.insert(this.tableName, newChanges);
  522. if (updateChanges.length > 0) await transaction.updateRows(this.tableName, updateChanges);
  523. await this.ctx.service.stagePos.updateChangeQuantity(transaction, pos, posQty, noValue, posPositiveQty, posNegativeQty);
  524. await transaction.commit();
  525. } catch (err) {
  526. await transaction.rollback();
  527. throw err;
  528. }
  529. // 获取返回数据
  530. try {
  531. const data = { bills: {}, pos: {} };
  532. data.bills.curStageData = await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, [pos.lid]);
  533. data.pos.curStageData = await this.ctx.service.stagePos.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, { pid: pos.id });
  534. return data;
  535. } catch (err) {
  536. throw '获取数据错误,请刷新页面';
  537. }
  538. }
  539. /**
  540. * 获取 变更令 - 变更清单 使用情况
  541. * @param {Number} sid - 查询期id
  542. * @param {uuid} cid - 变更令id
  543. * @return {Promise<void>}
  544. */
  545. async getUsedData(tid, cid) {
  546. if (this.ctx.stage.status === audit.stage.status.checked) {
  547. const sql = 'SELECT scf.* ' +
  548. ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
  549. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
  550. ' WHERE scf.tid = ? And scf.cid = ? And s.order <= ?';
  551. const result = await this.db.query(sql, [tid, cid, this.ctx.stage.order]);
  552. return result;
  553. } else {
  554. const preSql = 'SELECT scf.* ' +
  555. ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
  556. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
  557. ' WHERE scf.tid = ? And scf.cid = ? And s.order < ?';
  558. const pre = await this.db.query(preSql, [tid, cid, this.ctx.stage.order]);
  559. const sql = 'SELECT * FROM ' + this.tableName + ' WHERE sid = ?';
  560. const curAll = await this.db.query(sql, [this.ctx.stage.id]);
  561. const cur = this.ctx.helper.filterLastestData(curAll, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  562. return [...pre, ...cur];
  563. }
  564. }
  565. async getFinalUsedData(tid, cid) {
  566. const stage = await this.ctx.service.stage.getFlowLatestStage(tid, true);
  567. if (!stage) { // 防止未创建期时调用
  568. return [];
  569. }
  570. if (stage.status === audit.stage.status.checked) {
  571. const sql = 'SELECT scf.* ' +
  572. ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
  573. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
  574. this.ctx.helper.whereSql({ tid, cid }, 'scf') + ' And s.order <= ?';
  575. const result = await this.db.query(sql, [stage.order]);
  576. return result;
  577. } else {
  578. const preSql = 'SELECT scf.* ' +
  579. ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
  580. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
  581. this.ctx.helper.whereSql({ tid, cid }, 'scf') + ' And s.order < ?';
  582. const pre = await this.db.query(preSql, [stage.order]);
  583. const sql = 'SELECT * FROM ' + this.tableName + this.ctx.helper.whereSql({ sid: stage.id, cid });
  584. const curAll = await this.db.query(sql);
  585. const cur = this.ctx.helper.filterLastestData(curAll, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  586. return [...pre, ...cur];
  587. }
  588. }
  589. async getAllFinalUsedData(tid, cid) {
  590. const result = [];
  591. const stages = await this.ctx.service.stage.getAllDataByCondition({ where: { tid: tid }, orders: [['order', 'desc']] });
  592. for (const stage of stages) {
  593. if (stage.status === audit.stage.status.checked) {
  594. const sql = `SELECT * FROM ${this.ctx.service.stageChangeFinal.tableName} WHERE tid = ? and cid = ? AND sorder <= ?`;
  595. const pre = await this.db.query(sql, [tid, cid, stage.order]);
  596. result.push(...pre);
  597. break;
  598. } else {
  599. const sql = 'SELECT * FROM ' + this.tableName + this.ctx.helper.whereSql({ sid: stage.id, cid });
  600. const curAll = await this.db.query(sql);
  601. const cur = this.ctx.helper.filterLastestData(curAll, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  602. result.push(...cur);
  603. }
  604. }
  605. return result;
  606. }
  607. /**
  608. * 获取 变更令 - 变更清单 当期使用情况
  609. * @param {Number} sid - 查询期id
  610. * @param {uuid} cid - 变更令id
  611. * @return {Promise<*>}
  612. */
  613. async getStageUsedData(sid, cid) {
  614. const data = await this.getAllDataByCondition({ where: { sid, cid } });
  615. const _ = this.ctx.helper._;
  616. const filter = this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  617. if (filter.length === 0) return filter;
  618. const bills = await this.ctx.service.ledger.getAllDataByCondition({
  619. where: { id: _.uniq(_.map(filter, 'lid')) }
  620. });
  621. const pos = await this.ctx.service.pos.getAllDataByCondition({
  622. where: { id: _.uniq(_.map(filter, 'pid')) }
  623. });
  624. return filter.map(x => {
  625. const b = bills.find(y => { return y.id === x.lid });
  626. const rela_b = b
  627. ? {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,
  628. 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}
  629. : { 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: '' };
  630. const p = pos.find(y => { return y.id === x.pid });
  631. 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 };
  632. return { ...x, ...rela_b, ...rela_p };
  633. });
  634. }
  635. /**
  636. * 获取 本期 使用的变更令
  637. * @param sid
  638. * @return {Promise<void>}
  639. */
  640. async getStageUsedChangeId(sid) {
  641. const sql = 'SELECT lid, pid, cid, cbid, qty, stimes, sorder, no_value FROM ' + this.tableName + ' WHERE sid = ?';
  642. const curAll = await this.db.query(sql, [sid]);
  643. const cur = this.ctx.helper.filterLastestData(curAll, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  644. return this._.map(this._.filter(cur, 'qty'), 'cid');
  645. }
  646. async getCurStageData(tid, sid, stimes, sorder) {
  647. const sql = `SELECT * From ${this.tableName} WHERE tid = ? AND sid = ? AND (stimes < ? OR (stimes = ? AND sorder < ?))`;
  648. const data = await this.db.query(sql, [tid, sid, stimes, stimes, sorder]);
  649. return this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  650. }
  651. async getFinalStageData(tid, sid) {
  652. const data = await this.getAllDataByCondition({ where: { tid, sid } });
  653. return this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  654. }
  655. async getSumLoadFinalData(sid) {
  656. 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' +
  657. ' FROM ' + this.tableName + ' cf' +
  658. ' Left Join ' + this.ctx.service.change.tableName + ' c ON cf.cid = c.cid' +
  659. ' Where cf.sid = ?';
  660. const result = await this.db.query(sql, [sid]);
  661. return this.ctx.helper.filterLastestData(result, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  662. }
  663. async _getTender(stage) {
  664. if (this.ctx.tender) return this.ctx.tender;
  665. const tender = { id: stage.tid };
  666. tender.data = await this.ctx.service.tender.getTender(stage.tid);
  667. tender.info = await this.service.tenderInfo.getTenderInfo(tender.id);
  668. return tender;
  669. }
  670. async getSubtotal(stage) {
  671. const helper = this.ctx.helper;
  672. const tender = await this._getTender(stage);
  673. const sql = 'SELECT sc.*, c.quality FROM ' + this.tableName + ' sc' +
  674. ' LEFT JOIN ' + this.ctx.service.change.tableName + ' c ON sc.cid = c.cid' +
  675. ' WHERE sid = ? ' + (stage.readOnly ? ` and (stimes < ${stage.curTimes} or (stimes = ${stage.curTimes} and sorder <= ${stage.curOrder}))` : '');
  676. let data = await this.db.query(sql, [stage.id]);
  677. data = helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  678. const bqData = [];
  679. for (const d of data) {
  680. if (!d.qty || d.no_value) continue;
  681. let bd = bqData.find(x => { return x.lid === d.lid && x.quality === d.quality; });
  682. if (!bd) {
  683. bd = { lid: d.lid, quality: d.quality, unit_price: d.unit_price };
  684. bqData.push(bd);
  685. }
  686. const tp = this.ctx.helper.mul(d.qty, bd.unit_price, tender.info.decimal.tp);
  687. bd.tp = this.ctx.helper.add(bd.tp, tp);
  688. }
  689. const result = {};
  690. result.common = helper.sum(helper._.map(bqData.filter(x => {return x.quality === changeConst.quality.common.value; }), 'tp'));
  691. result.more = helper.sum(helper._.map(bqData.filter(x => {return x.quality === changeConst.quality.more.value; }), 'tp'));
  692. result.great = helper.sum(helper._.map(bqData.filter(x => {return x.quality === changeConst.quality.great.value; }), 'tp'));
  693. return result;
  694. }
  695. async getChangeBillsWithUsedInfo(stage) {
  696. if (stage.status === audit.stage.status.checked) {
  697. const sql = 'SELECT scf.* ' +
  698. ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
  699. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
  700. ' WHERE scf.tid = ? And s.order <= ?';
  701. const result = await this.db.query(sql, [stage.tid, stage.order]);
  702. return result;
  703. } else {
  704. const preSql = 'SELECT scf.* ' +
  705. ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
  706. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
  707. ' WHERE scf.tid = ? And s.order < ?';
  708. const pre = await this.db.query(preSql, [stage.tid, stage.order]);
  709. const sql = 'SELECT * FROM ' + this.tableName + ' WHERE sid = ? AND (stimes * 100 + sorder) <= (? * 100 + ?)';
  710. const curAll = await this.db.query(sql, [stage.id, stage.curTimes, stage.curOrder]);
  711. const cur = this.ctx.helper.filterLastestData(curAll, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  712. return [...pre, ...cur];
  713. }
  714. }
  715. async getChangeWithUsedInfo(stage) {
  716. const change = await this.ctx.service.change.getAllDataByCondition({
  717. where: { tid: stage.tid, status: audit.flow.status.checked },
  718. orders: [['code', 'asc']],
  719. });
  720. if (change.length === 0) return [];
  721. const changeBills = await this.ctx.service.changeAuditList.getAllDataByCondition({
  722. where: { cid: change.map(x => { return x.cid; }) }
  723. });
  724. const changeBillsIndex = {}, changeBillsPart = {};
  725. for (const cb of changeBills) {
  726. changeBillsIndex[cb.id] = cb;
  727. if (!changeBillsPart[cb.cid]) changeBillsPart[cb.cid] = [];
  728. changeBillsPart[cb.cid].push(cb);
  729. }
  730. const stageChangeBills = await this.getChangeBillsWithUsedInfo(stage);
  731. for (const scb of stageChangeBills) {
  732. if (!scb.qty) continue;
  733. const cb = changeBillsIndex[scb.cbid];
  734. if (cb) cb.used_qty = this.ctx.helper.add(cb.used_qty, scb.qty);
  735. }
  736. for (const cid in changeBillsPart) {
  737. const c = change.find(x => { return x.cid === cid });
  738. if (!c) continue;
  739. const sumBills = [];
  740. for (const cb of changeBillsPart[cid]) {
  741. let sb;
  742. if (cb.gcl_id) {
  743. sb = sumBills.find(x => { return x.gcl_id === cb.gcl_id; });
  744. }
  745. if (!cb.gcl_id || !sb) {
  746. sb = { gcl_id: cb.gcl_id, unit_price: cb.unit_price, used_qty: 0, p_used_qty: 0, n_used_qty: 0 };
  747. sumBills.push(sb);
  748. }
  749. sb.used_qty = this.ctx.helper.add(sb.used_qty, cb.used_qty);
  750. if (cb.spamount > 0) {
  751. sb.p_used_qty = this.ctx.helper.add(sb.p_used_qty, cb.used_qty);
  752. } else {
  753. sb.n_used_qty = this.ctx.helper.add(sb.n_used_qty, cb.used_qty);
  754. }
  755. cb.tp = this.ctx.helper.mul(cb.spamount, cb.unit_price, c.tp_decimal || this.ctx.tender.info.decimal.tp);
  756. cb.used_tp = this.ctx.helper.mul(cb.used_qty, cb.unit_price, this.ctx.tender.info.decimal.tp);
  757. }
  758. for (const sb of sumBills) {
  759. sb.used_tp = this.ctx.helper.mul(sb.used_qty, sb.unit_price, this.ctx.tender.info.decimal.tp);
  760. sb.p_used_tp = this.ctx.helper.mul(sb.p_used_qty, sb.unit_price, this.ctx.tender.info.decimal.tp);
  761. sb.n_used_tp = this.ctx.helper.mul(sb.n_used_qty, sb.unit_price, this.ctx.tender.info.decimal.tp);
  762. c.used_tp = this.ctx.helper.add(c.used_tp, sb.used_tp);
  763. c.p_used_tp = this.ctx.helper.add(c.p_used_tp, sb.p_used_tp);
  764. c.n_used_tp = this.ctx.helper.add(c.n_used_tp, sb.n_used_tp);
  765. }
  766. c.p_tp = c.positive_tp;
  767. c.n_tp = c.negative_tp;
  768. c.used_pt = c.total_price ? this.ctx.helper.mul(this.ctx.helper.div(c.used_tp, c.total_price, 4), 100) : 0;
  769. 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;
  770. 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;
  771. }
  772. return change;
  773. }
  774. async getStageMinusChange(stage) {
  775. const data = await this.getAllDataByCondition({ where: { sid: stage.id, minus: 1 } });
  776. return this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  777. };
  778. async getBillsMinusQty(stage, lid) {
  779. const data = await this.getAllDataByCondition({ where: { sid: stage.id, lid, minus: 1 } });
  780. const filter = this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  781. return { lid, qty: this.ctx.helper.sum(filter.map(x => { return x.qty; })) };
  782. };
  783. async getPosMinusQty(stage, pid) {
  784. const data = await this.getAllDataByCondition({ where: { sid: stage.id, pid, minus: 1 } });
  785. const filter = this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  786. return { pid, qty: this.ctx.helper.sum(filter.map(x => { return x.qty; })) };
  787. };
  788. async autoUseChangeBills(tender, stage, data) {
  789. const lid = [], cbid = [];
  790. data.forEach(x => {
  791. lid.push(x.lid);
  792. cbid.push(x.cbid);
  793. });
  794. const validChangeBills = await this.ctx.service.stageChangeFinal.getListChangeBillsValidQty(tender.id, cbid);
  795. validChangeBills.forEach(x => {
  796. x.billsPos = data.find(y => { return x.id === y.cbid; });
  797. });
  798. const ledgerData = await this.ctx.service.ledger.getAllDataByCondition({
  799. columns: ['id', 'ledger_id', 'ledger_pid', 'level', 'order', 'full_path', 'is_leaf', 'code', 'b_code', 'name', 'unit', 'unit_price', 'quantity', 'total_price'],
  800. where: { id: lid },
  801. });
  802. const extraData = await this.ctx.service.ledgerExtra.getData(this.ctx.tender.id, ['is_tp']);
  803. this.ctx.helper.assignRelaData(ledgerData, [
  804. { data: extraData, fields: ['is_tp'], prefix: '', relaId: 'id' },
  805. ]);
  806. const posData = await this.ctx.service.pos.getAllDataByCondition({
  807. columns: ['id', 'lid', 'name', 'porder'],
  808. where: { lid },
  809. });
  810. const stageBills = await this.ctx.service.stageBills.getAllDataByCondition({ where: { sid: stage.id } });
  811. const stagePos = await this.ctx.service.stagePos.getAllDataByCondition({ where: { sid: stage.id } });
  812. const stageChange = await this.ctx.service.stageChange.getAllDataByCondition({ where: { sid: stage.id, lid }});
  813. const preStageBills = stage.preCheckedStage ? await this.ctx.service.stageBillsFinal.getFinalData(tender, stage.preCheckedStage.order) : [];
  814. const useModal = new autoUseChange(this.ctx, tender.info);
  815. const projectFunInfo = this.ctx.subProject.fun_rela;
  816. const minusNoValue = projectFunInfo.minusNoValue && tender.info.fun_rela.stage_change.minusNoValue;
  817. useModal.use({ledgerData, posData, stageBills, stagePos, stageChange, preStageBills, default: { tid: stage.tid, sid: stage.id, said: this.ctx.session.sessionUser.accountId } }, validChangeBills, minusNoValue);
  818. const conn = await this.db.beginTransaction();
  819. try {
  820. if (useModal.insertBills.length > 0) await conn.insert(this.ctx.service.stageBills.tableName, useModal.insertBills);
  821. if (useModal.updateBills.length > 0) await conn.updateRows(this.ctx.service.stageBills.tableName, useModal.updateBills);
  822. if (useModal.insertPos.length > 0) await conn.insert(this.ctx.service.stagePos.tableName, useModal.insertPos);
  823. if (useModal.updatePos.length > 0) await conn.updateRows(this.ctx.service.stagePos.tableName, useModal.updatePos);
  824. if (useModal.insertChange.length > 0) await conn.insert(this.tableName, useModal.insertChange);
  825. if (useModal.updateChange.length > 0) await conn.updateRows(this.tableName, useModal.updateChange);
  826. await conn.commit();
  827. } catch (err) {
  828. await conn.rollback();
  829. this.ctx.log(err);
  830. throw '保存导入数据失败';
  831. }
  832. const rst = { bills: {}, pos: {} };
  833. rst.bills.curStageData = await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, lid);
  834. rst.pos.curStageData = await this.ctx.service.stagePos.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, { lid });
  835. return rst;
  836. };
  837. async autoUseAllChange(tender, stage) {
  838. const validChangeBills = await this.ctx.service.stageChangeFinal.getAllChangeBillsValidQty(tender.id);
  839. const ledgerData = await this.ctx.service.ledger.getAllDataByCondition({
  840. columns: ['id', 'ledger_id', 'ledger_pid', 'level', 'order', 'full_path', 'is_leaf', 'code', 'b_code', 'name', 'unit', 'unit_price', 'quantity', 'total_price'],
  841. where: { tender_id: stage.tid },
  842. });
  843. const extraData = await this.ctx.service.ledgerExtra.getData(this.ctx.tender.id, ['is_tp']);
  844. const settleStatusBills = stage.readySettle ? await this.ctx.service.settleBills.getAllDataByCondition({ where: { settle_id: stage.readySettle.id }}) : [];
  845. this.ctx.helper.assignRelaData(ledgerData, [
  846. { data: extraData, fields: ['is_tp'], prefix: '', relaId: 'id' },
  847. { data: settleStatusBills, fields: ['settle_status'], prefix: '', relaId: 'lid' },
  848. ]);
  849. const posData = await this.ctx.service.pos.getAllDataByCondition({
  850. columns: ['id', 'lid', 'name', 'porder'],
  851. where: { tid: stage.tid },
  852. });
  853. const settleStatusPos = stage.readySettle ? await this.ctx.service.settlePos.getAllDataByCondition({ where: { settle_id: stage.readySettle.id }}) : [];
  854. this.ctx.helper.assignRelaData(posData, [
  855. { data: settleStatusPos, fields: ['settle_status'], prefix: '', relaId: 'pid' },
  856. ]);
  857. const stageBills = await this.ctx.service.stageBills.getAllDataByCondition({ where: { sid: stage.id } });
  858. const stagePos = await this.ctx.service.stagePos.getAllDataByCondition({ where: { sid: stage.id } });
  859. const preStageBills = stage.preCheckedStage ? await this.ctx.service.stageBillsFinal.getFinalData(tender, stage.preCheckedStage.order) : [];
  860. const useModal = new autoUseChange(this.ctx, tender.info, this.ctx.service.settle.settleStatus);
  861. const projectFunInfo = this.ctx.subProject.fun_rela;
  862. const minusNoValue = projectFunInfo.minusNoValue && tender.info.fun_rela.stage_change.minusNoValue;
  863. useModal.use({ledgerData, posData, stageBills, stagePos, preStageBills, default: { tid: stage.tid, sid: stage.id, said: this.ctx.session.sessionUser.accountId } }, validChangeBills, minusNoValue);
  864. // if (useModal.insertChange.length === 0) return '无可调用的清单或计量单元';
  865. const conn = await this.db.beginTransaction();
  866. try {
  867. if (useModal.insertBills.length > 0) await conn.insert(this.ctx.service.stageBills.tableName, useModal.insertBills);
  868. if (useModal.updateBills.length > 0) await conn.updateRows(this.ctx.service.stageBills.tableName, useModal.updateBills);
  869. if (useModal.insertPos.length > 0) await conn.insert(this.ctx.service.stagePos.tableName, useModal.insertPos);
  870. if (useModal.updatePos.length > 0) await conn.updateRows(this.ctx.service.stagePos.tableName, useModal.updatePos);
  871. await conn.delete(this.tableName, { sid: stage.id });
  872. if (useModal.insertChange.length > 0) await conn.insert(this.tableName, useModal.insertChange);
  873. await conn.commit();
  874. } catch (err) {
  875. await conn.rollback();
  876. this.ctx.log(err);
  877. throw '保存导入数据失败';
  878. }
  879. }
  880. async updateStageChange4CheckCancel(sid, newTimes, newOrder, oldTimes, oldOrder, transaction) {
  881. const oldSBLists = await this.getAllDataByCondition({ where: { sid, stimes: oldTimes, sorder: oldOrder } });
  882. const newSBLists = await this.getAllDataByCondition({ where: { sid, stimes: newTimes, sorder: newOrder } });
  883. const delidList = [];
  884. for (const o of oldSBLists) {
  885. const newSBInfo = this._.find(newSBLists, { lid: o.lid });
  886. if (newSBInfo) {
  887. // 删除
  888. delidList.push(newSBInfo.id);
  889. }
  890. }
  891. if (delidList.length > 0) await transaction.delete(this.tableName, { id: delidList });
  892. if (oldSBLists.length > 0) {
  893. await transaction.update(this.tableName, {
  894. stimes: newTimes,
  895. sorder: newOrder,
  896. }, { where: { id: this._.map(oldSBLists, 'id') } });
  897. }
  898. }
  899. }
  900. return StageChange;
  901. };