base_bills_service.js 34 KB

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