ledger.js 79 KB

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