ledger.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. 'use strict';
  2. /**
  3. * 标段--台账 数据模型
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/12/1
  7. * @version
  8. */
  9. const needField = {
  10. id: 'ledger_id',
  11. pid: 'ledger_pid',
  12. order: 'order',
  13. level: 'level',
  14. fullPath: 'full_path',
  15. isLeaf: 'is_leaf',
  16. };
  17. const keyFields = {
  18. table: ['id'],
  19. index: ['tender_id', 'ledger_id'],
  20. };
  21. // 以下字段仅可通过树结构操作改变,不可直接通过update方式从接口提交,发现时过滤
  22. const readOnlyFields = ['id', 'tender_id', 'ledger_id', 'ledger_pid', 'order', 'level', 'full_path', 'is_leaf'];
  23. const calcFields = ['unit_price', 'sgfh_qty', 'sgfh_tp', 'sjcl_qty', 'sjcl_tp', 'qtcl_qty', 'qtcl_tp', 'deal_qty', 'deal_tp', 'dgn_qty1', 'dgn_qty2'];
  24. const upFields = ['unit_price'];
  25. const qtyFields = ['sgfh_qty', 'sjcl_qty', 'qtcl_qty', 'quantity', 'deal_qty', 'dgn_qty1', 'dgn_qty2'];
  26. const tpFields = ['sgfh_tp', 'sjcl_tp', 'qtcl_tp', 'total_price', 'deal_tp'];
  27. const rootId = -1;
  28. const keyPre = 'tender_node_maxId:';
  29. module.exports = app => {
  30. class Ledger extends app.BaseBillsService {
  31. /**
  32. * 构造函数
  33. *
  34. * @param {Object} ctx - egg全局变量
  35. * @return {void}
  36. */
  37. constructor(ctx) {
  38. super(ctx, {
  39. mid: 'tender_id',
  40. kid: 'ledger_id',
  41. pid: 'ledger_pid',
  42. order: 'order',
  43. level: 'level',
  44. isLeaf: 'is_leaf',
  45. fullPath: 'full_path',
  46. keyPre: 'ledger_bills_maxLid:',
  47. uuid: true,
  48. });
  49. this.tableName = 'ledger';
  50. }
  51. /**
  52. * 新增数据(供内部或其他service类调用, controller不可直接使用)
  53. * @param {Array|Object} data - 新增数据
  54. * @param {Number} tenderId - 标段id
  55. * @param {Object} transaction - 新增事务
  56. * @return {Promise<boolean>} - {Promise<是否正确新增成功>}
  57. */
  58. async innerAdd(data, tenderId, transaction) {
  59. const datas = data instanceof Array ? data : [data];
  60. if (tenderId <= 0) {
  61. throw '标段id错误';
  62. }
  63. if (datas.length <= 0) {
  64. throw '插入数据为空';
  65. }
  66. if (!transaction) {
  67. throw '内部错误';
  68. }
  69. // 整理数据
  70. const insertData = [];
  71. for (const tmp of datas) {
  72. tmp.ledger_id = tmp.template_id;
  73. tmp.ledger_pid = tmp.pid;
  74. tmp.tender_id = tenderId;
  75. delete tmp.template_id;
  76. delete tmp.pid;
  77. tmp.id = this.uuid.v4();
  78. insertData.push(tmp);
  79. }
  80. const operate = await transaction.insert(this.tableName, insertData);
  81. return operate.affectedRows === datas.length;
  82. }
  83. /**
  84. * 新增数据
  85. *
  86. * @param {Object} data - 新增的数据(可批量)
  87. * @param {Number} tenderId - 标段id
  88. * @return {Boolean} - 返回新增的结果
  89. */
  90. async add(data, tenderId) {
  91. this.transaction = await this.db.beginTransaction();
  92. let result = false;
  93. try {
  94. result = await this.innerAdd(data, tenderId, this.transaction);
  95. if (!result) {
  96. throw '新增数据错误';
  97. }
  98. await this.transaction.commit();
  99. } catch (error) {
  100. await this.transaction.rollback();
  101. result = false;
  102. }
  103. return result;
  104. }
  105. /**
  106. * 根据节点Id获取数据
  107. *
  108. * @param {Number} tenderId - 标段id
  109. * @param {Number} nodeId - 项目节/工程量清单节点id
  110. * @return {Object} - 返回查询到的节点数据
  111. */
  112. async getDataByNodeId(tenderId, nodeId) {
  113. if ((nodeId <= 0) || (tenderId <= 0)) {
  114. return undefined;
  115. }
  116. this.initSqlBuilder();
  117. this.sqlBuilder.setAndWhere('tender_id', {
  118. value: tenderId,
  119. operate: '=',
  120. });
  121. this.sqlBuilder.setAndWhere('ledger_id', {
  122. value: nodeId,
  123. operate: '=',
  124. });
  125. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  126. const data = await this.db.queryOne(sql, sqlParam);
  127. return data;
  128. }
  129. /**
  130. * 根据节点Id获取数据
  131. * @param {Number} tenderId - 标段Id
  132. * @param {Array} nodesIds - 节点Id
  133. * @return {Array}
  134. */
  135. async getDataByNodeIds(tenderId, nodesIds) {
  136. if (tenderId <= 0) {
  137. return [];
  138. }
  139. this.initSqlBuilder();
  140. this.sqlBuilder.setAndWhere('tender_id', {
  141. value: tenderId,
  142. operate: '=',
  143. });
  144. this.sqlBuilder.setAndWhere('ledger_id', {
  145. value: nodesIds,
  146. operate: 'in',
  147. });
  148. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  149. const data = await this.db.query(sql, sqlParam);
  150. return this._.sortBy(data, function (d) {
  151. return nodesIds.indexOf(d.ledger_id);
  152. });
  153. }
  154. /**
  155. * 根据主键id获取数据
  156. * @param {Array|Number} id - 主键id
  157. * @return {Promise<*>}
  158. */
  159. async getDataByIds(id) {
  160. if (!id) {
  161. return;
  162. }
  163. const ids = id instanceof Array ? id : [id];
  164. if (ids.length === 0) {
  165. return;
  166. }
  167. this.initSqlBuilder();
  168. this.sqlBuilder.setAndWhere('id', {
  169. value: ids,
  170. operate: 'in',
  171. });
  172. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  173. const data = await this.db.query(sql, sqlParam);
  174. return data;
  175. }
  176. /**
  177. * 根据 父节点id 获取子节点
  178. * @param tenderId
  179. * @param nodeId
  180. * @return {Promise<*>}
  181. */
  182. async getChildrenByParentId(tenderId, nodeId) {
  183. if (tenderId <= 0 || !nodeId) {
  184. return undefined;
  185. }
  186. const nodeIds = nodeId instanceof Array ? nodeId : [nodeId];
  187. if (nodeIds.length === 0) {
  188. return [];
  189. }
  190. this.initSqlBuilder();
  191. this.sqlBuilder.setAndWhere('tender_id', {
  192. value: tenderId,
  193. operate: '=',
  194. });
  195. this.sqlBuilder.setAndWhere('ledger_pid', {
  196. value: nodeIds,
  197. operate: 'in',
  198. });
  199. this.sqlBuilder.orderBy = [['order', 'ASC']];
  200. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  201. const data = await this.db.query(sql, sqlParam);
  202. return data;
  203. }
  204. /**
  205. * 获取项目工程量
  206. * @param tenderId
  207. * @returns {Promise<*>}
  208. */
  209. async getGatherGclBills(tenderId) {
  210. const sql = 'SELECT `b_code`, `name`, `unit`, `unit_price`, ' +
  211. ' Sum(`quantity`) As `quantity`, Sum(`total_price`) As `total_price`, ' +
  212. ' Sum(`deal_qty`) As `deal_qty`, Sum(`deal_tp`) As `deal_tp` ' +
  213. ' From ?? ' +
  214. ' WHERE `tender_id` = ? And `b_code` And `is_leaf` ' +
  215. ' GROUP BY `b_code`, `name`, `unit`, `unit_price`';
  216. const sqlParam = [this.tableName, tenderId];
  217. return await this.db.query(sql, sqlParam);
  218. }
  219. async getTenderUsedUnits(tenderId) {
  220. const sql = 'SELECT unit ' +
  221. ' FROM ' + this.tableName +
  222. ' WHERE tender_id = ? and is_leaf = true' +
  223. ' GROUP By unit';
  224. const sqlParam = [tenderId];
  225. const units = await this.db.query(sql, sqlParam);
  226. return this._.map(units, 'unit');
  227. }
  228. /**
  229. * 统计子节点total_price
  230. * @param {Number} tenderId - 标段id
  231. * @param {Number} pid - 父节点id
  232. * @param {Number} order - order取值
  233. * @param {String} orderOperate - order比较操作符
  234. * @return {Promise<void>}
  235. */
  236. async addUpChildren(tenderId, pid, order, orderOperate) {
  237. this.initSqlBuilder();
  238. const sql = ['SELECT SUM(??) As value FROM ?? ', ' WHERE '];
  239. const sqlParam = ['total_price', this.tableName];
  240. sql.push(' ?? = ' + tenderId);
  241. sqlParam.push('tender_id');
  242. sql.push(' And ?? = ' + pid);
  243. sqlParam.push('ledger_pid');
  244. sql.push(' And ?? ' + orderOperate + ' ' + order);
  245. sqlParam.push('order');
  246. const result = await this.db.queryOne(sql.join(''), sqlParam);
  247. return result.value;
  248. }
  249. /**
  250. * 删除相关数据 用于继承
  251. * @param mid
  252. * @param deleteData
  253. * @returns {Promise<void>}
  254. * @private
  255. */
  256. async _deleteRelaData(mid, deleteData) {
  257. await this.ctx.service.pos.deletePosData(this.transaction, mid, this._.map(deleteData, 'id'));
  258. }
  259. /**
  260. * 过滤data中update方式不可提交的字段
  261. * @param {Number} id - 主键key
  262. * @param {Object} data
  263. * @return {Object<{id: *}>}
  264. * @private
  265. */
  266. // _filterUpdateInvalidField(id, data) {
  267. // const result = {
  268. // id,
  269. // };
  270. // for (const prop in data) {
  271. // if (readOnlyFields.indexOf(prop) === -1) {
  272. // result[prop] = data[prop];
  273. // }
  274. // }
  275. // return result;
  276. // }
  277. /**
  278. * newData中,以orgData为基准,过滤掉orgData中未定义或值相等的部分
  279. * @param {Object} orgData
  280. * @param {Object} newData
  281. * @private
  282. */
  283. _filterChangedField(orgData, newData) {
  284. const result = {};
  285. let bChanged = false;
  286. for (const prop in orgData) {
  287. if (this._.isEmpty(newData[prop]) && newData[prop] !== orgData[prop]) {
  288. result[prop] = newData[prop];
  289. bChanged = true;
  290. }
  291. }
  292. return bChanged ? result : undefined;
  293. }
  294. _checkField(data, field) {
  295. const fields = field instanceof Array ? field : [field];
  296. for (const prop in data) {
  297. if (fields.indexOf(prop) >= 0) {
  298. return true;
  299. }
  300. }
  301. return false;
  302. }
  303. /**
  304. * 检查data中是否含有计算字段
  305. * @param {Object} data
  306. * @return {boolean}
  307. * @private
  308. */
  309. // _checkCalcField(data) {
  310. // for (const prop in data) {
  311. // if (calcFields.indexOf(prop) >= 0) {
  312. // return true;
  313. // }
  314. // }
  315. // return false;
  316. // }
  317. /**
  318. * 复制粘贴整块
  319. * @param {Number} tenderId - 标段Id
  320. * @param {Number} selectId - 选中几点Id
  321. * @param {Array} block - 复制节点Id
  322. * @return {Object} - 提价后的数据(其中新增粘贴数据,只返回第一层)
  323. */
  324. async pasteBlock(tenderId, selectId, block) {
  325. if ((tenderId <= 0) || (selectId <= 0)) {
  326. return [];
  327. }
  328. const selectData = await this.getDataByNodeId(this.ctx.tender.id, selectId);
  329. if (!selectData) {
  330. throw '位置数据错误';
  331. }
  332. const newParentPath = selectData.full_path.replace(selectData.ledger_id, '');
  333. const copyNodes = await this.getDataByNodeIds(tenderId, block);
  334. if (!copyNodes || copyNodes.length <= 0) {
  335. throw '复制数据错误';
  336. }
  337. let bSameParent = true;
  338. for (const node of copyNodes) {
  339. if (node.ledger_pid !== copyNodes[0].ledger_pid) {
  340. bSameParent = false;
  341. break;
  342. }
  343. }
  344. if (!bSameParent) {
  345. throw '复制数据错误:仅可操作同层节点';
  346. }
  347. const orgParentPath = copyNodes[0].full_path.replace(copyNodes[0].ledger_id, '');
  348. const newIds = [];
  349. this.transaction = await this.db.beginTransaction();
  350. try {
  351. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  352. await this._updateChildrenOrder(tenderId, selectData.ledger_pid, selectData.order + 1);
  353. // 数据库创建新增节点数据
  354. for (let iNode = 0; iNode < copyNodes.length; iNode++) {
  355. const node = copyNodes[iNode];
  356. let datas = await this.getDataByFullPath(tenderId, node.full_path + '%');
  357. datas = this._.sortBy(datas, 'level');
  358. const maxId = await this._getMaxLid(this.ctx.tender.id);
  359. const leafBillsId = [];
  360. // 计算粘贴数据中需更新部分
  361. for (let index = 0; index < datas.length; index++) {
  362. const data = datas[index];
  363. const newId = maxId + index + 1;
  364. const idChange = {
  365. org: data.id,
  366. };
  367. data.id = this.uuid.v4();
  368. idChange.new = data.id;
  369. data.tender_id = this.ctx.tender.id;
  370. if (!data.is_leaf) {
  371. for (const children of datas) {
  372. children.full_path = children.full_path.replace('-' + data.ledger_id, '-' + newId);
  373. if (children.ledger_pid === data.ledger_id) {
  374. children.ledger_pid = newId;
  375. }
  376. }
  377. } else {
  378. data.full_path = data.full_path.replace('-' + data.ledger_id, '-' + newId);
  379. }
  380. data.ledger_id = newId;
  381. data.full_path = data.full_path.replace(orgParentPath, newParentPath);
  382. if (data.ledger_pid === node.ledger_pid) {
  383. data.ledger_pid = selectData.ledger_pid;
  384. data.order = selectData.order + iNode + 1;
  385. }
  386. data.level = data.level + selectData.level - copyNodes[0].level;
  387. if (data.is_leaf) {
  388. leafBillsId.push(idChange);
  389. }
  390. newIds.push(data.id);
  391. }
  392. const newData = await this.transaction.insert(this.tableName, datas);
  393. for (const id of leafBillsId) {
  394. await this.ctx.service.pos.copyBillsPosData(id.org, id.new, this.transaction);
  395. }
  396. this._cacheMaxLid(tenderId, maxId + datas.length);
  397. }
  398. await this.transaction.commit();
  399. } catch (err) {
  400. await this.transaction.rollback();
  401. throw err;
  402. }
  403. // 查询应返回的结果
  404. const order = [];
  405. for (let i = 1; i <= copyNodes.length; i++) {
  406. order.push(selectData.order + i);
  407. }
  408. const createData = await this.getDataByIds(newIds);
  409. const updateData = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + copyNodes.length);
  410. const posData = await this.ctx.service.pos.getPosData({ lid: newIds });
  411. return {
  412. ledger: { create: createData, update: updateData },
  413. pos: posData,
  414. };
  415. }
  416. /**
  417. * 提交数据 - 响应计算(增量方式计算)
  418. * @param {Number} tenderId
  419. * @param {Object} data
  420. * @return {Promise<*>}
  421. */
  422. // async updateCalc(tenderId, data) {
  423. // // 简单验证数据
  424. // if (tenderId <= 0 || !this.ctx.tender) {
  425. // throw '标段不存在';
  426. // }
  427. // const info = this.ctx.tender.info;
  428. // if (!data) {
  429. // throw '提交数据错误';
  430. // }
  431. // const datas = data instanceof Array ? data : [data];
  432. // const ids = [];
  433. // for (const row of datas) {
  434. // if (tenderId !== row.tender_id) {
  435. // throw '提交数据错误';
  436. // }
  437. // ids.push(row.id);
  438. // }
  439. //
  440. // this.transaction = await this.db.beginTransaction();
  441. // try {
  442. // for (const row of datas) {
  443. // const updateNode = await this.getDataById(row.id);
  444. // if (!updateNode || tenderId !== updateNode.tender_id || row.ledger_id !== updateNode.ledger_id) {
  445. // throw '提交数据错误';
  446. // }
  447. // let updateData;
  448. // if (row.unit) {
  449. // if (row.sgfh_qty === undefined) { row.sgfh_qty = updateNode.sgfh_qty; }
  450. // if (row.sjcl_qty === undefined) { row.sjcl_qty = updateNode.sjcl_qty; }
  451. // if (row.qtcl_qty === undefined) { row.qtcl_qty = updateNode.qtcl_qty; }
  452. // if (row.deal_qty === undefined) { row.deal_qty = updateNode.deal_qty; }
  453. // }
  454. // if (row.b_code) {
  455. // row.dgn_qty1 = null;
  456. // row.dgn_qty2 = null;
  457. // }
  458. // if (this._checkCalcField(row)) {
  459. // let calcData = JSON.parse(JSON.stringify(row));
  460. // const precision = this.ctx.helper.findPrecision(info.precision, row.unit ? row.unit : updateNode.unit);
  461. // // 数量保留小数位数
  462. // this.ctx.helper.checkFieldPrecision(calcData, qtyFields, precision.value);
  463. // // 单位保留小数位数
  464. // this.ctx.helper.checkFieldPrecision(calcData, upFields, info.decimal.up);
  465. // // 未提交单价则读取数据库单价
  466. // if (row.unit_price === undefined) calcData.unit_price = updateNode.unit_price;
  467. // // 计算
  468. // if (row.sgfh_qty !== undefined || row.sjcl_qty !== undefined || row.qtcl_qty !== undefined ||
  469. // row.deal_qty !== undefined || row.unit_price) {
  470. // if (row.sgfh_qty === undefined) calcData.sgfh_qty = updateNode.sgfh_qty;
  471. // if (row.sjcl_qty === undefined) calcData.sjcl_qty = updateNode.sjcl_qty;
  472. // if (row.qtcl_qty === undefined) calcData.qtcl_qty = updateNode.qtcl_qty;
  473. // if (row.deal_qty === undefined) calcData.deal_qty = updateNode.deal_qty;
  474. // calcData.quantity = this.ctx.helper.sum([calcData.sgfh_qty, calcData.sjcl_qty, calcData.qtcl_qty]);
  475. // calcData.sgfh_tp = this.ctx.helper.mul(calcData.sgfh_qty, calcData.unit_price, info.decimal.tp);
  476. // calcData.sjcl_tp = this.ctx.helper.mul(calcData.sjcl_qty, calcData.unit_price, info.decimal.tp);
  477. // calcData.qtcl_tp = this.ctx.helper.mul(calcData.qtcl_qty, calcData.unit_price, info.decimal.tp);
  478. // calcData.total_price = this.ctx.helper.mul(calcData.quantity, calcData.unit_price, info.decimal.tp);
  479. // calcData.deal_tp = this.ctx.helper.mul(calcData.deal_qty, calcData.unit_price, info.decimal.tp);
  480. // } else if (row.sgfh_tp !== undefined || row.sjcl_tp !== undefined || row.qtcl_tp !== undefined || row.deal_tp !== undefined) {
  481. // calcData.sgfh_qty = null;
  482. // calcData.sjcl_qty = null;
  483. // calcData.qtcl_qty = null;
  484. // calcData.quantity = null;
  485. // calcData.deal_qty = null;
  486. // calcData.sgfh_tp = (row.sgfh_tp !== undefined) ? this.ctx.helper.round(calcData.row.sgfh_tp, info.decimal.tp) : updateNode.sgfh_tp;
  487. // calcData.sjcl_tp = (row.sgfh_tp !== undefined) ? this.ctx.helper.round(calcData.row.sjcl_tp, info.decimal.tp) : updateNode.sjcl_tp;
  488. // calcData.qtcl_tp = (row.sgfh_tp !== undefined) ? this.ctx.helper.round(calcData.row.qtcl_tp, info.decimal.tp) : updateNode.qtcl_tp;
  489. // calcData.total_price = this.ctx.helper.sum([calcData.sgfh_tp, calcData.sjcl_tp, calcData.qtcl_tp]);
  490. // calcData.deal_tp = (row.deal_tp !== undefined) ? this.ctx.helper.round(calcData.row.deal_tp, info.decimal.tp) : updateNode.deal_tp;
  491. // } else if (row.unit_price !== undefined) {
  492. // calcData.sgfh_tp = this.ctx.helper.mul(calcData.sgfh_qty, calcData.unit_price, info.decimal.tp);
  493. // calcData.sjcl_tp = this.ctx.helper.mul(calcData.sjcl_qty, calcData.unit_price, info.decimal.tp);
  494. // calcData.qtcl_tp = this.ctx.helper.mul(calcData.qtcl_qty, calcData.unit_price, info.decimal.tp);
  495. // calcData.total_price = this.ctx.helper.mul(calcData.quantity, calcData.unit_price, info.decimal.tp);
  496. // calcData.deal_tp = this.ctx.helper.mul(calcData.deal_qty, calcData.unit_price, info.decimal.tp);
  497. // }
  498. // updateData = this._filterUpdateInvalidField(updateNode.id, calcData);
  499. // } else {
  500. // updateData = this._filterUpdateInvalidField(updateNode.id, row);
  501. // }
  502. // await this.transaction.update(this.tableName, updateData);
  503. // }
  504. // await this.transaction.commit();
  505. // } catch (err) {
  506. // await this.transaction.rollback();
  507. // throw err;
  508. // }
  509. //
  510. // return { update: await this.getDataByIds(ids) };
  511. // }
  512. /**
  513. *
  514. * @param tenderId
  515. * @param xmj
  516. * @param order
  517. * @param parentData
  518. * @return {Promise<*[]>}
  519. * @private
  520. */
  521. async _sortBatchInsertData(tenderId, xmj, order, parentData) {
  522. const result = [],
  523. newIds = [];
  524. let tp = 0;
  525. const maxId = await this._getMaxLid(tenderId);
  526. // 添加xmj数据
  527. const parent = {
  528. tender_id: tenderId,
  529. ledger_id: maxId + 1,
  530. ledger_pid: parentData.ledger_id,
  531. is_leaf: xmj.children.length === 0,
  532. order,
  533. level: parentData.level + 1,
  534. name: xmj.name,
  535. };
  536. parent.full_path = parentData.full_path + '-' + parent.ledger_id;
  537. // 添加gcl数据
  538. for (let i = 0, iLen = xmj.children.length; i < iLen; i++) {
  539. const gcl = xmj.children[i];
  540. const child = {
  541. tender_id: tenderId,
  542. ledger_id: maxId + 1 + i + 1,
  543. ledger_pid: parent.ledger_id,
  544. is_leaf: true,
  545. order: i + 1,
  546. level: parent.level + 1,
  547. b_code: gcl.b_code,
  548. name: gcl.name,
  549. unit: gcl.unit,
  550. unit_price: gcl.unit_price,
  551. quantity: gcl.quantity,
  552. };
  553. child.full_path = parent.full_path + '-' + child.ledger_id;
  554. child.total_price = this.ctx.helper.mul(child.unit_price, child.quantity, this.ctx.tender.info.decimal.tp);
  555. tp = this.ctx.helper.add(tp, child.total_price);
  556. result.push(child);
  557. newIds.push(child.ledger_id);
  558. }
  559. parent.total_price = tp;
  560. result.push(parent);
  561. newIds.push(parent.ledger_id);
  562. return [result, tp, newIds];
  563. }
  564. /**
  565. * 批量插入子项
  566. * @param {Number} tenderId - 标段Id
  567. * @param {Number} selectId - 选中节点Id
  568. * @param {Object} data - 批量插入数据
  569. * @return {Promise<void>}
  570. */
  571. async batchInsertChild(tenderId, selectId, data) {
  572. const result = { ledger: {}, pos: null };
  573. if ((tenderId <= 0) || (selectId <= 0)) {
  574. return result;
  575. }
  576. const selectData = await this.getDataByNodeId(tenderId, selectId);
  577. if (!selectData) {
  578. throw '位置数据错误';
  579. }
  580. this.transaction = await this.db.beginTransaction();
  581. const newIds = [];
  582. const lastChild = await this.getLastChildData(tenderId, selectId);
  583. try {
  584. // 更新父项isLeaf
  585. if (!lastChild) {
  586. await this.transaction.update(this.tableName, {
  587. id: selectData.id,
  588. is_leaf: false,
  589. unit_price: null,
  590. quantity: null,
  591. total_price: null,
  592. deal_qty: null,
  593. deal_tp: null,
  594. });
  595. }
  596. const order = lastChild ? lastChild.order : 0;
  597. // 计算id
  598. const maxId = await this._getMaxLid(tenderId);
  599. // 数据库创建新增节点数据
  600. for (let i = 0, iLen = data.length; i < iLen; i++) {
  601. // 合并新增数据
  602. const qd = {
  603. id: this.uuid.v4(),
  604. tender_id: tenderId,
  605. ledger_id: maxId + i + 1,
  606. ledger_pid: selectData.ledger_id,
  607. is_leaf: true,
  608. order: order + i + 1,
  609. level: selectData.level + 1,
  610. b_code: data[i].b_code,
  611. name: data[i].name,
  612. unit: data[i].unit,
  613. unit_price: data[i].price,
  614. };
  615. qd.full_path = selectData.full_path + '-' + qd.ledger_id;
  616. const insertResult = await this.transaction.insert(this.tableName, qd);
  617. newIds.push(qd.id);
  618. if (data[i].pos.length > 0) {
  619. await this.ctx.service.pos.insertLedgerPosData(this.transaction, tenderId, qd, data[i].pos);
  620. await this._calcNode(qd, this.transaction);
  621. }
  622. }
  623. this._cacheMaxLid(tenderId, maxId + data.length);
  624. await this.transaction.commit();
  625. } catch (err) {
  626. await this.transaction.rollback();
  627. throw err;
  628. }
  629. // 查询应返回的结果
  630. result.ledger.create = await this.getDataByIds(newIds);
  631. if (!lastChild) {
  632. result.ledger.update = await this.getDataByIds([selectData.id]);
  633. }
  634. result.pos = await this.ctx.service.pos.getPosData({ lid: newIds });
  635. return result;
  636. }
  637. /**
  638. * 批量插入后项
  639. * @param {Number} tenderId - 标段Id
  640. * @param {Number} selectId - 选中节点Id
  641. * @param {Object} data - 批量插入数据
  642. * @return {Promise<void>}
  643. */
  644. async batchInsertNext(tenderId, selectId, data) {
  645. const result = { ledger: {}, pos: null };
  646. if ((tenderId <= 0) || (selectId <= 0)) {
  647. return result;
  648. }
  649. const selectData = await this.getDataByNodeId(tenderId, selectId);
  650. if (!selectData) {
  651. throw '位置数据错误';
  652. }
  653. const parentData = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  654. if (!parentData) {
  655. throw '位置数据错误';
  656. }
  657. this.transaction = await this.db.beginTransaction();
  658. const newIds = [];
  659. try {
  660. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  661. await this._updateChildrenOrder(tenderId, selectData.ledger_pid, selectData.order + 1, data.length);
  662. // 计算id和order
  663. const maxId = await this._getMaxLid(tenderId);
  664. const order = selectData.order;
  665. // 数据库创建新增节点数据
  666. for (let i = 0, iLen = data.length; i < iLen; i++) {
  667. // 合并新增数据
  668. const qd = {
  669. id: this.uuid.v4(),
  670. tender_id: tenderId,
  671. ledger_id: maxId + i + 1,
  672. ledger_pid: parentData.ledger_id,
  673. is_leaf: true,
  674. order: order + i + 1,
  675. level: parentData.level + 1,
  676. b_code: data[i].b_code,
  677. name: data[i].name,
  678. unit: data[i].unit,
  679. unit_price: data[i].price,
  680. };
  681. qd.full_path = parentData.full_path + '-' + qd.ledger_id;
  682. const insertResult = await this.transaction.insert(this.tableName, qd);
  683. newIds.push(qd.id);
  684. if (data[i].pos.length > 0) {
  685. await this.ctx.service.pos.insertLedgerPosData(this.transaction, tenderId, qd, data[i].pos);
  686. await this.calcNode(qd, this.transaction);
  687. }
  688. }
  689. this._cacheMaxLid(tenderId, maxId + data.length);
  690. await this.transaction.commit();
  691. } catch (err) {
  692. await this.transaction.rollback();
  693. throw err;
  694. }
  695. // 查询应返回的结果
  696. result.ledger.create = await this.getDataByIds(newIds);
  697. result.ledger.update = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + data.length);
  698. result.pos = await this.ctx.service.pos.getPosData({ lid: newIds });
  699. return result;
  700. }
  701. /**
  702. *
  703. * @param node
  704. * @param transaction
  705. * @returns {Promise<void>}
  706. * @private
  707. */
  708. async calcNode(node, transaction) {
  709. const info = this.ctx.tender.info;
  710. const precision = this.ctx.helper.findPrecision(info.precision, node.unit);
  711. const calcQtySql = 'SELECT SUM(`sgfh_qty`) As `sgfh_qty`, SUM(`sjcl_qty`) As `sjcl_qty`, SUM(`qtcl_qty`) As `qtcl_qty`, SUM(`quantity`) As `quantity` FROM ?? WHERE `lid` = ?';
  712. const data = await transaction.queryOne(calcQtySql, [this.ctx.service.pos.tableName, node.id]);
  713. data.id = node.id;
  714. data.sgfh_qty = this.round(data.sgfh_qty, precision.value);
  715. data.sjcl_qty = this.round(data.sjcl_qty, precision.value);
  716. data.qtcl_qty = this.round(data.qtcl_qty, precision.value);
  717. data.quantity = this.round(data.quantity, precision.value);
  718. data.sgfh_tp = this.ctx.helper.mul(data.sgfh_qty, node.unit_price, info.decimal.tp);
  719. data.sjcl_tp = this.ctx.helper.mul(data.sjcl_qty, node.unit_price, info.decimal.tp);
  720. data.qtcl_tp = this.ctx.helper.mul(data.qtcl_qty, node.unit_price, info.decimal.tp);
  721. data.total_price = this.ctx.helper.mul(data.quantity, node.unit_price, info.decimal.tp);
  722. const result = await transaction.update(this.tableName, data);
  723. }
  724. /**
  725. *
  726. * @param {Number} tid - 标段id
  727. * @param {Number} id - 需要计算的节点的id
  728. * @param {Object} transaction - 操作所属事务,没有则创建
  729. * @return {Promise<void>}
  730. */
  731. async calc(tid, id, transaction) {
  732. const node = await transaction.get(this.tableName, {id: id});
  733. if (!node) {
  734. throw '数据错误';
  735. }
  736. await this.calcNode(node, transaction);
  737. }
  738. async _importCacheTreeNodes(transaction, nodes) {
  739. const datas = [];
  740. for (const node of nodes) {
  741. datas.push({
  742. id: node.id,
  743. tender_id: this.ctx.tender.id,
  744. ledger_id: node.ledger_id,
  745. ledger_pid: node.ledger_pid,
  746. level: node.level,
  747. order: node.order,
  748. is_leaf: !node.children || node.children.length === 0,
  749. full_path: node.full_path,
  750. code: node.code,
  751. b_code: node.b_code,
  752. name: node.name,
  753. unit: node.unit,
  754. sgfh_qty: node.sgfh_qty,
  755. sgfh_tp: node.sgfh_tp,
  756. quantity: node.quantity,
  757. unit_price: node.unit_price,
  758. total_price: node.total_price,
  759. dgn_qty1: node.dgn_qty1,
  760. dgn_qty2: node.dgn_qty2,
  761. memo: node.memo,
  762. drawing_code: node.drawing_code,
  763. });
  764. }
  765. await transaction.insert(this.tableName, datas);
  766. return datas;
  767. }
  768. /**
  769. * 导入Excel数据
  770. * @param excelData
  771. * @returns {Promise<void>}
  772. */
  773. async importExcel(templateId, excelData) {
  774. console.time('analysis');
  775. const AnalysisExcel = require('../lib/analysis_excel');
  776. const analysisExcel = new AnalysisExcel(this.ctx);
  777. const tempData = await this.ctx.service.tenderNodeTemplate.getData(templateId, true);
  778. const cacheTree = analysisExcel.analysisData(excelData, tempData);
  779. const cacheKey = keyPre + this.ctx.tender.id;
  780. const orgMaxId = parseInt(await this.cache.get(cacheKey));
  781. console.timeEnd('analysis');
  782. const transaction = await this.db.beginTransaction();
  783. try {
  784. console.time('deleteBills');
  785. await transaction.delete(this.tableName, {tender_id: this.ctx.tender.id});
  786. console.timeEnd('deleteBills');
  787. console.time('deletePos');
  788. await transaction.delete(this.ctx.service.pos.tableName, {tid: this.ctx.tender.id});
  789. console.timeEnd('deletePos');
  790. console.time('insertBills');
  791. //const bills = await this._importCacheTreeNodes(transaction, cacheTree.items);
  792. const datas = [];
  793. for (const node of cacheTree.items) {
  794. datas.push({
  795. id: node.id,
  796. tender_id: this.ctx.tender.id,
  797. ledger_id: node.ledger_id,
  798. ledger_pid: node.ledger_pid,
  799. level: node.level,
  800. order: node.order,
  801. is_leaf: !node.children || node.children.length === 0,
  802. full_path: node.full_path,
  803. code: node.code,
  804. b_code: node.b_code,
  805. name: node.name,
  806. unit: node.unit,
  807. sgfh_qty: node.sgfh_qty,
  808. sgfh_tp: node.sgfh_tp,
  809. quantity: node.quantity,
  810. unit_price: node.unit_price,
  811. total_price: node.total_price,
  812. dgn_qty1: node.dgn_qty1,
  813. dgn_qty2: node.dgn_qty2,
  814. memo: node.memo,
  815. drawing_code: node.drawing_code,
  816. });
  817. }
  818. await transaction.insert(this.tableName, datas);
  819. console.timeEnd('insertBills');
  820. console.time('insertPos');
  821. if (cacheTree.pos && cacheTree.pos.length > 0) {
  822. await transaction.insert(this.ctx.service.pos.tableName, cacheTree.pos);
  823. }
  824. console.timeEnd('insertPos');
  825. await transaction.commit();
  826. this.cache.set(cacheKey, cacheTree.items.length + 1, 'EX', this.ctx.app.config.cacheTime);
  827. return {bills: datas, pos: cacheTree.pos}
  828. } catch (err) {
  829. await transaction.rollback();
  830. if (orgMaxId) {
  831. this.cache.set(cacheKey, cacheTree.keyNodeId, 'EX', this.ctx.app.config.cacheTime);
  832. }
  833. throw err;
  834. }
  835. }
  836. }
  837. return Ledger;
  838. };