base_bills_service.js 41 KB

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