base_tree_service.js 39 KB

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