base_tree_service.js 38 KB

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