base_budget_service.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date
  7. * @version
  8. */
  9. const TreeService = require('./base_tree_service');
  10. const billsUtils = require('../lib/bills_utils');
  11. const readOnlyFields = ['id', 'bid', 'tree_id', 'tree_pid', 'order', 'level', 'full_path', 'is_leaf'];
  12. const calcFields = ['unit_price', 'quantity', 'total_price'];
  13. class BaseBudget extends TreeService {
  14. /**
  15. * 构造函数
  16. *
  17. * @param {Object} ctx - egg全局变量
  18. * @param {String} tableName - 表名
  19. * @return {void}
  20. */
  21. constructor(ctx, setting, tablename) {
  22. super(ctx, {
  23. mid: 'bid',
  24. kid: 'tree_id',
  25. pid: 'tree_pid',
  26. order: 'order',
  27. level: 'level',
  28. isLeaf: 'is_leaf',
  29. fullPath: 'full_path',
  30. keyPre: setting.keyPre,
  31. uuid: true,
  32. });
  33. this.tableName = tablename;
  34. }
  35. async initByTemplate(conn, budgetId, templateId) {
  36. if (budgetId <= 0) throw '概算项目id错误';
  37. const data = await this.ctx.service.tenderNodeTemplate.getData(templateId);
  38. if (!data.length) throw '模板数据有误';
  39. // 整理数据
  40. const insertData = [];
  41. for (const tmp of data) {
  42. insertData.push({
  43. id: this.uuid.v4(),
  44. bid: budgetId,
  45. tree_id: tmp.template_id,
  46. tree_pid: tmp.pid,
  47. level: tmp.level,
  48. order: tmp.order,
  49. full_path: tmp.full_path,
  50. is_leaf: tmp.is_leaf,
  51. code: tmp.code,
  52. name: tmp.name,
  53. unit: tmp.unit,
  54. node_type: tmp.node_type,
  55. });
  56. }
  57. const operate = conn ? await conn.insert(this.tableName, insertData) : await this.db.insert(this.tableName, insertData);
  58. return operate.affectedRows === data.length;
  59. }
  60. async reInitByTemplate(budgetId, templateId) {
  61. const conn = await this.db.beginTransaction();
  62. try {
  63. await conn.delete(this.tableName, { bid: budgetId });
  64. await this.initByTemplate(conn, budgetId, templateId);
  65. } catch {
  66. await conn.rollback();
  67. }
  68. }
  69. async addChild(budgetId, selectId, data) {
  70. if ((budgetId <= 0) || (selectId <= 0)) return [];
  71. const selectData = await this.getDataByKid(budgetId, selectId);
  72. if (!selectData) {
  73. throw '新增节点数据错误';
  74. }
  75. const children = await this.getChildrenByParentId(budgetId, selectId);
  76. const maxId = await this._getMaxLid(budgetId);
  77. data.id = this.uuid.v4();
  78. data.bid = budgetId;
  79. data.tree_id = maxId + 1;
  80. data.tree_pid = selectData.tree_id;
  81. data.level = selectData.level + 1;
  82. data.order = children.length + 1;
  83. data.full_path = selectData.full_path + '-' + data.tree_id;
  84. data.is_leaf = true;
  85. this.transaction = await this.db.beginTransaction();
  86. try {
  87. const result = await this.transaction.insert(this.tableName, data);
  88. if (children.length === 0) {
  89. await this.transaction.update(this.tableName,
  90. { is_leaf: false, quantity: 0, unit_price: 0, total_price: 0 },
  91. { where: { bid: budgetId, tree_id: selectData.tree_id } });
  92. }
  93. await this.transaction.commit();
  94. } catch(err) {
  95. await this.transaction.rollback();
  96. throw err;
  97. }
  98. this._cacheMaxLid(budgetId, maxId + 1);
  99. // 查询应返回的结果
  100. const resultData = {};
  101. resultData.create = await this.getDataByKid(budgetId, data.tree_id);
  102. if (children.length === 0) resultData.update = await this.getDataByKid(budgetId, selectId);
  103. return resultData;
  104. }
  105. _filterStdData(stdData) {
  106. const result = {
  107. name: stdData.name,
  108. unit: stdData.unit,
  109. node_type: stdData.node_type,
  110. };
  111. result.code = stdData.code ? stdData.code : '';
  112. result.b_code = stdData.b_code ? stdData.b_code : '';
  113. return result;
  114. }
  115. async _addChildNodeData(budgetId, parentData, data) {
  116. if (budgetId <= 0) return undefined;
  117. if (!data) data = {};
  118. const pid = parentData ? parentData.tree_id : this.rootId;
  119. const maxId = await this._getMaxLid(budgetId);
  120. data.id = this.uuid.v4();
  121. data.bid = budgetId;
  122. data.tree_id = maxId + 1;
  123. data.tree_pid = pid;
  124. if (data.order === undefined) data.order = 1;
  125. data.level = parentData ? parentData.level + 1 : 1;
  126. data.full_path = parentData ? parentData.full_path + '-' + data.tree_id : '' + data.tree_id;
  127. if (data.is_leaf === undefined) data.is_leaf = true;
  128. const result = await this.transaction.insert(this.tableName, data);
  129. this._cacheMaxLid(budgetId, maxId + 1);
  130. return [result, data];
  131. }
  132. async _addChildAutoOrder(budgetId, parentData, data) {
  133. const findPreData = function(list, a) {
  134. if (!list || list.length === 0) { return null; }
  135. for (let i = 0, iLen = list.length; i < iLen; i++) {
  136. if (billsUtils.compareCode(list[i].code, a.code) > 0) {
  137. return i > 0 ? list[i - 1] : null;
  138. }
  139. }
  140. return list[list.length - 1];
  141. };
  142. const pid = parentData ? parentData.tree_id : this.rootId;
  143. const children = await this.getChildrenByParentId(budgetId, pid);
  144. const preData = findPreData(children, data);
  145. if (!preData || children.indexOf(preData) < children.length - 1) {
  146. await this._updateChildrenOrder(budgetId, pid, preData ? preData.order + 1 : 1);
  147. }
  148. data.order = preData ? preData.order + 1 : 1;
  149. const [addResult, node] = await this._addChildNodeData(budgetId, parentData, data);
  150. return [addResult, node];
  151. }
  152. async addStdNodeWithParent(budgetId, stdData, stdLib) {
  153. // 查询完整标准清单,并按层次排序
  154. const fullLevel = await stdLib.getFullLevelDataByFullPath(stdData.list_id, stdData.full_path);
  155. fullLevel.sort(function(x, y) {
  156. return x.level - y.level;
  157. });
  158. let isNew = false,
  159. node,
  160. firstNew,
  161. updateParent,
  162. addResult;
  163. const expandIds = [];
  164. this.transaction = await this.db.beginTransaction();
  165. try {
  166. // 从最顶层节点依次查询是否存在,否则添加
  167. for (let i = 0, len = fullLevel.length; i < len; i++) {
  168. const stdNode = fullLevel[i];
  169. if (isNew) {
  170. const newData = this._filterStdData(stdNode);
  171. newData.is_leaf = (i === len - 1);
  172. [addResult, node] = await this._addChildNodeData(budgetId, node, newData);
  173. } else {
  174. const parent = node;
  175. node = await this.getDataByCondition({
  176. bid: budgetId,
  177. tree_pid: parent ? parent.tree_id : this.rootId,
  178. code: stdNode.code,
  179. name: stdNode.name,
  180. });
  181. if (!node) {
  182. isNew = true;
  183. const newData = this._filterStdData(stdNode);
  184. newData.is_leaf = (i === len - 1);
  185. [addResult, node] = await this._addChildAutoOrder(budgetId, parent, newData);
  186. if (parent && parent.is_leaf) {
  187. await this.transaction.update(this.tableName, { id: parent.id, is_leaf: false,
  188. unit_price: 0, quantity: 0, total_price: 0});
  189. updateParent = parent;
  190. }
  191. firstNew = node;
  192. } else {
  193. expandIds.push(node.tree_id);
  194. }
  195. }
  196. }
  197. await this.transaction.commit();
  198. } catch (err) {
  199. await this.transaction.rollback();
  200. throw err;
  201. }
  202. // 查询应返回的结果
  203. let createData = [],
  204. updateData = [];
  205. if (firstNew) {
  206. createData = await this.getDataByFullPath(budgetId, firstNew.full_path + '%');
  207. updateData = await this.getNextsData(budgetId, firstNew.tree_pid, firstNew.order);
  208. if (updateParent) {
  209. updateData.push(await this.getDataByCondition({ id: updateParent.id }));
  210. }
  211. }
  212. return { create: createData, update: updateData };
  213. }
  214. async addBillsNode(budgetId, selectId, data) {
  215. return await this.addNode(budgetId, selectId, data ? data : {});
  216. }
  217. async addStdNode(budgetId, selectId, stdData) {
  218. const newData = this._filterStdData(stdData);
  219. const result = await this.addBillsNode(budgetId, selectId, newData);
  220. return result;
  221. }
  222. async addStdNodeAsChild(budgetId, selectId, stdData) {
  223. const newData = this._filterStdData(stdData);
  224. const result = await this.addChild(budgetId, selectId, newData);
  225. return result;
  226. }
  227. _filterUpdateInvalidField(id, data) {
  228. const result = { id };
  229. for (const prop in data) {
  230. if (readOnlyFields.indexOf(prop) === -1) result[prop] = data[prop];
  231. }
  232. return result;
  233. }
  234. _checkCalcField(data) {
  235. for (const prop in data) {
  236. if (calcFields.indexOf(prop) >= 0) {
  237. return true;
  238. }
  239. }
  240. return false;
  241. }
  242. clearParentingData(data) {
  243. data.unit_price = 0;
  244. data.quantity = 0;
  245. data.total_price = 0;
  246. }
  247. async updateCalc(budgetId, data) {
  248. const helper = this.ctx.helper;
  249. // 简单验证数据
  250. if (budgetId <= 0 || !this.ctx.budget) throw '标段不存在';
  251. if (!data) throw '提交数据错误';
  252. const datas = data instanceof Array ? data : [data];
  253. const ids = [];
  254. for (const row of datas) {
  255. if (budgetId !== row.bid) throw '提交数据错误';
  256. ids.push(row.id);
  257. }
  258. const conn = await this.db.beginTransaction();
  259. try {
  260. for (const row of datas) {
  261. const updateNode = await this.getDataById(row.id);
  262. if (!updateNode || budgetId !== updateNode.bid || row.tree_id !== updateNode.tree_id) throw '提交数据错误';
  263. let updateData;
  264. // 项目节、工程量清单相关
  265. if (row.b_code) {
  266. row.dgn_qty1 = 0;
  267. row.dgn_qty2 = 0;
  268. row.code = '';
  269. }
  270. if (row.code) row.b_code = '';
  271. if (this._checkCalcField(row)) {
  272. let calcData = JSON.parse(JSON.stringify(row));
  273. if (row.quantity !== undefined || row.unit_price !== undefined) {
  274. calcData.quantity = row.quantity === undefined ? updateNode.quantity : helper.round(row.quantity, this.ctx.budget.decimal.qty);
  275. calcData.unit_price = row.unit_price === undefined ? updateNode.unit_price : helper.round(row.unit_price, this.ctx.budget.decimal.up);
  276. calcData.total_price = helper.mul(calcData.quantity, calcData.unit_price, this.ctx.budget.decimal.tp);
  277. } else if (row.total_price !== undefined ) {
  278. calcData.quantity = 0;
  279. calcData.unit_price = 0;
  280. calcData.total_price = helper.round(row.total_price, this.ctx.budget.decimal.tp);
  281. }
  282. updateData = this._filterUpdateInvalidField(updateNode.id, this._.defaults(calcData, row));
  283. } else {
  284. updateData = this._filterUpdateInvalidField(updateNode.id, row);
  285. }
  286. await conn.update(this.tableName, updateData);
  287. }
  288. await conn.commit();
  289. } catch (err) {
  290. await conn.rollback();
  291. throw err;
  292. }
  293. return { update: await this.getDataById(ids) };
  294. }
  295. async pasteBlockData (bid, sid, pasteData, defaultData) {
  296. if ((bid <= 0) || (sid <= 0)) return [];
  297. if (!pasteData || pasteData.length <= 0) throw '复制数据错误';
  298. for (const pd of pasteData) {
  299. if (!pd || pd.length <= 0) throw '复制数据错误';
  300. pd.sort(function (x, y) {
  301. return x.level - y.level
  302. });
  303. if (pd[0].tree_pid !== pasteData[0][0].tree_pid) throw '复制数据错误:仅可操作同层节点';
  304. }
  305. this.newBills = false;
  306. const selectData = await this.getDataByKid(bid, sid);
  307. if (!selectData) throw '粘贴数据错误';
  308. const newParentPath = selectData.full_path.replace(selectData.tree_id, '');
  309. const pasteBillsData = [];
  310. let maxId = await this._getMaxLid(bid);
  311. for (const [i, pd] of pasteData.entries()) {
  312. for (const d of pd) {
  313. d.children = pd.filter(function (x) {
  314. return x.tree_pid === d.tree_id;
  315. });
  316. }
  317. const pbd = [];
  318. for (const [j, d] of pd.entries()) {
  319. const newBills = {
  320. id: this.uuid.v4(),
  321. bid: bid,
  322. tree_id: maxId + j + 1,
  323. tree_pid: j === 0 ? selectData.tree_pid : d.tree_pid,
  324. level: d.level + selectData.level - pd[0].level,
  325. order: j === 0 ? selectData.order + i + 1 : d.order,
  326. is_leaf: d.is_leaf,
  327. code: d.code,
  328. b_code: d.b_code,
  329. name: d.name,
  330. unit: d.unit,
  331. source: d.source,
  332. remark: d.remark,
  333. drawing_code: d.drawing_code,
  334. memo: d.memo,
  335. node_type: d.node_type,
  336. };
  337. for (const c of d.children) {
  338. c.tree_pid = newBills.tree_id;
  339. }
  340. if (d.b_code && d.is_leaf) {
  341. newBills.dgn_qty1 = 0;
  342. newBills.dgn_qty2 = 0;
  343. newBills.unit_price = this.ctx.helper.round(d.unit_price, this.ctx.budget.decimal.up);
  344. newBills.quantity = this.ctx.helper.round(d.quantity, this.ctx.budget.decimal.qty);
  345. newBills.total_price = this.ctx.helper.mul(newBills.quantity, newBills.unit_price, this.ctx.budget.decimal.tp);
  346. } else {
  347. newBills.dgn_qty1 = this.ctx.helper.round(d.dgn_qty1, this.ctx.budget.decimal.qty);
  348. newBills.dgn_qty2 = this.ctx.helper.round(d.dgn_qty2, this.ctx.budget.decimal.qty);
  349. newBills.unit_price = 0;
  350. newBills.quantity = 0;
  351. newBills.total_price = d.is_leaf ? this.ctx.helper.round(d.total_price, this.ctx.budget.decimal.tp) : 0;
  352. }
  353. if (defaultData) this.ctx.helper._.assignIn(newBills, defaultData);
  354. pbd.push(newBills);
  355. }
  356. for (const d of pbd) {
  357. const parent = pbd.find(function (x) {
  358. return x.tree_id === d.tree_pid;
  359. });
  360. d.full_path = parent
  361. ? parent.full_path + '-' + d.tree_id
  362. : newParentPath + d.tree_id;
  363. if (defaultData) this.ctx.helper._.assignIn(pbd, defaultData);
  364. pasteBillsData.push(d);
  365. }
  366. maxId = maxId + pbd.length;
  367. }
  368. this.transaction = await this.db.beginTransaction();
  369. try {
  370. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  371. await this._updateChildrenOrder(bid, selectData.tree_pid, selectData.order + 1, pasteData.length);
  372. // 数据库创建新增节点数据
  373. if (pasteBillsData.length > 0) await this.transaction.insert(this.tableName, pasteBillsData);
  374. this._cacheMaxLid(bid, maxId);
  375. await this.transaction.commit();
  376. } catch (err) {
  377. await this.transaction.rollback();
  378. throw err;
  379. }
  380. // 查询应返回的结果
  381. const updateData = await this.getNextsData(selectData.bid, selectData.tree_pid, selectData.order + pasteData.length);
  382. return { create: pasteBillsData, update: updateData };
  383. }
  384. async importExcel(templateId, excelData, needGcl, filter) {
  385. const AnalysisExcel = require('../lib/analysis_excel').AnalysisExcelTree;
  386. const analysisExcel = new AnalysisExcel(this.ctx, this.setting, needGcl ? ['code', 'b_code'] : ['code']);
  387. const tempData = await this.ctx.service.tenderNodeTemplate.getData(templateId, true);
  388. const cacheTree = analysisExcel.analysisData(excelData, tempData, {
  389. filterZeroGcl: filter, filterPos: true, filterGcl: !needGcl, filterCalc: true,
  390. });
  391. const orgMaxId = await this._getMaxLid(this.ctx.budget.id);
  392. const conn = await this.db.beginTransaction();
  393. try {
  394. await conn.delete(this.tableName, { bid: this.ctx.budget.id });
  395. const datas = [];
  396. for (const node of cacheTree.items) {
  397. const data = {
  398. id: node.id,
  399. bid: this.ctx.budget.id,
  400. tree_id: node.tree_id,
  401. tree_pid: node.tree_pid,
  402. level: node.level,
  403. order: node.order,
  404. is_leaf: !node.children || node.children.length === 0,
  405. full_path: node.full_path,
  406. code: node.code || '',
  407. b_code: node.b_code || '',
  408. name: node.name || '',
  409. unit: node.unit || '',
  410. unit_price: !node.children || node.children.length === 0 ? node.unit_price || 0 : 0,
  411. dgn_qty1: node.dgn_qty1 || 0,
  412. dgn_qty2: node.dgn_qty2 || 0,
  413. memo: node.memo,
  414. drawing_code: node.drawing_code,
  415. node_type: node.node_type,
  416. quantity: !node.children || node.children.length === 0 ? node.quantity || 0 : 0,
  417. total_price: !node.children || node.children.length === 0 ? node.total_price || 0 : 0,
  418. };
  419. datas.push(data);
  420. }
  421. await conn.insert(this.tableName, datas);
  422. await conn.commit();
  423. if (orgMaxId) this._cacheMaxLid(this.ctx.budget.id, cacheTree.keyNodeId);
  424. return datas;
  425. } catch (err) {
  426. await conn.rollback();
  427. throw err;
  428. }
  429. }
  430. async getSumTp(bid) {
  431. const sql = 'SELECT Sum(total_price) As total_price FROM ' + this.tableName + ' Where bid = ? and is_leaf = true';
  432. const result = await this.db.queryOne(sql, [bid]);
  433. return result.total_price;
  434. }
  435. async importYbpData(budget, ybpData, needGcl) {
  436. const filterGcl = function(data, compareData, isXmj) {
  437. return !isXmj;
  438. };
  439. const YbpTrees = require('../lib/ybp_tree');
  440. const gatherTreeSetting = {
  441. id: 'ledger_id', pid: 'ledger_pid', order: 'order', full_path: 'full_path', level: 'level', rootId: -1,
  442. calcFields: ['total_price'],
  443. calc(node, helper, decimal) {
  444. node.quantity = helper.round(node.quantity, decimal.qty);
  445. node.unit_price = helper.round(node.unit_price, decimal.up);
  446. if ((!node.children || node.children.length === 0)) {
  447. node.total_price = node.b_code ? helper.mul(node.quantity, node.unit_price, decimal.tp) : helper.round(node.total_fee, decimal.tp);
  448. }
  449. },
  450. };
  451. const ybpTreeSetting = { id: 'ID', pid: 'parentID', order: 'seq', rootId: '-1' };
  452. const helper = this.ctx.helper;
  453. const mergeCompliation = ['5b52b027fd3bb0000b257cf8', '5c66649650da2d000d8d37ba'];
  454. const ybpImportType = mergeCompliation.indexOf(ybpData.subjects[0].project.compilationID) >= 0 ? YbpTrees.YbpImportType.flow : YbpTrees.YbpImportType.merge;
  455. const gatherTree = new YbpTrees.YbpImportTree(gatherTreeSetting, ybpImportType, helper, budget.decimal);
  456. for (const subject of ybpData.subjects) {
  457. if (!subject.bills || subject.bills.length === 0) continue;
  458. const parents = YbpTrees.YbpUtils.getSubjectParentPath(subject, ybpData.subjects);
  459. const ybpTree = new YbpTrees.YbpTree(ybpTreeSetting);
  460. ybpTree.loadDatas(subject.bills);
  461. gatherTree.importTree(ybpTree, subject.project.name, parents, null, needGcl ? null : filterGcl);
  462. }
  463. gatherTree.sort(false);
  464. gatherTree.calculateAll();
  465. const bills = [];
  466. for (const n of gatherTree.nodes) {
  467. const billsId = this.uuid.v4();
  468. const isLeaf = !n.children || n.children.length === 0;
  469. bills.push({
  470. id: billsId,
  471. bid: budget.id,
  472. tree_id: n.ledger_id,
  473. tree_pid: n.ledger_pid,
  474. level: n.level,
  475. order: n.order,
  476. is_leaf: isLeaf,
  477. full_path: n.full_path,
  478. code: n.code || '',
  479. b_code: n.b_code || '',
  480. name: n.name || '',
  481. unit: n.unit || '',
  482. unit_price: isLeaf ? n.unit_price || 0 : 0,
  483. dgn_qty1: n.dgn_qty1 || 0,
  484. dgn_qty2: n.dgn_qty2 || 0,
  485. memo: n.remark,
  486. drawing_code: n.drawing_code,
  487. quantity: isLeaf ? n.quantity || 0 : 0,
  488. total_price: isLeaf ? n.total_price || 0 : 0,
  489. });
  490. }
  491. const conn = await this.db.beginTransaction();
  492. try {
  493. await conn.delete(this.tableName, { bid: budget.id });
  494. await conn.insert(this.tableName, bills);
  495. await conn.commit();
  496. return bills;
  497. } catch (err) {
  498. await conn.rollback();
  499. throw err;
  500. }
  501. }
  502. async importYbp(budget, ybp, needGcl) {
  503. const YBP = require('../lib/ybp');
  504. const ybpAnalysis = new YBP(this.ctx);
  505. const ybpData = ybpAnalysis.decryptBuffer(ybp);
  506. return await this.importYbpData(budget, ybpData, needGcl);
  507. }
  508. }
  509. module.exports = BaseBudget;