base_tree_service.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  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. /**
  92. * 获取节点数据
  93. * @param id
  94. * @returns {Promise<Array>}
  95. */
  96. async getDataById(id) {
  97. if (id instanceof Array) {
  98. return await this.db.select(this.tableName, { where: {id: id} });
  99. } else {
  100. return await this.db.get(this.tableName, { id: id });
  101. }
  102. }
  103. /**
  104. * 获取最末的子节点
  105. * @param {Number} mid - masterId
  106. * @param {Number} pid - 父节点id
  107. * @return {Object}
  108. */
  109. async getLastChildData(mid, pid) {
  110. this.initSqlBuilder();
  111. this.sqlBuilder.setAndWhere(this.setting.mid, {
  112. value: mid,
  113. operate: '=',
  114. });
  115. this.sqlBuilder.setAndWhere(this.setting.pid, {
  116. value: pid,
  117. operate: '=',
  118. });
  119. this.sqlBuilder.orderBy = [['order', 'DESC']];
  120. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  121. const resultData = await this.db.queryOne(sql, sqlParam);
  122. return resultData;
  123. }
  124. /**
  125. * 根据 父节点id 和 节点排序order 获取数据
  126. *
  127. * @param {Number} mid - master id
  128. * @param {Number} pid - 父节点id
  129. * @param {Number|Array} order - 排序
  130. * @return {Object|Array} - 查询结果
  131. */
  132. async getDataByParentAndOrder(mid, pid, order) {
  133. const result = await this.db.select(this.tableName, {
  134. where: this.getCondition({mid: mid, pid: pid, order: order})
  135. });
  136. return order instanceof Array ? result : (result.length > 0 ? result[0] : null);
  137. }
  138. /**
  139. * 根据 父节点ID 和 节点排序order 获取全部后节点数据
  140. * @param {Number} mid - master id
  141. * @param {Number} pid - 父节点id
  142. * @param {Number} order - 排序
  143. * @return {Array}
  144. */
  145. async getNextsData(mid, pid, order) {
  146. this.initSqlBuilder();
  147. this.sqlBuilder.setAndWhere(this.setting.mid, {
  148. value: mid,
  149. operate: '=',
  150. });
  151. this.sqlBuilder.setAndWhere(this.setting.pid, {
  152. value: pid,
  153. operate: '=',
  154. });
  155. this.sqlBuilder.setAndWhere(this.setting.order, {
  156. value: order,
  157. operate: '>',
  158. });
  159. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  160. const data = await this.db.query(sql, sqlParam);
  161. return data;
  162. }
  163. /**
  164. * 根据full_path获取数据 full_path Like ‘1.2.3%’(传参full_path = '1.2.3%')
  165. * @param {Number} tenderId - 标段id
  166. * @param {String} full_path - 路径
  167. * @return {Promise<void>}
  168. */
  169. async getDataByFullPath(mid, full_path) {
  170. this.initSqlBuilder();
  171. this.sqlBuilder.setAndWhere(this.setting.mid, {
  172. value: mid,
  173. operate: '=',
  174. });
  175. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  176. value: this.db.escape(full_path),
  177. operate: 'Like',
  178. });
  179. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  180. const resultData = await this.db.query(sql, sqlParam);
  181. return resultData;
  182. }
  183. /**
  184. * 根据full_path检索自己及所有父项
  185. * @param {Number} tenderId - 标段id
  186. * @param {Array|String} fullPath - 节点完整路径
  187. * @return {Promise<*>}
  188. * @private
  189. */
  190. async getFullLevelDataByFullPath(mid, fullPath) {
  191. const explodePath = this.ctx.helper.explodePath(fullPath);
  192. this.initSqlBuilder();
  193. this.sqlBuilder.setAndWhere(this.setting.mid, {
  194. value: mid,
  195. operate: '=',
  196. });
  197. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  198. value: explodePath,
  199. operate: 'in',
  200. });
  201. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  202. const data = await this.db.query(sql, sqlParam);
  203. return data;
  204. }
  205. /**
  206. * 获取最大节点id
  207. *
  208. * @param {Number} mid - master id
  209. * @return {Number}
  210. * @private
  211. */
  212. async _getMaxLid(mid) {
  213. const cacheKey = this.setting.keyPre + mid;
  214. let maxId = parseInt(await this.cache.get(cacheKey));
  215. if (!maxId) {
  216. const sql = 'SELECT Max(??) As max_id FROM ?? Where ' + this.setting.mid + ' = ?';
  217. const sqlParam = [this.setting.kid, this.tableName, mid];
  218. const queryResult = await this.db.queryOne(sql, sqlParam);
  219. maxId = queryResult.max_id || 0;
  220. this.cache.set(cacheKey, maxId, 'EX', this.ctx.app.config.cacheTime);
  221. }
  222. return maxId;
  223. }
  224. /**
  225. * 缓存最大节点id
  226. *
  227. * @param {Number} mid - master id
  228. * @param {Number} maxId - 当前最大节点id
  229. * @returns {Promise<void>}
  230. * @private
  231. */
  232. _cacheMaxLid(mid, maxId) {
  233. this.cache.set(this.setting.keyPre + mid , maxId, 'EX', this.ctx.app.config.cacheTime);
  234. }
  235. /**
  236. * 更新order
  237. * @param {Number} mid - master id
  238. * @param {Number} pid - 父节点id
  239. * @param {Number} order - 开始更新的order
  240. * @param {Number} incre - 更新的增量
  241. * @returns {Promise<*>}
  242. * @private
  243. */
  244. async _updateChildrenOrder(mid, pid, order, incre = 1) {
  245. this.initSqlBuilder();
  246. this.sqlBuilder.setAndWhere(this.setting.mid, {
  247. value: mid,
  248. operate: '=',
  249. });
  250. this.sqlBuilder.setAndWhere(this.setting.order, {
  251. value: order,
  252. operate: '>=',
  253. });
  254. this.sqlBuilder.setAndWhere(this.setting.pid, {
  255. value: pid,
  256. operate: '=',
  257. });
  258. this.sqlBuilder.setUpdateData(this.setting.order, {
  259. value: Math.abs(incre),
  260. selfOperate: incre > 0 ? '+' : '-',
  261. });
  262. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  263. const data = await this.transaction.query(sql, sqlParam);
  264. return data;
  265. }
  266. /**
  267. * 新增数据(新增为selectData的后项,该方法不可单独使用)
  268. *
  269. * @param {Number} mid - 台账id
  270. * @param {Object} select - 选中节点的数据
  271. * @param {Object} data - 新增节点的初始数据
  272. * @return {Object} - 新增结果
  273. * @private
  274. */
  275. async _addNodeData(mid, select, data) {
  276. if (!data) {
  277. data = {};
  278. }
  279. const maxId = await this._getMaxLid(mid);
  280. if (this.setting.uuid) data.id = this.uuid.v4();
  281. data[this.setting.kid] = maxId + 1;
  282. data[this.setting.pid] = select ? select[this.setting.pid] : rootId;
  283. data[this.setting.mid] = mid;
  284. data[this.setting.level] = select ? select[this.setting.level] : 1;
  285. data[this.setting.order] = select ? select[this.setting.order] + 1 : 1;
  286. 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] + '';
  287. data[this.setting.isLeaf] = true;
  288. const result = await this.transaction.insert(this.tableName, data);
  289. this._cacheMaxLid(mid, maxId + 1);
  290. return result;
  291. }
  292. /**
  293. * 新增节点
  294. * @param {Number} mid - 台账id
  295. * @param {Number} kid - 清单节点id
  296. * @returns {Promise<void>}
  297. */
  298. async addNode(mid, kid, data) {
  299. if (!mid) return null;
  300. const select = kid ? await this.getDataByKid(mid, kid) : null;
  301. if (kid && !select) throw '新增节点数据错误';
  302. this.transaction = await this.db.beginTransaction();
  303. try {
  304. if (select) await this._updateChildrenOrder(mid, select[this.setting.pid], select[this.setting.order]+1);
  305. const newNode = await this._addNodeData(mid, select, data);
  306. if (newNode.affectedRows !== 1) throw '新增节点数据额错误';
  307. await this.transaction.commit();
  308. this.transaction = null;
  309. } catch (err) {
  310. await this.transaction.rollback();
  311. this.transaction = null;
  312. throw err;
  313. }
  314. if (select) {
  315. const createData = await this.getDataByParentAndOrder(mid, select[this.setting.pid], [select[this.setting.order] + 1]);
  316. const updateData = await this.getNextsData(mid, select[this.setting.pid], select[this.setting.order] + 1);
  317. return {create: createData, update: updateData};
  318. } else {
  319. const createData = await this.getDataByParentAndOrder(mid, -1, [1]);
  320. return {create: createData};
  321. }
  322. }
  323. /**
  324. * 删除节点
  325. * @param {Number} tenderId - 标段id
  326. * @param {Object} deleteData - 删除节点数据
  327. * @return {Promise<*>}
  328. * @private
  329. */
  330. async _deleteNodeData(mid, deleteNode) {
  331. this.initSqlBuilder();
  332. this.sqlBuilder.setAndWhere(this.setting.mid, {
  333. value: mid,
  334. operate: '=',
  335. });
  336. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  337. value: this.db.escape(deleteNode[this.setting.fullPath] + '%'),
  338. operate: 'Like',
  339. });
  340. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'delete');
  341. const result = await this.transaction.query(sql, sqlParam);
  342. return result;
  343. }
  344. /**
  345. * tenderId标段中, 删除选中节点及其子节点
  346. *
  347. * @param {Number} tenderId - 标段id
  348. * @param {Number} selectId - 选中节点id
  349. * @return {Array} - 被删除的数据
  350. */
  351. async deleteNode(mid, kid) {
  352. if ((mid <= 0) || (kid <= 0)) return [];
  353. const select = await this.getDataByKid(mid, kid);
  354. if (!select) throw '删除节点数据错误';
  355. const parent = await this.getDataByKid(mid, select[this.setting.pid]);
  356. // 获取将要被删除的数据
  357. const deleteData = await this.getDataByFullPath(mid, select[this.setting.fullPath] + '%');
  358. if (deleteData.length === 0) throw '删除节点数据错误';
  359. this.transaction = await this.db.beginTransaction();
  360. try {
  361. // 删除
  362. const operate = await this._deleteNodeData(mid, select);
  363. // 选中节点--父节点 只有一个子节点时,应升级is_leaf
  364. if (parent) {
  365. const count = await this.db.count(this.tableName, this.getCondition({mid: mid, pid: select[this.setting.pid]}));
  366. if (count === 1) {
  367. const updateParent = {id: parent.id };
  368. updateParent[this.setting.isLeaf] = true;
  369. await this.transaction.update(this.tableName, updateParent);
  370. }
  371. }
  372. // 选中节点--全部后节点 order--
  373. await this._updateChildrenOrder(mid, select[this.setting.pid], select[this.setting.order] + 1, -1);
  374. //await this._updateSelectNextsOrder(select, -1);
  375. // 删除部位明细
  376. //await this.ctx.service.pos.deletePosData(this.transaction, tenderId, this._.map(deleteData, 'id'));
  377. await this.transaction.commit();
  378. this.transaction = null;
  379. } catch (err) {
  380. await this.transaction.rollback();
  381. this.transaction = null;
  382. throw err;
  383. }
  384. // 查询结果
  385. const updateData = await this.getNextsData(mid, select[this.setting.pid], select[this.setting.order] - 1);
  386. if (parent) {
  387. const updateData1 = await this.getDataByKid(mid, select[this.setting.pid]);
  388. if (updateData1[this.setting.isLeaf]) {
  389. updateData.push(updateData1);
  390. }
  391. }
  392. return { delete: deleteData, update: updateData };
  393. }
  394. /**
  395. * 上移节点
  396. *
  397. * @param {Number} mid - master id
  398. * @param {Number} kid - 选中节点id
  399. * @return {Array} - 发生改变的数据
  400. */
  401. async upMoveNode(mid, kid) {
  402. if (!mid || !kid) return null;
  403. const select = await this.getDataByKid(mid, kid);
  404. if (!select) {
  405. throw '上移节点数据错误';
  406. }
  407. const pre = await this.getDataByParentAndOrder(mid, select[this.setting.pid], select[this.setting.order] - 1);
  408. if (!pre) {
  409. throw '节点不可上移';
  410. }
  411. this.transaction = await this.db.beginTransaction();
  412. try {
  413. const sData = await this.transaction.update(this.tableName, { id: select.id, order: select[this.setting.order] - 1 });
  414. const pData = await this.transaction.update(this.tableName, { id: pre.id, order: pre[this.setting.order] + 1 });
  415. await this.transaction.commit();
  416. this.transaction = null;
  417. } catch (err) {
  418. await this.transaction.rollback();
  419. this.transaction = null;
  420. throw err;
  421. }
  422. const resultData = await this.getDataByParentAndOrder(mid, select[this.setting.pid], [select[this.setting.order], pre[this.setting.order]]);
  423. return { update: resultData };
  424. }
  425. /**
  426. * 下移节点
  427. *
  428. * @param {Number} mid - master id
  429. * @param {Number} kid - 选中节点id
  430. * @return {Array} - 发生改变的数据
  431. */
  432. async downMoveNode(mid, kid) {
  433. if (!mid || !kid) return null;
  434. const select = await this.getDataByKid(mid, kid);
  435. if (!select) {
  436. throw '下移节点数据错误';
  437. }
  438. const next = await this.getDataByParentAndOrder(mid, select[this.setting.pid], select[this.setting.order] + 1);
  439. if (!next) {
  440. throw '节点不可下移';
  441. }
  442. this.transaction = await this.db.beginTransaction();
  443. try {
  444. const sData = await this.transaction.update(this.tableName, { id: select.id, order: select[this.setting.order] + 1 });
  445. const pData = await this.transaction.update(this.tableName, { id: next.id, order: next[this.setting.order] - 1 });
  446. await this.transaction.commit();
  447. this.transaction = null;
  448. } catch (err) {
  449. await this.transaction.rollback();
  450. this.transaction = null;
  451. throw err;
  452. }
  453. const resultData = await this.getDataByParentAndOrder(mid, select[this.setting.pid], [select[this.setting.order], next[this.setting.order]]);
  454. return { update: resultData };
  455. }
  456. /**
  457. * 升级selectData, 同步修改所有子节点
  458. * @param {Object} selectData - 升级操作,选中节点
  459. * @return {Object}
  460. * @private
  461. */
  462. async _syncUplevelChildren(select) {
  463. this.initSqlBuilder();
  464. this.sqlBuilder.setAndWhere(this.setting.mid, {
  465. value: select[this.setting.mid],
  466. operate: '=',
  467. });
  468. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  469. value: this.db.escape(select[this.setting.fullPath] + '-%'),
  470. operate: 'like',
  471. });
  472. this.sqlBuilder.setUpdateData(this.setting.level, {
  473. value: 1,
  474. selfOperate: '-',
  475. });
  476. this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  477. value: [this.setting.fullPath, this.db.escape(select[this.setting.pid] + '.'), this.db.escape('')],
  478. literal: 'Replace',
  479. });
  480. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  481. const data = await this.transaction.query(sql, sqlParam);
  482. return data;
  483. }
  484. /**
  485. * 选中节点的后兄弟节点,全部变为当前节点的子节点
  486. * @param {Object} selectData - 选中节点
  487. * @return {Object}
  488. * @private
  489. */
  490. async _syncUpLevelNexts(select) {
  491. // 查询selectData的lastChild
  492. const lastChild = await this.getLastChildData(select[this.setting.mid], select[this.setting.kid]);
  493. const nexts = await this.getNextsData(select[this.setting.mid], select[this.setting.pid], select[this.setting.order]);
  494. if (nexts && nexts.length > 0) {
  495. // 修改nextsData pid, 排序
  496. this.initSqlBuilder();
  497. this.sqlBuilder.setUpdateData(this.setting.pid, {
  498. value: select[this.setting.kid],
  499. });
  500. const orderInc = lastChild ? lastChild[this.setting.order] - select[this.setting.order] : - select[this.setting.order];
  501. this.sqlBuilder.setUpdateData(this.setting.order, {
  502. value: Math.abs(orderInc),
  503. selfOperate: orderInc > 0 ? '+' : '-',
  504. });
  505. this.sqlBuilder.setAndWhere(this.setting.mid, {
  506. value: select[this.setting.mid],
  507. operate: '=',
  508. });
  509. this.sqlBuilder.setAndWhere(this.setting.pid, {
  510. value: select[this.setting.pid],
  511. operate: '=',
  512. });
  513. this.sqlBuilder.setAndWhere(this.setting.order, {
  514. value: select[this.setting.order],
  515. operate: '>',
  516. });
  517. const [sql1, sqlParam1] = this.sqlBuilder.build(this.tableName, 'update');
  518. await this.transaction.query(sql1, sqlParam1);
  519. // 选中节点 is_leaf应为false
  520. if (select.is_leaf) {
  521. const updateData = { id: select.id, is_leaf: false };
  522. await this.transaction.update(this.tableName, updateData);
  523. }
  524. // 修改nextsData及其子节点的full_path
  525. const oldSubStr = this.db.escape(select[this.setting.pid] + '.');
  526. const newSubStr = this.db.escape(select[this.setting.kid] + '.');
  527. const sqlArr = [];
  528. sqlArr.push('Update ?? SET `full_path` = Replace(`full_path`,' + oldSubStr + ',' + newSubStr + ') Where');
  529. sqlArr.push('(`' + this.setting.mid + '` = ' + select[this.setting.mid] + ')');
  530. sqlArr.push(' And (');
  531. for (const data of nexts) {
  532. sqlArr.push('`' + this.setting.fullPath + '` Like ' + this.db.escape(data[this.setting.fullPath] + '%'));
  533. if (nexts.indexOf(data) < nexts.length - 1) {
  534. sqlArr.push(' Or ');
  535. }
  536. }
  537. sqlArr.push(')');
  538. const sql = sqlArr.join('');
  539. const resultData = await this.transaction.query(sql, [this.tableName]);
  540. return resultData;
  541. }
  542. }
  543. /**
  544. * 升级节点
  545. *
  546. * @param {Number} tenderId - 标段id
  547. * @param {Number} selectId - 选中节点id
  548. * @return {Array} - 发生改变的数据
  549. */
  550. async upLevelNode(mid, kid) {
  551. if ((mid <= 0) || (kid <= 0)) return [];
  552. const select = await this.getDataByKid(mid, kid);
  553. if (!select) throw '升级节点数据错误';
  554. const parent = await this.getDataByKid(mid, select[this.setting.pid]);
  555. if (!parent) throw '升级节点数据错误';
  556. this.transaction = await this.db.beginTransaction();
  557. const newFullPath = select[this.setting.fullPath].replace(select[this.setting.pid] + '.', '');
  558. try {
  559. // 选中节点--父节点 选中节点为firstChild时,修改is_leaf
  560. if (select[this.setting.order] === 1) {
  561. await this.transaction.update(this.tableName, {
  562. id: parent.id,
  563. is_leaf: true,
  564. });
  565. }
  566. // 选中节点--父节点--全部后兄弟节点 order+1
  567. await this._updateChildrenOrder(mid, parent[this.setting.pid], parent[this.setting.order] + 1);
  568. //await this._updateSelectNextsOrder(parent);
  569. // 选中节点 修改pid, order, full_path, level, is_leaf, 清空计算项
  570. const updateData = { id: select.id };
  571. updateData[this.setting.pid] = parent[this.setting.pid];
  572. updateData[this.setting.order] = parent[this.setting.order] + 1;
  573. updateData[this.setting.level] = select[this.setting.level] - 1;
  574. updateData[this.setting.fullPath] = newFullPath;
  575. const nexts = await this.getNextsData(mid, parent[this.setting.kid], select[this.setting.order]);
  576. if (nexts.length > 0) {
  577. updateData.is_leaf = true;
  578. // updateData.unit_price = null;
  579. // updateData.quantity = null;
  580. // updateData.total_price = null;
  581. // updateData.deal_qty = null;
  582. // updateData.deal_tp = null;
  583. }
  584. await this.transaction.update(this.tableName, updateData);
  585. // 选中节点--全部子节点(含孙) level-1, full_path变更
  586. await this._syncUplevelChildren(select);
  587. // 选中节点--全部后兄弟节点 收编为子节点 修改pid, order, full_path
  588. await this._syncUpLevelNexts(select);
  589. await this.transaction.commit();
  590. this.transaction = null;
  591. } catch (err) {
  592. await this.transaction.rollback();
  593. this.transaction = null;
  594. throw err;
  595. }
  596. // 查询修改的数据
  597. const resultData1 = await this.getDataByFullPath(mid, newFullPath + '%');
  598. const resultData2 = await this.getNextsData(mid, parent[this.setting.pid], parent[this.setting.order] - 1);
  599. return { update: resultData1.concat(resultData2) };
  600. }
  601. /**
  602. * 降级selectData, 同步修改所有子节点
  603. * @param {Object} selectData - 选中节点
  604. * @param {Object} preData - 选中节点的前一节点(降级后为父节点)
  605. * @return {Promise<*>}
  606. * @private
  607. */
  608. async _syncDownlevelChildren(select, pre) {
  609. this.initSqlBuilder();
  610. this.sqlBuilder.setAndWhere(this.setting.mid, {
  611. value: select[this.setting.mid],
  612. operate: '=',
  613. });
  614. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  615. value: this.db.escape(select[this.setting.fullPath] + '-%'),
  616. operate: 'like',
  617. });
  618. this.sqlBuilder.setUpdateData(this.setting.level, {
  619. value: 1,
  620. selfOperate: '+',
  621. });
  622. this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  623. value: [this.setting.fullPath, this.db.escape(select[this.setting.kid] + '.'), this.db.escape(pre[this.setting.kid] + '.' + select[this.setting.kid] + '.')],
  624. literal: 'Replace',
  625. });
  626. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  627. const data = await this.transaction.query(sql, sqlParam);
  628. return data;
  629. }
  630. /**
  631. * 降级节点
  632. *
  633. * @param {Number} tenderId - 标段id
  634. * @param {Number} selectId - 选中节点id
  635. * @return {Array} - 发生改变的数据
  636. */
  637. async downLevelNode(mid, kid) {
  638. if ((mid <= 0) || (kid <= 0)) return [];
  639. const select = await this.getDataByKid(mid, kid);
  640. if (!select) throw '降级节点数据错误';
  641. const pre = await this.getDataByParentAndOrder(mid, select[this.setting.pid], select[this.setting.order] - 1);
  642. if (!pre) throw '节点不可降级';
  643. const preLastChild = await this.getLastChildData(mid, pre[this.setting.kid]);
  644. this.transaction = await this.db.beginTransaction();
  645. const orgLastPath = select[this.setting.level] === 1 ? select[this.setting.kid] : '.' + select[this.setting.kid];
  646. const newLastPath = select[this.setting.level] === 1 ? pre[this.setting.kid] + '.' + select[this.setting.kid] : '.' + pre[this.setting.kid] + '.' + select[this.setting.kid];
  647. const newFullPath = select.full_path.replace(orgLastPath, newLastPath);
  648. try {
  649. // 选中节点--全部后节点 order--
  650. await this._updateChildrenOrder(mid, select[this.setting.pid], select[this.setting.order] + 1, -1);
  651. // 选中节点 修改pid, level, order, full_path
  652. const updateData = { id: select.id };
  653. updateData[this.setting.pid] = pre[this.setting.kid];
  654. updateData[this.setting.order] = preLastChild ? preLastChild[this.setting.order] + 1 : 1;
  655. updateData[this.setting.level] = select[this.setting.level] + 1;
  656. updateData[this.setting.fullPath] = newFullPath;
  657. await this.transaction.update(this.tableName, updateData);
  658. // 选中节点--全部子节点(含孙) level++, full_path
  659. await this._syncDownlevelChildren(select, pre);
  660. // 选中节点--前兄弟节点 is_leaf应为false, 清空计算相关字段
  661. const updateData2 = { id: pre.id };
  662. updateData2[this.setting.isLeaf] = false;
  663. // updateData2.unit_price = null;
  664. // updateData2.quantity = null;
  665. // updateData2.total_price = null;
  666. // updateData2.deal_qty = null;
  667. // updateData2.deal_tp = null;
  668. await this.transaction.update(this.tableName, updateData2);
  669. await this.transaction.commit();
  670. this.transaction = null;
  671. } catch (err) {
  672. await this.transaction.rollback();
  673. this.transaction = null;
  674. throw err;
  675. }
  676. // 查询修改的数据
  677. // 选中节点及子节点
  678. const resultData1 = await this.getDataByFullPath(mid, newFullPath + '%');
  679. // 选中节点--原前兄弟节点&全部后兄弟节点
  680. const resultData2 = await this.getNextsData(mid, pre[this.setting.pid], pre[this.setting.order] - 1);
  681. return { update: resultData1.concat(resultData2) };
  682. }
  683. /**
  684. * 过滤data中update方式不可提交的字段
  685. * @param {Number} id - 主键key
  686. * @param {Object} data
  687. * @return {Object<{id: *}>}
  688. * @private
  689. */
  690. _filterUpdateInvalidField(id, data) {
  691. const result = {id: id};
  692. for (const prop in data) {
  693. if (this.readOnlyFields.indexOf(prop) === -1) {
  694. result[prop] = data[prop];
  695. }
  696. }
  697. return result;
  698. }
  699. /**
  700. * 提交多条数据 - 不影响计算等未提交项
  701. * @param {Number} tenderId - 标段id
  702. * @param {Array} datas - 提交数据
  703. * @return {Array} - 提交后的数据
  704. */
  705. async updateInfos(mid, datas) {
  706. if (mid <= 0) throw '数据错误';
  707. if (Array.isArray(datas)) {
  708. const updateDatas = [];
  709. for (const d of datas) {
  710. if (mid !== d[this.setting.mid]) throw '提交数据错误';
  711. const node = await this.getDataById(d.id);
  712. if (!node || mid !== node[this.setting.mid] || d[this.setting.kid] !== node[this.setting.kid]) throw '提交数据错误';
  713. updateDatas.push(this._filterUpdateInvalidField(node.id, d));
  714. }
  715. await this.db.updateRows(this.tableName, updateDatas);
  716. const resultData = await this.getDataById(this._.map(datas, 'id'));
  717. return resultData;
  718. } else {
  719. if (mid !== datas[this.setting.mid]) throw '提交数据错误';
  720. const node = await this.getDataById(datas.id);
  721. if (!node || mid !== node[this.setting.mid] || datas[this.setting.kid] !== node[this.setting.kid]) throw '提交数据错误';
  722. const updateData = this._filterUpdateInvalidField(node.id, datas);
  723. await this.db.update(this.tableName, updateData);
  724. return await this.getDataById(datas.id);
  725. }
  726. }
  727. }
  728. module.exports = TreeService;