base_bills_service.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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. class BaseBillsSerivce extends TreeService {
  19. // 继承方法
  20. clearParentingData(data) {
  21. data.unit_price = null;
  22. data.sgfh_qty = null;
  23. data.sgfh_tp = null;
  24. data.sjcl_qty = null;
  25. data.sjcl_tp = null;
  26. data.qtcl_qty = null;
  27. data.qtcl_tp = null;
  28. data.quantity = null;
  29. data.total_price = null;
  30. data.deal_qty = null;
  31. data.deal_tp = null;
  32. }
  33. /**
  34. * 从标准数据中提取有效数据
  35. * @param {Object} stdData - 从标准库中查询所得
  36. * @returns {name, unit, source, code, b_code}
  37. * @private
  38. */
  39. _filterStdData(stdData) {
  40. const result = {
  41. name: stdData.name,
  42. unit: stdData.unit,
  43. source: stdData.source,
  44. node_type: stdData.node_type,
  45. };
  46. result.code = stdData.code ? stdData.code : '';
  47. result.b_code = stdData.b_code ? stdData.b_code : '';
  48. return result;
  49. }
  50. async addBillsNode(tenderId, selectId, data, reviseId) {
  51. if (data) {
  52. if (reviseId) data.crid = reviseId;
  53. return await this.addNode(tenderId, selectId, data);
  54. } else {
  55. return await this.addNode(tenderId, selectId, {crid: reviseId});
  56. }
  57. }
  58. /**
  59. * 新增子节点,并排在所有子节点的末尾
  60. * @param {Number} tenderId - 标段Id
  61. * @param {Number} selectId - 父节点Id
  62. * @param {Object} data - 新增节点数据(编号名称等)
  63. * @returns {Promise<*>}
  64. */
  65. async addChild(tenderId, selectId, data, reviseId) {
  66. if ((tenderId <= 0) || (selectId <= 0)) {
  67. return [];
  68. }
  69. const selectData = await this.getDataByKid(tenderId, selectId);
  70. if (!selectData) {
  71. throw '新增节点数据错误';
  72. }
  73. const children = await this.getChildrenByParentId(tenderId, selectId);
  74. const maxId = await this._getMaxLid(tenderId);
  75. data.id = this.uuid.v4();
  76. data.tender_id = tenderId;
  77. data.ledger_id = maxId + 1;
  78. data.ledger_pid = selectData.ledger_id;
  79. data.level = selectData.level + 1;
  80. data.order = children.length + 1;
  81. data.full_path = selectData.full_path + '-' + data.ledger_id;
  82. data.is_leaf = true;
  83. if (reviseId) data.crid = reviseId;
  84. this.transaction = await this.db.beginTransaction();
  85. try {
  86. const result = await this.transaction.insert(this.tableName, data);
  87. if (children.length === 0) {
  88. await this.transaction.update(this.tableName,
  89. {
  90. is_leaf: false,
  91. sgfh_qty: null, sgfh_tp: null, qtcl_qty: null, qtcl_tp: null, sjcl_qty: null, sjcl_tp: null,
  92. quantity: null, unit_price: null, total_price: null, deal_qty: null, deal_tp: null
  93. },
  94. { where: {tender_id: tenderId, ledger_id: selectData.ledger_id} });
  95. }
  96. await this.transaction.commit();
  97. } catch(err) {
  98. this.transaction.rollback();
  99. throw err;
  100. }
  101. this._cacheMaxLid(tenderId, maxId + 1);
  102. // 查询应返回的结果
  103. const resultData = {};
  104. resultData.create = await this.getDataByKid(tenderId, data.ledger_id);
  105. if (children.length === 0) {
  106. resultData.update = await this.getDataByKid(tenderId, selectId);
  107. }
  108. return resultData;
  109. }
  110. /**
  111. * 添加节点(来自标准清单)
  112. * @param {Number} tenderId
  113. * @param {Number} selectId
  114. * @param {Object} stdData
  115. * @return {Promise<*>}
  116. */
  117. async addStdNode(tenderId, selectId, stdData, reviseId) {
  118. const newData = this._filterStdData(stdData);
  119. const result = await this.addBillsNode(tenderId, selectId, newData, reviseId);
  120. return result;
  121. }
  122. /**
  123. * 添加标准节点,将选择的标准节点,添加为子节点(排序为末尾)
  124. * @param {Number} tenderId - 标段Id
  125. * @param {Number} selectId - 添加目标节点Id
  126. * @param {Object} stdData - 标准节点数据
  127. * @returns {Promise<*>}
  128. */
  129. async addStdNodeAsChild(tenderId, selectId, stdData, reviseId) {
  130. const newData = this._filterStdData(stdData);
  131. const result = await this.addChild(tenderId, selectId, newData, reviseId);
  132. return result;
  133. }
  134. /**
  135. * 根据parentData, data新增数据(新增为parentData的最后一个子项)
  136. * @param {Number} tenderId - 标段id
  137. * @param {Object} parentData - 父项数据
  138. * @param {Object} data - 新增节点,初始数据
  139. * @return {Promise<*>} - 新增结果
  140. * @private
  141. */
  142. async _addChildNodeData(tenderId, parentData, data, reviseId) {
  143. if (tenderId <= 0) {
  144. return undefined;
  145. }
  146. if (!data) {
  147. data = {};
  148. }
  149. const pid = parentData ? parentData.ledger_id : rootId;
  150. const maxId = await this._getMaxLid(tenderId);
  151. data.id = this.uuid.v4();
  152. data.tender_id = tenderId;
  153. data.ledger_id = maxId + 1;
  154. data.ledger_pid = pid;
  155. if (data.order === undefined) {
  156. data.order = 1;
  157. }
  158. data.level = parentData ? parentData.level + 1 : 1;
  159. data.full_path = parentData ? parentData.full_path + '-' + data.ledger_id : '' + data.ledger_id;
  160. if (data.is_leaf === undefined) {
  161. data.is_leaf = true;
  162. }
  163. if (reviseId) data.crid = reviseId;
  164. const result = await this.transaction.insert(this.tableName, data);
  165. this._cacheMaxLid(tenderId, maxId + 1);
  166. return [result, data];
  167. }
  168. /**
  169. * 根据parentData, data新增数据(自动排序)
  170. * @param tenderId
  171. * @param parentData
  172. * @param data
  173. * @return {Promise<void>}
  174. * @private
  175. */
  176. async _addChildAutoOrder(tenderId, parentData, data, reviseId) {
  177. const self = this;
  178. const findPreData = function(list, a) {
  179. if (!list || list.length === 0) { return null; }
  180. for (let i = 0, iLen = list.length; i < iLen; i++) {
  181. if (self.ctx.helper.compareCode(list[i].code, a.code) > 0) {
  182. return i > 0 ? list[i - 1] : null;
  183. }
  184. }
  185. return list[list.length - 1];
  186. };
  187. const pid = parentData ? parentData.ledger_id : rootId;
  188. const children = await this.getChildrenByParentId(tenderId, pid);
  189. const preData = findPreData(children, data);
  190. if (!preData || children.indexOf(preData) < children.length - 1) {
  191. await this._updateChildrenOrder(tenderId, pid, preData ? preData.order + 1 : 1);
  192. }
  193. data.order = preData ? preData.order + 1 : 1;
  194. const [addResult, node] = await this._addChildNodeData(tenderId, parentData, data, reviseId);
  195. return [addResult, node];
  196. }
  197. /**
  198. * 添加节点,并同步添加父节点
  199. * @param {Number} tenderId - 标段id
  200. * @param {Number} selectId - 选中节点id
  201. * @param {Object} stdData - 节点数据
  202. * @param {StandardLib} stdLib - 标准库
  203. * @return {Promise<void>}
  204. */
  205. async addStdNodeWithParent(tenderId, stdData, stdLib, reviseId) {
  206. // 查询完整标准清单,并按层次排序
  207. const fullLevel = await stdLib.getFullLevelDataByFullPath(stdData.list_id, stdData.full_path);
  208. fullLevel.sort(function(x, y) {
  209. return x.level - y.level;
  210. });
  211. let isNew = false,
  212. node,
  213. firstNew,
  214. updateParent,
  215. addResult;
  216. const expandIds = [];
  217. this.transaction = await this.db.beginTransaction();
  218. try {
  219. // 从最顶层节点依次查询是否存在,否则添加
  220. for (let i = 0, len = fullLevel.length; i < len; i++) {
  221. const stdNode = fullLevel[i];
  222. if (isNew) {
  223. const newData = this._filterStdData(stdNode);
  224. newData.is_leaf = (i === len - 1);
  225. [addResult, node] = await this._addChildNodeData(tenderId, node, newData, reviseId);
  226. } else {
  227. const parent = node;
  228. node = await this.getDataByCondition({
  229. tender_id: tenderId,
  230. ledger_pid: parent ? parent.ledger_id : rootId,
  231. code: stdNode.code,
  232. name: stdNode.name,
  233. });
  234. if (!node) {
  235. isNew = true;
  236. const newData = this._filterStdData(stdNode);
  237. newData.is_leaf = (i === len - 1);
  238. [addResult, node] = await this._addChildAutoOrder(tenderId, parent, newData, reviseId);
  239. if (parent && parent.is_leaf) {
  240. await this.transaction.update(this.tableName, { id: parent.id, is_leaf: false,
  241. unit_price: null, quantity: null, total_price: null, deal_qty: null, deal_tp: null});
  242. updateParent = parent;
  243. }
  244. firstNew = node;
  245. } else {
  246. expandIds.push(node.ledger_id);
  247. }
  248. }
  249. }
  250. await this.transaction.commit();
  251. } catch (err) {
  252. await this.transaction.rollback();
  253. throw err;
  254. }
  255. // 查询应返回的结果
  256. let createData = [],
  257. updateData = [];
  258. if (firstNew) {
  259. createData = await this.getDataByFullPath(tenderId, firstNew.full_path + '%');
  260. updateData = await this.getNextsData(tenderId, firstNew.ledger_pid, firstNew.order);
  261. if (updateParent) {
  262. updateData.push(await this.getDataByCondition({ id: updateParent.id }));
  263. }
  264. }
  265. return { create: createData, update: updateData };
  266. }
  267. /**
  268. * 过滤data中update方式不可提交的字段
  269. * @param {Number} id - 主键key
  270. * @param {Object} data
  271. * @return {Object<{id: *}>}
  272. * @private
  273. */
  274. _filterUpdateInvalidField(id, data) {
  275. const result = {
  276. id,
  277. };
  278. for (const prop in data) {
  279. if (readOnlyFields.indexOf(prop) === -1) {
  280. result[prop] = data[prop];
  281. }
  282. }
  283. return result;
  284. }
  285. /**
  286. * newData中,以orgData为基准,过滤掉orgData中未定义或值相等的部分
  287. * @param {Object} orgData
  288. * @param {Object} newData
  289. * @private
  290. */
  291. _filterChangedField(orgData, newData) {
  292. const result = {};
  293. let bChanged = false;
  294. for (const prop in orgData) {
  295. if (this._.isEmpty(newData[prop]) && newData[prop] !== orgData[prop]) {
  296. result[prop] = newData[prop];
  297. bChanged = true;
  298. }
  299. }
  300. return bChanged ? result : undefined;
  301. }
  302. /**
  303. * 检查data中是否含有计算字段
  304. * @param {Object} data
  305. * @return {boolean}
  306. * @private
  307. */
  308. _checkCalcField(data) {
  309. for (const prop in data) {
  310. if (calcFields.indexOf(prop) >= 0) {
  311. return true;
  312. }
  313. }
  314. return false;
  315. }
  316. /**
  317. * 提交数据 - 响应计算(增量方式计算)
  318. * @param {Number} tenderId
  319. * @param {Object} data
  320. * @return {Promise<*>}
  321. */
  322. async updateCalc(tenderId, data) {
  323. // 简单验证数据
  324. if (tenderId <= 0 || !this.ctx.tender) {
  325. throw '标段不存在';
  326. }
  327. const info = this.ctx.tender.info;
  328. if (!data) {
  329. throw '提交数据错误';
  330. }
  331. const datas = data instanceof Array ? data : [data];
  332. const ids = [];
  333. for (const row of datas) {
  334. if (tenderId !== row.tender_id) {
  335. throw '提交数据错误';
  336. }
  337. ids.push(row.id);
  338. }
  339. this.transaction = await this.db.beginTransaction();
  340. try {
  341. for (const row of datas) {
  342. const updateNode = await this.getDataById(row.id);
  343. if (!updateNode || tenderId !== updateNode.tender_id || row.ledger_id !== updateNode.ledger_id) {
  344. throw '提交数据错误';
  345. }
  346. let updateData;
  347. if (row.unit) {
  348. if (row.sgfh_qty === undefined) { row.sgfh_qty = updateNode.sgfh_qty; }
  349. if (row.sjcl_qty === undefined) { row.sjcl_qty = updateNode.sjcl_qty; }
  350. if (row.qtcl_qty === undefined) { row.qtcl_qty = updateNode.qtcl_qty; }
  351. if (row.deal_qty === undefined) { row.deal_qty = updateNode.deal_qty; }
  352. }
  353. if (row.b_code) {
  354. row.dgn_qty1 = null;
  355. row.dgn_qty2 = null;
  356. row.code = null;
  357. }
  358. if (row.code) {
  359. row.b_code = null;
  360. }
  361. if (this._checkCalcField(row)) {
  362. let calcData = JSON.parse(JSON.stringify(row));
  363. const precision = this.ctx.helper.findPrecision(info.precision, row.unit ? row.unit : updateNode.unit);
  364. // 数量保留小数位数
  365. this.ctx.helper.checkFieldPrecision(calcData, qtyFields, precision.value);
  366. // 单位保留小数位数
  367. this.ctx.helper.checkFieldPrecision(calcData, upFields, info.decimal.up);
  368. // 未提交单价则读取数据库单价
  369. if (row.unit_price === undefined) calcData.unit_price = updateNode.unit_price;
  370. // 计算
  371. if (row.sgfh_qty !== undefined || row.sjcl_qty !== undefined || row.qtcl_qty !== undefined ||
  372. row.deal_qty !== undefined || row.unit_price) {
  373. if (row.sgfh_qty === undefined) calcData.sgfh_qty = updateNode.sgfh_qty;
  374. if (row.sjcl_qty === undefined) calcData.sjcl_qty = updateNode.sjcl_qty;
  375. if (row.qtcl_qty === undefined) calcData.qtcl_qty = updateNode.qtcl_qty;
  376. if (row.deal_qty === undefined) calcData.deal_qty = updateNode.deal_qty;
  377. calcData.quantity = this.ctx.helper.sum([calcData.sgfh_qty, calcData.sjcl_qty, calcData.qtcl_qty]);
  378. calcData.sgfh_tp = this.ctx.helper.mul(calcData.sgfh_qty, calcData.unit_price, info.decimal.tp);
  379. calcData.sjcl_tp = this.ctx.helper.mul(calcData.sjcl_qty, calcData.unit_price, info.decimal.tp);
  380. calcData.qtcl_tp = this.ctx.helper.mul(calcData.qtcl_qty, calcData.unit_price, info.decimal.tp);
  381. calcData.total_price = this.ctx.helper.mul(calcData.quantity, calcData.unit_price, info.decimal.tp);
  382. calcData.deal_tp = this.ctx.helper.mul(calcData.deal_qty, calcData.unit_price, info.decimal.tp);
  383. } else if (row.sgfh_tp !== undefined || row.sjcl_tp !== undefined || row.qtcl_tp !== undefined || row.deal_tp !== undefined) {
  384. calcData.sgfh_qty = null;
  385. calcData.sjcl_qty = null;
  386. calcData.qtcl_qty = null;
  387. calcData.quantity = null;
  388. calcData.deal_qty = null;
  389. calcData.sgfh_tp = (row.sgfh_tp !== undefined) ? this.ctx.helper.round(calcData.row.sgfh_tp, info.decimal.tp) : updateNode.sgfh_tp;
  390. calcData.sjcl_tp = (row.sgfh_tp !== undefined) ? this.ctx.helper.round(calcData.row.sjcl_tp, info.decimal.tp) : updateNode.sjcl_tp;
  391. calcData.qtcl_tp = (row.sgfh_tp !== undefined) ? this.ctx.helper.round(calcData.row.qtcl_tp, info.decimal.tp) : updateNode.qtcl_tp;
  392. calcData.total_price = this.ctx.helper.sum([calcData.sgfh_tp, calcData.sjcl_tp, calcData.qtcl_tp]);
  393. calcData.deal_tp = (row.deal_tp !== undefined) ? this.ctx.helper.round(calcData.row.deal_tp, info.decimal.tp) : updateNode.deal_tp;
  394. } else if (row.unit_price !== undefined) {
  395. calcData.sgfh_tp = this.ctx.helper.mul(calcData.sgfh_qty, calcData.unit_price, info.decimal.tp);
  396. calcData.sjcl_tp = this.ctx.helper.mul(calcData.sjcl_qty, calcData.unit_price, info.decimal.tp);
  397. calcData.qtcl_tp = this.ctx.helper.mul(calcData.qtcl_qty, calcData.unit_price, info.decimal.tp);
  398. calcData.total_price = this.ctx.helper.mul(calcData.quantity, calcData.unit_price, info.decimal.tp);
  399. calcData.deal_tp = this.ctx.helper.mul(calcData.deal_qty, calcData.unit_price, info.decimal.tp);
  400. }
  401. updateData = this._filterUpdateInvalidField(updateNode.id, calcData);
  402. } else {
  403. updateData = this._filterUpdateInvalidField(updateNode.id, row);
  404. }
  405. await this.transaction.update(this.tableName, updateData);
  406. }
  407. await this.transaction.commit();
  408. this.transaction = null;
  409. } catch (err) {
  410. await this.transaction.rollback();
  411. this.transaction = null;
  412. throw err;
  413. }
  414. return { update: await this.getDataById(ids) };
  415. }
  416. // 统计方法
  417. async addUp(condition) {
  418. const sql = 'SELECT Sum(total_price) As total_price, Sum(deal_tp) As deal_tp' +
  419. ' FROM ' + this.tableName + this.ctx.helper.whereSql(condition);
  420. const result = await this.db.queryOne(sql);
  421. return result;
  422. }
  423. // 导入Excel
  424. async importGclExcel(id, sheet, data) {
  425. const node = await this.getDataById(id);
  426. if (!node || !node.is_leaf || node.tender_id !== this.ctx.tender.id) throw '数据错误';
  427. const maxId = await this._getMaxLid(this.ctx.tender.id);
  428. const AnalysisExcel = require('../lib/analysis_excel').AnalysisGclExcelTree;
  429. const analysisExcel = new AnalysisExcel(this.ctx);
  430. const cacheData = analysisExcel.analysisData(sheet, node, maxId, data);
  431. const datas = [];
  432. for (const node of cacheData.items) {
  433. const data = {
  434. id: node.id, tender_id: this.ctx.tender.id,
  435. ledger_id: node.ledger_id,
  436. ledger_pid: node.ledger_pid,
  437. level: node.level,
  438. order: node.order,
  439. is_leaf: !node.children || node.children.length === 0,
  440. full_path: node.full_path,
  441. b_code: node.b_code,
  442. name: node.name,
  443. unit: node.unit,
  444. unit_price: node.unit_price,
  445. crid: node.crid,
  446. };
  447. if (this.ctx.tender.data.measure_type === measureType.tz.value) {
  448. data.sgfh_qty = node.quantity;
  449. data.sgfh_tp = node.total_price;
  450. data.quantity = node.quantity;
  451. data.total_price = node.total_price;
  452. } else if (this.ctx.tender.data.measure_type === measureType.gcl.value) {
  453. data.deal_qty = node.quantity;
  454. data.deal_tp = node.total_price;
  455. }
  456. datas.push(data);
  457. }
  458. const conn = await this.db.beginTransaction();
  459. try {
  460. await this.db.update(this.tableName, {id: node.id, is_leaf: false});
  461. await this.db.insert(this.tableName, datas);
  462. await conn.commit();
  463. } catch(err) {
  464. await conn.rollback();
  465. throw err;
  466. }
  467. this._cacheMaxLid(this.ctx.tender.id, cacheData.keyNodeId);
  468. node.is_leaf = false;
  469. return { create: datas, update: [node]};
  470. }
  471. async deal2sgfh(tid) {
  472. const sql = 'UPDATE ' + this.tableName + ' SET sgfh_qty = deal_qty,' +
  473. ' quantity = IFNULL(deal_qty, 0) + IFNULL(sjcl_qty, 0) + IFNULL(qtcl_qty, 0), ' +
  474. ' sgfh_tp = deal_tp,' +
  475. ' total_price = IFNULl(deal_tp, 0) + sjcl_tp, 0) + qtcl_tp, 0)' +
  476. ' WHERE tender_id = ?';
  477. const sqlParam = [tid];
  478. await this.db.query(sql, sqlParam);
  479. }
  480. }
  481. module.exports = BaseBillsSerivce;