base_tree_service.js 43 KB

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