base_bills_service.js 29 KB

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