stage_change.js 37 KB

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