stage_change.js 42 KB

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