control_price.js 19 KB

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