stage_change.js 35 KB

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