base_bills_service.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date
  7. * @version
  8. */
  9. const TreeService = require('./base_tree_service');
  10. // sql拼装器
  11. const rootId = -1;
  12. const calcFields = ['unit_price', 'sgfh_qty', 'sgfh_tp', 'sjcl_qty', 'sjcl_tp', 'qtcl_qty', 'qtcl_tp', 'deal_qty', 'deal_tp', 'dgn_qty1', 'dgn_qty2'];
  13. const readOnlyFields = ['id', 'tender_id', 'ledger_id', 'ledger_pid', 'order', 'level', 'full_path', 'is_leaf'];
  14. const upFields = ['unit_price'];
  15. const qtyFields = ['sgfh_qty', 'sjcl_qty', 'qtcl_qty', 'quantity', 'deal_qty'];
  16. const tpFields = ['sgfh_tp', 'sjcl_tp', 'qtcl_tp', 'total_price', 'deal_tp'];
  17. const measureType = require('../const/tender').measureType;
  18. const billsUtils = require('../lib/bills_utils');
  19. const SumLoad = require('../lib/sum_load');
  20. class BaseBillsSerivce extends TreeService {
  21. constructor (ctx, setting, relaPosName) {
  22. super(ctx, setting);
  23. this.relaPosService = relaPosName;
  24. }
  25. set relaPosService(posName) {
  26. this._posName = posName;
  27. }
  28. get relaPosService() {
  29. return this.ctx.service[this._posName];
  30. }
  31. // 继承方法
  32. clearParentingData(data) {
  33. data.unit_price = null;
  34. data.sgfh_qty = null;
  35. data.sgfh_tp = null;
  36. data.sjcl_qty = null;
  37. data.sjcl_tp = null;
  38. data.qtcl_qty = null;
  39. data.qtcl_tp = null;
  40. data.quantity = null;
  41. data.total_price = null;
  42. data.deal_qty = null;
  43. data.deal_tp = null;
  44. }
  45. /**
  46. * 从标准数据中提取有效数据
  47. * @param {Object} stdData - 从标准库中查询所得
  48. * @returns {name, unit, source, code, b_code}
  49. * @private
  50. */
  51. _filterStdData(stdData) {
  52. const result = {
  53. name: stdData.name,
  54. unit: stdData.unit,
  55. source: stdData.source,
  56. node_type: stdData.node_type,
  57. };
  58. result.code = stdData.code ? stdData.code : '';
  59. result.b_code = stdData.b_code ? stdData.b_code : '';
  60. return result;
  61. }
  62. async addBillsNode(tenderId, selectId, data, reviseId) {
  63. if (data) {
  64. if (reviseId) data.crid = reviseId;
  65. data.check_calc = 1;
  66. return await this.addNode(tenderId, selectId, data);
  67. } else {
  68. return await this.addNode(tenderId, selectId, {crid: reviseId, check_calc: 1});
  69. }
  70. }
  71. /**
  72. * 新增子节点,并排在所有子节点的末尾
  73. * @param {Number} tenderId - 标段Id
  74. * @param {Number} selectId - 父节点Id
  75. * @param {Object} data - 新增节点数据(编号名称等)
  76. * @returns {Promise<*>}
  77. */
  78. async addChild(tenderId, selectId, data, reviseId) {
  79. if ((tenderId <= 0) || (selectId <= 0)) {
  80. return [];
  81. }
  82. const selectData = await this.getDataByKid(tenderId, selectId);
  83. if (!selectData) {
  84. throw '新增节点数据错误';
  85. }
  86. const children = await this.getChildrenByParentId(tenderId, selectId);
  87. const maxId = await this._getMaxLid(tenderId);
  88. data.id = this.uuid.v4();
  89. data.tender_id = tenderId;
  90. data.ledger_id = maxId + 1;
  91. data.ledger_pid = selectData.ledger_id;
  92. data.level = selectData.level + 1;
  93. data.order = children.length + 1;
  94. data.full_path = selectData.full_path + '-' + data.ledger_id;
  95. data.is_leaf = true;
  96. data.check_calc = 1;
  97. if (reviseId) data.crid = reviseId;
  98. this.transaction = await this.db.beginTransaction();
  99. try {
  100. const result = await this.transaction.insert(this.tableName, data);
  101. if (children.length === 0) {
  102. await this.transaction.update(this.tableName,
  103. {
  104. is_leaf: false,
  105. sgfh_qty: null, sgfh_tp: null, qtcl_qty: null, qtcl_tp: null, sjcl_qty: null, sjcl_tp: null,
  106. quantity: null, unit_price: null, total_price: null, deal_qty: null, deal_tp: null
  107. },
  108. { where: {tender_id: tenderId, ledger_id: selectData.ledger_id} });
  109. }
  110. await this.transaction.commit();
  111. } catch(err) {
  112. this.transaction.rollback();
  113. throw err;
  114. }
  115. this._cacheMaxLid(tenderId, maxId + 1);
  116. // 查询应返回的结果
  117. const resultData = {};
  118. resultData.create = await this.getDataByKid(tenderId, data.ledger_id);
  119. if (children.length === 0) {
  120. resultData.update = await this.getDataByKid(tenderId, selectId);
  121. }
  122. return resultData;
  123. }
  124. /**
  125. * 添加节点(来自标准清单)
  126. * @param {Number} tenderId
  127. * @param {Number} selectId
  128. * @param {Object} stdData
  129. * @return {Promise<*>}
  130. */
  131. async addStdNode(tenderId, selectId, stdData, reviseId) {
  132. const newData = this._filterStdData(stdData);
  133. const result = await this.addBillsNode(tenderId, selectId, newData, reviseId);
  134. return result;
  135. }
  136. /**
  137. * 添加标准节点,将选择的标准节点,添加为子节点(排序为末尾)
  138. * @param {Number} tenderId - 标段Id
  139. * @param {Number} selectId - 添加目标节点Id
  140. * @param {Object} stdData - 标准节点数据
  141. * @returns {Promise<*>}
  142. */
  143. async addStdNodeAsChild(tenderId, selectId, stdData, reviseId) {
  144. const newData = this._filterStdData(stdData);
  145. const result = await this.addChild(tenderId, selectId, newData, reviseId);
  146. return result;
  147. }
  148. /**
  149. * 根据parentData, data新增数据(新增为parentData的最后一个子项)
  150. * @param {Number} tenderId - 标段id
  151. * @param {Object} parentData - 父项数据
  152. * @param {Object} data - 新增节点,初始数据
  153. * @return {Promise<*>} - 新增结果
  154. * @private
  155. */
  156. async _addChildNodeData(tenderId, parentData, data, reviseId) {
  157. if (tenderId <= 0) {
  158. return undefined;
  159. }
  160. if (!data) {
  161. data = {};
  162. }
  163. const pid = parentData ? parentData.ledger_id : rootId;
  164. const maxId = await this._getMaxLid(tenderId);
  165. data.id = this.uuid.v4();
  166. data.tender_id = tenderId;
  167. data.ledger_id = maxId + 1;
  168. data.ledger_pid = pid;
  169. if (data.order === undefined) {
  170. data.order = 1;
  171. }
  172. data.level = parentData ? parentData.level + 1 : 1;
  173. data.full_path = parentData ? parentData.full_path + '-' + data.ledger_id : '' + data.ledger_id;
  174. if (data.is_leaf === undefined) {
  175. data.is_leaf = true;
  176. }
  177. data.check_calc = 1;
  178. if (reviseId) data.crid = reviseId;
  179. const result = await this.transaction.insert(this.tableName, data);
  180. this._cacheMaxLid(tenderId, maxId + 1);
  181. return [result, data];
  182. }
  183. /**
  184. * 根据parentData, data新增数据(自动排序)
  185. * @param tenderId
  186. * @param parentData
  187. * @param data
  188. * @return {Promise<void>}
  189. * @private
  190. */
  191. async _addChildAutoOrder(tenderId, parentData, data, reviseId) {
  192. const self = this;
  193. const findPreData = function(list, a) {
  194. if (!list || list.length === 0) { return null; }
  195. for (let i = 0, iLen = list.length; i < iLen; i++) {
  196. if (billsUtils.compareCode(list[i].code, a.code) > 0) {
  197. return i > 0 ? list[i - 1] : null;
  198. }
  199. }
  200. return list[list.length - 1];
  201. };
  202. const pid = parentData ? parentData.ledger_id : rootId;
  203. const children = await this.getChildrenByParentId(tenderId, pid);
  204. const preData = findPreData(children, data);
  205. if (!preData || children.indexOf(preData) < children.length - 1) {
  206. await this._updateChildrenOrder(tenderId, pid, preData ? preData.order + 1 : 1);
  207. }
  208. data.order = preData ? preData.order + 1 : 1;
  209. const [addResult, node] = await this._addChildNodeData(tenderId, parentData, data, reviseId);
  210. return [addResult, node];
  211. }
  212. /**
  213. * 添加节点,并同步添加父节点
  214. * @param {Number} tenderId - 标段id
  215. * @param {Number} selectId - 选中节点id
  216. * @param {Object} stdData - 节点数据
  217. * @param {StandardLib} stdLib - 标准库
  218. * @return {Promise<void>}
  219. */
  220. async addStdNodeWithParent(tenderId, stdData, stdLib, reviseId) {
  221. // 查询完整标准清单,并按层次排序
  222. const fullLevel = await stdLib.getFullLevelDataByFullPath(stdData.list_id, stdData.full_path);
  223. fullLevel.sort(function(x, y) {
  224. return x.level - y.level;
  225. });
  226. let isNew = false,
  227. node,
  228. firstNew,
  229. updateParent,
  230. addResult;
  231. const expandIds = [];
  232. this.transaction = await this.db.beginTransaction();
  233. try {
  234. // 从最顶层节点依次查询是否存在,否则添加
  235. for (let i = 0, len = fullLevel.length; i < len; i++) {
  236. const stdNode = fullLevel[i];
  237. if (isNew) {
  238. const newData = this._filterStdData(stdNode);
  239. newData.is_leaf = (i === len - 1);
  240. [addResult, node] = await this._addChildNodeData(tenderId, node, newData, reviseId);
  241. } else {
  242. const parent = node;
  243. node = await this.getDataByCondition({
  244. tender_id: tenderId,
  245. ledger_pid: parent ? parent.ledger_id : rootId,
  246. code: stdNode.code,
  247. name: stdNode.name,
  248. });
  249. if (!node) {
  250. isNew = true;
  251. const newData = this._filterStdData(stdNode);
  252. newData.is_leaf = (i === len - 1);
  253. [addResult, node] = await this._addChildAutoOrder(tenderId, parent, newData, reviseId);
  254. if (parent && parent.is_leaf) {
  255. await this.transaction.update(this.tableName, { id: parent.id, is_leaf: false,
  256. unit_price: null, quantity: null, total_price: null, deal_qty: null, deal_tp: null});
  257. updateParent = parent;
  258. }
  259. firstNew = node;
  260. } else {
  261. expandIds.push(node.ledger_id);
  262. }
  263. }
  264. }
  265. await this.transaction.commit();
  266. } catch (err) {
  267. await this.transaction.rollback();
  268. throw err;
  269. }
  270. // 查询应返回的结果
  271. let createData = [],
  272. updateData = [];
  273. if (firstNew) {
  274. createData = await this.getDataByFullPath(tenderId, firstNew.full_path + '%');
  275. updateData = await this.getNextsData(tenderId, firstNew.ledger_pid, firstNew.order);
  276. if (updateParent) {
  277. updateData.push(await this.getDataByCondition({ id: updateParent.id }));
  278. }
  279. }
  280. return { create: createData, update: updateData };
  281. }
  282. /**
  283. * 过滤data中update方式不可提交的字段
  284. * @param {Number} id - 主键key
  285. * @param {Object} data
  286. * @return {Object<{id: *}>}
  287. * @private
  288. */
  289. _filterUpdateInvalidField(id, data) {
  290. const result = {
  291. id,
  292. };
  293. for (const prop in data) {
  294. if (readOnlyFields.indexOf(prop) === -1) {
  295. result[prop] = data[prop];
  296. }
  297. }
  298. return result;
  299. }
  300. /**
  301. * newData中,以orgData为基准,过滤掉orgData中未定义或值相等的部分
  302. * @param {Object} orgData
  303. * @param {Object} newData
  304. * @private
  305. */
  306. _filterChangedField(orgData, newData) {
  307. const result = {};
  308. let bChanged = false;
  309. for (const prop in orgData) {
  310. if (this._.isEmpty(newData[prop]) && newData[prop] !== orgData[prop]) {
  311. result[prop] = newData[prop];
  312. bChanged = true;
  313. }
  314. }
  315. return bChanged ? result : undefined;
  316. }
  317. /**
  318. * 检查data中是否含有计算字段
  319. * @param {Object} data
  320. * @return {boolean}
  321. * @private
  322. */
  323. _checkCalcField(data) {
  324. for (const prop in data) {
  325. if (calcFields.indexOf(prop) >= 0) {
  326. return true;
  327. }
  328. }
  329. return false;
  330. }
  331. /**
  332. * 提交数据 - 响应计算(增量方式计算)
  333. * @param {Number} tenderId
  334. * @param {Object} data
  335. * @return {Promise<*>}
  336. */
  337. async updateCalc(tenderId, data) {
  338. const helper = this.ctx.helper;
  339. // 简单验证数据
  340. if (tenderId <= 0 || !this.ctx.tender) {
  341. throw '标段不存在';
  342. }
  343. const info = this.ctx.tender.info;
  344. if (!data) {
  345. throw '提交数据错误';
  346. }
  347. const datas = data instanceof Array ? data : [data];
  348. const ids = [];
  349. for (const row of datas) {
  350. if (tenderId !== row.tender_id) {
  351. throw '提交数据错误';
  352. }
  353. ids.push(row.id);
  354. }
  355. this.transaction = await this.db.beginTransaction();
  356. try {
  357. for (const row of datas) {
  358. const updateNode = await this.getDataById(row.id);
  359. if (!updateNode || tenderId !== updateNode.tender_id || row.ledger_id !== updateNode.ledger_id) {
  360. throw '提交数据错误';
  361. }
  362. let updateData;
  363. // 更新单位或单价,全部数据都应重算
  364. if (row.unit !== undefined || row.unit_price !== undefined) {
  365. if (row.sgfh_qty === undefined) { row.sgfh_qty = updateNode.sgfh_qty; }
  366. if (row.sjcl_qty === undefined) { row.sjcl_qty = updateNode.sjcl_qty; }
  367. if (row.qtcl_qty === undefined) { row.qtcl_qty = updateNode.qtcl_qty; }
  368. if (row.deal_qty === undefined) { row.deal_qty = updateNode.deal_qty; }
  369. }
  370. // 项目节、工程量清单相关
  371. if (row.b_code) {
  372. row.dgn_qty1 = null;
  373. row.dgn_qty2 = null;
  374. row.code = null;
  375. }
  376. if (row.code) row.b_code = null;
  377. if (this._checkCalcField(row)) {
  378. let calcData = JSON.parse(JSON.stringify(row));
  379. calcData.check_calc = 1;
  380. const precision = helper.findPrecision(info.precision, row.unit ? row.unit : updateNode.unit);
  381. // 数量保留小数位数
  382. helper.checkFieldPrecision(calcData, qtyFields, precision.value);
  383. // 单位保留小数位数
  384. helper.checkFieldPrecision(calcData, upFields, info.decimal.up);
  385. // 未提交单价则读取数据库单价
  386. if (row.unit_price === undefined) calcData.unit_price = updateNode.unit_price;
  387. // 计算
  388. if (row.sgfh_qty !== undefined || row.sjcl_qty !== undefined || row.qtcl_qty !== undefined ||
  389. row.deal_qty !== undefined || row.unit_price) {
  390. if (row.sgfh_qty === undefined) calcData.sgfh_qty = updateNode.sgfh_qty;
  391. if (row.sjcl_qty === undefined) calcData.sjcl_qty = updateNode.sjcl_qty;
  392. if (row.qtcl_qty === undefined) calcData.qtcl_qty = updateNode.qtcl_qty;
  393. if (row.deal_qty === undefined) calcData.deal_qty = updateNode.deal_qty;
  394. calcData.quantity = helper.sum([calcData.sgfh_qty, calcData.sjcl_qty, calcData.qtcl_qty]);
  395. calcData.sgfh_tp = helper.mul(calcData.sgfh_qty, calcData.unit_price, info.decimal.tp);
  396. calcData.sjcl_tp = helper.mul(calcData.sjcl_qty, calcData.unit_price, info.decimal.tp);
  397. calcData.qtcl_tp = helper.mul(calcData.qtcl_qty, calcData.unit_price, info.decimal.tp);
  398. calcData.total_price = helper.mul(calcData.quantity, calcData.unit_price, info.decimal.tp);
  399. calcData.deal_tp = helper.mul(calcData.deal_qty, calcData.unit_price, info.decimal.tp);
  400. } else if (row.sgfh_tp !== undefined || row.sjcl_tp !== undefined || row.qtcl_tp !== undefined || row.deal_tp !== undefined) {
  401. calcData.sgfh_qty = null;
  402. calcData.sjcl_qty = null;
  403. calcData.qtcl_qty = null;
  404. calcData.quantity = null;
  405. calcData.deal_qty = null;
  406. calcData.sgfh_tp = helper.round(row.sgfh_tp !== undefined ? calcData.row.sgfh_tp : updateNode.sgfh_tp, info.decimal.tp);
  407. calcData.sjcl_tp = helper.round(row.sgfh_tp !== undefined ? calcData.row.sjcl_tp : updateNode.sjcl_tp, info.decimal.tp);
  408. calcData.qtcl_tp = helper.round(row.sgfh_tp !== undefined ? calcData.row.qtcl_tp : updateNode.qtcl_tp, info.decimal.tp);
  409. calcData.total_price = helper.sum([calcData.sgfh_tp, calcData.sjcl_tp, calcData.qtcl_tp]);
  410. calcData.deal_tp = helper.round(row.deal_tp !== undefined ? calcData.row.deal_tp : updateNode.deal_tp, info.decimal.tp);
  411. } else if (row.unit_price !== undefined) {
  412. calcData.sgfh_tp = helper.mul(calcData.sgfh_qty, calcData.unit_price, info.decimal.tp);
  413. calcData.sjcl_tp = helper.mul(calcData.sjcl_qty, calcData.unit_price, info.decimal.tp);
  414. calcData.qtcl_tp = helper.mul(calcData.qtcl_qty, calcData.unit_price, info.decimal.tp);
  415. calcData.total_price = helper.mul(calcData.quantity, calcData.unit_price, info.decimal.tp);
  416. calcData.deal_tp = helper.mul(calcData.deal_qty, calcData.unit_price, info.decimal.tp);
  417. }
  418. updateData = this._filterUpdateInvalidField(updateNode.id, calcData);
  419. } else {
  420. updateData = this._filterUpdateInvalidField(updateNode.id, row);
  421. }
  422. await this.transaction.update(this.tableName, updateData);
  423. }
  424. await this.transaction.commit();
  425. this.transaction = null;
  426. } catch (err) {
  427. await this.transaction.rollback();
  428. this.transaction = null;
  429. throw err;
  430. }
  431. return { update: await this.getDataById(ids) };
  432. }
  433. // 统计方法
  434. async addUp(condition) {
  435. if (!condition.tender_id) throw new TypeError('statistical lacks necessary parameter');
  436. const sql = 'SELECT Sum(total_price) As total_price, Sum(deal_tp) As deal_tp' +
  437. ' FROM ' + this.departTableName(condition.tender_id) + this.ctx.helper.whereSql(condition);
  438. const result = await this.db.queryOne(sql);
  439. return result;
  440. }
  441. // 导入Excel
  442. async importGclExcel(id, sheet, data) {
  443. const node = await this.getDataById(id);
  444. if (!node || !node.is_leaf || node.tender_id !== this.ctx.tender.id) throw '数据错误';
  445. const maxId = await this._getMaxLid(this.ctx.tender.id);
  446. const AnalysisExcel = require('../lib/analysis_excel').AnalysisGclExcelTree;
  447. const analysisExcel = new AnalysisExcel(this.ctx);
  448. const cacheData = analysisExcel.analysisData(sheet, node, maxId, data);
  449. if (!cacheData) throw '导入数据错误,请检查Excel文件后重试';
  450. const datas = [];
  451. for (const node of cacheData.items) {
  452. const data = {
  453. id: node.id, tender_id: this.ctx.tender.id,
  454. ledger_id: node.ledger_id,
  455. ledger_pid: node.ledger_pid,
  456. level: node.level,
  457. order: node.order,
  458. is_leaf: !node.children || node.children.length === 0,
  459. full_path: node.full_path,
  460. b_code: node.b_code,
  461. name: node.name,
  462. unit: node.unit,
  463. unit_price: node.unit_price,
  464. crid: node.crid,
  465. };
  466. if (this.ctx.tender.data.measure_type === measureType.tz.value) {
  467. data.sgfh_qty = node.quantity;
  468. data.sgfh_tp = node.total_price;
  469. data.quantity = node.quantity;
  470. data.total_price = node.total_price;
  471. } else if (this.ctx.tender.data.measure_type === measureType.gcl.value) {
  472. data.deal_qty = node.quantity;
  473. data.deal_tp = node.total_price;
  474. }
  475. datas.push(data);
  476. }
  477. const conn = await this.db.beginTransaction();
  478. try {
  479. await this.db.update(this.tableName, {id: node.id, is_leaf: false});
  480. await this.db.insert(this.tableName, datas);
  481. await conn.commit();
  482. } catch(err) {
  483. await conn.rollback();
  484. throw err;
  485. }
  486. this._cacheMaxLid(this.ctx.tender.id, cacheData.keyNodeId);
  487. node.is_leaf = false;
  488. return { create: datas, update: [node]};
  489. }
  490. async deal2sgfh(tid) {
  491. const sql = 'UPDATE ' + this.tableName + ' SET sgfh_qty = deal_qty,' +
  492. ' quantity = IFNULL(deal_qty, 0) + IFNULL(sjcl_qty, 0) + IFNULL(qtcl_qty, 0), ' +
  493. ' sgfh_tp = deal_tp,' +
  494. ' total_price = IFNULL(deal_tp, 0) + IFNULL(sjcl_tp, 0) + IFNULL(qtcl_tp, 0)' +
  495. ' WHERE tender_id = ?';
  496. const sqlParam = [tid];
  497. await this.db.query(sql, sqlParam);
  498. }
  499. _calcExpr(data, field, expr, defaultValue, precision) {
  500. if (expr) {
  501. try {
  502. data[field] = this.ctx.helper.round(this.ctx.helper.calcExpr(expr), precision.value);
  503. } catch (err) {
  504. }
  505. } else {
  506. data[field] = this.ctx.helper.round(defaultValue, precision.value);
  507. }
  508. }
  509. async pasteBlockData (tid, sid, pasteData, defaultData) {
  510. if ((tid <= 0) || (sid <= 0)) return [];
  511. if (!pasteData || pasteData.length <= 0) throw '复制数据错误';
  512. for (const pd of pasteData) {
  513. if (!pd || pd.length <= 0) throw '复制数据错误';
  514. pd.sort(function (x, y) {
  515. return x.level - y.level
  516. });
  517. if (pd[0].ledger_pid !== pasteData[0][0].ledger_pid) throw '复制数据错误:仅可操作同层节点';
  518. }
  519. const selectData = await this.getDataByKid(tid, sid);
  520. if (!selectData) throw '粘贴数据错误';
  521. const newParentPath = selectData.full_path.replace(selectData.ledger_id, '');
  522. const pasteBillsData = [], pastePosData = [], leafBillsId = [];
  523. const tpDecimal = this.ctx.tender.info.decimal.tp;
  524. let maxId = await this._getMaxLid(this.ctx.tender.id);
  525. for (const [i, pd] of pasteData.entries()) {
  526. for (const d of pd) {
  527. d.children = pd.filter(function (x) {
  528. return x.ledger_pid === d.ledger_id;
  529. });
  530. }
  531. const pbd = [];
  532. for (const [j, d] of pd.entries()) {
  533. const newBills = {
  534. id: this.uuid.v4(),
  535. tender_id: tid,
  536. ledger_id: maxId + j + 1,
  537. ledger_pid: j === 0 ? selectData.ledger_pid : d.ledger_pid,
  538. level: d.level + selectData.level - pd[0].level,
  539. order: j === 0 ? selectData.order + i + 1 : d.order,
  540. is_leaf: d.is_leaf,
  541. code: d.code,
  542. b_code: d.b_code,
  543. name: d.name,
  544. unit: d.unit,
  545. unit_price: this.ctx.helper.round(d.unit_price, this.ctx.tender.info.decimal.up),
  546. source: d.source,
  547. remark: d.remark,
  548. drawing_code: d.drawing_code,
  549. memo: d.memo,
  550. node_type: d.node_type,
  551. sgfh_expr: d.sgfh_expr,
  552. sjcl_expr: d.sjcl_expr,
  553. qtcl_expr: d.qtcl_expr,
  554. check_calc: 1,
  555. };
  556. for (const c of d.children) {
  557. c.ledger_pid = newBills.ledger_id;
  558. }
  559. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, newBills.unit);
  560. newBills.deal_qty = this.ctx.helper.round(d.deal_qty, precision.value);
  561. if (d.pos && d.pos.length > 0) {
  562. for (const pos of d.pos) {
  563. const newPos = {
  564. id: this.uuid.v4(),
  565. tid: tid,
  566. lid: newBills.id,
  567. name: pos.name,
  568. drawing_code: pos.drawing_code,
  569. add_user: this.ctx.session.sessionUser.accountId,
  570. in_time: new Date(),
  571. porder: pos.porder,
  572. position: pos.position,
  573. sgfh_expr: pos.sgfh_expr ? pos.sgfh_expr : '',
  574. sjcl_expr: pos.sjcl_expr ? pos.sjcl_expr : '',
  575. qtcl_expr: pos.qtcl_expr ? pos.qtcl_expr : '',
  576. add_stage: 0,
  577. add_times: 0,
  578. };
  579. this._calcExpr(newPos, 'sgfh_qty', pos.sgfh_expr, pos.sgfh_qty, precision);
  580. this._calcExpr(newPos, 'sjcl_qty', pos.sjcl_expr, pos.sjcl_qty, precision);
  581. this._calcExpr(newPos, 'qtcl_qty', pos.qtcl_expr, pos.qtcl_qty, precision);
  582. newPos.quantity = this.ctx.helper.add(newPos.sgfh_qty,
  583. this.ctx.helper.add(newPos.sjcl_qty, newPos.qtcl_qty));
  584. newBills.sgfh_qty = this.ctx.helper.add(newBills.sgfh_qty, newPos.sgfh_qty);
  585. newBills.sjcl_qty = this.ctx.helper.add(newBills.sjcl_qty, newPos.sjcl_qty);
  586. newBills.qtcl_qty = this.ctx.helper.add(newBills.qtcl_qty, newPos.qtcl_qty);
  587. if (defaultData) this.ctx.helper._.assignIn(newPos, defaultData);
  588. pastePosData.push(newPos);
  589. }
  590. } else {
  591. this._calcExpr(newBills, 'sgfh_qty', newBills.sgfh_expr, d.sgfh_qty, precision);
  592. this._calcExpr(newBills, 'sjcl_qty', newBills.sjcl_expr, d.sjcl_qty, precision);
  593. this._calcExpr(newBills, 'qtcl_qty', newBills.qtcl_expr, d.qtcl_qty, precision);
  594. }
  595. newBills.quantity = this.ctx.helper.add(newBills.sgfh_qty,
  596. this.ctx.helper.add(newBills.sjcl_qty, newBills.qtcl_qty));
  597. newBills.sgfh_tp = this.ctx.helper.mul(newBills.sgfh_qty, newBills.unit_price, tpDecimal);
  598. newBills.sjcl_tp = this.ctx.helper.mul(newBills.qtcl_qty, newBills.unit_price, tpDecimal);
  599. newBills.qtcl_tp = this.ctx.helper.mul(newBills.sjcl_qty, newBills.unit_price, tpDecimal);
  600. newBills.total_price = this.ctx.helper.mul(newBills.quantity, newBills.unit_price, tpDecimal);
  601. newBills.deal_tp = this.ctx.helper.mul(newBills.deal_qty, newBills.unit_price, tpDecimal);
  602. if (defaultData) this.ctx.helper._.assignIn(newBills, defaultData);
  603. pbd.push(newBills);
  604. }
  605. for (const d of pbd) {
  606. const parent = pbd.find(function (x) {
  607. return x.ledger_id === d.ledger_pid;
  608. });
  609. d.full_path = parent
  610. ? parent.full_path + '-' + d.ledger_id
  611. : newParentPath + d.ledger_id;
  612. if (defaultData) this.ctx.helper._.assignIn(pbd, defaultData);
  613. pasteBillsData.push(d);
  614. }
  615. maxId = maxId + pbd.length;
  616. }
  617. this.transaction = await this.db.beginTransaction();
  618. try {
  619. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  620. await this._updateChildrenOrder(tid, selectData.ledger_pid, selectData.order + 1, pasteData.length);
  621. // 数据库创建新增节点数据
  622. if (pasteBillsData.length > 0) {
  623. const newData = await this.transaction.insert(this.tableName, pasteBillsData);
  624. }
  625. this._cacheMaxLid(tid, maxId);
  626. if (pastePosData.length > 0) {
  627. await this.transaction.insert(this.relaPosService.tableName, pastePosData);
  628. }
  629. await this.transaction.commit();
  630. } catch (err) {
  631. await this.transaction.rollback();
  632. throw err;
  633. }
  634. // 查询应返回的结果
  635. const updateData = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + pasteData.length);
  636. return {
  637. ledger: { create: pasteBillsData, update: updateData },
  638. pos: pastePosData,
  639. };
  640. }
  641. async sumLoad(lid, tenders) {
  642. const maxId = await this._getMaxLid(this.ctx.tender.id);
  643. const select = await this.getDataById(lid);
  644. const sumLoad = new SumLoad(this.ctx);
  645. const loadTree = await sumLoad.loadGatherGcl(select, maxId, tenders, {
  646. });
  647. const result = loadTree.getUpdateData();
  648. const conn = await this.db.beginTransaction();
  649. try {
  650. this._cacheMaxLid(this.ctx.tender.id, loadTree.keyNodeId);
  651. await conn.update(this.tableName, result.update);
  652. await conn.insert(this.tableName, result.create);
  653. await conn.commit();
  654. return result;
  655. } catch (err) {
  656. console.log(err);
  657. await conn.rollback();
  658. throw (err.stack ? '导入工程量数据出错': err);
  659. }
  660. }
  661. }
  662. module.exports = BaseBillsSerivce;