control_price.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date
  7. * @version
  8. */
  9. const TreeService = require('../base/base_tree_service');
  10. const billsUtils = require('../lib/bills_utils');
  11. const readOnlyFields = ['id', 'tid', 'tree_id', 'tree_pid', 'order', 'level', 'full_path', 'is_leaf'];
  12. const calcFields = ['unit_price', 'quantity', 'total_price'];
  13. class ControlPrice extends TreeService {
  14. /**
  15. * 构造函数
  16. *
  17. * @param {Object} ctx - egg全局变量
  18. * @param {String} tableName - 表名
  19. * @return {void}
  20. */
  21. constructor(ctx) {
  22. super(ctx, {
  23. mid: 'tid',
  24. kid: 'tree_id',
  25. pid: 'tree_pid',
  26. order: 'order',
  27. level: 'level',
  28. isLeaf: 'is_leaf',
  29. fullPath: 'full_path',
  30. keyPre: 'ctrl_price_maxLid:',
  31. uuid: true,
  32. });
  33. this.tableName = 'control_price';
  34. }
  35. async checkInit(tender) {
  36. const count = await this.count({ tid: tender.id });
  37. if (count > 0) return;
  38. const templateId = await this.ctx.service.valuation.getValuationTemplate(
  39. this.ctx.tender.data.valuation, this.ctx.tender.data.measure_type);
  40. await this.initByTemplate(tender.id, templateId);
  41. }
  42. async initByTemplate(tenderId, templateId){
  43. if (tenderId <= 0) throw '标段数据错误';
  44. const data = await this.ctx.service.tenderNodeTemplate.getData(templateId);
  45. if (!data.length) throw '模板数据有误';
  46. // 整理数据
  47. const insertData = [];
  48. for (const tmp of data) {
  49. insertData.push({
  50. id: this.uuid.v4(),
  51. tid: tenderId,
  52. tree_id: tmp.template_id,
  53. tree_pid: tmp.pid,
  54. level: tmp.level,
  55. order: tmp.order,
  56. full_path: tmp.full_path,
  57. is_leaf: tmp.is_leaf,
  58. code: tmp.code,
  59. name: tmp.name,
  60. unit: tmp.unit,
  61. node_type: tmp.node_type,
  62. });
  63. }
  64. const operate = await this.db.insert(this.tableName, insertData);
  65. return operate.affectedRows === data.length;
  66. }
  67. async addChild(tenderId, selectId, data) {
  68. if ((tenderId <= 0) || (selectId <= 0)) return [];
  69. const selectData = await this.getDataByKid(tenderId, selectId);
  70. if (!selectData) {
  71. throw '新增节点数据错误';
  72. }
  73. const children = await this.getChildrenByParentId(tenderId, selectId);
  74. const maxId = await this._getMaxLid(tenderId);
  75. data.id = this.uuid.v4();
  76. data.tid = tenderId;
  77. data.tree_id = maxId + 1;
  78. data.tree_pid = selectData.tree_id;
  79. data.level = selectData.level + 1;
  80. data.order = children.length + 1;
  81. data.full_path = selectData.full_path + '-' + data.tree_id;
  82. data.is_leaf = true;
  83. this.transaction = await this.db.beginTransaction();
  84. try {
  85. const result = await this.transaction.insert(this.tableName, data);
  86. if (children.length === 0) {
  87. await this.transaction.update(this.tableName,
  88. { is_leaf: false, quantity: 0, unit_price: 0, total_price: 0 },
  89. { where: { tid: tenderId, tree_id: selectData.tree_id } });
  90. }
  91. await this.transaction.commit();
  92. } catch(err) {
  93. this.transaction.rollback();
  94. throw err;
  95. }
  96. this._cacheMaxLid(tenderId, maxId + 1);
  97. // 查询应返回的结果
  98. const resultData = {};
  99. resultData.create = await this.getDataByKid(tenderId, data.tree_id);
  100. if (children.length === 0) resultData.update = await this.getDataByKid(tenderId, selectId);
  101. return resultData;
  102. }
  103. _filterStdData(stdData) {
  104. const result = {
  105. name: stdData.name,
  106. unit: stdData.unit,
  107. node_type: stdData.node_type,
  108. };
  109. result.code = stdData.code ? stdData.code : '';
  110. result.b_code = stdData.b_code ? stdData.b_code : '';
  111. return result;
  112. }
  113. async _addChildNodeData(tenderId, parentData, data) {
  114. if (tenderId <= 0) return undefined;
  115. if (!data) data = {};
  116. const pid = parentData ? parentData.tree_id : this.rootId;
  117. const maxId = await this._getMaxLid(tenderId);
  118. data.id = this.uuid.v4();
  119. data.tid = tenderId;
  120. data.tree_id = maxId + 1;
  121. data.tree_pid = pid;
  122. if (data.order === undefined) data.order = 1;
  123. data.level = parentData ? parentData.level + 1 : 1;
  124. data.full_path = parentData ? parentData.full_path + '-' + data.tree_id : '' + data.tree_id;
  125. if (data.is_leaf === undefined) data.is_leaf = true;
  126. const result = await this.transaction.insert(this.tableName, data);
  127. this._cacheMaxLid(tenderId, maxId + 1);
  128. return [result, data];
  129. }
  130. async _addChildAutoOrder(tenderId, parentData, data) {
  131. const findPreData = function(list, a) {
  132. if (!list || list.length === 0) { return null; }
  133. for (let i = 0, iLen = list.length; i < iLen; i++) {
  134. if (billsUtils.compareCode(list[i].code, a.code) > 0) {
  135. return i > 0 ? list[i - 1] : null;
  136. }
  137. }
  138. return list[list.length - 1];
  139. };
  140. const pid = parentData ? parentData.tree_id : this.rootId;
  141. const children = await this.getChildrenByParentId(tenderId, pid);
  142. const preData = findPreData(children, data);
  143. if (!preData || children.indexOf(preData) < children.length - 1) {
  144. await this._updateChildrenOrder(tenderId, pid, preData ? preData.order + 1 : 1);
  145. }
  146. data.order = preData ? preData.order + 1 : 1;
  147. const [addResult, node] = await this._addChildNodeData(tenderId, parentData, data);
  148. return [addResult, node];
  149. }
  150. async addStdNodeWithParent(tenderId, stdData, stdLib) {
  151. // 查询完整标准清单,并按层次排序
  152. const fullLevel = await stdLib.getFullLevelDataByFullPath(stdData.list_id, stdData.full_path);
  153. fullLevel.sort(function(x, y) {
  154. return x.level - y.level;
  155. });
  156. let isNew = false,
  157. node,
  158. firstNew,
  159. updateParent,
  160. addResult;
  161. const expandIds = [];
  162. this.transaction = await this.db.beginTransaction();
  163. try {
  164. // 从最顶层节点依次查询是否存在,否则添加
  165. for (let i = 0, len = fullLevel.length; i < len; i++) {
  166. const stdNode = fullLevel[i];
  167. if (isNew) {
  168. const newData = this._filterStdData(stdNode);
  169. newData.is_leaf = (i === len - 1);
  170. [addResult, node] = await this._addChildNodeData(tenderId, node, newData);
  171. } else {
  172. const parent = node;
  173. node = await this.getDataByCondition({
  174. tid: tenderId,
  175. tree_pid: parent ? parent.tree_id : this.rootId,
  176. code: stdNode.code,
  177. name: stdNode.name,
  178. });
  179. if (!node) {
  180. isNew = true;
  181. const newData = this._filterStdData(stdNode);
  182. newData.is_leaf = (i === len - 1);
  183. [addResult, node] = await this._addChildAutoOrder(tenderId, parent, newData);
  184. if (parent && parent.is_leaf) {
  185. await this.transaction.update(this.tableName, { id: parent.id, is_leaf: false,
  186. unit_price: 0, quantity: 0, total_price: 0});
  187. updateParent = parent;
  188. }
  189. firstNew = node;
  190. } else {
  191. expandIds.push(node.tree_id);
  192. }
  193. }
  194. }
  195. await this.transaction.commit();
  196. } catch (err) {
  197. await this.transaction.rollback();
  198. throw err;
  199. }
  200. // 查询应返回的结果
  201. let createData = [],
  202. updateData = [];
  203. if (firstNew) {
  204. createData = await this.getDataByFullPath(tenderId, firstNew.full_path + '%');
  205. updateData = await this.getNextsData(tenderId, firstNew.tree_pid, firstNew.order);
  206. if (updateParent) {
  207. updateData.push(await this.getDataByCondition({ id: updateParent.id }));
  208. }
  209. }
  210. return { create: createData, update: updateData };
  211. }
  212. async addBillsNode(tenderId, selectId, data) {
  213. return await this.addNode(tenderId, selectId, data ? data : {});
  214. }
  215. async addStdNode(tenderId, selectId, stdData) {
  216. const newData = this._filterStdData(stdData);
  217. const result = await this.addBillsNode(tenderId, selectId, newData);
  218. return result;
  219. }
  220. async addStdNodeAsChild(tenderId, selectId, stdData) {
  221. const newData = this._filterStdData(stdData);
  222. const result = await this.addChild(tenderId, selectId, newData);
  223. return result;
  224. }
  225. clearParentingData(data) {
  226. data.unit_price = 0;
  227. data.quantity = 0;
  228. data.total_price = 0;
  229. }
  230. _filterUpdateInvalidField(id, data) {
  231. const result = { id };
  232. for (const prop in data) {
  233. if (readOnlyFields.indexOf(prop) === -1) result[prop] = data[prop];
  234. }
  235. return result;
  236. }
  237. _checkCalcField(data) {
  238. for (const prop in data) {
  239. if (calcFields.indexOf(prop) >= 0) {
  240. return true;
  241. }
  242. }
  243. return false;
  244. }
  245. async updateCalc(tenderId, data) {
  246. const helper = this.ctx.helper;
  247. // 简单验证数据
  248. if (tenderId <= 0 || !this.ctx.tender) throw '标段不存在';
  249. if (!data) throw '提交数据错误';
  250. const datas = data instanceof Array ? data : [data];
  251. const ids = [];
  252. for (const row of datas) {
  253. if (tenderId !== row.tid) throw '提交数据错误';
  254. ids.push(row.id);
  255. }
  256. const decimal = this.ctx.tender.info.decimal;
  257. const conn = await this.db.beginTransaction();
  258. try {
  259. for (const row of datas) {
  260. const updateNode = await this.getDataById(row.id);
  261. if (!updateNode || tenderId !== updateNode.tid || row.tree_id !== updateNode.tree_id) throw '提交数据错误';
  262. let updateData;
  263. // 项目节、工程量清单相关
  264. if (row.b_code) {
  265. row.dgn_qty1 = 0;
  266. row.dgn_qty2 = 0;
  267. row.code = '';
  268. }
  269. if (row.code) row.b_code = '';
  270. if (this._checkCalcField(row)) {
  271. let calcData = JSON.parse(JSON.stringify(row));
  272. if (row.quantity !== undefined || row.unit_price !== undefined) {
  273. calcData.quantity = row.quantity === undefined ? updateNode.quantity : helper.round(row.quantity, decimal.qty);
  274. calcData.unit_price = row.unit_price === undefined ? updateNode.unit_price : helper.round(row.unit_price, decimal.up);
  275. calcData.total_price = helper.mul(calcData.quantity, calcData.unit_price, decimal.tp);
  276. } else if (row.total_price !== undefined ) {
  277. calcData.quantity = 0;
  278. calcData.unit_price = 0;
  279. calcData.total_price = helper.round(row.total_price, decimal.tp);
  280. }
  281. updateData = this._filterUpdateInvalidField(updateNode.id, this._.defaults(calcData, row));
  282. } else {
  283. updateData = this._filterUpdateInvalidField(updateNode.id, row);
  284. }
  285. await conn.update(this.tableName, updateData);
  286. }
  287. await conn.commit();
  288. } catch (err) {
  289. await conn.rollback();
  290. throw err;
  291. }
  292. return { update: await this.getDataById(ids) };
  293. }
  294. async pasteBlockData (tid, sid, pasteData, defaultData) {
  295. if ((tid <= 0) || (sid <= 0)) return [];
  296. if (!pasteData || pasteData.length <= 0) throw '复制数据错误';
  297. for (const pd of pasteData) {
  298. if (!pd || pd.length <= 0) throw '复制数据错误';
  299. pd.sort(function (x, y) {
  300. return x.level - y.level
  301. });
  302. if (pd[0].tree_pid !== pasteData[0][0].tree_pid) throw '复制数据错误:仅可操作同层节点';
  303. }
  304. const decimal = this.ctx.tender.info.decimal;
  305. this.newBills = false;
  306. const selectData = await this.getDataByKid(tid, sid);
  307. if (!selectData) throw '粘贴数据错误';
  308. const newParentPath = selectData.full_path.replace(selectData.tree_id, '');
  309. const pasteBillsData = [];
  310. let maxId = await this._getMaxLid(tid);
  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. tid: tid,
  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, decimal.up);
  344. newBills.quantity = this.ctx.helper.round(d.quantity, decimal.qty);
  345. newBills.total_price = this.ctx.helper.mul(newBills.quantity, newBills.unit_price, decimal.tp);
  346. } else {
  347. newBills.dgn_qty1 = this.ctx.helper.round(d.dgn_qty1, decimal.qty);
  348. newBills.dgn_qty2 = this.ctx.helper.round(d.dgn_qty2, 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, 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(tid, selectData.tree_pid, selectData.order + 1, pasteData.length);
  372. // 数据库创建新增节点数据
  373. if (pasteBillsData.length > 0) await this.transaction.insert(this.tableName, pasteBillsData);
  374. this._cacheMaxLid(tid, 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.tid, selectData.tree_pid, selectData.order + pasteData.length);
  382. return { create: pasteBillsData, update: updateData };
  383. }
  384. async importExcel(templateId, excelData, filter) {
  385. const AnalysisExcel = require('../lib/analysis_excel').AnalysisExcelTree;
  386. const analysisExcel = new AnalysisExcel(this.ctx, this.setting, ['code', 'b_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: false, filterCalc: true,
  390. });
  391. const orgMaxId = await this._getMaxLid(this.ctx.tender.id);
  392. const conn = await this.db.beginTransaction();
  393. try {
  394. await conn.delete(this.tableName, { tid: this.ctx.tender.id });
  395. const datas = [];
  396. for (const node of cacheTree.items) {
  397. const data = {
  398. id: node.id,
  399. tid: this.ctx.tender.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.tender.id, cacheTree.keyNodeId);
  424. return datas;
  425. } catch (err) {
  426. await conn.rollback();
  427. throw err;
  428. }
  429. }
  430. async getSumTp(tid) {
  431. const sql = 'SELECT Sum(total_price) As total_price FROM ' + this.tableName + ' Where tid = ? and is_leaf = true';
  432. const result = await this.db.queryOne(sql, [tid]);
  433. return result.total_price;
  434. }
  435. }
  436. module.exports = ControlPrice;