stage_change.js 43 KB

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