ledger.js 68 KB

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