base_tree_service.js 39 KB

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