base_tree_service.js 42 KB

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