base_tree_service.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  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. /**
  465. * 删除相关数据 用于继承
  466. * @param mid
  467. * @param deleteData
  468. * @returns {Promise<void>}
  469. * @private
  470. */
  471. async _deleteRelaData(mid, deleteData) {
  472. }
  473. /**
  474. * 删除节点
  475. * @param {Number} tenderId - 标段id
  476. * @param {Object} deleteData - 删除节点数据
  477. * @return {Promise<*>}
  478. * @private
  479. */
  480. async _deletePosterity(mid, node) {
  481. this.initSqlBuilder();
  482. this.sqlBuilder.setAndWhere(this.setting.mid, {
  483. value: this.db.escape(mid),
  484. operate: '=',
  485. });
  486. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  487. value: this.db.escape(node[this.setting.fullPath] + '-%'),
  488. operate: 'Like',
  489. });
  490. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'delete');
  491. const result = await this.transaction.query(sql, sqlParam);
  492. return result;
  493. }
  494. /**
  495. * tenderId标段中, 删除选中节点及其子节点
  496. *
  497. * @param {Number} tenderId - 标段id
  498. * @param {Number} selectId - 选中节点id
  499. * @return {Array} - 被删除的数据
  500. */
  501. async deleteNode(mid, kid) {
  502. if (!mid || (kid <= 0)) return [];
  503. const select = await this.getDataByKid(mid, kid);
  504. if (!select) throw '删除节点数据错误';
  505. const parent = await this.getDataByKid(mid, select[this.setting.pid]);
  506. // 获取将要被删除的数据
  507. const deleteData = await this.getDataByFullPath(mid, select[this.setting.fullPath] + '-%');
  508. deleteData.unshift(select);
  509. if (deleteData.length === 0) throw '删除节点数据错误';
  510. this.transaction = await this.db.beginTransaction();
  511. try {
  512. // 删除
  513. await this.transaction.delete(this.tableName, { id: select.id });
  514. const operate = await this._deletePosterity(mid, select);
  515. // 选中节点--父节点 只有一个子节点时,应升级isLeaf
  516. if (parent) {
  517. const count = await this.db.count(this.tableName, this.getCondition({mid: mid, pid: select[this.setting.pid]}));
  518. if (count === 1) {
  519. const updateParent = {id: parent.id };
  520. updateParent[this.setting.isLeaf] = true;
  521. await this.transaction.update(this.tableName, updateParent);
  522. }
  523. }
  524. // 选中节点--全部后节点 order--
  525. await this._updateChildrenOrder(mid, select[this.setting.pid], select[this.setting.order] + 1, -1);
  526. // 删除部位明细
  527. await this._deleteRelaData(mid, deleteData);
  528. await this.transaction.commit();
  529. this.transaction = null;
  530. } catch (err) {
  531. await this.transaction.rollback();
  532. this.transaction = null;
  533. throw err;
  534. }
  535. // 查询结果
  536. const updateData = await this.getNextsData(mid, select[this.setting.pid], select[this.setting.order] - 1);
  537. if (parent) {
  538. const updateData1 = await this.getDataByKid(mid, select[this.setting.pid]);
  539. if (updateData1[this.setting.isLeaf]) {
  540. updateData.push(updateData1);
  541. }
  542. }
  543. return { delete: deleteData, update: updateData };
  544. }
  545. async deleteNodes(mid, kid, count) {
  546. if (!mid || (kid <= 0) || (count <= 0)) return [];
  547. const selects = await this.getDataByKidAndCount(mid, kid, count);
  548. const first = selects[0];
  549. const parent = await this.getDataByKid(mid, first[this.setting.pid]);
  550. const childCount = parent ? await this.count(this.getCondition({mid: mid, pid: parent[this.setting.kid]})) : -1;
  551. let deleteData = [];
  552. for (const s of selects) {
  553. deleteData = deleteData.concat(await this.getDataByFullPath(mid, s[this.setting.fullPath] + '-%'));
  554. deleteData.push(s);
  555. }
  556. this.transaction = await this.db.beginTransaction();
  557. try {
  558. // 删除
  559. await this.transaction.delete(this.tableName, { id: selects.map(x => { return x.id }) });
  560. for (const s of selects) {
  561. const operate = await this._deletePosterity(mid, s);
  562. }
  563. // 选中节点--父节点 只有一个子节点时,应升级isLeaf
  564. if (parent && childCount === count) {
  565. const updateParent = {id: parent.id };
  566. updateParent[this.setting.isLeaf] = true;
  567. await this.transaction.update(this.tableName, updateParent);
  568. }
  569. // 选中节点--全部后节点 order--
  570. await this._updateChildrenOrder(mid, first[this.setting.pid], first[this.setting.order] + count, -count);
  571. await this.transaction.commit();
  572. this.transaction = null;
  573. const updateData = await this.getNextsData(mid, first[this.setting.pid], first[this.setting.order] - 1);
  574. if (parent && childCount === count) {
  575. const updateData1 = await this.getDataByKid(mid, parent[this.setting.kid]);
  576. updateData.push(updateData1);
  577. }
  578. return { delete: deleteData, update: updateData };
  579. } catch (err) {
  580. if (this.transaction) {
  581. await this.transaction.rollback();
  582. this.transaction = null;
  583. }
  584. throw err;
  585. }
  586. }
  587. async delete(mid, kid, count) {
  588. if (count && count > 1) {
  589. return await this.deleteNodes(mid, kid, count);
  590. } else {
  591. return await this.deleteNode(mid, kid);
  592. }
  593. }
  594. /**
  595. * 上移节点
  596. *
  597. * @param {Number} mid - master id
  598. * @param {Number} kid - 选中节点id
  599. * @return {Array} - 发生改变的数据
  600. */
  601. async upMoveNode(mid, kid, count) {
  602. if (!count) count = 1;
  603. if (!mid || !kid || (kid <= 0)) return null;
  604. const selects = await this.getDataByKidAndCount(mid, kid, count);
  605. if (selects.length !== count) throw '上移节点数据错误';
  606. const first = selects[0];
  607. const pre = await this.getDataByParentAndOrder(mid, first[this.setting.pid], first[this.setting.order] - 1);
  608. if (!pre) throw '节点不可上移';
  609. const order = [];
  610. this.transaction = await this.db.beginTransaction();
  611. try {
  612. for (const s of selects) {
  613. const sData = { id: s.id };
  614. sData[this.setting.order] = s[this.setting.order] - 1;
  615. await this.transaction.update(this.tableName, sData);
  616. order.push(s[this.setting.order] - 1);
  617. }
  618. const pData = { id: pre.id };
  619. pData[this.setting.order] = pre[this.setting.order] + count;
  620. await this.transaction.update(this.tableName, pData);
  621. order.push(pre[this.setting.order] + count);
  622. await this.transaction.commit();
  623. this.transaction = null;
  624. } catch (err) {
  625. await this.transaction.rollback();
  626. this.transaction = null;
  627. throw err;
  628. }
  629. const resultData = await this.getDataByParentAndOrder(mid, first[this.setting.pid], order);
  630. return { update: resultData };
  631. }
  632. /**
  633. * 下移节点
  634. *
  635. * @param {Number} mid - master id
  636. * @param {Number} kid - 选中节点id
  637. * @return {Array} - 发生改变的数据
  638. */
  639. async downMoveNode(mid, kid, count) {
  640. if (!count) count = 1;
  641. if (!mid || !kid || (kid <= 0)) return null;
  642. const selects = await this.getDataByKidAndCount(mid, kid, count);
  643. if (selects.length !== count) {
  644. throw '下移节点数据错误';
  645. }
  646. const last = selects[count - 1];
  647. const next = await this.getDataByParentAndOrder(mid, last[this.setting.pid], last[this.setting.order] + 1);
  648. if (!next) {
  649. throw '节点不可下移';
  650. }
  651. const order = [];
  652. this.transaction = await this.db.beginTransaction();
  653. try {
  654. for (const s of selects) {
  655. const sData = { id: s.id };
  656. sData[this.setting.order] = s[this.setting.order] + 1;
  657. await this.transaction.update(this.tableName, sData);
  658. order.push(s[this.setting.order] + 1);
  659. }
  660. const nData = { id: next.id };
  661. nData[this.setting.order] = next[this.setting.order] - count;
  662. await this.transaction.update(this.tableName, nData);
  663. order.push(next[this.setting.order] - count);
  664. await this.transaction.commit();
  665. this.transaction = null;
  666. } catch (err) {
  667. await this.transaction.rollback();
  668. this.transaction = null;
  669. throw err;
  670. }
  671. const resultData = await this.getDataByParentAndOrder(mid, last[this.setting.pid], order);
  672. return { update: resultData };
  673. }
  674. /**
  675. * 节点成为父项时,可能需要修改父项数据,供子类继承
  676. * @param data
  677. */
  678. clearParentingData (data) {
  679. }
  680. /**
  681. * 升级selectData, 同步修改所有子节点
  682. * @param {Object} selectData - 升级操作,选中节点
  683. * @return {Object}
  684. * @private
  685. */
  686. async _syncUplevelChildren(select) {
  687. this.initSqlBuilder();
  688. this.sqlBuilder.setAndWhere(this.setting.mid, {
  689. value: this.db.escape(select[this.setting.mid]),
  690. operate: '=',
  691. });
  692. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  693. value: this.db.escape(select[this.setting.fullPath] + '-%'),
  694. operate: 'like',
  695. });
  696. this.sqlBuilder.setUpdateData(this.setting.level, {
  697. value: 1,
  698. selfOperate: '-',
  699. });
  700. this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  701. value: [this.setting.fullPath, this.db.escape(`-${select[this.setting.pid]}-`), this.db.escape('-')],
  702. literal: 'Replace',
  703. });
  704. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  705. const data = await this.transaction.query(sql, sqlParam);
  706. return data;
  707. }
  708. /**
  709. * 选中节点的后兄弟节点,全部变为当前节点的子节点
  710. * @param {Object} selectData - 选中节点
  711. * @return {Object}
  712. * @private
  713. */
  714. async _syncUpLevelNexts(select) {
  715. // 查询selectData的lastChild
  716. const lastChild = await this.getLastChildData(select[this.setting.mid], select[this.setting.kid]);
  717. const nexts = await this.getNextsData(select[this.setting.mid], select[this.setting.pid], select[this.setting.order]);
  718. if (nexts && nexts.length > 0) {
  719. // 修改nextsData pid, 排序
  720. this.initSqlBuilder();
  721. this.sqlBuilder.setUpdateData(this.setting.pid, {
  722. value: select[this.setting.kid],
  723. });
  724. const orderInc = lastChild ? lastChild[this.setting.order] - select[this.setting.order] : - select[this.setting.order];
  725. this.sqlBuilder.setUpdateData(this.setting.order, {
  726. value: Math.abs(orderInc),
  727. selfOperate: orderInc > 0 ? '+' : '-',
  728. });
  729. this.sqlBuilder.setAndWhere(this.setting.mid, {
  730. value: this.db.escape(select[this.setting.mid]),
  731. operate: '=',
  732. });
  733. this.sqlBuilder.setAndWhere(this.setting.pid, {
  734. value: select[this.setting.pid],
  735. operate: '=',
  736. });
  737. this.sqlBuilder.setAndWhere(this.setting.order, {
  738. value: select[this.setting.order],
  739. operate: '>',
  740. });
  741. const [sql1, sqlParam1] = this.sqlBuilder.build(this.tableName, 'update');
  742. await this.transaction.query(sql1, sqlParam1);
  743. // 选中节点 isLeaf应为false
  744. if (select[this.setting.isLeaf]) {
  745. const updateData = { id: select.id };
  746. updateData[this.setting.isLeaf] = false;
  747. await this.transaction.update(this.tableName, updateData);
  748. }
  749. // 修改nextsData及其子节点的fullPath
  750. const oldSubStr = this.db.escape(select[this.setting.pid] + '-');
  751. const newSubStr = this.db.escape(select[this.setting.kid] + '-');
  752. const sqlArr = [];
  753. sqlArr.push('Update ?? SET `' + this.setting.fullPath + '` = Replace(`' + this.setting.fullPath + '`,' + oldSubStr + ',' + newSubStr + ') Where');
  754. sqlArr.push('(`' + this.setting.mid + '` = ' + this.db.escape(select[this.setting.mid]) + ')');
  755. sqlArr.push(' And (');
  756. for (const data of nexts) {
  757. sqlArr.push('`' + this.setting.fullPath + '` Like ' + this.db.escape(data[this.setting.fullPath] + '%'));
  758. if (nexts.indexOf(data) < nexts.length - 1) {
  759. sqlArr.push(' Or ');
  760. }
  761. }
  762. sqlArr.push(')');
  763. const sql = sqlArr.join('');
  764. const resultData = await this.transaction.query(sql, [this.tableName]);
  765. return resultData;
  766. }
  767. }
  768. /**
  769. * 升级节点
  770. *
  771. * @param {Number} tenderId - 标段id
  772. * @param {Number} selectId - 选中节点id
  773. * @return {Array} - 发生改变的数据
  774. */
  775. async upLevelNode(mid, kid, count) {
  776. if (!count) count = 1;
  777. const selects = await this.getDataByKidAndCount(mid, kid, count);
  778. if (selects.length !== count) throw '升级节点数据错误';
  779. const first = selects[0], last = selects[count - 1];
  780. const parent = await this.getDataByKid(mid, first[this.setting.pid]);
  781. if (!parent) throw '升级节点数据错误';
  782. const newPath = [];
  783. this.transaction = await this.db.beginTransaction();
  784. try {
  785. // 选中节点--父节点 选中节点为firstChild时,修改isLeaf
  786. if (first[this.setting.order] === 1) {
  787. const updateParentData = { id: parent.id };
  788. updateParentData[this.setting.isLeaf] = true;
  789. await this.transaction.update(this.tableName, updateParentData);
  790. }
  791. // 选中节点--父节点--全部后兄弟节点 order+1
  792. await this._updateChildrenOrder(mid, parent[this.setting.pid], parent[this.setting.order] + 1, count);
  793. for (const [i, s] of selects.entries()) {
  794. // 选中节点 修改pid, order, fullPath, level, isLeaf, 清空计算项
  795. const updateData = { id: s.id };
  796. updateData[this.setting.pid] = parent[this.setting.pid];
  797. updateData[this.setting.order] = parent[this.setting.order] + i + 1;
  798. updateData[this.setting.level] = s[this.setting.level] - 1;
  799. updateData[this.setting.fullPath] = s[this.setting.fullPath].replace(`-${s[this.setting.pid]}-`, '-');
  800. newPath.push(updateData[this.setting.fullPath]);
  801. if (s[this.setting.isLeaf] && s.id === last.id) {
  802. const nexts = await this.getNextsData(mid, parent[this.setting.kid], last[this.setting.order]);
  803. if (nexts.length > 0) {
  804. updateData[this.setting.isLeaf] = false;
  805. this.clearParentingData(updateData);
  806. }
  807. }
  808. await this.transaction.update(this.tableName, updateData);
  809. // 选中节点--全部子节点(含孙) level-1, fullPath变更
  810. await this._syncUplevelChildren(s);
  811. }
  812. // 选中节点--全部后兄弟节点 收编为子节点 修改pid, order, fullPath
  813. await this._syncUpLevelNexts(last);
  814. await this.transaction.commit();
  815. this.transaction = null;
  816. } catch (err) {
  817. await this.transaction.rollback();
  818. this.transaction = null;
  819. throw err;
  820. }
  821. // 查询修改的数据
  822. let updateData = await this.getNextsData(mid, parent[this.setting.pid], parent[this.setting.order] - 1);
  823. for (const path of newPath) {
  824. const children = await this.getDataByFullPath(mid, path + '-%');
  825. updateData = updateData.concat(children);
  826. }
  827. return { update: updateData };
  828. }
  829. /**
  830. * 降级selectData, 同步修改所有子节点
  831. * @param {Object} selectData - 选中节点
  832. * @param {Object} preData - 选中节点的前一节点(降级后为父节点)
  833. * @return {Promise<*>}
  834. * @private
  835. */
  836. async _syncDownlevelChildren(select, newFullPath) {
  837. this.initSqlBuilder();
  838. this.sqlBuilder.setAndWhere(this.setting.mid, {
  839. value: this.db.escape(select[this.setting.mid]),
  840. operate: '=',
  841. });
  842. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  843. value: this.db.escape(select[this.setting.fullPath] + '-%'),
  844. operate: 'like',
  845. });
  846. this.sqlBuilder.setUpdateData(this.setting.level, {
  847. value: 1,
  848. selfOperate: '+',
  849. });
  850. this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  851. value: [this.setting.fullPath, this.db.escape(select[this.setting.fullPath] + '-'), this.db.escape(newFullPath + '-')],
  852. literal: 'Replace',
  853. });
  854. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  855. const data = await this.transaction.query(sql, sqlParam);
  856. return data;
  857. }
  858. /**
  859. * 降级节点
  860. *
  861. * @param {Number} tenderId - 标段id
  862. * @param {Number} selectId - 选中节点id
  863. * @return {Array} - 发生改变的数据
  864. */
  865. async downLevelNode(mid, kid, count) {
  866. if (!count) count = 1;
  867. const selects = await this.getDataByKidAndCount(mid, kid, count);
  868. if (!selects) throw '降级节点数据错误';
  869. const first = selects[0], last = selects[count - 1];
  870. const pre = await this.getDataByParentAndOrder(mid, first[this.setting.pid], first[this.setting.order] - 1);
  871. if (!pre) throw '节点不可降级';
  872. const preLastChild = await this.getLastChildData(mid, pre[this.setting.kid]);
  873. const newPath = [];
  874. this.transaction = await this.db.beginTransaction();
  875. try {
  876. // 选中节点--全部后节点 order--
  877. await this._updateChildrenOrder(mid, first[this.setting.pid], last[this.setting.order] + 1, -count);
  878. for (const [i, s] of selects.entries()) {
  879. // 选中节点 修改pid, level, order, fullPath
  880. const updateData = { id: s.id };
  881. updateData[this.setting.pid] = pre[this.setting.kid];
  882. updateData[this.setting.order] = preLastChild ? preLastChild[this.setting.order] + i + 1 : i + 1;
  883. updateData[this.setting.level] = s[this.setting.level] + 1;
  884. if (s[this.setting.level] === 1) {
  885. updateData[this.setting.fullPath] = pre[this.setting.kid] + '-' + s[this.setting.kid];
  886. } else {
  887. const index = s[this.setting.fullPath].lastIndexOf(s[this.setting.kid]);
  888. updateData[this.setting.fullPath] = s[this.setting.fullPath].substring(0, index-1) + '-' + pre[this.setting.kid] + '-' + s[this.setting.kid];
  889. }
  890. newPath.push(updateData[this.setting.fullPath]);
  891. await this.transaction.update(this.tableName, updateData);
  892. // 选中节点--全部子节点(含孙) level++, fullPath
  893. await this._syncDownlevelChildren(s, updateData[this.setting.fullPath]);
  894. }
  895. // 选中节点--前兄弟节点 isLeaf应为false, 清空计算相关字段
  896. const updateData2 = { id: pre.id };
  897. updateData2[this.setting.isLeaf] = false;
  898. this.clearParentingData(updateData2);
  899. await this.transaction.update(this.tableName, updateData2);
  900. await this.transaction.commit();
  901. this.transaction = null;
  902. } catch (err) {
  903. await this.transaction.rollback();
  904. this.transaction = null;
  905. throw err;
  906. }
  907. // 查询修改的数据
  908. let updateData = await this.getNextsData(mid, pre[this.setting.pid], pre[this.setting.order] - 1);
  909. // 选中节点及子节点
  910. for (const p of newPath) {
  911. updateData = updateData.concat(await this.getDataByFullPath(mid, p + '-%'));
  912. }
  913. updateData = updateData.concat(await this.getDataById(selects.map(x => { return x.id; })));
  914. // 选中节点--原前兄弟节点&全部后兄弟节点
  915. return { update: updateData };
  916. }
  917. /**
  918. * 过滤data中update方式不可提交的字段
  919. * @param {Number} id - 主键key
  920. * @param {Object} data
  921. * @return {Object<{id: *}>}
  922. * @private
  923. */
  924. _filterUpdateInvalidField(id, data) {
  925. const result = {id: id};
  926. for (const prop in data) {
  927. if (this.readOnlyFields.indexOf(prop) === -1) {
  928. result[prop] = data[prop];
  929. }
  930. }
  931. return result;
  932. }
  933. /**
  934. * 提交多条数据 - 不影响计算等未提交项
  935. * @param {Number} tenderId - 标段id
  936. * @param {Array} datas - 提交数据
  937. * @return {Array} - 提交后的数据
  938. */
  939. async updateInfos(mid, datas) {
  940. if (!mid) throw '数据错误';
  941. if (Array.isArray(datas)) {
  942. const updateDatas = [];
  943. for (const d of datas) {
  944. if (mid !== d[this.setting.mid]) throw '提交数据错误';
  945. const node = await this.getDataById(d.id);
  946. if (!node || mid !== node[this.setting.mid] || d[this.setting.kid] !== node[this.setting.kid]) throw '提交数据错误';
  947. updateDatas.push(this._filterUpdateInvalidField(node.id, d));
  948. }
  949. await this.db.updateRows(this.tableName, updateDatas);
  950. const resultData = await this.getDataById(this._.map(datas, 'id'));
  951. return resultData;
  952. } else {
  953. if (mid !== datas[this.setting.mid]) throw '提交数据错误';
  954. const node = await this.getDataById(datas.id);
  955. if (!node || mid !== node[this.setting.mid] || datas[this.setting.kid] !== node[this.setting.kid]) throw '提交数据错误';
  956. const updateData = this._filterUpdateInvalidField(node.id, datas);
  957. await this.db.update(this.tableName, updateData);
  958. return await this.getDataById(datas.id);
  959. }
  960. }
  961. }
  962. module.exports = TreeService;