base_bills_service.js 28 KB

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