base_tree_service.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  1. 'use strict';
  2. /**
  3. * 提供基础操作:增删改查
  4. *
  5. * @author Mai
  6. * @date
  7. * @version
  8. */
  9. const Service = require('./base_service');
  10. // sql拼装器
  11. const SqlBuilder = require('../lib/sql_builder');
  12. const rootId = -1;
  13. class TreeService extends Service {
  14. /**
  15. * 构造函数
  16. *
  17. * @param {Object} ctx - egg全局context
  18. * @param {Object} setting - 树结构设置
  19. * e.g.: {
  20. * mid: 'tender_id', 分块id(例如tender_id, rid, list_id)
  21. * kid: 'ledger_id', 分块内的树结构id
  22. * pid: 'ledger_pid', 父节点id
  23. * order: 'order',
  24. * level: 'level',
  25. * fullPath: 'full_path',
  26. * isLeaf: 'is_leaf',
  27. * keyPre: 'revise_bills_maxLid:'
  28. * }
  29. * @return {void}
  30. */
  31. constructor(ctx, setting) {
  32. super(ctx);
  33. this.tableName = setting.tableName;
  34. this.setting = setting;
  35. if (this.setting.cacheKey === undefined) this.setting.cacheKey = true;
  36. // 以下字段仅可通过树结构操作改变,不可直接通过update方式从接口提交,发现时过滤
  37. this.readOnlyFields = ['id'];
  38. this.readOnlyFields.push(this.setting.mid);
  39. this.readOnlyFields.push(this.setting.kid);
  40. this.readOnlyFields.push(this.setting.pid);
  41. this.readOnlyFields.push(this.setting.order);
  42. this.readOnlyFields.push(this.setting.level);
  43. this.readOnlyFields.push(this.setting.fullPath);
  44. this.readOnlyFields.push(this.setting.isLeaf);
  45. }
  46. get rootId() {
  47. return rootId;
  48. }
  49. getCondition (condition) {
  50. const result = {};
  51. if (condition.mid) result[this.setting.mid] = condition.mid;
  52. if (condition.kid) result[this.setting.kid] = condition.kid;
  53. if (condition.pid) result[this.setting.pid] = condition.pid;
  54. if (condition.order) result[this.setting.order] = condition.order;
  55. if (condition.level) result[this.setting.level] = condition.level;
  56. if (condition.fullPath) result[this.setting.fullPath] = condition.fullPath;
  57. if (condition.isLeaf) result[this.setting.isLeaf] = condition.isLeaf;
  58. return result;
  59. }
  60. /**
  61. * 获取 修订 清单数据
  62. * @param {Number} mid - masterId
  63. * @returns {Promise<void>}
  64. */
  65. async getData(mid, level) {
  66. if (level) {
  67. this.initSqlBuilder();
  68. this.sqlBuilder.setAndWhere(this.setting.mid, {
  69. operate: '=',
  70. value: this.db.escape(mid),
  71. });
  72. this.sqlBuilder.setAndWhere(this.setting.level, {
  73. operate: '<=',
  74. value: level,
  75. });
  76. const [sql, sqlParam] = this.sqlBuilder.build(this.departTableName(mid));
  77. return await this.db.query(sql, sqlParam);
  78. } else {
  79. return await this.db.select(this.departTableName(mid), {
  80. where: this.getCondition({ mid: mid })
  81. });
  82. }
  83. }
  84. /**
  85. * 获取节点数据
  86. * @param {Number} mid - masterId
  87. * @param {Number} id
  88. * @returns {Promise<void>}
  89. */
  90. async getDataByKid (mid, kid) {
  91. return await this.db.get(this.tableName, this.getCondition({
  92. mid: mid, kid: kid,
  93. }));
  94. }
  95. async getDataByKidAndCount(mid, kid, count) {
  96. if (!mid || (kid <= 0)) return [];
  97. const select = await this.getDataByKid(mid, kid);
  98. if (!select) throw '数据错误';
  99. if (count > 1) {
  100. const selects = await this.getNextsData(mid, select[this.setting.pid], select[this.setting.order] - 1);
  101. if (selects.length < count) throw '数据错误';
  102. return selects.slice(0, count);
  103. } else {
  104. return [select];
  105. }
  106. }
  107. /**
  108. * 获取节点数据
  109. * @param id
  110. * @returns {Promise<Array>}
  111. */
  112. async getDataById(id) {
  113. if (id instanceof Array) {
  114. return await this.db.select(this.tableName, { where: {id: id} });
  115. } else {
  116. return await this.db.get(this.tableName, { id: id });
  117. }
  118. }
  119. /**
  120. * 获取最末的子节点
  121. * @param {Number} mid - masterId
  122. * @param {Number} pid - 父节点id
  123. * @return {Object}
  124. */
  125. async getLastChildData(mid, pid) {
  126. this.initSqlBuilder();
  127. this.sqlBuilder.setAndWhere(this.setting.mid, {
  128. value: this.db.escape(mid),
  129. operate: '=',
  130. });
  131. this.sqlBuilder.setAndWhere(this.setting.pid, {
  132. value: pid,
  133. operate: '=',
  134. });
  135. this.sqlBuilder.orderBy = [[this.setting.order, 'DESC']];
  136. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  137. const resultData = await this.db.queryOne(sql, sqlParam);
  138. return resultData;
  139. }
  140. /**
  141. * 根据 父节点id 和 节点排序order 获取数据
  142. *
  143. * @param {Number} mid - master id
  144. * @param {Number} pid - 父节点id
  145. * @param {Number|Array} order - 排序
  146. * @return {Object|Array} - 查询结果
  147. */
  148. async getDataByParentAndOrder(mid, pid, order) {
  149. const result = await this.db.select(this.tableName, {
  150. where: this.getCondition({mid: mid, pid: pid, order: order})
  151. });
  152. return order instanceof Array ? result : (result.length > 0 ? result[0] : null);
  153. }
  154. async getChildBetween(mid, pid, order1, order2) {
  155. this.initSqlBuilder();
  156. this.sqlBuilder.setAndWhere(this.setting.mid, {
  157. value: this.db.escape(mid),
  158. operate: '=',
  159. });
  160. this.sqlBuilder.setAndWhere(this.setting.pid, {
  161. value: pid,
  162. operate: '=',
  163. });
  164. this.sqlBuilder.setAndWhere(this.setting.order, {
  165. value: order1,
  166. operate: '>',
  167. });
  168. this.sqlBuilder.setAndWhere(this.setting.order, {
  169. value: order2,
  170. operate: '<',
  171. });
  172. this.sqlBuilder.orderBy = [[this.setting.order, 'ASC']];
  173. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  174. const data = await this.db.query(sql, sqlParam);
  175. return data;
  176. }
  177. /**
  178. * 根据 父节点ID 和 节点排序order 获取全部后节点数据
  179. * @param {Number} mid - master id
  180. * @param {Number} pid - 父节点id
  181. * @param {Number} order - 排序
  182. * @return {Array}
  183. */
  184. async getNextsData(mid, pid, order) {
  185. this.initSqlBuilder();
  186. this.sqlBuilder.setAndWhere(this.setting.mid, {
  187. value: this.db.escape(mid),
  188. operate: '=',
  189. });
  190. this.sqlBuilder.setAndWhere(this.setting.pid, {
  191. value: pid,
  192. operate: '=',
  193. });
  194. this.sqlBuilder.setAndWhere(this.setting.order, {
  195. value: order,
  196. operate: '>',
  197. });
  198. this.sqlBuilder.orderBy = [[this.setting.order, 'ASC']];
  199. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  200. const data = await this.db.query(sql, sqlParam);
  201. return data;
  202. }
  203. /**
  204. * 根据fullPath获取数据 fullPath Like ‘1.2.3%’(传参fullPath = '1.2.3%')
  205. * @param {Number} tenderId - 标段id
  206. * @param {String} fullPath - 路径
  207. * @return {Promise<void>}
  208. */
  209. async getDataByFullPath(mid, fullPath) {
  210. this.initSqlBuilder();
  211. this.sqlBuilder.setAndWhere(this.setting.mid, {
  212. value: this.db.escape(mid),
  213. operate: '=',
  214. });
  215. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  216. value: this.db.escape(fullPath),
  217. operate: 'Like',
  218. });
  219. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  220. const resultData = await this.db.query(sql, sqlParam);
  221. return resultData;
  222. }
  223. /**
  224. * 根据fullPath检索自己及所有父项
  225. * @param {Number} tenderId - 标段id
  226. * @param {Array|String} fullPath - 节点完整路径
  227. * @return {Promise<*>}
  228. * @private
  229. */
  230. async getFullLevelDataByFullPath(mid, fullPath) {
  231. const explodePath = this.ctx.helper.explodePath(fullPath);
  232. this.initSqlBuilder();
  233. this.sqlBuilder.setAndWhere(this.setting.mid, {
  234. value: this.db.escape(mid),
  235. operate: '=',
  236. });
  237. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  238. value: explodePath,
  239. operate: 'in',
  240. });
  241. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  242. const data = await this.db.query(sql, sqlParam);
  243. return data;
  244. }
  245. /**
  246. * 根据 父节点id 获取子节点
  247. * @param tenderId
  248. * @param nodeId
  249. * @return {Promise<*>}
  250. */
  251. async getChildrenByParentId(mid, pid) {
  252. if (!mid || !pid) return undefined;
  253. const pids = pid instanceof Array ? pid : [pid];
  254. this.initSqlBuilder();
  255. this.sqlBuilder.setAndWhere(this.setting.mid, {
  256. value: this.db.escape(mid),
  257. operate: '=',
  258. });
  259. this.sqlBuilder.setAndWhere(this.setting.pid, {
  260. value: pids,
  261. operate: 'in',
  262. });
  263. this.sqlBuilder.orderBy = [[this.setting.order, 'ASC']];
  264. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  265. const data = await this.db.query(sql, sqlParam);
  266. return data;
  267. }
  268. /**
  269. * 根据 父节点id 获取孙子节点
  270. * @param tenderId
  271. * @param nodeId
  272. * @return {Promise<void>}
  273. */
  274. async getPosterityByParentId(mid, pid) {
  275. if (!mid || !pid) return undefined;
  276. const node = await this.getDataByKid(mid, pid);
  277. this.initSqlBuilder();
  278. this.sqlBuilder.setAndWhere(this.setting.mid, {
  279. value: this.db.escape(mid),
  280. operate: '=',
  281. });
  282. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  283. value: this.db.escape(node[this.setting.fullPath] + '-%'),
  284. operate: 'like',
  285. });
  286. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  287. const data = await this.db.query(sql, sqlParam);
  288. return data;
  289. }
  290. async getImportInfo(mid) {
  291. const maxId = await this._getMaxLid(mid);
  292. return { maxId };
  293. }
  294. /**
  295. * 获取最大节点id
  296. *
  297. * @param {Number} mid - master id
  298. * @return {Number}
  299. * @private
  300. */
  301. async _getMaxLid(mid) {
  302. const cacheKey = this.setting.keyPre + mid;
  303. let maxId = this.setting.cacheKey ? parseInt(await this.cache.get(cacheKey)) : undefined;
  304. if (!maxId) {
  305. const sql = 'SELECT Max(??) As max_id FROM ?? Where ' + this.setting.mid + ' = ?';
  306. const sqlParam = [this.setting.kid, this.tableName, mid];
  307. const queryResult = await this.db.queryOne(sql, sqlParam);
  308. maxId = queryResult.max_id || 0;
  309. if (this.setting.cacheKey) this.cache.set(cacheKey, maxId, 'EX', this.ctx.app.config.cacheTime);
  310. }
  311. return maxId;
  312. }
  313. /**
  314. * 缓存最大节点id
  315. *
  316. * @param {Number} mid - master id
  317. * @param {Number} maxId - 当前最大节点id
  318. * @returns {Promise<void>}
  319. * @private
  320. */
  321. _cacheMaxLid(mid, maxId) {
  322. this.cache.set(this.setting.keyPre + mid , maxId, 'EX', this.ctx.app.config.cacheTime);
  323. }
  324. /**
  325. * 移除最大节点id
  326. *
  327. * @param {Number} mid - master id
  328. * @return {Number}
  329. * @private
  330. */
  331. async _removeCacheMaxLid(mid) {
  332. return await this.cache.del(this.setting.keyPre + mid);
  333. }
  334. /**
  335. * 更新order
  336. * @param {Number} mid - master id
  337. * @param {Number} pid - 父节点id
  338. * @param {Number} order - 开始更新的order
  339. * @param {Number} incre - 更新的增量
  340. * @returns {Promise<*>}
  341. * @private
  342. */
  343. async _updateChildrenOrder(mid, pid, order, incre = 1) {
  344. this.initSqlBuilder();
  345. this.sqlBuilder.setAndWhere(this.setting.mid, {
  346. value: this.db.escape(mid),
  347. operate: '=',
  348. });
  349. this.sqlBuilder.setAndWhere(this.setting.order, {
  350. value: order,
  351. operate: '>=',
  352. });
  353. this.sqlBuilder.setAndWhere(this.setting.pid, {
  354. value: pid,
  355. operate: '=',
  356. });
  357. this.sqlBuilder.setUpdateData(this.setting.order, {
  358. value: Math.abs(incre),
  359. selfOperate: incre > 0 ? '+' : '-',
  360. });
  361. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  362. const data = await this.transaction.query(sql, sqlParam);
  363. return data;
  364. }
  365. /**
  366. * 新增数据(新增为selectData的后项,该方法不可单独使用)
  367. *
  368. * @param {Number} mid - 台账id
  369. * @param {Object} select - 选中节点的数据
  370. * @param {Object} data - 新增节点的初始数据
  371. * @return {Object} - 新增结果
  372. * @private
  373. */
  374. async _addNodeData(mid, select, data) {
  375. if (!data) {
  376. data = {};
  377. }
  378. const maxId = await this._getMaxLid(mid);
  379. if (this.setting.uuid) data.id = this.uuid.v4();
  380. data[this.setting.kid] = maxId + 1;
  381. data[this.setting.pid] = select ? select[this.setting.pid] : this.rootId;
  382. data[this.setting.mid] = mid;
  383. data[this.setting.level] = select ? select[this.setting.level] : 1;
  384. data[this.setting.order] = select ? select[this.setting.order] + 1 : 1;
  385. 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] + '';
  386. data[this.setting.isLeaf] = true;
  387. const result = await this.transaction.insert(this.tableName, data);
  388. this._cacheMaxLid(mid, maxId + 1);
  389. return result;
  390. }
  391. /**
  392. * 新增节点
  393. * @param {Number} mid - 台账id
  394. * @param {Number} kid - 清单节点id
  395. * @returns {Promise<void>}
  396. */
  397. async addNode(mid, kid, data) {
  398. if (!mid) return null;
  399. const select = kid ? await this.getDataByKid(mid, kid) : null;
  400. if (kid && !select) throw '新增节点数据错误';
  401. this.transaction = await this.db.beginTransaction();
  402. try {
  403. if (select) await this._updateChildrenOrder(mid, select[this.setting.pid], select[this.setting.order]+1);
  404. const newNode = await this._addNodeData(mid, select, data);
  405. if (newNode.affectedRows !== 1) throw '新增节点数据错误';
  406. await this.transaction.commit();
  407. this.transaction = null;
  408. } catch (err) {
  409. await this.transaction.rollback();
  410. this.transaction = null;
  411. throw err;
  412. }
  413. if (select) {
  414. const createData = await this.getDataByParentAndOrder(mid, select[this.setting.pid], [select[this.setting.order] + 1]);
  415. const updateData = await this.getNextsData(mid, select[this.setting.pid], select[this.setting.order] + 1);
  416. return {create: createData, update: updateData};
  417. } else {
  418. const createData = await this.getDataByParentAndOrder(mid, -1, [1]);
  419. return {create: createData};
  420. }
  421. }
  422. async addNodeBatch(mid, kid, data, count = 1) {
  423. if (!mid) return null;
  424. const select = kid ? await this.getDataByKid(mid, kid) : null;
  425. if (kid && !select) throw '新增节点数据错误';
  426. this.transaction = await this.db.beginTransaction();
  427. try {
  428. if (select) await this._updateChildrenOrder(mid, select[this.setting.pid], select[this.setting.order] + 1, count);
  429. const newDatas = [];
  430. const maxId = await this._getMaxLid(mid);
  431. for (let i = 1; i < count + 1; i++) {
  432. const newData = Object.assign({}, data);
  433. if (this.setting.uuid) newData.id = this.uuid.v4();
  434. newData[this.setting.kid] = maxId + i;
  435. newData[this.setting.pid] = select ? select[this.setting.pid] : this.rootId;
  436. newData[this.setting.mid] = mid;
  437. newData[this.setting.level] = select ? select[this.setting.level] : 1;
  438. newData[this.setting.order] = select ? select[this.setting.order] + i : i;
  439. newData[this.setting.fullPath] = newData[this.setting.level] > 1
  440. ? select[this.setting.fullPath].replace('-' + select[this.setting.kid], '-' + newData[this.setting.kid])
  441. : newData[this.setting.kid] + '';
  442. newData[this.setting.isLeaf] = true;
  443. newDatas.push(newData);
  444. }
  445. const insertResult = await this.transaction.insert(this.tableName, newDatas);
  446. this._cacheMaxLid(mid, maxId + count);
  447. if (insertResult.affectedRows !== count) throw '新增节点数据错误';
  448. await this.transaction.commit();
  449. this.transaction = null;
  450. } catch (err) {
  451. await this.transaction.rollback();
  452. this.transaction = null;
  453. throw err;
  454. }
  455. if (select) {
  456. const createData = await this.getChildBetween(mid, select[this.setting.pid], select[this.setting.order], select[this.setting.order] + count + 1);
  457. const updateData = await this.getNextsData(mid, select[this.setting.pid], select[this.setting.order] + count);
  458. return {create: createData, update: updateData};
  459. } else {
  460. const createData = await this.getChildBetween(mid, -1, 0, count + 1);
  461. return {create: createData};
  462. }
  463. }
  464. async addChildBatch(mid, kid, data, count = 1) {
  465. if (!mid || !kid) return null;
  466. const select = await this.getDataByKid(mid, kid);
  467. if (!select) throw '新增节点数据错误';
  468. const children = await this.getChildrenByParentId(mid, kid);
  469. const maxId = await this._getMaxLid(mid);
  470. this.transaction = await this.db.beginTransaction();
  471. try {
  472. const newDatas = [];
  473. for (let i = 1; i < count + 1; i++) {
  474. const newData = Object.assign({}, data);
  475. if (this.setting.uuid) newData.id = this.uuid.v4();
  476. newData[this.setting.kid] = maxId + i;
  477. newData[this.setting.pid] = select[this.setting.kid];
  478. newData[this.setting.mid] = mid;
  479. newData[this.setting.level] = select[this.setting.level] + 1;
  480. newData[this.setting.order] = children.length > 0 ? children[children.length - 1].order + i : i;
  481. newData[this.setting.fullPath] = select[this.setting.fullPath] + '-' + newData[this.setting.kid];
  482. newData[this.setting.isLeaf] = true;
  483. newDatas.push(newData);
  484. }
  485. const insertResult = await this.transaction.insert(this.tableName, newDatas);
  486. this._cacheMaxLid(mid, maxId + count);
  487. if (select[this.setting.isLeaf] || children.length === 0) {
  488. const updateData = { id: select.id };
  489. updateData[this.setting.isLeaf] = false;
  490. this.clearParentingData(updateData);
  491. await this.transaction.update(this.tableName, updateData);
  492. }
  493. if (insertResult.affectedRows !== count) throw '新增节点数据错误';
  494. await this.transaction.commit();
  495. this.transaction = null;
  496. } catch (err) {
  497. await this.transaction.rollback();
  498. this.transaction = null;
  499. throw err;
  500. }
  501. if (select[this.setting.isLeaf] || children.length === 0) {
  502. const createData = await this.getDataByKidAndCount(mid, maxId + 1, count);
  503. const updateData = await this.getDataByKid(mid, select[this.setting.id]);
  504. return {create: createData, update: updateData};
  505. } else {
  506. const createData = await this.getDataByKidAndCount(mid, maxId + 1, count);
  507. return {create: createData};
  508. }
  509. }
  510. /**
  511. * 删除相关数据 用于继承
  512. * @param mid
  513. * @param deleteData
  514. * @returns {Promise<void>}
  515. * @private
  516. */
  517. async _deleteRelaData(mid, deleteData) {
  518. }
  519. /**
  520. * 删除节点
  521. * @param {Number} tenderId - 标段id
  522. * @param {Object} deleteData - 删除节点数据
  523. * @return {Promise<*>}
  524. * @private
  525. */
  526. async _deletePosterity(mid, node) {
  527. this.initSqlBuilder();
  528. this.sqlBuilder.setAndWhere(this.setting.mid, {
  529. value: this.db.escape(mid),
  530. operate: '=',
  531. });
  532. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  533. value: this.db.escape(node[this.setting.fullPath] + '-%'),
  534. operate: 'Like',
  535. });
  536. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'delete');
  537. const result = await this.transaction.query(sql, sqlParam);
  538. return result;
  539. }
  540. /**
  541. * tenderId标段中, 删除选中节点及其子节点
  542. *
  543. * @param {Number} tenderId - 标段id
  544. * @param {Number} selectId - 选中节点id
  545. * @return {Array} - 被删除的数据
  546. */
  547. async deleteNode(mid, kid) {
  548. if (!mid || (kid <= 0)) return [];
  549. const select = await this.getDataByKid(mid, kid);
  550. if (!select) throw '删除节点数据错误';
  551. const parent = await this.getDataByKid(mid, select[this.setting.pid]);
  552. // 获取将要被删除的数据
  553. const deleteData = await this.getDataByFullPath(mid, select[this.setting.fullPath] + '-%');
  554. deleteData.unshift(select);
  555. if (deleteData.length === 0) throw '删除节点数据错误';
  556. this.transaction = await this.db.beginTransaction();
  557. try {
  558. // 删除
  559. await this.transaction.delete(this.tableName, { id: select.id });
  560. const operate = await this._deletePosterity(mid, select);
  561. // 选中节点--父节点 只有一个子节点时,应升级isLeaf
  562. if (parent) {
  563. const count = await this.db.count(this.tableName, this.getCondition({mid: mid, pid: select[this.setting.pid]}));
  564. if (count === 1) {
  565. const updateParent = {id: parent.id };
  566. updateParent[this.setting.isLeaf] = true;
  567. await this.transaction.update(this.tableName, updateParent);
  568. }
  569. }
  570. // 选中节点--全部后节点 order--
  571. await this._updateChildrenOrder(mid, select[this.setting.pid], select[this.setting.order] + 1, -1);
  572. // 删除部位明细
  573. await this._deleteRelaData(mid, deleteData);
  574. await this.transaction.commit();
  575. this.transaction = null;
  576. } catch (err) {
  577. await this.transaction.rollback();
  578. this.transaction = null;
  579. throw err;
  580. }
  581. // 查询结果
  582. const updateData = await this.getNextsData(mid, select[this.setting.pid], select[this.setting.order] - 1);
  583. if (parent) {
  584. const updateData1 = await this.getDataByKid(mid, select[this.setting.pid]);
  585. if (updateData1[this.setting.isLeaf]) {
  586. updateData.push(updateData1);
  587. }
  588. }
  589. return { delete: deleteData, update: updateData };
  590. }
  591. async deleteNodes(mid, kid, count) {
  592. if (!mid || (kid <= 0) || (count <= 0)) return [];
  593. const selects = await this.getDataByKidAndCount(mid, kid, count);
  594. const first = selects[0];
  595. const parent = await this.getDataByKid(mid, first[this.setting.pid]);
  596. const childCount = parent ? await this.count(this.getCondition({mid: mid, pid: parent[this.setting.kid]})) : -1;
  597. let deleteData = [];
  598. for (const s of selects) {
  599. deleteData = deleteData.concat(await this.getDataByFullPath(mid, s[this.setting.fullPath] + '-%'));
  600. deleteData.push(s);
  601. }
  602. this.transaction = await this.db.beginTransaction();
  603. try {
  604. // 删除
  605. await this.transaction.delete(this.tableName, { id: selects.map(x => { return x.id }) });
  606. for (const s of selects) {
  607. const operate = await this._deletePosterity(mid, s);
  608. }
  609. // 选中节点--父节点 只有一个子节点时,应升级isLeaf
  610. if (parent && childCount === count) {
  611. const updateParent = {id: parent.id };
  612. updateParent[this.setting.isLeaf] = true;
  613. await this.transaction.update(this.tableName, updateParent);
  614. }
  615. // 选中节点--全部后节点 order--
  616. await this._updateChildrenOrder(mid, first[this.setting.pid], first[this.setting.order] + count, -count);
  617. await this.transaction.commit();
  618. this.transaction = null;
  619. const updateData = await this.getNextsData(mid, first[this.setting.pid], first[this.setting.order] - 1);
  620. if (parent && childCount === count) {
  621. const updateData1 = await this.getDataByKid(mid, parent[this.setting.kid]);
  622. updateData.push(updateData1);
  623. }
  624. return { delete: deleteData, update: updateData };
  625. } catch (err) {
  626. if (this.transaction) {
  627. await this.transaction.rollback();
  628. this.transaction = null;
  629. }
  630. throw err;
  631. }
  632. }
  633. async delete(mid, kid, count) {
  634. if (count && count > 1) {
  635. return await this.deleteNodes(mid, kid, count);
  636. } else {
  637. return await this.deleteNode(mid, kid);
  638. }
  639. }
  640. /**
  641. * 上移节点
  642. *
  643. * @param {Number} mid - master id
  644. * @param {Number} kid - 选中节点id
  645. * @return {Array} - 发生改变的数据
  646. */
  647. async upMoveNode(mid, kid, count) {
  648. if (!count) count = 1;
  649. if (!mid || !kid || (kid <= 0)) return null;
  650. const selects = await this.getDataByKidAndCount(mid, kid, count);
  651. if (selects.length !== count) throw '上移节点数据错误';
  652. const first = selects[0];
  653. const pre = await this.getDataByParentAndOrder(mid, first[this.setting.pid], first[this.setting.order] - 1);
  654. if (!pre) throw '节点不可上移';
  655. const order = [];
  656. this.transaction = await this.db.beginTransaction();
  657. try {
  658. for (const s of selects) {
  659. const sData = { id: s.id };
  660. sData[this.setting.order] = s[this.setting.order] - 1;
  661. await this.transaction.update(this.tableName, sData);
  662. order.push(s[this.setting.order] - 1);
  663. }
  664. const pData = { id: pre.id };
  665. pData[this.setting.order] = pre[this.setting.order] + count;
  666. await this.transaction.update(this.tableName, pData);
  667. order.push(pre[this.setting.order] + count);
  668. await this.transaction.commit();
  669. this.transaction = null;
  670. } catch (err) {
  671. await this.transaction.rollback();
  672. this.transaction = null;
  673. throw err;
  674. }
  675. const resultData = await this.getDataByParentAndOrder(mid, first[this.setting.pid], order);
  676. return { update: resultData };
  677. }
  678. /**
  679. * 下移节点
  680. *
  681. * @param {Number} mid - master id
  682. * @param {Number} kid - 选中节点id
  683. * @return {Array} - 发生改变的数据
  684. */
  685. async downMoveNode(mid, kid, count) {
  686. if (!count) count = 1;
  687. if (!mid || !kid || (kid <= 0)) return null;
  688. const selects = await this.getDataByKidAndCount(mid, kid, count);
  689. if (selects.length !== count) {
  690. throw '下移节点数据错误';
  691. }
  692. const last = selects[count - 1];
  693. const next = await this.getDataByParentAndOrder(mid, last[this.setting.pid], last[this.setting.order] + 1);
  694. if (!next) {
  695. throw '节点不可下移';
  696. }
  697. const order = [];
  698. this.transaction = await this.db.beginTransaction();
  699. try {
  700. for (const s of selects) {
  701. const sData = { id: s.id };
  702. sData[this.setting.order] = s[this.setting.order] + 1;
  703. await this.transaction.update(this.tableName, sData);
  704. order.push(s[this.setting.order] + 1);
  705. }
  706. const nData = { id: next.id };
  707. nData[this.setting.order] = next[this.setting.order] - count;
  708. await this.transaction.update(this.tableName, nData);
  709. order.push(next[this.setting.order] - count);
  710. await this.transaction.commit();
  711. this.transaction = null;
  712. } catch (err) {
  713. await this.transaction.rollback();
  714. this.transaction = null;
  715. throw err;
  716. }
  717. const resultData = await this.getDataByParentAndOrder(mid, last[this.setting.pid], order);
  718. return { update: resultData };
  719. }
  720. /**
  721. * 节点成为父项时,可能需要修改父项数据,供子类继承
  722. * @param data
  723. */
  724. clearParentingData (data) {
  725. }
  726. /**
  727. * 升级selectData, 同步修改所有子节点
  728. * @param {Object} selectData - 升级操作,选中节点
  729. * @return {Object}
  730. * @private
  731. */
  732. async _syncUplevelChildren(select) {
  733. this.initSqlBuilder();
  734. this.sqlBuilder.setAndWhere(this.setting.mid, {
  735. value: this.db.escape(select[this.setting.mid]),
  736. operate: '=',
  737. });
  738. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  739. value: this.db.escape(select[this.setting.fullPath] + '-%'),
  740. operate: 'like',
  741. });
  742. this.sqlBuilder.setUpdateData(this.setting.level, {
  743. value: 1,
  744. selfOperate: '-',
  745. });
  746. this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  747. value: [this.setting.fullPath, this.db.escape(`-${select[this.setting.pid]}-`), this.db.escape('-')],
  748. literal: 'Replace',
  749. });
  750. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  751. const data = await this.transaction.query(sql, sqlParam);
  752. return data;
  753. }
  754. /**
  755. * 选中节点的后兄弟节点,全部变为当前节点的子节点
  756. * @param {Object} selectData - 选中节点
  757. * @return {Object}
  758. * @private
  759. */
  760. async _syncUpLevelNexts(select) {
  761. // 查询selectData的lastChild
  762. const lastChild = await this.getLastChildData(select[this.setting.mid], select[this.setting.kid]);
  763. const nexts = await this.getNextsData(select[this.setting.mid], select[this.setting.pid], select[this.setting.order]);
  764. if (nexts && nexts.length > 0) {
  765. // 修改nextsData pid, 排序
  766. this.initSqlBuilder();
  767. this.sqlBuilder.setUpdateData(this.setting.pid, {
  768. value: select[this.setting.kid],
  769. });
  770. const orderInc = lastChild ? lastChild[this.setting.order] - select[this.setting.order] : - select[this.setting.order];
  771. this.sqlBuilder.setUpdateData(this.setting.order, {
  772. value: Math.abs(orderInc),
  773. selfOperate: orderInc > 0 ? '+' : '-',
  774. });
  775. this.sqlBuilder.setAndWhere(this.setting.mid, {
  776. value: this.db.escape(select[this.setting.mid]),
  777. operate: '=',
  778. });
  779. this.sqlBuilder.setAndWhere(this.setting.pid, {
  780. value: select[this.setting.pid],
  781. operate: '=',
  782. });
  783. this.sqlBuilder.setAndWhere(this.setting.order, {
  784. value: select[this.setting.order],
  785. operate: '>',
  786. });
  787. const [sql1, sqlParam1] = this.sqlBuilder.build(this.tableName, 'update');
  788. await this.transaction.query(sql1, sqlParam1);
  789. // 选中节点 isLeaf应为false
  790. if (select[this.setting.isLeaf]) {
  791. const updateData = { id: select.id };
  792. updateData[this.setting.isLeaf] = false;
  793. await this.transaction.update(this.tableName, updateData);
  794. }
  795. // 修改nextsData及其子节点的fullPath
  796. const oldSubStr = this.db.escape(select[this.setting.pid] + '-');
  797. const newSubStr = this.db.escape(select[this.setting.kid] + '-');
  798. const sqlArr = [];
  799. sqlArr.push('Update ?? SET `' + this.setting.fullPath + '` = Replace(`' + this.setting.fullPath + '`,' + oldSubStr + ',' + newSubStr + ') Where');
  800. sqlArr.push('(`' + this.setting.mid + '` = ' + this.db.escape(select[this.setting.mid]) + ')');
  801. sqlArr.push(' And (');
  802. for (const data of nexts) {
  803. sqlArr.push('`' + this.setting.fullPath + '` Like ' + this.db.escape(data[this.setting.fullPath] + '%'));
  804. if (nexts.indexOf(data) < nexts.length - 1) {
  805. sqlArr.push(' Or ');
  806. }
  807. }
  808. sqlArr.push(')');
  809. const sql = sqlArr.join('');
  810. const resultData = await this.transaction.query(sql, [this.tableName]);
  811. return resultData;
  812. }
  813. }
  814. /**
  815. * 升级节点
  816. *
  817. * @param {Number} tenderId - 标段id
  818. * @param {Number} selectId - 选中节点id
  819. * @return {Array} - 发生改变的数据
  820. */
  821. async upLevelNode(mid, kid, count) {
  822. if (!count) count = 1;
  823. const selects = await this.getDataByKidAndCount(mid, kid, count);
  824. if (selects.length !== count) throw '升级节点数据错误';
  825. const first = selects[0], last = selects[count - 1];
  826. const parent = await this.getDataByKid(mid, first[this.setting.pid]);
  827. if (!parent) throw '升级节点数据错误';
  828. const newPath = [];
  829. this.transaction = await this.db.beginTransaction();
  830. try {
  831. // 选中节点--父节点 选中节点为firstChild时,修改isLeaf
  832. if (first[this.setting.order] === 1) {
  833. const updateParentData = { id: parent.id };
  834. updateParentData[this.setting.isLeaf] = true;
  835. await this.transaction.update(this.tableName, updateParentData);
  836. }
  837. // 选中节点--父节点--全部后兄弟节点 order+1
  838. await this._updateChildrenOrder(mid, parent[this.setting.pid], parent[this.setting.order] + 1, count);
  839. for (const [i, s] of selects.entries()) {
  840. // 选中节点 修改pid, order, fullPath, level, isLeaf, 清空计算项
  841. const updateData = { id: s.id };
  842. updateData[this.setting.pid] = parent[this.setting.pid];
  843. updateData[this.setting.order] = parent[this.setting.order] + i + 1;
  844. updateData[this.setting.level] = s[this.setting.level] - 1;
  845. updateData[this.setting.fullPath] = s[this.setting.fullPath].replace(`-${s[this.setting.pid]}-`, '-');
  846. newPath.push(updateData[this.setting.fullPath]);
  847. if (s[this.setting.isLeaf] && s.id === last.id) {
  848. const nexts = await this.getNextsData(mid, parent[this.setting.kid], last[this.setting.order]);
  849. if (nexts.length > 0) {
  850. updateData[this.setting.isLeaf] = false;
  851. this.clearParentingData(updateData);
  852. }
  853. }
  854. await this.transaction.update(this.tableName, updateData);
  855. // 选中节点--全部子节点(含孙) level-1, fullPath变更
  856. await this._syncUplevelChildren(s);
  857. }
  858. // 选中节点--全部后兄弟节点 收编为子节点 修改pid, order, fullPath
  859. await this._syncUpLevelNexts(last);
  860. await this.transaction.commit();
  861. this.transaction = null;
  862. } catch (err) {
  863. await this.transaction.rollback();
  864. this.transaction = null;
  865. throw err;
  866. }
  867. // 查询修改的数据
  868. let updateData = await this.getNextsData(mid, parent[this.setting.pid], parent[this.setting.order] - 1);
  869. for (const path of newPath) {
  870. const children = await this.getDataByFullPath(mid, path + '-%');
  871. updateData = updateData.concat(children);
  872. }
  873. return { update: updateData };
  874. }
  875. /**
  876. * 降级selectData, 同步修改所有子节点
  877. * @param {Object} selectData - 选中节点
  878. * @param {Object} preData - 选中节点的前一节点(降级后为父节点)
  879. * @return {Promise<*>}
  880. * @private
  881. */
  882. async _syncDownlevelChildren(select, newFullPath) {
  883. this.initSqlBuilder();
  884. this.sqlBuilder.setAndWhere(this.setting.mid, {
  885. value: this.db.escape(select[this.setting.mid]),
  886. operate: '=',
  887. });
  888. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  889. value: this.db.escape(select[this.setting.fullPath] + '-%'),
  890. operate: 'like',
  891. });
  892. this.sqlBuilder.setUpdateData(this.setting.level, {
  893. value: 1,
  894. selfOperate: '+',
  895. });
  896. this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  897. value: [this.setting.fullPath, this.db.escape(select[this.setting.fullPath] + '-'), this.db.escape(newFullPath + '-')],
  898. literal: 'Replace',
  899. });
  900. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  901. const data = await this.transaction.query(sql, sqlParam);
  902. return data;
  903. }
  904. /**
  905. * 降级节点
  906. *
  907. * @param {Number} tenderId - 标段id
  908. * @param {Number} selectId - 选中节点id
  909. * @return {Array} - 发生改变的数据
  910. */
  911. async downLevelNode(mid, kid, count) {
  912. if (!count) count = 1;
  913. const selects = await this.getDataByKidAndCount(mid, kid, count);
  914. if (!selects) throw '降级节点数据错误';
  915. const first = selects[0], last = selects[count - 1];
  916. const pre = await this.getDataByParentAndOrder(mid, first[this.setting.pid], first[this.setting.order] - 1);
  917. if (!pre) throw '节点不可降级';
  918. const preLastChild = await this.getLastChildData(mid, pre[this.setting.kid]);
  919. const newPath = [];
  920. this.transaction = await this.db.beginTransaction();
  921. try {
  922. // 选中节点--全部后节点 order--
  923. await this._updateChildrenOrder(mid, first[this.setting.pid], last[this.setting.order] + 1, -count);
  924. for (const [i, s] of selects.entries()) {
  925. // 选中节点 修改pid, level, order, fullPath
  926. const updateData = { id: s.id };
  927. updateData[this.setting.pid] = pre[this.setting.kid];
  928. updateData[this.setting.order] = preLastChild ? preLastChild[this.setting.order] + i + 1 : i + 1;
  929. updateData[this.setting.level] = s[this.setting.level] + 1;
  930. if (s[this.setting.level] === 1) {
  931. updateData[this.setting.fullPath] = pre[this.setting.kid] + '-' + s[this.setting.kid];
  932. } else {
  933. const index = s[this.setting.fullPath].lastIndexOf(s[this.setting.kid]);
  934. updateData[this.setting.fullPath] = s[this.setting.fullPath].substring(0, index-1) + '-' + pre[this.setting.kid] + '-' + s[this.setting.kid];
  935. }
  936. newPath.push(updateData[this.setting.fullPath]);
  937. await this.transaction.update(this.tableName, updateData);
  938. // 选中节点--全部子节点(含孙) level++, fullPath
  939. await this._syncDownlevelChildren(s, updateData[this.setting.fullPath]);
  940. }
  941. // 选中节点--前兄弟节点 isLeaf应为false, 清空计算相关字段
  942. const updateData2 = { id: pre.id };
  943. updateData2[this.setting.isLeaf] = false;
  944. this.clearParentingData(updateData2);
  945. await this.transaction.update(this.tableName, updateData2);
  946. await this.transaction.commit();
  947. this.transaction = null;
  948. } catch (err) {
  949. await this.transaction.rollback();
  950. this.transaction = null;
  951. throw err;
  952. }
  953. // 查询修改的数据
  954. let updateData = await this.getNextsData(mid, pre[this.setting.pid], pre[this.setting.order] - 1);
  955. // 选中节点及子节点
  956. for (const p of newPath) {
  957. updateData = updateData.concat(await this.getDataByFullPath(mid, p + '-%'));
  958. }
  959. updateData = updateData.concat(await this.getDataById(selects.map(x => { return x.id; })));
  960. // 选中节点--原前兄弟节点&全部后兄弟节点
  961. return { update: updateData };
  962. }
  963. /**
  964. * 过滤data中update方式不可提交的字段
  965. * @param {Number} id - 主键key
  966. * @param {Object} data
  967. * @return {Object<{id: *}>}
  968. * @private
  969. */
  970. _filterUpdateInvalidField(id, data) {
  971. const result = {id: id};
  972. for (const prop in data) {
  973. if (this.readOnlyFields.indexOf(prop) === -1) {
  974. result[prop] = data[prop];
  975. }
  976. }
  977. return result;
  978. }
  979. /**
  980. * 提交多条数据 - 不影响计算等未提交项
  981. * @param {Number} tenderId - 标段id
  982. * @param {Array} datas - 提交数据
  983. * @return {Array} - 提交后的数据
  984. */
  985. async updateInfos(mid, datas) {
  986. if (!mid) throw '数据错误';
  987. if (Array.isArray(datas)) {
  988. const updateDatas = [];
  989. for (const d of datas) {
  990. if (mid !== d[this.setting.mid]) throw '提交数据错误';
  991. const node = await this.getDataById(d.id);
  992. if (!node || mid !== node[this.setting.mid] || d[this.setting.kid] !== node[this.setting.kid]) throw '提交数据错误';
  993. updateDatas.push(this._filterUpdateInvalidField(node.id, d));
  994. }
  995. await this.db.updateRows(this.tableName, updateDatas);
  996. const resultData = await this.getDataById(this._.map(datas, 'id'));
  997. return resultData;
  998. } else {
  999. if (mid !== datas[this.setting.mid]) throw '提交数据错误';
  1000. const node = await this.getDataById(datas.id);
  1001. if (!node || mid !== node[this.setting.mid] || datas[this.setting.kid] !== node[this.setting.kid]) throw '提交数据错误';
  1002. const updateData = this._filterUpdateInvalidField(node.id, datas);
  1003. await this.db.update(this.tableName, updateData);
  1004. return await this.getDataById(datas.id);
  1005. }
  1006. }
  1007. }
  1008. module.exports = TreeService;