base_tree_service.js 39 KB

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