ledger.js 81 KB

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