change_ledger.js 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708
  1. 'use strict';
  2. /**
  3. * 变更插入 --- 标段--台账 数据模型
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/12/1
  7. * @version
  8. */
  9. const needField = {
  10. id: 'ledger_id',
  11. pid: 'ledger_pid',
  12. order: 'order',
  13. level: 'level',
  14. fullPath: 'full_path',
  15. isLeaf: 'is_leaf',
  16. };
  17. const keyFields = {
  18. table: ['id'],
  19. index: ['tender_id', 'ledger_id'],
  20. };
  21. // 以下字段仅可通过树结构操作改变,不可直接通过update方式从接口提交,发现时过滤
  22. const readOnlyFields = ['id', 'tender_id', 'ledger_id', 'ledger_pid', 'order', 'level', 'full_path', 'is_leaf'];
  23. const calcFields = ['unit_price', 'sgfh_qty', 'sgfh_tp', 'sjcl_qty', 'sjcl_tp', 'qtcl_qty', 'qtcl_tp', 'deal_qty', 'deal_tp', 'dgn_qty1', 'dgn_qty2'];
  24. const upFields = ['unit_price'];
  25. const qtyFields = ['sgfh_qty', 'sjcl_qty', 'qtcl_qty', 'quantity', 'deal_qty'];
  26. const tpFields = ['sgfh_tp', 'sjcl_tp', 'qtcl_tp', 'total_price', 'deal_tp'];
  27. const rootId = -1;
  28. const keyPre = 'tender_node_maxId:';
  29. const measureType = require('../const/tender').measureType;
  30. const SumLoad = require('../lib/sum_load');
  31. const billsUtils = require('../lib/bills_utils');
  32. module.exports = app => {
  33. class ChangeLedger extends app.BaseBillsService {
  34. /**
  35. * 构造函数
  36. *
  37. * @param {Object} ctx - egg全局变量
  38. * @return {void}
  39. */
  40. constructor(ctx) {
  41. const setting = {
  42. mid: 'tender_id',
  43. kid: 'ledger_id',
  44. pid: 'ledger_pid',
  45. order: 'order',
  46. level: 'level',
  47. isLeaf: 'is_leaf',
  48. fullPath: 'full_path',
  49. keyPre: 'change_ledger_maxLid:',
  50. uuid: true,
  51. };
  52. super(ctx, setting, 'pos');
  53. this.setting = setting;
  54. this.depart = 0;
  55. this.tableName = 'change_ledger';
  56. }
  57. /**
  58. * 获取节点数据
  59. * @param {Number} mid - masterId
  60. * @param {Number} id
  61. * @returns {Promise<void>}
  62. */
  63. async getDataByKid(mid, kid) {
  64. const bills = await this.db.get(this.ctx.service.ledger.tableName, this.getCondition({
  65. mid: mid, kid: kid,
  66. }));
  67. if (bills) {
  68. this.newBills = false;
  69. return bills;
  70. }
  71. const cBills = await this.db.get(this.tableName, this.getCondition({mid: mid, kid: kid}));
  72. // 判断父节点是否是变更新建的
  73. const parentBills = await this.db.get(this.tableName, this.getCondition({
  74. mid: cBills[this.setting.pid], kid: kid,
  75. }));
  76. this.newBills = parentBills !== null && parentBills !== undefined;
  77. return cBills;
  78. }
  79. async getDataByKidAndCount(mid, kid, count) {
  80. if ((mid <= 0) || (kid <= 0)) return [];
  81. const select = await this.getDataByKid(mid, kid);
  82. if (!select) throw '数据错误';
  83. if (count > 1) {
  84. const selects = await this.getNextsData(this.tableName, mid, select[this.setting.pid], select[this.setting.order] - 1);
  85. if (selects.length < count) throw '数据错误';
  86. return selects.slice(0, count);
  87. } else {
  88. return [select];
  89. }
  90. }
  91. /**
  92. * 更新order
  93. * @param {Number} mid - master id
  94. * @param {Number} pid - 父节点id
  95. * @param {Number} order - 开始更新的order
  96. * @param {Number} incre - 更新的增量
  97. * @returns {Promise<*>}
  98. * @private
  99. */
  100. async _updateChildrenOrder(tableName, mid, pid, order, incre = 1) {
  101. this.initSqlBuilder();
  102. this.sqlBuilder.setAndWhere(this.setting.mid, {
  103. value: mid,
  104. operate: '=',
  105. });
  106. this.sqlBuilder.setAndWhere(this.setting.order, {
  107. value: order,
  108. operate: '>=',
  109. });
  110. this.sqlBuilder.setAndWhere(this.setting.pid, {
  111. value: pid,
  112. operate: '=',
  113. });
  114. this.sqlBuilder.setUpdateData(this.setting.order, {
  115. value: Math.abs(incre),
  116. selfOperate: incre > 0 ? '+' : '-',
  117. });
  118. const [sql, sqlParam] = this.sqlBuilder.build(tableName, 'update');
  119. const data = await this.transaction.query(sql, sqlParam);
  120. return data;
  121. }
  122. /**
  123. * 获取最大节点id
  124. *
  125. * @param {Number} mid - master id
  126. * @return {Number}
  127. * @private
  128. */
  129. async _getMaxLid(mid) {
  130. const cacheKey = this.setting.keyPre + mid;
  131. let maxId = parseInt(await this.cache.get(cacheKey));
  132. if (!maxId) {
  133. const sql = 'SELECT Max(??) As max_id FROM ?? Where ' + this.setting.mid + ' = ?';
  134. const sqlParam = [this.setting.kid, this.ctx.service.ledger.tableName, mid];
  135. const queryResult = await this.db.queryOne(sql, sqlParam);
  136. maxId = queryResult.max_id || 0;
  137. if (this.newBills) {
  138. const sql2 = 'SELECT Max(??) As max_id FROM ?? Where ' + this.setting.mid + ' = ?';
  139. const sqlParam2 = [this.setting.kid, this.tableName, mid];
  140. const queryResult2 = await this.db.queryOne(sql2, sqlParam2);
  141. if (maxId < queryResult2.max_id || 0) {
  142. maxId = queryResult2.max_id || 0;
  143. }
  144. }
  145. this.cache.set(cacheKey, maxId, 'EX', this.ctx.app.config.cacheTime);
  146. }
  147. return maxId;
  148. }
  149. /**
  150. * 根据 父节点id 和 节点排序order 获取数据
  151. *
  152. * @param {Number} mid - master id
  153. * @param {Number} pid - 父节点id
  154. * @param {Number|Array} order - 排序
  155. * @return {Object|Array} - 查询结果
  156. */
  157. async getDataByParentAndOrder(mid, pid, order) {
  158. let result = await this.db.select(this.tableName, {
  159. where: this.getCondition({mid: mid, pid: pid, order: order})
  160. });
  161. if (!this.newBills) {
  162. const ledgerResult = await this.db.select(this.ctx.service.ledger.tableName, {
  163. where: this.getCondition({mid: mid, pid: pid, order: order})
  164. });
  165. result = this._.orderBy(this._.concat(ledgerResult, result), [this.setting.order], ['asc']);
  166. }
  167. return order instanceof Array ? result : (result.length > 0 ? result[0] : null);
  168. }
  169. async getChildBetween(tableName, mid, pid, order1, order2) {
  170. this.initSqlBuilder();
  171. this.sqlBuilder.setAndWhere(this.setting.mid, {
  172. value: mid,
  173. operate: '=',
  174. });
  175. this.sqlBuilder.setAndWhere(this.setting.pid, {
  176. value: pid,
  177. operate: '=',
  178. });
  179. this.sqlBuilder.setAndWhere(this.setting.order, {
  180. value: order1,
  181. operate: '>',
  182. });
  183. this.sqlBuilder.setAndWhere(this.setting.order, {
  184. value: order2,
  185. operate: '<',
  186. });
  187. this.sqlBuilder.orderBy = [['order', 'ASC']];
  188. const [sql, sqlParam] = this.sqlBuilder.build(tableName);
  189. const data = await this.db.query(sql, sqlParam);
  190. return data;
  191. }
  192. /**
  193. * 根据 父节点ID 和 节点排序order 获取全部后节点数据
  194. * @param {Number} mid - master id
  195. * @param {Number} pid - 父节点id
  196. * @param {Number} order - 排序
  197. * @return {Array}
  198. */
  199. async getNextsData(tableName, mid, pid, order) {
  200. this.initSqlBuilder();
  201. this.sqlBuilder.setAndWhere(this.setting.mid, {
  202. value: mid,
  203. operate: '=',
  204. });
  205. this.sqlBuilder.setAndWhere(this.setting.pid, {
  206. value: pid,
  207. operate: '=',
  208. });
  209. this.sqlBuilder.setAndWhere(this.setting.order, {
  210. value: order,
  211. operate: '>',
  212. });
  213. this.sqlBuilder.orderBy = [['order', 'ASC']];
  214. const [sql, sqlParam] = this.sqlBuilder.build(tableName);
  215. const data = await this.db.query(sql, sqlParam);
  216. return data;
  217. }
  218. /**
  219. * 根据节点Id获取数据
  220. *
  221. * @param {Number} tenderId - 标段id
  222. * @param {Number} nodeId - 项目节/工程量清单节点id
  223. * @return {Object} - 返回查询到的节点数据
  224. */
  225. async getDataByNodeId(tenderId, nodeId) {
  226. if ((nodeId <= 0) || (tenderId <= 0)) {
  227. return undefined;
  228. }
  229. this.initSqlBuilder();
  230. this.sqlBuilder.setAndWhere('tender_id', {
  231. value: tenderId,
  232. operate: '=',
  233. });
  234. this.sqlBuilder.setAndWhere('ledger_id', {
  235. value: nodeId,
  236. operate: '=',
  237. });
  238. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  239. const data = await this.db.queryOne(sql, sqlParam);
  240. return data;
  241. }
  242. /**
  243. * 新增数据(新增为selectData的后项,该方法不可单独使用)
  244. *
  245. * @param {Number} mid - 台账id
  246. * @param {Object} select - 选中节点的数据
  247. * @param {Object} data - 新增节点的初始数据
  248. * @return {Object} - 新增结果
  249. * @private
  250. */
  251. async _addNodeData(mid, select, data) {
  252. if (!data) {
  253. data = {};
  254. }
  255. const maxId = await this._getMaxLid(mid);
  256. if (this.setting.uuid) data.id = this.uuid.v4();
  257. data[this.setting.kid] = maxId + 1;
  258. data[this.setting.pid] = select ? select[this.setting.pid] : rootId;
  259. data[this.setting.mid] = mid;
  260. data[this.setting.level] = select ? select[this.setting.level] : 1;
  261. data[this.setting.order] = select ? select[this.setting.order] + 1 : 1;
  262. data[this.setting.fullPath] = data[this.setting.level] > 1 ? select[this.setting.fullPath].replace('-' + select[this.setting.kid], '-' + data[this.setting.kid]) : data[this.setting.kid] + '';
  263. data[this.setting.isLeaf] = true;
  264. const result = await this.transaction.insert(this.tableName, data);
  265. this._cacheMaxLid(mid, maxId + 1);
  266. return result;
  267. }
  268. /**
  269. * 新增节点
  270. * @param {Number} mid - 台账id
  271. * @param {Number} kid - 清单节点id
  272. * @returns {Promise<void>}
  273. */
  274. async addNode(mid, kid, data) {
  275. if (!mid) return null;
  276. this.newBills = false;
  277. const select = kid ? await this.getDataByKid(mid, kid) : null;
  278. if (kid && !select) throw '新增节点数据错误';
  279. this.transaction = await this.db.beginTransaction();
  280. try {
  281. if (select) await this._updateChildrenOrder(this.tableName, mid, select[this.setting.pid], select[this.setting.order]+1);
  282. if (!this.newBills) {
  283. if (select) await this._updateChildrenOrder(this.ctx.service.ledger.tableName, mid, select[this.setting.pid], select[this.setting.order]+1);
  284. }
  285. const newNode = await this._addNodeData(mid, select, data);
  286. if (newNode.affectedRows !== 1) throw '新增节点数据错误';
  287. await this.transaction.commit();
  288. this.transaction = null;
  289. } catch (err) {
  290. await this.transaction.rollback();
  291. this.transaction = null;
  292. throw err;
  293. }
  294. if (select) {
  295. const createData = await this.getDataByParentAndOrder(mid, select[this.setting.pid], [select[this.setting.order] + 1]);
  296. let updateData = await this.getNextsData(this.tableName, mid, select[this.setting.pid], select[this.setting.order] + 1);
  297. if (!this.newBills) {
  298. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, mid, select[this.setting.pid], select[this.setting.order] + 1);
  299. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  300. }
  301. return { create: createData, update: updateData };
  302. } else {
  303. const createData = await this.getDataByParentAndOrder(mid, -1, [1]);
  304. return { create: createData };
  305. }
  306. }
  307. async addNodeBatch(mid, kid, data, count = 1) {
  308. if (!mid) return null;
  309. this.newBills = false;
  310. const select = kid ? await this.getDataByKid(mid, kid) : null;
  311. if (kid && !select) throw '新增节点数据错误';
  312. this.transaction = await this.db.beginTransaction();
  313. try {
  314. // 判断select的父节点是否是变更新增的,如果是则修改自己的表就行了,否则修改2个ledger,changeLedger表
  315. if (select) await this._updateChildrenOrder(this.tableName, mid, select[this.setting.pid], select[this.setting.order] + 1, count);
  316. if (!this.newBills) {
  317. if (select) await this._updateChildrenOrder(this.ctx.service.ledger.tableName, mid, select[this.setting.pid], select[this.setting.order] + 1, count);
  318. }
  319. const newDatas = [];
  320. const maxId = await this._getMaxLid(mid);
  321. for (let i = 1; i < count + 1; i++) {
  322. const newData = Object.assign({}, data);
  323. if (this.setting.uuid) newData.id = this.uuid.v4();
  324. newData[this.setting.kid] = maxId + i;
  325. newData[this.setting.pid] = select ? select[this.setting.pid] : rootId;
  326. newData[this.setting.mid] = mid;
  327. newData[this.setting.level] = select ? select[this.setting.level] : 1;
  328. newData[this.setting.order] = select ? select[this.setting.order] + i : i;
  329. newData[this.setting.fullPath] = newData[this.setting.level] > 1
  330. ? select[this.setting.fullPath].replace('-' + select[this.setting.kid], '-' + newData[this.setting.kid])
  331. : newData[this.setting.kid] + '';
  332. newData[this.setting.isLeaf] = true;
  333. newDatas.push(newData);
  334. }
  335. const insertResult = await this.transaction.insert(this.tableName, newDatas);
  336. this._cacheMaxLid(mid, maxId + count);
  337. if (insertResult.affectedRows !== count) throw '新增节点数据错误';
  338. await this.transaction.commit();
  339. this.transaction = null;
  340. } catch (err) {
  341. await this.transaction.rollback();
  342. this.transaction = null;
  343. throw err;
  344. }
  345. if (select) {
  346. let createData = await this.getChildBetween(this.tableName, mid, select[this.setting.pid], select[this.setting.order], select[this.setting.order] + count + 1);
  347. let updateData = await this.getNextsData(this.tableName, mid, select[this.setting.pid], select[this.setting.order] + count);
  348. if (!this.newBills) {
  349. const ledgerCreateData = await this.getChildBetween(this.ctx.service.ledger.tableName, mid, select[this.setting.pid], select[this.setting.order], select[this.setting.order] + count + 1);
  350. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, mid, select[this.setting.pid], select[this.setting.order] + count);
  351. createData = this._.orderBy(this._.concat(createData, ledgerCreateData), [this.setting.order], ['asc']);
  352. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  353. }
  354. return { create: createData, update: updateData };
  355. } else {
  356. const createData = await this.getChildBetween(this.ctx.service.ledger.tableName, mid, -1, 0, count + 1);
  357. return { create: createData };
  358. }
  359. }
  360. /**
  361. * 删除相关数据 用于继承
  362. * @param mid
  363. * @param deleteData
  364. * @return {Promise<void>}
  365. * @private
  366. */
  367. async _deleteRelaData(mid, deleteData) {
  368. await this.ctx.service.changePos.deletePosData(this.transaction, mid, this._.map(deleteData, 'id'));
  369. }
  370. async _deleteChangeAuditListData(mid, deleteData) {
  371. await this.ctx.service.changeAuditList.deleteDataByRevise(this.transaction, mid, this._.map(deleteData, 'id'));
  372. }
  373. /**
  374. * 删除节点
  375. * @param {Number} tenderId - 标段id
  376. * @param {Object} deleteData - 删除节点数据
  377. * @return {Promise<*>}
  378. * @private
  379. */
  380. async _deleteNodeData(mid, deleteNode) {
  381. this.initSqlBuilder();
  382. this.sqlBuilder.setAndWhere(this.setting.mid, {
  383. value: mid,
  384. operate: '=',
  385. });
  386. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  387. value: this.db.escape(deleteNode[this.setting.fullPath] + '%'),
  388. operate: 'Like',
  389. });
  390. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'delete');
  391. const result = await this.transaction.query(sql, sqlParam);
  392. return result;
  393. }
  394. /**
  395. * tenderId标段中, 删除选中节点及其子节点
  396. *
  397. * @param {Number} tenderId - 标段id
  398. * @param {Number} selectId - 选中节点id
  399. * @return {Array} - 被删除的数据
  400. */
  401. async deleteNode(mid, kid) {
  402. if ((mid <= 0) || (kid <= 0)) return [];
  403. this.newBills = false;
  404. const select = await this.getDataByKid(mid, kid);
  405. if (!select) throw '删除节点数据错误';
  406. const parent = await this.getDataByKid(mid, select[this.setting.pid]);
  407. // 获取将要被删除的数据
  408. const deleteData = await this.getDataByFullPath(this.tableName, mid, select[this.setting.fullPath] + '%');
  409. if (deleteData.length === 0) throw '删除节点数据错误';
  410. this.transaction = await this.db.beginTransaction();
  411. try {
  412. // 删除
  413. const operate = await this._deleteNodeData(mid, select);
  414. // 选中节点--父节点 只有一个子节点时,应升级is_leaf
  415. if (parent) {
  416. let count = await this.db.count(this.tableName, this.getCondition({mid: mid, pid: select[this.setting.pid]}));
  417. if (!this.newBills) {
  418. const ledgerCount = await this.db.count(this.ctx.service.ledger.tableName, this.getCondition({mid: mid, pid: select[this.setting.pid]}));
  419. count = count + ledgerCount;
  420. }
  421. if (count === 1) {
  422. const updateParent = {id: parent.id };
  423. updateParent[this.setting.isLeaf] = true;
  424. this.newBills ? await this.transaction.update(this.tableName, updateParent) : await this.transaction.update(this.ctx.service.ledger.tableName, updateParent);
  425. }
  426. }
  427. // 选中节点--全部后节点 order--
  428. await this._updateChildrenOrder(this.tableName, mid, select[this.setting.pid], select[this.setting.order] + 1, -1);
  429. if (!this.newBills) {
  430. await this._updateChildrenOrder(this.ctx.service.ledger.tableName, mid, select[this.setting.pid], select[this.setting.order] + 1, -1);
  431. }
  432. // 删除部位明细
  433. await this._deleteRelaData(mid, deleteData);
  434. await this._deleteChangeAuditListData(mid, deleteData);
  435. await this.transaction.commit();
  436. this.transaction = null;
  437. } catch (err) {
  438. await this.transaction.rollback();
  439. this.transaction = null;
  440. throw err;
  441. }
  442. // 查询结果
  443. let updateData = await this.getNextsData(this.tableName, mid, select[this.setting.pid], select[this.setting.order] - 1);
  444. if (!this.newBills) {
  445. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, mid, select[this.setting.pid], select[this.setting.order] - 1);
  446. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  447. }
  448. if (parent) {
  449. const updateData1 = await this.getDataByKid(mid, select[this.setting.pid]);
  450. if (updateData1[this.setting.isLeaf]) {
  451. updateData.push(updateData1);
  452. }
  453. }
  454. return { delete: deleteData, update: updateData };
  455. }
  456. async deleteNodes(mid, kid, count) {
  457. if ((mid <= 0) || (kid <= 0) || (count <= 0)) return [];
  458. this.newBills = false;
  459. const selects = await this.getDataByKidAndCount(mid, kid, count);
  460. const first = selects[0];
  461. const newBills = this.newBills;
  462. const parent = await this.getDataByKid(mid, first[this.setting.pid]);
  463. let childCount = 0;
  464. if (parent) {
  465. childCount = await this.db.count(this.tableName, this.getCondition({mid: mid, pid: parent[this.setting.kid]}));
  466. if (!newBills) {
  467. const ledgerCount = await this.db.count(this.ctx.service.ledger.tableName, this.getCondition({mid: mid, pid: parent[this.setting.pid]}));
  468. childCount = childCount + ledgerCount;
  469. }
  470. } else {
  471. childCount = -1;
  472. }
  473. // const childCount = parent ? await this.count(this.getCondition({mid: mid, pid: parent[this.setting.kid]})) : -1;
  474. let deleteData = [];
  475. for (const s of selects) {
  476. deleteData = deleteData.concat(await this.getDataByFullPath(this.tableName, mid, s[this.setting.fullPath] + '%'));
  477. }
  478. this.transaction = await this.db.beginTransaction();
  479. try {
  480. // 删除
  481. for (const s of selects) {
  482. const operate = await this._deleteNodeData(mid, s);
  483. }
  484. // 选中节点--父节点 只有一个子节点时,应升级is_leaf
  485. if (parent && childCount === count) {
  486. const updateParent = {id: parent.id };
  487. updateParent[this.setting.isLeaf] = true;
  488. newBills ? await this.transaction.update(this.tableName, updateParent) : await this.transaction.update(this.ctx.service.ledger.tableName, updateParent);
  489. }
  490. // 选中节点--全部后节点 order--
  491. await this._updateChildrenOrder(this.tableName, mid, first[this.setting.pid], first[this.setting.order] + count, -count);
  492. if (!newBills) {
  493. await this._updateChildrenOrder(this.ctx.service.ledger.tableName, mid, first[this.setting.pid], first[this.setting.order] + count, -count);
  494. }
  495. // 删除部位明细
  496. await this._deleteRelaData(mid, deleteData);
  497. await this._deleteChangeAuditListData(mid, deleteData);
  498. await this.transaction.commit();
  499. this.transaction = null;
  500. let updateData = await this.getNextsData(this.tableName, mid, first[this.setting.pid], first[this.setting.order] - 1);
  501. if (!newBills) {
  502. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, mid, first[this.setting.pid], first[this.setting.order] - 1);
  503. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  504. }
  505. if (parent && childCount === count) {
  506. const updateData1 = await this.getDataByKid(mid, parent[this.setting.kid]);
  507. updateData.push(updateData1);
  508. }
  509. return { delete: deleteData, update: updateData };
  510. } catch (err) {
  511. if (this.transaction) {
  512. await this.transaction.rollback();
  513. this.transaction = null;
  514. }
  515. throw err;
  516. }
  517. }
  518. async delete(mid, kid, count) {
  519. if (count && count > 1) {
  520. return await this.deleteNodes(mid, kid, count);
  521. } else {
  522. return await this.deleteNode(mid, kid);
  523. }
  524. }
  525. /**
  526. * 上移节点
  527. *
  528. * @param {Number} mid - master id
  529. * @param {Number} kid - 选中节点id
  530. * @return {Array} - 发生改变的数据
  531. */
  532. async upMoveNode(mid, kid, count) {
  533. if (!count) count = 1;
  534. if (!mid || (mid <= 0) || !kid || (kid <= 0)) return null;
  535. this.newBills = false;
  536. const selects = await this.getDataByKidAndCount(mid, kid, count);
  537. if (selects.length !== count) throw '上移节点数据错误';
  538. const first = selects[0];
  539. const pre = await this.getDataByParentAndOrder(mid, first[this.setting.pid], first[this.setting.order] - 1);
  540. if (!pre) throw '节点不可上移';
  541. const order = [];
  542. this.transaction = await this.db.beginTransaction();
  543. try {
  544. for (const s of selects) {
  545. const sData = await this.transaction.update(this.tableName, { id: s.id, order: s[this.setting.order] - 1 });
  546. if (!this.newBills) {
  547. await this.transaction.update(this.ctx.service.ledger.tableName, { id: s.id, order: s[this.setting.order] - 1 });
  548. }
  549. order.push(s[this.setting.order] - 1);
  550. }
  551. const pData = await this.transaction.update(this.tableName, { id: pre.id, order: pre[this.setting.order] + count });
  552. if (!this.newBills) {
  553. await this.transaction.update(this.ctx.service.ledger.tableName, { id: pre.id, order: pre[this.setting.order] + count });
  554. }
  555. order.push(pre[this.setting.order] + count);
  556. await this.transaction.commit();
  557. this.transaction = null;
  558. } catch (err) {
  559. await this.transaction.rollback();
  560. this.transaction = null;
  561. throw err;
  562. }
  563. const resultData = await this.getDataByParentAndOrder(mid, first[this.setting.pid], order);
  564. return { update: resultData };
  565. }
  566. /**
  567. * 下移节点
  568. *
  569. * @param {Number} mid - master id
  570. * @param {Number} kid - 选中节点id
  571. * @return {Array} - 发生改变的数据
  572. */
  573. async downMoveNode(mid, kid, count) {
  574. if (!count) count = 1;
  575. if (!mid || (mid <= 0) || !kid || (kid <= 0)) return null;
  576. this.newBills = false;
  577. const selects = await this.getDataByKidAndCount(mid, kid, count);
  578. if (selects.length !== count) {
  579. throw '下移节点数据错误';
  580. }
  581. const last = selects[count - 1];
  582. const next = await this.getDataByParentAndOrder(mid, last[this.setting.pid], last[this.setting.order] + 1);
  583. if (!next) {
  584. throw '节点不可下移';
  585. }
  586. const order = [];
  587. this.transaction = await this.db.beginTransaction();
  588. try {
  589. for (const s of selects) {
  590. const sData = await this.transaction.update(this.tableName, { id: s.id, order: s[this.setting.order] + 1 });
  591. if (!this.newBills) {
  592. await this.transaction.update(this.ctx.service.ledger.tableName, { id: s.id, order: s[this.setting.order] + 1 });
  593. }
  594. order.push(s[this.setting.order] + 1);
  595. }
  596. const nData = await this.transaction.update(this.tableName, { id: next.id, order: next[this.setting.order] - count });
  597. if (!this.newBills) {
  598. await this.transaction.update(this.ctx.service.ledger.tableName, { id: next.id, order: next[this.setting.order] - count });
  599. }
  600. order.push(next[this.setting.order] - count);
  601. await this.transaction.commit();
  602. this.transaction = null;
  603. } catch (err) {
  604. await this.transaction.rollback();
  605. this.transaction = null;
  606. throw err;
  607. }
  608. const resultData = await this.getDataByParentAndOrder(mid, last[this.setting.pid], order);
  609. return { update: resultData };
  610. }
  611. /**
  612. * 批量插入子项
  613. * @param {Number} tenderId - 标段Id
  614. * @param {Number} selectId - 选中节点Id
  615. * @param {Object} data - 批量插入数据
  616. * @return {Promise<void>}
  617. */
  618. async batchInsertChild(tenderId, selectId, data) {
  619. const result = { ledger: {}, pos: null };
  620. if ((tenderId <= 0) || (selectId <= 0)) {
  621. return result;
  622. }
  623. const selectData = await this.getDataByNodeId(tenderId, selectId);
  624. if (!selectData) {
  625. throw '位置数据错误';
  626. }
  627. this.transaction = await this.db.beginTransaction();
  628. const newIds = [];
  629. const lastChild = await this.getLastChildData(tenderId, selectId);
  630. try {
  631. // 更新父项isLeaf
  632. if (!lastChild) {
  633. await this.transaction.update(this.tableName, {
  634. id: selectData.id,
  635. is_leaf: false,
  636. unit_price: null,
  637. sgfh_qty: null,
  638. sgfh_tp: null,
  639. sjcl_qty: null,
  640. sjcl_tp: null,
  641. qtcl_qty: null,
  642. qtcl_tp: null,
  643. quantity: null,
  644. total_price: null,
  645. deal_qty: null,
  646. deal_tp: null,
  647. });
  648. }
  649. const order = lastChild ? lastChild.order : 0;
  650. // 计算id
  651. const maxId = await this._getMaxLid(tenderId);
  652. // 数据库创建新增节点数据
  653. for (let i = 0, iLen = data.length; i < iLen; i++) {
  654. // 合并新增数据
  655. const qd = {
  656. id: this.uuid.v4(),
  657. tender_id: tenderId,
  658. ledger_id: maxId + i + 1,
  659. ledger_pid: selectData.ledger_id,
  660. is_leaf: true,
  661. order: order + i + 1,
  662. level: selectData.level + 1,
  663. b_code: data[i].b_code,
  664. name: data[i].name,
  665. unit: data[i].unit,
  666. unit_price: data[i].price,
  667. };
  668. qd.full_path = selectData.full_path + '-' + qd.ledger_id;
  669. const insertResult = await this.transaction.insert(this.tableName, qd);
  670. newIds.push(qd.id);
  671. if (data[i].pos.length > 0) {
  672. await this.ctx.service.pos.insertLedgerPosData(this.transaction, tenderId, qd, data[i].pos);
  673. await this.calcNode(qd, this.transaction);
  674. }
  675. }
  676. this._cacheMaxLid(tenderId, maxId + data.length);
  677. await this.transaction.commit();
  678. } catch (err) {
  679. await this.transaction.rollback();
  680. throw err;
  681. }
  682. // 查询应返回的结果
  683. result.ledger.create = await this.getDataByIds(newIds);
  684. if (!lastChild) {
  685. result.ledger.update = await this.getDataByIds([selectData.id]);
  686. }
  687. result.pos = await this.ctx.service.pos.getPosData({tid: tenderId, lid: newIds });
  688. return result;
  689. }
  690. /**
  691. * 批量插入后项
  692. * @param {Number} tenderId - 标段Id
  693. * @param {Number} selectId - 选中节点Id
  694. * @param {Object} data - 批量插入数据
  695. * @return {Promise<void>}
  696. */
  697. async batchInsertNext(tenderId, selectId, data) {
  698. const result = { ledger: {}, pos: null };
  699. if ((tenderId <= 0) || (selectId <= 0)) {
  700. return result;
  701. }
  702. const selectData = await this.getDataByNodeId(tenderId, selectId);
  703. if (!selectData) {
  704. throw '位置数据错误';
  705. }
  706. const parentData = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  707. if (!parentData) {
  708. throw '位置数据错误';
  709. }
  710. this.transaction = await this.db.beginTransaction();
  711. const newIds = [];
  712. try {
  713. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  714. await this._updateChildrenOrder(tenderId, selectData.ledger_pid, selectData.order + 1, data.length);
  715. // 计算id和order
  716. const maxId = await this._getMaxLid(tenderId);
  717. const order = selectData.order;
  718. // 数据库创建新增节点数据
  719. for (let i = 0, iLen = data.length; i < iLen; i++) {
  720. // 合并新增数据
  721. const qd = {
  722. id: this.uuid.v4(),
  723. tender_id: tenderId,
  724. ledger_id: maxId + i + 1,
  725. ledger_pid: parentData.ledger_id,
  726. is_leaf: true,
  727. order: order + i + 1,
  728. level: parentData.level + 1,
  729. b_code: data[i].b_code,
  730. name: data[i].name,
  731. unit: data[i].unit,
  732. unit_price: data[i].price,
  733. };
  734. qd.full_path = parentData.full_path + '-' + qd.ledger_id;
  735. const insertResult = await this.transaction.insert(this.tableName, qd);
  736. newIds.push(qd.id);
  737. if (data[i].pos.length > 0) {
  738. await this.ctx.service.pos.insertLedgerPosData(this.transaction, tenderId, qd, data[i].pos);
  739. await this.calcNode(qd, this.transaction);
  740. }
  741. }
  742. this._cacheMaxLid(tenderId, maxId + data.length);
  743. await this.transaction.commit();
  744. } catch (err) {
  745. await this.transaction.rollback();
  746. throw err;
  747. }
  748. // 查询应返回的结果
  749. result.ledger.create = await this.getDataByIds(newIds);
  750. result.ledger.update = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + data.length);
  751. result.pos = await this.ctx.service.pos.getPosData({tid: tenderId, lid: newIds });
  752. return result;
  753. }
  754. /**
  755. * 升级selectData, 同步修改所有子节点
  756. * @param {Object} selectData - 升级操作,选中节点
  757. * @return {Object}
  758. * @private
  759. */
  760. async _syncUplevelChildren(select) {
  761. this.initSqlBuilder();
  762. this.sqlBuilder.setAndWhere(this.setting.mid, {
  763. value: select[this.setting.mid],
  764. operate: '=',
  765. });
  766. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  767. value: this.db.escape(select[this.setting.fullPath] + '-%'),
  768. operate: 'like',
  769. });
  770. this.sqlBuilder.setUpdateData(this.setting.level, {
  771. value: 1,
  772. selfOperate: '-',
  773. });
  774. this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  775. value: [this.setting.fullPath, this.db.escape(select[this.setting.pid] + '-'), this.db.escape('')],
  776. literal: 'Replace',
  777. });
  778. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  779. const data = await this.transaction.query(sql, sqlParam);
  780. return data;
  781. }
  782. /**
  783. * 选中节点的后兄弟节点,全部变为当前节点的子节点
  784. * @param {Object} selectData - 选中节点
  785. * @return {Object}
  786. * @private
  787. */
  788. async _syncUpLevelNexts(select) {
  789. // 查询selectData的lastChild
  790. const lastChild = await this.getLastChildDataFormCR(select[this.setting.mid], select[this.setting.kid]);
  791. const nexts = await this.getNextsData(this.tableName, select[this.setting.mid], select[this.setting.pid], select[this.setting.order]);
  792. if (nexts && nexts.length > 0) {
  793. // 修改nextsData pid, 排序
  794. this.initSqlBuilder();
  795. this.sqlBuilder.setUpdateData(this.setting.pid, {
  796. value: select[this.setting.kid],
  797. });
  798. const orderInc = lastChild ? lastChild[this.setting.order] - select[this.setting.order] : - select[this.setting.order];
  799. this.sqlBuilder.setUpdateData(this.setting.order, {
  800. value: Math.abs(orderInc),
  801. selfOperate: orderInc > 0 ? '+' : '-',
  802. });
  803. this.sqlBuilder.setAndWhere(this.setting.mid, {
  804. value: select[this.setting.mid],
  805. operate: '=',
  806. });
  807. this.sqlBuilder.setAndWhere(this.setting.pid, {
  808. value: select[this.setting.pid],
  809. operate: '=',
  810. });
  811. this.sqlBuilder.setAndWhere(this.setting.order, {
  812. value: select[this.setting.order],
  813. operate: '>',
  814. });
  815. const [sql1, sqlParam1] = this.sqlBuilder.build(this.tableName, 'update');
  816. await this.transaction.query(sql1, sqlParam1);
  817. // 选中节点 is_leaf应为false
  818. if (select.is_leaf) {
  819. const updateData = { id: select.id, is_leaf: false };
  820. await this.transaction.update(this.tableName, updateData);
  821. }
  822. // 修改nextsData及其子节点的full_path
  823. const oldSubStr = this.db.escape(select[this.setting.pid] + '-');
  824. const newSubStr = this.db.escape(select[this.setting.kid] + '-');
  825. const sqlArr = [];
  826. sqlArr.push('Update ?? SET `full_path` = Replace(`full_path`,' + oldSubStr + ',' + newSubStr + ') Where');
  827. sqlArr.push('(`' + this.setting.mid + '` = ' + select[this.setting.mid] + ')');
  828. sqlArr.push(' And (');
  829. for (const data of nexts) {
  830. sqlArr.push('`' + this.setting.fullPath + '` Like ' + this.db.escape(data[this.setting.fullPath] + '%'));
  831. if (nexts.indexOf(data) < nexts.length - 1) {
  832. sqlArr.push(' Or ');
  833. }
  834. }
  835. sqlArr.push(')');
  836. const sql = sqlArr.join('');
  837. const resultData = await this.transaction.query(sql, [this.tableName]);
  838. // 存在下节点,则把此变更清单删除
  839. await this._deleteChangeAuditListData(select[this.setting.mid], [select]);
  840. return resultData;
  841. }
  842. }
  843. /**
  844. * 升级节点
  845. *
  846. * @param {Number} tenderId - 标段id
  847. * @param {Number} selectId - 选中节点id
  848. * @return {Array} - 发生改变的数据
  849. */
  850. async upLevelNode(mid, kid, count) {
  851. if (!count) count = 1;
  852. this.newBills = false;
  853. const selects = await this.getDataByKidAndCount(mid, kid, count);
  854. // const newBills = this.newBills;
  855. if (selects.length !== count) throw '升级节点数据错误';
  856. const first = selects[0], last = selects[count - 1];
  857. const parent = await this.getDataByKid(mid, first[this.setting.pid]);
  858. if (!parent) throw '升级节点数据错误';
  859. const newPath = [];
  860. this.transaction = await this.db.beginTransaction();
  861. try {
  862. // 选中节点--父节点 选中节点为firstChild时,修改is_leaf
  863. if (first[this.setting.order] === 1) {
  864. await this.transaction.update(this.tableName, {
  865. id: parent.id,
  866. is_leaf: true,
  867. });
  868. // throw '不能升级为最高级节点';
  869. }
  870. // 选中节点--父节点--全部后兄弟节点 order+1
  871. await this._updateChildrenOrder(this.tableName, mid, parent[this.setting.pid], parent[this.setting.order] + 1, count);
  872. if (!this.newBills) {
  873. await this._updateChildrenOrder(this.ctx.service.ledger.tableName, mid, parent[this.setting.pid], parent[this.setting.order] + 1, count);
  874. }
  875. for (const [i, s] of selects.entries()) {
  876. // 选中节点 修改pid, order, full_path, level, is_leaf, 清空计算项
  877. const updateData = { id: s.id };
  878. updateData[this.setting.pid] = parent[this.setting.pid];
  879. updateData[this.setting.order] = parent[this.setting.order] + i + 1;
  880. updateData[this.setting.level] = s[this.setting.level] - 1;
  881. updateData[this.setting.fullPath] = s[this.setting.fullPath].replace(s[this.setting.pid] + '-', '');
  882. newPath.push(updateData[this.setting.fullPath]);
  883. if (s.id === last.id) {
  884. const nexts = await this.getNextsData(this.tableName, mid, parent[this.setting.kid], last[this.setting.order]);
  885. if (!this.newBills) {
  886. const ledgerNexts = await this.getNextsData(this.ctx.service.ledger.tableName, mid, parent[this.setting.kid], last[this.setting.order]);
  887. if (ledgerNexts.length > 0) {
  888. throw '该节点下存在台账节点,不可升级';
  889. }
  890. // nexts = this._.orderBy(this._.concat(ledgerNexts, nexts), [this.setting.order], ['asc']);
  891. }
  892. if (s.is_leaf && nexts.length > 0) {
  893. updateData.is_leaf = false;
  894. this.clearParentingData(updateData);
  895. }
  896. }
  897. await this.transaction.update(this.tableName, updateData);
  898. // 选中节点--全部子节点(含孙) level-1, full_path变更
  899. await this._syncUplevelChildren(s);
  900. }
  901. // 选中节点--全部后兄弟节点 收编为子节点 修改pid, order, full_path
  902. await this._syncUpLevelNexts(last);
  903. await this.transaction.commit();
  904. this.transaction = null;
  905. } catch (err) {
  906. await this.transaction.rollback();
  907. this.transaction = null;
  908. throw err;
  909. }
  910. // 查询修改的数据
  911. let updateData = await this.getNextsData(this.tableName, mid, parent[this.setting.pid], parent[this.setting.order] - 1);
  912. if (!this.newBills) {
  913. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, mid, parent[this.setting.pid], parent[this.setting.order] - 1);
  914. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  915. }
  916. for (const path of newPath) {
  917. const children = await this.getDataByFullPath(this.tableName, mid, path + '-%');
  918. updateData = updateData.concat(children);
  919. if (!this.newBills) {
  920. updateData = updateData.concat(await this.getDataByFullPath(this.ctx.service.ledger.tableName, mid, path + '-%'));
  921. }
  922. }
  923. return { update: updateData };
  924. }
  925. /**
  926. * 降级selectData, 同步修改所有子节点
  927. * @param {Object} selectData - 选中节点
  928. * @param {Object} preData - 选中节点的前一节点(降级后为父节点)
  929. * @return {Promise<*>}
  930. * @private
  931. */
  932. async _syncDownlevelChildren(select, pre) {
  933. this.initSqlBuilder();
  934. this.sqlBuilder.setAndWhere(this.setting.mid, {
  935. value: select[this.setting.mid],
  936. operate: '=',
  937. });
  938. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  939. value: this.db.escape(select[this.setting.fullPath] + '-%'),
  940. operate: 'like',
  941. });
  942. this.sqlBuilder.setUpdateData(this.setting.level, {
  943. value: 1,
  944. selfOperate: '+',
  945. });
  946. this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  947. value: [this.setting.fullPath, this.db.escape(select[this.setting.kid] + '-'), this.db.escape(pre[this.setting.kid] + '-' + select[this.setting.kid] + '-')],
  948. literal: 'Replace',
  949. });
  950. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  951. const data = await this.transaction.query(sql, sqlParam);
  952. return data;
  953. }
  954. async getDataByFullPath(tableName, mid, full_path, transaction = null) {
  955. this.initSqlBuilder();
  956. this.sqlBuilder.setAndWhere(this.setting.mid, {
  957. value: mid,
  958. operate: '=',
  959. });
  960. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  961. value: this.db.escape(full_path),
  962. operate: 'Like',
  963. });
  964. const [sql, sqlParam] = this.sqlBuilder.build(tableName);
  965. const resultData = transaction ? await transaction.query(sql, sqlParam) : await this.db.query(sql, sqlParam);
  966. return resultData;
  967. }
  968. /**
  969. * 获取最末的子节点
  970. * @param {Number} mid - masterId
  971. * @param {Number} pid - 父节点id
  972. * @return {Object}
  973. */
  974. async getLastChildDataFormCR(mid, pid) {
  975. let preLastChild = await this.getLastChildData(this.tableName, mid, pid);
  976. if (!this.newBills) {
  977. const preLedgerLastChild = await this.getLastChildData(this.ctx.service.ledger.tableName, mid, pid);
  978. if (!preLastChild) {
  979. preLastChild = preLedgerLastChild;
  980. } else {
  981. preLastChild = preLedgerLastChild && preLedgerLastChild[this.setting.order] > preLastChild[this.setting.order] ? preLedgerLastChild : preLastChild;
  982. }
  983. }
  984. return preLastChild;
  985. }
  986. async getLastChildData(tableName, mid, pid) {
  987. this.initSqlBuilder();
  988. this.sqlBuilder.setAndWhere(this.setting.mid, {
  989. value: mid,
  990. operate: '=',
  991. });
  992. this.sqlBuilder.setAndWhere(this.setting.pid, {
  993. value: pid,
  994. operate: '=',
  995. });
  996. this.sqlBuilder.orderBy = [['order', 'DESC']];
  997. const [sql, sqlParam] = this.sqlBuilder.build(tableName);
  998. const resultData = await this.db.queryOne(sql, sqlParam);
  999. return resultData;
  1000. }
  1001. /**
  1002. * 降级节点
  1003. *
  1004. * @param {Number} tenderId - 标段id
  1005. * @param {Number} selectId - 选中节点id
  1006. * @return {Array} - 发生改变的数据
  1007. */
  1008. async downLevelNode(mid, kid, count) {
  1009. if (!count) count = 1;
  1010. this.newBills = false;
  1011. const selects = await this.getDataByKidAndCount(mid, kid, count);
  1012. // const newBills = this.newBills;
  1013. if (!selects) throw '降级节点数据错误';
  1014. const first = selects[0], last = selects[count - 1];
  1015. const pre = await this.getDataByParentAndOrder(mid, first[this.setting.pid], first[this.setting.order] - 1);
  1016. if (!pre) throw '节点不可降级';
  1017. const preLastChild = await this.getLastChildDataFormCR(mid, pre[this.setting.kid]);
  1018. const newPath = [];
  1019. this.transaction = await this.db.beginTransaction();
  1020. try {
  1021. // 选中节点--全部后节点 order--
  1022. await this._updateChildrenOrder(this.tableName, mid, first[this.setting.pid], last[this.setting.order] + 1, -count);
  1023. if (!this.newBills) {
  1024. await this._updateChildrenOrder(this.ctx.service.ledger.tableName, mid, first[this.setting.pid], last[this.setting.order] + 1, -count);
  1025. }
  1026. for (const [i, s] of selects.entries()) {
  1027. // 选中节点 修改pid, level, order, full_path
  1028. const updateData = { id: s.id };
  1029. updateData[this.setting.pid] = pre[this.setting.kid];
  1030. updateData[this.setting.order] = preLastChild ? preLastChild[this.setting.order] + i + 1 : i + 1;
  1031. updateData[this.setting.level] = s[this.setting.level] + 1;
  1032. const orgLastPath = s[this.setting.level] === 1 ? s[this.setting.kid] : '-' + s[this.setting.kid];
  1033. const newLastPath = s[this.setting.level] === 1 ? pre[this.setting.kid] + '-' + s[this.setting.kid] : '-' + pre[this.setting.kid] + '-' + s[this.setting.kid];
  1034. updateData[this.setting.fullPath] = s[this.setting.fullPath].replace(orgLastPath, newLastPath);
  1035. newPath.push(updateData[this.setting.fullPath]);
  1036. // console.log(updateData);
  1037. await this.transaction.update(this.tableName, updateData);
  1038. // 选中节点--全部子节点(含孙) level++, full_path
  1039. await this._syncDownlevelChildren(s, pre);
  1040. }
  1041. // 选中节点--前兄弟节点 is_leaf应为false, 清空计算相关字段
  1042. const updateData2 = { id: pre.id };
  1043. updateData2[this.setting.isLeaf] = false;
  1044. this.clearParentingData(updateData2);
  1045. await this.transaction.update(this.tableName, updateData2);
  1046. await this._deleteChangeAuditListData(mid, [pre]);
  1047. // if (selects) {
  1048. // throw '阻断';
  1049. // }
  1050. await this.transaction.commit();
  1051. this.transaction = null;
  1052. } catch (err) {
  1053. await this.transaction.rollback();
  1054. this.transaction = null;
  1055. throw err;
  1056. }
  1057. // 查询修改的数据
  1058. let updateData = await this.getNextsData(this.tableName, mid, pre[this.setting.pid], pre[this.setting.order] - 1);
  1059. if (!this.newBills) {
  1060. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, mid, pre[this.setting.pid], pre[this.setting.order] - 1);
  1061. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  1062. }
  1063. // 选中节点及子节点
  1064. for (const p of newPath) {
  1065. updateData = updateData.concat(await this.getDataByFullPath(this.tableName, mid, p + '%'));
  1066. if (!this.newBills) {
  1067. updateData = updateData.concat(await this.getDataByFullPath(this.ctx.service.ledger.tableName, mid, p + '%'));
  1068. }
  1069. }
  1070. // 选中节点--原前兄弟节点&全部后兄弟节点
  1071. return { update: updateData };
  1072. }
  1073. async pasteBlockData (tid, sid, pasteData, defaultData) {
  1074. if ((tid <= 0) || (sid <= 0)) return [];
  1075. if (!pasteData || pasteData.length <= 0) throw '复制数据错误';
  1076. for (const pd of pasteData) {
  1077. if (!pd || pd.length <= 0) throw '复制数据错误';
  1078. pd.sort(function (x, y) {
  1079. return x.level - y.level
  1080. });
  1081. if (pd[0].ledger_pid !== pasteData[0][0].ledger_pid) throw '复制数据错误:仅可操作同层节点';
  1082. }
  1083. const selectData = await this.getDataByKid(tid, sid);
  1084. if (!selectData) throw '粘贴数据错误';
  1085. const newParentPath = selectData.full_path.replace(selectData.ledger_id, '');
  1086. const pasteBillsData = [], pastePosData = [], leafBillsId = [];
  1087. const tpDecimal = this.ctx.tender.info.decimal.tp;
  1088. let maxId = await this._getMaxLid(this.ctx.tender.id);
  1089. for (const [i, pd] of pasteData.entries()) {
  1090. for (const d of pd) {
  1091. d.children = pd.filter(function (x) {
  1092. return x.ledger_pid === d.ledger_id;
  1093. });
  1094. }
  1095. const pbd = [];
  1096. for (const [j, d] of pd.entries()) {
  1097. const newBills = {
  1098. id: this.uuid.v4(),
  1099. tender_id: tid,
  1100. ledger_id: maxId + j + 1,
  1101. ledger_pid: j === 0 ? selectData.ledger_pid : d.ledger_pid,
  1102. level: d.level + selectData.level - pd[0].level,
  1103. order: j === 0 ? selectData.order + i + 1 : d.order,
  1104. is_leaf: d.is_leaf,
  1105. code: d.code,
  1106. b_code: d.b_code,
  1107. name: d.name,
  1108. unit: d.unit,
  1109. unit_price: this.ctx.helper.round(d.unit_price, this.ctx.tender.info.decimal.up),
  1110. source: d.source,
  1111. remark: d.remark,
  1112. drawing_code: d.drawing_code,
  1113. memo: d.memo,
  1114. ex_memo1: d.ex_memo1,
  1115. ex_memo2: d.ex_memo2,
  1116. ex_memo3: d.ex_memo3,
  1117. node_type: d.node_type,
  1118. sgfh_expr: d.sgfh_expr,
  1119. sjcl_expr: d.sjcl_expr,
  1120. qtcl_expr: d.qtcl_expr,
  1121. check_calc: 1,
  1122. ccid: this.ctx.change.cid,
  1123. };
  1124. for (const c of d.children) {
  1125. c.ledger_pid = newBills.ledger_id;
  1126. }
  1127. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, newBills.unit);
  1128. newBills.deal_qty = this.ctx.helper.round(d.deal_qty, precision.value);
  1129. if (d.pos && d.pos.length > 0) {
  1130. for (const pos of d.pos) {
  1131. const newPos = {
  1132. id: this.uuid.v4(),
  1133. tid: tid,
  1134. lid: newBills.id,
  1135. name: pos.name,
  1136. drawing_code: pos.drawing_code,
  1137. add_user: this.ctx.session.sessionUser.accountId,
  1138. in_time: new Date(),
  1139. porder: pos.porder,
  1140. position: pos.position,
  1141. sgfh_expr: pos.sgfh_expr ? pos.sgfh_expr : '',
  1142. sjcl_expr: pos.sjcl_expr ? pos.sjcl_expr : '',
  1143. qtcl_expr: pos.qtcl_expr ? pos.qtcl_expr : '',
  1144. add_stage: 0,
  1145. add_times: 0,
  1146. ex_memo1: pos.ex_memo1,
  1147. ex_memo2: pos.ex_memo2,
  1148. ex_memo3: pos.ex_memo3,
  1149. ccid: this.ctx.change.cid,
  1150. };
  1151. this._calcExpr(newPos, 'sgfh_qty', pos.sgfh_expr, pos.sgfh_qty, precision);
  1152. this._calcExpr(newPos, 'sjcl_qty', pos.sjcl_expr, pos.sjcl_qty, precision);
  1153. this._calcExpr(newPos, 'qtcl_qty', pos.qtcl_expr, pos.qtcl_qty, precision);
  1154. newPos.quantity = this.ctx.helper.add(newPos.sgfh_qty,
  1155. this.ctx.helper.add(newPos.sjcl_qty, newPos.qtcl_qty));
  1156. newBills.sgfh_qty = this.ctx.helper.add(newBills.sgfh_qty, newPos.sgfh_qty);
  1157. newBills.sjcl_qty = this.ctx.helper.add(newBills.sjcl_qty, newPos.sjcl_qty);
  1158. newBills.qtcl_qty = this.ctx.helper.add(newBills.qtcl_qty, newPos.qtcl_qty);
  1159. if (defaultData) this.ctx.helper._.assignIn(newPos, defaultData);
  1160. pastePosData.push(newPos);
  1161. }
  1162. } else {
  1163. this._calcExpr(newBills, 'sgfh_qty', newBills.sgfh_expr, d.sgfh_qty, precision);
  1164. this._calcExpr(newBills, 'sjcl_qty', newBills.sjcl_expr, d.sjcl_qty, precision);
  1165. this._calcExpr(newBills, 'qtcl_qty', newBills.qtcl_expr, d.qtcl_qty, precision);
  1166. }
  1167. newBills.quantity = this.ctx.helper.add(newBills.sgfh_qty,
  1168. this.ctx.helper.add(newBills.sjcl_qty, newBills.qtcl_qty));
  1169. newBills.sgfh_tp = this.ctx.helper.mul(newBills.sgfh_qty, newBills.unit_price, tpDecimal);
  1170. newBills.sjcl_tp = this.ctx.helper.mul(newBills.qtcl_qty, newBills.unit_price, tpDecimal);
  1171. newBills.qtcl_tp = this.ctx.helper.mul(newBills.sjcl_qty, newBills.unit_price, tpDecimal);
  1172. newBills.total_price = this.ctx.helper.mul(newBills.quantity, newBills.unit_price, tpDecimal);
  1173. newBills.deal_tp = this.ctx.helper.mul(newBills.deal_qty, newBills.unit_price, tpDecimal);
  1174. if (defaultData) this.ctx.helper._.assignIn(newBills, defaultData);
  1175. pbd.push(newBills);
  1176. }
  1177. for (const d of pbd) {
  1178. const parent = pbd.find(function (x) {
  1179. return x.ledger_id === d.ledger_pid;
  1180. });
  1181. d.full_path = parent
  1182. ? parent.full_path + '-' + d.ledger_id
  1183. : newParentPath + d.ledger_id;
  1184. if (defaultData) this.ctx.helper._.assignIn(pbd, defaultData);
  1185. pasteBillsData.push(d);
  1186. }
  1187. maxId = maxId + pbd.length;
  1188. }
  1189. this.transaction = await this.db.beginTransaction();
  1190. try {
  1191. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  1192. await this._updateChildrenOrder(this.tableName, tid, selectData.ledger_pid, selectData.order + 1, pasteData.length);
  1193. if (!this.newBills) {
  1194. await this._updateChildrenOrder(this.ctx.service.ledger.tableName, tid, selectData.ledger_pid, selectData.order + 1, pasteData.length);
  1195. }
  1196. // 数据库创建新增节点数据
  1197. if (pasteBillsData.length > 0) {
  1198. const newData = await this.transaction.insert(this.tableName, pasteBillsData);
  1199. }
  1200. this._cacheMaxLid(tid, maxId);
  1201. if (pastePosData.length > 0) {
  1202. await this.transaction.insert(this.ctx.service.changePos.tableName, pastePosData);
  1203. }
  1204. await this.transaction.commit();
  1205. } catch (err) {
  1206. await this.transaction.rollback();
  1207. throw err;
  1208. }
  1209. // 查询应返回的结果
  1210. let updateData = await this.getNextsData(this.tableName, selectData.tender_id, selectData.ledger_pid, selectData.order + pasteData.length);
  1211. if (!this.newBills) {
  1212. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, selectData.tender_id, selectData.ledger_pid, selectData.order + pasteData.length);
  1213. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  1214. }
  1215. return {
  1216. ledger: { create: pasteBillsData, update: updateData },
  1217. pos: pastePosData,
  1218. };
  1219. }
  1220. /**
  1221. * 添加标准节点,将选择的标准节点,添加为子节点(排序为末尾)
  1222. * @param {Number} tenderId - 标段Id
  1223. * @param {Number} selectId - 添加目标节点Id
  1224. * @param {Object} stdData - 标准节点数据
  1225. * @returns {Promise<*>}
  1226. */
  1227. async addStdNodeAsChild(tenderId, selectId, stdData, changeId) {
  1228. const newData = this._filterStdData(stdData);
  1229. const result = await this.addChild(tenderId, selectId, newData, changeId);
  1230. return result;
  1231. }
  1232. /**
  1233. * 新增子节点,并排在所有子节点的末尾
  1234. * @param {Number} tenderId - 标段Id
  1235. * @param {Number} selectId - 父节点Id
  1236. * @param {Object} data - 新增节点数据(编号名称等)
  1237. * @returns {Promise<*>}
  1238. */
  1239. async addChild(tenderId, selectId, data, changeId) {
  1240. if ((tenderId <= 0) || (selectId <= 0)) {
  1241. return [];
  1242. }
  1243. this.newBills = false;
  1244. const selectData = await this.getDataByKid(tenderId, selectId);
  1245. if (!selectData) {
  1246. throw '新增节点数据错误';
  1247. }
  1248. let children = await this.getChildrenByParentId(this.tableName, tenderId, selectId);
  1249. if (!this.newBills) {
  1250. const ledgerChildren = await this.getChildrenByParentId(this.ctx.service.ledger.tableName, tenderId, selectId);
  1251. children = this._.orderBy(this._.concat(ledgerChildren, children), [this.setting.order], ['asc']);
  1252. }
  1253. const maxId = await this._getMaxLid(tenderId);
  1254. data.id = this.uuid.v4();
  1255. data.tender_id = tenderId;
  1256. data.ledger_id = maxId + 1;
  1257. data.ledger_pid = selectData.ledger_id;
  1258. data.level = selectData.level + 1;
  1259. data.order = children.length + 1;
  1260. data.full_path = selectData.full_path + '-' + data.ledger_id;
  1261. data.is_leaf = true;
  1262. data.ccid = changeId;
  1263. data.check_calc = 1;
  1264. // if (reviseId) data.crid = reviseId;
  1265. this.transaction = await this.db.beginTransaction();
  1266. try {
  1267. const result = await this.transaction.insert(this.tableName, data);
  1268. if (children.length === 0 && this.newBills) {
  1269. await this.transaction.update(this.tableName,
  1270. {
  1271. is_leaf: false,
  1272. sgfh_qty: null, sgfh_tp: null, qtcl_qty: null, qtcl_tp: null, sjcl_qty: null, sjcl_tp: null,
  1273. quantity: null, unit_price: null, total_price: null, deal_qty: null, deal_tp: null
  1274. },
  1275. { where: {tender_id: tenderId, ledger_id: selectData.ledger_id} });
  1276. }
  1277. await this.transaction.commit();
  1278. } catch (err) {
  1279. this.transaction.rollback();
  1280. throw err;
  1281. }
  1282. this._cacheMaxLid(tenderId, maxId + 1);
  1283. // 查询应返回的结果
  1284. const resultData = {};
  1285. resultData.create = await this.getDataByKid(tenderId, data.ledger_id);
  1286. if (children.length === 0) {
  1287. resultData.update = await this.getDataByKid(tenderId, selectId);
  1288. }
  1289. return resultData;
  1290. }
  1291. /**
  1292. * 根据 父节点id 获取子节点
  1293. * @param tenderId
  1294. * @param nodeId
  1295. * @return {Promise<*>}
  1296. */
  1297. async getChildrenByParentId(tableName, tenderId, nodeId) {
  1298. if (tenderId <= 0 || !nodeId) {
  1299. return undefined;
  1300. }
  1301. const nodeIds = nodeId instanceof Array ? nodeId : [nodeId];
  1302. if (nodeIds.length === 0) {
  1303. return [];
  1304. }
  1305. this.initSqlBuilder();
  1306. this.sqlBuilder.setAndWhere('tender_id', {
  1307. value: tenderId,
  1308. operate: '=',
  1309. });
  1310. this.sqlBuilder.setAndWhere('ledger_pid', {
  1311. value: nodeIds,
  1312. operate: 'in',
  1313. });
  1314. this.sqlBuilder.orderBy = [['order', 'ASC']];
  1315. const [sql, sqlParam] = this.sqlBuilder.build(tableName);
  1316. const data = await this.db.query(sql, sqlParam);
  1317. return data;
  1318. }
  1319. /**
  1320. * 添加节点(来自标准清单)
  1321. * @param {Number} tenderId
  1322. * @param {Number} selectId
  1323. * @param {Object} stdData
  1324. * @return {Promise<*>}
  1325. */
  1326. async addStdNode(tenderId, selectId, stdData, changeId) {
  1327. const newData = this._filterStdData(stdData);
  1328. const result = await this.addBillsNode(tenderId, selectId, newData, changeId);
  1329. return result;
  1330. }
  1331. async addBillsNode(tenderId, selectId, data, changeId) {
  1332. if (data) {
  1333. if (changeId) data.ccid = changeId;
  1334. data.check_calc = 1;
  1335. return await this.addNode(tenderId, selectId, data);
  1336. } else {
  1337. return await this.addNode(tenderId, selectId, {ccid: changeId, check_calc: 1});
  1338. }
  1339. }
  1340. /**
  1341. * 添加节点,并同步添加父节点
  1342. * @param {Number} tenderId - 标段id
  1343. * @param {Number} selectId - 选中节点id
  1344. * @param {Object} stdData - 节点数据
  1345. * @param {StandardLib} stdLib - 标准库
  1346. * @return {Promise<void>}
  1347. */
  1348. async addStdNodeWithParent(tenderId, stdData, stdLib, changeId) {
  1349. // 查询完整标准清单,并按层次排序
  1350. const fullLevel = await stdLib.getFullLevelDataByFullPath(stdData.list_id, stdData.full_path);
  1351. fullLevel.sort(function(x, y) {
  1352. return x.level - y.level;
  1353. });
  1354. let isNew = false,
  1355. node,
  1356. firstNew,
  1357. updateParent,
  1358. addResult;
  1359. const expandIds = [];
  1360. this.transaction = await this.db.beginTransaction();
  1361. try {
  1362. // 从最顶层节点依次查询是否存在,否则添加
  1363. for (let i = 0, len = fullLevel.length; i < len; i++) {
  1364. const stdNode = fullLevel[i];
  1365. if (isNew) {
  1366. const newData = this._filterStdData(stdNode);
  1367. newData.is_leaf = (i === len - 1);
  1368. [addResult, node] = await this._addChildNodeData(tenderId, node, newData, changeId);
  1369. } else {
  1370. const parent = node;
  1371. node = await this.getDataByCondition({
  1372. tender_id: tenderId,
  1373. ledger_pid: parent ? parent.ledger_id : rootId,
  1374. code: stdNode.code,
  1375. name: stdNode.name,
  1376. }) || await this.ctx.service.ledger.getDataByCondition({tender_id: tenderId, ledger_pid: parent ? parent.ledger_id : rootId, code: stdNode.code, name: stdNode.name });
  1377. if (!node) {
  1378. isNew = true;
  1379. const newData = this._filterStdData(stdNode);
  1380. newData.is_leaf = (i === len - 1);
  1381. [addResult, node] = await this._addChildAutoOrder(tenderId, parent, newData, changeId);
  1382. if (parent && parent.is_leaf && this.newBills) {
  1383. await this.transaction.update(this.tableName, { id: parent.id, is_leaf: false,
  1384. unit_price: null, quantity: null, total_price: null, deal_qty: null, deal_tp: null});
  1385. updateParent = parent;
  1386. }
  1387. firstNew = node;
  1388. } else {
  1389. expandIds.push(node.ledger_id);
  1390. }
  1391. }
  1392. }
  1393. await this.transaction.commit();
  1394. } catch (err) {
  1395. await this.transaction.rollback();
  1396. throw err;
  1397. }
  1398. // 查询应返回的结果
  1399. let createData = [],
  1400. updateData = [];
  1401. if (firstNew) {
  1402. createData = await this.getDataByFullPath(this.tableName, tenderId, firstNew.full_path + '%');
  1403. updateData = await this.getNextsData(this.tableName, tenderId, firstNew.ledger_pid, firstNew.order);
  1404. if (!this.newBills) {
  1405. createData = createData.concat(await this.getDataByFullPath(this.ctx.service.ledger.tableName, tenderId, firstNew.full_path + '%'));
  1406. updateData = await this.getNextsData(this.ctx.service.ledger.tableName, tenderId, firstNew.ledger_pid, firstNew.order);
  1407. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, tenderId, firstNew.ledger_pid, firstNew.order);
  1408. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  1409. }
  1410. if (updateParent) {
  1411. updateData.push(await this.getDataByCondition({ id: updateParent.id }));
  1412. }
  1413. }
  1414. return { create: createData, update: updateData };
  1415. }
  1416. /**
  1417. * 根据parentData, data新增数据(新增为parentData的最后一个子项)
  1418. * @param {Number} tenderId - 标段id
  1419. * @param {Object} parentData - 父项数据
  1420. * @param {Object} data - 新增节点,初始数据
  1421. * @return {Promise<*>} - 新增结果
  1422. * @private
  1423. */
  1424. async _addChildNodeData(tenderId, parentData, data, changeId) {
  1425. if (tenderId <= 0) {
  1426. return undefined;
  1427. }
  1428. if (!data) {
  1429. data = {};
  1430. }
  1431. const pid = parentData ? parentData.ledger_id : rootId;
  1432. const maxId = await this._getMaxLid(tenderId);
  1433. data.id = this.uuid.v4();
  1434. data.tender_id = tenderId;
  1435. data.ledger_id = maxId + 1;
  1436. data.ledger_pid = pid;
  1437. if (data.order === undefined) {
  1438. data.order = 1;
  1439. }
  1440. data.level = parentData ? parentData.level + 1 : 1;
  1441. data.full_path = parentData ? parentData.full_path + '-' + data.ledger_id : '' + data.ledger_id;
  1442. if (data.is_leaf === undefined) {
  1443. data.is_leaf = true;
  1444. }
  1445. data.check_calc = 1;
  1446. if (changeId) data.ccid = changeId;
  1447. const result = await this.transaction.insert(this.tableName, data);
  1448. this._cacheMaxLid(tenderId, maxId + 1);
  1449. return [result, data];
  1450. }
  1451. /**
  1452. * 根据parentData, data新增数据(自动排序)
  1453. * @param tenderId
  1454. * @param parentData
  1455. * @param data
  1456. * @return {Promise<void>}
  1457. * @private
  1458. */
  1459. async _addChildAutoOrder(tenderId, parentData, data, changeId) {
  1460. const self = this;
  1461. const findPreData = function(list, a) {
  1462. if (!list || list.length === 0) { return null; }
  1463. for (let i = 0, iLen = list.length; i < iLen; i++) {
  1464. if (billsUtils.compareCode(list[i].code, a.code) > 0) {
  1465. return i > 0 ? list[i - 1] : null;
  1466. }
  1467. }
  1468. return list[list.length - 1];
  1469. };
  1470. const pid = parentData ? parentData.ledger_id : rootId;
  1471. const children = await this.getChildrenByParentId(tenderId, pid);
  1472. const preData = findPreData(children, data);
  1473. if (!preData || children.indexOf(preData) < children.length - 1) {
  1474. await this._updateChildrenOrder(this.tableName, tenderId, pid, preData ? preData.order + 1 : 1);
  1475. if (!this.newBills) {
  1476. await this._updateChildrenOrder(this.ctx.service.ledger.tableName, tenderId, pid, preData ? preData.order + 1 : 1);
  1477. }
  1478. }
  1479. data.order = preData ? preData.order + 1 : 1;
  1480. const [addResult, node] = await this._addChildNodeData(tenderId, parentData, data, changeId);
  1481. return [addResult, node];
  1482. }
  1483. /**
  1484. * 提交数据 - 响应计算(增量方式计算)
  1485. * @param {Number} tenderId
  1486. * @param {Object} data
  1487. * @return {Promise<*>}
  1488. */
  1489. async updateCalc(tenderId, data) {
  1490. const helper = this.ctx.helper;
  1491. // 简单验证数据
  1492. if (tenderId <= 0 || !this.ctx.tender) {
  1493. throw '标段不存在';
  1494. }
  1495. const info = this.ctx.tender.info;
  1496. if (!data) {
  1497. throw '提交数据错误';
  1498. }
  1499. const datas = data instanceof Array ? data : [data];
  1500. const ids = [];
  1501. for (const row of datas) {
  1502. if (tenderId !== row.tender_id) {
  1503. throw '提交数据错误';
  1504. }
  1505. ids.push(row.id);
  1506. }
  1507. this.transaction = await this.db.beginTransaction();
  1508. try {
  1509. // const updateDatas = [];
  1510. for (const row of datas) {
  1511. const updateNode = await this.getDataById(row.id);
  1512. if (!updateNode || tenderId !== updateNode.tender_id || row.ledger_id !== updateNode.ledger_id) {
  1513. throw '提交数据错误';
  1514. }
  1515. let updateData;
  1516. // 更新单位或单价,全部数据都应重算
  1517. if (row.unit !== undefined || row.unit_price !== undefined) {
  1518. if (row.sgfh_qty === undefined) { row.sgfh_qty = updateNode.sgfh_qty; }
  1519. if (row.sjcl_qty === undefined) { row.sjcl_qty = updateNode.sjcl_qty; }
  1520. if (row.qtcl_qty === undefined) { row.qtcl_qty = updateNode.qtcl_qty; }
  1521. if (row.deal_qty === undefined) { row.deal_qty = updateNode.deal_qty; }
  1522. }
  1523. // 项目节、工程量清单相关
  1524. if (row.b_code) {
  1525. row.dgn_qty1 = null;
  1526. row.dgn_qty2 = null;
  1527. row.code = null;
  1528. }
  1529. if (row.code) row.b_code = null;
  1530. if (this._checkCalcField(row)) {
  1531. let calcData = JSON.parse(JSON.stringify(row));
  1532. calcData.check_calc = 1;
  1533. const precision = helper.findPrecision(info.precision, row.unit ? row.unit : updateNode.unit);
  1534. // 数量保留小数位数
  1535. helper.checkFieldPrecision(calcData, qtyFields, precision.value);
  1536. // 单位保留小数位数
  1537. helper.checkFieldPrecision(calcData, upFields, info.decimal.up);
  1538. // 未提交单价则读取数据库单价
  1539. if (row.unit_price === undefined) calcData.unit_price = updateNode.unit_price;
  1540. // 计算
  1541. if (row.sgfh_qty !== undefined || row.sjcl_qty !== undefined || row.qtcl_qty !== undefined ||
  1542. row.deal_qty !== undefined || row.unit_price) {
  1543. if (row.sgfh_qty === undefined) calcData.sgfh_qty = updateNode.sgfh_qty;
  1544. if (row.sjcl_qty === undefined) calcData.sjcl_qty = updateNode.sjcl_qty;
  1545. if (row.qtcl_qty === undefined) calcData.qtcl_qty = updateNode.qtcl_qty;
  1546. if (row.deal_qty === undefined) calcData.deal_qty = updateNode.deal_qty;
  1547. calcData.quantity = helper.sum([calcData.sgfh_qty, calcData.sjcl_qty, calcData.qtcl_qty]);
  1548. calcData.sgfh_tp = helper.mul(calcData.sgfh_qty, calcData.unit_price, info.decimal.tp);
  1549. calcData.sjcl_tp = helper.mul(calcData.sjcl_qty, calcData.unit_price, info.decimal.tp);
  1550. calcData.qtcl_tp = helper.mul(calcData.qtcl_qty, calcData.unit_price, info.decimal.tp);
  1551. calcData.total_price = helper.mul(calcData.quantity, calcData.unit_price, info.decimal.tp);
  1552. calcData.deal_tp = helper.mul(calcData.deal_qty, calcData.unit_price, info.decimal.tp);
  1553. } else if (row.sgfh_tp !== undefined || row.sjcl_tp !== undefined || row.qtcl_tp !== undefined || row.deal_tp !== undefined) {
  1554. calcData.sgfh_qty = null;
  1555. calcData.sjcl_qty = null;
  1556. calcData.qtcl_qty = null;
  1557. calcData.quantity = null;
  1558. calcData.deal_qty = null;
  1559. calcData.sgfh_tp = helper.round(row.sgfh_tp !== undefined ? calcData.row.sgfh_tp : updateNode.sgfh_tp, info.decimal.tp);
  1560. calcData.sjcl_tp = helper.round(row.sgfh_tp !== undefined ? calcData.row.sjcl_tp : updateNode.sjcl_tp, info.decimal.tp);
  1561. calcData.qtcl_tp = helper.round(row.sgfh_tp !== undefined ? calcData.row.qtcl_tp : updateNode.qtcl_tp, info.decimal.tp);
  1562. calcData.total_price = helper.sum([calcData.sgfh_tp, calcData.sjcl_tp, calcData.qtcl_tp]);
  1563. calcData.deal_tp = helper.round(row.deal_tp !== undefined ? calcData.row.deal_tp : updateNode.deal_tp, info.decimal.tp);
  1564. } else if (row.unit_price !== undefined) {
  1565. calcData.sgfh_tp = helper.mul(calcData.sgfh_qty, calcData.unit_price, info.decimal.tp);
  1566. calcData.sjcl_tp = helper.mul(calcData.sjcl_qty, calcData.unit_price, info.decimal.tp);
  1567. calcData.qtcl_tp = helper.mul(calcData.qtcl_qty, calcData.unit_price, info.decimal.tp);
  1568. calcData.total_price = helper.mul(calcData.quantity, calcData.unit_price, info.decimal.tp);
  1569. calcData.deal_tp = helper.mul(calcData.deal_qty, calcData.unit_price, info.decimal.tp);
  1570. }
  1571. updateData = this._filterUpdateInvalidField(updateNode.id, calcData);
  1572. } else {
  1573. updateData = this._filterUpdateInvalidField(updateNode.id, row);
  1574. }
  1575. await this.transaction.update(this.tableName, updateData);
  1576. // 如非子节点,需要更新底下所有已选清单的分部分项等数据
  1577. // updateDatas.push(updateData);
  1578. }
  1579. // console.log(updateDatas);
  1580. // 如果是子节点 更新了单位或单价,则更新数据并重算变更令总金额
  1581. await this.ctx.service.changeAuditList.updateDataByReviseLedger(this.transaction, tenderId, datas);
  1582. // if (data) {
  1583. // throw '阻断';
  1584. // }
  1585. await this.transaction.commit();
  1586. this.transaction = null;
  1587. } catch (err) {
  1588. await this.transaction.rollback();
  1589. this.transaction = null;
  1590. throw err;
  1591. }
  1592. return { update: await this.getDataById(ids) };
  1593. }
  1594. }
  1595. return ChangeLedger;
  1596. };