base_tree_service.js 43 KB

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