stage_stash.js 20 KB

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