stage_stash.js 16 KB

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