stage_pos.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date
  7. * @version
  8. */
  9. const measureType = require('../const/tender').measureType;
  10. const timesLen = require('../const/audit').stage.timesLen;
  11. module.exports = app => {
  12. class StagePos extends app.BaseService {
  13. /**
  14. * 构造函数
  15. *
  16. * @param {Object} ctx - egg全局变量
  17. * @return {void}
  18. */
  19. constructor(ctx) {
  20. super(ctx);
  21. this.depart = 20;
  22. this.tableName = 'stage_pos';
  23. this.qtyFields = ['contract_qty', 'qc_qty', 'qc_minus_qty', 'positive_qc_qty', 'negative_qc_qty']
  24. }
  25. _getPosFilterSql(where, asTable = '') {
  26. let whereSql = '';
  27. if (!where) return whereSql;
  28. if (where.pid) {
  29. if (where.pid instanceof Array) {
  30. whereSql += ' And ' + asTable + 'pid in (' + this.ctx.helper.getInArrStrSqlFilter(where.pid) + ')';
  31. } else if (typeof where.pid === "string") {
  32. whereSql += ' And ' + asTable + 'pid = ' + this.db.escape(where.pid);
  33. }
  34. }
  35. if (where.lid) {
  36. if (where.lid instanceof Array) {
  37. whereSql += ' And ' + asTable + 'lid in (' + this.ctx.helper.getInArrStrSqlFilter(where.lid) + ')';
  38. } else if (typeof where.lid === "string") {
  39. whereSql += ' And ' + asTable + 'lid = ' + this.db.escape(where.lid);
  40. }
  41. }
  42. return whereSql;
  43. }
  44. /**
  45. * 查询期计量最后审核人数据
  46. * @param {Number} tid - 标段id
  47. * @param {Number} sid - 期id
  48. * @param {Number|Array} pid - 部位明细id(可以为空)
  49. * @returns {Promise<*>}
  50. */
  51. // async getLastestStageData(tid, sid, where) {
  52. // const filterSql = this._getPosFilterSql(where);
  53. // const sql = 'SELECT Pos.id, Pos.tid, Pos.sid, Pos.lid, Pos.pid, Pos.contract_qty, Pos.qc_qty, Pos.postil, Pos.times, Pos.order, Pos.contract_expr FROM ' +
  54. // ' (SELECT * FROM ' + this.tableName + ' WHERE tid = ? And sid = ?) As Pos ' +
  55. // ' INNER JOIN ( ' +
  56. // ' SELECT MAX(`times` * ' + timesLen + ' + `order`) As `flow`, `tid`, `sid`, `pid` From ' + this.tableName +
  57. // ' WHERE `tid` = ? And sid = ?' + filterSql +
  58. // ' GROUP BY `pid`' +
  59. // ' ) As MaxFilter ' +
  60. // ' ON (Pos.times * ' + timesLen + ' + Pos.order) = MaxFilter.flow And Pos.pid = MaxFilter.pid And Pos.sid = MaxFilter.sid';
  61. // const sqlParam = [tid, sid, tid, sid];
  62. // return await this.db.query(sql, sqlParam);
  63. // }
  64. /**
  65. * 查询 某期 某轮审批 某审核人数据
  66. * @param {Number} tid - 标段id
  67. * @param {Number} sid - 期id
  68. * @param {Number} times - 期第几轮审批
  69. * @param {Number} order - 审核人顺序
  70. * @param {Number|Array|Null} pid - 部位明细id - 为空则查询全部
  71. * @returns {Promise<*>}
  72. */
  73. // async getAuditorStageData(tid, sid, times, order, where) {
  74. // const filterSql = this._getPosFilterSql(where);
  75. // const sql = 'SELECT Pos.id, Pos.tid, Pos.sid, Pos.pid, Pos.lid, Pos.contract_qty, Pos.qc_qty, Pos.postil, Pos.times, Pos.order, Pos.contract_expr FROM ' +
  76. // ' (SELECT * FROM '+ this.tableName + ' WHERE tid = ? And sid = ?) As Pos ' +
  77. // ' INNER JOIN ( ' +
  78. // ' SELECT MAX(`times` * ' + timesLen + ' + `order`) As `flow`, `pid`, `sid` From ' + this.tableName +
  79. // ' WHERE (`times` < ? OR (`times` = ? AND `order` <= ?)) And tid = ? And sid = ?' + filterSql +
  80. // ' GROUP BY `pid`' +
  81. // ' ) As MaxFilter ' +
  82. // ' ON (Pos.times * ' + timesLen + ' + Pos.order) = MaxFilter.flow And Pos.pid = MaxFilter.pid And Pos.sid = MaxFilter.sid';
  83. // const sqlParam = [tid, sid, times, times, order, tid, sid];
  84. // return await this.db.query(sql, sqlParam);
  85. // }
  86. _filterLastestData(stagePos) {
  87. const stagePosIndex = {};
  88. for (const sp of stagePos) {
  89. const key = 'sp-' + sp.pid;
  90. const spi = stagePosIndex[key];
  91. if (spi) {
  92. if ((spi.times * timesLen + spi.order) < (sp.times * timesLen + sp.order)) stagePosIndex[key] = sp;
  93. } else {
  94. stagePosIndex[key] = sp;
  95. }
  96. }
  97. const result = [];
  98. for (const prop in stagePosIndex) {
  99. result.push(stagePosIndex[prop]);
  100. }
  101. return result;
  102. }
  103. async getLastestStageData2(tid, sid, where) {
  104. const filterSql = this._getPosFilterSql(where);
  105. const sql = 'SELECT id, tid, sid, pid, lid, contract_qty, qc_qty, qc_minus_qty, positive_qc_qty, negative_qc_qty, postil, `times`, `order`, `contract_expr`' +
  106. ' FROM ' + this.departTableName(tid) +
  107. ' WHERE tid = ? And sid = ? ' + filterSql;
  108. const sqlParam = [tid, sid];
  109. const stagePos = await this.db.query(sql, sqlParam);
  110. return this._filterLastestData(stagePos);
  111. }
  112. async getAuditorStageData2(tid, sid, times, order, where) {
  113. const filterSql = this._getPosFilterSql(where);
  114. const sql = 'SELECT id, tid, sid, pid, lid, contract_qty, qc_qty, qc_minus_qty, positive_qc_qty, negative_qc_qty, postil, `times`, `order`, `contract_expr`' +
  115. ' FROM ' + this.departTableName(tid) +
  116. ' WHERE tid = ? And sid = ? And (`times` < ? OR (`times` = ? AND `order` <= ?)) ' + filterSql;
  117. const sqlParam = [tid, sid, times, times, order];
  118. const stagePos = await this.db.query(sql, sqlParam);
  119. return this._filterLastestData(stagePos);
  120. }
  121. async updateStagePos4CheckCancel(sid, newTimes, newOrder, oldTimes, oldOrder, transaction) {
  122. const oldSBLists = await this.getAllDataByCondition({ where: { sid, times: oldTimes, order: oldOrder } });
  123. const newSBLists = await this.getAllDataByCondition({ where: { sid, times: newTimes, order: newOrder } });
  124. const delidList = [];
  125. for (const o of oldSBLists) {
  126. const newSBInfo = this._.find(newSBLists, { lid: o.lid, pid: o.pid });
  127. if (newSBInfo) {
  128. // 删除
  129. delidList.push(newSBInfo.id);
  130. }
  131. }
  132. if (delidList.length > 0) await transaction.delete(this.tableName, { id: delidList });
  133. if (oldSBLists.length > 0) {
  134. await transaction.update(this.tableName, {
  135. times: newTimes,
  136. order: newOrder,
  137. }, { where: { id: this._.map(oldSBLists, 'id') } });
  138. }
  139. }
  140. async getStageUsedPos(tid, sid, where) {
  141. const self = this;
  142. const stagePos = await this.getLastestStageData2(tid, sid, where);
  143. const pids = this._.map(stagePos, function (sp) {
  144. if (!self.ctx.helper.checkZero(sp.contract_qty) || !self.ctx.helper.checkZero(sp.qc_qty) || !self.ctx.helper.checkZero(sp.qc_minus_qty)) {
  145. return sp.pid;
  146. } else {
  147. return -1;
  148. }
  149. });
  150. return this._.pull(pids, -1);
  151. }
  152. /**
  153. * 新增部位明细数据(仅供updateStageData调用)
  154. *
  155. * @param transaction - 事务
  156. * @param data - 新增数据
  157. * @returns {Promise<{}>}
  158. * @private
  159. */
  160. async _addStagePosData(data) {
  161. let bills , precision;
  162. const result = {pos: [], ledger: []};
  163. const datas = data instanceof Array ? data : [data], calcStageBills = [];
  164. if (datas[0].sgfh_qty !== undefined || datas[0].sjcl_qty !== undefined || datas[0].qtcl_qty !== undefined
  165. || datas[0].contract_qty !== undefined || datas[0].qc_qty !== undefined || datas[0].real_qty !== undefined) {
  166. bills = await this.ctx.service.ledger.getDataById(datas[0].lid);
  167. precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, bills.unit);
  168. result.ledger.push(bills.id);
  169. }
  170. const insertPos = [], insertPosStage = [];
  171. for (const d of datas) {
  172. const p = {
  173. id: this.uuid.v4(), tid: this.ctx.tender.id, lid: d.lid, name: d.name, porder: d.porder, position: d.position,
  174. add_stage: this.ctx.stage.id, add_stage_order: this.ctx.stage.order,
  175. add_times: this.ctx.stage.curTimes,
  176. add_user: this.ctx.session.sessionUser.accountId,
  177. };
  178. if (d.sgfh_qty !== undefined || d.sjcl_qty !== undefined || d.qtcl_qty !== undefined ||
  179. d.sgfh_expr !== undefined || d.sjcl_expr !== undefined || d.qtcl_expr !== undefined) {
  180. if (d.sgfh_qty!== undefined) p.sgfh_qty = this.round(d.sgfh_qty, precision.value);
  181. if (d.sjcl_qty!== undefined) p.sjcl_qty = this.round(d.sjcl_qty, precision.value);
  182. if (d.qtcl_qty!== undefined) p.qtcl_qty = this.round(d.qtcl_qty, precision.value);
  183. if (d.sgfh_expr !== undefined) p.sgfh_expr = d.sgfh_expr;
  184. if (d.sjcl_expr !== undefined) p.sjcl_expr = d.sjcl_expr;
  185. if (d.qtcl_expr !== undefined) p.qtcl_expr = d.qtcl_expr;
  186. p.quantity = this.ctx.helper.sum([p.sgfh_qty, p.sjcl_qty, p.qtcl_qty]);
  187. }
  188. if (d.real_qty!== undefined) p.real_qty = this.round(d.real_qty, precision.value);
  189. insertPos.push(p);
  190. result.pos.push(p.id);
  191. if (d.contract_qty!== undefined || d.qc_qty!== undefined || d.postil!== undefined || data.contract_expr !== undefined) {
  192. result.stageUpdate = true;
  193. const ps = {
  194. pid: p.id,
  195. lid: d.lid,
  196. tid: this.ctx.tender.id,
  197. sid: this.ctx.stage.id,
  198. said: this.ctx.session.sessionUser.accountId,
  199. times: this.ctx.stage.curTimes,
  200. order: this.ctx.stage.curOrder,
  201. };
  202. if (d.contract_qty !== undefined) ps.contract_qty = this.round(d.contract_qty, precision.value);
  203. if (d.contract_expr !== undefined) ps.contract_expr = d.contract_expr;
  204. if (d.postil!== undefined) ps.postil = d.postil;
  205. insertPosStage.push(ps);
  206. if (d.contract_qty && calcStageBills.indexOf(ps.lid) === -1) {
  207. calcStageBills.push(ps.lid);
  208. }
  209. }
  210. }
  211. const transaction = await this.db.beginTransaction();
  212. try {
  213. if (insertPos.length > 0) await transaction.insert(this.ctx.service.pos.tableName, insertPos);
  214. if (insertPosStage.length > 0) await transaction.insert(this.tableName, insertPosStage);
  215. for (const lid of calcStageBills) {
  216. await this.ctx.service.stageBills.calc(this.ctx.tender.id, this.ctx.stage.id, lid, transaction);
  217. }
  218. await transaction.commit();
  219. return result;
  220. } catch(err) {
  221. await transaction.rollback();
  222. throw err;
  223. }
  224. }
  225. /**
  226. * 更新部位明细数据(仅供updateStageData调用)
  227. *
  228. * @param transaction - 事务
  229. * @param data - 更新数据(允许一次性提交多条)
  230. * @returns {Promise<{ledger: Array, pos: Array}>}
  231. * @private
  232. */
  233. async _updateStagePosData(data) {
  234. let bills, precision, updateBills = null;
  235. const datas = data instanceof Array ? data : [data];
  236. const orgPos = await this.ctx.service.pos.getPosDataByIds(this.ctx.tender.id, this._.map(datas, 'pid'));
  237. const result = {ledger: [], pos: [], stageUpdate: true};
  238. const orgStagePos = await this.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id,
  239. {pid: this._.map(datas, 'pid')});
  240. if (datas[0].sgfh_qty !== undefined || datas[0].qtcl_qty !== undefined || datas[0].sjcl_qty !== undefined
  241. || datas[0].contract_qty !== undefined || datas[0].qc_qty !== undefined || datas[0].real_qty !== undefined) {
  242. bills = await this.ctx.service.ledger.getDataById(datas[0].lid);
  243. precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, bills.unit);
  244. result.ledger.push(bills.id);
  245. }
  246. const updatePos = [], updatePosStage = [], insertPosStage = [];
  247. for (const d of datas) {
  248. if (d.name !== undefined || d.drawing_code !== undefined || d.position !== undefined
  249. || d.sgfh_qty !== undefined || d.qtcl_qty !== undefined || d.sjcl_qty !== undefined
  250. || d.real_qty !== undefined
  251. || d.ex_memo1 !== undefined || d.ex_memo2 !== undefined || d.ex_memo3 !== undefined
  252. ) {
  253. const op = this._.find(orgPos, {id: d.pid});
  254. if (op.add_stage !== this.ctx.stage.id && (
  255. d.name !== undefined || d.drawing_code !== undefined || d.position !== undefined
  256. || d.sgfh_qty !== undefined || d.qtcl_qty !== undefined || d.sjcl_qty !== undefined
  257. )) throw '不可修改数据';
  258. const p = {id: op.id};
  259. if (d.name !== undefined) p.name = d.name;
  260. if (d.position !== undefined) p.position = d.position;
  261. if (d.sgfh_qty !== undefined || d.qtcl_qty !== undefined || d.sjcl_qty !== undefined) {
  262. p.sgfh_qty = d.sgfh_qty !== undefined ? d.sgfh_qty : op.sgfh_qty;
  263. p.sjcl_qty = d.sjcl_qty !== undefined ? d.sjcl_qty : op.sjcl_qty;
  264. p.qtcl_qty = d.qtcl_qty !== undefined ? d.qtcl_qty : op.qtcl_qty;
  265. if (d.sgfh_expr !== undefined) p.sgfh_expr = d.sgfh_expr;
  266. if (d.sjcl_expr !== undefined) p.sjcl_expr = d.sjcl_expr;
  267. if (d.qtcl_expr !== undefined) p.qtcl_expr = d.qtcl_expr;
  268. p.quantity = this.ctx.helper.sum([p.sgfh_qty, p.sjcl_qty, p.qtcl_qty]);
  269. if (!updateBills) updateBills = {id: bills.id};
  270. }
  271. if (d.drawing_code !== undefined) p.drawing_code = d.drawing_code;
  272. if (d.real_qty !== undefined) p.real_qty = this.ctx.helper.round(d.real_qty, precision.value);
  273. if (d.ex_memo1 !== undefined) p.ex_memo1 = d.ex_memo1;
  274. if (d.ex_memo2 !== undefined) p.ex_memo2 = d.ex_memo2;
  275. if (d.ex_memo3 !== undefined) p.ex_memo3 = d.ex_memo3;
  276. updatePos.push(p);
  277. }
  278. if (d.contract_qty !== undefined || d.qc_qty !== undefined || d.postil !== undefined) {
  279. const osp = this._.find(orgStagePos, function (p) { return p.pid === d.pid; });
  280. if (osp && osp.times === this.ctx.stage.curTimes && osp.order === this.ctx.stage.curOrder) {
  281. const sp = { id: osp.id, said: this.ctx.session.sessionUser.accountId };
  282. if (d.contract_qty !== undefined) {
  283. sp.contract_qty = this.ctx.helper.round(d.contract_qty, precision.value);
  284. }
  285. if (d.contract_expr !== undefined) sp.contract_expr = d.contract_expr;
  286. if (d.qc_qty !== undefined) {
  287. sp.qc_qty = this.ctx.helper.round(d.qc_qty, precision.value);
  288. }
  289. if (d.postil !== undefined) {
  290. sp.postil = d.postil;
  291. }
  292. updatePosStage.push(sp);
  293. } else {
  294. const sp = {
  295. pid: d.pid, lid: d.lid,
  296. tid: this.ctx.tender.id, sid: this.ctx.stage.id,
  297. said: this.ctx.session.sessionUser.accountId,
  298. times: this.ctx.stage.curTimes, order: this.ctx.stage.curOrder
  299. };
  300. if (d.contract_qty !== undefined || osp) {
  301. sp.contract_qty = d.contract_qty === undefined && osp
  302. ? osp.contract_qty
  303. : this.ctx.helper.round(d.contract_qty, precision.value);
  304. }
  305. if (d.contract_expr !== undefined) sp.contract_expr = d.contract_expr;
  306. if (d.qc_qty || osp) {
  307. sp.qc_qty = d.qc_qty === undefined && osp
  308. ? osp.qc_qty
  309. : this.ctx.helper.round(d.qc_qty, precision.value);
  310. }
  311. if (d.postil || osp) {
  312. sp.postil = d.postil === undefined && osp ? osp.postil : d.postil;
  313. }
  314. sp.qc_minus_qty = osp ? osp.qc_minus_qty : 0;
  315. sp.positive_qc_qty = osp ? osp.positive_qc_qty : 0;
  316. sp.negative_qc_qty = osp ? osp.negative_qc_qty : 0;
  317. insertPosStage.push(sp);
  318. }
  319. }
  320. result.pos.push(d.pid);
  321. }
  322. if (updateBills) {
  323. const billsPos = await this.ctx.service.pos.getAllDataByCondition({where: {tid: bills.tender_id, lid: bills.id} });
  324. for (const bp of billsPos) {
  325. const newPos = updatePos.find(function (x) { return x.id === bp.id });
  326. const calcData = newPos ? newPos : bp;
  327. updateBills.sgfh_qty = this.ctx.helper.add(updateBills.sgfh_qty, calcData.sgfh_qty);
  328. updateBills.sjcl_qty = this.ctx.helper.add(updateBills.sjcl_qty, calcData.sjcl_qty);
  329. updateBills.qtcl_qty = this.ctx.helper.add(updateBills.qtcl_qty, calcData.qtcl_qty);
  330. updateBills.quantity = this.ctx.helper.add(updateBills.quantity, calcData.quantity);
  331. }
  332. const info = this.ctx.tender.info;
  333. updateBills.sgfh_tp = this.ctx.helper.mul(updateBills.sgfh_qty, bills.unit_price, info.decimal.tp);
  334. updateBills.sjcl_tp = this.ctx.helper.mul(updateBills.sjcl_qty, bills.unit_price, info.decimal.tp);
  335. updateBills.qtcl_tp = this.ctx.helper.mul(updateBills.qtcl_qty, bills.unit_price, info.decimal.tp);
  336. updateBills.total_price = this.ctx.helper.mul(updateBills.quantity, bills.unit_price, info.decimal.tp);
  337. }
  338. const transaction = await this.db.beginTransaction();
  339. try {
  340. if (updatePos.length > 0) await transaction.updateRows(this.ctx.service.pos.tableName, updatePos);
  341. if (updateBills) await transaction.update(this.ctx.service.ledger.tableName, updateBills);
  342. if (updatePosStage.length > 0) await transaction.updateRows(this.tableName, updatePosStage);
  343. if (insertPosStage.length > 0) await transaction.insert(this.tableName, insertPosStage);
  344. if (bills) await this.ctx.service.stageBills.calc(this.ctx.tender.id, this.ctx.stage.id, bills.id, transaction);
  345. await transaction.commit();
  346. return result;
  347. } catch (err) {
  348. await transaction.rollback();
  349. throw err;
  350. }
  351. }
  352. /**
  353. * 更新部位明细数据(仅供updateStageData调用)
  354. *
  355. * @param transaction - 事务
  356. * @param data - 更新数据(允许一次性提交多条)
  357. * @returns {Promise<{ledger: Array, pos: Array}>}
  358. * @private
  359. */
  360. async _batchUpdateStagePosData(data) {
  361. const datas = data instanceof Array ? data : [data];
  362. const result = {
  363. ledger: this._.uniq(this._.map(datas, 'lid')),
  364. pos: this._.map(datas, 'pid'),
  365. stageUpdate: true
  366. };
  367. const orgStagePos = await this.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id,
  368. {pid: this._.map(datas, 'pid')});
  369. const bills = await this.ctx.service.ledger.getAllDataByCondition({where: {id: result.ledger}});
  370. for (const b of bills) {
  371. b.precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, b.unit);
  372. }
  373. const updatePosStage = [], insertPosStage = [];
  374. for (const d of datas) {
  375. const b = this._.find(bills, {id: d.lid});
  376. const osp = this._.find(orgStagePos, function (p) { return p.pid === d.pid; });
  377. if (osp && osp.times === this.ctx.stage.curTimes && osp.order === this.ctx.stage.curOrder) {
  378. const sp = { id: osp.id, pid: osp.pid, said: this.ctx.session.sessionUser.accountId };
  379. if (d.contract_qty !== undefined) {
  380. sp.contract_qty = this.ctx.helper.round(d.contract_qty, b.precision.value);
  381. }
  382. sp.contract_expr = d.contract_expr;
  383. updatePosStage.push(sp);
  384. } else {
  385. const sp = {
  386. pid: d.pid, lid: d.lid,
  387. tid: this.ctx.tender.id, sid: this.ctx.stage.id,
  388. said: this.ctx.session.sessionUser.accountId,
  389. times: this.ctx.stage.curTimes, order: this.ctx.stage.curOrder
  390. };
  391. if (d.contract_qty !== undefined || osp) {
  392. sp.contract_qty = d.contract_qty === undefined && osp
  393. ? osp.contract_qty
  394. : this.ctx.helper.round(d.contract_qty, b.precision.value);
  395. sp.contract_expr = d.contract_expr;
  396. }
  397. insertPosStage.push(sp);
  398. }
  399. result.pos.push(d.pid);
  400. }
  401. const updateBillsStage = [], insertBillsStage = [], info = this.ctx.tender.info;
  402. for (const b of bills) {
  403. const stageBills = await this.ctx.service.stageBills.getLastestStageData2(b.tender_id, this.ctx.stage.id, b.id);
  404. const posStage = await this.getLastestStageData2(b.tender_id, this.ctx.stage.id, {lid: b.id});
  405. let contract_qty = 0;
  406. const newPosRange = insertPosStage.filter(x => {return x.lid === b.id});
  407. for (const nps of newPosRange) {
  408. contract_qty = this.ctx.helper.add(contract_qty, nps.contract_qty);
  409. }
  410. for (const ps of posStage) {
  411. const ips = this._.find(insertPosStage, {pid: ps.pid});
  412. if (!ips) {
  413. const ups = this._.find(updatePosStage, {id: ps.id});
  414. contract_qty = this.ctx.helper.add(contract_qty, ups ? ups.contract_qty : ps.contract_qty);
  415. }
  416. }
  417. if (stageBills && stageBills.times === this.ctx.stage.curTimes && stageBills.order === this.ctx.stage.curOrder) {
  418. if (contract_qty === stageBills.contract_qty) continue;
  419. updateBillsStage.push({
  420. id: stageBills.id,
  421. said: this.ctx.session.sessionUser.accountId,
  422. contract_qty: contract_qty,
  423. contract_tp: this.ctx.helper.mul(contract_qty, b.unit_price, info.decimal.tp),
  424. });
  425. } else {
  426. insertBillsStage.push({
  427. tid: this.ctx.tender.id,
  428. lid: b.id,
  429. sid: this.ctx.stage.id,
  430. times: this.ctx.stage.curTimes,
  431. order: this.ctx.stage.curOrder,
  432. said: this.ctx.session.sessionUser.accountId,
  433. contract_qty: contract_qty,
  434. contract_tp: this.ctx.helper.mul(contract_qty, b.unit_price, info.decimal.tp),
  435. })
  436. }
  437. }
  438. const transaction = await this.db.beginTransaction();
  439. try {
  440. if (updatePosStage.length > 0) await transaction.updateRows(this.tableName, updatePosStage);
  441. if (insertPosStage.length > 0) await transaction.insert(this.tableName, insertPosStage);
  442. if (updateBillsStage.length > 0) await transaction.updateRows(this.ctx.service.stageBills.tableName, updateBillsStage);
  443. if (insertBillsStage.length > 0) await transaction.insert(this.ctx.service.stageBills.tableName, insertBillsStage);
  444. await transaction.commit();
  445. return result;
  446. } catch (err) {
  447. await transaction.rollback();
  448. throw err;
  449. }
  450. }
  451. /**
  452. * 删除部位明细数据(仅供updateStageData调用)
  453. *
  454. * @param transaction - 事务
  455. * @param data - 删除的部位明细(允许一次提醒多条,也允许跨清单(但前端操作不允许))
  456. * @returns {Promise<{}>}
  457. * @private
  458. */
  459. async _deleteStagePosData(data) {
  460. const pos = await this.ctx.service.pos.getPosData({tid: this.ctx.tender.id, id: data});
  461. const result = { pos: data, isDeletePos: true };
  462. if (pos instanceof Array) {
  463. for (const p of pos) {
  464. if (p.add_stage !== this.ctx.stage.id /*|| p.add_times !== this.ctx.stage.curTimes || p.add_user !== this.ctx.session.sessionUser.accountId*/) {
  465. throw '不可删除该数据';
  466. }
  467. if (p.lid !== pos[0].lid) {
  468. throw '提交数据错误';
  469. }
  470. }
  471. } else if (pos.add_stage !== this.ctx.stage.id /*|| pos.add_times !== this.ctx.stage.curTimes || pos.add_user !== this.ctx.session.sessionUser.accountId*/) {
  472. throw '不可删除该数据';
  473. }
  474. const transaction = await this.db.beginTransaction();
  475. try {
  476. // 删除部位明细
  477. await transaction.delete(this.ctx.service.pos.tableName, {tid: this.ctx.tender.id, id: data});
  478. // 删除部位明细计量数据
  479. await transaction.delete(this.tableName, {tid: this.ctx.tender.id, lid: data});
  480. await this.ctx.service.stageBills.calc(this.ctx.tender.id, this.ctx.stage.id, pos[0].lid, transaction);
  481. await transaction.commit();
  482. // 获取需要更新的数据
  483. result.ledger = [pos[0].lid];
  484. result.stageUpdate = true;
  485. return result;
  486. } catch (err) {
  487. await transaction.rollback();
  488. throw err;
  489. }
  490. }
  491. /**
  492. * 根据前端提交数据,更新并计算
  493. *
  494. * @param data
  495. * @returns {Promise<{ledger: {}, pos: {}}>}
  496. */
  497. async updateStageData(data) {
  498. if ((data.updateType === 'add' || data.upateType === 'delete') && this.ctx.tender.measure_type === measureType.tz) {
  499. throw '台账模式下,不可在计量中新增或删除部位明细,如需操作,请进行台账修订';
  500. }
  501. let refreshData;
  502. if (data.updateType === 'add') {
  503. refreshData = await this._addStagePosData(data.updateData);
  504. } else if (data.updateType === 'update') {
  505. refreshData = await this._updateStagePosData(data.updateData);
  506. } else if (data.updateType === 'batchUpdate') {
  507. refreshData = await this._batchUpdateStagePosData(data.updateData);
  508. } else if (data.updateType === 'delete') {
  509. if (!data.updateData || data.updateData.length === 0) {
  510. throw '提交数据错误';
  511. }
  512. refreshData = await this._deleteStagePosData(data.updateData);
  513. } else {
  514. throw '提交数据错误';
  515. }
  516. try {
  517. const result = {ledger: {}, pos: {}};
  518. if (refreshData.ledger && refreshData.ledger.length > 0) {
  519. result.ledger.bills = await this.ctx.service.ledger.getDataByIds(refreshData.ledger);
  520. if (refreshData.stageUpdate) {
  521. result.ledger.curStageData = await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, refreshData.ledger);
  522. }
  523. }
  524. if (refreshData.pos) {
  525. if (refreshData.isDeletePos) {
  526. result.pos.pos = refreshData.pos;
  527. } else if (refreshData.pos.length > 0) {
  528. result.pos.pos = await this.ctx.service.pos.getPosDataWithAddStageOrder({tid: this.ctx.tender.id, id: refreshData.pos});
  529. if (refreshData.stageUpdate) {
  530. result.pos.curStageData = await this.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, {pid: refreshData.pos});
  531. }
  532. }
  533. }
  534. return result;
  535. } catch(err) {
  536. throw '获取数据异常,请刷新页面。';
  537. }
  538. }
  539. async updateChangeQuantity(transaction, pos, qty, noValue, positiveQty, negativeQty) {
  540. let orgPos = await this.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id, {pid: pos.id});
  541. if (orgPos.length > 1) {
  542. throw '数据错误';
  543. } else {
  544. orgPos = orgPos[0];
  545. }
  546. if (orgPos && orgPos.times === this.ctx.stage.curTimes && orgPos.order === this.ctx.stage.curOrder) {
  547. await transaction.update(this.tableName, noValue
  548. ? { id: orgPos.id, qc_minus_qty: qty || 0, said: this.ctx.session.sessionUser.accountId, }
  549. : { id: orgPos.id, qc_qty: qty, positive_qc_qty: positiveQty, negative_qc_qty: negativeQty, said: this.ctx.session.sessionUser.accountId }
  550. );
  551. } else {
  552. await transaction.insert(this.tableName, {
  553. tid: this.ctx.tender.id,
  554. sid: this.ctx.stage.id,
  555. lid: pos.lid,
  556. pid: pos.id,
  557. said: this.ctx.session.sessionUser.accountId,
  558. times: this.ctx.stage.curTimes,
  559. order: this.ctx.stage.curOrder,
  560. contract_qty: orgPos ? orgPos.contract_qty : 0,
  561. qc_qty: !noValue ? qty : (orgPos ? orgPos.qc_qty : 0),
  562. qc_minus_qty: noValue ? qty : (orgPos ? orgPos.qc_minus_qty : 0),
  563. positive_qc_qty: !noValue ? positiveQty : (orgPos ? orgPos.positive_qc_qty : 0),
  564. negative_qc_qty: !noValue ? negativeQty : (orgPos ? orgPos.negative_qc_qty : 0),
  565. });
  566. }
  567. await this.ctx.service.stageBills.calc(this.ctx.tender.id, this.ctx.stage.id, pos.lid, transaction);
  568. }
  569. /**
  570. * 统计清单下部位明细合计
  571. * @param {Number} tid - 标段id
  572. * @param {Number} sid - 期id
  573. * @param {Number} lid - 清单节点id
  574. * @param transaction - 事务(不为空则在事务中查询,反之在数据库中查询)
  575. * @returns {Promise<*>}
  576. */
  577. async getPosGather(tid, sid, lid, transaction) {
  578. const calcQtySql = 'SELECT SUM(`contract_qty`) As `contract_qty`, SUM(`qc_qty`) As `qc_qty`, SUM(`qc_minus_qty`) AS `qc_minus_qty`, SUM(`positive_qc_qty`) As `positive_qc_qty`, SUM(`negative_qc_qty`) As `negative_qc_qty` FROM (' +
  579. ' SELECT `contract_qty`, `qc_qty`, `qc_minus_qty`, `positive_qc_qty`, `negative_qc_qty` FROM ' + this.ctx.service.stagePos.tableName + ' As Pos ' +
  580. ' INNER JOIN (' +
  581. ' SELECT MAX(`times` * ' + timesLen + ' + `order`) As `flow`, `pid` ' +
  582. ' FROM ' + this.ctx.service.stagePos.tableName +
  583. ' WHERE `tid` = ? And sid = ? And `lid` = ? ' +
  584. ' GROUP BY `pid`' +
  585. ' ) As MaxFilter ' +
  586. ' ON (Pos.times * ' + timesLen + ' + Pos.order) = MaxFilter.flow And Pos.pid = MaxFilter.pid ' +
  587. ' WHERE Pos.tid = ? And Pos.sid = ? And Pos.lid = ?' +
  588. ' ) As Gather';
  589. const param = [tid, sid, lid];
  590. const sqlParam = param.concat(param);
  591. if (transaction) {
  592. return await transaction.queryOne(calcQtySql, sqlParam);
  593. } else {
  594. return await this.db.queryOne(calcQtySql, sqlParam);
  595. }
  596. }
  597. /**
  598. * 多期清单数据整合 (材料调差调用)
  599. * @param {Number} tid - 标段id
  600. * @param {String} stage_id_list - 期id列表
  601. * @param {String} comefrom - 来源(部分不调用计量不获取)
  602. * @returns {Promise<void>}
  603. */
  604. async getStagesData(tid, stage_id_list, comefrom = '') {
  605. const sids = stage_id_list.split(',');
  606. const result = [];
  607. for (const sid of sids) {
  608. const sql = 'SELECT id, tid, sid, pid, lid, contract_qty, qc_qty, `qc_minus_qty`, postil, `times`, `order`, `contract_expr`' +
  609. ' FROM ' + this.tableName +
  610. ' WHERE tid = ? And sid = ? ';
  611. const sqlParam = [tid, sid];
  612. const stagePos = await this.db.query(sql, sqlParam);
  613. const stagePosFilter = this._filterLastestData(stagePos);
  614. for (const sp of stagePosFilter) {
  615. const rsp = result.find(function (x) { return x.pid === sp.pid});
  616. if (rsp) {
  617. rsp.contract_qty = this.ctx.helper.add(rsp.contract_qty, sp.contract_qty);
  618. rsp.qc_qty = this.ctx.helper.add(rsp.qc_qty, sp.qc_qty);
  619. rsp.qc_minus_qty = this.ctx.helper.add(rsp.qc_minus_qty, sp.qc_minus_qty);
  620. } else if (!comefrom || (comefrom === 'list' && (sp.contract_qty || sp.qc_qty || sp.qc_minus_qty))) {
  621. result.push({
  622. id: sp.id, tid: sp.tid, lid: sp.lid, pid: sp.pid,
  623. contract_qty: sp.contract_qty, qc_qty: sp.qc_qty, qc_minus_qty: sp.qc_minus_qty,
  624. });
  625. }
  626. }
  627. }
  628. return result;
  629. }
  630. /**
  631. * 获取多期(合同和数量变更相加)计量-小计(材料调差调用)
  632. * @param {Number} tid - 标段id
  633. * @param {String} stage_id_list - 期id列表
  634. * @param {String} lid - 台账id
  635. * @param {String} pid - 部位id
  636. * @returns {Promise<void>}
  637. */
  638. async getGatherQtyByMaterial(tid, stage_id_list, lid, pid) {
  639. stage_id_list = stage_id_list !== null ? stage_id_list.split(',') : [];
  640. const qtys = {
  641. gather_qty: 0,
  642. contract_qty: 0,
  643. qc_qty: 0,
  644. qc_minus_qty: 0,
  645. };
  646. for (const sid of stage_id_list) {
  647. const sql = 'SELECT Pos.contract_qty, Pos.qc_qty FROM ' +
  648. ' (SELECT * FROM ' + this.tableName + ' WHERE tid = ? AND sid = ?) As Pos ' +
  649. ' INNER JOIN ( ' +
  650. ' SELECT MAX(`times` * ' + timesLen + ' + `order`) As `flow`, `tid`, `sid`, `pid` From ' + this.tableName +
  651. ' WHERE `tid` = ? AND sid = ?' +
  652. ' GROUP BY `pid`' +
  653. ' ) As MaxFilter ' +
  654. ' ON (Pos.times * ' + timesLen + ' + Pos.order) = MaxFilter.flow And Pos.pid = MaxFilter.pid And Pos.sid = MaxFilter.sid' +
  655. ' WHERE Pos.lid = ? AND Pos.pid = ?';
  656. const sqlParam = [tid, sid, tid, sid, lid, pid];
  657. const result = await this.db.queryOne(sql, sqlParam);
  658. if (result) {
  659. qtys.contract_qty = this.ctx.helper.add(qtys.contract_qty, result.contract_qty);
  660. qtys.qc_qty = this.ctx.helper.add(qtys.qc_qty, result.qc_qty);
  661. qtys.qc_minus_qty = this.ctx.helper.add(qtys.qc_minus_qty, result.qc_minus_qty);
  662. qtys.gather_qty = this.ctx.helper.add(qtys.gather_qty, this.ctx.helper.add(result.contract_qty, result.qc_qty));
  663. }
  664. }
  665. return this.ctx.helper.resetQtys(qtys);
  666. }
  667. }
  668. return StagePos;
  669. };