stage_stash.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date
  7. * @version
  8. */
  9. class loadStageExcelTree {
  10. constructor(ctx) {
  11. this.ctx = ctx;
  12. this.decimal = ctx.tender.info.decimal;
  13. this.settleStatus = ctx.service.settle.settleStatus;
  14. this.insertBills = [];
  15. this.insertPos = [];
  16. this.updateBills = [];
  17. this.updatePos = [];
  18. this.insertDgn = [];
  19. this.updateDgn = [];
  20. }
  21. init(source) {
  22. this.default = source.default;
  23. const LedgerModel = require('../lib/ledger');
  24. this.ledgerTree = new LedgerModel.billsTree(this.ctx, {
  25. id: 'ledger_id', pid: 'ledger_pid', order: 'order', level: 'level', rootId: -1, calcFields: [],
  26. });
  27. this.pos = new LedgerModel.pos({ id: 'id', ledgerId: 'lid' });
  28. this.ledgerTree.loadDatas(source.ledgerData);
  29. this.pos.loadDatas(source.posData);
  30. this.stageBills = source.stageBills;
  31. this.stagePos = source.stagePos;
  32. this.stageBillsDgn = source.stageBillsDgn;
  33. }
  34. findNode(node, parent) {
  35. const _ = this.ctx.helper._;
  36. const sibling = parent ? parent.children : this.ledgerTree.children;
  37. const self = this;
  38. return sibling.find(x => {
  39. if (node.is_leaf !== x.is_leaf) return false;
  40. if (node.b_code) {
  41. if (x.has_pos === undefined) {
  42. const relaPos = self.pos.getLedgerPos(x.id);
  43. x.has_pos = !!relaPos && relaPos.length > 0;
  44. }
  45. return node.b_code === _.trimEnd(x.b_code) && node.name === _.trimEnd(x.name) && node.unit === _.trimEnd(x.unit)
  46. && node.unit_price === x.unit_price && node.has_pos === x.has_pos;
  47. } else {
  48. return node.code === _.trimEnd(x.code) && node.name === _.trimEnd(x.name);
  49. }
  50. });
  51. }
  52. loadLeaf(node, source) {
  53. const curStageBills = this.stageBills.find(csb => { return csb.lid === source.id; });
  54. if (node.has_pos) {
  55. const sourcePos = this.pos.getLedgerPos(source.id);
  56. const sourceStagePos = this.stagePos.filter(sp => { return sp.lid === source.id; });
  57. let contract_qty = 0;
  58. for (const p of node.pos) {
  59. if (!p.contract_qty) continue;
  60. const sp = sourcePos.find(x => { return x.name === p.name; });
  61. if (!sp || sp.settle_status === this.settleStatus.finish) continue;
  62. contract_qty = this.ctx.helper.add(contract_qty, p.contract_qty);
  63. let ssp = sourceStagePos.find(x => { return x.pid === sp.id; });
  64. if (ssp) {
  65. this.updatePos.push({ id: ssp.id, contract_qty: p.contract_qty, postil: p.postil || ssp.postil || '' });
  66. sourceStagePos.splice(sourceStagePos.indexOf(ssp), 1);
  67. } else {
  68. this.insertPos.push({
  69. tid: this.default.tid, sid: this.default.sid, said: this.default.said, times: 1, order: 0,
  70. lid: source.id, pid:sp.id, contract_qty: p.contract_qty, postil: p.postil || ''
  71. });
  72. }
  73. }
  74. for (const ssp of sourceStagePos) {
  75. contract_qty = this.ctx.helper.add(contract_qty, ssp.contract_qty);
  76. }
  77. const contract_tp = this.ctx.helper.mul(contract_qty, source.unit_price, this.decimal.tp);
  78. if (curStageBills) {
  79. this.updateBills.push({ id: curStageBills.id, contract_qty, contract_tp, postil: node.postil || curStageBills.postil || '' });
  80. } else {
  81. if (contract_qty) this.insertBills.push({
  82. tid: this.default.tid, sid: this.default.sid, said: this.default.said, times: 1, order: 0,
  83. lid: source.id, contract_qty, contract_tp, postil: node.postil || ''
  84. });
  85. }
  86. } else {
  87. if (!node.contract_qty && !node.contract_tp) return;
  88. const contract_qty = source.is_tp ? 0 : node.contract_qty;
  89. const contract_tp = contract_qty
  90. ? this.ctx.helper.mul(contract_qty, source.unit_price, this.decimal.tp)
  91. : source.is_tp ? this.ctx.helper.round(node.contract_tp, this.decimal.tp) : 0;
  92. if (curStageBills) {
  93. this.updateBills.push({ id: curStageBills.id, contract_qty: contract_qty, contract_tp: contract_tp, postil: node.postil || curStageBills.postil || '' });
  94. } else {
  95. this.insertBills.push({
  96. tid: this.default.tid, sid: this.default.sid, said: this.default.said, times: 1, order: 0,
  97. lid: source.id, contract_qty: contract_qty, contract_tp: contract_tp, postil: node.postil || ''
  98. });
  99. }
  100. }
  101. }
  102. loadDgn(node, cur) {
  103. if (!node.deal_dgn_qty1 && !node.deal_dgn_qty2 && !node.c_dgn_qty1 && !node.c_dgn_qty2) return;
  104. const dgn = this.stageBillsDgn.find(x => { return x.id === cur.id; });
  105. if (dgn) {
  106. this.updateDgn.push({ id: cur.id, deal_dgn_qty1: node.deal_dgn_qty1, deal_dgn_qty2: node.deal_dgn_qty2, c_dgn_qty1: node.c_dgn_qty1, c_dgn_qty2: node.c_dgn_qty2 });
  107. } else {
  108. this.insertDgn.push({ id: cur.id, tid: this.default.tid, deal_dgn_qty1: node.deal_dgn_qty1, deal_dgn_qty2: node.deal_dgn_qty2, c_dgn_qty1: node.c_dgn_qty1, c_dgn_qty2: node.c_dgn_qty2 });
  109. }
  110. }
  111. loadNode(node, parent) {
  112. node.is_leaf = !node.children || node.children.length === 0 ? 1 : 0;
  113. node.has_pos = node.pos && node.pos.length > 0;
  114. const cur = this.findNode(node, parent);
  115. if (!cur || cur.settle_status === this.settleStatus.finish) return;
  116. if (cur) {
  117. if (!node.b_code) this.loadDgn(node, cur);
  118. if (node.is_leaf) {
  119. this.loadLeaf(node, cur);
  120. } else {
  121. for (const c of node.children) {
  122. this.loadNode(c, cur);
  123. }
  124. }
  125. }
  126. }
  127. load(excelTree, source) {
  128. this.init(source);
  129. for (const node of excelTree.roots) {
  130. this.loadNode(node, null);
  131. }
  132. }
  133. }
  134. module.exports = app => {
  135. class StageStash extends app.BaseService {
  136. /**
  137. * 构造函数
  138. *
  139. * @param {Object} ctx - egg全局变量
  140. * @return {void}
  141. */
  142. constructor(ctx) {
  143. super(ctx);
  144. this.tableName = 'stage_stash';
  145. }
  146. async getValidStash(tid) {
  147. const sql = `SELECT id, sorder, create_time, uid, uname, remark FROM ${this.tableName} WHERE tid = ? and valid and TO_DAYS(NOW()) - TO_DAYS(create_time) <= 30 ORDER BY create_time DESC`;
  148. return await this.db.query(sql, [tid]);
  149. }
  150. async addStash(stage, remark = '') {
  151. const bills = await this.ctx.service.stageBills.getLastestStageData2(stage.tid, stage.id);
  152. const pos = await this.ctx.service.stagePos.getLastestStageData2(stage.tid, stage.id);
  153. const change = await this.ctx.service.stageChange.getFinalStageData(stage.tid, stage.id);
  154. const timestamp = (new Date()).getTime();
  155. const filepath = `${this.ctx.session.sessionProject.id}-${stage.tid}-${timestamp}.json`;
  156. await this.ctx.hisOss.put(this.ctx.stashOssPath + filepath, Buffer.from(JSON.stringify({bills, pos, change}), 'utf8'));
  157. const result = await this.db.insert(this.tableName, {
  158. pid: this.ctx.session.sessionProject.id, tid: stage.tid, sid: stage.id, sorder: stage.order,
  159. uid: this.ctx.session.sessionUser.accountId, uname: this.ctx.session.sessionUser.name,
  160. filepath, info: JSON.stringify({ status: stage.status, flow: stage.curAuditorIds.length > 0 ? stage.curAuditorIds : stage.uid }), remark
  161. });
  162. return result.insertId;
  163. }
  164. async delStash(id) {
  165. const stash = await this.getDataById(id);
  166. if (!stash) throw '暂存计量不存在';
  167. if (stash.tid !== this.ctx.tender.id) throw '非当前标段暂存计量,不可操作';
  168. await this.deleteById(id);
  169. await this.ctx.hisOss.delete(this.ctx.stashOssPath + stash.filepath);
  170. }
  171. async loadLedgerDataFromOss(filepath) {
  172. const File = await this.ctx.hisOss.get(this.ctx.stashOssPath + filepath);
  173. if (File.res.status !== 200) return '获取暂存计量有误';
  174. const result = JSON.parse(File.content);
  175. return result;
  176. }
  177. async loadAndAnalysis(filepath) {
  178. const data = await this.loadLedgerDataFromOss(filepath);
  179. const billsIndex = {};
  180. for (const b of data.bills) {
  181. billsIndex[b.lid] = b;
  182. }
  183. for (const p of data.pos) {
  184. if (!billsIndex[p.lid]) continue;
  185. if (!billsIndex[p.lid].pos) billsIndex[p.lid].pos = [];
  186. billsIndex[p.lid].pos.push(p);
  187. }
  188. for (const c of data.change) {
  189. if (!billsIndex[c.lid]) continue;
  190. if (billsIndex[c.lid].pos) {
  191. const p = billsIndex[c.lid].pos.find(x => { return x.pid === c.pid });
  192. if (!p) continue;
  193. if (!p.change) p.change = [];
  194. p.change.push(c);
  195. } else {
  196. if (!billsIndex[c.lid].change) billsIndex[c.lid].change = [];
  197. billsIndex[c.lid].change.push(c);
  198. }
  199. }
  200. return data.bills;
  201. }
  202. async reCalcStashData(stage, data) {
  203. const decimal = this.ctx.tender.info.decimal;
  204. const insertBillsData = [], insertPosData = [], insertChangeData = [];
  205. const settleStatus = this.ctx.service.settle.settleStatus;
  206. const bills = await this.ctx.service.ledger.getAllDataByCondition({ where: { tender_id: stage.tid, is_leaf: true } });
  207. const extraData = await this.ctx.service.ledgerExtra.getData(stage.tid, ['id', 'is_tp']);
  208. const settleStatusBills = stage.readySettle ? await this.ctx.service.settleBills.getAllDataByCondition({ where: { settle_id: stage.readySettle.id }}) : [];
  209. this.ctx.helper.assignRelaData(bills, [
  210. { data: extraData, fields: ['is_tp'], prefix: '', relaId: 'id' },
  211. { data: settleStatusBills, fields: ['settle_status'], prefix: '', relaId: 'lid' },
  212. ]);
  213. const pos = await this.ctx.service.pos.getAllDataByCondition({ where: { tid: stage.tid } });
  214. const settleStatusPos = stage.readySettle ? await this.ctx.service.settlePos.getAllDataByCondition({ where: { settle_id: stage.readySettle.id }}) : [];
  215. this.ctx.helper.assignRelaData(pos, [
  216. { data: settleStatusPos, fields: ['settle_status'], prefix: '', relaId: 'pid' },
  217. ]);
  218. const said = this.ctx.session.sessionUser.accountId;
  219. for (const d of data) {
  220. const b = bills.find(x => { return x.id === d.lid });
  221. if (!b || b.settle_status === settleStatus.finish) continue;
  222. const nbs = {
  223. tid: stage.tid, sid: stage.id, said, lid: b.id, times: 1, order: 0,
  224. contract_qty: 0, qc_qty: 0, qc_minus_qty: 0, positive_qc_qty: 0, negative_qc_qty: 0,
  225. contract_tp: 0, qc_tp: 0, positive_qc_tp: 0, negative_qc_tp: 0
  226. };
  227. if (d.pos) {
  228. for (const bp of d.pos) {
  229. const p = pos.find(x => { return x.id === bp.pid});
  230. if (!p || p.settle_status === settleStatus.finish) continue;
  231. const nps = { tid: stage.tid, sid: stage.id, said, lid: b.id, pid: p.id, times: 1, order: 0 };
  232. nps.contract_qty = this.ctx.helper.round(bp.contract_qty, decimal.qty);
  233. nps.qc_qty = 0;
  234. nps.qc_minus_qty = 0;
  235. nps.positive_qc_qty = 0;
  236. nps.negative_qc_qty = 0;
  237. insertPosData.push(nps);
  238. if (bp.change) {
  239. for (const c of bp.change) {
  240. if (!c.qty) continue;
  241. const ncs = { tid: stage.tid, sid: stage.id, lid: b.id, pid: p.id, stimes: 1, sorder: 0, cid: c.cid, cbid: c.cbid, minus: c.minus, no_value: c.no_value };
  242. const validQty = await this.ctx.service.stageChangeFinal.getChangeBillsValidQty(c.cbid);
  243. ncs.qty = ncs.minus ? Math.max(validQty, c.qty) : Math.min(validQty, c.qty);
  244. insertChangeData.push(ncs);
  245. if (!ncs.no_value) {
  246. nps.qc_qty = this.ctx.helper.add(nps.qc_qty, ncs.qty);
  247. if (ncs.minus) {
  248. nps.negative_qc_qty = this.ctx.helper.add(nps.negative_qc_qty, ncs.qty);
  249. } else {
  250. nps.positive_qc_qty = this.ctx.helper.add(nps.positive_qc_qty, ncs.qty);
  251. }
  252. } else {
  253. nps.qc_minus_qty = this.ctx.helper.add(nps.qc_minus_qty, ncs.qty);
  254. }
  255. }
  256. }
  257. nbs.contract_qty = this.ctx.helper.add(nbs.contract_qty, nps.contract_qty);
  258. nbs.qc_qty = this.ctx.helper.add(nbs.qc_qty, nps.qc_qty);
  259. nbs.qc_minus_qty = this.ctx.helper.add(nbs.qc_minus_qty, nps.qc_minus_qty);
  260. nbs.positive_qc_qty = this.ctx.helper.add(nbs.positive_qc_qty, nps.positive_qc_qty);
  261. nbs.negative_qc_qty = this.ctx.helper.add(nbs.negative_qc_qty, nps.negative_qc_qty);
  262. }
  263. nbs.contract_tp = this.ctx.helper.mul(nbs.contract_qty, b.unit_price, decimal.tp);
  264. nbs.qc_tp = this.ctx.helper.mul(nbs.qc_qty, b.unit_price, decimal.tp);
  265. nbs.positive_qc_tp = this.ctx.helper.mul(nbs.positive_qc_qty, b.unit_price, decimal.tp);
  266. nbs.negative_qc_tp = this.ctx.helper.mul(nbs.negative_qc_qty, b.unit_price, decimal.tp);
  267. } else {
  268. if (b.is_tp) {
  269. nbs.contract_tp = this.ctx.helper.round(d.contract_tp, decimal.tp);
  270. } else {
  271. nbs.contract_qty = this.ctx.helper.round(d.contract_qty, decimal.qty);
  272. nbs.contract_tp = this.ctx.helper.mul(nbs.contract_qty, b.unit_price, decimal.tp);
  273. if (d.change) {
  274. for (const c of d.change) {
  275. if (!c.qty) continue;
  276. const ncs = { tid: stage.tid, sid: stage.id, lid: b.id, pid: -1, stimes: 1, sorder: 0, cid: c.cid, cbid: c.cbid, minus: c.minus, no_value: c.no_value };
  277. const validQty = await this.ctx.service.stageChangeFinal.getChangeBillsValidQty(c.cbid);
  278. ncs.qty = ncs.minus ? Math.max(validQty, c.qty) : Math.min(validQty, c.qty);
  279. insertChangeData.push(ncs);
  280. if (!ncs.no_value) {
  281. nbs.qc_qty = this.ctx.helper.add(nbs.qc_qty, ncs.qty);
  282. if (ncs.minus) {
  283. nbs.negative_qc_qty = this.ctx.helper.add(nbs.negative_qc_qty, ncs.qty);
  284. } else {
  285. nbs.positive_qc_qty = this.ctx.helper.add(nbs.positive_qc_qty, ncs.qty);
  286. }
  287. } else {
  288. nbs.qc_minus_qty = this.ctx.helper.add(nbs.qc_minus_qty, ncs.qty);
  289. }
  290. }
  291. }
  292. nbs.qc_tp = this.ctx.helper.mul(nbs.qc_qty, b.unit_price, decimal.tp);
  293. nbs.positive_qc_tp = this.ctx.helper.mul(nbs.positive_qc_qty, b.unit_price, decimal.tp);
  294. nbs.negative_qc_tp = this.ctx.helper.mul(nbs.negative_qc_qty, b.unit_price, decimal.tp);
  295. }
  296. }
  297. insertBillsData.push(nbs);
  298. }
  299. return [insertBillsData, insertPosData, insertChangeData]
  300. }
  301. async recover(stage, id) {
  302. const stash = await this.getDataById(id);
  303. if (!stash) throw '暂存计量不存在';
  304. if (stash.tid !== stage.tid) throw '暂存计量不可导入';
  305. const stashData = await this.loadAndAnalysis(stash.filepath);
  306. const [insertBills, insertPos, insertChange] = await this.reCalcStashData(stage, stashData);
  307. const conn = await this.db.beginTransaction();
  308. try {
  309. await conn.delete(this.ctx.service.stageBills.tableName, { sid: stage.id });
  310. await conn.delete(this.ctx.service.stageChange.tableName, { sid: stage.id });
  311. await conn.delete(this.ctx.service.stagePos.tableName, { sid: stage.id });
  312. if (insertBills.length > 0) conn.insert(this.ctx.service.stageBills.tableName, insertBills);
  313. if (insertPos.length > 0) conn.insert(this.ctx.service.stagePos.tableName, insertPos);
  314. if (insertChange.length > 0) conn.insert(this.ctx.service.stageChange.tableName, insertChange);
  315. await conn.commit();
  316. } catch (err) {
  317. await conn.rollback();
  318. throw err;
  319. }
  320. };
  321. /**
  322. * 导入Excel期计量(仅导入合同计量)
  323. * 该方法本应该独立或者在stage下,但是跟stage_stash业务非常类似,暂归类于此
  324. * @param stage
  325. * @param sheet
  326. * @returns {Promise<void>}
  327. */
  328. async loadExcelSheet(stage, excelData) {
  329. const AnalysisExcel = require('../lib/analysis_excel').AnalysisStageExcelTree;
  330. const analysisExcel = new AnalysisExcel(this.ctx, this.ctx.service.ledger.setting);
  331. try {
  332. const templateId = await this.ctx.service.valuation.getValuationTemplate(
  333. this.ctx.tender.data.valuation, this.ctx.tender.data.measure_type);
  334. const tempData = await this.ctx.service.tenderNodeTemplate.getData(templateId, true);
  335. const cacheTree = analysisExcel.analysisData(excelData, tempData, { filterZeroGcl: false });
  336. const ledgerData = await this.ctx.service.ledger.getAllDataByCondition({
  337. columns: ['id', 'ledger_id', 'ledger_pid', 'level', 'order', 'full_path', 'is_leaf', 'code', 'b_code', 'name', 'unit', 'unit_price'],
  338. where: { tender_id: stage.tid},
  339. });
  340. const extraData = await this.ctx.service.ledgerExtra.getData(this.ctx.tender.id, ['is_tp']);
  341. const settleStatusBills = stage.readySettle ? await this.ctx.service.settleBills.getAllDataByCondition({ where: { settle_id: stage.readySettle.id }}) : [];
  342. this.ctx.helper.assignRelaData(ledgerData, [
  343. { data: extraData, fields: ['is_tp'], prefix: '', relaId: 'id' },
  344. { data: settleStatusBills, fields: ['settle_status'], prefix: '', relaId: 'lid' },
  345. ]);
  346. const posData = await this.ctx.service.pos.getAllDataByCondition({
  347. columns: ['id', 'lid', 'name', 'porder'],
  348. where: { tid: stage.tid },
  349. });
  350. const settleStatusPos = stage.readySettle ? await this.ctx.service.settlePos.getAllDataByCondition({ where: { settle_id: stage.readySettle.id }}) : [];
  351. this.ctx.helper.assignRelaData(posData, [
  352. { data: settleStatusPos, fields: ['settle_status'], prefix: '', relaId: 'pid' },
  353. ]);
  354. const stageBills = await this.ctx.service.stageBills.getAllDataByCondition({ where: { sid: stage.id } });
  355. const stagePos = await this.ctx.service.stagePos.getAllDataByCondition({ where: { sid: stage.id } });
  356. const stageBillsDgn = await this.ctx.service.stageBillsDgn.getAllDataByCondition({ where: { tid: stage.tid } });
  357. const loadModal = new loadStageExcelTree(this.ctx);
  358. loadModal.load(cacheTree, { ledgerData, posData, stageBills, stagePos, stageBillsDgn, default: { tid: stage.tid, sid: stage.id, said: this.ctx.session.sessionUser.accountId } });
  359. const conn = await this.db.beginTransaction();
  360. try {
  361. if (loadModal.insertBills.length > 0) conn.insert(this.ctx.service.stageBills.tableName, loadModal.insertBills);
  362. if (loadModal.updateBills.length > 0) conn.updateRows(this.ctx.service.stageBills.tableName, loadModal.updateBills);
  363. if (loadModal.insertPos.length > 0) conn.insert(this.ctx.service.stagePos.tableName, loadModal.insertPos);
  364. if (loadModal.updatePos.length > 0) conn.updateRows(this.ctx.service.stagePos.tableName, loadModal.updatePos);
  365. if (loadModal.insertDgn.length > 0) conn.insert(this.ctx.service.stageBillsDgn.tableName, loadModal.insertDgn);
  366. if (loadModal.updateDgn.length > 0) conn.updateRows(this.ctx.service.stageBillsDgn.tableName, loadModal.updateDgn);
  367. await conn.commit();
  368. } catch (err) {
  369. await conn.rollback();
  370. this.ctx.log(err);
  371. throw '保存导入数据失败';
  372. }
  373. } catch (err) {
  374. this.ctx.log(err);
  375. throw '解析Excel错误';
  376. }
  377. }
  378. }
  379. return StageStash;
  380. };