ledger.js 83 KB

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