base_tree_service.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  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. _getDefaultData(data) {
  366. }
  367. /**
  368. * 新增数据(新增为selectData的后项,该方法不可单独使用)
  369. *
  370. * @param {Number} mid - 台账id
  371. * @param {Object} select - 选中节点的数据
  372. * @param {Object} data - 新增节点的初始数据
  373. * @return {Object} - 新增结果
  374. * @private
  375. */
  376. async _addNodeData(mid, select, data) {
  377. if (!data) {
  378. data = {};
  379. }
  380. const maxId = await this._getMaxLid(mid);
  381. if (this.setting.uuid) data.id = this.uuid.v4();
  382. data[this.setting.kid] = maxId + 1;
  383. data[this.setting.pid] = select ? select[this.setting.pid] : this.rootId;
  384. data[this.setting.mid] = mid;
  385. data[this.setting.level] = select ? select[this.setting.level] : 1;
  386. data[this.setting.order] = select ? select[this.setting.order] + 1 : 1;
  387. 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] + '';
  388. data[this.setting.isLeaf] = true;
  389. this._getDefaultData(data);
  390. const result = await this.transaction.insert(this.tableName, data);
  391. this._cacheMaxLid(mid, maxId + 1);
  392. return result;
  393. }
  394. /**
  395. * 新增节点
  396. * @param {Number} mid - 台账id
  397. * @param {Number} kid - 清单节点id
  398. * @returns {Promise<void>}
  399. */
  400. async addNode(mid, kid, data) {
  401. if (!mid) return null;
  402. const select = kid ? await this.getDataByKid(mid, kid) : null;
  403. if (kid && !select) throw '新增节点数据错误';
  404. this.transaction = await this.db.beginTransaction();
  405. try {
  406. if (select) await this._updateChildrenOrder(mid, select[this.setting.pid], select[this.setting.order]+1);
  407. const newNode = await this._addNodeData(mid, select, data);
  408. if (newNode.affectedRows !== 1) throw '新增节点数据错误';
  409. await this.transaction.commit();
  410. this.transaction = null;
  411. } catch (err) {
  412. await this.transaction.rollback();
  413. this.transaction = null;
  414. throw err;
  415. }
  416. if (select) {
  417. const createData = await this.getDataByParentAndOrder(mid, select[this.setting.pid], [select[this.setting.order] + 1]);
  418. const updateData = await this.getNextsData(mid, select[this.setting.pid], select[this.setting.order] + 1);
  419. return {create: createData, update: updateData};
  420. } else {
  421. const createData = await this.getDataByParentAndOrder(mid, -1, [1]);
  422. return {create: createData};
  423. }
  424. }
  425. async addNodeBatch(mid, kid, data, count = 1) {
  426. if (!mid) return null;
  427. const select = kid ? await this.getDataByKid(mid, kid) : null;
  428. if (kid && !select) throw '新增节点数据错误';
  429. this.transaction = await this.db.beginTransaction();
  430. try {
  431. if (select) await this._updateChildrenOrder(mid, select[this.setting.pid], select[this.setting.order] + 1, count);
  432. const newDatas = [];
  433. const maxId = await this._getMaxLid(mid);
  434. for (let i = 1; i < count + 1; i++) {
  435. const newData = Object.assign({}, data);
  436. if (this.setting.uuid) newData.id = this.uuid.v4();
  437. newData[this.setting.kid] = maxId + i;
  438. newData[this.setting.pid] = select ? select[this.setting.pid] : this.rootId;
  439. newData[this.setting.mid] = mid;
  440. newData[this.setting.level] = select ? select[this.setting.level] : 1;
  441. newData[this.setting.order] = select ? select[this.setting.order] + i : i;
  442. newData[this.setting.fullPath] = newData[this.setting.level] > 1
  443. ? select[this.setting.fullPath].replace('-' + select[this.setting.kid], '-' + newData[this.setting.kid])
  444. : newData[this.setting.kid] + '';
  445. newData[this.setting.isLeaf] = true;
  446. newDatas.push(newData);
  447. }
  448. const insertResult = await this.transaction.insert(this.tableName, newDatas);
  449. this._cacheMaxLid(mid, maxId + count);
  450. if (insertResult.affectedRows !== count) throw '新增节点数据错误';
  451. await this.transaction.commit();
  452. this.transaction = null;
  453. } catch (err) {
  454. await this.transaction.rollback();
  455. this.transaction = null;
  456. throw err;
  457. }
  458. if (select) {
  459. const createData = await this.getChildBetween(mid, select[this.setting.pid], select[this.setting.order], select[this.setting.order] + count + 1);
  460. const updateData = await this.getNextsData(mid, select[this.setting.pid], select[this.setting.order] + count);
  461. return {create: createData, update: updateData};
  462. } else {
  463. const createData = await this.getChildBetween(mid, -1, 0, count + 1);
  464. return {create: createData};
  465. }
  466. }
  467. async addChildBatch(mid, kid, data, count = 1) {
  468. if (!mid || !kid) return null;
  469. const select = await this.getDataByKid(mid, kid);
  470. if (!select) throw '新增节点数据错误';
  471. const children = await this.getChildrenByParentId(mid, kid);
  472. const maxId = await this._getMaxLid(mid);
  473. this.transaction = await this.db.beginTransaction();
  474. try {
  475. const newDatas = [];
  476. for (let i = 1; i < count + 1; i++) {
  477. const newData = Object.assign({}, data);
  478. if (this.setting.uuid) newData.id = this.uuid.v4();
  479. newData[this.setting.kid] = maxId + i;
  480. newData[this.setting.pid] = select[this.setting.kid];
  481. newData[this.setting.mid] = mid;
  482. newData[this.setting.level] = select[this.setting.level] + 1;
  483. newData[this.setting.order] = children.length > 0 ? children[children.length - 1].order + i : i;
  484. newData[this.setting.fullPath] = select[this.setting.fullPath] + '-' + newData[this.setting.kid];
  485. newData[this.setting.isLeaf] = true;
  486. newDatas.push(newData);
  487. }
  488. const insertResult = await this.transaction.insert(this.tableName, newDatas);
  489. this._cacheMaxLid(mid, maxId + count);
  490. if (select[this.setting.isLeaf] || children.length === 0) {
  491. const updateData = { id: select.id };
  492. updateData[this.setting.isLeaf] = false;
  493. this.clearParentingData(updateData);
  494. await this.transaction.update(this.tableName, updateData);
  495. }
  496. if (insertResult.affectedRows !== count) throw '新增节点数据错误';
  497. await this.transaction.commit();
  498. this.transaction = null;
  499. } catch (err) {
  500. await this.transaction.rollback();
  501. this.transaction = null;
  502. throw err;
  503. }
  504. if (select[this.setting.isLeaf] || children.length === 0) {
  505. const createData = await this.getDataByKidAndCount(mid, maxId + 1, count);
  506. const updateData = await this.getDataByKid(mid, select[this.setting.id]);
  507. return {create: createData, update: updateData};
  508. } else {
  509. const createData = await this.getDataByKidAndCount(mid, maxId + 1, count);
  510. return {create: createData};
  511. }
  512. }
  513. /**
  514. * 删除相关数据 用于继承
  515. * @param mid
  516. * @param deleteData
  517. * @returns {Promise<void>}
  518. * @private
  519. */
  520. async _deleteRelaData(mid, deleteData) {
  521. }
  522. /**
  523. * 删除节点
  524. * @param {Number} tenderId - 标段id
  525. * @param {Object} deleteData - 删除节点数据
  526. * @return {Promise<*>}
  527. * @private
  528. */
  529. async _deletePosterity(mid, node) {
  530. this.initSqlBuilder();
  531. this.sqlBuilder.setAndWhere(this.setting.mid, {
  532. value: this.db.escape(mid),
  533. operate: '=',
  534. });
  535. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  536. value: this.db.escape(node[this.setting.fullPath] + '-%'),
  537. operate: 'Like',
  538. });
  539. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'delete');
  540. const result = await this.transaction.query(sql, sqlParam);
  541. return result;
  542. }
  543. /**
  544. * tenderId标段中, 删除选中节点及其子节点
  545. *
  546. * @param {Number} tenderId - 标段id
  547. * @param {Number} selectId - 选中节点id
  548. * @return {Array} - 被删除的数据
  549. */
  550. async deleteNode(mid, kid) {
  551. if (!mid || (kid <= 0)) return [];
  552. const select = await this.getDataByKid(mid, kid);
  553. if (!select) throw '删除节点数据错误';
  554. const parent = await this.getDataByKid(mid, select[this.setting.pid]);
  555. // 获取将要被删除的数据
  556. const deleteData = await this.getDataByFullPath(mid, select[this.setting.fullPath] + '-%');
  557. deleteData.unshift(select);
  558. if (deleteData.length === 0) throw '删除节点数据错误';
  559. this.transaction = await this.db.beginTransaction();
  560. try {
  561. // 删除
  562. await this.transaction.delete(this.tableName, { id: select.id });
  563. const operate = await this._deletePosterity(mid, select);
  564. // 选中节点--父节点 只有一个子节点时,应升级isLeaf
  565. if (parent) {
  566. const count = await this.db.count(this.tableName, this.getCondition({mid: mid, pid: select[this.setting.pid]}));
  567. if (count === 1) {
  568. const updateParent = {id: parent.id };
  569. updateParent[this.setting.isLeaf] = true;
  570. await this.transaction.update(this.tableName, updateParent);
  571. }
  572. }
  573. // 选中节点--全部后节点 order--
  574. await this._updateChildrenOrder(mid, select[this.setting.pid], select[this.setting.order] + 1, -1);
  575. // 删除部位明细
  576. await this._deleteRelaData(mid, deleteData);
  577. await this.transaction.commit();
  578. this.transaction = null;
  579. } catch (err) {
  580. await this.transaction.rollback();
  581. this.transaction = null;
  582. throw err;
  583. }
  584. // 查询结果
  585. const updateData = await this.getNextsData(mid, select[this.setting.pid], select[this.setting.order] - 1);
  586. if (parent) {
  587. const updateData1 = await this.getDataByKid(mid, select[this.setting.pid]);
  588. if (updateData1[this.setting.isLeaf]) {
  589. updateData.push(updateData1);
  590. }
  591. }
  592. return { delete: deleteData, update: updateData };
  593. }
  594. async deleteNodes(mid, kid, count) {
  595. if (!mid || (kid <= 0) || (count <= 0)) return [];
  596. const selects = await this.getDataByKidAndCount(mid, kid, count);
  597. const first = selects[0];
  598. const parent = await this.getDataByKid(mid, first[this.setting.pid]);
  599. const childCount = parent ? await this.count(this.getCondition({mid: mid, pid: parent[this.setting.kid]})) : -1;
  600. let deleteData = [];
  601. for (const s of selects) {
  602. deleteData = deleteData.concat(await this.getDataByFullPath(mid, s[this.setting.fullPath] + '-%'));
  603. deleteData.push(s);
  604. }
  605. this.transaction = await this.db.beginTransaction();
  606. try {
  607. // 删除
  608. await this.transaction.delete(this.tableName, { id: selects.map(x => { return x.id }) });
  609. for (const s of selects) {
  610. const operate = await this._deletePosterity(mid, s);
  611. }
  612. // 选中节点--父节点 只有一个子节点时,应升级isLeaf
  613. if (parent && childCount === count) {
  614. const updateParent = {id: parent.id };
  615. updateParent[this.setting.isLeaf] = true;
  616. await this.transaction.update(this.tableName, updateParent);
  617. }
  618. // 选中节点--全部后节点 order--
  619. await this._updateChildrenOrder(mid, first[this.setting.pid], first[this.setting.order] + count, -count);
  620. // 删除部位明细
  621. await this._deleteRelaData(mid, deleteData);
  622. await this.transaction.commit();
  623. this.transaction = null;
  624. const updateData = await this.getNextsData(mid, first[this.setting.pid], first[this.setting.order] - 1);
  625. if (parent && childCount === count) {
  626. const updateData1 = await this.getDataByKid(mid, parent[this.setting.kid]);
  627. updateData.push(updateData1);
  628. }
  629. return { delete: deleteData, update: updateData };
  630. } catch (err) {
  631. if (this.transaction) {
  632. await this.transaction.rollback();
  633. this.transaction = null;
  634. }
  635. throw err;
  636. }
  637. }
  638. async delete(mid, kid, count) {
  639. if (count && count > 1) {
  640. return await this.deleteNodes(mid, kid, count);
  641. } else {
  642. return await this.deleteNode(mid, kid);
  643. }
  644. }
  645. /**
  646. * 上移节点
  647. *
  648. * @param {Number} mid - master id
  649. * @param {Number} kid - 选中节点id
  650. * @return {Array} - 发生改变的数据
  651. */
  652. async upMoveNode(mid, kid, count) {
  653. if (!count) count = 1;
  654. if (!mid || !kid || (kid <= 0)) return null;
  655. const selects = await this.getDataByKidAndCount(mid, kid, count);
  656. if (selects.length !== count) throw '上移节点数据错误';
  657. const first = selects[0];
  658. const pre = await this.getDataByParentAndOrder(mid, first[this.setting.pid], first[this.setting.order] - 1);
  659. if (!pre) throw '节点不可上移';
  660. const order = [];
  661. this.transaction = await this.db.beginTransaction();
  662. try {
  663. for (const s of selects) {
  664. const sData = { id: s.id };
  665. sData[this.setting.order] = s[this.setting.order] - 1;
  666. await this.transaction.update(this.tableName, sData);
  667. order.push(s[this.setting.order] - 1);
  668. }
  669. const pData = { id: pre.id };
  670. pData[this.setting.order] = pre[this.setting.order] + count;
  671. await this.transaction.update(this.tableName, pData);
  672. order.push(pre[this.setting.order] + count);
  673. await this.transaction.commit();
  674. this.transaction = null;
  675. } catch (err) {
  676. await this.transaction.rollback();
  677. this.transaction = null;
  678. throw err;
  679. }
  680. const resultData = await this.getDataByParentAndOrder(mid, first[this.setting.pid], order);
  681. return { update: resultData };
  682. }
  683. /**
  684. * 下移节点
  685. *
  686. * @param {Number} mid - master id
  687. * @param {Number} kid - 选中节点id
  688. * @return {Array} - 发生改变的数据
  689. */
  690. async downMoveNode(mid, kid, count) {
  691. if (!count) count = 1;
  692. if (!mid || !kid || (kid <= 0)) return null;
  693. const selects = await this.getDataByKidAndCount(mid, kid, count);
  694. if (selects.length !== count) {
  695. throw '下移节点数据错误';
  696. }
  697. const last = selects[count - 1];
  698. const next = await this.getDataByParentAndOrder(mid, last[this.setting.pid], last[this.setting.order] + 1);
  699. if (!next) {
  700. throw '节点不可下移';
  701. }
  702. const order = [];
  703. this.transaction = await this.db.beginTransaction();
  704. try {
  705. for (const s of selects) {
  706. const sData = { id: s.id };
  707. sData[this.setting.order] = s[this.setting.order] + 1;
  708. await this.transaction.update(this.tableName, sData);
  709. order.push(s[this.setting.order] + 1);
  710. }
  711. const nData = { id: next.id };
  712. nData[this.setting.order] = next[this.setting.order] - count;
  713. await this.transaction.update(this.tableName, nData);
  714. order.push(next[this.setting.order] - count);
  715. await this.transaction.commit();
  716. this.transaction = null;
  717. } catch (err) {
  718. await this.transaction.rollback();
  719. this.transaction = null;
  720. throw err;
  721. }
  722. const resultData = await this.getDataByParentAndOrder(mid, last[this.setting.pid], order);
  723. return { update: resultData };
  724. }
  725. /**
  726. * 节点成为父项时,可能需要修改父项数据,供子类继承
  727. * @param data
  728. */
  729. clearParentingData (data) {
  730. }
  731. /**
  732. * 升级selectData, 同步修改所有子节点
  733. * @param {Object} selectData - 升级操作,选中节点
  734. * @return {Object}
  735. * @private
  736. */
  737. async _syncUplevelChildren(select, isParentToTop = false) {
  738. this.initSqlBuilder();
  739. this.sqlBuilder.setAndWhere(this.setting.mid, {
  740. value: this.db.escape(select[this.setting.mid]),
  741. operate: '=',
  742. });
  743. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  744. value: this.db.escape(select[this.setting.fullPath] + '-%'),
  745. operate: 'like',
  746. });
  747. this.sqlBuilder.setUpdateData(this.setting.level, {
  748. value: 1,
  749. selfOperate: '-',
  750. });
  751. if (isParentToTop) {
  752. this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  753. value: [this.setting.fullPath, this.db.escape(`${select[this.setting.pid]}-`), this.db.escape('')],
  754. literal: 'Replace',
  755. });
  756. } else {
  757. this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  758. value: [this.setting.fullPath, this.db.escape(`-${select[this.setting.pid]}-`), this.db.escape('-')],
  759. literal: 'Replace',
  760. });
  761. }
  762. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  763. const data = await this.transaction.query(sql, sqlParam);
  764. return data;
  765. }
  766. /**
  767. * 选中节点的后兄弟节点,全部变为当前节点的子节点
  768. * @param {Object} selectData - 选中节点
  769. * @return {Object}
  770. * @private
  771. */
  772. async _syncUpLevelNexts(select) {
  773. // 查询selectData的lastChild
  774. const lastChild = await this.getLastChildData(select[this.setting.mid], select[this.setting.kid]);
  775. const nexts = await this.getNextsData(select[this.setting.mid], select[this.setting.pid], select[this.setting.order]);
  776. if (nexts && nexts.length > 0) {
  777. // 修改nextsData pid, 排序
  778. this.initSqlBuilder();
  779. this.sqlBuilder.setUpdateData(this.setting.pid, {
  780. value: select[this.setting.kid],
  781. });
  782. const orderInc = lastChild ? lastChild[this.setting.order] - select[this.setting.order] : - select[this.setting.order];
  783. this.sqlBuilder.setUpdateData(this.setting.order, {
  784. value: Math.abs(orderInc),
  785. selfOperate: orderInc > 0 ? '+' : '-',
  786. });
  787. this.sqlBuilder.setAndWhere(this.setting.mid, {
  788. value: this.db.escape(select[this.setting.mid]),
  789. operate: '=',
  790. });
  791. this.sqlBuilder.setAndWhere(this.setting.pid, {
  792. value: select[this.setting.pid],
  793. operate: '=',
  794. });
  795. this.sqlBuilder.setAndWhere(this.setting.order, {
  796. value: select[this.setting.order],
  797. operate: '>',
  798. });
  799. const [sql1, sqlParam1] = this.sqlBuilder.build(this.tableName, 'update');
  800. await this.transaction.query(sql1, sqlParam1);
  801. // 选中节点 isLeaf应为false
  802. if (select[this.setting.isLeaf]) {
  803. const updateData = { id: select.id };
  804. updateData[this.setting.isLeaf] = false;
  805. await this.transaction.update(this.tableName, updateData);
  806. }
  807. // 修改nextsData及其子节点的fullPath
  808. const oldSubStr = this.db.escape(select[this.setting.pid] + '-');
  809. const newSubStr = this.db.escape(select[this.setting.kid] + '-');
  810. const sqlArr = [];
  811. sqlArr.push('Update ?? SET `' + this.setting.fullPath + '` = Replace(`' + this.setting.fullPath + '`,' + oldSubStr + ',' + newSubStr + ') Where');
  812. sqlArr.push('(`' + this.setting.mid + '` = ' + this.db.escape(select[this.setting.mid]) + ')');
  813. sqlArr.push(' And (');
  814. for (const data of nexts) {
  815. sqlArr.push('`' + this.setting.fullPath + '` Like ' + this.db.escape(data[this.setting.fullPath] + '%'));
  816. if (nexts.indexOf(data) < nexts.length - 1) {
  817. sqlArr.push(' Or ');
  818. }
  819. }
  820. sqlArr.push(')');
  821. const sql = sqlArr.join('');
  822. const resultData = await this.transaction.query(sql, [this.tableName]);
  823. return resultData;
  824. }
  825. }
  826. /**
  827. * 升级节点
  828. *
  829. * @param {Number} tenderId - 标段id
  830. * @param {Number} selectId - 选中节点id
  831. * @return {Array} - 发生改变的数据
  832. */
  833. async upLevelNode(mid, kid, count) {
  834. if (!count) count = 1;
  835. const selects = await this.getDataByKidAndCount(mid, kid, count);
  836. if (selects.length !== count) throw '升级节点数据错误';
  837. const first = selects[0], last = selects[count - 1];
  838. const parent = await this.getDataByKid(mid, first[this.setting.pid]);
  839. if (!parent) throw '升级节点数据错误';
  840. const newPath = [];
  841. this.transaction = await this.db.beginTransaction();
  842. try {
  843. // 选中节点--父节点 选中节点为firstChild时,修改isLeaf
  844. if (first[this.setting.order] === 1) {
  845. const updateParentData = { id: parent.id };
  846. updateParentData[this.setting.isLeaf] = true;
  847. await this.transaction.update(this.tableName, updateParentData);
  848. }
  849. // 选中节点--父节点--全部后兄弟节点 order+1
  850. await this._updateChildrenOrder(mid, parent[this.setting.pid], parent[this.setting.order] + 1, count);
  851. for (const [i, s] of selects.entries()) {
  852. // 选中节点 修改pid, order, fullPath, level, isLeaf, 清空计算项
  853. const updateData = { id: s.id };
  854. updateData[this.setting.pid] = parent[this.setting.pid];
  855. updateData[this.setting.order] = parent[this.setting.order] + i + 1;
  856. updateData[this.setting.level] = s[this.setting.level] - 1;
  857. updateData[this.setting.fullPath] = s[this.setting.level] === 2 ? s[this.setting.kid] + '' : s[this.setting.fullPath].replace(`-${s[this.setting.pid]}-`, '-');
  858. newPath.push(updateData[this.setting.fullPath]);
  859. if (s[this.setting.isLeaf] && s.id === last.id) {
  860. const nexts = await this.getNextsData(mid, parent[this.setting.kid], last[this.setting.order]);
  861. if (nexts.length > 0) {
  862. updateData[this.setting.isLeaf] = false;
  863. this.clearParentingData(updateData);
  864. }
  865. }
  866. await this.transaction.update(this.tableName, updateData);
  867. // 选中节点--全部子节点(含孙) level-1, fullPath变更
  868. await this._syncUplevelChildren(s, s[this.setting.level] === 2);
  869. }
  870. // 选中节点--全部后兄弟节点 收编为子节点 修改pid, order, fullPath
  871. await this._syncUpLevelNexts(last);
  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, parent[this.setting.pid], parent[this.setting.order] - 1);
  881. for (const path of newPath) {
  882. const children = await this.getDataByFullPath(mid, path + '-%');
  883. updateData = updateData.concat(children);
  884. }
  885. return { update: updateData };
  886. }
  887. /**
  888. * 降级selectData, 同步修改所有子节点
  889. * @param {Object} selectData - 选中节点
  890. * @param {Object} preData - 选中节点的前一节点(降级后为父节点)
  891. * @return {Promise<*>}
  892. * @private
  893. */
  894. async _syncDownlevelChildren(select, newFullPath) {
  895. this.initSqlBuilder();
  896. this.sqlBuilder.setAndWhere(this.setting.mid, {
  897. value: this.db.escape(select[this.setting.mid]),
  898. operate: '=',
  899. });
  900. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  901. value: this.db.escape(select[this.setting.fullPath] + '-%'),
  902. operate: 'like',
  903. });
  904. this.sqlBuilder.setUpdateData(this.setting.level, {
  905. value: 1,
  906. selfOperate: '+',
  907. });
  908. this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  909. value: [this.setting.fullPath, this.db.escape(select[this.setting.fullPath] + '-'), this.db.escape(newFullPath + '-')],
  910. literal: 'Replace',
  911. });
  912. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  913. const data = await this.transaction.query(sql, sqlParam);
  914. return data;
  915. }
  916. /**
  917. * 降级节点
  918. *
  919. * @param {Number} tenderId - 标段id
  920. * @param {Number} selectId - 选中节点id
  921. * @return {Array} - 发生改变的数据
  922. */
  923. async downLevelNode(mid, kid, count) {
  924. if (!count) count = 1;
  925. const selects = await this.getDataByKidAndCount(mid, kid, count);
  926. if (!selects) throw '降级节点数据错误';
  927. const first = selects[0], last = selects[count - 1];
  928. const pre = await this.getDataByParentAndOrder(mid, first[this.setting.pid], first[this.setting.order] - 1);
  929. if (!pre) throw '节点不可降级';
  930. const preLastChild = await this.getLastChildData(mid, pre[this.setting.kid]);
  931. const newPath = [];
  932. this.transaction = await this.db.beginTransaction();
  933. try {
  934. // 选中节点--全部后节点 order--
  935. await this._updateChildrenOrder(mid, first[this.setting.pid], last[this.setting.order] + 1, -count);
  936. for (const [i, s] of selects.entries()) {
  937. // 选中节点 修改pid, level, order, fullPath
  938. const updateData = { id: s.id };
  939. updateData[this.setting.pid] = pre[this.setting.kid];
  940. updateData[this.setting.order] = preLastChild ? preLastChild[this.setting.order] + i + 1 : i + 1;
  941. updateData[this.setting.level] = s[this.setting.level] + 1;
  942. if (s[this.setting.level] === 1) {
  943. updateData[this.setting.fullPath] = pre[this.setting.kid] + '-' + s[this.setting.kid];
  944. } else {
  945. const index = s[this.setting.fullPath].lastIndexOf(s[this.setting.kid]);
  946. updateData[this.setting.fullPath] = s[this.setting.fullPath].substring(0, index-1) + '-' + pre[this.setting.kid] + '-' + s[this.setting.kid];
  947. }
  948. newPath.push(updateData[this.setting.fullPath]);
  949. await this.transaction.update(this.tableName, updateData);
  950. // 选中节点--全部子节点(含孙) level++, fullPath
  951. await this._syncDownlevelChildren(s, updateData[this.setting.fullPath]);
  952. }
  953. // 选中节点--前兄弟节点 isLeaf应为false, 清空计算相关字段
  954. const updateData2 = { id: pre.id };
  955. updateData2[this.setting.isLeaf] = false;
  956. this.clearParentingData(updateData2);
  957. await this.transaction.update(this.tableName, updateData2);
  958. await this.transaction.commit();
  959. this.transaction = null;
  960. } catch (err) {
  961. await this.transaction.rollback();
  962. this.transaction = null;
  963. throw err;
  964. }
  965. // 查询修改的数据
  966. let updateData = await this.getNextsData(mid, pre[this.setting.pid], pre[this.setting.order] - 1);
  967. // 选中节点及子节点
  968. for (const p of newPath) {
  969. updateData = updateData.concat(await this.getDataByFullPath(mid, p + '-%'));
  970. }
  971. updateData = updateData.concat(await this.getDataById(selects.map(x => { return x.id; })));
  972. // 选中节点--原前兄弟节点&全部后兄弟节点
  973. return { update: updateData };
  974. }
  975. /**
  976. * 过滤data中update方式不可提交的字段
  977. * @param {Number} id - 主键key
  978. * @param {Object} data
  979. * @return {Object<{id: *}>}
  980. * @private
  981. */
  982. _filterUpdateInvalidField(id, data) {
  983. const result = {id: id};
  984. for (const prop in data) {
  985. if (this.readOnlyFields.indexOf(prop) === -1) {
  986. result[prop] = data[prop];
  987. }
  988. }
  989. return result;
  990. }
  991. /**
  992. * 提交多条数据 - 不影响计算等未提交项
  993. * @param {Number} tenderId - 标段id
  994. * @param {Array} datas - 提交数据
  995. * @return {Array} - 提交后的数据
  996. */
  997. async updateInfos(mid, datas) {
  998. if (!mid) throw '数据错误';
  999. if (Array.isArray(datas)) {
  1000. const updateDatas = [];
  1001. for (const d of datas) {
  1002. if (mid !== d[this.setting.mid]) throw '提交数据错误';
  1003. const node = await this.getDataById(d.id);
  1004. if (!node || mid !== node[this.setting.mid] || d[this.setting.kid] !== node[this.setting.kid]) throw '提交数据错误';
  1005. updateDatas.push(this._filterUpdateInvalidField(node.id, d));
  1006. }
  1007. await this.db.updateRows(this.tableName, updateDatas);
  1008. const resultData = await this.getDataById(this._.map(datas, 'id'));
  1009. return resultData;
  1010. } else {
  1011. if (mid !== datas[this.setting.mid]) throw '提交数据错误';
  1012. const node = await this.getDataById(datas.id);
  1013. if (!node || mid !== node[this.setting.mid] || datas[this.setting.kid] !== node[this.setting.kid]) throw '提交数据错误';
  1014. const updateData = this._filterUpdateInvalidField(node.id, datas);
  1015. await this.db.update(this.tableName, updateData);
  1016. return await this.getDataById(datas.id);
  1017. }
  1018. }
  1019. }
  1020. module.exports = TreeService;