stage_stash.js 17 KB

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