base_tree_service.js 43 KB

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