base_bills_service.js 29 KB

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