change_ledger.js 81 KB

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