base_tree_service.js 39 KB

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