ledger.js 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837
  1. 'use strict';
  2. /**
  3. * 标段--台账 数据模型
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/12/1
  7. * @version
  8. */
  9. const needField = {
  10. id: 'ledger_id',
  11. pid: 'ledger_pid',
  12. order: 'order',
  13. level: 'level',
  14. fullPath: 'full_path',
  15. isLeaf: 'is_leaf',
  16. };
  17. const keyFields = {
  18. table: ['id'],
  19. index: ['tender_id', 'ledger_id'],
  20. };
  21. // 以下字段仅可通过树结构操作改变,不可直接通过update方式从接口提交,发现时过滤
  22. const readOnlyFields = ['id', 'tender_id', 'ledger_id', 'ledger_pid', 'order', 'level', 'full_path', 'is_leaf'];
  23. const calcFields = ['quantity', 'unit_price', 'total_price', 'deal_qty', 'deal_tp'];
  24. const qtyFields = ['quantity', 'deal_qty', 'dgn_qty1', 'dgn_qty2'];
  25. const zeroRange = 0.0000000001;
  26. const rootId = -1;
  27. const keyPre = 'tender_node_maxId:';
  28. module.exports = app => {
  29. class Ledger extends app.BaseService {
  30. /**
  31. * 构造函数
  32. *
  33. * @param {Object} ctx - egg全局变量
  34. * @return {void}
  35. */
  36. constructor(ctx) {
  37. super(ctx);
  38. this.tableName = 'ledger';
  39. }
  40. /**
  41. * 新增数据(供内部或其他service类调用, controller不可直接使用)
  42. * @param {Array|Object} data - 新增数据
  43. * @param {Number} tenderId - 标段id
  44. * @param {Object} transaction - 新增事务
  45. * @return {Promise<boolean>} - {Promise<是否正确新增成功>}
  46. */
  47. async innerAdd(data, tenderId, transaction) {
  48. const datas = data instanceof Array ? data : [data];
  49. if (tenderId <= 0) {
  50. throw '标段id错误';
  51. }
  52. if (datas.length <= 0) {
  53. throw '插入数据为空';
  54. }
  55. if (!transaction) {
  56. throw '内部错误';
  57. }
  58. // 整理数据
  59. const insertData = [];
  60. for (const tmp of datas) {
  61. tmp.ledger_id = tmp.id;
  62. tmp.ledger_pid = tmp.pid;
  63. tmp.tender_id = tenderId;
  64. delete tmp.id;
  65. delete tmp.pid;
  66. insertData.push(tmp);
  67. }
  68. const operate = await transaction.insert(this.tableName, insertData);
  69. return operate.affectedRows === datas.length;
  70. }
  71. /**
  72. * 新增数据
  73. *
  74. * @param {Object} data - 新增的数据(可批量)
  75. * @param {Number} tenderId - 标段id
  76. * @return {Boolean} - 返回新增的结果
  77. */
  78. async add(data, tenderId) {
  79. this.transaction = await this.db.beginTransaction();
  80. let result = false;
  81. try {
  82. result = await this.innerAdd(data, tenderId, this.transaction);
  83. if (!result) {
  84. throw '新增数据错误';
  85. }
  86. await this.transaction.commit();
  87. } catch (error) {
  88. await this.transaction.rollback();
  89. result = false;
  90. }
  91. return result;
  92. }
  93. /**
  94. * 根据层级获取数据
  95. *
  96. * @param {Number} tenderId - 标段id
  97. * @param {Number} showLevel - 显示层数
  98. * @return {Array} - 返回数据
  99. */
  100. async getDataByTenderId(tenderId, showLevel = 4) {
  101. if (tenderId <= 0) {
  102. return [];
  103. }
  104. this.initSqlBuilder();
  105. this.sqlBuilder.setAndWhere('tender_id', {
  106. value: tenderId,
  107. operate: '=',
  108. });
  109. if (showLevel > 0) {
  110. this.sqlBuilder.setAndWhere('level', {
  111. value: showLevel,
  112. operate: '<=',
  113. });
  114. }
  115. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  116. const data = await this.db.query(sql, sqlParam);
  117. return data;
  118. }
  119. /**
  120. * 根据节点Id获取数据
  121. *
  122. * @param {Number} tenderId - 标段id
  123. * @param {Number} nodeId - 项目节/工程量清单节点id
  124. * @return {Object} - 返回查询到的节点数据
  125. */
  126. async getDataByNodeId(tenderId, nodeId) {
  127. if ((nodeId <= 0) || (tenderId <= 0)) {
  128. return undefined;
  129. }
  130. this.initSqlBuilder();
  131. this.sqlBuilder.setAndWhere('tender_id', {
  132. value: tenderId,
  133. operate: '=',
  134. });
  135. this.sqlBuilder.setAndWhere('ledger_id', {
  136. value: nodeId,
  137. operate: '=',
  138. });
  139. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  140. const data = await this.db.queryOne(sql, sqlParam);
  141. return data;
  142. }
  143. /**
  144. * 根据节点Id获取数据
  145. * @param {Number} tenderId - 标段Id
  146. * @param {Array} nodesIds - 节点Id
  147. * @return {Array}
  148. */
  149. async getDataByNodeIds(tenderId, nodesIds) {
  150. if (tenderId <= 0) {
  151. return [];
  152. }
  153. this.initSqlBuilder();
  154. this.sqlBuilder.setAndWhere('tender_id', {
  155. value: tenderId,
  156. operate: '=',
  157. });
  158. this.sqlBuilder.setAndWhere('ledger_id', {
  159. value: nodesIds,
  160. operate: 'in',
  161. });
  162. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  163. const data = await this.db.query(sql, sqlParam);
  164. return data;
  165. }
  166. /**
  167. * 根据主键id获取数据
  168. * @param {Array|Number} id - 主键id
  169. * @return {Promise<*>}
  170. */
  171. async getDataByIds(id) {
  172. const ids = id instanceof Array ? id : [id];
  173. this.initSqlBuilder();
  174. this.sqlBuilder.setAndWhere('id', {
  175. value: ids,
  176. operate: 'in',
  177. });
  178. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  179. const data = await this.db.query(sql, sqlParam);
  180. return data;
  181. }
  182. /**
  183. * 根据标准清单源检索
  184. * @param tenderId
  185. * @param source
  186. * @return {Promise<*>}
  187. */
  188. async getDataBySource(tenderId, source) {
  189. this.initSqlBuilder();
  190. this.sqlBuilder.setAndWhere('tender_id', {
  191. value: tenderId,
  192. operate: '=',
  193. });
  194. this.sqlBuilder.setAndWhere('source', {
  195. value: source,
  196. operate: '=',
  197. });
  198. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  199. const data = await this.db.query(sql, sqlParam);
  200. return data;
  201. }
  202. /**
  203. * 获取最末的子节点
  204. * @param {Number} tenderId - 标段id
  205. * @param {Number} pid - 父节点id
  206. * @return {Object}
  207. */
  208. async getLastChildData(tenderId, pid) {
  209. this.initSqlBuilder();
  210. this.sqlBuilder.setAndWhere('tender_id', {
  211. value: tenderId,
  212. operate: '=',
  213. });
  214. this.sqlBuilder.setAndWhere('ledger_pid', {
  215. value: pid,
  216. operate: '=',
  217. });
  218. this.sqlBuilder.orderBy = [['order', 'DESC']];
  219. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  220. const resultData = await this.db.queryOne(sql, sqlParam);
  221. return resultData;
  222. }
  223. /**
  224. * 根据 父节点id 和 节点排序order 获取数据
  225. *
  226. * @param {Number} tenderId - 标段id
  227. * @param {Number} pid - 父节点id
  228. * @param {Number|Array} order - 排序
  229. * @return {Object|Array} - 查询结果
  230. */
  231. async getDataByParentAndOrder(tenderId, pid, order) {
  232. if ((tenderId <= 0) || (pid <= 0) || (order <= 0)) {
  233. return undefined;
  234. }
  235. this.initSqlBuilder();
  236. this.sqlBuilder.setAndWhere('tender_id', {
  237. value: tenderId,
  238. operate: '=',
  239. });
  240. this.sqlBuilder.setAndWhere('ledger_pid', {
  241. value: pid,
  242. operate: '=',
  243. });
  244. if (order instanceof Array) {
  245. this.sqlBuilder.setAndWhere('order', {
  246. value: order,
  247. operate: 'in',
  248. });
  249. } else {
  250. this.sqlBuilder.setAndWhere('order', {
  251. value: order,
  252. operate: '=',
  253. });
  254. }
  255. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  256. let data;
  257. if (order instanceof Array) {
  258. data = await this.db.query(sql, sqlParam);
  259. } else {
  260. data = await this.db.queryOne(sql, sqlParam);
  261. }
  262. return data;
  263. }
  264. /**
  265. * 根据 父节点id 获取子节点
  266. * @param tenderId
  267. * @param nodeId
  268. * @return {Promise<*>}
  269. */
  270. async getChildrenByParentId(tenderId, nodeId) {
  271. if (tenderId <= 0 || !nodeId) {
  272. return undefined;
  273. }
  274. const nodeIds = nodeId instanceof Array ? nodeId : [nodeId];
  275. if (nodeIds.length === 0) {
  276. return [];
  277. }
  278. this.initSqlBuilder();
  279. this.sqlBuilder.setAndWhere('tender_id', {
  280. value: tenderId,
  281. operate: '=',
  282. });
  283. this.sqlBuilder.setAndWhere('ledger_pid', {
  284. value: nodeIds,
  285. operate: 'in',
  286. });
  287. this.sqlBuilder.orderBy = [['order', 'ASC']];
  288. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  289. const data = await this.db.query(sql, sqlParam);
  290. return data;
  291. }
  292. /**
  293. * 根据 父节点id 获取孙子节点
  294. * @param tenderId
  295. * @param nodeId
  296. * @return {Promise<void>}
  297. */
  298. async getPosterityByParentId(tenderId, nodeId) {
  299. if (tenderId <= 0 || !nodeId) {
  300. return undefined;
  301. }
  302. const node = await this.getDataByNodeId(tenderId, nodeId);
  303. this.initSqlBuilder();
  304. this.sqlBuilder.setAndWhere('tender_id', {
  305. value: tenderId,
  306. operate: '=',
  307. });
  308. this.sqlBuilder.setAndWhere('full_path', {
  309. value: this.db.escape(node.full_path + '.%'),
  310. operate: 'like',
  311. });
  312. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  313. const data = await this.db.query(sql, sqlParam);
  314. return data;
  315. }
  316. /**
  317. * 根据 父节点ID 和 节点排序order 获取全部后节点数据
  318. * @param {Number} tenderId - 标段id
  319. * @param {Number} pid - 父节点id
  320. * @param {Number} order - 排序
  321. * @return {Array}
  322. */
  323. async getNextsData(tenderId, pid, order) {
  324. if ((tenderId <= 0) || (order < 0)) {
  325. return undefined;
  326. }
  327. this.initSqlBuilder();
  328. this.sqlBuilder.setAndWhere('tender_id', {
  329. value: tenderId,
  330. operate: '=',
  331. });
  332. this.sqlBuilder.setAndWhere('ledger_pid', {
  333. value: pid,
  334. operate: '=',
  335. });
  336. this.sqlBuilder.setAndWhere('order', {
  337. value: order,
  338. operate: '>',
  339. });
  340. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  341. const data = await this.db.query(sql, sqlParam);
  342. return data;
  343. }
  344. /**
  345. * 根据full_path获取数据 full_path Like ‘1.2.3%’(传参full_path = '1.2.3%')
  346. * @param {Number} tenderId - 标段id
  347. * @param {String} full_path - 路径
  348. * @return {Promise<void>}
  349. */
  350. async getDataByFullPath(tenderId, full_path) {
  351. this.initSqlBuilder();
  352. this.sqlBuilder.setAndWhere('tender_id', {
  353. value: tenderId,
  354. operate: '=',
  355. });
  356. this.sqlBuilder.setAndWhere('full_path', {
  357. value: this.db.escape(full_path),
  358. operate: 'Like',
  359. });
  360. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  361. const resultData = await this.db.query(sql, sqlParam);
  362. return resultData;
  363. }
  364. /**
  365. * 根据full_path检索自己及所有父项
  366. * @param {Number} tenderId - 标段id
  367. * @param {Array|String} fullPath - 节点完整路径
  368. * @return {Promise<*>}
  369. * @private
  370. */
  371. async getFullLevelDataByFullPath(tenderId, fullPath) {
  372. const explodePath = this.ctx.helper.explodePath(fullPath);
  373. this.initSqlBuilder();
  374. this.sqlBuilder.setAndWhere('tender_id', {
  375. value: tenderId,
  376. operate: '=',
  377. });
  378. this.sqlBuilder.setAndWhere('full_path', {
  379. value: explodePath,
  380. operate: 'in',
  381. });
  382. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  383. const data = await this.db.query(sql, sqlParam);
  384. return data;
  385. }
  386. /**
  387. * 获取sql条件语句片段,仅供search、searchRange方法使用
  388. * @param {Object} where - 条件参数
  389. * @return {*[]}
  390. * e.g.
  391. * where = {type: 'And', value: 'A', operate: '=', fields: ['code', 'name']}
  392. * return [sql: 'And (?? = \'A\' Or ?? = \'A\')', sqlParam: ['code', name]]
  393. * @private
  394. */
  395. _getWhereString(where) {
  396. const sqlParam = [],
  397. sqlPart = [];
  398. const values = where.value instanceof Array ? where.value : [where.value];
  399. const fields = where.fields instanceof Array ? where.fields : [where.fields];
  400. for (const field of fields) {
  401. for (const v of values) {
  402. sqlPart.push('?? ' + where.operate + ' ' + v);
  403. sqlParam.push(field);
  404. }
  405. }
  406. const sql = ' ' + (where.type ? where.type : 'And') + ' (' + sqlPart.join(' OR ') + ')';
  407. return [sql, sqlParam];
  408. }
  409. /**
  410. * 搜索台账
  411. *
  412. * @param {Number} tenderId - 标段id
  413. * @param {Object} key - 查询信息
  414. * @return {Promise<void>}
  415. */
  416. async search(tenderId, key) {
  417. let sql = 'Select * From ?? Where';
  418. let sqlParam = [this.tableName];
  419. sql = sql + ' ?? = ' + tenderId;
  420. sqlParam.push('tender_id');
  421. const [sql1, sqlParam1] = this._getWhereString(key);
  422. sql = sql + sql1;
  423. sqlParam = sqlParam.concat(sqlParam1);
  424. return this.db.query(sql, sqlParam);
  425. }
  426. /**
  427. * 范围内搜索台账
  428. *
  429. * @param {Number} tenderId - 标段id
  430. * @param {Object} key - 查询信息
  431. * @param {Array} range - 查询范围
  432. * @return {Promise<void>}
  433. */
  434. async searchRange(tenderId, key, range) {
  435. let sql = 'Select * From ?? Where';
  436. let sqlParam = [this.tableName];
  437. sql = sql + ' ?? = ' + tenderId;
  438. sqlParam.push('tender_id');
  439. let [sql1, sqlParam1] = this._getWhereString(key);
  440. sql = sql + sql1;
  441. sqlParam = sqlParam.concat(sqlParam1);
  442. for (const r of range) {
  443. [sql1, sqlParam1] = this._getWhereString(r);
  444. sql = sql + sql1;
  445. sqlParam = sqlParam.concat(sqlParam1);
  446. }
  447. return this.db.query(sql, sqlParam);
  448. }
  449. /**
  450. * 统计子节点total_price
  451. * @param {Number} tenderId - 标段id
  452. * @param {Number} pid - 父节点id
  453. * @param {Number} order - order取值
  454. * @param {String} orderOperate - order比较操作符
  455. * @return {Promise<void>}
  456. */
  457. async addUpChildren(tenderId, pid, order, orderOperate) {
  458. this.initSqlBuilder();
  459. const sql = ['SELECT SUM(??) As value FROM ?? ', ' WHERE '];
  460. const sqlParam = ['total_price', this.tableName];
  461. sql.push(' ?? = ' + tenderId);
  462. sqlParam.push('tender_id');
  463. sql.push(' And ?? = ' + pid);
  464. sqlParam.push('ledger_pid');
  465. sql.push(' And ?? ' + orderOperate + ' ' + order);
  466. sqlParam.push('order');
  467. const result = await this.db.queryOne(sql.join(''), sqlParam);
  468. return result.value;
  469. }
  470. /**
  471. * 更新order
  472. * @param {Number} tenderId - 标段id
  473. * @param {Number} parentId - 父节点id
  474. * @param {Number} order - 自增起始order(含)
  475. * @param {Number} incre - 自增量
  476. * @return {Promise<*>}
  477. * @private
  478. */
  479. async _updateChildrenOrderAfter(tenderId, parentId, order, incre = 1) {
  480. this.initSqlBuilder();
  481. this.sqlBuilder.setAndWhere('tender_id', {
  482. value: tenderId,
  483. operate: '=',
  484. });
  485. this.sqlBuilder.setAndWhere('order', {
  486. value: order,
  487. operate: '>=',
  488. });
  489. this.sqlBuilder.setAndWhere('ledger_pid', {
  490. value: parentId,
  491. operate: '=',
  492. });
  493. this.sqlBuilder.setUpdateData('order', {
  494. value: Math.abs(incre),
  495. selfOperate: incre > 0 ? '+' : '-',
  496. });
  497. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  498. const data = await this.transaction.query(sql, sqlParam);
  499. return data;
  500. }
  501. /**
  502. * select的全部后兄弟节点,Order自增
  503. *
  504. * @param {Object} select - 选中的节点
  505. * @param {Number} incre - 自增值
  506. * @return {Array} - 自增后的数据
  507. * @private
  508. */
  509. async _updateSelectNextsOrder(select, incre = 1) {
  510. return await this._updateChildrenOrderAfter(select.tender_id, select.ledger_pid, select.order + 1, incre);
  511. }
  512. /**
  513. * 从数据库获取标段的最大节点id
  514. *
  515. * @param {Number} tenderId - 标段id
  516. * @return {Number}
  517. * @private
  518. */
  519. async _getMaxNodeId(tenderId) {
  520. const sql = 'SELECT Max(??) As max_id FROM ?? Where tender_id = ' + tenderId;
  521. const sqlParam = ['ledger_id', this.tableName];
  522. const queryResult = await this.db.queryOne(sql, sqlParam);
  523. return queryResult.max_id;
  524. }
  525. /**
  526. * 根据selectData, data 新增数据(新增为selectData的后项,该方法不可单独使用)
  527. *
  528. * @param {Number} tenderId - 标段id
  529. * @param {Object} selectData - 选中节点的数据
  530. * @param {Object} data - 新增节点的初始数据
  531. * @return {Object} - 新增结果
  532. * @private
  533. */
  534. async _addNodeData(tenderId, selectData, data) {
  535. if (tenderId <= 0) {
  536. return undefined;
  537. }
  538. if (!data) {
  539. data = {};
  540. }
  541. const cacheKey = keyPre + tenderId;
  542. let maxId = parseInt(await this.cache.get(cacheKey));
  543. if (!maxId) {
  544. maxId = await this._getMaxNodeId(tenderId);
  545. this.cache.set(cacheKey, maxId, 'EX', this.ctx.app.config.cacheTime);
  546. }
  547. data.tender_id = tenderId;
  548. data.ledger_id = maxId + 1;
  549. data.ledger_pid = selectData.ledger_pid;
  550. data.level = selectData.level;
  551. data.order = selectData.order + 1;
  552. data.full_path = selectData.full_path.replace('.' + selectData.ledger_id, '.' + data.ledger_id);
  553. data.is_leaf = true;
  554. const result = await this.transaction.insert(this.tableName, data);
  555. this.cache.set(cacheKey, maxId + 1, 'EX', this.ctx.app.config.cacheTime);
  556. return result;
  557. }
  558. /**
  559. * 根据parentData, data新增数据(新增为parentData的最后一个子项)
  560. * @param {Number} tenderId - 标段id
  561. * @param {Object} parentData - 父项数据
  562. * @param {Object} data - 新增节点,初始数据
  563. * @return {Promise<*>} - 新增结果
  564. * @private
  565. */
  566. async _addChildNodeData(tenderId, parentData, data) {
  567. if (tenderId <= 0) {
  568. return undefined;
  569. }
  570. if (!data) {
  571. data = {};
  572. }
  573. const pid = parentData ? parentData.ledger_id : rootId;
  574. const cacheKey = keyPre + tenderId;
  575. let maxId = parseInt(await this.cache.get(cacheKey));
  576. if (!maxId) {
  577. maxId = await this._getMaxNodeId(tenderId);
  578. }
  579. this.cache.set(cacheKey, maxId + 1, 'EX', this.ctx.app.config.cacheTime);
  580. data.tender_id = tenderId;
  581. data.ledger_id = maxId + 1;
  582. data.ledger_pid = pid;
  583. if (data.order === undefined) {
  584. data.order = 1;
  585. }
  586. data.level = parentData ? parentData.level + 1 : 1;
  587. data.full_path = parentData ? parentData.full_path + '.' + data.ledger_id : '' + data.ledger_id;
  588. if (data.is_leaf === undefined) {
  589. data.is_leaf = true;
  590. }
  591. const result = await this.transaction.insert(this.tableName, data);
  592. return [result, data];
  593. }
  594. /**
  595. * 根据parentData, data新增数据(自动排序)
  596. * @param tenderId
  597. * @param parentData
  598. * @param data
  599. * @return {Promise<void>}
  600. * @private
  601. */
  602. async _addChildAutoOrder(tenderId, parentData, data) {
  603. const self = this;
  604. const findPreData = function(list, a) {
  605. if (!list || list.length === 0) { return null; }
  606. for (let i = 0, iLen = list.length; i < iLen; i++) {
  607. if (self.ctx.helper.compareCode(list[i].code, a.code) > 0) {
  608. return i > 0 ? list[i - 1] : null;
  609. }
  610. }
  611. return list[list.length - 1];
  612. };
  613. const pid = parentData ? parentData.ledger_id : rootId;
  614. const children = await this.getChildrenByParentId(tenderId, pid);
  615. const preData = findPreData(children, data);
  616. const parent = null;
  617. if (!preData || children.indexOf(preData) < children.length - 1) {
  618. await this._updateChildrenOrderAfter(tenderId, pid, preData ? preData.order + 1 : 1);
  619. }
  620. data.order = preData ? preData.order + 1 : 1;
  621. const [addResult, node] = await this._addChildNodeData(tenderId, parentData, data);
  622. return [addResult, node];
  623. }
  624. /**
  625. * tenderId标段中, 在selectId后新增一个节点
  626. *
  627. * @param {Number} tenderId - 标段id
  628. * @param {Number} selectId - 选中节点id
  629. * @param {Object} data - 新增节点初始化数据
  630. * @return {Array} 新增后的数据,其他被修改的数据
  631. */
  632. async addNode(tenderId, selectId, data) {
  633. if ((tenderId <= 0) || (selectId <= 0)) {
  634. return [];
  635. }
  636. const selectData = await this.getDataByNodeId(tenderId, selectId);
  637. if (!selectData) {
  638. throw '新增节点数据错误';
  639. }
  640. if (!this.transaction) {
  641. this.transaction = await this.db.beginTransaction();
  642. }
  643. try {
  644. // 选中节点的所有后兄弟节点,order+1
  645. await this._updateSelectNextsOrder(selectData);
  646. // 数据库创建新增节点数据
  647. const newNode = await this._addNodeData(tenderId, selectData, data);
  648. if (!newNode) { throw '新增节点数据错误'; }
  649. await this.transaction.commit();
  650. } catch (err) {
  651. await this.transaction.rollback();
  652. this.transaction = null;
  653. throw err;
  654. }
  655. this.transaction = null;
  656. // 查询应返回的结果
  657. const createData = await this.getDataByParentAndOrder(selectData.tender_id, selectData.ledger_pid, [selectData.order + 1]);
  658. const updateData = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + 1);
  659. return { create: createData, update: updateData };
  660. }
  661. /**
  662. * 从标准数据中提取有效数据
  663. * @param {Object} stdData - 从标准库中查询所得
  664. * @returns {name, unit, source, code, b_code}
  665. * @private
  666. */
  667. _filterStdData(stdData) {
  668. const result = {
  669. name: stdData.name,
  670. unit: stdData.unit,
  671. source: stdData.source,
  672. };
  673. result.code = stdData.code ? stdData.code : '';
  674. result.b_code = stdData.b_code ? stdData.b_code : '';
  675. return result;
  676. }
  677. /**
  678. * 添加节点(来自标准清单)
  679. * @param {Number} tenderId
  680. * @param {Number} selectId
  681. * @param {Object} stdData
  682. * @return {Promise<*>}
  683. */
  684. async addStdNode(tenderId, selectId, stdData) {
  685. const newData = this._filterStdData(stdData);
  686. const result = await this.addNode(tenderId, selectId, newData);
  687. return result;
  688. }
  689. /**
  690. * 添加节点,并同步添加父节点
  691. * @param {Number} tenderId - 标段id
  692. * @param {Number} selectId - 选中节点id
  693. * @param {Object} stdData - 节点数据
  694. * @param {StandardLib} stdLib - 标准库
  695. * @return {Promise<void>}
  696. */
  697. async addStdNodeWithParent(tenderId, stdData, stdLib) {
  698. const fullLevel = await stdLib.getFullLevelDataByFullPath(stdData.list_id, stdData.full_path);
  699. fullLevel.sort(function(x, y) {
  700. return x.level - y.level;
  701. });
  702. let isNew = false,
  703. node,
  704. firstNew,
  705. updateParent,
  706. addResult;
  707. const expandIds = [];
  708. this.transaction = await this.db.beginTransaction();
  709. try {
  710. for (let i = 0, len = fullLevel.length; i < len; i++) {
  711. const stdNode = fullLevel[i];
  712. if (isNew) {
  713. const newData = this._filterStdData(stdNode);
  714. newData.is_leaf = (i === len - 1);
  715. [addResult, node] = await this._addChildNodeData(tenderId, node, newData);
  716. } else {
  717. const parent = node;
  718. node = await this.getDataByCondition({
  719. tender_id: tenderId,
  720. ledger_pid: parent ? parent.ledger_id : rootId,
  721. code: stdNode.code,
  722. name: stdNode.name,
  723. });
  724. if (!node) {
  725. isNew = true;
  726. const newData = this._filterStdData(stdNode);
  727. newData.is_leaf = (i === len - 1);
  728. [addResult, node] = await this._addChildAutoOrder(tenderId, parent, newData);
  729. if (parent && parent.is_leaf) {
  730. await this.transaction.update(this.tableName, { id: parent.id, is_leaf: false });
  731. updateParent = parent;
  732. }
  733. firstNew = node;
  734. } else {
  735. expandIds.push(node.ledger_id);
  736. }
  737. }
  738. }
  739. await this.transaction.commit();
  740. } catch (err) {
  741. await this.transaction.rollback();
  742. throw err;
  743. }
  744. // 查询应返回的结果
  745. let createData = [],
  746. updateData = [];
  747. if (firstNew) {
  748. createData = await this.getDataByFullPath(tenderId, firstNew.full_path + '%');
  749. updateData = await this.getNextsData(tenderId, firstNew.ledger_pid, firstNew.order);
  750. if (updateParent) {
  751. updateData.push(await this.getDataByCondition({ id: updateParent.id }));
  752. }
  753. }
  754. const expandData = await this.getChildrenByParentId(tenderId, expandIds);
  755. return { create: createData, update: updateData, expand: expandData };
  756. }
  757. /**
  758. * 删除节点
  759. * @param {Number} tenderId - 标段id
  760. * @param {Object} deleteData - 删除节点数据
  761. * @return {Promise<*>}
  762. * @private
  763. */
  764. async _deleteNodeData(tenderId, deleteData) {
  765. this.initSqlBuilder();
  766. this.sqlBuilder.setAndWhere('tender_id', {
  767. value: tenderId,
  768. operate: '=',
  769. });
  770. this.sqlBuilder.setAndWhere('full_path', {
  771. value: this.db.escape(deleteData.full_path + '%'),
  772. operate: 'Like',
  773. });
  774. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'delete');
  775. const result = await this.transaction.query(sql, sqlParam);
  776. return result;
  777. }
  778. /**
  779. * tenderId标段中, 删除选中节点及其子节点
  780. *
  781. * @param {Number} tenderId - 标段id
  782. * @param {Number} selectId - 选中节点id
  783. * @return {Array} - 被删除的数据
  784. */
  785. async deleteNode(tenderId, selectId) {
  786. if ((tenderId <= 0) || (selectId <= 0)) {
  787. return [];
  788. }
  789. const selectData = await this.getDataByNodeId(tenderId, selectId);
  790. if (!selectData) {
  791. throw '删除节点数据错误';
  792. }
  793. const parentData = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  794. this.transaction = await this.db.beginTransaction();
  795. let deleteData = [];
  796. try {
  797. // 获取将要被删除的数据
  798. deleteData = await this.getDataByFullPath(tenderId, selectData.full_path + '%');
  799. // 删除
  800. const operate = await this._deleteNodeData(tenderId, selectData);
  801. // 选中节点--父节点 只有一个子节点时,应升级is_leaf
  802. if (parentData) {
  803. const count = await this.db.count(this.tableName, { tender_id: tenderId, ledger_pid: selectData.ledger_pid });
  804. if (count === 1) {
  805. await this.transaction.update(this.tableName, { id: parentData.id, is_leaf: true });
  806. }
  807. }
  808. // 选中节点--全部后节点 order--
  809. await this._updateSelectNextsOrder(selectData, -1);
  810. // 删除部位明细
  811. await this.transaction.delete(this.ctx.service.pos.tableName, { tid: tenderId, lid: this._.map(deleteData, 'id') });
  812. await this.ctx.service.pos.deletePosData(this.transaction, tenderId, this._.map(deleteData, 'id'));
  813. await this.transaction.commit();
  814. } catch (err) {
  815. deleteData = [];
  816. await this.transaction.rollback();
  817. throw err;
  818. }
  819. // 查询结果
  820. let updateData = [];
  821. if (deleteData.length > 0) {
  822. updateData = await this.getNextsData(tenderId, selectData.ledger_pid, selectData.order - 1);
  823. updateData = updateData ? updateData : [];
  824. if (selectData.ledger_pid !== rootId) {
  825. const updateData1 = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  826. if (updateData1.is_leaf !== parentData.is_leaf) {
  827. updateData.push(updateData1);
  828. }
  829. }
  830. }
  831. return { delete: deleteData, update: updateData };
  832. }
  833. /**
  834. * tenderId标段中, 选中节点selectId上移
  835. *
  836. * @param {Number} tenderId - 标段id
  837. * @param {Number} selectId - 选中节点id
  838. * @return {Array} - 发生改变的数据
  839. */
  840. async upMoveNode(tenderId, selectId) {
  841. if ((tenderId <= 0) || (selectId <= 0)) {
  842. return [];
  843. }
  844. const selectData = await this.getDataByNodeId(tenderId, selectId);
  845. if (!selectData) {
  846. throw '上移节点数据错误';
  847. }
  848. const preData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, selectData.order - 1);
  849. if (!preData) {
  850. throw '节点不可上移';
  851. }
  852. this.transaction = await this.db.beginTransaction();
  853. try {
  854. const sData = await this.transaction.update(this.tableName, { id: selectData.id, order: selectData.order - 1 });
  855. const pData = await this.transaction.update(this.tableName, { id: preData.id, order: preData.order + 1 });
  856. await this.transaction.commit();
  857. } catch (err) {
  858. await this.transaction.rollback();
  859. throw err;
  860. }
  861. const resultData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, [selectData.order, preData.order]);
  862. return { update: resultData };
  863. }
  864. /**
  865. * tenderId标段中, 选中节点selectId下移
  866. *
  867. * @param {Number} tenderId - 标段id
  868. * @param {Number} selectId - 选中节点id
  869. * @return {Array} - 发生改变的数据
  870. */
  871. async downMoveNode(tenderId, selectId) {
  872. if ((tenderId <= 0) || (selectId <= 0)) {
  873. return [];
  874. }
  875. const selectData = await this.getDataByNodeId(tenderId, selectId);
  876. if (!selectData) {
  877. throw '下移节点数据错误';
  878. }
  879. const nextData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, selectData.order + 1);
  880. if (!nextData) {
  881. throw '节点不可下移';
  882. }
  883. this.transaction = await this.db.beginTransaction();
  884. try {
  885. const sData = await this.transaction.update(this.tableName, { id: selectData.id, order: selectData.order + 1 });
  886. const pData = await this.transaction.update(this.tableName, { id: nextData.id, order: nextData.order - 1 });
  887. await this.transaction.commit();
  888. } catch (err) {
  889. await this.transaction.rollback();
  890. throw err;
  891. }
  892. const resultData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, [selectData.order, nextData.order]);
  893. return { update: resultData };
  894. }
  895. /**
  896. * 升级selectData, 同步修改所有子节点
  897. * @param {Object} selectData - 升级操作,选中节点
  898. * @return {Object}
  899. * @private
  900. */
  901. async _syncUplevelChildren(selectData) {
  902. this.initSqlBuilder();
  903. this.sqlBuilder.setAndWhere('tender_id', {
  904. value: selectData.tender_id,
  905. operate: '=',
  906. });
  907. this.sqlBuilder.setAndWhere('full_path', {
  908. value: this.db.escape(selectData.full_path + '.%'),
  909. operate: 'like',
  910. });
  911. this.sqlBuilder.setUpdateData('level', {
  912. value: 1,
  913. selfOperate: '-',
  914. });
  915. this.sqlBuilder.setUpdateData('full_path', {
  916. value: ['`full_path`', this.db.escape(selectData.ledger_pid + '.'), this.db.escape('')],
  917. literal: 'Replace',
  918. });
  919. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  920. const data = await this.transaction.query(sql, sqlParam);
  921. return data;
  922. }
  923. /**
  924. * 选中节点的后兄弟节点,全部变为当前节点的子节点
  925. * @param {Object} selectData - 选中节点
  926. * @return {Object}
  927. * @private
  928. */
  929. async _syncUpLevelNexts(selectData) {
  930. // 查询selectData的lastChild
  931. const lastChildData = await this.getLastChildData(selectData.tender_id, selectData.ledger_id);
  932. const nextsData = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order);
  933. if (nextsData && nextsData.length > 0) {
  934. // 修改nextsData pid, 排序
  935. this.initSqlBuilder();
  936. this.sqlBuilder.setUpdateData('ledger_pid', {
  937. value: selectData.ledger_id,
  938. });
  939. const orderInc = lastChildData ? lastChildData.order - selectData.order : -selectData.order;
  940. this.sqlBuilder.setUpdateData('order', {
  941. value: Math.abs(orderInc),
  942. selfOperate: orderInc > 0 ? '+' : '-',
  943. });
  944. this.sqlBuilder.setAndWhere('ledger_pid', {
  945. value: selectData.ledger_pid,
  946. operate: '=',
  947. });
  948. this.sqlBuilder.setAndWhere('order', {
  949. value: selectData.order,
  950. operate: '>',
  951. });
  952. const [sql1, sqlParam1] = this.sqlBuilder.build(this.tableName, 'update');
  953. await this.transaction.query(sql1, sqlParam1);
  954. // 选中节点 is_leaf应为false
  955. if (selectData.is_leaf) {
  956. const updateData = { id: selectData.id,
  957. is_leaf: false,
  958. };
  959. await this.transaction.update(this.tableName, updateData);
  960. }
  961. // 修改nextsData及其子节点的full_path
  962. const oldSubStr = this.db.escape(selectData.ledger_pid + '.');
  963. const newSubStr = this.db.escape(selectData.ledger_id + '.');
  964. const sqlArr = [];
  965. sqlArr.push('Update ?? SET `full_path` = Replace(`full_path`,' + oldSubStr + ',' + newSubStr + ') Where');
  966. sqlArr.push('(`tender_id` = ' + selectData.tender_id + ')');
  967. sqlArr.push(' And (');
  968. for (const data of nextsData) {
  969. sqlArr.push('`full_path` Like ' + this.db.escape(data.full_path + '%'));
  970. if (nextsData.indexOf(data) < nextsData.length - 1) {
  971. sqlArr.push(' Or ');
  972. }
  973. }
  974. sqlArr.push(')');
  975. const sql = sqlArr.join('');
  976. const resultData = await this.transaction.query(sql, [this.tableName]);
  977. return resultData;
  978. }
  979. }
  980. /**
  981. * 升级节点
  982. *
  983. * @param {Number} tenderId - 标段id
  984. * @param {Number} selectId - 选中节点id
  985. * @return {Array} - 发生改变的数据
  986. */
  987. async upLevelNode(tenderId, selectId) {
  988. if ((tenderId <= 0) || (selectId <= 0)) {
  989. return [];
  990. }
  991. const selectData = await this.getDataByNodeId(tenderId, selectId);
  992. if (!selectData) {
  993. throw '升级节点数据错误';
  994. }
  995. const parentData = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  996. if (!parentData) {
  997. throw '升级节点数据错误';
  998. }
  999. this.transaction = await this.db.beginTransaction();
  1000. const newFullPath = selectData.full_path.replace(selectData.ledger_pid + '.', '');
  1001. try {
  1002. // 选中节点--父节点 选中节点为firstChild时,修改is_leaf
  1003. if (selectData.order === 1) {
  1004. await this.transaction.update(this.tableName, {
  1005. id: parentData.id,
  1006. is_leaf: true,
  1007. });
  1008. }
  1009. // 选中节点--父节点--全部后兄弟节点 order+1
  1010. await this._updateSelectNextsOrder(parentData);
  1011. // 选中节点 修改pid, order, full_path
  1012. const updateData = { id: selectData.id,
  1013. ledger_pid: parentData.ledger_pid,
  1014. order: parentData.order + 1,
  1015. level: selectData.level - 1,
  1016. full_path: newFullPath,
  1017. };
  1018. await this.transaction.update(this.tableName, updateData);
  1019. // 选中节点--全部子节点(含孙) level-1, full_path变更
  1020. await this._syncUplevelChildren(selectData);
  1021. // 选中节点--全部后兄弟节点 收编为子节点 修改pid, order, full_path
  1022. await this._syncUpLevelNexts(selectData);
  1023. await this.transaction.commit();
  1024. } catch (err) {
  1025. await this.transaction.rollback();
  1026. throw err;
  1027. }
  1028. // 查询修改的数据
  1029. const resultData1 = await this.getDataByFullPath(tenderId, newFullPath + '%');
  1030. const resultData2 = await this.getNextsData(tenderId, parentData.ledger_pid, parentData.order + 1);
  1031. // 默认原Parent被刷新过,不核对total_price修改
  1032. const preParent = await this.getDataByNodeId(tenderId, parentData.ledger_id);
  1033. resultData2.push(preParent);
  1034. return { update: resultData1.concat(resultData2) };
  1035. }
  1036. /**
  1037. * 降级selectData, 同步修改所有子节点
  1038. * @param {Object} selectData - 选中节点
  1039. * @param {Object} preData - 选中节点的前一节点(降级后为父节点)
  1040. * @return {Promise<*>}
  1041. * @private
  1042. */
  1043. async _syncDownlevelChildren(selectData, preData) {
  1044. this.initSqlBuilder();
  1045. this.sqlBuilder.setAndWhere('tender_id', {
  1046. value: selectData.tender_id,
  1047. operate: '=',
  1048. });
  1049. this.sqlBuilder.setAndWhere('full_path', {
  1050. value: this.db.escape(selectData.full_path + '.%'),
  1051. operate: 'like',
  1052. });
  1053. this.sqlBuilder.setUpdateData('level', {
  1054. value: 1,
  1055. selfOperate: '+',
  1056. });
  1057. this.sqlBuilder.setUpdateData('full_path', {
  1058. value: ['`full_path`', this.db.escape('.' + selectData.ledger_id), this.db.escape('.' + preData.ledger_id + '.' + selectData.ledger_id)],
  1059. literal: 'Replace',
  1060. });
  1061. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  1062. const data = await this.transaction.query(sql, sqlParam);
  1063. return data;
  1064. }
  1065. /**
  1066. * 降级节点
  1067. *
  1068. * @param {Number} tenderId - 标段id
  1069. * @param {Number} selectId - 选中节点id
  1070. * @return {Array} - 发生改变的数据
  1071. */
  1072. async downLevelNode(tenderId, selectId) {
  1073. if ((tenderId <= 0) || (selectId <= 0)) {
  1074. return [];
  1075. }
  1076. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1077. if (!selectData) {
  1078. throw '降级节点数据错误';
  1079. }
  1080. const preData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, selectData.order - 1);
  1081. if (!preData) {
  1082. throw '节点不可降级';
  1083. }
  1084. const preLastChildData = await this.getLastChildData(tenderId, preData.ledger_id);
  1085. this.transaction = await this.db.beginTransaction();
  1086. const orgLastPath = selectData.level === 1 ? selectData.ledger_id : '.' + selectData.ledger_id;
  1087. const newLastPath = selectData.level === 1 ? preData.ledger_id + '.' + selectData.ledger_id : '.' + preData.ledger_id + '.' + selectData.ledger_id;
  1088. const newFullPath = selectData.full_path.replace(orgLastPath, newLastPath);
  1089. try {
  1090. // 选中节点--全部后节点 order--
  1091. await this._updateSelectNextsOrder(selectData, -1);
  1092. // 选中节点 修改pid, level, order, full_path
  1093. const updateData = {
  1094. id: selectData.id,
  1095. ledger_pid: preData.ledger_id,
  1096. order: preLastChildData ? preLastChildData.order + 1 : 1,
  1097. level: selectData.level + 1,
  1098. full_path: newFullPath,
  1099. };
  1100. await this.transaction.update(this.tableName, updateData);
  1101. // 选中节点--全部子节点(含孙) level++, full_path
  1102. await this._syncDownlevelChildren(selectData, preData);
  1103. // 选中节点--前兄弟节点 is_leaf应为false
  1104. if (preData.is_leaf) {
  1105. const updateData2 = {
  1106. id: preData.id,
  1107. is_leaf: false,
  1108. };
  1109. await this.transaction.update(this.tableName, updateData2);
  1110. }
  1111. await this.transaction.commit();
  1112. } catch (err) {
  1113. await this.transaction.rollback();
  1114. throw err;
  1115. }
  1116. // 查询修改的数据
  1117. // 选中节点及子节点
  1118. const resultData1 = await this.getDataByFullPath(tenderId, newFullPath + '%');
  1119. // 选中节点--原前兄弟节点&全部后兄弟节点
  1120. const queryOrder = (preData.is_leaf || this.ctx.helper.checkZero(selectData.total_price)) ? preData.order - 1 : preData.order;
  1121. const resultData2 = await this.getNextsData(tenderId, preData.ledger_pid, queryOrder);
  1122. return { update: resultData1.concat(resultData2) };
  1123. }
  1124. /**
  1125. * 过滤data中update方式不可提交的字段
  1126. * @param {Number} id - 主键key
  1127. * @param {Object} data
  1128. * @return {Object<{id: *}>}
  1129. * @private
  1130. */
  1131. _filterUpdateInvalidField(id, data) {
  1132. const result = {
  1133. id,
  1134. };
  1135. for (const prop in data) {
  1136. if (readOnlyFields.indexOf(prop) === -1) {
  1137. result[prop] = data[prop];
  1138. }
  1139. }
  1140. return result;
  1141. }
  1142. /**
  1143. * newData中,以orgData为基准,过滤掉orgData中未定义或值相等的部分
  1144. * @param {Object} orgData
  1145. * @param {Object} newData
  1146. * @private
  1147. */
  1148. _filterChangedField(orgData, newData) {
  1149. const result = {};
  1150. let bChanged = false;
  1151. for (const prop in orgData) {
  1152. if (newData[prop] !== orgData[prop]) {
  1153. result[prop] = newData[prop];
  1154. bChanged = true;
  1155. }
  1156. }
  1157. return bChanged ? result : undefined;
  1158. }
  1159. /**
  1160. * 检查data中是否含有计算字段
  1161. * @param {Object} data
  1162. * @return {boolean}
  1163. * @private
  1164. */
  1165. _checkCalcField(data) {
  1166. for (const prop in data) {
  1167. if (calcFields.indexOf(prop) >= 0) {
  1168. return true;
  1169. }
  1170. }
  1171. return false;
  1172. }
  1173. /**
  1174. * 提交数据 - 不影响计算等未提交项
  1175. * @param {Number} tenderId - 标段id
  1176. * @param {Object} data - 提交数据
  1177. * @return {Object} - 提交后的数据
  1178. */
  1179. async updateInfo(tenderId, data) {
  1180. // 简单校验数据
  1181. if (tenderId <= 0) {
  1182. throw '标段不存在';
  1183. }
  1184. if (tenderId !== data.tender_id) {
  1185. throw '提交数据错误';
  1186. }
  1187. try {
  1188. // 过滤不可提交字段
  1189. const updateNode = await this.getDataById(data.id);
  1190. if (!updateNode || tenderId !== updateNode.tender_id || data.ledger_id !== updateNode.ledger_id) {
  1191. throw '提交数据错误';
  1192. }
  1193. const updateData = this._filterUpdateInvalidField(updateNode.id, data);
  1194. await this.db.update(this.tableName, updateData);
  1195. } catch (err) {
  1196. throw err;
  1197. }
  1198. const result = await this.getDataByNodeId(tenderId, data.ledger_id);
  1199. return result;
  1200. }
  1201. /**
  1202. * 提交多条数据 - 不影响计算等未提交项
  1203. * @param {Number} tenderId - 标段id
  1204. * @param {Array} datas - 提交数据
  1205. * @return {Array} - 提交后的数据
  1206. */
  1207. async updateInfos(tenderId, datas) {
  1208. if (tenderId <= 0) {
  1209. throw '标段不存在';
  1210. }
  1211. for (const data of datas) {
  1212. if (tenderId !== data.tender_id) {
  1213. throw '提交数据错误';
  1214. }
  1215. }
  1216. this.transaction = await this.db.beginTransaction();
  1217. try {
  1218. for (const data of datas) {
  1219. const updateNode = await this.getDataById(data.id);
  1220. if (!updateNode || tenderId !== updateNode.tender_id || data.ledger_id !== updateNode.ledger_id) {
  1221. throw '提交数据错误';
  1222. }
  1223. const updateData = this._filterUpdateInvalidField(updateNode.id, data);
  1224. await this.transaction.update(this.tableName, updateData);
  1225. }
  1226. await this.transaction.commit();
  1227. } catch (err) {
  1228. await this.transaction.rollback();
  1229. throw err;
  1230. }
  1231. const filter = [];
  1232. for (const data of datas) {
  1233. filter.push(data.id);
  1234. }
  1235. this.initSqlBuilder();
  1236. this.sqlBuilder.setAndWhere('id', {
  1237. value: filter,
  1238. operate: 'in',
  1239. });
  1240. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  1241. const resultData = await this.db.query(sql, sqlParam);
  1242. return resultData;
  1243. }
  1244. /**
  1245. * 复制粘贴整块
  1246. * @param {Number} tenderId - 标段Id
  1247. * @param {Number} selectId - 选中几点Id
  1248. * @param {Array} block - 复制节点Id
  1249. * @return {Object} - 提价后的数据(其中新增粘贴数据,只返回第一层)
  1250. */
  1251. async pasteBlock(tenderId, selectId, block) {
  1252. if ((tenderId <= 0) || (selectId <= 0)) {
  1253. return [];
  1254. }
  1255. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1256. if (!selectData) {
  1257. throw '位置数据错误';
  1258. }
  1259. const newParentPath = selectData.full_path.replace(selectData.ledger_id, '');
  1260. const copyNodes = await this.getDataByNodeIds(tenderId, block);
  1261. if (!copyNodes || copyNodes.length <= 0) {
  1262. throw '复制数据错误';
  1263. }
  1264. let bSameParent = true;
  1265. for (const node of copyNodes) {
  1266. if (node.ledger_pid !== copyNodes[0].ledger_pid) {
  1267. bSameParent = false;
  1268. break;
  1269. }
  1270. }
  1271. if (!bSameParent) {
  1272. throw '复制数据错误:仅可操作同层节点';
  1273. }
  1274. const orgParentPath = copyNodes[0].full_path.replace(copyNodes[0].ledger_id, '');
  1275. const newIds = [];
  1276. this.transaction = await this.db.beginTransaction();
  1277. try {
  1278. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  1279. await this._updateSelectNextsOrder(selectData, copyNodes.length);
  1280. // 数据库创建新增节点数据
  1281. for (const node of copyNodes) {
  1282. const datas = await this.getDataByFullPath(tenderId, node.full_path + '%');
  1283. const cacheKey = keyPre + tenderId;
  1284. let maxId = parseInt(await this.cache.get(cacheKey));
  1285. if (!maxId) {
  1286. maxId = await this._getMaxNodeId(tenderId);
  1287. }
  1288. this.cache.set(cacheKey, maxId + datas.length, 'EX', this.ctx.app.config.cacheTime);
  1289. const leafBillsId = [];
  1290. // 计算粘贴数据中需更新部分
  1291. for (let index = 0; index < datas.length; index++) {
  1292. const data = datas[index];
  1293. const newId = maxId + index + 1;
  1294. const idChange = {
  1295. org: data.id,
  1296. };
  1297. delete data.id;
  1298. if (!data.is_leaf) {
  1299. for (const children of datas) {
  1300. children.full_path = children.full_path.replace('.' + data.ledger_id, '.' + newId);
  1301. if (children.ledger_pid === data.ledger_id) {
  1302. children.ledger_pid = newId;
  1303. }
  1304. }
  1305. } else {
  1306. data.full_path = data.full_path.replace('.' + data.ledger_id, '.' + newId);
  1307. }
  1308. data.ledger_id = newId;
  1309. data.full_path = data.full_path.replace(orgParentPath, newParentPath);
  1310. if (data.ledger_pid === copyNodes[0].ledger_pid) {
  1311. data.ledger_pid = selectData.ledger_pid;
  1312. data.order = selectData.order + index + 1;
  1313. }
  1314. data.level = data.level + selectData.level - copyNodes[0].level;
  1315. const newData = await this.transaction.insert(this.tableName, data);
  1316. if (data.is_leaf) {
  1317. idChange.new = newData.insertId;
  1318. leafBillsId.push(idChange);
  1319. }
  1320. newIds.push(newData.insertId);
  1321. }
  1322. for (const id of leafBillsId) {
  1323. await this.ctx.service.pos.copyBillsPosData(id.org, id.new, this.transaction);
  1324. }
  1325. }
  1326. await this.transaction.commit();
  1327. } catch (err) {
  1328. await this.transaction.rollback();
  1329. throw err;
  1330. }
  1331. // 查询应返回的结果
  1332. const order = [];
  1333. for (let i = 1; i <= copyNodes.length; i++) {
  1334. order.push(selectData.order + i);
  1335. }
  1336. const createData = await this.getDataByIds(newIds);
  1337. const updateData = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + copyNodes.length);
  1338. const posData = await this.ctx.service.pos.getPosData({ lid: newIds });
  1339. return {
  1340. ledger: { create: createData, update: updateData },
  1341. pos: posData,
  1342. };
  1343. }
  1344. /**
  1345. * 增量更新父项金额
  1346. * @param {Number} tenderId - 标段id
  1347. * @param {Object} updateMap - 增量更新数,使用更新父项的full_path为索引
  1348. * e.g: {'1.2.6.8': 30, '1.2.6.10': 40}表示'1.2.6.8'增量30,'1.2.6.10'增量40(此处同步更新'1.2.6', '1.2', '1')
  1349. * @return {Promise<void>}
  1350. * @private
  1351. */
  1352. async _increCalcParent(tenderId, updateMap) {
  1353. for (const prop in updateMap) {
  1354. this.initSqlBuilder();
  1355. this.sqlBuilder.setAndWhere('tender_id', {
  1356. value: tenderId,
  1357. operate: '=',
  1358. });
  1359. const fullPath = this.ctx.helper.explodePath(prop);
  1360. this.sqlBuilder.setAndWhere('full_path', {
  1361. value: this.ctx.helper.explodePath(prop),
  1362. operate: 'in',
  1363. });
  1364. this.sqlBuilder.setUpdateData('total_price', {
  1365. value: updateMap[prop] > 0 ? updateMap[prop] : -updateMap[prop],
  1366. selfOperate: updateMap[prop] > 0 ? '+' : '-',
  1367. });
  1368. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  1369. await this.transaction.query(sql, sqlParam);
  1370. }
  1371. }
  1372. /**
  1373. * 提交数据 - 响应计算(增量方式计算)
  1374. * @param {Number} tenderId
  1375. * @param {Object} data
  1376. * @return {Promise<*>}
  1377. */
  1378. async updateCalc(tenderId, data) {
  1379. // 简单验证数据
  1380. if (tenderId <= 0) {
  1381. throw '标段不存在';
  1382. }
  1383. if (!data) {
  1384. throw '提交数据错误';
  1385. }
  1386. const datas = data instanceof Array ? data : [data];
  1387. const ids = [];
  1388. for (const row of datas) {
  1389. if (tenderId !== row.tender_id) {
  1390. throw '提交数据错误';
  1391. }
  1392. ids.push(row.id);
  1393. }
  1394. this.transaction = await this.db.beginTransaction();
  1395. try {
  1396. for (const row of datas) {
  1397. const updateNode = await this.getDataById(row.id);
  1398. if (!updateNode || tenderId !== updateNode.tender_id || row.ledger_id !== updateNode.ledger_id) {
  1399. throw '提交数据错误';
  1400. }
  1401. let updateData;
  1402. if (this._checkCalcField(row)) {
  1403. const calcData = this.ctx.helper.updateObj(updateNode, row);
  1404. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, updateNode.unit);
  1405. this.ctx.helper.checkFieldPrecision(calcData, qtyFields, precision.value);
  1406. if (updateNode.is_leaf) {
  1407. calcData.total_price = calcData.quantity * calcData.unit_price;
  1408. calcData.deal_tp = calcData.deal_qty * calcData.unit_price;
  1409. }
  1410. const data1 = this._filterChangedField(updateNode, calcData);
  1411. updateData = this._filterUpdateInvalidField(updateNode.id, data1);
  1412. } else {
  1413. updateData = this._filterUpdateInvalidField(updateNode.id, row);
  1414. }
  1415. await this.transaction.update(this.tableName, updateData);
  1416. }
  1417. await this.transaction.commit();
  1418. } catch (err) {
  1419. await this.transaction.rollback();
  1420. throw err;
  1421. }
  1422. return { update: await this.getDataByIds(ids) };
  1423. }
  1424. /**
  1425. *
  1426. * @param tenderId
  1427. * @param xmj
  1428. * @param order
  1429. * @param parentData
  1430. * @return {Promise<*[]>}
  1431. * @private
  1432. */
  1433. async _sortBatchInsertData(tenderId, xmj, order, parentData) {
  1434. const result = [],
  1435. newIds = [];
  1436. let tp = 0;
  1437. const cacheKey = keyPre + tenderId;
  1438. let maxId = parseInt(await this.cache.get(cacheKey));
  1439. if (!maxId) {
  1440. maxId = await this._getMaxNodeId(tenderId);
  1441. }
  1442. this.cache.set(cacheKey, maxId + xmj.children.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1443. // 添加xmj数据
  1444. const parent = {
  1445. tender_id: tenderId,
  1446. ledger_id: maxId + 1,
  1447. ledger_pid: parentData.ledger_id,
  1448. is_leaf: xmj.children.length === 0,
  1449. order,
  1450. level: parentData.level + 1,
  1451. name: xmj.name,
  1452. };
  1453. parent.full_path = parentData.full_path + '.' + parent.ledger_id;
  1454. // 添加gcl数据
  1455. for (let i = 0, iLen = xmj.children.length; i < iLen; i++) {
  1456. const gcl = xmj.children[i];
  1457. const child = {
  1458. tender_id: tenderId,
  1459. ledger_id: maxId + 1 + i + 1,
  1460. ledger_pid: parent.ledger_id,
  1461. is_leaf: true,
  1462. order: i + 1,
  1463. level: parent.level + 1,
  1464. b_code: gcl.b_code,
  1465. name: gcl.name,
  1466. unit: gcl.unit,
  1467. unit_price: gcl.unit_price,
  1468. quantity: gcl.quantity,
  1469. };
  1470. child.full_path = parent.full_path + '.' + child.ledger_id;
  1471. child.total_price = child.unit_price * child.quantity;
  1472. tp = tp + child.total_price;
  1473. result.push(child);
  1474. newIds.push(child.ledger_id);
  1475. }
  1476. parent.total_price = tp;
  1477. result.push(parent);
  1478. newIds.push(parent.ledger_id);
  1479. return [result, tp, newIds];
  1480. }
  1481. /**
  1482. * 批量插入子项
  1483. * @param {Number} tenderId - 标段Id
  1484. * @param {Number} selectId - 选中节点Id
  1485. * @param {Object} data - 批量插入数据
  1486. * @return {Promise<void>}
  1487. */
  1488. async batchInsertChild(tenderId, selectId, data) {
  1489. const result = { ledger: {}, pos: null };
  1490. if ((tenderId <= 0) || (selectId <= 0)) {
  1491. return result;
  1492. }
  1493. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1494. if (!selectData) {
  1495. throw '位置数据错误';
  1496. }
  1497. this.transaction = await this.db.beginTransaction();
  1498. const newIds = [];
  1499. try {
  1500. const lastChild = await this.getLastChildData(tenderId, selectId);
  1501. // 更新父项isLeaf
  1502. if (!lastChild) {
  1503. await this.transaction.update(this.tableName, {
  1504. id: selectData.id,
  1505. is_leaf: false,
  1506. });
  1507. }
  1508. const order = lastChild ? lastChild.order : 0;
  1509. // 计算id
  1510. const cacheKey = keyPre + tenderId;
  1511. let maxId = parseInt(await this.cache.get(cacheKey));
  1512. if (!maxId) {
  1513. maxId = await this._getMaxNodeId(tenderId);
  1514. }
  1515. // 数据库创建新增节点数据
  1516. for (let i = 0, iLen = data.length; i < iLen; i++) {
  1517. // 合并新增数据
  1518. const qd = {
  1519. tender_id: tenderId,
  1520. ledger_id: maxId + i + 1,
  1521. ledger_pid: selectData.ledger_id,
  1522. is_leaf: true,
  1523. order: order + i + 1,
  1524. level: selectData.level + 1,
  1525. b_code: data[i].b_code,
  1526. name: data[i].name,
  1527. unit: data[i].unit,
  1528. unit_price: data[i].price,
  1529. };
  1530. qd.full_path = selectData.full_path + '.' + qd.ledger_id;
  1531. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, qd.unit);
  1532. this.ctx.helper.checkPrecision(qd, qtyFields, precision.value);
  1533. const insertResult = await this.transaction.insert(this.tableName, qd);
  1534. newIds.push(insertResult.insertId);
  1535. await this.ctx.service.pos.insertLedgerPosData(this.transaction, tenderId, insertResult.insertId, data[i].pos);
  1536. await this.calc(tenderId, insertResult.insertId, this.transaction);
  1537. }
  1538. this.cache.set(cacheKey, maxId + data.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1539. await this.transaction.commit();
  1540. } catch (err) {
  1541. await this.transaction.rollback();
  1542. throw err;
  1543. }
  1544. // 查询应返回的结果
  1545. result.ledger.create = await this.getDataByIds(newIds);
  1546. result.pos = await this.ctx.service.pos.getPosData({ lid: newIds });
  1547. return result;
  1548. }
  1549. /**
  1550. * 批量插入后项
  1551. * @param {Number} tenderId - 标段Id
  1552. * @param {Number} selectId - 选中节点Id
  1553. * @param {Object} data - 批量插入数据
  1554. * @return {Promise<void>}
  1555. */
  1556. async batchInsertNext(tenderId, selectId, data) {
  1557. const result = { ledger: {}, pos: null };
  1558. if ((tenderId <= 0) || (selectId <= 0)) {
  1559. return result;
  1560. }
  1561. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1562. if (!selectData) {
  1563. throw '位置数据错误';
  1564. }
  1565. const parentData = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  1566. if (!parentData) {
  1567. throw '位置数据错误';
  1568. }
  1569. this.transaction = await this.db.beginTransaction();
  1570. const newIds = [];
  1571. try {
  1572. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  1573. await this._updateSelectNextsOrder(selectData, data.length);
  1574. // 计算id和order
  1575. const cacheKey = keyPre + tenderId;
  1576. let maxId = parseInt(await this.cache.get(cacheKey));
  1577. if (!maxId) {
  1578. maxId = await this._getMaxNodeId(tenderId);
  1579. }
  1580. const order = selectData.order;
  1581. // 数据库创建新增节点数据
  1582. for (let i = 0, iLen = data.length; i < iLen; i++) {
  1583. // 合并新增数据
  1584. const qd = {
  1585. tender_id: tenderId,
  1586. ledger_id: maxId + i + 1,
  1587. ledger_pid: parentData.ledger_id,
  1588. is_leaf: true,
  1589. order: order + i + 1,
  1590. level: parentData.level + 1,
  1591. b_code: data[i].b_code,
  1592. name: data[i].name,
  1593. unit: data[i].unit,
  1594. unit_price: data[i].price,
  1595. };
  1596. qd.full_path = parentData.full_path + '.' + qd.ledger_id;
  1597. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, qd.unit);
  1598. this.ctx.helper.checkPrecision(qd, qtyFields, precision.value);
  1599. const insertResult = await this.transaction.insert(this.tableName, qd);
  1600. newIds.push(insertResult.insertId);
  1601. await this.ctx.service.pos.insertLedgerPosData(this.transaction, tenderId, insertResult.insertId, data[i].pos);
  1602. await this.calc(tenderId, insertResult.insertId, this.transaction);
  1603. }
  1604. this.cache.set(cacheKey, maxId + data.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1605. await this.transaction.commit();
  1606. } catch (err) {
  1607. await this.transaction.rollback();
  1608. throw err;
  1609. }
  1610. // 查询应返回的结果
  1611. result.ledger.create = await this.getDataByIds(newIds);
  1612. result.ledger.update = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + data.length);
  1613. result.pos = await this.ctx.service.pos.getPosData({ lid: newIds });
  1614. return result;
  1615. }
  1616. /**
  1617. *
  1618. * @param {Number} tid - 标段id
  1619. * @param {Number} id - 需要计算的节点的id
  1620. * @param {Object} transaction - 操作所属事务,没有则创建
  1621. * @return {Promise<void>}
  1622. */
  1623. async calc(tid, id, transaction) {
  1624. const node = await this.getAllDataByCondition({ id });
  1625. if (!node) {
  1626. throw '数据错误';
  1627. }
  1628. const calcQtySql = 'UPDATE ??' +
  1629. ' SET `quantity` = (SELECT SUM(`quantity`) FROM ?? WHERE `lid` = ?), `total_price` = `quantity` * `unit_price`' +
  1630. ' WHERE `id` = ?';
  1631. await transaction.query(this.db.format(calcQtySql, [this.tableName, this.ctx.service.pos.tableName, id, id]));
  1632. }
  1633. /**
  1634. * 查找定位 --> 废弃
  1635. * @param tenderId
  1636. * @param nodeId
  1637. * @return {Promise<{expand: *}>}
  1638. */
  1639. async locateNode(tenderId, nodeId) {
  1640. const node = await this.getDataByNodeId(tenderId, nodeId);
  1641. if (!node) {
  1642. throw '查询数据有误';
  1643. }
  1644. const expandIds = node.full_path.split('.');
  1645. expandIds.pop();
  1646. const expandData = await this.getChildrenByParentId(tenderId, expandIds);
  1647. return { expand: expandData };
  1648. }
  1649. async _importCacheTreeNode(transaction, node) {
  1650. const data = {
  1651. tender_id: this.ctx.tender.id,
  1652. ledger_id: node.ledger_id,
  1653. ledger_pid: node.ledger_pid,
  1654. level: node.level,
  1655. order: node.order,
  1656. is_leaf: !node.children || node.children.length === 0,
  1657. full_path: node.full_path,
  1658. code: node.code,
  1659. b_code: node.b_code,
  1660. name: node.name,
  1661. unit: node.unit,
  1662. quantity: node.quantity,
  1663. unit_price: node.unit_price,
  1664. total_price: node.total_price,
  1665. dgn_qty1: node.dgn_qty1,
  1666. dgn_qty2: node.dgn_qty2,
  1667. memo: node.memo,
  1668. drawing_code: node.drawing_code,
  1669. };
  1670. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, data.unit);
  1671. this.ctx.helper.checkPrecision(data, qtyFields, precision.value);
  1672. const result = await transaction.insert(this.tableName, data);
  1673. if (node.children && node.children.length > 0) {
  1674. for (const child of node.children) {
  1675. await this._importCacheTreeNode(transaction, child);
  1676. }
  1677. } else if (node.pos && node.pos.length > 0) {
  1678. await this.ctx.service.pos.insertLedgerPosData(transaction, this.ctx.tender.id, result.insertId, node.pos);
  1679. }
  1680. }
  1681. async importExcel(excelData) {
  1682. const AnalysisExcel = require('../lib/analysis_excel');
  1683. const analysisExcel = new AnalysisExcel();
  1684. const tempData = await this.ctx.service.tenderNodeTemplate.getData(true);
  1685. const cacheTree = analysisExcel.analysisData(excelData, tempData);
  1686. const cacheKey = keyPre + this.ctx.tender.id;
  1687. const orgMaxId = parseInt(await this.cache.get(cacheKey));
  1688. const transaction = await this.db.beginTransaction();
  1689. try {
  1690. await transaction.delete(this.tableName, {tender_id: this.ctx.tender.id});
  1691. await transaction.delete(this.ctx.service.pos.tableName, {tid: this.ctx.tender.id});
  1692. for (const node of cacheTree.roots) {
  1693. await this._importCacheTreeNode(transaction, node);
  1694. }
  1695. await transaction.commit();
  1696. this.cache.set(cacheKey, cacheTree.items.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1697. } catch (err) {
  1698. await transaction.rollback();
  1699. if (orgMaxId) {
  1700. this.cache.set(cacheKey, orgMaxId, 'EX', this.ctx.app.config.cacheTime);
  1701. }
  1702. throw err;
  1703. }
  1704. }
  1705. }
  1706. return Ledger;
  1707. };