base_bills_service.js 28 KB

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