base_bills_service.js 44 KB

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