base_bills_service.js 36 KB

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