ledger.js 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853
  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. * 获取项目工程量
  388. * @param tenderId
  389. * @returns {Promise<*>}
  390. */
  391. async getGatherGclBills(tenderId) {
  392. const sql = 'SELECT `b_code`, `name`, `unit`, `unit_price`, ' +
  393. ' Sum(`quantity`) As `quantity`, Sum(`total_price`) As `total_price`, ' +
  394. ' Sum(`deal_qty`) As `deal_qty`, Sum(`deal_tp`) As `deal_tp` ' +
  395. ' From ?? ' +
  396. ' WHERE `tender_id` = ? And `b_code` And `is_leaf` ' +
  397. ' GROUP BY `b_code`, `name`, `unit`, `unit_price`';
  398. const sqlParam = [this.tableName, tenderId];
  399. return await this.db.query(sql, sqlParam);
  400. }
  401. /**
  402. * 获取sql条件语句片段,仅供search、searchRange方法使用
  403. * @param {Object} where - 条件参数
  404. * @return {*[]}
  405. * e.g.
  406. * where = {type: 'And', value: 'A', operate: '=', fields: ['code', 'name']}
  407. * return [sql: 'And (?? = \'A\' Or ?? = \'A\')', sqlParam: ['code', name]]
  408. * @private
  409. */
  410. _getWhereString(where) {
  411. const sqlParam = [],
  412. sqlPart = [];
  413. const values = where.value instanceof Array ? where.value : [where.value];
  414. const fields = where.fields instanceof Array ? where.fields : [where.fields];
  415. for (const field of fields) {
  416. for (const v of values) {
  417. sqlPart.push('?? ' + where.operate + ' ' + v);
  418. sqlParam.push(field);
  419. }
  420. }
  421. const sql = ' ' + (where.type ? where.type : 'And') + ' (' + sqlPart.join(' OR ') + ')';
  422. return [sql, sqlParam];
  423. }
  424. /**
  425. * 搜索台账
  426. *
  427. * @param {Number} tenderId - 标段id
  428. * @param {Object} key - 查询信息
  429. * @return {Promise<void>}
  430. */
  431. async search(tenderId, key) {
  432. let sql = 'Select * From ?? Where';
  433. let sqlParam = [this.tableName];
  434. sql = sql + ' ?? = ' + tenderId;
  435. sqlParam.push('tender_id');
  436. const [sql1, sqlParam1] = this._getWhereString(key);
  437. sql = sql + sql1;
  438. sqlParam = sqlParam.concat(sqlParam1);
  439. return this.db.query(sql, sqlParam);
  440. }
  441. /**
  442. * 范围内搜索台账
  443. *
  444. * @param {Number} tenderId - 标段id
  445. * @param {Object} key - 查询信息
  446. * @param {Array} range - 查询范围
  447. * @return {Promise<void>}
  448. */
  449. async searchRange(tenderId, key, range) {
  450. let sql = 'Select * From ?? Where';
  451. let sqlParam = [this.tableName];
  452. sql = sql + ' ?? = ' + tenderId;
  453. sqlParam.push('tender_id');
  454. let [sql1, sqlParam1] = this._getWhereString(key);
  455. sql = sql + sql1;
  456. sqlParam = sqlParam.concat(sqlParam1);
  457. for (const r of range) {
  458. [sql1, sqlParam1] = this._getWhereString(r);
  459. sql = sql + sql1;
  460. sqlParam = sqlParam.concat(sqlParam1);
  461. }
  462. return this.db.query(sql, sqlParam);
  463. }
  464. /**
  465. * 统计子节点total_price
  466. * @param {Number} tenderId - 标段id
  467. * @param {Number} pid - 父节点id
  468. * @param {Number} order - order取值
  469. * @param {String} orderOperate - order比较操作符
  470. * @return {Promise<void>}
  471. */
  472. async addUpChildren(tenderId, pid, order, orderOperate) {
  473. this.initSqlBuilder();
  474. const sql = ['SELECT SUM(??) As value FROM ?? ', ' WHERE '];
  475. const sqlParam = ['total_price', this.tableName];
  476. sql.push(' ?? = ' + tenderId);
  477. sqlParam.push('tender_id');
  478. sql.push(' And ?? = ' + pid);
  479. sqlParam.push('ledger_pid');
  480. sql.push(' And ?? ' + orderOperate + ' ' + order);
  481. sqlParam.push('order');
  482. const result = await this.db.queryOne(sql.join(''), sqlParam);
  483. return result.value;
  484. }
  485. /**
  486. * 更新order
  487. * @param {Number} tenderId - 标段id
  488. * @param {Number} parentId - 父节点id
  489. * @param {Number} order - 自增起始order(含)
  490. * @param {Number} incre - 自增量
  491. * @return {Promise<*>}
  492. * @private
  493. */
  494. async _updateChildrenOrderAfter(tenderId, parentId, order, incre = 1) {
  495. this.initSqlBuilder();
  496. this.sqlBuilder.setAndWhere('tender_id', {
  497. value: tenderId,
  498. operate: '=',
  499. });
  500. this.sqlBuilder.setAndWhere('order', {
  501. value: order,
  502. operate: '>=',
  503. });
  504. this.sqlBuilder.setAndWhere('ledger_pid', {
  505. value: parentId,
  506. operate: '=',
  507. });
  508. this.sqlBuilder.setUpdateData('order', {
  509. value: Math.abs(incre),
  510. selfOperate: incre > 0 ? '+' : '-',
  511. });
  512. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  513. const data = await this.transaction.query(sql, sqlParam);
  514. return data;
  515. }
  516. /**
  517. * select的全部后兄弟节点,Order自增
  518. *
  519. * @param {Object} select - 选中的节点
  520. * @param {Number} incre - 自增值
  521. * @return {Array} - 自增后的数据
  522. * @private
  523. */
  524. async _updateSelectNextsOrder(select, incre = 1) {
  525. return await this._updateChildrenOrderAfter(select.tender_id, select.ledger_pid, select.order + 1, incre);
  526. }
  527. /**
  528. * 从数据库获取标段的最大节点id
  529. *
  530. * @param {Number} tenderId - 标段id
  531. * @return {Number}
  532. * @private
  533. */
  534. async _getMaxNodeId(tenderId) {
  535. const sql = 'SELECT Max(??) As max_id FROM ?? Where tender_id = ' + tenderId;
  536. const sqlParam = ['ledger_id', this.tableName];
  537. const queryResult = await this.db.queryOne(sql, sqlParam);
  538. return queryResult.max_id;
  539. }
  540. /**
  541. * 根据selectData, data 新增数据(新增为selectData的后项,该方法不可单独使用)
  542. *
  543. * @param {Number} tenderId - 标段id
  544. * @param {Object} selectData - 选中节点的数据
  545. * @param {Object} data - 新增节点的初始数据
  546. * @return {Object} - 新增结果
  547. * @private
  548. */
  549. async _addNodeData(tenderId, selectData, data) {
  550. if (tenderId <= 0) {
  551. return undefined;
  552. }
  553. if (!data) {
  554. data = {};
  555. }
  556. const cacheKey = keyPre + tenderId;
  557. let maxId = parseInt(await this.cache.get(cacheKey));
  558. if (!maxId) {
  559. maxId = await this._getMaxNodeId(tenderId);
  560. this.cache.set(cacheKey, maxId, 'EX', this.ctx.app.config.cacheTime);
  561. }
  562. data.tender_id = tenderId;
  563. data.ledger_id = maxId + 1;
  564. data.ledger_pid = selectData.ledger_pid;
  565. data.level = selectData.level;
  566. data.order = selectData.order + 1;
  567. data.full_path = selectData.full_path.replace('.' + selectData.ledger_id, '.' + data.ledger_id);
  568. data.is_leaf = true;
  569. const result = await this.transaction.insert(this.tableName, data);
  570. this.cache.set(cacheKey, maxId + 1, 'EX', this.ctx.app.config.cacheTime);
  571. return result;
  572. }
  573. /**
  574. * 根据parentData, data新增数据(新增为parentData的最后一个子项)
  575. * @param {Number} tenderId - 标段id
  576. * @param {Object} parentData - 父项数据
  577. * @param {Object} data - 新增节点,初始数据
  578. * @return {Promise<*>} - 新增结果
  579. * @private
  580. */
  581. async _addChildNodeData(tenderId, parentData, data) {
  582. if (tenderId <= 0) {
  583. return undefined;
  584. }
  585. if (!data) {
  586. data = {};
  587. }
  588. const pid = parentData ? parentData.ledger_id : rootId;
  589. const cacheKey = keyPre + tenderId;
  590. let maxId = parseInt(await this.cache.get(cacheKey));
  591. if (!maxId) {
  592. maxId = await this._getMaxNodeId(tenderId);
  593. }
  594. this.cache.set(cacheKey, maxId + 1, 'EX', this.ctx.app.config.cacheTime);
  595. data.tender_id = tenderId;
  596. data.ledger_id = maxId + 1;
  597. data.ledger_pid = pid;
  598. if (data.order === undefined) {
  599. data.order = 1;
  600. }
  601. data.level = parentData ? parentData.level + 1 : 1;
  602. data.full_path = parentData ? parentData.full_path + '.' + data.ledger_id : '' + data.ledger_id;
  603. if (data.is_leaf === undefined) {
  604. data.is_leaf = true;
  605. }
  606. const result = await this.transaction.insert(this.tableName, data);
  607. return [result, data];
  608. }
  609. /**
  610. * 根据parentData, data新增数据(自动排序)
  611. * @param tenderId
  612. * @param parentData
  613. * @param data
  614. * @return {Promise<void>}
  615. * @private
  616. */
  617. async _addChildAutoOrder(tenderId, parentData, data) {
  618. const self = this;
  619. const findPreData = function(list, a) {
  620. if (!list || list.length === 0) { return null; }
  621. for (let i = 0, iLen = list.length; i < iLen; i++) {
  622. if (self.ctx.helper.compareCode(list[i].code, a.code) > 0) {
  623. return i > 0 ? list[i - 1] : null;
  624. }
  625. }
  626. return list[list.length - 1];
  627. };
  628. const pid = parentData ? parentData.ledger_id : rootId;
  629. const children = await this.getChildrenByParentId(tenderId, pid);
  630. const preData = findPreData(children, data);
  631. const parent = null;
  632. if (!preData || children.indexOf(preData) < children.length - 1) {
  633. await this._updateChildrenOrderAfter(tenderId, pid, preData ? preData.order + 1 : 1);
  634. }
  635. data.order = preData ? preData.order + 1 : 1;
  636. const [addResult, node] = await this._addChildNodeData(tenderId, parentData, data);
  637. return [addResult, node];
  638. }
  639. /**
  640. * tenderId标段中, 在selectId后新增一个节点
  641. *
  642. * @param {Number} tenderId - 标段id
  643. * @param {Number} selectId - 选中节点id
  644. * @param {Object} data - 新增节点初始化数据
  645. * @return {Array} 新增后的数据,其他被修改的数据
  646. */
  647. async addNode(tenderId, selectId, data) {
  648. if ((tenderId <= 0) || (selectId <= 0)) {
  649. return [];
  650. }
  651. const selectData = await this.getDataByNodeId(tenderId, selectId);
  652. if (!selectData) {
  653. throw '新增节点数据错误';
  654. }
  655. if (!this.transaction) {
  656. this.transaction = await this.db.beginTransaction();
  657. }
  658. try {
  659. // 选中节点的所有后兄弟节点,order+1
  660. await this._updateSelectNextsOrder(selectData);
  661. // 数据库创建新增节点数据
  662. const newNode = await this._addNodeData(tenderId, selectData, data);
  663. if (!newNode) { throw '新增节点数据错误'; }
  664. await this.transaction.commit();
  665. } catch (err) {
  666. await this.transaction.rollback();
  667. this.transaction = null;
  668. throw err;
  669. }
  670. this.transaction = null;
  671. // 查询应返回的结果
  672. const createData = await this.getDataByParentAndOrder(selectData.tender_id, selectData.ledger_pid, [selectData.order + 1]);
  673. const updateData = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + 1);
  674. return { create: createData, update: updateData };
  675. }
  676. /**
  677. * 从标准数据中提取有效数据
  678. * @param {Object} stdData - 从标准库中查询所得
  679. * @returns {name, unit, source, code, b_code}
  680. * @private
  681. */
  682. _filterStdData(stdData) {
  683. const result = {
  684. name: stdData.name,
  685. unit: stdData.unit,
  686. source: stdData.source,
  687. };
  688. result.code = stdData.code ? stdData.code : '';
  689. result.b_code = stdData.b_code ? stdData.b_code : '';
  690. return result;
  691. }
  692. /**
  693. * 添加节点(来自标准清单)
  694. * @param {Number} tenderId
  695. * @param {Number} selectId
  696. * @param {Object} stdData
  697. * @return {Promise<*>}
  698. */
  699. async addStdNode(tenderId, selectId, stdData) {
  700. const newData = this._filterStdData(stdData);
  701. const result = await this.addNode(tenderId, selectId, newData);
  702. return result;
  703. }
  704. /**
  705. * 添加节点,并同步添加父节点
  706. * @param {Number} tenderId - 标段id
  707. * @param {Number} selectId - 选中节点id
  708. * @param {Object} stdData - 节点数据
  709. * @param {StandardLib} stdLib - 标准库
  710. * @return {Promise<void>}
  711. */
  712. async addStdNodeWithParent(tenderId, stdData, stdLib) {
  713. const fullLevel = await stdLib.getFullLevelDataByFullPath(stdData.list_id, stdData.full_path);
  714. fullLevel.sort(function(x, y) {
  715. return x.level - y.level;
  716. });
  717. let isNew = false,
  718. node,
  719. firstNew,
  720. updateParent,
  721. addResult;
  722. const expandIds = [];
  723. this.transaction = await this.db.beginTransaction();
  724. try {
  725. for (let i = 0, len = fullLevel.length; i < len; i++) {
  726. const stdNode = fullLevel[i];
  727. if (isNew) {
  728. const newData = this._filterStdData(stdNode);
  729. newData.is_leaf = (i === len - 1);
  730. [addResult, node] = await this._addChildNodeData(tenderId, node, newData);
  731. } else {
  732. const parent = node;
  733. node = await this.getDataByCondition({
  734. tender_id: tenderId,
  735. ledger_pid: parent ? parent.ledger_id : rootId,
  736. code: stdNode.code,
  737. name: stdNode.name,
  738. });
  739. if (!node) {
  740. isNew = true;
  741. const newData = this._filterStdData(stdNode);
  742. newData.is_leaf = (i === len - 1);
  743. [addResult, node] = await this._addChildAutoOrder(tenderId, parent, newData);
  744. if (parent && parent.is_leaf) {
  745. await this.transaction.update(this.tableName, { id: parent.id, is_leaf: false });
  746. updateParent = parent;
  747. }
  748. firstNew = node;
  749. } else {
  750. expandIds.push(node.ledger_id);
  751. }
  752. }
  753. }
  754. await this.transaction.commit();
  755. } catch (err) {
  756. await this.transaction.rollback();
  757. throw err;
  758. }
  759. // 查询应返回的结果
  760. let createData = [],
  761. updateData = [];
  762. if (firstNew) {
  763. createData = await this.getDataByFullPath(tenderId, firstNew.full_path + '%');
  764. updateData = await this.getNextsData(tenderId, firstNew.ledger_pid, firstNew.order);
  765. if (updateParent) {
  766. updateData.push(await this.getDataByCondition({ id: updateParent.id }));
  767. }
  768. }
  769. const expandData = await this.getChildrenByParentId(tenderId, expandIds);
  770. return { create: createData, update: updateData, expand: expandData };
  771. }
  772. /**
  773. * 删除节点
  774. * @param {Number} tenderId - 标段id
  775. * @param {Object} deleteData - 删除节点数据
  776. * @return {Promise<*>}
  777. * @private
  778. */
  779. async _deleteNodeData(tenderId, deleteData) {
  780. this.initSqlBuilder();
  781. this.sqlBuilder.setAndWhere('tender_id', {
  782. value: tenderId,
  783. operate: '=',
  784. });
  785. this.sqlBuilder.setAndWhere('full_path', {
  786. value: this.db.escape(deleteData.full_path + '%'),
  787. operate: 'Like',
  788. });
  789. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'delete');
  790. const result = await this.transaction.query(sql, sqlParam);
  791. return result;
  792. }
  793. /**
  794. * tenderId标段中, 删除选中节点及其子节点
  795. *
  796. * @param {Number} tenderId - 标段id
  797. * @param {Number} selectId - 选中节点id
  798. * @return {Array} - 被删除的数据
  799. */
  800. async deleteNode(tenderId, selectId) {
  801. if ((tenderId <= 0) || (selectId <= 0)) {
  802. return [];
  803. }
  804. const selectData = await this.getDataByNodeId(tenderId, selectId);
  805. if (!selectData) {
  806. throw '删除节点数据错误';
  807. }
  808. const parentData = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  809. this.transaction = await this.db.beginTransaction();
  810. let deleteData = [];
  811. try {
  812. // 获取将要被删除的数据
  813. deleteData = await this.getDataByFullPath(tenderId, selectData.full_path + '%');
  814. // 删除
  815. const operate = await this._deleteNodeData(tenderId, selectData);
  816. // 选中节点--父节点 只有一个子节点时,应升级is_leaf
  817. if (parentData) {
  818. const count = await this.db.count(this.tableName, { tender_id: tenderId, ledger_pid: selectData.ledger_pid });
  819. if (count === 1) {
  820. await this.transaction.update(this.tableName, { id: parentData.id, is_leaf: true });
  821. }
  822. }
  823. // 选中节点--全部后节点 order--
  824. await this._updateSelectNextsOrder(selectData, -1);
  825. // 删除部位明细
  826. await this.transaction.delete(this.ctx.service.pos.tableName, { tid: tenderId, lid: this._.map(deleteData, 'id') });
  827. await this.ctx.service.pos.deletePosData(this.transaction, tenderId, this._.map(deleteData, 'id'));
  828. await this.transaction.commit();
  829. } catch (err) {
  830. deleteData = [];
  831. await this.transaction.rollback();
  832. throw err;
  833. }
  834. // 查询结果
  835. let updateData = [];
  836. if (deleteData.length > 0) {
  837. updateData = await this.getNextsData(tenderId, selectData.ledger_pid, selectData.order - 1);
  838. updateData = updateData ? updateData : [];
  839. if (selectData.ledger_pid !== rootId) {
  840. const updateData1 = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  841. if (updateData1.is_leaf !== parentData.is_leaf) {
  842. updateData.push(updateData1);
  843. }
  844. }
  845. }
  846. return { delete: deleteData, update: updateData };
  847. }
  848. /**
  849. * tenderId标段中, 选中节点selectId上移
  850. *
  851. * @param {Number} tenderId - 标段id
  852. * @param {Number} selectId - 选中节点id
  853. * @return {Array} - 发生改变的数据
  854. */
  855. async upMoveNode(tenderId, selectId) {
  856. if ((tenderId <= 0) || (selectId <= 0)) {
  857. return [];
  858. }
  859. const selectData = await this.getDataByNodeId(tenderId, selectId);
  860. if (!selectData) {
  861. throw '上移节点数据错误';
  862. }
  863. const preData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, selectData.order - 1);
  864. if (!preData) {
  865. throw '节点不可上移';
  866. }
  867. this.transaction = await this.db.beginTransaction();
  868. try {
  869. const sData = await this.transaction.update(this.tableName, { id: selectData.id, order: selectData.order - 1 });
  870. const pData = await this.transaction.update(this.tableName, { id: preData.id, order: preData.order + 1 });
  871. await this.transaction.commit();
  872. } catch (err) {
  873. await this.transaction.rollback();
  874. throw err;
  875. }
  876. const resultData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, [selectData.order, preData.order]);
  877. return { update: resultData };
  878. }
  879. /**
  880. * tenderId标段中, 选中节点selectId下移
  881. *
  882. * @param {Number} tenderId - 标段id
  883. * @param {Number} selectId - 选中节点id
  884. * @return {Array} - 发生改变的数据
  885. */
  886. async downMoveNode(tenderId, selectId) {
  887. if ((tenderId <= 0) || (selectId <= 0)) {
  888. return [];
  889. }
  890. const selectData = await this.getDataByNodeId(tenderId, selectId);
  891. if (!selectData) {
  892. throw '下移节点数据错误';
  893. }
  894. const nextData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, selectData.order + 1);
  895. if (!nextData) {
  896. throw '节点不可下移';
  897. }
  898. this.transaction = await this.db.beginTransaction();
  899. try {
  900. const sData = await this.transaction.update(this.tableName, { id: selectData.id, order: selectData.order + 1 });
  901. const pData = await this.transaction.update(this.tableName, { id: nextData.id, order: nextData.order - 1 });
  902. await this.transaction.commit();
  903. } catch (err) {
  904. await this.transaction.rollback();
  905. throw err;
  906. }
  907. const resultData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, [selectData.order, nextData.order]);
  908. return { update: resultData };
  909. }
  910. /**
  911. * 升级selectData, 同步修改所有子节点
  912. * @param {Object} selectData - 升级操作,选中节点
  913. * @return {Object}
  914. * @private
  915. */
  916. async _syncUplevelChildren(selectData) {
  917. this.initSqlBuilder();
  918. this.sqlBuilder.setAndWhere('tender_id', {
  919. value: selectData.tender_id,
  920. operate: '=',
  921. });
  922. this.sqlBuilder.setAndWhere('full_path', {
  923. value: this.db.escape(selectData.full_path + '.%'),
  924. operate: 'like',
  925. });
  926. this.sqlBuilder.setUpdateData('level', {
  927. value: 1,
  928. selfOperate: '-',
  929. });
  930. this.sqlBuilder.setUpdateData('full_path', {
  931. value: ['`full_path`', this.db.escape(selectData.ledger_pid + '.'), this.db.escape('')],
  932. literal: 'Replace',
  933. });
  934. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  935. const data = await this.transaction.query(sql, sqlParam);
  936. return data;
  937. }
  938. /**
  939. * 选中节点的后兄弟节点,全部变为当前节点的子节点
  940. * @param {Object} selectData - 选中节点
  941. * @return {Object}
  942. * @private
  943. */
  944. async _syncUpLevelNexts(selectData) {
  945. // 查询selectData的lastChild
  946. const lastChildData = await this.getLastChildData(selectData.tender_id, selectData.ledger_id);
  947. const nextsData = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order);
  948. if (nextsData && nextsData.length > 0) {
  949. // 修改nextsData pid, 排序
  950. this.initSqlBuilder();
  951. this.sqlBuilder.setUpdateData('ledger_pid', {
  952. value: selectData.ledger_id,
  953. });
  954. const orderInc = lastChildData ? lastChildData.order - selectData.order : -selectData.order;
  955. this.sqlBuilder.setUpdateData('order', {
  956. value: Math.abs(orderInc),
  957. selfOperate: orderInc > 0 ? '+' : '-',
  958. });
  959. this.sqlBuilder.setAndWhere('ledger_pid', {
  960. value: selectData.ledger_pid,
  961. operate: '=',
  962. });
  963. this.sqlBuilder.setAndWhere('order', {
  964. value: selectData.order,
  965. operate: '>',
  966. });
  967. const [sql1, sqlParam1] = this.sqlBuilder.build(this.tableName, 'update');
  968. await this.transaction.query(sql1, sqlParam1);
  969. // 选中节点 is_leaf应为false
  970. if (selectData.is_leaf) {
  971. const updateData = { id: selectData.id,
  972. is_leaf: false,
  973. };
  974. await this.transaction.update(this.tableName, updateData);
  975. }
  976. // 修改nextsData及其子节点的full_path
  977. const oldSubStr = this.db.escape(selectData.ledger_pid + '.');
  978. const newSubStr = this.db.escape(selectData.ledger_id + '.');
  979. const sqlArr = [];
  980. sqlArr.push('Update ?? SET `full_path` = Replace(`full_path`,' + oldSubStr + ',' + newSubStr + ') Where');
  981. sqlArr.push('(`tender_id` = ' + selectData.tender_id + ')');
  982. sqlArr.push(' And (');
  983. for (const data of nextsData) {
  984. sqlArr.push('`full_path` Like ' + this.db.escape(data.full_path + '%'));
  985. if (nextsData.indexOf(data) < nextsData.length - 1) {
  986. sqlArr.push(' Or ');
  987. }
  988. }
  989. sqlArr.push(')');
  990. const sql = sqlArr.join('');
  991. const resultData = await this.transaction.query(sql, [this.tableName]);
  992. return resultData;
  993. }
  994. }
  995. /**
  996. * 升级节点
  997. *
  998. * @param {Number} tenderId - 标段id
  999. * @param {Number} selectId - 选中节点id
  1000. * @return {Array} - 发生改变的数据
  1001. */
  1002. async upLevelNode(tenderId, selectId) {
  1003. if ((tenderId <= 0) || (selectId <= 0)) {
  1004. return [];
  1005. }
  1006. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1007. if (!selectData) {
  1008. throw '升级节点数据错误';
  1009. }
  1010. const parentData = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  1011. if (!parentData) {
  1012. throw '升级节点数据错误';
  1013. }
  1014. this.transaction = await this.db.beginTransaction();
  1015. const newFullPath = selectData.full_path.replace(selectData.ledger_pid + '.', '');
  1016. try {
  1017. // 选中节点--父节点 选中节点为firstChild时,修改is_leaf
  1018. if (selectData.order === 1) {
  1019. await this.transaction.update(this.tableName, {
  1020. id: parentData.id,
  1021. is_leaf: true,
  1022. });
  1023. }
  1024. // 选中节点--父节点--全部后兄弟节点 order+1
  1025. await this._updateSelectNextsOrder(parentData);
  1026. // 选中节点 修改pid, order, full_path
  1027. const updateData = { id: selectData.id,
  1028. ledger_pid: parentData.ledger_pid,
  1029. order: parentData.order + 1,
  1030. level: selectData.level - 1,
  1031. full_path: newFullPath,
  1032. };
  1033. await this.transaction.update(this.tableName, updateData);
  1034. // 选中节点--全部子节点(含孙) level-1, full_path变更
  1035. await this._syncUplevelChildren(selectData);
  1036. // 选中节点--全部后兄弟节点 收编为子节点 修改pid, order, full_path
  1037. await this._syncUpLevelNexts(selectData);
  1038. await this.transaction.commit();
  1039. } catch (err) {
  1040. await this.transaction.rollback();
  1041. throw err;
  1042. }
  1043. // 查询修改的数据
  1044. const resultData1 = await this.getDataByFullPath(tenderId, newFullPath + '%');
  1045. const resultData2 = await this.getNextsData(tenderId, parentData.ledger_pid, parentData.order + 1);
  1046. // 默认原Parent被刷新过,不核对total_price修改
  1047. const preParent = await this.getDataByNodeId(tenderId, parentData.ledger_id);
  1048. resultData2.push(preParent);
  1049. return { update: resultData1.concat(resultData2) };
  1050. }
  1051. /**
  1052. * 降级selectData, 同步修改所有子节点
  1053. * @param {Object} selectData - 选中节点
  1054. * @param {Object} preData - 选中节点的前一节点(降级后为父节点)
  1055. * @return {Promise<*>}
  1056. * @private
  1057. */
  1058. async _syncDownlevelChildren(selectData, preData) {
  1059. this.initSqlBuilder();
  1060. this.sqlBuilder.setAndWhere('tender_id', {
  1061. value: selectData.tender_id,
  1062. operate: '=',
  1063. });
  1064. this.sqlBuilder.setAndWhere('full_path', {
  1065. value: this.db.escape(selectData.full_path + '.%'),
  1066. operate: 'like',
  1067. });
  1068. this.sqlBuilder.setUpdateData('level', {
  1069. value: 1,
  1070. selfOperate: '+',
  1071. });
  1072. this.sqlBuilder.setUpdateData('full_path', {
  1073. value: ['`full_path`', this.db.escape('.' + selectData.ledger_id), this.db.escape('.' + preData.ledger_id + '.' + selectData.ledger_id)],
  1074. literal: 'Replace',
  1075. });
  1076. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  1077. const data = await this.transaction.query(sql, sqlParam);
  1078. return data;
  1079. }
  1080. /**
  1081. * 降级节点
  1082. *
  1083. * @param {Number} tenderId - 标段id
  1084. * @param {Number} selectId - 选中节点id
  1085. * @return {Array} - 发生改变的数据
  1086. */
  1087. async downLevelNode(tenderId, selectId) {
  1088. if ((tenderId <= 0) || (selectId <= 0)) {
  1089. return [];
  1090. }
  1091. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1092. if (!selectData) {
  1093. throw '降级节点数据错误';
  1094. }
  1095. const preData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, selectData.order - 1);
  1096. if (!preData) {
  1097. throw '节点不可降级';
  1098. }
  1099. const preLastChildData = await this.getLastChildData(tenderId, preData.ledger_id);
  1100. this.transaction = await this.db.beginTransaction();
  1101. const orgLastPath = selectData.level === 1 ? selectData.ledger_id : '.' + selectData.ledger_id;
  1102. const newLastPath = selectData.level === 1 ? preData.ledger_id + '.' + selectData.ledger_id : '.' + preData.ledger_id + '.' + selectData.ledger_id;
  1103. const newFullPath = selectData.full_path.replace(orgLastPath, newLastPath);
  1104. try {
  1105. // 选中节点--全部后节点 order--
  1106. await this._updateSelectNextsOrder(selectData, -1);
  1107. // 选中节点 修改pid, level, order, full_path
  1108. const updateData = {
  1109. id: selectData.id,
  1110. ledger_pid: preData.ledger_id,
  1111. order: preLastChildData ? preLastChildData.order + 1 : 1,
  1112. level: selectData.level + 1,
  1113. full_path: newFullPath,
  1114. };
  1115. await this.transaction.update(this.tableName, updateData);
  1116. // 选中节点--全部子节点(含孙) level++, full_path
  1117. await this._syncDownlevelChildren(selectData, preData);
  1118. // 选中节点--前兄弟节点 is_leaf应为false
  1119. if (preData.is_leaf) {
  1120. const updateData2 = {
  1121. id: preData.id,
  1122. is_leaf: false,
  1123. };
  1124. await this.transaction.update(this.tableName, updateData2);
  1125. }
  1126. await this.transaction.commit();
  1127. } catch (err) {
  1128. await this.transaction.rollback();
  1129. throw err;
  1130. }
  1131. // 查询修改的数据
  1132. // 选中节点及子节点
  1133. const resultData1 = await this.getDataByFullPath(tenderId, newFullPath + '%');
  1134. // 选中节点--原前兄弟节点&全部后兄弟节点
  1135. const queryOrder = (preData.is_leaf || this.ctx.helper.checkZero(selectData.total_price)) ? preData.order - 1 : preData.order;
  1136. const resultData2 = await this.getNextsData(tenderId, preData.ledger_pid, queryOrder);
  1137. return { update: resultData1.concat(resultData2) };
  1138. }
  1139. /**
  1140. * 过滤data中update方式不可提交的字段
  1141. * @param {Number} id - 主键key
  1142. * @param {Object} data
  1143. * @return {Object<{id: *}>}
  1144. * @private
  1145. */
  1146. _filterUpdateInvalidField(id, data) {
  1147. const result = {
  1148. id,
  1149. };
  1150. for (const prop in data) {
  1151. if (readOnlyFields.indexOf(prop) === -1) {
  1152. result[prop] = data[prop];
  1153. }
  1154. }
  1155. return result;
  1156. }
  1157. /**
  1158. * newData中,以orgData为基准,过滤掉orgData中未定义或值相等的部分
  1159. * @param {Object} orgData
  1160. * @param {Object} newData
  1161. * @private
  1162. */
  1163. _filterChangedField(orgData, newData) {
  1164. const result = {};
  1165. let bChanged = false;
  1166. for (const prop in orgData) {
  1167. if (newData[prop] !== orgData[prop]) {
  1168. result[prop] = newData[prop];
  1169. bChanged = true;
  1170. }
  1171. }
  1172. return bChanged ? result : undefined;
  1173. }
  1174. /**
  1175. * 检查data中是否含有计算字段
  1176. * @param {Object} data
  1177. * @return {boolean}
  1178. * @private
  1179. */
  1180. _checkCalcField(data) {
  1181. for (const prop in data) {
  1182. if (calcFields.indexOf(prop) >= 0) {
  1183. return true;
  1184. }
  1185. }
  1186. return false;
  1187. }
  1188. /**
  1189. * 提交数据 - 不影响计算等未提交项
  1190. * @param {Number} tenderId - 标段id
  1191. * @param {Object} data - 提交数据
  1192. * @return {Object} - 提交后的数据
  1193. */
  1194. async updateInfo(tenderId, data) {
  1195. // 简单校验数据
  1196. if (tenderId <= 0) {
  1197. throw '标段不存在';
  1198. }
  1199. if (tenderId !== data.tender_id) {
  1200. throw '提交数据错误';
  1201. }
  1202. try {
  1203. // 过滤不可提交字段
  1204. const updateNode = await this.getDataById(data.id);
  1205. if (!updateNode || tenderId !== updateNode.tender_id || data.ledger_id !== updateNode.ledger_id) {
  1206. throw '提交数据错误';
  1207. }
  1208. const updateData = this._filterUpdateInvalidField(updateNode.id, data);
  1209. await this.db.update(this.tableName, updateData);
  1210. } catch (err) {
  1211. throw err;
  1212. }
  1213. const result = await this.getDataByNodeId(tenderId, data.ledger_id);
  1214. return result;
  1215. }
  1216. /**
  1217. * 提交多条数据 - 不影响计算等未提交项
  1218. * @param {Number} tenderId - 标段id
  1219. * @param {Array} datas - 提交数据
  1220. * @return {Array} - 提交后的数据
  1221. */
  1222. async updateInfos(tenderId, datas) {
  1223. if (tenderId <= 0) {
  1224. throw '标段不存在';
  1225. }
  1226. for (const data of datas) {
  1227. if (tenderId !== data.tender_id) {
  1228. throw '提交数据错误';
  1229. }
  1230. }
  1231. this.transaction = await this.db.beginTransaction();
  1232. try {
  1233. for (const data of datas) {
  1234. const updateNode = await this.getDataById(data.id);
  1235. if (!updateNode || tenderId !== updateNode.tender_id || data.ledger_id !== updateNode.ledger_id) {
  1236. throw '提交数据错误';
  1237. }
  1238. const updateData = this._filterUpdateInvalidField(updateNode.id, data);
  1239. await this.transaction.update(this.tableName, updateData);
  1240. }
  1241. await this.transaction.commit();
  1242. } catch (err) {
  1243. await this.transaction.rollback();
  1244. throw err;
  1245. }
  1246. const filter = [];
  1247. for (const data of datas) {
  1248. filter.push(data.id);
  1249. }
  1250. this.initSqlBuilder();
  1251. this.sqlBuilder.setAndWhere('id', {
  1252. value: filter,
  1253. operate: 'in',
  1254. });
  1255. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  1256. const resultData = await this.db.query(sql, sqlParam);
  1257. return resultData;
  1258. }
  1259. /**
  1260. * 复制粘贴整块
  1261. * @param {Number} tenderId - 标段Id
  1262. * @param {Number} selectId - 选中几点Id
  1263. * @param {Array} block - 复制节点Id
  1264. * @return {Object} - 提价后的数据(其中新增粘贴数据,只返回第一层)
  1265. */
  1266. async pasteBlock(tenderId, selectId, block) {
  1267. if ((tenderId <= 0) || (selectId <= 0)) {
  1268. return [];
  1269. }
  1270. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1271. if (!selectData) {
  1272. throw '位置数据错误';
  1273. }
  1274. const newParentPath = selectData.full_path.replace(selectData.ledger_id, '');
  1275. const copyNodes = await this.getDataByNodeIds(tenderId, block);
  1276. if (!copyNodes || copyNodes.length <= 0) {
  1277. throw '复制数据错误';
  1278. }
  1279. let bSameParent = true;
  1280. for (const node of copyNodes) {
  1281. if (node.ledger_pid !== copyNodes[0].ledger_pid) {
  1282. bSameParent = false;
  1283. break;
  1284. }
  1285. }
  1286. if (!bSameParent) {
  1287. throw '复制数据错误:仅可操作同层节点';
  1288. }
  1289. const orgParentPath = copyNodes[0].full_path.replace(copyNodes[0].ledger_id, '');
  1290. const newIds = [];
  1291. this.transaction = await this.db.beginTransaction();
  1292. try {
  1293. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  1294. await this._updateSelectNextsOrder(selectData, copyNodes.length);
  1295. // 数据库创建新增节点数据
  1296. for (const node of copyNodes) {
  1297. const datas = await this.getDataByFullPath(tenderId, node.full_path + '%');
  1298. const cacheKey = keyPre + tenderId;
  1299. let maxId = parseInt(await this.cache.get(cacheKey));
  1300. if (!maxId) {
  1301. maxId = await this._getMaxNodeId(tenderId);
  1302. }
  1303. this.cache.set(cacheKey, maxId + datas.length, 'EX', this.ctx.app.config.cacheTime);
  1304. const leafBillsId = [];
  1305. // 计算粘贴数据中需更新部分
  1306. for (let index = 0; index < datas.length; index++) {
  1307. const data = datas[index];
  1308. const newId = maxId + index + 1;
  1309. const idChange = {
  1310. org: data.id,
  1311. };
  1312. delete data.id;
  1313. if (!data.is_leaf) {
  1314. for (const children of datas) {
  1315. children.full_path = children.full_path.replace('.' + data.ledger_id, '.' + newId);
  1316. if (children.ledger_pid === data.ledger_id) {
  1317. children.ledger_pid = newId;
  1318. }
  1319. }
  1320. } else {
  1321. data.full_path = data.full_path.replace('.' + data.ledger_id, '.' + newId);
  1322. }
  1323. data.ledger_id = newId;
  1324. data.full_path = data.full_path.replace(orgParentPath, newParentPath);
  1325. if (data.ledger_pid === copyNodes[0].ledger_pid) {
  1326. data.ledger_pid = selectData.ledger_pid;
  1327. data.order = selectData.order + index + 1;
  1328. }
  1329. data.level = data.level + selectData.level - copyNodes[0].level;
  1330. const newData = await this.transaction.insert(this.tableName, data);
  1331. if (data.is_leaf) {
  1332. idChange.new = newData.insertId;
  1333. leafBillsId.push(idChange);
  1334. }
  1335. newIds.push(newData.insertId);
  1336. }
  1337. for (const id of leafBillsId) {
  1338. await this.ctx.service.pos.copyBillsPosData(id.org, id.new, this.transaction);
  1339. }
  1340. }
  1341. await this.transaction.commit();
  1342. } catch (err) {
  1343. await this.transaction.rollback();
  1344. throw err;
  1345. }
  1346. // 查询应返回的结果
  1347. const order = [];
  1348. for (let i = 1; i <= copyNodes.length; i++) {
  1349. order.push(selectData.order + i);
  1350. }
  1351. const createData = await this.getDataByIds(newIds);
  1352. const updateData = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + copyNodes.length);
  1353. const posData = await this.ctx.service.pos.getPosData({ lid: newIds });
  1354. return {
  1355. ledger: { create: createData, update: updateData },
  1356. pos: posData,
  1357. };
  1358. }
  1359. /**
  1360. * 增量更新父项金额
  1361. * @param {Number} tenderId - 标段id
  1362. * @param {Object} updateMap - 增量更新数,使用更新父项的full_path为索引
  1363. * 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')
  1364. * @return {Promise<void>}
  1365. * @private
  1366. */
  1367. async _increCalcParent(tenderId, updateMap) {
  1368. for (const prop in updateMap) {
  1369. this.initSqlBuilder();
  1370. this.sqlBuilder.setAndWhere('tender_id', {
  1371. value: tenderId,
  1372. operate: '=',
  1373. });
  1374. const fullPath = this.ctx.helper.explodePath(prop);
  1375. this.sqlBuilder.setAndWhere('full_path', {
  1376. value: this.ctx.helper.explodePath(prop),
  1377. operate: 'in',
  1378. });
  1379. this.sqlBuilder.setUpdateData('total_price', {
  1380. value: updateMap[prop] > 0 ? updateMap[prop] : -updateMap[prop],
  1381. selfOperate: updateMap[prop] > 0 ? '+' : '-',
  1382. });
  1383. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  1384. await this.transaction.query(sql, sqlParam);
  1385. }
  1386. }
  1387. /**
  1388. * 提交数据 - 响应计算(增量方式计算)
  1389. * @param {Number} tenderId
  1390. * @param {Object} data
  1391. * @return {Promise<*>}
  1392. */
  1393. async updateCalc(tenderId, data) {
  1394. // 简单验证数据
  1395. if (tenderId <= 0) {
  1396. throw '标段不存在';
  1397. }
  1398. if (!data) {
  1399. throw '提交数据错误';
  1400. }
  1401. const datas = data instanceof Array ? data : [data];
  1402. const ids = [];
  1403. for (const row of datas) {
  1404. if (tenderId !== row.tender_id) {
  1405. throw '提交数据错误';
  1406. }
  1407. ids.push(row.id);
  1408. }
  1409. this.transaction = await this.db.beginTransaction();
  1410. try {
  1411. for (const row of datas) {
  1412. const updateNode = await this.getDataById(row.id);
  1413. if (!updateNode || tenderId !== updateNode.tender_id || row.ledger_id !== updateNode.ledger_id) {
  1414. throw '提交数据错误';
  1415. }
  1416. let updateData;
  1417. if (this._checkCalcField(row)) {
  1418. const calcData = this.ctx.helper.updateObj(updateNode, row);
  1419. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, updateNode.unit);
  1420. this.ctx.helper.checkFieldPrecision(calcData, qtyFields, precision.value);
  1421. if (updateNode.is_leaf) {
  1422. calcData.total_price = calcData.quantity * calcData.unit_price;
  1423. calcData.deal_tp = calcData.deal_qty * calcData.unit_price;
  1424. }
  1425. const data1 = this._filterChangedField(updateNode, calcData);
  1426. updateData = this._filterUpdateInvalidField(updateNode.id, data1);
  1427. } else {
  1428. updateData = this._filterUpdateInvalidField(updateNode.id, row);
  1429. }
  1430. await this.transaction.update(this.tableName, updateData);
  1431. }
  1432. await this.transaction.commit();
  1433. } catch (err) {
  1434. await this.transaction.rollback();
  1435. throw err;
  1436. }
  1437. return { update: await this.getDataByIds(ids) };
  1438. }
  1439. /**
  1440. *
  1441. * @param tenderId
  1442. * @param xmj
  1443. * @param order
  1444. * @param parentData
  1445. * @return {Promise<*[]>}
  1446. * @private
  1447. */
  1448. async _sortBatchInsertData(tenderId, xmj, order, parentData) {
  1449. const result = [],
  1450. newIds = [];
  1451. let tp = 0;
  1452. const cacheKey = keyPre + tenderId;
  1453. let maxId = parseInt(await this.cache.get(cacheKey));
  1454. if (!maxId) {
  1455. maxId = await this._getMaxNodeId(tenderId);
  1456. }
  1457. this.cache.set(cacheKey, maxId + xmj.children.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1458. // 添加xmj数据
  1459. const parent = {
  1460. tender_id: tenderId,
  1461. ledger_id: maxId + 1,
  1462. ledger_pid: parentData.ledger_id,
  1463. is_leaf: xmj.children.length === 0,
  1464. order,
  1465. level: parentData.level + 1,
  1466. name: xmj.name,
  1467. };
  1468. parent.full_path = parentData.full_path + '.' + parent.ledger_id;
  1469. // 添加gcl数据
  1470. for (let i = 0, iLen = xmj.children.length; i < iLen; i++) {
  1471. const gcl = xmj.children[i];
  1472. const child = {
  1473. tender_id: tenderId,
  1474. ledger_id: maxId + 1 + i + 1,
  1475. ledger_pid: parent.ledger_id,
  1476. is_leaf: true,
  1477. order: i + 1,
  1478. level: parent.level + 1,
  1479. b_code: gcl.b_code,
  1480. name: gcl.name,
  1481. unit: gcl.unit,
  1482. unit_price: gcl.unit_price,
  1483. quantity: gcl.quantity,
  1484. };
  1485. child.full_path = parent.full_path + '.' + child.ledger_id;
  1486. child.total_price = child.unit_price * child.quantity;
  1487. tp = tp + child.total_price;
  1488. result.push(child);
  1489. newIds.push(child.ledger_id);
  1490. }
  1491. parent.total_price = tp;
  1492. result.push(parent);
  1493. newIds.push(parent.ledger_id);
  1494. return [result, tp, newIds];
  1495. }
  1496. /**
  1497. * 批量插入子项
  1498. * @param {Number} tenderId - 标段Id
  1499. * @param {Number} selectId - 选中节点Id
  1500. * @param {Object} data - 批量插入数据
  1501. * @return {Promise<void>}
  1502. */
  1503. async batchInsertChild(tenderId, selectId, data) {
  1504. const result = { ledger: {}, pos: null };
  1505. if ((tenderId <= 0) || (selectId <= 0)) {
  1506. return result;
  1507. }
  1508. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1509. if (!selectData) {
  1510. throw '位置数据错误';
  1511. }
  1512. this.transaction = await this.db.beginTransaction();
  1513. const newIds = [];
  1514. try {
  1515. const lastChild = await this.getLastChildData(tenderId, selectId);
  1516. // 更新父项isLeaf
  1517. if (!lastChild) {
  1518. await this.transaction.update(this.tableName, {
  1519. id: selectData.id,
  1520. is_leaf: false,
  1521. });
  1522. }
  1523. const order = lastChild ? lastChild.order : 0;
  1524. // 计算id
  1525. const cacheKey = keyPre + tenderId;
  1526. let maxId = parseInt(await this.cache.get(cacheKey));
  1527. if (!maxId) {
  1528. maxId = await this._getMaxNodeId(tenderId);
  1529. }
  1530. // 数据库创建新增节点数据
  1531. for (let i = 0, iLen = data.length; i < iLen; i++) {
  1532. // 合并新增数据
  1533. const qd = {
  1534. tender_id: tenderId,
  1535. ledger_id: maxId + i + 1,
  1536. ledger_pid: selectData.ledger_id,
  1537. is_leaf: true,
  1538. order: order + i + 1,
  1539. level: selectData.level + 1,
  1540. b_code: data[i].b_code,
  1541. name: data[i].name,
  1542. unit: data[i].unit,
  1543. unit_price: data[i].price,
  1544. };
  1545. qd.full_path = selectData.full_path + '.' + qd.ledger_id;
  1546. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, qd.unit);
  1547. this.ctx.helper.checkPrecision(qd, qtyFields, precision.value);
  1548. const insertResult = await this.transaction.insert(this.tableName, qd);
  1549. newIds.push(insertResult.insertId);
  1550. await this.ctx.service.pos.insertLedgerPosData(this.transaction, tenderId, insertResult.insertId, data[i].pos);
  1551. await this.calc(tenderId, insertResult.insertId, this.transaction);
  1552. }
  1553. this.cache.set(cacheKey, maxId + data.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1554. await this.transaction.commit();
  1555. } catch (err) {
  1556. await this.transaction.rollback();
  1557. throw err;
  1558. }
  1559. // 查询应返回的结果
  1560. result.ledger.create = await this.getDataByIds(newIds);
  1561. result.pos = await this.ctx.service.pos.getPosData({ lid: newIds });
  1562. return result;
  1563. }
  1564. /**
  1565. * 批量插入后项
  1566. * @param {Number} tenderId - 标段Id
  1567. * @param {Number} selectId - 选中节点Id
  1568. * @param {Object} data - 批量插入数据
  1569. * @return {Promise<void>}
  1570. */
  1571. async batchInsertNext(tenderId, selectId, data) {
  1572. const result = { ledger: {}, pos: null };
  1573. if ((tenderId <= 0) || (selectId <= 0)) {
  1574. return result;
  1575. }
  1576. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1577. if (!selectData) {
  1578. throw '位置数据错误';
  1579. }
  1580. const parentData = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  1581. if (!parentData) {
  1582. throw '位置数据错误';
  1583. }
  1584. this.transaction = await this.db.beginTransaction();
  1585. const newIds = [];
  1586. try {
  1587. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  1588. await this._updateSelectNextsOrder(selectData, data.length);
  1589. // 计算id和order
  1590. const cacheKey = keyPre + tenderId;
  1591. let maxId = parseInt(await this.cache.get(cacheKey));
  1592. if (!maxId) {
  1593. maxId = await this._getMaxNodeId(tenderId);
  1594. }
  1595. const order = selectData.order;
  1596. // 数据库创建新增节点数据
  1597. for (let i = 0, iLen = data.length; i < iLen; i++) {
  1598. // 合并新增数据
  1599. const qd = {
  1600. tender_id: tenderId,
  1601. ledger_id: maxId + i + 1,
  1602. ledger_pid: parentData.ledger_id,
  1603. is_leaf: true,
  1604. order: order + i + 1,
  1605. level: parentData.level + 1,
  1606. b_code: data[i].b_code,
  1607. name: data[i].name,
  1608. unit: data[i].unit,
  1609. unit_price: data[i].price,
  1610. };
  1611. qd.full_path = parentData.full_path + '.' + qd.ledger_id;
  1612. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, qd.unit);
  1613. this.ctx.helper.checkPrecision(qd, qtyFields, precision.value);
  1614. const insertResult = await this.transaction.insert(this.tableName, qd);
  1615. newIds.push(insertResult.insertId);
  1616. await this.ctx.service.pos.insertLedgerPosData(this.transaction, tenderId, insertResult.insertId, data[i].pos);
  1617. await this.calc(tenderId, insertResult.insertId, this.transaction);
  1618. }
  1619. this.cache.set(cacheKey, maxId + data.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1620. await this.transaction.commit();
  1621. } catch (err) {
  1622. await this.transaction.rollback();
  1623. throw err;
  1624. }
  1625. // 查询应返回的结果
  1626. result.ledger.create = await this.getDataByIds(newIds);
  1627. result.ledger.update = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + data.length);
  1628. result.pos = await this.ctx.service.pos.getPosData({ lid: newIds });
  1629. return result;
  1630. }
  1631. /**
  1632. *
  1633. * @param {Number} tid - 标段id
  1634. * @param {Number} id - 需要计算的节点的id
  1635. * @param {Object} transaction - 操作所属事务,没有则创建
  1636. * @return {Promise<void>}
  1637. */
  1638. async calc(tid, id, transaction) {
  1639. const node = await this.getAllDataByCondition({ id });
  1640. if (!node) {
  1641. throw '数据错误';
  1642. }
  1643. const calcQtySql = 'UPDATE ??' +
  1644. ' SET `quantity` = (SELECT SUM(`quantity`) FROM ?? WHERE `lid` = ?), `total_price` = `quantity` * `unit_price`' +
  1645. ' WHERE `id` = ?';
  1646. await transaction.query(this.db.format(calcQtySql, [this.tableName, this.ctx.service.pos.tableName, id, id]));
  1647. }
  1648. /**
  1649. * 查找定位 --> 废弃
  1650. * @param tenderId
  1651. * @param nodeId
  1652. * @return {Promise<{expand: *}>}
  1653. */
  1654. async locateNode(tenderId, nodeId) {
  1655. const node = await this.getDataByNodeId(tenderId, nodeId);
  1656. if (!node) {
  1657. throw '查询数据有误';
  1658. }
  1659. const expandIds = node.full_path.split('.');
  1660. expandIds.pop();
  1661. const expandData = await this.getChildrenByParentId(tenderId, expandIds);
  1662. return { expand: expandData };
  1663. }
  1664. async _importCacheTreeNode(transaction, node) {
  1665. const data = {
  1666. tender_id: this.ctx.tender.id,
  1667. ledger_id: node.ledger_id,
  1668. ledger_pid: node.ledger_pid,
  1669. level: node.level,
  1670. order: node.order,
  1671. is_leaf: !node.children || node.children.length === 0,
  1672. full_path: node.full_path,
  1673. code: node.code,
  1674. b_code: node.b_code,
  1675. name: node.name,
  1676. unit: node.unit,
  1677. quantity: node.quantity,
  1678. unit_price: node.unit_price,
  1679. total_price: node.total_price,
  1680. dgn_qty1: node.dgn_qty1,
  1681. dgn_qty2: node.dgn_qty2,
  1682. memo: node.memo,
  1683. drawing_code: node.drawing_code,
  1684. };
  1685. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, data.unit);
  1686. this.ctx.helper.checkPrecision(data, qtyFields, precision.value);
  1687. const result = await transaction.insert(this.tableName, data);
  1688. if (node.children && node.children.length > 0) {
  1689. for (const child of node.children) {
  1690. await this._importCacheTreeNode(transaction, child);
  1691. }
  1692. } else if (node.pos && node.pos.length > 0) {
  1693. await this.ctx.service.pos.insertLedgerPosData(transaction, this.ctx.tender.id, result.insertId, node.pos);
  1694. }
  1695. }
  1696. async importExcel(excelData) {
  1697. const AnalysisExcel = require('../lib/analysis_excel');
  1698. const analysisExcel = new AnalysisExcel();
  1699. const tempData = await this.ctx.service.tenderNodeTemplate.getData(true);
  1700. const cacheTree = analysisExcel.analysisData(excelData, tempData);
  1701. const cacheKey = keyPre + this.ctx.tender.id;
  1702. const orgMaxId = parseInt(await this.cache.get(cacheKey));
  1703. const transaction = await this.db.beginTransaction();
  1704. try {
  1705. await transaction.delete(this.tableName, {tender_id: this.ctx.tender.id});
  1706. await transaction.delete(this.ctx.service.pos.tableName, {tid: this.ctx.tender.id});
  1707. for (const node of cacheTree.roots) {
  1708. await this._importCacheTreeNode(transaction, node);
  1709. }
  1710. await transaction.commit();
  1711. this.cache.set(cacheKey, cacheTree.items.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1712. } catch (err) {
  1713. await transaction.rollback();
  1714. if (orgMaxId) {
  1715. this.cache.set(cacheKey, orgMaxId, 'EX', this.ctx.app.config.cacheTime);
  1716. }
  1717. throw err;
  1718. }
  1719. }
  1720. }
  1721. return Ledger;
  1722. };