ledger.js 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110
  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. 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. };
  700. result.code = stdData.code ? stdData.code : '';
  701. result.b_code = stdData.b_code ? stdData.b_code : '';
  702. return result;
  703. }
  704. /**
  705. * 添加节点(来自标准清单)
  706. * @param {Number} tenderId
  707. * @param {Number} selectId
  708. * @param {Object} stdData
  709. * @return {Promise<*>}
  710. */
  711. async addStdNode(tenderId, selectId, stdData) {
  712. const newData = this._filterStdData(stdData);
  713. const result = await this.addNode(tenderId, selectId, newData);
  714. return result;
  715. }
  716. /**
  717. * 新增子节点,并排在所有子节点的末尾
  718. * @param {Number} tenderId - 标段Id
  719. * @param {Number} selectId - 父节点Id
  720. * @param {Object} data - 新增节点数据(编号名称等)
  721. * @returns {Promise<*>}
  722. */
  723. async addChild(tenderId, selectId, data) {
  724. if ((tenderId <= 0) || (selectId <= 0)) {
  725. return [];
  726. }
  727. const selectData = await this.getDataByNodeId(tenderId, selectId);
  728. if (!selectData) {
  729. throw '新增节点数据错误';
  730. }
  731. const children = await this.getChildrenByParentId(tenderId, selectId);
  732. const cacheKey = keyPre + tenderId;
  733. let maxId = parseInt(await this.cache.get(cacheKey));
  734. if (!maxId) {
  735. maxId = await this._getMaxNodeId(tenderId);
  736. this.cache.set(cacheKey, maxId, 'EX', this.ctx.app.config.cacheTime);
  737. }
  738. data.id = this.uuid.v4();
  739. data.tender_id = tenderId;
  740. data.ledger_id = maxId + 1;
  741. data.ledger_pid = selectData.ledger_id;
  742. data.level = selectData.level + 1;
  743. data.order = children.length + 1;
  744. data.full_path = selectData.full_path + '.' + data.ledger_id;
  745. data.is_leaf = true;
  746. this.transaction = await this.db.beginTransaction();
  747. try {
  748. const result = await this.transaction.insert(this.tableName, data);
  749. if (children.length === 0) {
  750. await this.transaction.update(this.tableName,
  751. {is_leaf: false, quantity: null, unit_price: null, total_price: null, deal_qty: null, deal_tp: null},
  752. { where: {tender_id: tenderId, ledger_id: selectData.ledger_id} });
  753. }
  754. await this.transaction.commit();
  755. } catch(err) {
  756. this.transaction.rollback();
  757. throw err;
  758. }
  759. this.cache.set(cacheKey, maxId + 1, 'EX', this.ctx.app.config.cacheTime);
  760. // 查询应返回的结果
  761. const resultData = {};
  762. resultData.create = await this.getDataByNodeId(tenderId, data.ledger_id);
  763. if (children.length === 0) {
  764. resultData.update = await this.getDataByNodeId(tenderId, selectId);
  765. }
  766. return resultData;
  767. }
  768. /**
  769. * 添加标准节点,将选择的标准节点,添加为子节点(排序为末尾)
  770. * @param {Number} tenderId - 标段Id
  771. * @param {Number} selectId - 添加目标节点Id
  772. * @param {Object} stdData - 标准节点数据
  773. * @returns {Promise<*>}
  774. */
  775. async addStdNodeAsChild(tenderId, selectId, stdData) {
  776. const newData = this._filterStdData(stdData);
  777. const result = await this.addChild(tenderId, selectId, newData);
  778. return result;
  779. }
  780. /**
  781. * 添加节点,并同步添加父节点
  782. * @param {Number} tenderId - 标段id
  783. * @param {Number} selectId - 选中节点id
  784. * @param {Object} stdData - 节点数据
  785. * @param {StandardLib} stdLib - 标准库
  786. * @return {Promise<void>}
  787. */
  788. async addStdNodeWithParent(tenderId, stdData, stdLib) {
  789. // 查询完整标准清单,并按层次排序
  790. const fullLevel = await stdLib.getFullLevelDataByFullPath(stdData.list_id, stdData.full_path);
  791. fullLevel.sort(function(x, y) {
  792. return x.level - y.level;
  793. });
  794. let isNew = false,
  795. node,
  796. firstNew,
  797. updateParent,
  798. addResult;
  799. const expandIds = [];
  800. this.transaction = await this.db.beginTransaction();
  801. try {
  802. // 从最顶层节点依次查询是否存在,否则添加
  803. for (let i = 0, len = fullLevel.length; i < len; i++) {
  804. const stdNode = fullLevel[i];
  805. if (isNew) {
  806. const newData = this._filterStdData(stdNode);
  807. newData.is_leaf = (i === len - 1);
  808. [addResult, node] = await this._addChildNodeData(tenderId, node, newData);
  809. } else {
  810. const parent = node;
  811. node = await this.getDataByCondition({
  812. tender_id: tenderId,
  813. ledger_pid: parent ? parent.ledger_id : rootId,
  814. code: stdNode.code,
  815. name: stdNode.name,
  816. });
  817. if (!node) {
  818. isNew = true;
  819. const newData = this._filterStdData(stdNode);
  820. newData.is_leaf = (i === len - 1);
  821. [addResult, node] = await this._addChildAutoOrder(tenderId, parent, newData);
  822. if (parent && parent.is_leaf) {
  823. await this.transaction.update(this.tableName, { id: parent.id, is_leaf: false,
  824. unit_price: null, quantity: null, total_price: null, deal_qty: null, deal_tp: null});
  825. updateParent = parent;
  826. }
  827. firstNew = node;
  828. } else {
  829. expandIds.push(node.ledger_id);
  830. }
  831. }
  832. }
  833. await this.transaction.commit();
  834. } catch (err) {
  835. await this.transaction.rollback();
  836. throw err;
  837. }
  838. // 查询应返回的结果
  839. let createData = [],
  840. updateData = [];
  841. if (firstNew) {
  842. createData = await this.getDataByFullPath(tenderId, firstNew.full_path + '%');
  843. updateData = await this.getNextsData(tenderId, firstNew.ledger_pid, firstNew.order);
  844. if (updateParent) {
  845. updateData.push(await this.getDataByCondition({ id: updateParent.id }));
  846. }
  847. }
  848. //const expandData = await this.getChildrenByParentId(tenderId, expandIds);
  849. return { create: createData, update: updateData };
  850. }
  851. /**
  852. * 删除节点
  853. * @param {Number} tenderId - 标段id
  854. * @param {Object} deleteData - 删除节点数据
  855. * @return {Promise<*>}
  856. * @private
  857. */
  858. async _deleteNodeData(tenderId, deleteData) {
  859. this.initSqlBuilder();
  860. this.sqlBuilder.setAndWhere('tender_id', {
  861. value: tenderId,
  862. operate: '=',
  863. });
  864. this.sqlBuilder.setAndWhere('full_path', {
  865. value: this.db.escape(deleteData.full_path + '%'),
  866. operate: 'Like',
  867. });
  868. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'delete');
  869. const result = await this.transaction.query(sql, sqlParam);
  870. return result;
  871. }
  872. /**
  873. * tenderId标段中, 删除选中节点及其子节点
  874. *
  875. * @param {Number} tenderId - 标段id
  876. * @param {Number} selectId - 选中节点id
  877. * @return {Array} - 被删除的数据
  878. */
  879. async deleteNode(tenderId, selectId) {
  880. if ((tenderId <= 0) || (selectId <= 0)) {
  881. return [];
  882. }
  883. const selectData = await this.getDataByNodeId(tenderId, selectId);
  884. if (!selectData) {
  885. throw '删除节点数据错误';
  886. }
  887. const parentData = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  888. this.transaction = await this.db.beginTransaction();
  889. let deleteData = [];
  890. try {
  891. // 获取将要被删除的数据
  892. deleteData = await this.getDataByFullPath(tenderId, selectData.full_path + '%');
  893. // 删除
  894. const operate = await this._deleteNodeData(tenderId, selectData);
  895. // 选中节点--父节点 只有一个子节点时,应升级is_leaf
  896. if (parentData) {
  897. const count = await this.db.count(this.tableName, { tender_id: tenderId, ledger_pid: selectData.ledger_pid });
  898. if (count === 1) {
  899. await this.transaction.update(this.tableName, { id: parentData.id, is_leaf: true });
  900. }
  901. }
  902. // 选中节点--全部后节点 order--
  903. await this._updateSelectNextsOrder(selectData, -1);
  904. // 删除部位明细
  905. await this.transaction.delete(this.ctx.service.pos.tableName, { tid: tenderId, lid: this._.map(deleteData, 'id') });
  906. await this.ctx.service.pos.deletePosData(this.transaction, tenderId, this._.map(deleteData, 'id'));
  907. await this.transaction.commit();
  908. } catch (err) {
  909. deleteData = [];
  910. await this.transaction.rollback();
  911. throw err;
  912. }
  913. // 查询结果
  914. let updateData = [];
  915. if (deleteData.length > 0) {
  916. updateData = await this.getNextsData(tenderId, selectData.ledger_pid, selectData.order - 1);
  917. updateData = updateData ? updateData : [];
  918. if (selectData.ledger_pid !== rootId) {
  919. const updateData1 = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  920. if (updateData1.is_leaf !== parentData.is_leaf) {
  921. updateData.push(updateData1);
  922. }
  923. }
  924. }
  925. return { delete: deleteData, update: updateData };
  926. }
  927. async deleteNodes(tenderId, Ids) {
  928. }
  929. /**
  930. * tenderId标段中, 选中节点selectId上移
  931. *
  932. * @param {Number} tenderId - 标段id
  933. * @param {Number} selectId - 选中节点id
  934. * @return {Array} - 发生改变的数据
  935. */
  936. async upMoveNode(tenderId, selectId) {
  937. if ((tenderId <= 0) || (selectId <= 0)) {
  938. return [];
  939. }
  940. const selectData = await this.getDataByNodeId(tenderId, selectId);
  941. if (!selectData) {
  942. throw '上移节点数据错误';
  943. }
  944. const preData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, selectData.order - 1);
  945. if (!preData) {
  946. throw '节点不可上移';
  947. }
  948. this.transaction = await this.db.beginTransaction();
  949. try {
  950. const sData = await this.transaction.update(this.tableName, { id: selectData.id, order: selectData.order - 1 });
  951. const pData = await this.transaction.update(this.tableName, { id: preData.id, order: preData.order + 1 });
  952. await this.transaction.commit();
  953. } catch (err) {
  954. await this.transaction.rollback();
  955. throw err;
  956. }
  957. const resultData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, [selectData.order, preData.order]);
  958. return { update: resultData };
  959. }
  960. /**
  961. * tenderId标段中, 选中节点selectId下移
  962. *
  963. * @param {Number} tenderId - 标段id
  964. * @param {Number} selectId - 选中节点id
  965. * @return {Array} - 发生改变的数据
  966. */
  967. async downMoveNode(tenderId, selectId) {
  968. if ((tenderId <= 0) || (selectId <= 0)) {
  969. return [];
  970. }
  971. const selectData = await this.getDataByNodeId(tenderId, selectId);
  972. if (!selectData) {
  973. throw '下移节点数据错误';
  974. }
  975. const nextData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, selectData.order + 1);
  976. if (!nextData) {
  977. throw '节点不可下移';
  978. }
  979. this.transaction = await this.db.beginTransaction();
  980. try {
  981. const sData = await this.transaction.update(this.tableName, { id: selectData.id, order: selectData.order + 1 });
  982. const pData = await this.transaction.update(this.tableName, { id: nextData.id, order: nextData.order - 1 });
  983. await this.transaction.commit();
  984. } catch (err) {
  985. await this.transaction.rollback();
  986. throw err;
  987. }
  988. const resultData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, [selectData.order, nextData.order]);
  989. return { update: resultData };
  990. }
  991. /**
  992. * 升级selectData, 同步修改所有子节点
  993. * @param {Object} selectData - 升级操作,选中节点
  994. * @return {Object}
  995. * @private
  996. */
  997. async _syncUplevelChildren(selectData) {
  998. this.initSqlBuilder();
  999. this.sqlBuilder.setAndWhere('tender_id', {
  1000. value: selectData.tender_id,
  1001. operate: '=',
  1002. });
  1003. this.sqlBuilder.setAndWhere('full_path', {
  1004. value: this.db.escape(selectData.full_path + '.%'),
  1005. operate: 'like',
  1006. });
  1007. this.sqlBuilder.setUpdateData('level', {
  1008. value: 1,
  1009. selfOperate: '-',
  1010. });
  1011. this.sqlBuilder.setUpdateData('full_path', {
  1012. value: ['`full_path`', this.db.escape(selectData.ledger_pid + '.'), this.db.escape('')],
  1013. literal: 'Replace',
  1014. });
  1015. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  1016. const data = await this.transaction.query(sql, sqlParam);
  1017. return data;
  1018. }
  1019. /**
  1020. * 选中节点的后兄弟节点,全部变为当前节点的子节点
  1021. * @param {Object} selectData - 选中节点
  1022. * @return {Object}
  1023. * @private
  1024. */
  1025. async _syncUpLevelNexts(selectData) {
  1026. // 查询selectData的lastChild
  1027. const lastChildData = await this.getLastChildData(selectData.tender_id, selectData.ledger_id);
  1028. const nextsData = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order);
  1029. if (nextsData && nextsData.length > 0) {
  1030. // 修改nextsData pid, 排序
  1031. this.initSqlBuilder();
  1032. this.sqlBuilder.setUpdateData('ledger_pid', {
  1033. value: selectData.ledger_id,
  1034. });
  1035. const orderInc = lastChildData ? lastChildData.order - selectData.order : -selectData.order;
  1036. this.sqlBuilder.setUpdateData('order', {
  1037. value: Math.abs(orderInc),
  1038. selfOperate: orderInc > 0 ? '+' : '-',
  1039. });
  1040. this.sqlBuilder.setAndWhere('tender_id', {
  1041. value: selectData.tender_id,
  1042. operate: '=',
  1043. });
  1044. this.sqlBuilder.setAndWhere('ledger_pid', {
  1045. value: selectData.ledger_pid,
  1046. operate: '=',
  1047. });
  1048. this.sqlBuilder.setAndWhere('order', {
  1049. value: selectData.order,
  1050. operate: '>',
  1051. });
  1052. const [sql1, sqlParam1] = this.sqlBuilder.build(this.tableName, 'update');
  1053. await this.transaction.query(sql1, sqlParam1);
  1054. // 选中节点 is_leaf应为false
  1055. if (selectData.is_leaf) {
  1056. const updateData = { id: selectData.id,
  1057. is_leaf: false,
  1058. };
  1059. await this.transaction.update(this.tableName, updateData);
  1060. }
  1061. // 修改nextsData及其子节点的full_path
  1062. const oldSubStr = this.db.escape(selectData.ledger_pid + '.');
  1063. const newSubStr = this.db.escape(selectData.ledger_id + '.');
  1064. const sqlArr = [];
  1065. sqlArr.push('Update ?? SET `full_path` = Replace(`full_path`,' + oldSubStr + ',' + newSubStr + ') Where');
  1066. sqlArr.push('(`tender_id` = ' + selectData.tender_id + ')');
  1067. sqlArr.push(' And (');
  1068. for (const data of nextsData) {
  1069. sqlArr.push('`full_path` Like ' + this.db.escape(data.full_path + '%'));
  1070. if (nextsData.indexOf(data) < nextsData.length - 1) {
  1071. sqlArr.push(' Or ');
  1072. }
  1073. }
  1074. sqlArr.push(')');
  1075. const sql = sqlArr.join('');
  1076. const resultData = await this.transaction.query(sql, [this.tableName]);
  1077. return resultData;
  1078. }
  1079. }
  1080. /**
  1081. * 升级节点
  1082. *
  1083. * @param {Number} tenderId - 标段id
  1084. * @param {Number} selectId - 选中节点id
  1085. * @return {Array} - 发生改变的数据
  1086. */
  1087. async upLevelNode(tenderId, selectId) {
  1088. if ((tenderId <= 0) || (selectId <= 0)) {
  1089. return [];
  1090. }
  1091. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1092. if (!selectData) {
  1093. throw '升级节点数据错误';
  1094. }
  1095. const parentData = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  1096. if (!parentData) {
  1097. throw '升级节点数据错误';
  1098. }
  1099. this.transaction = await this.db.beginTransaction();
  1100. const newFullPath = selectData.full_path.replace(selectData.ledger_pid + '.', '');
  1101. try {
  1102. // 选中节点--父节点 选中节点为firstChild时,修改is_leaf
  1103. if (selectData.order === 1) {
  1104. await this.transaction.update(this.tableName, {
  1105. id: parentData.id,
  1106. is_leaf: true,
  1107. });
  1108. }
  1109. // 选中节点--父节点--全部后兄弟节点 order+1
  1110. await this._updateSelectNextsOrder(parentData);
  1111. // 选中节点 修改pid, order, full_path, level, is_leaf, 清空计算项
  1112. const updateData = {
  1113. id: selectData.id,
  1114. ledger_pid: parentData.ledger_pid,
  1115. order: parentData.order + 1,
  1116. level: selectData.level - 1,
  1117. full_path: newFullPath,
  1118. };
  1119. const nexts = await this.getNextsData(tenderId, parentData.ledger_id, selectData.order);
  1120. if (nexts.length > 0) {
  1121. updateData.is_leaf = true;
  1122. updateData.unit_price = null;
  1123. updateData.quantity = null;
  1124. updateData.total_price = null;
  1125. updateData.deal_qty = null;
  1126. updateData.deal_tp = null;
  1127. }
  1128. await this.transaction.update(this.tableName, updateData);
  1129. // 选中节点--全部子节点(含孙) level-1, full_path变更
  1130. await this._syncUplevelChildren(selectData);
  1131. // 选中节点--全部后兄弟节点 收编为子节点 修改pid, order, full_path
  1132. await this._syncUpLevelNexts(selectData);
  1133. await this.transaction.commit();
  1134. } catch (err) {
  1135. await this.transaction.rollback();
  1136. throw err;
  1137. }
  1138. // 查询修改的数据
  1139. const resultData1 = await this.getDataByFullPath(tenderId, newFullPath + '%');
  1140. const resultData2 = await this.getNextsData(tenderId, parentData.ledger_pid, parentData.order + 1);
  1141. // 默认原Parent被刷新过,不核对total_price修改
  1142. const preParent = await this.getDataByNodeId(tenderId, parentData.ledger_id);
  1143. resultData2.push(preParent);
  1144. return { update: resultData1.concat(resultData2) };
  1145. }
  1146. /**
  1147. * 降级selectData, 同步修改所有子节点
  1148. * @param {Object} selectData - 选中节点
  1149. * @param {Object} preData - 选中节点的前一节点(降级后为父节点)
  1150. * @return {Promise<*>}
  1151. * @private
  1152. */
  1153. async _syncDownlevelChildren(selectData, preData) {
  1154. this.initSqlBuilder();
  1155. this.sqlBuilder.setAndWhere('tender_id', {
  1156. value: selectData.tender_id,
  1157. operate: '=',
  1158. });
  1159. this.sqlBuilder.setAndWhere('full_path', {
  1160. value: this.db.escape(selectData.full_path + '.%'),
  1161. operate: 'like',
  1162. });
  1163. this.sqlBuilder.setUpdateData('level', {
  1164. value: 1,
  1165. selfOperate: '+',
  1166. });
  1167. this.sqlBuilder.setUpdateData('full_path', {
  1168. value: ['`full_path`', this.db.escape('.' + selectData.ledger_id), this.db.escape('.' + preData.ledger_id + '.' + selectData.ledger_id)],
  1169. literal: 'Replace',
  1170. });
  1171. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  1172. const data = await this.transaction.query(sql, sqlParam);
  1173. return data;
  1174. }
  1175. /**
  1176. * 降级节点
  1177. *
  1178. * @param {Number} tenderId - 标段id
  1179. * @param {Number} selectId - 选中节点id
  1180. * @return {Array} - 发生改变的数据
  1181. */
  1182. async downLevelNode(tenderId, selectId) {
  1183. if ((tenderId <= 0) || (selectId <= 0)) {
  1184. return [];
  1185. }
  1186. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1187. if (!selectData) {
  1188. throw '降级节点数据错误';
  1189. }
  1190. const preData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, selectData.order - 1);
  1191. if (!preData) {
  1192. throw '节点不可降级';
  1193. }
  1194. const preLastChildData = await this.getLastChildData(tenderId, preData.ledger_id);
  1195. this.transaction = await this.db.beginTransaction();
  1196. const orgLastPath = selectData.level === 1 ? selectData.ledger_id : '.' + selectData.ledger_id;
  1197. const newLastPath = selectData.level === 1 ? preData.ledger_id + '.' + selectData.ledger_id : '.' + preData.ledger_id + '.' + selectData.ledger_id;
  1198. const newFullPath = selectData.full_path.replace(orgLastPath, newLastPath);
  1199. try {
  1200. // 选中节点--全部后节点 order--
  1201. await this._updateSelectNextsOrder(selectData, -1);
  1202. // 选中节点 修改pid, level, order, full_path
  1203. const updateData = {
  1204. id: selectData.id,
  1205. ledger_pid: preData.ledger_id,
  1206. order: preLastChildData ? preLastChildData.order + 1 : 1,
  1207. level: selectData.level + 1,
  1208. full_path: newFullPath,
  1209. };
  1210. await this.transaction.update(this.tableName, updateData);
  1211. // 选中节点--全部子节点(含孙) level++, full_path
  1212. await this._syncDownlevelChildren(selectData, preData);
  1213. // 选中节点--前兄弟节点 is_leaf应为false, 清空计算相关字段
  1214. if (preData.is_leaf || preData.unit_price || preData.quantity || preData.total_price || preData.deal_qty || preData.deal_tp) {
  1215. const updateData2 = {
  1216. id: preData.id,
  1217. is_leaf: false,
  1218. unit_price: null,
  1219. quantity: null,
  1220. total_price: null,
  1221. deal_qty: null,
  1222. deal_tp: null,
  1223. };
  1224. await this.transaction.update(this.tableName, updateData2);
  1225. }
  1226. await this.transaction.commit();
  1227. } catch (err) {
  1228. await this.transaction.rollback();
  1229. throw err;
  1230. }
  1231. // 查询修改的数据
  1232. // 选中节点及子节点
  1233. const resultData1 = await this.getDataByFullPath(tenderId, newFullPath + '%');
  1234. // 选中节点--原前兄弟节点&全部后兄弟节点
  1235. const queryOrder = (preData.is_leaf || this.ctx.helper.checkZero(selectData.total_price)) ? preData.order - 1 : preData.order;
  1236. const resultData2 = await this.getNextsData(tenderId, preData.ledger_pid, queryOrder);
  1237. return { update: resultData1.concat(resultData2) };
  1238. }
  1239. /**
  1240. * 过滤data中update方式不可提交的字段
  1241. * @param {Number} id - 主键key
  1242. * @param {Object} data
  1243. * @return {Object<{id: *}>}
  1244. * @private
  1245. */
  1246. _filterUpdateInvalidField(id, data) {
  1247. const result = {
  1248. id,
  1249. };
  1250. for (const prop in data) {
  1251. if (readOnlyFields.indexOf(prop) === -1) {
  1252. result[prop] = data[prop];
  1253. }
  1254. }
  1255. return result;
  1256. }
  1257. /**
  1258. * newData中,以orgData为基准,过滤掉orgData中未定义或值相等的部分
  1259. * @param {Object} orgData
  1260. * @param {Object} newData
  1261. * @private
  1262. */
  1263. _filterChangedField(orgData, newData) {
  1264. const result = {};
  1265. let bChanged = false;
  1266. for (const prop in orgData) {
  1267. if (this._.isEmpty(newData[prop]) && newData[prop] !== orgData[prop]) {
  1268. result[prop] = newData[prop];
  1269. bChanged = true;
  1270. }
  1271. }
  1272. return bChanged ? result : undefined;
  1273. }
  1274. _checkField(data, field) {
  1275. const fields = field instanceof Array ? field : [field];
  1276. for (const prop in data) {
  1277. if (fields.indexOf(prop) >= 0) {
  1278. return true;
  1279. }
  1280. }
  1281. return false;
  1282. }
  1283. /**
  1284. * 检查data中是否含有计算字段
  1285. * @param {Object} data
  1286. * @return {boolean}
  1287. * @private
  1288. */
  1289. _checkCalcField(data) {
  1290. for (const prop in data) {
  1291. if (calcFields.indexOf(prop) >= 0) {
  1292. return true;
  1293. }
  1294. }
  1295. return false;
  1296. }
  1297. /**
  1298. * 提交数据 - 不影响计算等未提交项
  1299. * @param {Number} tenderId - 标段id
  1300. * @param {Object} data - 提交数据
  1301. * @return {Object} - 提交后的数据
  1302. */
  1303. async updateInfo(tenderId, data) {
  1304. // 简单校验数据
  1305. if (tenderId <= 0) {
  1306. throw '标段不存在';
  1307. }
  1308. if (tenderId !== data.tender_id) {
  1309. throw '提交数据错误';
  1310. }
  1311. try {
  1312. // 过滤不可提交字段
  1313. const updateNode = await this.getDataById(data.id);
  1314. if (!updateNode || tenderId !== updateNode.tender_id || data.ledger_id !== updateNode.ledger_id) {
  1315. throw '提交数据错误';
  1316. }
  1317. const updateData = this._filterUpdateInvalidField(updateNode.id, data);
  1318. await this.db.update(this.tableName, updateData);
  1319. } catch (err) {
  1320. throw err;
  1321. }
  1322. const result = await this.getDataByNodeId(tenderId, data.ledger_id);
  1323. return result;
  1324. }
  1325. /**
  1326. * 提交多条数据 - 不影响计算等未提交项
  1327. * @param {Number} tenderId - 标段id
  1328. * @param {Array} datas - 提交数据
  1329. * @return {Array} - 提交后的数据
  1330. */
  1331. async updateInfos(tenderId, datas) {
  1332. if (tenderId <= 0) {
  1333. throw '标段不存在';
  1334. }
  1335. for (const data of datas) {
  1336. if (tenderId !== data.tender_id) {
  1337. throw '提交数据错误';
  1338. }
  1339. }
  1340. this.transaction = await this.db.beginTransaction();
  1341. try {
  1342. for (const data of datas) {
  1343. const updateNode = await this.getDataById(data.id);
  1344. if (!updateNode || tenderId !== updateNode.tender_id || data.ledger_id !== updateNode.ledger_id) {
  1345. throw '提交数据错误';
  1346. }
  1347. const updateData = this._filterUpdateInvalidField(updateNode.id, data);
  1348. await this.transaction.update(this.tableName, updateData);
  1349. }
  1350. await this.transaction.commit();
  1351. } catch (err) {
  1352. await this.transaction.rollback();
  1353. throw err;
  1354. }
  1355. const filter = [];
  1356. for (const data of datas) {
  1357. filter.push(data.id);
  1358. }
  1359. this.initSqlBuilder();
  1360. this.sqlBuilder.setAndWhere('id', {
  1361. value: filter,
  1362. operate: 'in',
  1363. });
  1364. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  1365. const resultData = await this.db.query(sql, sqlParam);
  1366. return resultData;
  1367. }
  1368. /**
  1369. * 复制粘贴整块
  1370. * @param {Number} tenderId - 标段Id
  1371. * @param {Number} selectId - 选中几点Id
  1372. * @param {Array} block - 复制节点Id
  1373. * @return {Object} - 提价后的数据(其中新增粘贴数据,只返回第一层)
  1374. */
  1375. async pasteBlock(tenderId, selectId, block) {
  1376. console.log(1);
  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. console.log(2);
  1401. const newIds = [];
  1402. this.transaction = await this.db.beginTransaction();
  1403. try {
  1404. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  1405. await this._updateSelectNextsOrder(selectData, copyNodes.length);
  1406. // 数据库创建新增节点数据
  1407. for (let iNode = 0; iNode < copyNodes.length; iNode++) {
  1408. const node = copyNodes[iNode];
  1409. let datas = await this.getDataByFullPath(tenderId, node.full_path + '%');
  1410. datas = this._.sortBy(datas, 'level');
  1411. const cacheKey = keyPre + this.ctx.tender.id;
  1412. let maxId = parseInt(await this.cache.get(cacheKey));
  1413. if (!maxId) {
  1414. maxId = await this._getMaxNodeId(this.ctx.tender.id);
  1415. }
  1416. this.cache.set(cacheKey, maxId + datas.length, 'EX', this.ctx.app.config.cacheTime);
  1417. const leafBillsId = [];
  1418. // 计算粘贴数据中需更新部分
  1419. for (let index = 0; index < datas.length; index++) {
  1420. const data = datas[index];
  1421. const newId = maxId + index + 1;
  1422. const idChange = {
  1423. org: data.id,
  1424. };
  1425. data.id = this.uuid.v4();
  1426. idChange.new = data.id;
  1427. data.tender_id = this.ctx.tender.id;
  1428. if (!data.is_leaf) {
  1429. for (const children of datas) {
  1430. children.full_path = children.full_path.replace('.' + data.ledger_id, '.' + newId);
  1431. if (children.ledger_pid === data.ledger_id) {
  1432. children.ledger_pid = newId;
  1433. }
  1434. }
  1435. } else {
  1436. data.full_path = data.full_path.replace('.' + data.ledger_id, '.' + newId);
  1437. }
  1438. data.ledger_id = newId;
  1439. data.full_path = data.full_path.replace(orgParentPath, newParentPath);
  1440. if (data.ledger_pid === node.ledger_pid) {
  1441. data.ledger_pid = selectData.ledger_pid;
  1442. data.order = selectData.order + iNode + 1;
  1443. }
  1444. data.level = data.level + selectData.level - copyNodes[0].level;
  1445. if (data.is_leaf) {
  1446. leafBillsId.push(idChange);
  1447. }
  1448. newIds.push(data.id);
  1449. }
  1450. const newData = await this.transaction.insert(this.tableName, datas);
  1451. for (const id of leafBillsId) {
  1452. await this.ctx.service.pos.copyBillsPosData(id.org, id.new, this.transaction);
  1453. }
  1454. }
  1455. await this.transaction.commit();
  1456. } catch (err) {
  1457. await this.transaction.rollback();
  1458. throw err;
  1459. }
  1460. console.log(3);
  1461. // 查询应返回的结果
  1462. const order = [];
  1463. for (let i = 1; i <= copyNodes.length; i++) {
  1464. order.push(selectData.order + i);
  1465. }
  1466. const createData = await this.getDataByIds(newIds);
  1467. const updateData = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + copyNodes.length);
  1468. const posData = await this.ctx.service.pos.getPosData({ lid: newIds });
  1469. return {
  1470. ledger: { create: createData, update: updateData },
  1471. pos: posData,
  1472. };
  1473. console.log(4);
  1474. }
  1475. /**
  1476. * 增量更新父项金额
  1477. * @param {Number} tenderId - 标段id
  1478. * @param {Object} updateMap - 增量更新数,使用更新父项的full_path为索引
  1479. * 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')
  1480. * @return {Promise<void>}
  1481. * @private
  1482. */
  1483. async _increCalcParent(tenderId, updateMap) {
  1484. for (const prop in updateMap) {
  1485. this.initSqlBuilder();
  1486. this.sqlBuilder.setAndWhere('tender_id', {
  1487. value: tenderId,
  1488. operate: '=',
  1489. });
  1490. const fullPath = this.ctx.helper.explodePath(prop);
  1491. this.sqlBuilder.setAndWhere('full_path', {
  1492. value: this.ctx.helper.explodePath(prop),
  1493. operate: 'in',
  1494. });
  1495. this.sqlBuilder.setUpdateData('total_price', {
  1496. value: updateMap[prop] > 0 ? updateMap[prop] : -updateMap[prop],
  1497. selfOperate: updateMap[prop] > 0 ? '+' : '-',
  1498. });
  1499. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  1500. await this.transaction.query(sql, sqlParam);
  1501. }
  1502. }
  1503. /**
  1504. * 提交数据 - 响应计算(增量方式计算)
  1505. * @param {Number} tenderId
  1506. * @param {Object} data
  1507. * @return {Promise<*>}
  1508. */
  1509. async updateCalc(tenderId, data) {
  1510. // 简单验证数据
  1511. if (tenderId <= 0 || !this.ctx.tender) {
  1512. throw '标段不存在';
  1513. }
  1514. const info = this.ctx.tender.info;
  1515. if (!data) {
  1516. throw '提交数据错误';
  1517. }
  1518. const datas = data instanceof Array ? data : [data];
  1519. const ids = [];
  1520. for (const row of datas) {
  1521. if (tenderId !== row.tender_id) {
  1522. throw '提交数据错误';
  1523. }
  1524. ids.push(row.id);
  1525. }
  1526. this.transaction = await this.db.beginTransaction();
  1527. try {
  1528. for (const row of datas) {
  1529. const updateNode = await this.getDataById(row.id);
  1530. if (!updateNode || tenderId !== updateNode.tender_id || row.ledger_id !== updateNode.ledger_id) {
  1531. throw '提交数据错误';
  1532. }
  1533. let updateData;
  1534. if (row.unit) {
  1535. if (row.sgfh_qty === undefined) { row.sgfh_qty = updateNode.sgfh_qty; }
  1536. if (row.sjcl_qty === undefined) { row.sjcl_qty = updateNode.sjcl_qty; }
  1537. if (row.qtcl_qty === undefined) { row.qtcl_qty = updateNode.qtcl_qty; }
  1538. if (row.deal_qty === undefined) { row.deal_qty = updateNode.deal_qty; }
  1539. }
  1540. if (row.b_code) {
  1541. row.dgn_qty1 = null;
  1542. row.dgn_qty2 = null;
  1543. }
  1544. if (this._checkCalcField(row)) {
  1545. let calcData = JSON.parse(JSON.stringify(row));
  1546. const precision = this.ctx.helper.findPrecision(info.precision, row.unit ? row.unit : updateNode.unit);
  1547. // 数量保留小数位数
  1548. this.ctx.helper.checkFieldPrecision(calcData, qtyFields, precision.value);
  1549. // 单位保留小数位数
  1550. this.ctx.helper.checkFieldPrecision(calcData, upFields, info.decimal.up);
  1551. // 未提交单价则读取数据库单价
  1552. if (row.unit_price === undefined) calcData.unit_price = updateNode.unit_price;
  1553. // 计算
  1554. if (row.sgfh_qty !== undefined || row.sjcl_qty !== undefined || row.qtcl_qty !== undefined ||
  1555. row.deal_qty !== undefined || row.unit_price) {
  1556. if (row.sgfh_qty === undefined) calcData.sgfh_qty = updateNode.sgfh_qty;
  1557. if (row.sjcl_qty === undefined) calcData.sjcl_qty = updateNode.sjcl_qty;
  1558. if (row.qtcl_qty === undefined) calcData.qtcl_qty = updateNode.qtcl_qty;
  1559. if (row.deal_qty === undefined) calcData.deal_qty = updateNode.deal_qty;
  1560. calcData.quantity = this.ctx.helper.sum([calcData.sgfh_qty, calcData.sjcl_qty, calcData.qtcl_qty]);
  1561. calcData.sgfh_tp = this.ctx.helper.mul(calcData.sgfh_qty, calcData.unit_price, info.decimal.tp);
  1562. calcData.sjcl_tp = this.ctx.helper.mul(calcData.sjcl_qty, calcData.unit_price, info.decimal.tp);
  1563. calcData.qtcl_tp = this.ctx.helper.mul(calcData.qtcl_qty, calcData.unit_price, info.decimal.tp);
  1564. calcData.total_price = this.ctx.helper.mul(calcData.quantity, calcData.unit_price, info.decimal.tp);
  1565. calcData.deal_tp = this.ctx.helper.mul(calcData.deal_qty, calcData.unit_price, info.decimal.tp);
  1566. } else if (row.sgfh_tp !== undefined || row.sjcl_tp !== undefined || row.qtcl_tp !== undefined || row.deal_tp !== undefined) {
  1567. calcData.sgfh_qty = null;
  1568. calcData.sjcl_qty = null;
  1569. calcData.qtcl_qty = null;
  1570. calcData.quantity = null;
  1571. calcData.deal_qty = null;
  1572. calcData.sgfh_tp = (row.sgfh_tp !== undefined) ? this.ctx.helper.round(calcData.row.sgfh_tp, info.decimal.tp) : updateNode.sgfh_tp;
  1573. calcData.sjcl_tp = (row.sgfh_tp !== undefined) ? this.ctx.helper.round(calcData.row.sjcl_tp, info.decimal.tp) : updateNode.sjcl_tp;
  1574. calcData.qtcl_tp = (row.sgfh_tp !== undefined) ? this.ctx.helper.round(calcData.row.qtcl_tp, info.decimal.tp) : updateNode.qtcl_tp;
  1575. calcData.total_price = this.ctx.helper.sum([calcData.sgfh_tp, calcData.sjcl_tp, calcData.qtcl_tp]);
  1576. calcData.deal_tp = (row.deal_tp !== undefined) ? this.ctx.helper.round(calcData.row.deal_tp, info.decimal.tp) : updateNode.deal_tp;
  1577. } else if (row.unit_price !== undefined) {
  1578. calcData.sgfh_tp = this.ctx.helper.mul(calcData.sgfh_qty, calcData.unit_price, info.decimal.tp);
  1579. calcData.sjcl_tp = this.ctx.helper.mul(calcData.sjcl_qty, calcData.unit_price, info.decimal.tp);
  1580. calcData.qtcl_tp = this.ctx.helper.mul(calcData.qtcl_qty, calcData.unit_price, info.decimal.tp);
  1581. calcData.total_price = this.ctx.helper.mul(calcData.quantity, calcData.unit_price, info.decimal.tp);
  1582. calcData.deal_tp = this.ctx.helper.mul(calcData.deal_qty, calcData.unit_price, info.decimal.tp);
  1583. }
  1584. updateData = this._filterUpdateInvalidField(updateNode.id, calcData);
  1585. } else {
  1586. updateData = this._filterUpdateInvalidField(updateNode.id, row);
  1587. }
  1588. await this.transaction.update(this.tableName, updateData);
  1589. }
  1590. await this.transaction.commit();
  1591. } catch (err) {
  1592. await this.transaction.rollback();
  1593. throw err;
  1594. }
  1595. return { update: await this.getDataByIds(ids) };
  1596. }
  1597. /**
  1598. *
  1599. * @param tenderId
  1600. * @param xmj
  1601. * @param order
  1602. * @param parentData
  1603. * @return {Promise<*[]>}
  1604. * @private
  1605. */
  1606. async _sortBatchInsertData(tenderId, xmj, order, parentData) {
  1607. const result = [],
  1608. newIds = [];
  1609. let tp = 0;
  1610. const cacheKey = keyPre + tenderId;
  1611. let maxId = parseInt(await this.cache.get(cacheKey));
  1612. if (!maxId) {
  1613. maxId = await this._getMaxNodeId(tenderId);
  1614. }
  1615. this.cache.set(cacheKey, maxId + xmj.children.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1616. // 添加xmj数据
  1617. const parent = {
  1618. tender_id: tenderId,
  1619. ledger_id: maxId + 1,
  1620. ledger_pid: parentData.ledger_id,
  1621. is_leaf: xmj.children.length === 0,
  1622. order,
  1623. level: parentData.level + 1,
  1624. name: xmj.name,
  1625. };
  1626. parent.full_path = parentData.full_path + '.' + parent.ledger_id;
  1627. // 添加gcl数据
  1628. for (let i = 0, iLen = xmj.children.length; i < iLen; i++) {
  1629. const gcl = xmj.children[i];
  1630. const child = {
  1631. tender_id: tenderId,
  1632. ledger_id: maxId + 1 + i + 1,
  1633. ledger_pid: parent.ledger_id,
  1634. is_leaf: true,
  1635. order: i + 1,
  1636. level: parent.level + 1,
  1637. b_code: gcl.b_code,
  1638. name: gcl.name,
  1639. unit: gcl.unit,
  1640. unit_price: gcl.unit_price,
  1641. quantity: gcl.quantity,
  1642. };
  1643. child.full_path = parent.full_path + '.' + child.ledger_id;
  1644. child.total_price = this.ctx.helper.mul(child.unit_price, child.quantity, this.ctx.tender.info.decimal.tp);
  1645. tp = this.ctx.helper.add(tp, child.total_price);
  1646. result.push(child);
  1647. newIds.push(child.ledger_id);
  1648. }
  1649. parent.total_price = tp;
  1650. result.push(parent);
  1651. newIds.push(parent.ledger_id);
  1652. return [result, tp, newIds];
  1653. }
  1654. /**
  1655. * 批量插入子项
  1656. * @param {Number} tenderId - 标段Id
  1657. * @param {Number} selectId - 选中节点Id
  1658. * @param {Object} data - 批量插入数据
  1659. * @return {Promise<void>}
  1660. */
  1661. async batchInsertChild(tenderId, selectId, data) {
  1662. const result = { ledger: {}, pos: null };
  1663. if ((tenderId <= 0) || (selectId <= 0)) {
  1664. return result;
  1665. }
  1666. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1667. if (!selectData) {
  1668. throw '位置数据错误';
  1669. }
  1670. this.transaction = await this.db.beginTransaction();
  1671. const newIds = [];
  1672. const lastChild = await this.getLastChildData(tenderId, selectId);
  1673. try {
  1674. // 更新父项isLeaf
  1675. if (!lastChild) {
  1676. await this.transaction.update(this.tableName, {
  1677. id: selectData.id,
  1678. is_leaf: false,
  1679. unit_price: null,
  1680. quantity: null,
  1681. total_price: null,
  1682. deal_qty: null,
  1683. deal_tp: null,
  1684. });
  1685. }
  1686. const order = lastChild ? lastChild.order : 0;
  1687. // 计算id
  1688. const cacheKey = keyPre + tenderId;
  1689. let maxId = parseInt(await this.cache.get(cacheKey));
  1690. if (!maxId) {
  1691. maxId = await this._getMaxNodeId(tenderId);
  1692. }
  1693. // 数据库创建新增节点数据
  1694. for (let i = 0, iLen = data.length; i < iLen; i++) {
  1695. // 合并新增数据
  1696. const qd = {
  1697. id: this.uuid.v4(),
  1698. tender_id: tenderId,
  1699. ledger_id: maxId + i + 1,
  1700. ledger_pid: selectData.ledger_id,
  1701. is_leaf: true,
  1702. order: order + i + 1,
  1703. level: selectData.level + 1,
  1704. b_code: data[i].b_code,
  1705. name: data[i].name,
  1706. unit: data[i].unit,
  1707. unit_price: data[i].price,
  1708. };
  1709. qd.full_path = selectData.full_path + '.' + qd.ledger_id;
  1710. const insertResult = await this.transaction.insert(this.tableName, qd);
  1711. newIds.push(qd.id);
  1712. if (data[i].pos.length > 0) {
  1713. await this.ctx.service.pos.insertLedgerPosData(this.transaction, tenderId, qd, data[i].pos);
  1714. await this._calcNode(qd, this.transaction);
  1715. }
  1716. }
  1717. this.cache.set(cacheKey, maxId + data.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1718. await this.transaction.commit();
  1719. } catch (err) {
  1720. await this.transaction.rollback();
  1721. throw err;
  1722. }
  1723. // 查询应返回的结果
  1724. result.ledger.create = await this.getDataByIds(newIds);
  1725. if (!lastChild) {
  1726. result.ledger.update = await this.getDataByIds([selectData.id]);
  1727. }
  1728. result.pos = await this.ctx.service.pos.getPosData({ lid: newIds });
  1729. return result;
  1730. }
  1731. /**
  1732. * 批量插入后项
  1733. * @param {Number} tenderId - 标段Id
  1734. * @param {Number} selectId - 选中节点Id
  1735. * @param {Object} data - 批量插入数据
  1736. * @return {Promise<void>}
  1737. */
  1738. async batchInsertNext(tenderId, selectId, data) {
  1739. const result = { ledger: {}, pos: null };
  1740. if ((tenderId <= 0) || (selectId <= 0)) {
  1741. return result;
  1742. }
  1743. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1744. if (!selectData) {
  1745. throw '位置数据错误';
  1746. }
  1747. const parentData = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  1748. if (!parentData) {
  1749. throw '位置数据错误';
  1750. }
  1751. this.transaction = await this.db.beginTransaction();
  1752. const newIds = [];
  1753. try {
  1754. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  1755. await this._updateSelectNextsOrder(selectData, data.length);
  1756. // 计算id和order
  1757. const cacheKey = keyPre + tenderId;
  1758. let maxId = parseInt(await this.cache.get(cacheKey));
  1759. if (!maxId) {
  1760. maxId = await this._getMaxNodeId(tenderId);
  1761. }
  1762. const order = selectData.order;
  1763. // 数据库创建新增节点数据
  1764. for (let i = 0, iLen = data.length; i < iLen; i++) {
  1765. // 合并新增数据
  1766. const qd = {
  1767. id: this.uuid.v4(),
  1768. tender_id: tenderId,
  1769. ledger_id: maxId + i + 1,
  1770. ledger_pid: parentData.ledger_id,
  1771. is_leaf: true,
  1772. order: order + i + 1,
  1773. level: parentData.level + 1,
  1774. b_code: data[i].b_code,
  1775. name: data[i].name,
  1776. unit: data[i].unit,
  1777. unit_price: data[i].price,
  1778. };
  1779. qd.full_path = parentData.full_path + '.' + qd.ledger_id;
  1780. const insertResult = await this.transaction.insert(this.tableName, qd);
  1781. newIds.push(qd.id);
  1782. if (data[i].pos.length > 0) {
  1783. await this.ctx.service.pos.insertLedgerPosData(this.transaction, tenderId, qd, data[i].pos);
  1784. await this._calcNode(qd, this.transaction);
  1785. }
  1786. }
  1787. this.cache.set(cacheKey, maxId + data.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1788. await this.transaction.commit();
  1789. } catch (err) {
  1790. await this.transaction.rollback();
  1791. throw err;
  1792. }
  1793. // 查询应返回的结果
  1794. result.ledger.create = await this.getDataByIds(newIds);
  1795. result.ledger.update = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + data.length);
  1796. result.pos = await this.ctx.service.pos.getPosData({ lid: newIds });
  1797. return result;
  1798. }
  1799. /**
  1800. *
  1801. * @param node
  1802. * @param transaction
  1803. * @returns {Promise<void>}
  1804. * @private
  1805. */
  1806. async _calcNode(node, transaction) {
  1807. const info = this.ctx.tender.info;
  1808. const precision = this.ctx.helper.findPrecision(info.precision, node.unit);
  1809. 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` = ?';
  1810. const data = await transaction.queryOne(calcQtySql, [this.ctx.service.pos.tableName, node.id]);
  1811. data.id = node.id;
  1812. data.sgfh_qty = this.round(data.sgfh_qty, precision.value);
  1813. data.sjcl_qty = this.round(data.sjcl_qty, precision.value);
  1814. data.qtcl_qty = this.round(data.qtcl_qty, precision.value);
  1815. data.quantity = this.round(data.quantity, precision.value);
  1816. data.sgfh_tp = this.ctx.helper.mul(data.sgfh_qty, node.unit_price, info.decimal.tp);
  1817. data.sjcl_tp = this.ctx.helper.mul(data.sjcl_qty, node.unit_price, info.decimal.tp);
  1818. data.qtcl_tp = this.ctx.helper.mul(data.qtcl_qty, node.unit_price, info.decimal.tp);
  1819. data.total_price = this.ctx.helper.mul(data.quantity, node.unit_price, info.decimal.tp);
  1820. const result = await transaction.update(this.tableName, data);
  1821. }
  1822. /**
  1823. *
  1824. * @param {Number} tid - 标段id
  1825. * @param {Number} id - 需要计算的节点的id
  1826. * @param {Object} transaction - 操作所属事务,没有则创建
  1827. * @return {Promise<void>}
  1828. */
  1829. async calc(tid, id, transaction) {
  1830. const node = await transaction.get(this.tableName, {id: id});
  1831. if (!node) {
  1832. throw '数据错误';
  1833. }
  1834. await this._calcNode(node, transaction);
  1835. }
  1836. /**
  1837. * 查找定位 --> 废弃
  1838. * @param tenderId
  1839. * @param nodeId
  1840. * @return {Promise<{expand: *}>}
  1841. */
  1842. async locateNode(tenderId, nodeId) {
  1843. const node = await this.getDataByNodeId(tenderId, nodeId);
  1844. if (!node) {
  1845. throw '查询数据有误';
  1846. }
  1847. const expandIds = node.full_path.split('.');
  1848. expandIds.pop();
  1849. const expandData = await this.getChildrenByParentId(tenderId, expandIds);
  1850. return { expand: expandData };
  1851. }
  1852. async _importCacheTreeNode(transaction, node) {
  1853. const data = {
  1854. id: this.uuid.v4(),
  1855. tender_id: this.ctx.tender.id,
  1856. ledger_id: node.ledger_id,
  1857. ledger_pid: node.ledger_pid,
  1858. level: node.level,
  1859. order: node.order,
  1860. is_leaf: !node.children || node.children.length === 0,
  1861. full_path: node.full_path,
  1862. code: node.code,
  1863. b_code: node.b_code,
  1864. name: node.name,
  1865. unit: node.unit,
  1866. sgfh_qty: node.sgfh_qty,
  1867. sgfh_tp: node.sgfh_tp,
  1868. quantity: node.quantity,
  1869. unit_price: node.unit_price,
  1870. total_price: node.total_price,
  1871. dgn_qty1: node.dgn_qty1,
  1872. dgn_qty2: node.dgn_qty2,
  1873. memo: node.memo,
  1874. drawing_code: node.drawing_code,
  1875. };
  1876. const result = await transaction.insert(this.tableName, data);
  1877. //data.id = result.insertId;
  1878. if (node.children && node.children.length > 0) {
  1879. for (const child of node.children) {
  1880. await this._importCacheTreeNode(transaction, child);
  1881. }
  1882. } else if (node.pos && node.pos.length > 0) {
  1883. await this.ctx.service.pos.insertLedgerPosData(transaction, this.ctx.tender.id, data, node.pos);
  1884. }
  1885. if (node.pos && node.pos.length > 0) {
  1886. for (const p of node.pos) {
  1887. //p.lid = result.insertId;
  1888. p.lid = node.id;
  1889. }
  1890. }
  1891. }
  1892. async _importCacheTreeNodes(transaction, nodes) {
  1893. const datas = [];
  1894. for (const node of nodes) {
  1895. datas.push({
  1896. id: this.uuid.v4(),
  1897. tender_id: this.ctx.tender.id,
  1898. ledger_id: node.ledger_id,
  1899. ledger_pid: node.ledger_pid,
  1900. level: node.level,
  1901. order: node.order,
  1902. is_leaf: !node.children || node.children.length === 0,
  1903. full_path: node.full_path,
  1904. code: node.code,
  1905. b_code: node.b_code,
  1906. name: node.name,
  1907. unit: node.unit,
  1908. sgfh_qty: node.sgfh_qty,
  1909. sgfh_tp: node.sgfh_tp,
  1910. quantity: node.quantity,
  1911. unit_price: node.unit_price,
  1912. total_price: node.total_price,
  1913. dgn_qty1: node.dgn_qty1,
  1914. dgn_qty2: node.dgn_qty2,
  1915. memo: node.memo,
  1916. drawing_code: node.drawing_code,
  1917. });
  1918. }
  1919. await transaction.insert(this.tableName, datas);
  1920. const sql = 'SELECT id, ledger_id FROM ' + this.tableName + ' WHERE tender_id = ?';
  1921. const sqlParam = [this.ctx.tender.id];
  1922. const insertDatas = await transaction.query(sql, sqlParam);
  1923. for (const iD of insertDatas) {
  1924. const node = this.ctx.helper._.find(nodes, {ledger_id: iD.ledger_id});
  1925. if (node.pos && node.pos.length > 0) {
  1926. for (const p of node.pos) {
  1927. p.lid = iD.id;
  1928. }
  1929. }
  1930. }
  1931. }
  1932. /**
  1933. * 导入Excel数据
  1934. * @param excelData
  1935. * @returns {Promise<void>}
  1936. */
  1937. async importExcel(excelData) {
  1938. const AnalysisExcel = require('../lib/analysis_excel');
  1939. const analysisExcel = new AnalysisExcel(this.ctx);
  1940. const tempData = await this.ctx.service.tenderNodeTemplate.getData(true);
  1941. const cacheTree = analysisExcel.analysisData(excelData, tempData);
  1942. const cacheKey = keyPre + this.ctx.tender.id;
  1943. const orgMaxId = parseInt(await this.cache.get(cacheKey));
  1944. const transaction = await this.db.beginTransaction();
  1945. try {
  1946. await transaction.delete(this.tableName, {tender_id: this.ctx.tender.id});
  1947. await transaction.delete(this.ctx.service.pos.tableName, {tid: this.ctx.tender.id});
  1948. // for (const node of cacheTree.roots) {
  1949. // await this._importCacheTreeNode(transaction, node);
  1950. // }
  1951. await this._importCacheTreeNodes(transaction, cacheTree.items);
  1952. await transaction.insert(this.ctx.service.pos.tableName, cacheTree.pos);
  1953. await transaction.commit();
  1954. this.cache.set(cacheKey, cacheTree.items.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1955. } catch (err) {
  1956. await transaction.rollback();
  1957. if (orgMaxId) {
  1958. this.cache.set(cacheKey, orgMaxId, 'EX', this.ctx.app.config.cacheTime);
  1959. }
  1960. throw err;
  1961. }
  1962. }
  1963. }
  1964. return Ledger;
  1965. };