base_budget_service.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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 (!conn) throw '内部错误';
  37. if (budgetId <= 0) throw '概算项目id错误';
  38. const data = await this.ctx.service.tenderNodeTemplate.getData(templateId);
  39. if (!data.length) throw '模板数据有误';
  40. // 整理数据
  41. const insertData = [];
  42. for (const tmp of data) {
  43. insertData.push({
  44. id: this.uuid.v4(),
  45. bid: budgetId,
  46. tree_id: tmp.template_id,
  47. tree_pid: tmp.pid,
  48. level: tmp.level,
  49. order: tmp.order,
  50. full_path: tmp.full_path,
  51. is_leaf: tmp.is_leaf,
  52. code: tmp.code,
  53. name: tmp.name,
  54. unit: tmp.unit,
  55. node_type: tmp.node_type,
  56. });
  57. }
  58. const operate = await conn.insert(this.tableName, insertData);
  59. return operate.affectedRows === data.length;
  60. }
  61. async addChild(budgetId, selectId, data) {
  62. if ((budgetId <= 0) || (selectId <= 0)) return [];
  63. const selectData = await this.getDataByKid(budgetId, selectId);
  64. if (!selectData) {
  65. throw '新增节点数据错误';
  66. }
  67. const children = await this.getChildrenByParentId(budgetId, selectId);
  68. const maxId = await this._getMaxLid(budgetId);
  69. data.id = this.uuid.v4();
  70. data.bid = budgetId;
  71. data.tree_id = maxId + 1;
  72. data.tree_pid = selectData.tree_id;
  73. data.level = selectData.level + 1;
  74. data.order = children.length + 1;
  75. data.full_path = selectData.full_path + '-' + data.tree_id;
  76. data.is_leaf = true;
  77. this.transaction = await this.db.beginTransaction();
  78. try {
  79. const result = await this.transaction.insert(this.tableName, data);
  80. if (children.length === 0) {
  81. await this.transaction.update(this.tableName,
  82. { is_leaf: false, quantity: 0, unit_price: 0, total_price: 0 },
  83. { where: { bid: budgetId, tree_id: selectData.tree_id } });
  84. }
  85. await this.transaction.commit();
  86. } catch(err) {
  87. this.transaction.rollback();
  88. throw err;
  89. }
  90. this._cacheMaxLid(budgetId, maxId + 1);
  91. // 查询应返回的结果
  92. const resultData = {};
  93. resultData.create = await this.getDataByKid(budgetId, data.tree_id);
  94. if (children.length === 0) resultData.update = await this.getDataByKid(budgetId, selectId);
  95. return resultData;
  96. }
  97. _filterStdData(stdData) {
  98. const result = {
  99. name: stdData.name,
  100. unit: stdData.unit,
  101. node_type: stdData.node_type,
  102. };
  103. result.code = stdData.code ? stdData.code : '';
  104. result.b_code = stdData.b_code ? stdData.b_code : '';
  105. return result;
  106. }
  107. async _addChildNodeData(budgetId, parentData, data) {
  108. if (budgetId <= 0) return undefined;
  109. if (!data) data = {};
  110. const pid = parentData ? parentData.tree_id : this.rootId;
  111. const maxId = await this._getMaxLid(budgetId);
  112. data.id = this.uuid.v4();
  113. data.bid = budgetId;
  114. data.tree_id = maxId + 1;
  115. data.tree_pid = pid;
  116. if (data.order === undefined) data.order = 1;
  117. data.level = parentData ? parentData.level + 1 : 1;
  118. data.full_path = parentData ? parentData.full_path + '-' + data.tree_id : '' + data.tree_id;
  119. if (data.is_leaf === undefined) data.is_leaf = true;
  120. const result = await this.transaction.insert(this.tableName, data);
  121. this._cacheMaxLid(budgetId, maxId + 1);
  122. return [result, data];
  123. }
  124. async _addChildAutoOrder(budgetId, parentData, data) {
  125. const findPreData = function(list, a) {
  126. if (!list || list.length === 0) { return null; }
  127. for (let i = 0, iLen = list.length; i < iLen; i++) {
  128. if (billsUtils.compareCode(list[i].code, a.code) > 0) {
  129. return i > 0 ? list[i - 1] : null;
  130. }
  131. }
  132. return list[list.length - 1];
  133. };
  134. const pid = parentData ? parentData.tree_id : this.rootId;
  135. const children = await this.getChildrenByParentId(budgetId, pid);
  136. const preData = findPreData(children, data);
  137. if (!preData || children.indexOf(preData) < children.length - 1) {
  138. await this._updateChildrenOrder(budgetId, pid, preData ? preData.order + 1 : 1);
  139. }
  140. data.order = preData ? preData.order + 1 : 1;
  141. const [addResult, node] = await this._addChildNodeData(budgetId, parentData, data);
  142. return [addResult, node];
  143. }
  144. async addStdNodeWithParent(budgetId, stdData, stdLib) {
  145. // 查询完整标准清单,并按层次排序
  146. const fullLevel = await stdLib.getFullLevelDataByFullPath(stdData.list_id, stdData.full_path);
  147. fullLevel.sort(function(x, y) {
  148. return x.level - y.level;
  149. });
  150. let isNew = false,
  151. node,
  152. firstNew,
  153. updateParent,
  154. addResult;
  155. const expandIds = [];
  156. this.transaction = await this.db.beginTransaction();
  157. try {
  158. // 从最顶层节点依次查询是否存在,否则添加
  159. for (let i = 0, len = fullLevel.length; i < len; i++) {
  160. const stdNode = fullLevel[i];
  161. if (isNew) {
  162. const newData = this._filterStdData(stdNode);
  163. newData.is_leaf = (i === len - 1);
  164. [addResult, node] = await this._addChildNodeData(budgetId, node, newData);
  165. } else {
  166. const parent = node;
  167. node = await this.getDataByCondition({
  168. bid: budgetId,
  169. tree_pid: parent ? parent.tree_id : this.rootId,
  170. code: stdNode.code,
  171. name: stdNode.name,
  172. });
  173. if (!node) {
  174. isNew = true;
  175. const newData = this._filterStdData(stdNode);
  176. newData.is_leaf = (i === len - 1);
  177. [addResult, node] = await this._addChildAutoOrder(budgetId, parent, newData);
  178. if (parent && parent.is_leaf) {
  179. await this.transaction.update(this.tableName, { id: parent.id, is_leaf: false,
  180. unit_price: 0, quantity: 0, total_price: 0});
  181. updateParent = parent;
  182. }
  183. firstNew = node;
  184. } else {
  185. expandIds.push(node.tree_id);
  186. }
  187. }
  188. }
  189. await this.transaction.commit();
  190. } catch (err) {
  191. await this.transaction.rollback();
  192. throw err;
  193. }
  194. // 查询应返回的结果
  195. let createData = [],
  196. updateData = [];
  197. if (firstNew) {
  198. createData = await this.getDataByFullPath(budgetId, firstNew.full_path + '%');
  199. updateData = await this.getNextsData(budgetId, firstNew.tree_pid, firstNew.order);
  200. if (updateParent) {
  201. updateData.push(await this.getDataByCondition({ id: updateParent.id }));
  202. }
  203. }
  204. return { create: createData, update: updateData };
  205. }
  206. async addBillsNode(budgetId, selectId, data) {
  207. return await this.addNode(budgetId, selectId, data ? data : {});
  208. }
  209. async addStdNode(budgetId, selectId, stdData) {
  210. const newData = this._filterStdData(stdData);
  211. const result = await this.addBillsNode(budgetId, selectId, newData);
  212. return result;
  213. }
  214. async addStdNodeAsChild(budgetId, selectId, stdData) {
  215. const newData = this._filterStdData(stdData);
  216. const result = await this.addChild(budgetId, selectId, newData);
  217. return result;
  218. }
  219. _filterUpdateInvalidField(id, data) {
  220. const result = { id };
  221. for (const prop in data) {
  222. if (readOnlyFields.indexOf(prop) === -1) result[prop] = data[prop];
  223. }
  224. return result;
  225. }
  226. _checkCalcField(data) {
  227. for (const prop in data) {
  228. if (calcFields.indexOf(prop) >= 0) {
  229. return true;
  230. }
  231. }
  232. return false;
  233. }
  234. async updateCalc(budgetId, data) {
  235. const helper = this.ctx.helper;
  236. // 简单验证数据
  237. if (budgetId <= 0 || !this.ctx.budget) throw '标段不存在';
  238. if (!data) throw '提交数据错误';
  239. const datas = data instanceof Array ? data : [data];
  240. const ids = [];
  241. for (const row of datas) {
  242. if (budgetId !== row.bid) throw '提交数据错误';
  243. ids.push(row.id);
  244. }
  245. this.transaction = await this.db.beginTransaction();
  246. try {
  247. for (const row of datas) {
  248. const updateNode = await this.getDataById(row.id);
  249. if (!updateNode || budgetId !== updateNode.bid || row.tree_id !== updateNode.tree_id) throw '提交数据错误';
  250. let updateData;
  251. // 项目节、工程量清单相关
  252. if (row.b_code) {
  253. row.dgn_qty1 = 0;
  254. row.dgn_qty2 = 0;
  255. row.code = '';
  256. }
  257. if (row.code) row.b_code = '';
  258. if (this._checkCalcField(row)) {
  259. console.log(row);
  260. let calcData = JSON.parse(JSON.stringify(row));
  261. if (row.quantity !== undefined || row.unit_price !== undefined) {
  262. calcData.quantity = row.quantity === undefined ? updateNode.quantity : helper.round(row.quantity, 2);
  263. calcData.unit_price = row.unit_price === undefined ? updateNode.unit_price : helper.round(row.unit_price, 2);
  264. calcData.total_price = helper.mul(calcData.quantity, calcData.unit_price, 2);
  265. } else if (row.total_price !== undefined ) {
  266. calcData.quantity = 0;
  267. calcData.total_price = helper.round(row.total_price, 2);
  268. }
  269. updateData = this._filterUpdateInvalidField(updateNode.id, calcData);
  270. } else {
  271. updateData = this._filterUpdateInvalidField(updateNode.id, row);
  272. }
  273. await this.transaction.update(this.tableName, updateData);
  274. }
  275. await this.transaction.commit();
  276. this.transaction = null;
  277. } catch (err) {
  278. await this.transaction.rollback();
  279. this.transaction = null;
  280. throw err;
  281. }
  282. return { update: await this.getDataById(ids) };
  283. }
  284. async pasteBlockData (bid, sid, pasteData, defaultData) {
  285. if ((bid <= 0) || (sid <= 0)) return [];
  286. if (!pasteData || pasteData.length <= 0) throw '复制数据错误';
  287. for (const pd of pasteData) {
  288. if (!pd || pd.length <= 0) throw '复制数据错误';
  289. pd.sort(function (x, y) {
  290. return x.level - y.level
  291. });
  292. if (pd[0].tree_pid !== pasteData[0][0].tree_pid) throw '复制数据错误:仅可操作同层节点';
  293. }
  294. this.newBills = false;
  295. const selectData = await this.getDataByKid(bid, sid);
  296. if (!selectData) throw '粘贴数据错误';
  297. const newParentPath = selectData.full_path.replace(selectData.tree_id, '');
  298. const pasteBillsData = [];
  299. let maxId = await this._getMaxLid(bid);
  300. for (const [i, pd] of pasteData.entries()) {
  301. for (const d of pd) {
  302. d.children = pd.filter(function (x) {
  303. return x.tree_pid === d.tree_id;
  304. });
  305. }
  306. const pbd = [];
  307. for (const [j, d] of pd.entries()) {
  308. const newBills = {
  309. id: this.uuid.v4(),
  310. bid: bid,
  311. tree_id: maxId + j + 1,
  312. tree_pid: j === 0 ? selectData.tree_pid : d.tree_pid,
  313. level: d.level + selectData.level - pd[0].level,
  314. order: j === 0 ? selectData.order + i + 1 : d.order,
  315. is_leaf: d.is_leaf,
  316. code: d.code,
  317. b_code: d.b_code,
  318. name: d.name,
  319. unit: d.unit,
  320. source: d.source,
  321. remark: d.remark,
  322. drawing_code: d.drawing_code,
  323. memo: d.memo,
  324. node_type: d.node_type,
  325. };
  326. for (const c of d.children) {
  327. c.tree_pid = newBills.tree_id;
  328. }
  329. if (d.b_code) {
  330. newBills.unit_price = this.ctx.helper.round(d.unit_price, 2);
  331. newBills.quantity = this.ctx.helper.round(d.quantity, 2);
  332. newBills.total_price = this.ctx.helper.mul(newBills.quantity, newBills.unit_price, 2);
  333. } else {
  334. newBills.dgn_qty1 = this.ctx.helper.round(d.dgn_qty1, 2);
  335. newBills.dgn_qty2 = this.ctx.helper.round(d.dgn_qty2, 2);
  336. newBills.total_price = this.ctx.helper.round(d.total_price, 2);
  337. }
  338. if (defaultData) this.ctx.helper._.assignIn(newBills, defaultData);
  339. pbd.push(newBills);
  340. }
  341. for (const d of pbd) {
  342. const parent = pbd.find(function (x) {
  343. return x.tree_id === d.tree_pid;
  344. });
  345. d.full_path = parent
  346. ? parent.full_path + '-' + d.tree_id
  347. : newParentPath + d.tree_id;
  348. if (defaultData) this.ctx.helper._.assignIn(pbd, defaultData);
  349. pasteBillsData.push(d);
  350. }
  351. maxId = maxId + pbd.length;
  352. }
  353. this.transaction = await this.db.beginTransaction();
  354. try {
  355. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  356. await this._updateChildrenOrder(bid, selectData.tree_pid, selectData.order + 1, pasteData.length);
  357. // 数据库创建新增节点数据
  358. if (pasteBillsData.length > 0) await this.transaction.insert(this.tableName, pasteBillsData);
  359. this._cacheMaxLid(bid, maxId);
  360. await this.transaction.commit();
  361. } catch (err) {
  362. await this.transaction.rollback();
  363. throw err;
  364. }
  365. // 查询应返回的结果
  366. const updateData = await this.getNextsData(selectData.bid, selectData.tree_pid, selectData.order + pasteData.length);
  367. return { create: pasteBillsData, update: updateData };
  368. }
  369. async importExcel(templateId, excelData, needGcl, filter) {
  370. console.log(needGcl);
  371. const AnalysisExcel = require('../lib/analysis_excel').AnalysisExcelTree;
  372. const analysisExcel = new AnalysisExcel(this.ctx, this.setting);
  373. const tempData = await this.ctx.service.tenderNodeTemplate.getData(templateId, true);
  374. const cacheTree = analysisExcel.analysisData(excelData, tempData, {
  375. filterZeroGcl: filter, filterPos: true, filterGcl: !needGcl, filterCalc: true,
  376. });
  377. const orgMaxId = await this._getMaxLid(this.ctx.budget.id);
  378. const transaction = await this.db.beginTransaction();
  379. try {
  380. await transaction.delete(this.tableName, { bid: this.ctx.budget.id });
  381. const datas = [];
  382. for (const node of cacheTree.items) {
  383. const data = {
  384. id: node.id,
  385. bid: this.ctx.budget.id,
  386. tree_id: node.tree_id,
  387. tree_pid: node.tree_pid,
  388. level: node.level,
  389. order: node.order,
  390. is_leaf: !node.children || node.children.length === 0,
  391. full_path: node.full_path,
  392. code: node.code || '',
  393. b_code: node.b_code || '',
  394. name: node.name || '',
  395. unit: node.unit || '',
  396. unit_price: !node.children || node.children.length === 0 ? node.unit_price || 0 : 0,
  397. dgn_qty1: node.dgn_qty1 || 0,
  398. dgn_qty2: node.dgn_qty2 || 0,
  399. memo: node.memo,
  400. drawing_code: node.drawing_code,
  401. node_type: node.node_type,
  402. quantity: !node.children || node.children.length === 0 ? node.quantity || 0 : 0,
  403. total_price: !node.children || node.children.length === 0 ? node.total_price || 0 : 0,
  404. };
  405. datas.push(data);
  406. }
  407. await transaction.insert(this.tableName, datas);
  408. await transaction.commit();
  409. if (orgMaxId) this._cacheMaxLid(this.ctx.budget.id, cacheTree.keyNodeId);
  410. return datas;
  411. } catch (err) {
  412. await transaction.rollback();
  413. throw err;
  414. }
  415. }
  416. async getSumTp(bid) {
  417. const sql = 'SELECT Sum(total_price) As total_price FROM ' + this.tableName + ' Where bid = ?';
  418. const result = await this.db.queryOne(sql, [bid]);
  419. return result.total_price;
  420. }
  421. }
  422. module.exports = BaseBudget;