ledger.js 80 KB

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