base_tree_service.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  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. * 升级selectData, 同步修改所有子节点
  581. * @param {Object} selectData - 升级操作,选中节点
  582. * @return {Object}
  583. * @private
  584. */
  585. async _syncUplevelChildren(select) {
  586. this.initSqlBuilder();
  587. this.sqlBuilder.setAndWhere(this.setting.mid, {
  588. value: select[this.setting.mid],
  589. operate: '=',
  590. });
  591. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  592. value: this.db.escape(select[this.setting.fullPath] + '-%'),
  593. operate: 'like',
  594. });
  595. this.sqlBuilder.setUpdateData(this.setting.level, {
  596. value: 1,
  597. selfOperate: '-',
  598. });
  599. this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  600. value: [this.setting.fullPath, this.db.escape(select[this.setting.pid] + '-'), this.db.escape('')],
  601. literal: 'Replace',
  602. });
  603. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  604. const data = await this.transaction.query(sql, sqlParam);
  605. return data;
  606. }
  607. /**
  608. * 选中节点的后兄弟节点,全部变为当前节点的子节点
  609. * @param {Object} selectData - 选中节点
  610. * @return {Object}
  611. * @private
  612. */
  613. async _syncUpLevelNexts(select) {
  614. // 查询selectData的lastChild
  615. const lastChild = await this.getLastChildData(select[this.setting.mid], select[this.setting.kid]);
  616. const nexts = await this.getNextsData(select[this.setting.mid], select[this.setting.pid], select[this.setting.order]);
  617. if (nexts && nexts.length > 0) {
  618. // 修改nextsData pid, 排序
  619. this.initSqlBuilder();
  620. this.sqlBuilder.setUpdateData(this.setting.pid, {
  621. value: select[this.setting.kid],
  622. });
  623. const orderInc = lastChild ? lastChild[this.setting.order] - select[this.setting.order] : - select[this.setting.order];
  624. this.sqlBuilder.setUpdateData(this.setting.order, {
  625. value: Math.abs(orderInc),
  626. selfOperate: orderInc > 0 ? '+' : '-',
  627. });
  628. this.sqlBuilder.setAndWhere(this.setting.mid, {
  629. value: select[this.setting.mid],
  630. operate: '=',
  631. });
  632. this.sqlBuilder.setAndWhere(this.setting.pid, {
  633. value: select[this.setting.pid],
  634. operate: '=',
  635. });
  636. this.sqlBuilder.setAndWhere(this.setting.order, {
  637. value: select[this.setting.order],
  638. operate: '>',
  639. });
  640. const [sql1, sqlParam1] = this.sqlBuilder.build(this.tableName, 'update');
  641. await this.transaction.query(sql1, sqlParam1);
  642. // 选中节点 is_leaf应为false
  643. if (select.is_leaf) {
  644. const updateData = { id: select.id, is_leaf: false };
  645. await this.transaction.update(this.tableName, updateData);
  646. }
  647. // 修改nextsData及其子节点的full_path
  648. const oldSubStr = this.db.escape(select[this.setting.pid] + '-');
  649. const newSubStr = this.db.escape(select[this.setting.kid] + '-');
  650. const sqlArr = [];
  651. sqlArr.push('Update ?? SET `full_path` = Replace(`full_path`,' + oldSubStr + ',' + newSubStr + ') Where');
  652. sqlArr.push('(`' + this.setting.mid + '` = ' + select[this.setting.mid] + ')');
  653. sqlArr.push(' And (');
  654. for (const data of nexts) {
  655. sqlArr.push('`' + this.setting.fullPath + '` Like ' + this.db.escape(data[this.setting.fullPath] + '%'));
  656. if (nexts.indexOf(data) < nexts.length - 1) {
  657. sqlArr.push(' Or ');
  658. }
  659. }
  660. sqlArr.push(')');
  661. const sql = sqlArr.join('');
  662. const resultData = await this.transaction.query(sql, [this.tableName]);
  663. return resultData;
  664. }
  665. }
  666. /**
  667. * 升级节点
  668. *
  669. * @param {Number} tenderId - 标段id
  670. * @param {Number} selectId - 选中节点id
  671. * @return {Array} - 发生改变的数据
  672. */
  673. async upLevelNode(mid, kid, count) {
  674. if (!count) count = 1;
  675. const selects = await this.getDataByKidAndCount(mid, kid, count);
  676. if (selects.length !== count) throw '升级节点数据错误';
  677. const first = selects[0], last = selects[count - 1];
  678. const parent = await this.getDataByKid(mid, first[this.setting.pid]);
  679. if (!parent) throw '升级节点数据错误';
  680. const newPath = [];
  681. this.transaction = await this.db.beginTransaction();
  682. try {
  683. // 选中节点--父节点 选中节点为firstChild时,修改is_leaf
  684. if (first[this.setting.order] === 1) {
  685. await this.transaction.update(this.tableName, {
  686. id: parent.id,
  687. is_leaf: true,
  688. });
  689. }
  690. // 选中节点--父节点--全部后兄弟节点 order+1
  691. await this._updateChildrenOrder(mid, parent[this.setting.pid], parent[this.setting.order] + 1, count);
  692. for (const [i, s] of selects.entries()) {
  693. // 选中节点 修改pid, order, full_path, level, is_leaf, 清空计算项
  694. const updateData = { id: s.id };
  695. updateData[this.setting.pid] = parent[this.setting.pid];
  696. updateData[this.setting.order] = parent[this.setting.order] + i + 1;
  697. updateData[this.setting.level] = s[this.setting.level] - 1;
  698. updateData[this.setting.fullPath] = s[this.setting.fullPath].replace(s[this.setting.pid] + '-', '');
  699. newPath.push(updateData[this.setting.fullPath]);
  700. if (s.is_leaf && s.id === last.id) {
  701. const nexts = await this.getNextsData(mid, parent[this.setting.kid], last[this.setting.order]);
  702. if (nexts.length > 0) {
  703. updateData.is_leaf = false;
  704. // updateData.unit_price = null;
  705. // updateData.quantity = null;
  706. // updateData.total_price = null;
  707. // updateData.deal_qty = null;
  708. // updateData.deal_tp = null;
  709. }
  710. }
  711. await this.transaction.update(this.tableName, updateData);
  712. // 选中节点--全部子节点(含孙) level-1, full_path变更
  713. await this._syncUplevelChildren(s);
  714. }
  715. // 选中节点--全部后兄弟节点 收编为子节点 修改pid, order, full_path
  716. await this._syncUpLevelNexts(last);
  717. await this.transaction.commit();
  718. this.transaction = null;
  719. } catch (err) {
  720. await this.transaction.rollback();
  721. this.transaction = null;
  722. throw err;
  723. }
  724. // 查询修改的数据
  725. let updateData = await this.getNextsData(mid, parent[this.setting.pid], parent[this.setting.order] - 1);
  726. for (const path of newPath) {
  727. const children = await this.getDataByFullPath(mid, path + '-%');
  728. updateData = updateData.concat(children);
  729. }
  730. return { update: updateData };
  731. }
  732. /**
  733. * 降级selectData, 同步修改所有子节点
  734. * @param {Object} selectData - 选中节点
  735. * @param {Object} preData - 选中节点的前一节点(降级后为父节点)
  736. * @return {Promise<*>}
  737. * @private
  738. */
  739. async _syncDownlevelChildren(select, pre) {
  740. this.initSqlBuilder();
  741. this.sqlBuilder.setAndWhere(this.setting.mid, {
  742. value: select[this.setting.mid],
  743. operate: '=',
  744. });
  745. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  746. value: this.db.escape(select[this.setting.fullPath] + '-%'),
  747. operate: 'like',
  748. });
  749. this.sqlBuilder.setUpdateData(this.setting.level, {
  750. value: 1,
  751. selfOperate: '+',
  752. });
  753. this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  754. value: [this.setting.fullPath, this.db.escape(select[this.setting.kid] + '-'), this.db.escape(pre[this.setting.kid] + '-' + select[this.setting.kid] + '-')],
  755. literal: 'Replace',
  756. });
  757. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  758. const data = await this.transaction.query(sql, sqlParam);
  759. return data;
  760. }
  761. /**
  762. * 降级节点
  763. *
  764. * @param {Number} tenderId - 标段id
  765. * @param {Number} selectId - 选中节点id
  766. * @return {Array} - 发生改变的数据
  767. */
  768. async downLevelNode(mid, kid, count) {
  769. console.log(mid);
  770. console.log(kid);
  771. console.log(count);
  772. if (!count) count = 1;
  773. const selects = await this.getDataByKidAndCount(mid, kid, count);
  774. if (!selects) throw '降级节点数据错误';
  775. const first = selects[0];
  776. const pre = await this.getDataByParentAndOrder(mid, first[this.setting.pid], first[this.setting.order] - 1);
  777. if (!pre) throw '节点不可降级';
  778. const preLastChild = await this.getLastChildData(mid, pre[this.setting.kid]);
  779. console.log(selects);
  780. console.log(pre);
  781. const newPath = [];
  782. this.transaction = await this.db.beginTransaction();
  783. try {
  784. // 选中节点--全部后节点 order--
  785. await this._updateChildrenOrder(mid, first[this.setting.pid], first[this.setting.order] + 1, -count);
  786. for (const [i, s] of selects.entries()) {
  787. // 选中节点 修改pid, level, order, full_path
  788. const updateData = { id: s.id };
  789. updateData[this.setting.pid] = pre[this.setting.kid];
  790. updateData[this.setting.order] = preLastChild ? preLastChild[this.setting.order] + i + 1 : i + 1;
  791. updateData[this.setting.level] = s[this.setting.level] + 1;
  792. const orgLastPath = s[this.setting.level] === 1 ? s[this.setting.kid] : '-' + s[this.setting.kid];
  793. const newLastPath = s[this.setting.level] === 1 ? pre[this.setting.kid] + '-' + s[this.setting.kid] : '-' + pre[this.setting.kid] + '-' + s[this.setting.kid];
  794. updateData[this.setting.fullPath] = s[this.setting.fullPath].replace(orgLastPath, newLastPath);
  795. newPath.push(updateData[this.setting.fullPath]);
  796. await this.transaction.update(this.tableName, updateData);
  797. // 选中节点--全部子节点(含孙) level++, full_path
  798. await this._syncDownlevelChildren(s, pre);
  799. }
  800. // 选中节点--前兄弟节点 is_leaf应为false, 清空计算相关字段
  801. const updateData2 = { id: pre.id };
  802. updateData2[this.setting.isLeaf] = false;
  803. // updateData2.unit_price = null;
  804. // updateData2.quantity = null;
  805. // updateData2.total_price = null;
  806. // updateData2.deal_qty = null;
  807. // updateData2.deal_tp = null;
  808. await this.transaction.update(this.tableName, updateData2);
  809. await this.transaction.commit();
  810. this.transaction = null;
  811. } catch (err) {
  812. await this.transaction.rollback();
  813. this.transaction = null;
  814. throw err;
  815. }
  816. // 查询修改的数据
  817. let updateData = await this.getNextsData(mid, pre[this.setting.pid], pre[this.setting.order] - 1);
  818. // 选中节点及子节点
  819. for (const p of newPath) {
  820. updateData = updateData.concat(await this.getDataByFullPath(mid, p + '%'));
  821. }
  822. // 选中节点--原前兄弟节点&全部后兄弟节点
  823. return { update: updateData };
  824. }
  825. /**
  826. * 过滤data中update方式不可提交的字段
  827. * @param {Number} id - 主键key
  828. * @param {Object} data
  829. * @return {Object<{id: *}>}
  830. * @private
  831. */
  832. _filterUpdateInvalidField(id, data) {
  833. const result = {id: id};
  834. for (const prop in data) {
  835. if (this.readOnlyFields.indexOf(prop) === -1) {
  836. result[prop] = data[prop];
  837. }
  838. }
  839. return result;
  840. }
  841. /**
  842. * 提交多条数据 - 不影响计算等未提交项
  843. * @param {Number} tenderId - 标段id
  844. * @param {Array} datas - 提交数据
  845. * @return {Array} - 提交后的数据
  846. */
  847. async updateInfos(mid, datas) {
  848. if (mid <= 0) throw '数据错误';
  849. if (Array.isArray(datas)) {
  850. const updateDatas = [];
  851. for (const d of datas) {
  852. if (mid !== d[this.setting.mid]) throw '提交数据错误';
  853. const node = await this.getDataById(d.id);
  854. if (!node || mid !== node[this.setting.mid] || d[this.setting.kid] !== node[this.setting.kid]) throw '提交数据错误';
  855. updateDatas.push(this._filterUpdateInvalidField(node.id, d));
  856. }
  857. await this.db.updateRows(this.tableName, updateDatas);
  858. const resultData = await this.getDataById(this._.map(datas, 'id'));
  859. return resultData;
  860. } else {
  861. if (mid !== datas[this.setting.mid]) throw '提交数据错误';
  862. const node = await this.getDataById(datas.id);
  863. if (!node || mid !== node[this.setting.mid] || datas[this.setting.kid] !== node[this.setting.kid]) throw '提交数据错误';
  864. const updateData = this._filterUpdateInvalidField(node.id, datas);
  865. await this.db.update(this.tableName, updateData);
  866. return await this.getDataById(datas.id);
  867. }
  868. }
  869. async pasteBlockRelaData(relaData) {
  870. if (!this.transaction) throw '更新数据错误';
  871. // for (const id of relaData) {
  872. // await this.ctx.service.pos.copyBillsPosData(id.org, id.new, this.transaction);
  873. // }
  874. }
  875. async getPasteBlockResult(select, copyNodes) {
  876. const createData = await this.getDataByIds(newIds);
  877. const updateData = await this.getNextsData(selectData[this.setting.mid], selectData[this.setting.pid], selectData[this.setting.order] + copyNodes.length);
  878. //const posData = await this.ctx.service.pos.getPosData({ lid: newIds });
  879. return {
  880. ledger: { create: createData, update: updateData },
  881. //pos: posData,
  882. };
  883. }
  884. /**
  885. * 复制粘贴整块
  886. * @param {Number} tenderId - 标段Id
  887. * @param {Number} selectId - 选中几点Id
  888. * @param {Array} block - 复制节点Id
  889. * @return {Object} - 提价后的数据(其中新增粘贴数据,只返回第一层)
  890. */
  891. async pasteBlock(mid, kid, block) {
  892. if ((mid <= 0) || (kid <= 0)) return [];
  893. const selectData = await this.getDataByKid(mid, kid);
  894. if (!selectData) throw '数据错误';
  895. const copyNodes = await this.getDataByNodeIds(mid, block);
  896. if (!copyNodes || copyNodes.length <= 0) throw '复制数据错误';
  897. for (const node of copyNodes) {
  898. if (node[this.setting.pid] !== copyNodes[0][this.setting.pid]) throw '复制数据错误:仅可操作同层节点';
  899. }
  900. const newParentPath = selectData[this.setting.fullPath].replace(selectData[this.setting.kid], '');
  901. const orgParentPath = copyNodes[0][this.setting.fullPath].replace(copyNodes[0][this.setting.kid], '');
  902. const newIds = [];
  903. this.transaction = await this.db.beginTransaction();
  904. try {
  905. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  906. await this._updateSelectNextsOrder(selectData, copyNodes.length);
  907. for (let iNode = 0; iNode < copyNodes.length; iNode++) {
  908. const node = copyNodes[iNode];
  909. let datas = await this.getDataByFullPath(mid, node[this.setting.fullPath] + '%');
  910. datas = this._.sortBy(datas, 'level');
  911. const maxId = await this._getMaxLid(mid);
  912. this._cacheMaxLid(mid, maxId + datas.length);
  913. const billsId = [];
  914. // 计算粘贴数据中需更新部分
  915. for (let index = 0; index < datas.length; index++) {
  916. const data = datas[index];
  917. const newId = maxId + index + 1;
  918. const idChange = {
  919. org: data.id,
  920. };
  921. if (this.setting.uuid) data.id = this.uuid.v4();
  922. idChange.new = data.id;
  923. data[this.setting.mid] = mid;
  924. if (!data[this.setting.isLeaf]) {
  925. for (const children of datas) {
  926. children[this.setting.fullPath] = children[this.setting.fullPath].replace('-' + data[this.setting.kid], '-' + newId);
  927. if (children[this.setting.pid] === data[this.setting.kid]) {
  928. children[this.setting.pid] = newId;
  929. }
  930. }
  931. } else {
  932. data[this.setting.fullPath] = data[this.setting.fullPath].replace('-' + data[this.setting.kid], '-' + newId);
  933. }
  934. data[this.setting.kid] = newId;
  935. data[this.setting.fullPath] = data[this.setting.fullPath].replace(orgParentPath, newParentPath);
  936. if (data[this.setting.pid] === node[this.setting.pid]) {
  937. data[this.setting.pid] = selectData[this.setting.pid];
  938. data[this.setting.order] = selectData[this.setting.order] + iNode + 1;
  939. }
  940. data[this.setting.level] = data[this.setting.level] + selectData[this.setting.level] - copyNodes[0][this.setting.level];
  941. idChange.isLeaf = data[this.setting.isLeaf];
  942. billsId.push(idChange);
  943. newIds.push(data.id);
  944. }
  945. const newData = await this.transaction.insert(this.tableName, datas);
  946. await this.pasteBlockRelaData(billsId);
  947. }
  948. // 数据库创建新增节点数据
  949. await this.transaction.commit();
  950. this.transaction = null;
  951. } catch (err) {
  952. await this.transaction.rollback();
  953. this.transaction = null;
  954. throw err;
  955. }
  956. // 查询应返回的结果
  957. const createData = await this.getDataByIds(newIds);
  958. const updateData = await this.getNextsData(selectData[this.setting.mid], selectData[this.setting.pid], selectData[this.setting.order] + copyNodes.length);
  959. //const posData = await this.ctx.service.pos.getPosData({ lid: newIds });
  960. return {
  961. ledger: { create: createData, update: updateData },
  962. //pos: posData,
  963. };
  964. }
  965. }
  966. module.exports = TreeService;