stage_change.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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;
  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. billsQty = this.ctx.helper.add(billsQty, change.qty);
  281. if (oc.stimes === this.ctx.stage.curTimes && oc.sorder === this.ctx.stage.curOrder) {
  282. change.id = oc.id;
  283. updateChanges.push(change);
  284. } else {
  285. newChanges.push(change);
  286. }
  287. } else {
  288. billsQty = this.ctx.helper.add(billsQty, oc.qty);
  289. }
  290. }
  291. for (const c of changes) {
  292. const nc = this._.find(oldChanges, { cid: c.cid, cbid: c.cbid });
  293. if (!nc) {
  294. const change = getNewChange(c.cid, c.cbid, this.ctx.stage.curTimes, this.ctx.stage.curOrder, this.round(c.qty, precision.value), c.minus, noValue);
  295. billsQty = this.ctx.helper.add(billsQty, change.qty);
  296. newChanges.push(change);
  297. }
  298. }
  299. // 更新数据
  300. const transaction = await this.db.beginTransaction();
  301. try {
  302. if (newChanges.length > 0) await transaction.insert(this.tableName, newChanges);
  303. if (updateChanges.length > 0) await transaction.updateRows(this.tableName, updateChange);
  304. const stageBills = await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, bills.id);
  305. const sbUpdate = noValue ? {qc_minus_qty: billsQty} : {qc_qty: billsQty};
  306. await this.ctx.service.stageBills.updateStageBillsQty(transaction, ledgerBills, stageBills, sbUpdate);
  307. await transaction.commit();
  308. } catch (err) {
  309. await transaction.rollback();
  310. throw err;
  311. }
  312. const result = await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, [bills.id]);
  313. return { bills: { curStageData: result } };
  314. }
  315. /**
  316. * 部位明细,调用变更令
  317. *
  318. * @param {Object} pos - 部位明细数据
  319. * @param {Array} changes - 调用的变更令
  320. * @return {Promise<{}>}
  321. */
  322. async posChange(pos, noValue, changes) {
  323. const self = this;
  324. function getNewChange(cid, cbid, times, order, qty, minus, no_value) {
  325. return {
  326. tid: self.ctx.tender.id, sid: self.ctx.stage.id,
  327. lid: pos.lid, pid: pos.id,
  328. cid, cbid,
  329. stimes: times, sorder: order,
  330. qty, minus, no_value,
  331. };
  332. }
  333. const ledgerBills = await this.ctx.service.ledger.getCompleteDataById(pos.lid);
  334. if (!ledgerBills || ledgerBills.tender_id !== this.ctx.tender.id) {
  335. throw '提交数据错误';
  336. }
  337. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, ledgerBills.unit);
  338. // 获取原变更令
  339. const oldChanges = await this.getLastestStageData(this.ctx.tender.id, this.ctx.stage.id, pos.lid, pos.id, noValue);
  340. const updateChanges = [],
  341. newChanges = [];
  342. let posQty = 0;
  343. for (const oc of oldChanges) {
  344. const nc = this._.find(changes, { cid: oc.cid, cbid: oc.cbid });
  345. if (!nc || nc.qty !== oc.qty) {
  346. const qty = nc ? this.round(nc.qty, precision.value) : null;
  347. const change = getNewChange(oc.cid, oc.cbid, this.ctx.stage.curTimes, this.ctx.stage.curOrder, qty, nc ? nc.minus : oc.minus, noValue);
  348. posQty = this.ctx.helper.add(posQty, change.qty);
  349. if (oc.stimes === this.ctx.stage.curTimes && oc.sorder === this.ctx.stage.curOrder) {
  350. change.id = oc.id;
  351. updateChanges.push(change);
  352. } else {
  353. newChanges.push(change);
  354. }
  355. } else {
  356. posQty = this.ctx.helper.add(posQty, oc.qty);
  357. }
  358. }
  359. for (const c of changes) {
  360. const nc = this._.find(oldChanges, { cid: c.cid, cbid: c.cbid });
  361. if (!nc) {
  362. const change = getNewChange(c.cid, c.cbid, this.ctx.stage.curTimes, this.ctx.stage.curOrder, this.round(c.qty, precision.value), c.minus, noValue);
  363. posQty = this.ctx.helper.add(posQty, change.qty);
  364. newChanges.push(change);
  365. }
  366. }
  367. // 更新数据
  368. const transaction = await this.db.beginTransaction();
  369. try {
  370. if (newChanges.length > 0) await transaction.insert(this.tableName, newChanges);
  371. if (updateChanges.length > 0) await transaction.updateRows(this.tableName, updateChanges);
  372. await this.ctx.service.stagePos.updateChangeQuantity(transaction, pos, posQty, noValue);
  373. await transaction.commit();
  374. } catch (err) {
  375. await transaction.rollback();
  376. throw err;
  377. }
  378. // 获取返回数据
  379. try {
  380. const data = { bills: {}, pos: {} };
  381. data.bills.curStageData = await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, [pos.lid]);
  382. data.pos.curStageData = await this.ctx.service.stagePos.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, { pid: pos.id });
  383. return data;
  384. } catch (err) {
  385. throw '获取数据错误,请刷新页面';
  386. }
  387. }
  388. /**
  389. * 获取 变更令 - 变更清单 使用情况
  390. * @param {Number} sid - 查询期id
  391. * @param {uuid} cid - 变更令id
  392. * @return {Promise<void>}
  393. */
  394. async getUsedData(tid, cid) {
  395. if (this.ctx.stage.status === audit.stage.status.checked) {
  396. const sql = 'SELECT scf.* ' +
  397. ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
  398. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
  399. ' WHERE scf.tid = ? And scf.cid = ? And s.order <= ?';
  400. const result = await this.db.query(sql, [tid, cid, this.ctx.stage.order]);
  401. return result;
  402. } else {
  403. const preSql = 'SELECT scf.* ' +
  404. ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
  405. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
  406. ' WHERE scf.tid = ? And scf.cid = ? And s.order < ?';
  407. const pre = await this.db.query(preSql, [tid, cid, this.ctx.stage.order]);
  408. const sql = 'SELECT * FROM ' + this.tableName + ' WHERE sid = ?';
  409. const curAll = await this.db.query(sql, [this.ctx.stage.id]);
  410. const cur = this.ctx.helper.filterLastestData(curAll, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  411. return [...pre, ...cur];
  412. }
  413. }
  414. async getFinalUsedData(tid, cid) {
  415. const stage = await this.ctx.service.stage.getLastestStage(tid, true);
  416. if (!stage) { // 防止未创建期时调用
  417. return [];
  418. }
  419. if (stage.status === audit.stage.status.checked) {
  420. const sql = 'SELECT scf.* ' +
  421. ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
  422. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
  423. ' WHERE scf.tid = ? And scf.cid = ? And s.order <= ?';
  424. const result = await this.db.query(sql, [tid, cid, stage.order]);
  425. return result;
  426. } else {
  427. const preSql = 'SELECT scf.* ' +
  428. ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
  429. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
  430. ' WHERE scf.tid = ? And scf.cid = ? And s.order < ?';
  431. const pre = await this.db.query(preSql, [tid, cid, stage.order]);
  432. const sql = 'SELECT * FROM ' + this.tableName + ' WHERE sid = ? and cid = ?';
  433. const curAll = await this.db.query(sql, [stage.id, cid]);
  434. const cur = this.ctx.helper.filterLastestData(curAll, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  435. return [...pre, ...cur];
  436. }
  437. }
  438. /**
  439. * 获取 变更令 - 变更清单 当期使用情况
  440. * @param {Number} sid - 查询期id
  441. * @param {uuid} cid - 变更令id
  442. * @return {Promise<*>}
  443. */
  444. async getStageUsedData(sid, cid) {
  445. const data = await this.getAllDataByCondition({ where: { sid, cid } });
  446. const _ = this.ctx.helper._;
  447. const filter = this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  448. if (filter.length === 0) return filter;
  449. const bills = await this.ctx.service.ledger.getAllDataByCondition({
  450. where: { id: _.uniq(_.map(filter, 'lid')) }
  451. });
  452. const pos = await this.ctx.service.pos.getAllDataByCondition({
  453. where: { id: _.uniq(_.map(filter, 'pid')) }
  454. });
  455. return filter.map(x => {
  456. const b = bills.find(y => { return y.id === x.lid });
  457. const p = pos.find(y => { return y.id === x.pid });
  458. return {
  459. ...x,
  460. ledger_id: b.ledger_id, l_code: b.b_code, l_name: b.name, l_unit: b.unit, l_up: b.unit_price,
  461. 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,
  462. p_name: p ? p.name : '', p_drawing_code: p ? p.drawing_code : '', p_qty: p ? p.quantity : '',
  463. };
  464. });
  465. }
  466. /**
  467. * 获取 本期 使用的变更令
  468. * @param sid
  469. * @return {Promise<void>}
  470. */
  471. async getStageUsedChangeId(sid) {
  472. const sql = 'SELECT lid, pid, cid, cbid, qty, stimes, sorder FROM ' + this.tableName + ' WHERE sid = ?';
  473. const curAll = await this.db.query(sql, [sid]);
  474. const cur = this.ctx.helper.filterLastestData(curAll, ['lid', 'pid', 'cbid'], 'stimes', 'sorder');
  475. return this._.map(this._.filter(cur, 'qty'), 'cid');
  476. }
  477. async getFinalStageData(tid, sid) {
  478. const data = await this.getAllDataByCondition({ where: { tid, sid } });
  479. return this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  480. }
  481. async getSumLoadFinalData(sid) {
  482. 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' +
  483. ' FROM ' + this.tableName + ' cf' +
  484. ' Left Join ' + this.ctx.service.change.tableName + ' c ON cf.cid = c.cid' +
  485. ' Where cf.sid = ?';
  486. const result = await this.db.query(sql, [sid]);
  487. return this.ctx.helper.filterLastestData(result, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  488. }
  489. async _getTender(stage) {
  490. if (this.ctx.tender) return this.ctx.tender;
  491. const tender = { id: stage.tid };
  492. tender.data = await this.ctx.service.tender.getTender(stage.tid);
  493. tender.info = await this.service.tenderInfo.getTenderInfo(tender.id);
  494. return tender;
  495. }
  496. async getSubtotal(stage) {
  497. const helper = this.ctx.helper;
  498. const tender = await this._getTender(stage);
  499. const sql = 'SELECT sc.*, c.quality FROM ' + this.tableName + ' sc' +
  500. ' LEFT JOIN ' + this.ctx.service.change.tableName + ' c ON sc.cid = c.cid' +
  501. ' WHERE sid = ? ' + (stage.readOnly ? ` and (stimes < ${stage.curTimes} or (stimes = ${stage.curTimes} and sorder <= ${stage.curOrder}))` : '');
  502. let data = await this.db.query(sql, [stage.id]);
  503. data = helper.filterLastestData(data, ['lid', 'pid', 'cbid'], 'stimes', 'sorder');
  504. const bqData = [];
  505. for (const d of data) {
  506. if (!d.qty) continue;
  507. let bd = bqData.find(x => { return x.lid === d.lid && x.quality === d.quality; });
  508. if (!bd) {
  509. const bills = await this.db.get(this.ctx.service.ledger.departTableName(tender.id), { id: d.lid });
  510. if (!bills) continue;
  511. bd = { lid: d.lid, quality: d.quality, unit_price: bills.unit_price };
  512. bqData.push(bd);
  513. }
  514. const tp = this.ctx.helper.mul(d.qty, bd.unit_price, tender.info.decimal.tp);
  515. bd.tp = this.ctx.helper.add(bd.tp, tp);
  516. }
  517. const result = {};
  518. result.common = helper.sum(helper._.map(bqData.filter(x => {return x.quality === changeConst.quality.common.value; }), 'tp'));
  519. result.more = helper.sum(helper._.map(bqData.filter(x => {return x.quality === changeConst.quality.more.value; }), 'tp'));
  520. result.great = helper.sum(helper._.map(bqData.filter(x => {return x.quality === changeConst.quality.great.value; }), 'tp'));
  521. return result;
  522. }
  523. async _getChangeBillsWithUsedInfo(stage) {
  524. if (stage.status === audit.stage.status.checked) {
  525. const sql = 'SELECT scf.* ' +
  526. ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
  527. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
  528. ' WHERE scf.tid = ? And s.order <= ?';
  529. const result = await this.db.query(sql, [stage.tid, stage.order]);
  530. return result;
  531. } else {
  532. const preSql = 'SELECT scf.* ' +
  533. ' FROM ' + this.ctx.service.stageChangeFinal.tableName + ' scf ' +
  534. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' s ON scf.sid = s.id' +
  535. ' WHERE scf.tid = ? And s.order < ?';
  536. const pre = await this.db.query(preSql, [stage.tid, stage.order]);
  537. const sql = 'SELECT * FROM ' + this.tableName + ' WHERE sid = ? AND (stimes * 100 + sorder) <= (? * 100 + ?)';
  538. const curAll = await this.db.query(sql, [stage.id, stage.curTimes, stage.curOrder]);
  539. const cur = this.ctx.helper.filterLastestData(curAll, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
  540. return [...pre, ...cur];
  541. }
  542. }
  543. async getChangeWithUsedInfo(stage) {
  544. const change = await this.ctx.service.change.getAllDataByCondition({
  545. where: { tid: stage.tid, status: audit.flow.status.checked },
  546. orders: [['code', 'asc']],
  547. });
  548. if (change.length === 0) return [];
  549. const changeBills = await this.ctx.service.changeAuditList.getAllDataByCondition({
  550. where: { cid: change.map(x => { return x.cid; }) }
  551. });
  552. const changeBillsIndex = {}, changeBillsPart = {};
  553. for (const cb of changeBills) {
  554. changeBillsIndex[cb.id] = cb;
  555. if (!changeBillsPart[cb.cid]) changeBillsPart[cb.cid] = [];
  556. changeBillsPart[cb.cid].push(cb);
  557. }
  558. const stageChangeBills = await this._getChangeBillsWithUsedInfo(stage);
  559. for (const scb of stageChangeBills) {
  560. if (!scb.qty) continue;
  561. const cb = changeBillsIndex[scb.cbid];
  562. if (cb) cb.used_qty = this.ctx.helper.add(cb.used_qty, scb.qty);
  563. }
  564. for (const cid in changeBillsPart) {
  565. const c = change.find(x => { return x.cid === cid });
  566. if (!c) continue;
  567. for (const cb of changeBillsPart[cid]) {
  568. cb.tp = this.ctx.helper.mul(cb.spamount, cb.unit_price, c.tp_decimal || this.ctx.tender.info.decimal.tp);
  569. cb.used_tp = this.ctx.helper.mul(cb.used_qty, cb.unit_price, this.ctx.tender.info.decimal.tp);
  570. c.used_tp = this.ctx.helper.add(c.used_tp, cb.used_tp);
  571. if (cb.spamount > 0) {
  572. c.p_tp = this.ctx.helper.add(c.p_tp, cb.tp);
  573. c.p_used_tp = this.ctx.helper.add(c.p_used_tp, cb.used_tp);
  574. } else if (cb.spamount < 0){
  575. c.n_tp = this.ctx.helper.add(c.n_tp, cb.tp);
  576. c.n_used_tp = this.ctx.helper.add(c.n_used_tp, cb.used_tp);
  577. }
  578. }
  579. c.used_pt = c.total_price ? this.ctx.helper.mul(this.ctx.helper.div(c.used_tp, c.total_price, 4), 100) : 0;
  580. 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;
  581. 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;
  582. }
  583. return change;
  584. }
  585. async getStageMinusChange(stage) {
  586. const data = await this.getAllDataByCondition({ where: { sid: stage.id, minus: 1 } });
  587. return this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid'], 'stimes', 'sorder');
  588. };
  589. async getBillsMinusQty(stage, lid) {
  590. const data = await this.getAllDataByCondition({ where: { sid: stage.id, lid, minus: 1 } });
  591. const filter = this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid'], 'stimes', 'sorder');
  592. return { lid, qty: this.ctx.helper.sum(filter.map(x => { return x.qty; })) };
  593. };
  594. async getPosMinusQty(stage, pid) {
  595. const data = await this.getAllDataByCondition({ where: { sid: stage.id, pid, minus: 1 } });
  596. const filter = this.ctx.helper.filterLastestData(data, ['lid', 'pid', 'cbid'], 'stimes', 'sorder');
  597. return { pid, qty: this.ctx.helper.sum(filter.map(x => { return x.qty; })) };
  598. };
  599. async autoUseChangeBills(tender, stage, data) {
  600. for (const d of data) {
  601. const changeBills = await this.ctx.service.changeAuditList.getDataById(d.cbid);
  602. const bills = await this.ctx.service.ledger.getDataById(data.lid);
  603. const pos = await this.ctx.service.pos.getDataById(data.pid);
  604. if (pos && pos.lid !== bills.id) throw '数据错误';
  605. const allSc = await this.getAllDataByCondition({ where: { cbid: d.cbid, lid: data.lid, pid: data.pid } });
  606. const curSc = this.ctx.helper.filterLastestData(allSc, ['lid', 'pid', 'cbid'], 'stimes', 'sorder');
  607. }
  608. const changeBills = await this.ctx.service.changeAuditList.getDataById(cbid);
  609. const source = changeBills.gcl_id
  610. ? await this.ctx.service.ledger.getDataByCondition({ where: { id: [changeBills.gcl_id] } })
  611. : 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 }});
  612. if (source.length < 1) then
  613. const pos = this.ctx.service.pos.getDataByCondition({ where: { lid: bills.id, name: changeBills.bwmx} });
  614. };
  615. async autoUseAllChange(tender, stage) {
  616. const validChangeBills = await this.ctx.service.stageChangeFinal.getAllChangeBillsValidQty(tender.id);
  617. const ledgerData = await this.ctx.service.ledger.getAllDataByCondition({
  618. columns: ['id', 'ledger_id', 'ledger_pid', 'level', 'order', 'full_path', 'is_leaf', 'code', 'b_code', 'name', 'unit', 'unit_price'],
  619. where: { tender_id: stage.tid },
  620. });
  621. const extraData = await this.ctx.service.ledgerExtra.getData(this.ctx.tender.id, ['is_tp']);
  622. this.ctx.helper.assignRelaData(ledgerData, [
  623. { data: extraData, fields: ['is_tp'], prefix: '', relaId: 'id' },
  624. ]);
  625. const posData = await this.ctx.service.pos.getAllDataByCondition({
  626. columns: ['id', 'lid', 'name', 'porder'],
  627. where: { tid: stage.tid },
  628. });
  629. const stageBills = await this.ctx.service.stageBills.getAllDataByCondition({ where: { sid: stage.id } });
  630. const stagePos = await this.ctx.service.stagePos.getAllDataByCondition({ where: { sid: stage.id } });
  631. const useModal = new autoUseChange(this.ctx.helper, tender.info);
  632. useModal.use({ledgerData, posData, stageBills, stagePos, default: { tid: stage.tid, sid: stage.id, said: this.ctx.session.sessionUser.accountId } }, validChangeBills);
  633. const conn = await this.db.beginTransaction();
  634. try {
  635. if (useModal.insertBills.length > 0) conn.insert(this.ctx.service.stageBills.tableName, useModal.insertBills);
  636. if (useModal.updateBills.length > 0) conn.updateRows(this.ctx.service.stageBills.tableName, useModal.updateBills);
  637. if (useModal.insertPos.length > 0) conn.insert(this.ctx.service.stagePos.tableName, useModal.insertPos);
  638. if (useModal.updatePos.length > 0) conn.updateRows(this.ctx.service.stagePos.tableName, useModal.updatePos);
  639. await conn.delete(this.tableName, { sid: stage.id });
  640. await conn.insert(this.tableName, useModal.insertChange);
  641. await conn.commit();
  642. } catch (err) {
  643. await conn.rollback();
  644. this.ctx.log(err);
  645. throw '保存导入数据失败';
  646. }
  647. }
  648. }
  649. return StageChange;
  650. };