base_tree_service.js 40 KB

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