base_tree_service.js 42 KB

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