stage_change.js 51 KB

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