base_budget_service.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. await 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. clearParentingData(data) {
  235. data.unit_price = 0;
  236. data.quantity = 0;
  237. data.total_price = 0;
  238. }
  239. async updateCalc(budgetId, data) {
  240. const helper = this.ctx.helper;
  241. // 简单验证数据
  242. if (budgetId <= 0 || !this.ctx.budget) throw '标段不存在';
  243. if (!data) throw '提交数据错误';
  244. const datas = data instanceof Array ? data : [data];
  245. const ids = [];
  246. for (const row of datas) {
  247. if (budgetId !== row.bid) throw '提交数据错误';
  248. ids.push(row.id);
  249. }
  250. const conn = await this.db.beginTransaction();
  251. try {
  252. for (const row of datas) {
  253. const updateNode = await this.getDataById(row.id);
  254. if (!updateNode || budgetId !== updateNode.bid || row.tree_id !== updateNode.tree_id) throw '提交数据错误';
  255. let updateData;
  256. // 项目节、工程量清单相关
  257. if (row.b_code) {
  258. row.dgn_qty1 = 0;
  259. row.dgn_qty2 = 0;
  260. row.code = '';
  261. }
  262. if (row.code) row.b_code = '';
  263. if (this._checkCalcField(row)) {
  264. let calcData = JSON.parse(JSON.stringify(row));
  265. if (row.quantity !== undefined || row.unit_price !== undefined) {
  266. calcData.quantity = row.quantity === undefined ? updateNode.quantity : helper.round(row.quantity, this.ctx.budget.decimal.qty);
  267. calcData.unit_price = row.unit_price === undefined ? updateNode.unit_price : helper.round(row.unit_price, this.ctx.budget.decimal.up);
  268. calcData.total_price = helper.mul(calcData.quantity, calcData.unit_price, this.ctx.budget.decimal.tp);
  269. } else if (row.total_price !== undefined ) {
  270. calcData.quantity = 0;
  271. calcData.unit_price = 0;
  272. calcData.total_price = helper.round(row.total_price, this.ctx.budget.decimal.tp);
  273. }
  274. updateData = this._filterUpdateInvalidField(updateNode.id, this._.defaults(calcData, row));
  275. } else {
  276. updateData = this._filterUpdateInvalidField(updateNode.id, row);
  277. }
  278. await conn.update(this.tableName, updateData);
  279. }
  280. await conn.commit();
  281. } catch (err) {
  282. await conn.rollback();
  283. throw err;
  284. }
  285. return { update: await this.getDataById(ids) };
  286. }
  287. async pasteBlockData (bid, sid, pasteData, defaultData) {
  288. if ((bid <= 0) || (sid <= 0)) return [];
  289. if (!pasteData || pasteData.length <= 0) throw '复制数据错误';
  290. for (const pd of pasteData) {
  291. if (!pd || pd.length <= 0) throw '复制数据错误';
  292. pd.sort(function (x, y) {
  293. return x.level - y.level
  294. });
  295. if (pd[0].tree_pid !== pasteData[0][0].tree_pid) throw '复制数据错误:仅可操作同层节点';
  296. }
  297. this.newBills = false;
  298. const selectData = await this.getDataByKid(bid, sid);
  299. if (!selectData) throw '粘贴数据错误';
  300. const newParentPath = selectData.full_path.replace(selectData.tree_id, '');
  301. const pasteBillsData = [];
  302. let maxId = await this._getMaxLid(bid);
  303. for (const [i, pd] of pasteData.entries()) {
  304. for (const d of pd) {
  305. d.children = pd.filter(function (x) {
  306. return x.tree_pid === d.tree_id;
  307. });
  308. }
  309. const pbd = [];
  310. for (const [j, d] of pd.entries()) {
  311. const newBills = {
  312. id: this.uuid.v4(),
  313. bid: bid,
  314. tree_id: maxId + j + 1,
  315. tree_pid: j === 0 ? selectData.tree_pid : d.tree_pid,
  316. level: d.level + selectData.level - pd[0].level,
  317. order: j === 0 ? selectData.order + i + 1 : d.order,
  318. is_leaf: d.is_leaf,
  319. code: d.code,
  320. b_code: d.b_code,
  321. name: d.name,
  322. unit: d.unit,
  323. source: d.source,
  324. remark: d.remark,
  325. drawing_code: d.drawing_code,
  326. memo: d.memo,
  327. node_type: d.node_type,
  328. };
  329. for (const c of d.children) {
  330. c.tree_pid = newBills.tree_id;
  331. }
  332. if (d.b_code && d.is_leaf) {
  333. newBills.dgn_qty1 = 0;
  334. newBills.dgn_qty2 = 0;
  335. newBills.unit_price = this.ctx.helper.round(d.unit_price, this.ctx.budget.decimal.up);
  336. newBills.quantity = this.ctx.helper.round(d.quantity, this.ctx.budget.decimal.qty);
  337. newBills.total_price = this.ctx.helper.mul(newBills.quantity, newBills.unit_price, this.ctx.budget.decimal.tp);
  338. } else {
  339. newBills.dgn_qty1 = this.ctx.helper.round(d.dgn_qty1, this.ctx.budget.decimal.qty);
  340. newBills.dgn_qty2 = this.ctx.helper.round(d.dgn_qty2, this.ctx.budget.decimal.qty);
  341. newBills.unit_price = 0;
  342. newBills.quantity = 0;
  343. newBills.total_price = d.is_leaf ? this.ctx.helper.round(d.total_price, this.ctx.budget.decimal.tp) : 0;
  344. }
  345. if (defaultData) this.ctx.helper._.assignIn(newBills, defaultData);
  346. pbd.push(newBills);
  347. }
  348. for (const d of pbd) {
  349. const parent = pbd.find(function (x) {
  350. return x.tree_id === d.tree_pid;
  351. });
  352. d.full_path = parent
  353. ? parent.full_path + '-' + d.tree_id
  354. : newParentPath + d.tree_id;
  355. if (defaultData) this.ctx.helper._.assignIn(pbd, defaultData);
  356. pasteBillsData.push(d);
  357. }
  358. maxId = maxId + pbd.length;
  359. }
  360. this.transaction = await this.db.beginTransaction();
  361. try {
  362. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  363. await this._updateChildrenOrder(bid, selectData.tree_pid, selectData.order + 1, pasteData.length);
  364. // 数据库创建新增节点数据
  365. if (pasteBillsData.length > 0) await this.transaction.insert(this.tableName, pasteBillsData);
  366. this._cacheMaxLid(bid, maxId);
  367. await this.transaction.commit();
  368. } catch (err) {
  369. await this.transaction.rollback();
  370. throw err;
  371. }
  372. // 查询应返回的结果
  373. const updateData = await this.getNextsData(selectData.bid, selectData.tree_pid, selectData.order + pasteData.length);
  374. return { create: pasteBillsData, update: updateData };
  375. }
  376. async importExcel(templateId, excelData, needGcl, filter) {
  377. const AnalysisExcel = require('../lib/analysis_excel').AnalysisExcelTree;
  378. const analysisExcel = new AnalysisExcel(this.ctx, this.setting, needGcl ? ['code', 'b_code'] : ['code']);
  379. const tempData = await this.ctx.service.tenderNodeTemplate.getData(templateId, true);
  380. const cacheTree = analysisExcel.analysisData(excelData, tempData, {
  381. filterZeroGcl: filter, filterPos: true, filterGcl: !needGcl, filterCalc: true,
  382. });
  383. const orgMaxId = await this._getMaxLid(this.ctx.budget.id);
  384. const conn = await this.db.beginTransaction();
  385. try {
  386. await conn.delete(this.tableName, { bid: this.ctx.budget.id });
  387. const datas = [];
  388. for (const node of cacheTree.items) {
  389. const data = {
  390. id: node.id,
  391. bid: this.ctx.budget.id,
  392. tree_id: node.tree_id,
  393. tree_pid: node.tree_pid,
  394. level: node.level,
  395. order: node.order,
  396. is_leaf: !node.children || node.children.length === 0,
  397. full_path: node.full_path,
  398. code: node.code || '',
  399. b_code: node.b_code || '',
  400. name: node.name || '',
  401. unit: node.unit || '',
  402. unit_price: !node.children || node.children.length === 0 ? node.unit_price || 0 : 0,
  403. dgn_qty1: node.dgn_qty1 || 0,
  404. dgn_qty2: node.dgn_qty2 || 0,
  405. memo: node.memo,
  406. drawing_code: node.drawing_code,
  407. node_type: node.node_type,
  408. quantity: !node.children || node.children.length === 0 ? node.quantity || 0 : 0,
  409. total_price: !node.children || node.children.length === 0 ? node.total_price || 0 : 0,
  410. };
  411. datas.push(data);
  412. }
  413. await conn.insert(this.tableName, datas);
  414. await conn.commit();
  415. if (orgMaxId) this._cacheMaxLid(this.ctx.budget.id, cacheTree.keyNodeId);
  416. return datas;
  417. } catch (err) {
  418. await conn.rollback();
  419. throw err;
  420. }
  421. }
  422. async getSumTp(bid) {
  423. const sql = 'SELECT Sum(total_price) As total_price FROM ' + this.tableName + ' Where bid = ? and is_leaf = true';
  424. const result = await this.db.queryOne(sql, [bid]);
  425. return result.total_price;
  426. }
  427. }
  428. module.exports = BaseBudget;