ledger.js 71 KB

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