ledger.js 82 KB

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