base_tree_service.js 39 KB

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