ledger.js 75 KB

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