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