change_ledger.js 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735
  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'];
  26. const tpFields = ['sgfh_tp', 'sjcl_tp', 'qtcl_tp', 'total_price', 'deal_tp'];
  27. const rootId = -1;
  28. const keyPre = 'tender_node_maxId:';
  29. const measureType = require('../const/tender').measureType;
  30. const SumLoad = require('../lib/sum_load');
  31. const billsUtils = require('../lib/bills_utils');
  32. module.exports = app => {
  33. class ChangeLedger extends app.BaseBillsService {
  34. /**
  35. * 构造函数
  36. *
  37. * @param {Object} ctx - egg全局变量
  38. * @return {void}
  39. */
  40. constructor(ctx) {
  41. const setting = {
  42. mid: 'tender_id',
  43. kid: 'ledger_id',
  44. pid: 'ledger_pid',
  45. order: 'order',
  46. level: 'level',
  47. isLeaf: 'is_leaf',
  48. fullPath: 'full_path',
  49. keyPre: 'change_ledger_maxLid2:', // 换个名称,防止缓存导致旧数据出问题
  50. uuid: true,
  51. };
  52. super(ctx, setting, 'pos');
  53. this.setting = setting;
  54. this.depart = 0;
  55. this.tableName = 'change_ledger';
  56. }
  57. /**
  58. * 获取节点数据
  59. * @param {Number} mid - masterId
  60. * @param {Number} id
  61. * @returns {Promise<void>}
  62. */
  63. async getDataByKid(mid, kid) {
  64. const bills = await this.db.get(this.ctx.service.ledger.tableName, this.getCondition({
  65. mid: mid, kid: kid,
  66. }));
  67. if (bills) {
  68. this.newBills = false;
  69. return bills;
  70. }
  71. const cBills = await this.db.get(this.tableName, this.getCondition({mid: mid, kid: kid}));
  72. // 判断父节点是否是变更新建的
  73. const parentBills = await this.db.get(this.tableName, this.getCondition({
  74. mid: mid, kid: cBills[this.setting.pid],
  75. }));
  76. this.newBills = parentBills !== null && parentBills !== undefined;
  77. return cBills;
  78. }
  79. async getDataByKidAndCount(mid, kid, count) {
  80. if ((mid <= 0) || (kid <= 0)) return [];
  81. const select = await this.getDataByKid(mid, kid);
  82. if (!select) throw '数据错误';
  83. if (count > 1) {
  84. const selects = await this.getNextsData(this.tableName, mid, select[this.setting.pid], select[this.setting.order] - 1);
  85. if (selects.length < count) throw '数据错误';
  86. return selects.slice(0, count);
  87. } else {
  88. return [select];
  89. }
  90. }
  91. /**
  92. * 更新order
  93. * @param {Number} mid - master id
  94. * @param {Number} pid - 父节点id
  95. * @param {Number} order - 开始更新的order
  96. * @param {Number} incre - 更新的增量
  97. * @returns {Promise<*>}
  98. * @private
  99. */
  100. async _updateChildrenOrder(tableName, mid, pid, order, incre = 1) {
  101. this.initSqlBuilder();
  102. this.sqlBuilder.setAndWhere(this.setting.mid, {
  103. value: mid,
  104. operate: '=',
  105. });
  106. this.sqlBuilder.setAndWhere(this.setting.order, {
  107. value: order,
  108. operate: '>=',
  109. });
  110. this.sqlBuilder.setAndWhere(this.setting.pid, {
  111. value: pid,
  112. operate: '=',
  113. });
  114. this.sqlBuilder.setUpdateData(this.setting.order, {
  115. value: Math.abs(incre),
  116. selfOperate: incre > 0 ? '+' : '-',
  117. });
  118. const [sql, sqlParam] = this.sqlBuilder.build(tableName, 'update');
  119. const data = await this.transaction.query(sql, sqlParam);
  120. return data;
  121. }
  122. /**
  123. * 获取最大节点id
  124. *
  125. * @param {Number} mid - master id
  126. * @return {Number}
  127. * @private
  128. */
  129. async _getMaxLid(mid) {
  130. const cacheKey = this.setting.keyPre + mid;
  131. let maxId = parseInt(await this.cache.get(cacheKey));
  132. if (!maxId) {
  133. const sql = 'SELECT Max(??) As max_id FROM ?? Where ' + this.setting.mid + ' = ?';
  134. const sqlParam = [this.setting.kid, this.ctx.service.ledger.tableName, mid];
  135. const queryResult = await this.db.queryOne(sql, sqlParam);
  136. maxId = queryResult.max_id || 0;
  137. // if (this.newBills) {
  138. const sql2 = 'SELECT Max(??) As max_id FROM ?? Where ' + this.setting.mid + ' = ?';
  139. const sqlParam2 = [this.setting.kid, this.tableName, mid];
  140. const queryResult2 = await this.db.queryOne(sql2, sqlParam2);
  141. if (maxId < queryResult2.max_id || 0) {
  142. maxId = queryResult2.max_id || 0;
  143. }
  144. // }
  145. const oldCacheKey = 'change_ledger_maxLid:' + mid;
  146. this.cache.del(oldCacheKey);
  147. this.cache.set(cacheKey, maxId, 'EX', this.ctx.app.config.cacheTime);
  148. }
  149. return maxId;
  150. }
  151. /**
  152. * 移除最大节点id(修订时使用)
  153. *
  154. * @param {Number} mid - master id
  155. * @return {Number}
  156. * @private
  157. */
  158. async _removeCacheMaxLid(mid) {
  159. return await this.cache.del(this.setting.keyPre + mid);
  160. }
  161. /**
  162. * 根据 父节点id 和 节点排序order 获取数据
  163. *
  164. * @param {Number} mid - master id
  165. * @param {Number} pid - 父节点id
  166. * @param {Number|Array} order - 排序
  167. * @return {Object|Array} - 查询结果
  168. */
  169. async getDataByParentAndOrder(mid, pid, order) {
  170. let result = await this.db.select(this.tableName, {
  171. where: this.getCondition({mid: mid, pid: pid, order: order})
  172. });
  173. if (!this.newBills) {
  174. const ledgerResult = await this.db.select(this.ctx.service.ledger.tableName, {
  175. where: this.getCondition({mid: mid, pid: pid, order: order})
  176. });
  177. result = this._.orderBy(this._.concat(ledgerResult, result), [this.setting.order], ['asc']);
  178. }
  179. return order instanceof Array ? result : (result.length > 0 ? result[0] : null);
  180. }
  181. async getChildBetween(tableName, mid, pid, order1, order2) {
  182. this.initSqlBuilder();
  183. this.sqlBuilder.setAndWhere(this.setting.mid, {
  184. value: mid,
  185. operate: '=',
  186. });
  187. this.sqlBuilder.setAndWhere(this.setting.pid, {
  188. value: pid,
  189. operate: '=',
  190. });
  191. this.sqlBuilder.setAndWhere(this.setting.order, {
  192. value: order1,
  193. operate: '>',
  194. });
  195. this.sqlBuilder.setAndWhere(this.setting.order, {
  196. value: order2,
  197. operate: '<',
  198. });
  199. this.sqlBuilder.orderBy = [['order', 'ASC']];
  200. const [sql, sqlParam] = this.sqlBuilder.build(tableName);
  201. const data = await this.db.query(sql, sqlParam);
  202. return data;
  203. }
  204. /**
  205. * 根据 父节点ID 和 节点排序order 获取全部后节点数据
  206. * @param {Number} mid - master id
  207. * @param {Number} pid - 父节点id
  208. * @param {Number} order - 排序
  209. * @return {Array}
  210. */
  211. async getNextsData(tableName, mid, pid, order) {
  212. this.initSqlBuilder();
  213. this.sqlBuilder.setAndWhere(this.setting.mid, {
  214. value: mid,
  215. operate: '=',
  216. });
  217. this.sqlBuilder.setAndWhere(this.setting.pid, {
  218. value: pid,
  219. operate: '=',
  220. });
  221. this.sqlBuilder.setAndWhere(this.setting.order, {
  222. value: order,
  223. operate: '>',
  224. });
  225. this.sqlBuilder.orderBy = [['order', 'ASC']];
  226. const [sql, sqlParam] = this.sqlBuilder.build(tableName);
  227. const data = await this.db.query(sql, sqlParam);
  228. return data;
  229. }
  230. /**
  231. * 根据节点Id获取数据
  232. *
  233. * @param {Number} tenderId - 标段id
  234. * @param {Number} nodeId - 项目节/工程量清单节点id
  235. * @return {Object} - 返回查询到的节点数据
  236. */
  237. async getDataByNodeId(tenderId, nodeId) {
  238. if ((nodeId <= 0) || (tenderId <= 0)) {
  239. return undefined;
  240. }
  241. this.initSqlBuilder();
  242. this.sqlBuilder.setAndWhere('tender_id', {
  243. value: tenderId,
  244. operate: '=',
  245. });
  246. this.sqlBuilder.setAndWhere('ledger_id', {
  247. value: nodeId,
  248. operate: '=',
  249. });
  250. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  251. const data = await this.db.queryOne(sql, sqlParam);
  252. return data;
  253. }
  254. /**
  255. * 新增数据(新增为selectData的后项,该方法不可单独使用)
  256. *
  257. * @param {Number} mid - 台账id
  258. * @param {Object} select - 选中节点的数据
  259. * @param {Object} data - 新增节点的初始数据
  260. * @return {Object} - 新增结果
  261. * @private
  262. */
  263. async _addNodeData(mid, select, data) {
  264. if (!data) {
  265. data = {};
  266. }
  267. const maxId = await this._getMaxLid(mid);
  268. if (this.setting.uuid) data.id = this.uuid.v4();
  269. data[this.setting.kid] = maxId + 1;
  270. data[this.setting.pid] = select ? select[this.setting.pid] : rootId;
  271. data[this.setting.mid] = mid;
  272. data[this.setting.level] = select ? select[this.setting.level] : 1;
  273. data[this.setting.order] = select ? select[this.setting.order] + 1 : 1;
  274. data[this.setting.fullPath] = data[this.setting.level] > 1 ? select[this.setting.fullPath].replace('-' + select[this.setting.kid], '-' + data[this.setting.kid]) : data[this.setting.kid] + '';
  275. data[this.setting.isLeaf] = true;
  276. const result = await this.transaction.insert(this.tableName, data);
  277. this._cacheMaxLid(mid, maxId + 1);
  278. return result;
  279. }
  280. /**
  281. * 新增节点
  282. * @param {Number} mid - 台账id
  283. * @param {Number} kid - 清单节点id
  284. * @returns {Promise<void>}
  285. */
  286. async addNode(mid, kid, data) {
  287. if (!mid) return null;
  288. this.newBills = false;
  289. const select = kid ? await this.getDataByKid(mid, kid) : null;
  290. if (kid && !select) throw '新增节点数据错误';
  291. this.transaction = await this.db.beginTransaction();
  292. try {
  293. if (select) await this._updateChildrenOrder(this.tableName, mid, select[this.setting.pid], select[this.setting.order]+1);
  294. if (!this.newBills) {
  295. if (select) await this._updateChildrenOrder(this.ctx.service.ledger.tableName, mid, select[this.setting.pid], select[this.setting.order]+1);
  296. }
  297. const newNode = await this._addNodeData(mid, select, data);
  298. if (newNode.affectedRows !== 1) throw '新增节点数据错误';
  299. await this.transaction.commit();
  300. this.transaction = null;
  301. } catch (err) {
  302. await this.transaction.rollback();
  303. this.transaction = null;
  304. throw err;
  305. }
  306. if (select) {
  307. const createData = await this.getDataByParentAndOrder(mid, select[this.setting.pid], [select[this.setting.order] + 1]);
  308. let updateData = await this.getNextsData(this.tableName, mid, select[this.setting.pid], select[this.setting.order] + 1);
  309. if (!this.newBills) {
  310. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, mid, select[this.setting.pid], select[this.setting.order] + 1);
  311. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  312. }
  313. return { create: createData, update: updateData };
  314. } else {
  315. const createData = await this.getDataByParentAndOrder(mid, -1, [1]);
  316. return { create: createData };
  317. }
  318. }
  319. async addNodeBatch(mid, kid, data, count = 1) {
  320. if (!mid) return null;
  321. this.newBills = false;
  322. const select = kid ? await this.getDataByKid(mid, kid) : null;
  323. if (kid && !select) throw '新增节点数据错误';
  324. this.transaction = await this.db.beginTransaction();
  325. try {
  326. // 判断select的父节点是否是变更新增的,如果是则修改自己的表就行了,否则修改2个ledger,changeLedger表
  327. if (select) await this._updateChildrenOrder(this.tableName, mid, select[this.setting.pid], select[this.setting.order] + 1, count);
  328. if (!this.newBills) {
  329. if (select) await this._updateChildrenOrder(this.ctx.service.ledger.tableName, mid, select[this.setting.pid], select[this.setting.order] + 1, count);
  330. }
  331. const newDatas = [];
  332. const maxId = await this._getMaxLid(mid);
  333. for (let i = 1; i < count + 1; i++) {
  334. const newData = Object.assign({}, data);
  335. if (this.setting.uuid) newData.id = this.uuid.v4();
  336. newData[this.setting.kid] = maxId + i;
  337. newData[this.setting.pid] = select ? select[this.setting.pid] : rootId;
  338. newData[this.setting.mid] = mid;
  339. newData[this.setting.level] = select ? select[this.setting.level] : 1;
  340. newData[this.setting.order] = select ? select[this.setting.order] + i : i;
  341. newData[this.setting.fullPath] = newData[this.setting.level] > 1
  342. ? select[this.setting.fullPath].replace('-' + select[this.setting.kid], '-' + newData[this.setting.kid])
  343. : newData[this.setting.kid] + '';
  344. newData[this.setting.isLeaf] = true;
  345. newDatas.push(newData);
  346. }
  347. const insertResult = await this.transaction.insert(this.tableName, newDatas);
  348. this._cacheMaxLid(mid, maxId + count);
  349. if (insertResult.affectedRows !== count) throw '新增节点数据错误';
  350. await this.transaction.commit();
  351. this.transaction = null;
  352. } catch (err) {
  353. await this.transaction.rollback();
  354. this.transaction = null;
  355. throw err;
  356. }
  357. if (select) {
  358. let createData = await this.getChildBetween(this.tableName, mid, select[this.setting.pid], select[this.setting.order], select[this.setting.order] + count + 1);
  359. let updateData = await this.getNextsData(this.tableName, mid, select[this.setting.pid], select[this.setting.order] + count);
  360. if (!this.newBills) {
  361. const ledgerCreateData = await this.getChildBetween(this.ctx.service.ledger.tableName, mid, select[this.setting.pid], select[this.setting.order], select[this.setting.order] + count + 1);
  362. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, mid, select[this.setting.pid], select[this.setting.order] + count);
  363. createData = this._.orderBy(this._.concat(createData, ledgerCreateData), [this.setting.order], ['asc']);
  364. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  365. }
  366. return { create: createData, update: updateData };
  367. } else {
  368. const createData = await this.getChildBetween(this.ctx.service.ledger.tableName, mid, -1, 0, count + 1);
  369. return { create: createData };
  370. }
  371. }
  372. /**
  373. * 删除相关数据 用于继承
  374. * @param mid
  375. * @param deleteData
  376. * @return {Promise<void>}
  377. * @private
  378. */
  379. async _deleteRelaData(mid, deleteData) {
  380. await this.ctx.service.changePos.deletePosData(this.transaction, mid, this._.map(deleteData, 'id'));
  381. }
  382. async _deleteChangeAuditListData(mid, deleteData) {
  383. await this.ctx.service.changeAuditList.deleteDataByRevise(this.transaction, mid, this._.map(deleteData, 'id'));
  384. }
  385. /**
  386. * 删除节点
  387. * @param {Number} tenderId - 标段id
  388. * @param {Object} deleteData - 删除节点数据
  389. * @return {Promise<*>}
  390. * @private
  391. */
  392. async _deleteNodeData(mid, deleteNode) {
  393. this.initSqlBuilder();
  394. this.sqlBuilder.setAndWhere(this.setting.mid, {
  395. value: mid,
  396. operate: '=',
  397. });
  398. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  399. value: this.db.escape(deleteNode[this.setting.fullPath] + '%'),
  400. operate: 'Like',
  401. });
  402. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'delete');
  403. const result = await this.transaction.query(sql, sqlParam);
  404. return result;
  405. }
  406. /**
  407. * tenderId标段中, 删除选中节点及其子节点
  408. *
  409. * @param {Number} tenderId - 标段id
  410. * @param {Number} selectId - 选中节点id
  411. * @return {Array} - 被删除的数据
  412. */
  413. async deleteNode(mid, kid) {
  414. if ((mid <= 0) || (kid <= 0)) return [];
  415. this.newBills = false;
  416. const select = await this.getDataByKid(mid, kid);
  417. if (!select) throw '删除节点数据错误';
  418. const parent = await this.getDataByKid(mid, select[this.setting.pid]);
  419. // 获取将要被删除的数据
  420. const deleteData = await this.getDataByFullPath(this.tableName, mid, select[this.setting.fullPath] + '%');
  421. if (deleteData.length === 0) throw '删除节点数据错误';
  422. this.transaction = await this.db.beginTransaction();
  423. try {
  424. // 删除
  425. const operate = await this._deleteNodeData(mid, select);
  426. // 选中节点--父节点 只有一个子节点时,应升级is_leaf
  427. if (parent) {
  428. let count = await this.db.count(this.tableName, this.getCondition({mid: mid, pid: select[this.setting.pid]}));
  429. if (!this.newBills) {
  430. const ledgerCount = await this.db.count(this.ctx.service.ledger.tableName, this.getCondition({mid: mid, pid: select[this.setting.pid]}));
  431. count = count + ledgerCount;
  432. }
  433. if (count === 1) {
  434. const updateParent = {id: parent.id };
  435. updateParent[this.setting.isLeaf] = true;
  436. await this.transaction.update(this.tableName, updateParent);
  437. }
  438. }
  439. // 选中节点--全部后节点 order--
  440. await this._updateChildrenOrder(this.tableName, mid, select[this.setting.pid], select[this.setting.order] + 1, -1);
  441. if (!this.newBills) {
  442. await this._updateChildrenOrder(this.ctx.service.ledger.tableName, mid, select[this.setting.pid], select[this.setting.order] + 1, -1);
  443. }
  444. // 删除部位明细
  445. await this._deleteRelaData(mid, deleteData);
  446. await this._deleteChangeAuditListData(mid, deleteData);
  447. await this.transaction.commit();
  448. this.transaction = null;
  449. } catch (err) {
  450. await this.transaction.rollback();
  451. this.transaction = null;
  452. throw err;
  453. }
  454. // 查询结果
  455. let updateData = await this.getNextsData(this.tableName, mid, select[this.setting.pid], select[this.setting.order] - 1);
  456. if (!this.newBills) {
  457. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, mid, select[this.setting.pid], select[this.setting.order] - 1);
  458. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  459. }
  460. if (parent) {
  461. const updateData1 = await this.getDataByKid(mid, select[this.setting.pid]);
  462. if (updateData1[this.setting.isLeaf]) {
  463. updateData.push(updateData1);
  464. }
  465. }
  466. return { delete: deleteData, update: updateData };
  467. }
  468. async deleteNodes(mid, kid, count) {
  469. if ((mid <= 0) || (kid <= 0) || (count <= 0)) return [];
  470. this.newBills = false;
  471. const selects = await this.getDataByKidAndCount(mid, kid, count);
  472. const first = selects[0];
  473. const newBills = this.newBills;
  474. const parent = await this.getDataByKid(mid, first[this.setting.pid]);
  475. let childCount = 0;
  476. if (parent) {
  477. childCount = await this.db.count(this.tableName, this.getCondition({mid: mid, pid: parent[this.setting.kid]}));
  478. if (!newBills) {
  479. const ledgerCount = await this.db.count(this.ctx.service.ledger.tableName, this.getCondition({mid: mid, pid: parent[this.setting.pid]}));
  480. childCount = childCount + ledgerCount;
  481. }
  482. } else {
  483. childCount = -1;
  484. }
  485. // const childCount = parent ? await this.count(this.getCondition({mid: mid, pid: parent[this.setting.kid]})) : -1;
  486. let deleteData = [];
  487. for (const s of selects) {
  488. deleteData = deleteData.concat(await this.getDataByFullPath(this.tableName, mid, s[this.setting.fullPath] + '%'));
  489. }
  490. this.transaction = await this.db.beginTransaction();
  491. try {
  492. // 删除
  493. for (const s of selects) {
  494. const operate = await this._deleteNodeData(mid, s);
  495. }
  496. // 选中节点--父节点 只有一个子节点时,应升级is_leaf
  497. if (parent && childCount === count) {
  498. const updateParent = { id: parent.id };
  499. updateParent[this.setting.isLeaf] = true;
  500. await this.transaction.update(this.tableName, updateParent);
  501. }
  502. // 选中节点--全部后节点 order--
  503. await this._updateChildrenOrder(this.tableName, mid, first[this.setting.pid], first[this.setting.order] + count, -count);
  504. if (!newBills) {
  505. await this._updateChildrenOrder(this.ctx.service.ledger.tableName, mid, first[this.setting.pid], first[this.setting.order] + count, -count);
  506. }
  507. // 删除部位明细
  508. await this._deleteRelaData(mid, deleteData);
  509. await this._deleteChangeAuditListData(mid, deleteData);
  510. await this.transaction.commit();
  511. this.transaction = null;
  512. let updateData = await this.getNextsData(this.tableName, mid, first[this.setting.pid], first[this.setting.order] - 1);
  513. if (!newBills) {
  514. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, mid, first[this.setting.pid], first[this.setting.order] - 1);
  515. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  516. }
  517. if (parent && childCount === count) {
  518. const updateData1 = await this.getDataByKid(mid, parent[this.setting.kid]);
  519. updateData.push(updateData1);
  520. }
  521. return { delete: deleteData, update: updateData };
  522. } catch (err) {
  523. if (this.transaction) {
  524. await this.transaction.rollback();
  525. this.transaction = null;
  526. }
  527. throw err;
  528. }
  529. }
  530. async delete(mid, kid, count) {
  531. if (count && count > 1) {
  532. return await this.deleteNodes(mid, kid, count);
  533. } else {
  534. return await this.deleteNode(mid, kid);
  535. }
  536. }
  537. /**
  538. * 上移节点
  539. *
  540. * @param {Number} mid - master id
  541. * @param {Number} kid - 选中节点id
  542. * @return {Array} - 发生改变的数据
  543. */
  544. async upMoveNode(mid, kid, count) {
  545. if (!count) count = 1;
  546. if (!mid || (mid <= 0) || !kid || (kid <= 0)) return null;
  547. this.newBills = false;
  548. const selects = await this.getDataByKidAndCount(mid, kid, count);
  549. if (selects.length !== count) throw '上移节点数据错误';
  550. const first = selects[0];
  551. const pre = await this.getDataByParentAndOrder(mid, first[this.setting.pid], first[this.setting.order] - 1);
  552. if (!pre) throw '节点不可上移';
  553. const order = [];
  554. this.transaction = await this.db.beginTransaction();
  555. try {
  556. for (const s of selects) {
  557. const sData = await this.transaction.update(this.tableName, { id: s.id, order: s[this.setting.order] - 1 });
  558. if (!this.newBills) {
  559. await this.transaction.update(this.ctx.service.ledger.tableName, { id: s.id, order: s[this.setting.order] - 1 });
  560. }
  561. order.push(s[this.setting.order] - 1);
  562. }
  563. const pData = await this.transaction.update(this.tableName, { id: pre.id, order: pre[this.setting.order] + count });
  564. if (!this.newBills) {
  565. await this.transaction.update(this.ctx.service.ledger.tableName, { id: pre.id, order: pre[this.setting.order] + count });
  566. }
  567. order.push(pre[this.setting.order] + count);
  568. await this.transaction.commit();
  569. this.transaction = null;
  570. } catch (err) {
  571. await this.transaction.rollback();
  572. this.transaction = null;
  573. throw err;
  574. }
  575. const resultData = await this.getDataByParentAndOrder(mid, first[this.setting.pid], order);
  576. return { update: resultData };
  577. }
  578. /**
  579. * 下移节点
  580. *
  581. * @param {Number} mid - master id
  582. * @param {Number} kid - 选中节点id
  583. * @return {Array} - 发生改变的数据
  584. */
  585. async downMoveNode(mid, kid, count) {
  586. if (!count) count = 1;
  587. if (!mid || (mid <= 0) || !kid || (kid <= 0)) return null;
  588. this.newBills = false;
  589. const selects = await this.getDataByKidAndCount(mid, kid, count);
  590. if (selects.length !== count) {
  591. throw '下移节点数据错误';
  592. }
  593. const last = selects[count - 1];
  594. const next = await this.getDataByParentAndOrder(mid, last[this.setting.pid], last[this.setting.order] + 1);
  595. if (!next) {
  596. throw '节点不可下移';
  597. }
  598. const order = [];
  599. this.transaction = await this.db.beginTransaction();
  600. try {
  601. for (const s of selects) {
  602. const sData = await this.transaction.update(this.tableName, { id: s.id, order: s[this.setting.order] + 1 });
  603. if (!this.newBills) {
  604. await this.transaction.update(this.ctx.service.ledger.tableName, { id: s.id, order: s[this.setting.order] + 1 });
  605. }
  606. order.push(s[this.setting.order] + 1);
  607. }
  608. const nData = await this.transaction.update(this.tableName, { id: next.id, order: next[this.setting.order] - count });
  609. if (!this.newBills) {
  610. await this.transaction.update(this.ctx.service.ledger.tableName, { id: next.id, order: next[this.setting.order] - count });
  611. }
  612. order.push(next[this.setting.order] - count);
  613. await this.transaction.commit();
  614. this.transaction = null;
  615. } catch (err) {
  616. await this.transaction.rollback();
  617. this.transaction = null;
  618. throw err;
  619. }
  620. const resultData = await this.getDataByParentAndOrder(mid, last[this.setting.pid], order);
  621. return { update: resultData };
  622. }
  623. /**
  624. * 批量插入子项
  625. * @param {Number} tenderId - 标段Id
  626. * @param {Number} selectId - 选中节点Id
  627. * @param {Object} data - 批量插入数据
  628. * @return {Promise<void>}
  629. */
  630. async batchInsertChild(tenderId, selectId, data) {
  631. const result = { ledger: {}, pos: null };
  632. if ((tenderId <= 0) || (selectId <= 0)) {
  633. return result;
  634. }
  635. const selectData = await this.getDataByNodeId(tenderId, selectId);
  636. if (!selectData) {
  637. throw '位置数据错误';
  638. }
  639. this.transaction = await this.db.beginTransaction();
  640. const newIds = [];
  641. const lastChild = await this.getLastChildData(tenderId, selectId);
  642. try {
  643. // 更新父项isLeaf
  644. if (!lastChild) {
  645. await this.transaction.update(this.tableName, {
  646. id: selectData.id,
  647. is_leaf: false,
  648. unit_price: null,
  649. sgfh_qty: null,
  650. sgfh_tp: null,
  651. sjcl_qty: null,
  652. sjcl_tp: null,
  653. qtcl_qty: null,
  654. qtcl_tp: null,
  655. quantity: null,
  656. total_price: null,
  657. deal_qty: null,
  658. deal_tp: null,
  659. });
  660. }
  661. const order = lastChild ? lastChild.order : 0;
  662. // 计算id
  663. const maxId = await this._getMaxLid(tenderId);
  664. // 数据库创建新增节点数据
  665. for (let i = 0, iLen = data.length; i < iLen; i++) {
  666. // 合并新增数据
  667. const qd = {
  668. id: this.uuid.v4(),
  669. tender_id: tenderId,
  670. ledger_id: maxId + i + 1,
  671. ledger_pid: selectData.ledger_id,
  672. is_leaf: true,
  673. order: order + i + 1,
  674. level: selectData.level + 1,
  675. b_code: data[i].b_code,
  676. name: data[i].name,
  677. unit: data[i].unit,
  678. unit_price: data[i].price,
  679. };
  680. qd.full_path = selectData.full_path + '-' + qd.ledger_id;
  681. const insertResult = await this.transaction.insert(this.tableName, qd);
  682. newIds.push(qd.id);
  683. if (data[i].pos.length > 0) {
  684. await this.ctx.service.pos.insertLedgerPosData(this.transaction, tenderId, qd, data[i].pos);
  685. await this.calcNode(qd, this.transaction);
  686. }
  687. }
  688. this._cacheMaxLid(tenderId, maxId + data.length);
  689. await this.transaction.commit();
  690. } catch (err) {
  691. await this.transaction.rollback();
  692. throw err;
  693. }
  694. // 查询应返回的结果
  695. result.ledger.create = await this.getDataByIds(newIds);
  696. if (!lastChild) {
  697. result.ledger.update = await this.getDataByIds([selectData.id]);
  698. }
  699. result.pos = await this.ctx.service.pos.getPosData({tid: tenderId, lid: newIds });
  700. return result;
  701. }
  702. /**
  703. * 批量插入后项
  704. * @param {Number} tenderId - 标段Id
  705. * @param {Number} selectId - 选中节点Id
  706. * @param {Object} data - 批量插入数据
  707. * @return {Promise<void>}
  708. */
  709. async batchInsertNext(tenderId, selectId, data) {
  710. const result = { ledger: {}, pos: null };
  711. if ((tenderId <= 0) || (selectId <= 0)) {
  712. return result;
  713. }
  714. const selectData = await this.getDataByNodeId(tenderId, selectId);
  715. if (!selectData) {
  716. throw '位置数据错误';
  717. }
  718. const parentData = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  719. if (!parentData) {
  720. throw '位置数据错误';
  721. }
  722. this.transaction = await this.db.beginTransaction();
  723. const newIds = [];
  724. try {
  725. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  726. await this._updateChildrenOrder(tenderId, selectData.ledger_pid, selectData.order + 1, data.length);
  727. // 计算id和order
  728. const maxId = await this._getMaxLid(tenderId);
  729. const order = selectData.order;
  730. // 数据库创建新增节点数据
  731. for (let i = 0, iLen = data.length; i < iLen; i++) {
  732. // 合并新增数据
  733. const qd = {
  734. id: this.uuid.v4(),
  735. tender_id: tenderId,
  736. ledger_id: maxId + i + 1,
  737. ledger_pid: parentData.ledger_id,
  738. is_leaf: true,
  739. order: order + i + 1,
  740. level: parentData.level + 1,
  741. b_code: data[i].b_code,
  742. name: data[i].name,
  743. unit: data[i].unit,
  744. unit_price: data[i].price,
  745. };
  746. qd.full_path = parentData.full_path + '-' + qd.ledger_id;
  747. const insertResult = await this.transaction.insert(this.tableName, qd);
  748. newIds.push(qd.id);
  749. if (data[i].pos.length > 0) {
  750. await this.ctx.service.pos.insertLedgerPosData(this.transaction, tenderId, qd, data[i].pos);
  751. await this.calcNode(qd, this.transaction);
  752. }
  753. }
  754. this._cacheMaxLid(tenderId, maxId + data.length);
  755. await this.transaction.commit();
  756. } catch (err) {
  757. await this.transaction.rollback();
  758. throw err;
  759. }
  760. // 查询应返回的结果
  761. result.ledger.create = await this.getDataByIds(newIds);
  762. result.ledger.update = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + data.length);
  763. result.pos = await this.ctx.service.pos.getPosData({tid: tenderId, lid: newIds });
  764. return result;
  765. }
  766. /**
  767. * 升级selectData, 同步修改所有子节点
  768. * @param {Object} selectData - 升级操作,选中节点
  769. * @return {Object}
  770. * @private
  771. */
  772. async _syncUplevelChildren(select) {
  773. this.initSqlBuilder();
  774. this.sqlBuilder.setAndWhere(this.setting.mid, {
  775. value: select[this.setting.mid],
  776. operate: '=',
  777. });
  778. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  779. value: this.db.escape(select[this.setting.fullPath] + '-%'),
  780. operate: 'like',
  781. });
  782. this.sqlBuilder.setUpdateData(this.setting.level, {
  783. value: 1,
  784. selfOperate: '-',
  785. });
  786. this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  787. value: [this.setting.fullPath, this.db.escape(select[this.setting.pid] + '-'), this.db.escape('')],
  788. literal: 'Replace',
  789. });
  790. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  791. const data = await this.transaction.query(sql, sqlParam);
  792. return data;
  793. }
  794. /**
  795. * 选中节点的后兄弟节点,全部变为当前节点的子节点
  796. * @param {Object} selectData - 选中节点
  797. * @return {Object}
  798. * @private
  799. */
  800. async _syncUpLevelNexts(select) {
  801. // 查询selectData的lastChild
  802. const lastChild = await this.getLastChildDataFormCR(select[this.setting.mid], select[this.setting.kid]);
  803. const nexts = await this.getNextsData(this.tableName, select[this.setting.mid], select[this.setting.pid], select[this.setting.order]);
  804. if (nexts && nexts.length > 0) {
  805. // 修改nextsData pid, 排序
  806. this.initSqlBuilder();
  807. this.sqlBuilder.setUpdateData(this.setting.pid, {
  808. value: select[this.setting.kid],
  809. });
  810. const orderInc = lastChild ? lastChild[this.setting.order] - select[this.setting.order] : - select[this.setting.order];
  811. this.sqlBuilder.setUpdateData(this.setting.order, {
  812. value: Math.abs(orderInc),
  813. selfOperate: orderInc > 0 ? '+' : '-',
  814. });
  815. this.sqlBuilder.setAndWhere(this.setting.mid, {
  816. value: select[this.setting.mid],
  817. operate: '=',
  818. });
  819. this.sqlBuilder.setAndWhere(this.setting.pid, {
  820. value: select[this.setting.pid],
  821. operate: '=',
  822. });
  823. this.sqlBuilder.setAndWhere(this.setting.order, {
  824. value: select[this.setting.order],
  825. operate: '>',
  826. });
  827. const [sql1, sqlParam1] = this.sqlBuilder.build(this.tableName, 'update');
  828. await this.transaction.query(sql1, sqlParam1);
  829. // 选中节点 is_leaf应为false
  830. if (select.is_leaf) {
  831. const updateData = { id: select.id, is_leaf: false };
  832. await this.transaction.update(this.tableName, updateData);
  833. }
  834. // 修改nextsData及其子节点的full_path
  835. const oldSubStr = this.db.escape(select[this.setting.pid] + '-');
  836. const newSubStr = this.db.escape(select[this.setting.kid] + '-');
  837. const sqlArr = [];
  838. sqlArr.push('Update ?? SET `full_path` = Replace(`full_path`,' + oldSubStr + ',' + newSubStr + ') Where');
  839. sqlArr.push('(`' + this.setting.mid + '` = ' + select[this.setting.mid] + ')');
  840. sqlArr.push(' And (');
  841. for (const data of nexts) {
  842. sqlArr.push('`' + this.setting.fullPath + '` Like ' + this.db.escape(data[this.setting.fullPath] + '%'));
  843. if (nexts.indexOf(data) < nexts.length - 1) {
  844. sqlArr.push(' Or ');
  845. }
  846. }
  847. sqlArr.push(')');
  848. const sql = sqlArr.join('');
  849. const resultData = await this.transaction.query(sql, [this.tableName]);
  850. // 存在下节点,则把此变更清单删除
  851. await this._deleteChangeAuditListData(select[this.setting.mid], [select]);
  852. return resultData;
  853. }
  854. }
  855. /**
  856. * 升级节点
  857. *
  858. * @param {Number} tenderId - 标段id
  859. * @param {Number} selectId - 选中节点id
  860. * @return {Array} - 发生改变的数据
  861. */
  862. async upLevelNode(mid, kid, count) {
  863. if (!count) count = 1;
  864. this.newBills = false;
  865. const selects = await this.getDataByKidAndCount(mid, kid, count);
  866. // const newBills = this.newBills;
  867. if (selects.length !== count) throw '升级节点数据错误';
  868. const first = selects[0], last = selects[count - 1];
  869. const parent = await this.getDataByKid(mid, first[this.setting.pid]);
  870. if (!parent) throw '升级节点数据错误';
  871. const newPath = [];
  872. this.transaction = await this.db.beginTransaction();
  873. try {
  874. // 选中节点--父节点 选中节点为firstChild时,修改is_leaf
  875. if (first[this.setting.order] === 1) {
  876. await this.transaction.update(this.tableName, {
  877. id: parent.id,
  878. is_leaf: true,
  879. });
  880. // throw '不能升级为最高级节点';
  881. }
  882. // 选中节点--父节点--全部后兄弟节点 order+1
  883. await this._updateChildrenOrder(this.tableName, mid, parent[this.setting.pid], parent[this.setting.order] + 1, count);
  884. if (!this.newBills) {
  885. await this._updateChildrenOrder(this.ctx.service.ledger.tableName, mid, parent[this.setting.pid], parent[this.setting.order] + 1, count);
  886. }
  887. for (const [i, s] of selects.entries()) {
  888. // 选中节点 修改pid, order, full_path, level, is_leaf, 清空计算项
  889. const updateData = { id: s.id };
  890. updateData[this.setting.pid] = parent[this.setting.pid];
  891. updateData[this.setting.order] = parent[this.setting.order] + i + 1;
  892. updateData[this.setting.level] = s[this.setting.level] - 1;
  893. updateData[this.setting.fullPath] = s[this.setting.fullPath].replace(s[this.setting.pid] + '-', '');
  894. newPath.push(updateData[this.setting.fullPath]);
  895. if (s.id === last.id) {
  896. const nexts = await this.getNextsData(this.tableName, mid, parent[this.setting.kid], last[this.setting.order]);
  897. if (!this.newBills) {
  898. const ledgerNexts = await this.getNextsData(this.ctx.service.ledger.tableName, mid, parent[this.setting.kid], last[this.setting.order]);
  899. if (ledgerNexts.length > 0) {
  900. throw '该节点下存在台账节点,不可升级';
  901. }
  902. // nexts = this._.orderBy(this._.concat(ledgerNexts, nexts), [this.setting.order], ['asc']);
  903. }
  904. if (s.is_leaf && nexts.length > 0) {
  905. updateData.is_leaf = false;
  906. this.clearParentingData(updateData);
  907. }
  908. }
  909. await this.transaction.update(this.tableName, updateData);
  910. // 选中节点--全部子节点(含孙) level-1, full_path变更
  911. await this._syncUplevelChildren(s);
  912. }
  913. // 选中节点--全部后兄弟节点 收编为子节点 修改pid, order, full_path
  914. await this._syncUpLevelNexts(last);
  915. await this.transaction.commit();
  916. this.transaction = null;
  917. } catch (err) {
  918. await this.transaction.rollback();
  919. this.transaction = null;
  920. throw err;
  921. }
  922. // 查询修改的数据
  923. let updateData = await this.getNextsData(this.tableName, mid, parent[this.setting.pid], parent[this.setting.order] - 1);
  924. if (!this.newBills) {
  925. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, mid, parent[this.setting.pid], parent[this.setting.order] - 1);
  926. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  927. }
  928. for (const path of newPath) {
  929. const children = await this.getDataByFullPath(this.tableName, mid, path + '-%');
  930. updateData = updateData.concat(children);
  931. if (!this.newBills) {
  932. updateData = updateData.concat(await this.getDataByFullPath(this.ctx.service.ledger.tableName, mid, path + '-%'));
  933. }
  934. }
  935. return { update: updateData };
  936. }
  937. /**
  938. * 降级selectData, 同步修改所有子节点
  939. * @param {Object} selectData - 选中节点
  940. * @param {Object} preData - 选中节点的前一节点(降级后为父节点)
  941. * @return {Promise<*>}
  942. * @private
  943. */
  944. async _syncDownlevelChildren(select, pre) {
  945. this.initSqlBuilder();
  946. this.sqlBuilder.setAndWhere(this.setting.mid, {
  947. value: select[this.setting.mid],
  948. operate: '=',
  949. });
  950. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  951. value: this.db.escape(select[this.setting.fullPath] + '-%'),
  952. operate: 'like',
  953. });
  954. this.sqlBuilder.setUpdateData(this.setting.level, {
  955. value: 1,
  956. selfOperate: '+',
  957. });
  958. this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  959. value: [this.setting.fullPath, this.db.escape(select[this.setting.kid] + '-'), this.db.escape(pre[this.setting.kid] + '-' + select[this.setting.kid] + '-')],
  960. literal: 'Replace',
  961. });
  962. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  963. const data = await this.transaction.query(sql, sqlParam);
  964. return data;
  965. }
  966. async getDataByFullPath(tableName, mid, full_path, transaction = null) {
  967. this.initSqlBuilder();
  968. this.sqlBuilder.setAndWhere(this.setting.mid, {
  969. value: mid,
  970. operate: '=',
  971. });
  972. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  973. value: this.db.escape(full_path),
  974. operate: 'Like',
  975. });
  976. const [sql, sqlParam] = this.sqlBuilder.build(tableName);
  977. const resultData = transaction ? await transaction.query(sql, sqlParam) : await this.db.query(sql, sqlParam);
  978. return resultData;
  979. }
  980. /**
  981. * 获取最末的子节点
  982. * @param {Number} mid - masterId
  983. * @param {Number} pid - 父节点id
  984. * @return {Object}
  985. */
  986. async getLastChildDataFormCR(mid, pid) {
  987. let preLastChild = await this.getLastChildData(this.tableName, mid, pid);
  988. if (!this.newBills) {
  989. const preLedgerLastChild = await this.getLastChildData(this.ctx.service.ledger.tableName, mid, pid);
  990. if (!preLastChild) {
  991. preLastChild = preLedgerLastChild;
  992. } else {
  993. preLastChild = preLedgerLastChild && preLedgerLastChild[this.setting.order] > preLastChild[this.setting.order] ? preLedgerLastChild : preLastChild;
  994. }
  995. }
  996. return preLastChild;
  997. }
  998. async getLastChildData(tableName, mid, pid) {
  999. this.initSqlBuilder();
  1000. this.sqlBuilder.setAndWhere(this.setting.mid, {
  1001. value: mid,
  1002. operate: '=',
  1003. });
  1004. this.sqlBuilder.setAndWhere(this.setting.pid, {
  1005. value: pid,
  1006. operate: '=',
  1007. });
  1008. this.sqlBuilder.orderBy = [['order', 'DESC']];
  1009. const [sql, sqlParam] = this.sqlBuilder.build(tableName);
  1010. const resultData = await this.db.queryOne(sql, sqlParam);
  1011. return resultData;
  1012. }
  1013. /**
  1014. * 降级节点
  1015. *
  1016. * @param {Number} tenderId - 标段id
  1017. * @param {Number} selectId - 选中节点id
  1018. * @return {Array} - 发生改变的数据
  1019. */
  1020. async downLevelNode(mid, kid, count) {
  1021. if (!count) count = 1;
  1022. this.newBills = false;
  1023. const selects = await this.getDataByKidAndCount(mid, kid, count);
  1024. if (!selects) throw '降级节点数据错误';
  1025. const first = selects[0], last = selects[count - 1];
  1026. const pre = await this.getDataByParentAndOrder(mid, first[this.setting.pid], first[this.setting.order] - 1);
  1027. if (!pre) throw '节点不可降级';
  1028. const preLastChild = await this.getLastChildDataFormCR(mid, pre[this.setting.kid]);
  1029. const newPath = [];
  1030. this.transaction = await this.db.beginTransaction();
  1031. try {
  1032. // 选中节点--全部后节点 order--
  1033. await this._updateChildrenOrder(this.tableName, mid, first[this.setting.pid], last[this.setting.order] + 1, -count);
  1034. if (!this.newBills) {
  1035. await this._updateChildrenOrder(this.ctx.service.ledger.tableName, mid, first[this.setting.pid], last[this.setting.order] + 1, -count);
  1036. }
  1037. for (const [i, s] of selects.entries()) {
  1038. // 选中节点 修改pid, level, order, full_path
  1039. const updateData = { id: s.id };
  1040. updateData[this.setting.pid] = pre[this.setting.kid];
  1041. updateData[this.setting.order] = preLastChild ? preLastChild[this.setting.order] + i + 1 : i + 1;
  1042. updateData[this.setting.level] = s[this.setting.level] + 1;
  1043. const orgLastPath = s[this.setting.level] === 1 ? s[this.setting.kid] : '-' + s[this.setting.kid];
  1044. const newLastPath = s[this.setting.level] === 1 ? pre[this.setting.kid] + '-' + s[this.setting.kid] : '-' + pre[this.setting.kid] + '-' + s[this.setting.kid];
  1045. updateData[this.setting.fullPath] = s[this.setting.fullPath].replace(orgLastPath, newLastPath);
  1046. newPath.push(updateData[this.setting.fullPath]);
  1047. // console.log(updateData);
  1048. await this.transaction.update(this.tableName, updateData);
  1049. // 选中节点--全部子节点(含孙) level++, full_path
  1050. await this._syncDownlevelChildren(s, pre);
  1051. }
  1052. // 选中节点--前兄弟节点 is_leaf应为false, 清空计算相关字段
  1053. if (pre.ccid) {
  1054. const updateData2 = { id: pre.id };
  1055. updateData2[this.setting.isLeaf] = false;
  1056. this.clearParentingData(updateData2);
  1057. await this.transaction.update(this.tableName, updateData2);
  1058. await this._deleteChangeAuditListData(mid, [pre]);
  1059. }
  1060. // else if (!pre.ccid && pre.is_leaf === 1) {
  1061. // throw '原台账节点为子项时不能降级成为它的子项';
  1062. // }
  1063. await this.transaction.commit();
  1064. this.transaction = null;
  1065. } catch (err) {
  1066. await this.transaction.rollback();
  1067. this.transaction = null;
  1068. throw err;
  1069. }
  1070. // 查询修改的数据
  1071. let updateData = await this.getNextsData(this.tableName, mid, pre[this.setting.pid], pre[this.setting.order] - 1);
  1072. if (!this.newBills) {
  1073. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, mid, pre[this.setting.pid], pre[this.setting.order] - 1);
  1074. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  1075. }
  1076. // 选中节点及子节点
  1077. for (const p of newPath) {
  1078. updateData = updateData.concat(await this.getDataByFullPath(this.tableName, mid, p + '%'));
  1079. if (!this.newBills) {
  1080. updateData = updateData.concat(await this.getDataByFullPath(this.ctx.service.ledger.tableName, mid, p + '%'));
  1081. }
  1082. }
  1083. // 选中节点--原前兄弟节点&全部后兄弟节点
  1084. return { update: updateData };
  1085. }
  1086. async pasteBlockData (tid, sid, pasteData, defaultData) {
  1087. if ((tid <= 0) || (sid <= 0)) return [];
  1088. if (!pasteData || pasteData.length <= 0) throw '复制数据错误';
  1089. for (const pd of pasteData) {
  1090. if (!pd || pd.length <= 0) throw '复制数据错误';
  1091. pd.sort(function (x, y) {
  1092. return x.level - y.level
  1093. });
  1094. if (pd[0].ledger_pid !== pasteData[0][0].ledger_pid) throw '复制数据错误:仅可操作同层节点';
  1095. }
  1096. const selectData = await this.getDataByKid(tid, sid);
  1097. if (!selectData) throw '粘贴数据错误';
  1098. const newParentPath = selectData.full_path.replace(selectData.ledger_id, '');
  1099. const pasteBillsData = [], pastePosData = [], leafBillsId = [];
  1100. const tpDecimal = this.ctx.tender.info.decimal.tp;
  1101. let maxId = await this._getMaxLid(this.ctx.tender.id);
  1102. for (const [i, pd] of pasteData.entries()) {
  1103. for (const d of pd) {
  1104. d.children = pd.filter(function (x) {
  1105. return x.ledger_pid === d.ledger_id;
  1106. });
  1107. }
  1108. const pbd = [];
  1109. for (const [j, d] of pd.entries()) {
  1110. const newBills = {
  1111. id: this.uuid.v4(),
  1112. tender_id: tid,
  1113. ledger_id: maxId + j + 1,
  1114. ledger_pid: j === 0 ? selectData.ledger_pid : d.ledger_pid,
  1115. level: d.level + selectData.level - pd[0].level,
  1116. order: j === 0 ? selectData.order + i + 1 : d.order,
  1117. is_leaf: d.is_leaf,
  1118. code: d.code,
  1119. b_code: d.b_code,
  1120. name: d.name,
  1121. unit: d.unit,
  1122. unit_price: this.ctx.helper.round(d.unit_price, this.ctx.tender.info.decimal.up),
  1123. source: d.source,
  1124. remark: d.remark,
  1125. drawing_code: d.drawing_code,
  1126. memo: d.memo,
  1127. ex_memo1: d.ex_memo1,
  1128. ex_memo2: d.ex_memo2,
  1129. ex_memo3: d.ex_memo3,
  1130. node_type: d.node_type,
  1131. sgfh_expr: d.sgfh_expr,
  1132. sjcl_expr: d.sjcl_expr,
  1133. qtcl_expr: d.qtcl_expr,
  1134. check_calc: 1,
  1135. ccid: this.ctx.change.cid,
  1136. formc: 1,
  1137. };
  1138. for (const c of d.children) {
  1139. c.ledger_pid = newBills.ledger_id;
  1140. }
  1141. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, newBills.unit);
  1142. newBills.deal_qty = this.ctx.helper.round(d.deal_qty, precision.value);
  1143. if (d.pos && d.pos.length > 0) {
  1144. for (const pos of d.pos) {
  1145. const newPos = {
  1146. id: this.uuid.v4(),
  1147. tid: tid,
  1148. lid: newBills.id,
  1149. name: pos.name,
  1150. drawing_code: pos.drawing_code,
  1151. add_user: this.ctx.session.sessionUser.accountId,
  1152. in_time: new Date(),
  1153. porder: pos.porder,
  1154. position: pos.position,
  1155. sgfh_expr: pos.sgfh_expr ? pos.sgfh_expr : '',
  1156. sjcl_expr: pos.sjcl_expr ? pos.sjcl_expr : '',
  1157. qtcl_expr: pos.qtcl_expr ? pos.qtcl_expr : '',
  1158. add_stage: 0,
  1159. add_stage_order: 0,
  1160. add_times: 0,
  1161. ex_memo1: pos.ex_memo1,
  1162. ex_memo2: pos.ex_memo2,
  1163. ex_memo3: pos.ex_memo3,
  1164. ccid: this.ctx.change.cid,
  1165. formc: 1,
  1166. };
  1167. this._calcExpr(newPos, 'sgfh_qty', pos.sgfh_expr, pos.sgfh_qty, precision);
  1168. this._calcExpr(newPos, 'sjcl_qty', pos.sjcl_expr, pos.sjcl_qty, precision);
  1169. this._calcExpr(newPos, 'qtcl_qty', pos.qtcl_expr, pos.qtcl_qty, precision);
  1170. newPos.quantity = this.ctx.helper.add(newPos.sgfh_qty,
  1171. this.ctx.helper.add(newPos.sjcl_qty, newPos.qtcl_qty));
  1172. newBills.sgfh_qty = this.ctx.helper.add(newBills.sgfh_qty, newPos.sgfh_qty);
  1173. newBills.sjcl_qty = this.ctx.helper.add(newBills.sjcl_qty, newPos.sjcl_qty);
  1174. newBills.qtcl_qty = this.ctx.helper.add(newBills.qtcl_qty, newPos.qtcl_qty);
  1175. if (defaultData) this.ctx.helper._.assignIn(newPos, defaultData);
  1176. pastePosData.push(newPos);
  1177. }
  1178. } else {
  1179. this._calcExpr(newBills, 'sgfh_qty', newBills.sgfh_expr, d.sgfh_qty, precision);
  1180. this._calcExpr(newBills, 'sjcl_qty', newBills.sjcl_expr, d.sjcl_qty, precision);
  1181. this._calcExpr(newBills, 'qtcl_qty', newBills.qtcl_expr, d.qtcl_qty, precision);
  1182. }
  1183. newBills.quantity = this.ctx.helper.add(newBills.sgfh_qty,
  1184. this.ctx.helper.add(newBills.sjcl_qty, newBills.qtcl_qty));
  1185. newBills.sgfh_tp = this.ctx.helper.mul(newBills.sgfh_qty, newBills.unit_price, tpDecimal);
  1186. newBills.sjcl_tp = this.ctx.helper.mul(newBills.qtcl_qty, newBills.unit_price, tpDecimal);
  1187. newBills.qtcl_tp = this.ctx.helper.mul(newBills.sjcl_qty, newBills.unit_price, tpDecimal);
  1188. newBills.total_price = this.ctx.helper.mul(newBills.quantity, newBills.unit_price, tpDecimal);
  1189. newBills.deal_tp = this.ctx.helper.mul(newBills.deal_qty, newBills.unit_price, tpDecimal);
  1190. if (defaultData) this.ctx.helper._.assignIn(newBills, defaultData);
  1191. pbd.push(newBills);
  1192. }
  1193. for (const d of pbd) {
  1194. const parent = pbd.find(function (x) {
  1195. return x.ledger_id === d.ledger_pid;
  1196. });
  1197. d.full_path = parent
  1198. ? parent.full_path + '-' + d.ledger_id
  1199. : newParentPath + d.ledger_id;
  1200. if (defaultData) this.ctx.helper._.assignIn(pbd, defaultData);
  1201. pasteBillsData.push(d);
  1202. }
  1203. maxId = maxId + pbd.length;
  1204. }
  1205. this.transaction = await this.db.beginTransaction();
  1206. try {
  1207. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  1208. await this._updateChildrenOrder(this.tableName, tid, selectData.ledger_pid, selectData.order + 1, pasteData.length);
  1209. if (!this.newBills) {
  1210. await this._updateChildrenOrder(this.ctx.service.ledger.tableName, tid, selectData.ledger_pid, selectData.order + 1, pasteData.length);
  1211. }
  1212. // 数据库创建新增节点数据
  1213. if (pasteBillsData.length > 0) {
  1214. const newData = await this.transaction.insert(this.tableName, pasteBillsData);
  1215. }
  1216. this._cacheMaxLid(tid, maxId);
  1217. if (pastePosData.length > 0) {
  1218. await this.transaction.insert(this.ctx.service.changePos.tableName, pastePosData);
  1219. }
  1220. await this.transaction.commit();
  1221. } catch (err) {
  1222. await this.transaction.rollback();
  1223. throw err;
  1224. }
  1225. // 查询应返回的结果
  1226. let updateData = await this.getNextsData(this.tableName, selectData.tender_id, selectData.ledger_pid, selectData.order + pasteData.length);
  1227. if (!this.newBills) {
  1228. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, selectData.tender_id, selectData.ledger_pid, selectData.order + pasteData.length);
  1229. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  1230. }
  1231. return {
  1232. ledger: { create: pasteBillsData, update: updateData },
  1233. pos: pastePosData,
  1234. };
  1235. }
  1236. /**
  1237. * 添加标准节点,将选择的标准节点,添加为子节点(排序为末尾)
  1238. * @param {Number} tenderId - 标段Id
  1239. * @param {Number} selectId - 添加目标节点Id
  1240. * @param {Object} stdData - 标准节点数据
  1241. * @returns {Promise<*>}
  1242. */
  1243. async addStdNodeAsChild(tenderId, selectId, stdData, changeId) {
  1244. const newData = this._filterStdData(stdData);
  1245. const result = await this.addChild(tenderId, selectId, newData, changeId);
  1246. return result;
  1247. }
  1248. /**
  1249. * 新增子节点,并排在所有子节点的末尾
  1250. * @param {Number} tenderId - 标段Id
  1251. * @param {Number} selectId - 父节点Id
  1252. * @param {Object} data - 新增节点数据(编号名称等)
  1253. * @returns {Promise<*>}
  1254. */
  1255. async addChild(tenderId, selectId, data, changeId) {
  1256. if ((tenderId <= 0) || (selectId <= 0)) {
  1257. return [];
  1258. }
  1259. this.newBills = false;
  1260. const selectData = await this.getDataByKid(tenderId, selectId);
  1261. if (!selectData) {
  1262. throw '新增节点数据错误';
  1263. }
  1264. let children = await this.getChildrenByParentId(this.tableName, tenderId, selectId);
  1265. if (!this.newBills) {
  1266. const ledgerChildren = await this.getChildrenByParentId(this.ctx.service.ledger.tableName, tenderId, selectId);
  1267. children = this._.orderBy(this._.concat(ledgerChildren, children), [this.setting.order], ['asc']);
  1268. }
  1269. const maxId = await this._getMaxLid(tenderId);
  1270. data.id = this.uuid.v4();
  1271. data.tender_id = tenderId;
  1272. data.ledger_id = maxId + 1;
  1273. data.ledger_pid = selectData.ledger_id;
  1274. data.level = selectData.level + 1;
  1275. data.order = children.length + 1;
  1276. data.full_path = selectData.full_path + '-' + data.ledger_id;
  1277. data.is_leaf = true;
  1278. data.ccid = changeId;
  1279. data.check_calc = 1;
  1280. // if (reviseId) data.crid = reviseId;
  1281. this.transaction = await this.db.beginTransaction();
  1282. try {
  1283. const result = await this.transaction.insert(this.tableName, data);
  1284. if (children.length === 0 && selectData.ccid) {
  1285. await this.transaction.update(this.tableName,
  1286. {
  1287. is_leaf: false,
  1288. sgfh_qty: null, sgfh_tp: null, qtcl_qty: null, qtcl_tp: null, sjcl_qty: null, sjcl_tp: null,
  1289. quantity: null, unit_price: null, total_price: null, deal_qty: null, deal_tp: null
  1290. },
  1291. { where: {tender_id: tenderId, ledger_id: selectData.ledger_id} });
  1292. }
  1293. // else if (!selectData.ccid && children.length === 0) {
  1294. // throw '原台账节点为子项时不能添加它的子项';
  1295. // }
  1296. await this.transaction.commit();
  1297. } catch (err) {
  1298. this.transaction.rollback();
  1299. throw err;
  1300. }
  1301. this._cacheMaxLid(tenderId, maxId + 1);
  1302. // 查询应返回的结果
  1303. const resultData = {};
  1304. resultData.create = await this.getDataByKid(tenderId, data.ledger_id);
  1305. if (children.length === 0) {
  1306. resultData.update = await this.getDataByKid(tenderId, selectId);
  1307. }
  1308. return resultData;
  1309. }
  1310. /**
  1311. * 根据 父节点id 获取子节点
  1312. * @param tenderId
  1313. * @param nodeId
  1314. * @return {Promise<*>}
  1315. */
  1316. async getChildrenByParentId(tableName, tenderId, nodeId) {
  1317. if (tenderId <= 0 || !nodeId) {
  1318. return undefined;
  1319. }
  1320. const nodeIds = nodeId instanceof Array ? nodeId : [nodeId];
  1321. if (nodeIds.length === 0) {
  1322. return [];
  1323. }
  1324. this.initSqlBuilder();
  1325. this.sqlBuilder.setAndWhere('tender_id', {
  1326. value: tenderId,
  1327. operate: '=',
  1328. });
  1329. this.sqlBuilder.setAndWhere('ledger_pid', {
  1330. value: nodeIds,
  1331. operate: 'in',
  1332. });
  1333. this.sqlBuilder.orderBy = [['order', 'ASC']];
  1334. const [sql, sqlParam] = this.sqlBuilder.build(tableName);
  1335. const data = await this.db.query(sql, sqlParam);
  1336. return data;
  1337. }
  1338. /**
  1339. * 添加节点(来自标准清单)
  1340. * @param {Number} tenderId
  1341. * @param {Number} selectId
  1342. * @param {Object} stdData
  1343. * @return {Promise<*>}
  1344. */
  1345. async addStdNode(tenderId, selectId, stdData, changeId) {
  1346. const newData = this._filterStdData(stdData);
  1347. const result = await this.addBillsNode(tenderId, selectId, newData, changeId);
  1348. return result;
  1349. }
  1350. async addBillsNode(tenderId, selectId, data, changeId) {
  1351. if (data) {
  1352. if (changeId) data.ccid = changeId;
  1353. data.check_calc = 1;
  1354. return await this.addNode(tenderId, selectId, data);
  1355. } else {
  1356. return await this.addNode(tenderId, selectId, {ccid: changeId, check_calc: 1});
  1357. }
  1358. }
  1359. /**
  1360. * 添加节点,并同步添加父节点
  1361. * @param {Number} tenderId - 标段id
  1362. * @param {Number} selectId - 选中节点id
  1363. * @param {Object} stdData - 节点数据
  1364. * @param {StandardLib} stdLib - 标准库
  1365. * @return {Promise<void>}
  1366. */
  1367. async addStdNodeWithParent(tenderId, stdData, stdLib, changeId) {
  1368. // 查询完整标准清单,并按层次排序
  1369. const fullLevel = await stdLib.getFullLevelDataByFullPath(stdData.list_id, stdData.full_path);
  1370. fullLevel.sort(function(x, y) {
  1371. return x.level - y.level;
  1372. });
  1373. let isNew = false,
  1374. node,
  1375. firstNew,
  1376. updateParent,
  1377. addResult;
  1378. const expandIds = [];
  1379. this.transaction = await this.db.beginTransaction();
  1380. try {
  1381. // 从最顶层节点依次查询是否存在,否则添加
  1382. for (let i = 0, len = fullLevel.length; i < len; i++) {
  1383. const stdNode = fullLevel[i];
  1384. if (isNew) {
  1385. const newData = this._filterStdData(stdNode);
  1386. newData.is_leaf = (i === len - 1);
  1387. [addResult, node] = await this._addChildNodeData(tenderId, node, newData, changeId);
  1388. } else {
  1389. const parent = node;
  1390. node = await this.getDataByCondition({
  1391. tender_id: tenderId,
  1392. ledger_pid: parent ? parent.ledger_id : rootId,
  1393. code: stdNode.code,
  1394. name: stdNode.name,
  1395. }) || await this.ctx.service.ledger.getDataByCondition({tender_id: tenderId, ledger_pid: parent ? parent.ledger_id : rootId, code: stdNode.code, name: stdNode.name });
  1396. if (!node) {
  1397. let children = await this.getChildrenByParentId(this.tableName, tenderId, parent.ledger_id);
  1398. if (!this.newBills) {
  1399. const ledgerChildren = await this.getChildrenByParentId(this.ctx.service.ledger.tableName, tenderId, parent.ledger_id);
  1400. children = this._.orderBy(this._.concat(ledgerChildren, children), [this.setting.order], ['asc']);
  1401. }
  1402. // if (children.length === 0 && !parent.ccid) {
  1403. // throw '原台账节点为子项时不能添加它的子项';
  1404. // }
  1405. isNew = true;
  1406. const newData = this._filterStdData(stdNode);
  1407. newData.is_leaf = (i === len - 1);
  1408. [addResult, node] = await this._addChildAutoOrder(tenderId, parent, newData, changeId);
  1409. if (parent && parent.is_leaf && this.newBills) {
  1410. await this.transaction.update(this.tableName, { id: parent.id, is_leaf: false,
  1411. unit_price: null, quantity: null, total_price: null, deal_qty: null, deal_tp: null});
  1412. updateParent = parent;
  1413. }
  1414. firstNew = node;
  1415. } else {
  1416. expandIds.push(node.ledger_id);
  1417. }
  1418. }
  1419. }
  1420. await this.transaction.commit();
  1421. } catch (err) {
  1422. await this.transaction.rollback();
  1423. throw err;
  1424. }
  1425. // 查询应返回的结果
  1426. let createData = [],
  1427. updateData = [];
  1428. if (firstNew) {
  1429. createData = await this.getDataByFullPath(this.tableName, tenderId, firstNew.full_path + '%');
  1430. updateData = await this.getNextsData(this.tableName, tenderId, firstNew.ledger_pid, firstNew.order);
  1431. if (!this.newBills) {
  1432. createData = createData.concat(await this.getDataByFullPath(this.ctx.service.ledger.tableName, tenderId, firstNew.full_path + '%'));
  1433. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, tenderId, firstNew.ledger_pid, firstNew.order);
  1434. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  1435. }
  1436. if (updateParent) {
  1437. updateData.push(await this.getDataByCondition({ id: updateParent.id }));
  1438. }
  1439. }
  1440. return { create: createData, update: updateData };
  1441. }
  1442. /**
  1443. * 根据parentData, data新增数据(新增为parentData的最后一个子项)
  1444. * @param {Number} tenderId - 标段id
  1445. * @param {Object} parentData - 父项数据
  1446. * @param {Object} data - 新增节点,初始数据
  1447. * @return {Promise<*>} - 新增结果
  1448. * @private
  1449. */
  1450. async _addChildNodeData(tenderId, parentData, data, changeId) {
  1451. if (tenderId <= 0) {
  1452. return undefined;
  1453. }
  1454. if (!data) {
  1455. data = {};
  1456. }
  1457. const pid = parentData ? parentData.ledger_id : rootId;
  1458. const maxId = await this._getMaxLid(tenderId);
  1459. data.id = this.uuid.v4();
  1460. data.tender_id = tenderId;
  1461. data.ledger_id = maxId + 1;
  1462. data.ledger_pid = pid;
  1463. if (data.order === undefined) {
  1464. data.order = 1;
  1465. }
  1466. data.level = parentData ? parentData.level + 1 : 1;
  1467. data.full_path = parentData ? parentData.full_path + '-' + data.ledger_id : '' + data.ledger_id;
  1468. if (data.is_leaf === undefined) {
  1469. data.is_leaf = true;
  1470. }
  1471. data.check_calc = 1;
  1472. if (changeId) data.ccid = changeId;
  1473. const result = await this.transaction.insert(this.tableName, data);
  1474. this._cacheMaxLid(tenderId, maxId + 1);
  1475. return [result, data];
  1476. }
  1477. /**
  1478. * 根据parentData, data新增数据(自动排序)
  1479. * @param tenderId
  1480. * @param parentData
  1481. * @param data
  1482. * @return {Promise<void>}
  1483. * @private
  1484. */
  1485. async _addChildAutoOrder(tenderId, parentData, data, changeId) {
  1486. const self = this;
  1487. const findPreData = function(list, a) {
  1488. if (!list || list.length === 0) { return null; }
  1489. for (let i = 0, iLen = list.length; i < iLen; i++) {
  1490. if (billsUtils.compareCode(list[i].code, a.code) > 0) {
  1491. return i > 0 ? list[i - 1] : null;
  1492. }
  1493. }
  1494. return list[list.length - 1];
  1495. };
  1496. const pid = parentData ? parentData.ledger_id : rootId;
  1497. let children = await this.getChildrenByParentId(this.tableName, tenderId, pid);
  1498. if (!this.newBills) {
  1499. const ledgerChildren = await this.getChildrenByParentId(this.ctx.service.ledger.tableName, tenderId, pid);
  1500. children = this._.orderBy(this._.concat(children, ledgerChildren), [this.setting.order], ['asc']);
  1501. }
  1502. const preData = findPreData(children, data);
  1503. if (!preData || children.indexOf(preData) < children.length - 1) {
  1504. await this._updateChildrenOrder(this.tableName, tenderId, pid, preData ? preData.order + 1 : 1);
  1505. if (!this.newBills) {
  1506. await this._updateChildrenOrder(this.ctx.service.ledger.tableName, tenderId, pid, preData ? preData.order + 1 : 1);
  1507. }
  1508. }
  1509. data.order = preData ? preData.order + 1 : 1;
  1510. const [addResult, node] = await this._addChildNodeData(tenderId, parentData, data, changeId);
  1511. return [addResult, node];
  1512. }
  1513. /**
  1514. * 提交数据 - 响应计算(增量方式计算)
  1515. * @param {Number} tenderId
  1516. * @param {Object} data
  1517. * @return {Promise<*>}
  1518. */
  1519. async updateCalc(tenderId, data) {
  1520. const helper = this.ctx.helper;
  1521. // 简单验证数据
  1522. if (tenderId <= 0 || !this.ctx.tender) {
  1523. throw '标段不存在';
  1524. }
  1525. const info = this.ctx.tender.info;
  1526. if (!data) {
  1527. throw '提交数据错误';
  1528. }
  1529. const datas = data instanceof Array ? data : [data];
  1530. const ids = [];
  1531. for (const row of datas) {
  1532. if (tenderId !== row.tender_id) {
  1533. throw '提交数据错误';
  1534. }
  1535. ids.push(row.id);
  1536. }
  1537. this.transaction = await this.db.beginTransaction();
  1538. try {
  1539. const updateDatas = [];
  1540. for (const row of datas) {
  1541. const updateNode = await this.getDataById(row.id);
  1542. if (!updateNode || tenderId !== updateNode.tender_id || row.ledger_id !== updateNode.ledger_id) {
  1543. throw '提交数据错误';
  1544. }
  1545. let updateData;
  1546. // 更新单位或单价,全部数据都应重算
  1547. if (row.unit !== undefined || row.unit_price !== undefined) {
  1548. if (row.sgfh_qty === undefined) { row.sgfh_qty = updateNode.sgfh_qty; }
  1549. if (row.sjcl_qty === undefined) { row.sjcl_qty = updateNode.sjcl_qty; }
  1550. if (row.qtcl_qty === undefined) { row.qtcl_qty = updateNode.qtcl_qty; }
  1551. if (row.deal_qty === undefined) { row.deal_qty = updateNode.deal_qty; }
  1552. }
  1553. // 项目节、工程量清单相关
  1554. if (row.b_code) {
  1555. row.dgn_qty1 = null;
  1556. row.dgn_qty2 = null;
  1557. row.code = null;
  1558. }
  1559. if (row.code) row.b_code = null;
  1560. if (this._checkCalcField(row)) {
  1561. const calcData = JSON.parse(JSON.stringify(row));
  1562. calcData.check_calc = 1;
  1563. const precision = helper.findPrecision(info.precision, row.unit ? row.unit : updateNode.unit);
  1564. // 数量保留小数位数
  1565. helper.checkFieldPrecision(calcData, qtyFields, precision.value);
  1566. // 单位保留小数位数
  1567. helper.checkFieldPrecision(calcData, upFields, info.decimal.up);
  1568. // 未提交单价则读取数据库单价
  1569. if (row.unit_price === undefined) calcData.unit_price = updateNode.unit_price;
  1570. // 计算
  1571. if (row.sgfh_qty !== undefined || row.sjcl_qty !== undefined || row.qtcl_qty !== undefined ||
  1572. row.deal_qty !== undefined || row.unit_price) {
  1573. if (row.sgfh_qty === undefined) calcData.sgfh_qty = updateNode.sgfh_qty;
  1574. if (row.sjcl_qty === undefined) calcData.sjcl_qty = updateNode.sjcl_qty;
  1575. if (row.qtcl_qty === undefined) calcData.qtcl_qty = updateNode.qtcl_qty;
  1576. if (row.deal_qty === undefined) calcData.deal_qty = updateNode.deal_qty;
  1577. calcData.quantity = helper.sum([calcData.sgfh_qty, calcData.sjcl_qty, calcData.qtcl_qty]);
  1578. calcData.sgfh_tp = helper.mul(calcData.sgfh_qty, calcData.unit_price, info.decimal.tp);
  1579. calcData.sjcl_tp = helper.mul(calcData.sjcl_qty, calcData.unit_price, info.decimal.tp);
  1580. calcData.qtcl_tp = helper.mul(calcData.qtcl_qty, calcData.unit_price, info.decimal.tp);
  1581. calcData.total_price = helper.mul(calcData.quantity, calcData.unit_price, info.decimal.tp);
  1582. calcData.deal_tp = helper.mul(calcData.deal_qty, calcData.unit_price, info.decimal.tp);
  1583. } else if (row.sgfh_tp !== undefined || row.sjcl_tp !== undefined || row.qtcl_tp !== undefined || row.deal_tp !== undefined) {
  1584. calcData.sgfh_qty = null;
  1585. calcData.sjcl_qty = null;
  1586. calcData.qtcl_qty = null;
  1587. calcData.quantity = null;
  1588. calcData.deal_qty = null;
  1589. calcData.sgfh_tp = helper.round(row.sgfh_tp !== undefined ? calcData.row.sgfh_tp : updateNode.sgfh_tp, info.decimal.tp);
  1590. calcData.sjcl_tp = helper.round(row.sgfh_tp !== undefined ? calcData.row.sjcl_tp : updateNode.sjcl_tp, info.decimal.tp);
  1591. calcData.qtcl_tp = helper.round(row.sgfh_tp !== undefined ? calcData.row.qtcl_tp : updateNode.qtcl_tp, info.decimal.tp);
  1592. calcData.total_price = helper.sum([calcData.sgfh_tp, calcData.sjcl_tp, calcData.qtcl_tp]);
  1593. calcData.deal_tp = helper.round(row.deal_tp !== undefined ? calcData.row.deal_tp : updateNode.deal_tp, info.decimal.tp);
  1594. } else if (row.unit_price !== undefined) {
  1595. calcData.sgfh_tp = helper.mul(calcData.sgfh_qty, calcData.unit_price, info.decimal.tp);
  1596. calcData.sjcl_tp = helper.mul(calcData.sjcl_qty, calcData.unit_price, info.decimal.tp);
  1597. calcData.qtcl_tp = helper.mul(calcData.qtcl_qty, calcData.unit_price, info.decimal.tp);
  1598. calcData.total_price = helper.mul(calcData.quantity, calcData.unit_price, info.decimal.tp);
  1599. calcData.deal_tp = helper.mul(calcData.deal_qty, calcData.unit_price, info.decimal.tp);
  1600. }
  1601. updateData = this._filterUpdateInvalidField(updateNode.id, calcData);
  1602. } else {
  1603. updateData = this._filterUpdateInvalidField(updateNode.id, row);
  1604. }
  1605. await this.transaction.update(this.tableName, updateData);
  1606. // 如非子节点,需要更新底下所有已选清单的分部分项等数据
  1607. updateDatas.push(updateData);
  1608. }
  1609. // console.log(updateDatas);
  1610. // 如果是子节点 更新了单位或单价,则更新数据并重算变更令总金额
  1611. await this.ctx.service.changeAuditList.updateDataByReviseLedger(this.transaction, tenderId, updateDatas);
  1612. await this.transaction.commit();
  1613. this.transaction = null;
  1614. } catch (err) {
  1615. await this.transaction.rollback();
  1616. this.transaction = null;
  1617. throw err;
  1618. }
  1619. return { update: await this.getDataById(ids) };
  1620. }
  1621. }
  1622. return ChangeLedger;
  1623. };