ledger.js 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900
  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] !== 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. const calcData = this.ctx.helper.updateObj(updateNode, row);
  1458. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, updateNode.unit);
  1459. this.ctx.helper.checkFieldPrecision(calcData, qtyFields, precision.value);
  1460. if (updateNode.is_leaf) {
  1461. calcData.total_price = calcData.quantity * calcData.unit_price;
  1462. calcData.deal_tp = calcData.deal_qty * calcData.unit_price;
  1463. }
  1464. const data1 = this._filterChangedField(updateNode, calcData);
  1465. updateData = this._filterUpdateInvalidField(updateNode.id, data1);
  1466. } else {
  1467. updateData = this._filterUpdateInvalidField(updateNode.id, row);
  1468. }
  1469. await this.transaction.update(this.tableName, updateData);
  1470. }
  1471. await this.transaction.commit();
  1472. } catch (err) {
  1473. await this.transaction.rollback();
  1474. throw err;
  1475. }
  1476. return { update: await this.getDataByIds(ids) };
  1477. }
  1478. /**
  1479. *
  1480. * @param tenderId
  1481. * @param xmj
  1482. * @param order
  1483. * @param parentData
  1484. * @return {Promise<*[]>}
  1485. * @private
  1486. */
  1487. async _sortBatchInsertData(tenderId, xmj, order, parentData) {
  1488. const result = [],
  1489. newIds = [];
  1490. let tp = 0;
  1491. const cacheKey = keyPre + tenderId;
  1492. let maxId = parseInt(await this.cache.get(cacheKey));
  1493. if (!maxId) {
  1494. maxId = await this._getMaxNodeId(tenderId);
  1495. }
  1496. this.cache.set(cacheKey, maxId + xmj.children.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1497. // 添加xmj数据
  1498. const parent = {
  1499. tender_id: tenderId,
  1500. ledger_id: maxId + 1,
  1501. ledger_pid: parentData.ledger_id,
  1502. is_leaf: xmj.children.length === 0,
  1503. order,
  1504. level: parentData.level + 1,
  1505. name: xmj.name,
  1506. };
  1507. parent.full_path = parentData.full_path + '.' + parent.ledger_id;
  1508. // 添加gcl数据
  1509. for (let i = 0, iLen = xmj.children.length; i < iLen; i++) {
  1510. const gcl = xmj.children[i];
  1511. const child = {
  1512. tender_id: tenderId,
  1513. ledger_id: maxId + 1 + i + 1,
  1514. ledger_pid: parent.ledger_id,
  1515. is_leaf: true,
  1516. order: i + 1,
  1517. level: parent.level + 1,
  1518. b_code: gcl.b_code,
  1519. name: gcl.name,
  1520. unit: gcl.unit,
  1521. unit_price: gcl.unit_price,
  1522. quantity: gcl.quantity,
  1523. };
  1524. child.full_path = parent.full_path + '.' + child.ledger_id;
  1525. child.total_price = child.unit_price * child.quantity;
  1526. tp = tp + child.total_price;
  1527. result.push(child);
  1528. newIds.push(child.ledger_id);
  1529. }
  1530. parent.total_price = tp;
  1531. result.push(parent);
  1532. newIds.push(parent.ledger_id);
  1533. return [result, tp, newIds];
  1534. }
  1535. /**
  1536. * 批量插入子项
  1537. * @param {Number} tenderId - 标段Id
  1538. * @param {Number} selectId - 选中节点Id
  1539. * @param {Object} data - 批量插入数据
  1540. * @return {Promise<void>}
  1541. */
  1542. async batchInsertChild(tenderId, selectId, data) {
  1543. const result = { ledger: {}, pos: null };
  1544. if ((tenderId <= 0) || (selectId <= 0)) {
  1545. return result;
  1546. }
  1547. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1548. if (!selectData) {
  1549. throw '位置数据错误';
  1550. }
  1551. this.transaction = await this.db.beginTransaction();
  1552. const newIds = [];
  1553. try {
  1554. const lastChild = await this.getLastChildData(tenderId, selectId);
  1555. // 更新父项isLeaf
  1556. if (!lastChild) {
  1557. await this.transaction.update(this.tableName, {
  1558. id: selectData.id,
  1559. is_leaf: false,
  1560. });
  1561. }
  1562. const order = lastChild ? lastChild.order : 0;
  1563. // 计算id
  1564. const cacheKey = keyPre + tenderId;
  1565. let maxId = parseInt(await this.cache.get(cacheKey));
  1566. if (!maxId) {
  1567. maxId = await this._getMaxNodeId(tenderId);
  1568. }
  1569. // 数据库创建新增节点数据
  1570. for (let i = 0, iLen = data.length; i < iLen; i++) {
  1571. // 合并新增数据
  1572. const qd = {
  1573. tender_id: tenderId,
  1574. ledger_id: maxId + i + 1,
  1575. ledger_pid: selectData.ledger_id,
  1576. is_leaf: true,
  1577. order: order + i + 1,
  1578. level: selectData.level + 1,
  1579. b_code: data[i].b_code,
  1580. name: data[i].name,
  1581. unit: data[i].unit,
  1582. unit_price: data[i].price,
  1583. };
  1584. qd.full_path = selectData.full_path + '.' + qd.ledger_id;
  1585. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, qd.unit);
  1586. this.ctx.helper.checkFieldPrecision(qd, qtyFields, precision.value);
  1587. const insertResult = await this.transaction.insert(this.tableName, qd);
  1588. newIds.push(insertResult.insertId);
  1589. await this.ctx.service.pos.insertLedgerPosData(this.transaction, tenderId, insertResult.insertId, data[i].pos);
  1590. await this.calc(tenderId, insertResult.insertId, this.transaction);
  1591. }
  1592. this.cache.set(cacheKey, maxId + data.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1593. await this.transaction.commit();
  1594. } catch (err) {
  1595. await this.transaction.rollback();
  1596. throw err;
  1597. }
  1598. // 查询应返回的结果
  1599. result.ledger.create = await this.getDataByIds(newIds);
  1600. result.pos = await this.ctx.service.pos.getPosData({ lid: newIds });
  1601. return result;
  1602. }
  1603. /**
  1604. * 批量插入后项
  1605. * @param {Number} tenderId - 标段Id
  1606. * @param {Number} selectId - 选中节点Id
  1607. * @param {Object} data - 批量插入数据
  1608. * @return {Promise<void>}
  1609. */
  1610. async batchInsertNext(tenderId, selectId, data) {
  1611. const result = { ledger: {}, pos: null };
  1612. if ((tenderId <= 0) || (selectId <= 0)) {
  1613. return result;
  1614. }
  1615. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1616. if (!selectData) {
  1617. throw '位置数据错误';
  1618. }
  1619. const parentData = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  1620. if (!parentData) {
  1621. throw '位置数据错误';
  1622. }
  1623. this.transaction = await this.db.beginTransaction();
  1624. const newIds = [];
  1625. try {
  1626. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  1627. await this._updateSelectNextsOrder(selectData, data.length);
  1628. // 计算id和order
  1629. const cacheKey = keyPre + tenderId;
  1630. let maxId = parseInt(await this.cache.get(cacheKey));
  1631. if (!maxId) {
  1632. maxId = await this._getMaxNodeId(tenderId);
  1633. }
  1634. const order = selectData.order;
  1635. // 数据库创建新增节点数据
  1636. for (let i = 0, iLen = data.length; i < iLen; i++) {
  1637. // 合并新增数据
  1638. const qd = {
  1639. tender_id: tenderId,
  1640. ledger_id: maxId + i + 1,
  1641. ledger_pid: parentData.ledger_id,
  1642. is_leaf: true,
  1643. order: order + i + 1,
  1644. level: parentData.level + 1,
  1645. b_code: data[i].b_code,
  1646. name: data[i].name,
  1647. unit: data[i].unit,
  1648. unit_price: data[i].price,
  1649. };
  1650. qd.full_path = parentData.full_path + '.' + qd.ledger_id;
  1651. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, qd.unit);
  1652. this.ctx.helper.checkFieldPrecision(qd, qtyFields, precision.value);
  1653. const insertResult = await this.transaction.insert(this.tableName, qd);
  1654. newIds.push(insertResult.insertId);
  1655. await this.ctx.service.pos.insertLedgerPosData(this.transaction, tenderId, insertResult.insertId, data[i].pos);
  1656. await this.calc(tenderId, insertResult.insertId, this.transaction);
  1657. }
  1658. this.cache.set(cacheKey, maxId + data.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1659. await this.transaction.commit();
  1660. } catch (err) {
  1661. await this.transaction.rollback();
  1662. throw err;
  1663. }
  1664. // 查询应返回的结果
  1665. result.ledger.create = await this.getDataByIds(newIds);
  1666. result.ledger.update = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + data.length);
  1667. result.pos = await this.ctx.service.pos.getPosData({ lid: newIds });
  1668. return result;
  1669. }
  1670. /**
  1671. *
  1672. * @param {Number} tid - 标段id
  1673. * @param {Number} id - 需要计算的节点的id
  1674. * @param {Object} transaction - 操作所属事务,没有则创建
  1675. * @return {Promise<void>}
  1676. */
  1677. async calc(tid, id, transaction) {
  1678. const node = await this.getAllDataByCondition({ id });
  1679. if (!node) {
  1680. throw '数据错误';
  1681. }
  1682. const calcQtySql = 'UPDATE ??' +
  1683. ' SET `quantity` = (SELECT SUM(`quantity`) FROM ?? WHERE `lid` = ?), `total_price` = `quantity` * `unit_price`' +
  1684. ' WHERE `id` = ?';
  1685. await transaction.query(this.db.format(calcQtySql, [this.tableName, this.ctx.service.pos.tableName, id, id]));
  1686. }
  1687. /**
  1688. * 查找定位 --> 废弃
  1689. * @param tenderId
  1690. * @param nodeId
  1691. * @return {Promise<{expand: *}>}
  1692. */
  1693. async locateNode(tenderId, nodeId) {
  1694. const node = await this.getDataByNodeId(tenderId, nodeId);
  1695. if (!node) {
  1696. throw '查询数据有误';
  1697. }
  1698. const expandIds = node.full_path.split('.');
  1699. expandIds.pop();
  1700. const expandData = await this.getChildrenByParentId(tenderId, expandIds);
  1701. return { expand: expandData };
  1702. }
  1703. async _importCacheTreeNode(transaction, node) {
  1704. const data = {
  1705. tender_id: this.ctx.tender.id,
  1706. ledger_id: node.ledger_id,
  1707. ledger_pid: node.ledger_pid,
  1708. level: node.level,
  1709. order: node.order,
  1710. is_leaf: !node.children || node.children.length === 0,
  1711. full_path: node.full_path,
  1712. code: node.code,
  1713. b_code: node.b_code,
  1714. name: node.name,
  1715. unit: node.unit,
  1716. quantity: node.quantity,
  1717. unit_price: node.unit_price,
  1718. total_price: node.total_price,
  1719. dgn_qty1: node.dgn_qty1,
  1720. dgn_qty2: node.dgn_qty2,
  1721. memo: node.memo,
  1722. drawing_code: node.drawing_code,
  1723. };
  1724. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, data.unit);
  1725. this.ctx.helper.checkFieldPrecision(data, qtyFields, precision.value);
  1726. const result = await transaction.insert(this.tableName, data);
  1727. data.id = result.insertId;
  1728. if (node.children && node.children.length > 0) {
  1729. for (const child of node.children) {
  1730. await this._importCacheTreeNode(transaction, child);
  1731. }
  1732. } else if (node.pos && node.pos.length > 0) {
  1733. await this.ctx.service.pos.insertLedgerPosDataExcel(transaction, this.ctx.tender.id, data, node.pos);
  1734. }
  1735. }
  1736. async importExcel(excelData) {
  1737. const AnalysisExcel = require('../lib/analysis_excel');
  1738. const analysisExcel = new AnalysisExcel();
  1739. const tempData = await this.ctx.service.tenderNodeTemplate.getData(true);
  1740. const cacheTree = analysisExcel.analysisData(excelData, tempData);
  1741. const cacheKey = keyPre + this.ctx.tender.id;
  1742. const orgMaxId = parseInt(await this.cache.get(cacheKey));
  1743. const transaction = await this.db.beginTransaction();
  1744. try {
  1745. await transaction.delete(this.tableName, {tender_id: this.ctx.tender.id});
  1746. await transaction.delete(this.ctx.service.pos.tableName, {tid: this.ctx.tender.id});
  1747. for (const node of cacheTree.roots) {
  1748. await this._importCacheTreeNode(transaction, node);
  1749. }
  1750. await transaction.commit();
  1751. this.cache.set(cacheKey, cacheTree.items.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1752. } catch (err) {
  1753. await transaction.rollback();
  1754. if (orgMaxId) {
  1755. this.cache.set(cacheKey, orgMaxId, 'EX', this.ctx.app.config.cacheTime);
  1756. }
  1757. throw err;
  1758. }
  1759. }
  1760. }
  1761. return Ledger;
  1762. };