change_ledger.js 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750
  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, transaction = this.transaction) {
  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 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, transaction = this.transaction) {
  380. await this.ctx.service.changePos.deletePosData(transaction, mid, this._.map(deleteData, 'id'));
  381. }
  382. async _deleteChangeAuditListData(mid, deleteData, transaction = this.transaction) {
  383. await this.ctx.service.changeAuditList.deleteDataByRevise(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, transaction = this.transaction) {
  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 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 = null) {
  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. async deleteBySettle(transcation, mid, ledgerDatas) {
  538. if (ledgerDatas.length <= 0) return;
  539. const allDeleteData = [];
  540. for (const l of ledgerDatas) {
  541. // 删除部位明细
  542. const deleteData = await this.getDataByFullPath(this.tableName, mid, l[this.setting.fullPath] + '%', transcation);
  543. if (deleteData.length === 0) throw '删除节点数据错误';
  544. // deleteData数组插入到allDeleteData后面
  545. allDeleteData.push(...deleteData);
  546. const operate = await this._deleteNodeData(mid, l, transcation);
  547. await this._updateChildrenOrder(this.ctx.service.ledger.tableName, mid, l[this.setting.pid], l[this.setting.order] + 1, -1, transcation);
  548. }
  549. await this._deleteRelaData(mid, allDeleteData, transcation);
  550. await this._deleteChangeAuditListData(mid, allDeleteData, transcation);
  551. }
  552. /**
  553. * 上移节点
  554. *
  555. * @param {Number} mid - master id
  556. * @param {Number} kid - 选中节点id
  557. * @return {Array} - 发生改变的数据
  558. */
  559. async upMoveNode(mid, kid, count) {
  560. if (!count) count = 1;
  561. if (!mid || (mid <= 0) || !kid || (kid <= 0)) return null;
  562. this.newBills = false;
  563. const selects = await this.getDataByKidAndCount(mid, kid, count);
  564. if (selects.length !== count) throw '上移节点数据错误';
  565. const first = selects[0];
  566. const pre = await this.getDataByParentAndOrder(mid, first[this.setting.pid], first[this.setting.order] - 1);
  567. if (!pre) throw '节点不可上移';
  568. const order = [];
  569. this.transaction = await this.db.beginTransaction();
  570. try {
  571. for (const s of selects) {
  572. const sData = await this.transaction.update(this.tableName, { id: s.id, order: s[this.setting.order] - 1 });
  573. if (!this.newBills) {
  574. await this.transaction.update(this.ctx.service.ledger.tableName, { id: s.id, order: s[this.setting.order] - 1 });
  575. }
  576. order.push(s[this.setting.order] - 1);
  577. }
  578. const pData = await this.transaction.update(this.tableName, { id: pre.id, order: pre[this.setting.order] + count });
  579. if (!this.newBills) {
  580. await this.transaction.update(this.ctx.service.ledger.tableName, { id: pre.id, order: pre[this.setting.order] + count });
  581. }
  582. order.push(pre[this.setting.order] + count);
  583. await this.transaction.commit();
  584. this.transaction = null;
  585. } catch (err) {
  586. await this.transaction.rollback();
  587. this.transaction = null;
  588. throw err;
  589. }
  590. const resultData = await this.getDataByParentAndOrder(mid, first[this.setting.pid], order);
  591. return { update: resultData };
  592. }
  593. /**
  594. * 下移节点
  595. *
  596. * @param {Number} mid - master id
  597. * @param {Number} kid - 选中节点id
  598. * @return {Array} - 发生改变的数据
  599. */
  600. async downMoveNode(mid, kid, count) {
  601. if (!count) count = 1;
  602. if (!mid || (mid <= 0) || !kid || (kid <= 0)) return null;
  603. this.newBills = false;
  604. const selects = await this.getDataByKidAndCount(mid, kid, count);
  605. if (selects.length !== count) {
  606. throw '下移节点数据错误';
  607. }
  608. const last = selects[count - 1];
  609. const next = await this.getDataByParentAndOrder(mid, last[this.setting.pid], last[this.setting.order] + 1);
  610. if (!next) {
  611. throw '节点不可下移';
  612. }
  613. const order = [];
  614. this.transaction = await this.db.beginTransaction();
  615. try {
  616. for (const s of selects) {
  617. const sData = await this.transaction.update(this.tableName, { id: s.id, order: s[this.setting.order] + 1 });
  618. if (!this.newBills) {
  619. await this.transaction.update(this.ctx.service.ledger.tableName, { id: s.id, order: s[this.setting.order] + 1 });
  620. }
  621. order.push(s[this.setting.order] + 1);
  622. }
  623. const nData = await this.transaction.update(this.tableName, { id: next.id, order: next[this.setting.order] - count });
  624. if (!this.newBills) {
  625. await this.transaction.update(this.ctx.service.ledger.tableName, { id: next.id, order: next[this.setting.order] - count });
  626. }
  627. order.push(next[this.setting.order] - count);
  628. await this.transaction.commit();
  629. this.transaction = null;
  630. } catch (err) {
  631. await this.transaction.rollback();
  632. this.transaction = null;
  633. throw err;
  634. }
  635. const resultData = await this.getDataByParentAndOrder(mid, last[this.setting.pid], order);
  636. return { update: resultData };
  637. }
  638. /**
  639. * 批量插入子项
  640. * @param {Number} tenderId - 标段Id
  641. * @param {Number} selectId - 选中节点Id
  642. * @param {Object} data - 批量插入数据
  643. * @return {Promise<void>}
  644. */
  645. async batchInsertChild(tenderId, selectId, data) {
  646. const result = { ledger: {}, pos: null };
  647. if ((tenderId <= 0) || (selectId <= 0)) {
  648. return result;
  649. }
  650. const selectData = await this.getDataByNodeId(tenderId, selectId);
  651. if (!selectData) {
  652. throw '位置数据错误';
  653. }
  654. this.transaction = await this.db.beginTransaction();
  655. const newIds = [];
  656. const lastChild = await this.getLastChildData(tenderId, selectId);
  657. try {
  658. // 更新父项isLeaf
  659. if (!lastChild) {
  660. await this.transaction.update(this.tableName, {
  661. id: selectData.id,
  662. is_leaf: false,
  663. unit_price: null,
  664. sgfh_qty: null,
  665. sgfh_tp: null,
  666. sjcl_qty: null,
  667. sjcl_tp: null,
  668. qtcl_qty: null,
  669. qtcl_tp: null,
  670. quantity: null,
  671. total_price: null,
  672. deal_qty: null,
  673. deal_tp: null,
  674. });
  675. }
  676. const order = lastChild ? lastChild.order : 0;
  677. // 计算id
  678. const maxId = await this._getMaxLid(tenderId);
  679. // 数据库创建新增节点数据
  680. for (let i = 0, iLen = data.length; i < iLen; i++) {
  681. // 合并新增数据
  682. const qd = {
  683. id: this.uuid.v4(),
  684. tender_id: tenderId,
  685. ledger_id: maxId + i + 1,
  686. ledger_pid: selectData.ledger_id,
  687. is_leaf: true,
  688. order: order + i + 1,
  689. level: selectData.level + 1,
  690. b_code: data[i].b_code,
  691. name: data[i].name,
  692. unit: data[i].unit,
  693. unit_price: data[i].price,
  694. };
  695. qd.full_path = selectData.full_path + '-' + qd.ledger_id;
  696. const insertResult = await this.transaction.insert(this.tableName, qd);
  697. newIds.push(qd.id);
  698. if (data[i].pos.length > 0) {
  699. await this.ctx.service.pos.insertLedgerPosData(this.transaction, tenderId, qd, data[i].pos);
  700. await this.calcNode(qd, this.transaction);
  701. }
  702. }
  703. this._cacheMaxLid(tenderId, maxId + data.length);
  704. await this.transaction.commit();
  705. } catch (err) {
  706. await this.transaction.rollback();
  707. throw err;
  708. }
  709. // 查询应返回的结果
  710. result.ledger.create = await this.getDataByIds(newIds);
  711. if (!lastChild) {
  712. result.ledger.update = await this.getDataByIds([selectData.id]);
  713. }
  714. result.pos = await this.ctx.service.pos.getPosData({tid: tenderId, lid: newIds });
  715. return result;
  716. }
  717. /**
  718. * 批量插入后项
  719. * @param {Number} tenderId - 标段Id
  720. * @param {Number} selectId - 选中节点Id
  721. * @param {Object} data - 批量插入数据
  722. * @return {Promise<void>}
  723. */
  724. async batchInsertNext(tenderId, selectId, data) {
  725. const result = { ledger: {}, pos: null };
  726. if ((tenderId <= 0) || (selectId <= 0)) {
  727. return result;
  728. }
  729. const selectData = await this.getDataByNodeId(tenderId, selectId);
  730. if (!selectData) {
  731. throw '位置数据错误';
  732. }
  733. const parentData = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  734. if (!parentData) {
  735. throw '位置数据错误';
  736. }
  737. this.transaction = await this.db.beginTransaction();
  738. const newIds = [];
  739. try {
  740. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  741. await this._updateChildrenOrder(tenderId, selectData.ledger_pid, selectData.order + 1, data.length);
  742. // 计算id和order
  743. const maxId = await this._getMaxLid(tenderId);
  744. const order = selectData.order;
  745. // 数据库创建新增节点数据
  746. for (let i = 0, iLen = data.length; i < iLen; i++) {
  747. // 合并新增数据
  748. const qd = {
  749. id: this.uuid.v4(),
  750. tender_id: tenderId,
  751. ledger_id: maxId + i + 1,
  752. ledger_pid: parentData.ledger_id,
  753. is_leaf: true,
  754. order: order + i + 1,
  755. level: parentData.level + 1,
  756. b_code: data[i].b_code,
  757. name: data[i].name,
  758. unit: data[i].unit,
  759. unit_price: data[i].price,
  760. };
  761. qd.full_path = parentData.full_path + '-' + qd.ledger_id;
  762. const insertResult = await this.transaction.insert(this.tableName, qd);
  763. newIds.push(qd.id);
  764. if (data[i].pos.length > 0) {
  765. await this.ctx.service.pos.insertLedgerPosData(this.transaction, tenderId, qd, data[i].pos);
  766. await this.calcNode(qd, this.transaction);
  767. }
  768. }
  769. this._cacheMaxLid(tenderId, maxId + data.length);
  770. await this.transaction.commit();
  771. } catch (err) {
  772. await this.transaction.rollback();
  773. throw err;
  774. }
  775. // 查询应返回的结果
  776. result.ledger.create = await this.getDataByIds(newIds);
  777. result.ledger.update = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + data.length);
  778. result.pos = await this.ctx.service.pos.getPosData({tid: tenderId, lid: newIds });
  779. return result;
  780. }
  781. /**
  782. * 升级selectData, 同步修改所有子节点
  783. * @param {Object} selectData - 升级操作,选中节点
  784. * @return {Object}
  785. * @private
  786. */
  787. async _syncUplevelChildren(select) {
  788. this.initSqlBuilder();
  789. this.sqlBuilder.setAndWhere(this.setting.mid, {
  790. value: select[this.setting.mid],
  791. operate: '=',
  792. });
  793. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  794. value: this.db.escape(select[this.setting.fullPath] + '-%'),
  795. operate: 'like',
  796. });
  797. this.sqlBuilder.setUpdateData(this.setting.level, {
  798. value: 1,
  799. selfOperate: '-',
  800. });
  801. this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  802. value: [this.setting.fullPath, this.db.escape(select[this.setting.pid] + '-'), this.db.escape('')],
  803. literal: 'Replace',
  804. });
  805. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  806. const data = await this.transaction.query(sql, sqlParam);
  807. return data;
  808. }
  809. /**
  810. * 选中节点的后兄弟节点,全部变为当前节点的子节点
  811. * @param {Object} selectData - 选中节点
  812. * @return {Object}
  813. * @private
  814. */
  815. async _syncUpLevelNexts(select) {
  816. // 查询selectData的lastChild
  817. const lastChild = await this.getLastChildDataFormCR(select[this.setting.mid], select[this.setting.kid]);
  818. const nexts = await this.getNextsData(this.tableName, select[this.setting.mid], select[this.setting.pid], select[this.setting.order]);
  819. if (nexts && nexts.length > 0) {
  820. // 修改nextsData pid, 排序
  821. this.initSqlBuilder();
  822. this.sqlBuilder.setUpdateData(this.setting.pid, {
  823. value: select[this.setting.kid],
  824. });
  825. const orderInc = lastChild ? lastChild[this.setting.order] - select[this.setting.order] : - select[this.setting.order];
  826. this.sqlBuilder.setUpdateData(this.setting.order, {
  827. value: Math.abs(orderInc),
  828. selfOperate: orderInc > 0 ? '+' : '-',
  829. });
  830. this.sqlBuilder.setAndWhere(this.setting.mid, {
  831. value: select[this.setting.mid],
  832. operate: '=',
  833. });
  834. this.sqlBuilder.setAndWhere(this.setting.pid, {
  835. value: select[this.setting.pid],
  836. operate: '=',
  837. });
  838. this.sqlBuilder.setAndWhere(this.setting.order, {
  839. value: select[this.setting.order],
  840. operate: '>',
  841. });
  842. const [sql1, sqlParam1] = this.sqlBuilder.build(this.tableName, 'update');
  843. await this.transaction.query(sql1, sqlParam1);
  844. // 选中节点 is_leaf应为false
  845. if (select.is_leaf) {
  846. const updateData = { id: select.id, is_leaf: false };
  847. await this.transaction.update(this.tableName, updateData);
  848. }
  849. // 修改nextsData及其子节点的full_path
  850. const oldSubStr = this.db.escape(select[this.setting.pid] + '-');
  851. const newSubStr = this.db.escape(select[this.setting.kid] + '-');
  852. const sqlArr = [];
  853. sqlArr.push('Update ?? SET `full_path` = Replace(`full_path`,' + oldSubStr + ',' + newSubStr + ') Where');
  854. sqlArr.push('(`' + this.setting.mid + '` = ' + select[this.setting.mid] + ')');
  855. sqlArr.push(' And (');
  856. for (const data of nexts) {
  857. sqlArr.push('`' + this.setting.fullPath + '` Like ' + this.db.escape(data[this.setting.fullPath] + '%'));
  858. if (nexts.indexOf(data) < nexts.length - 1) {
  859. sqlArr.push(' Or ');
  860. }
  861. }
  862. sqlArr.push(')');
  863. const sql = sqlArr.join('');
  864. const resultData = await this.transaction.query(sql, [this.tableName]);
  865. // 存在下节点,则把此变更清单删除
  866. await this._deleteChangeAuditListData(select[this.setting.mid], [select]);
  867. return resultData;
  868. }
  869. }
  870. /**
  871. * 升级节点
  872. *
  873. * @param {Number} tenderId - 标段id
  874. * @param {Number} selectId - 选中节点id
  875. * @return {Array} - 发生改变的数据
  876. */
  877. async upLevelNode(mid, kid, count) {
  878. if (!count) count = 1;
  879. this.newBills = false;
  880. const selects = await this.getDataByKidAndCount(mid, kid, count);
  881. // const newBills = this.newBills;
  882. if (selects.length !== count) throw '升级节点数据错误';
  883. const first = selects[0], last = selects[count - 1];
  884. const parent = await this.getDataByKid(mid, first[this.setting.pid]);
  885. if (!parent) throw '升级节点数据错误';
  886. const newPath = [];
  887. this.transaction = await this.db.beginTransaction();
  888. try {
  889. // 选中节点--父节点 选中节点为firstChild时,修改is_leaf
  890. if (first[this.setting.order] === 1) {
  891. await this.transaction.update(this.tableName, {
  892. id: parent.id,
  893. is_leaf: true,
  894. });
  895. // throw '不能升级为最高级节点';
  896. }
  897. // 选中节点--父节点--全部后兄弟节点 order+1
  898. await this._updateChildrenOrder(this.tableName, mid, parent[this.setting.pid], parent[this.setting.order] + 1, count);
  899. if (!this.newBills) {
  900. await this._updateChildrenOrder(this.ctx.service.ledger.tableName, mid, parent[this.setting.pid], parent[this.setting.order] + 1, count);
  901. }
  902. for (const [i, s] of selects.entries()) {
  903. // 选中节点 修改pid, order, full_path, level, is_leaf, 清空计算项
  904. const updateData = { id: s.id };
  905. updateData[this.setting.pid] = parent[this.setting.pid];
  906. updateData[this.setting.order] = parent[this.setting.order] + i + 1;
  907. updateData[this.setting.level] = s[this.setting.level] - 1;
  908. updateData[this.setting.fullPath] = s[this.setting.fullPath].replace(s[this.setting.pid] + '-', '');
  909. newPath.push(updateData[this.setting.fullPath]);
  910. if (s.id === last.id) {
  911. const nexts = await this.getNextsData(this.tableName, mid, parent[this.setting.kid], last[this.setting.order]);
  912. if (!this.newBills) {
  913. const ledgerNexts = await this.getNextsData(this.ctx.service.ledger.tableName, mid, parent[this.setting.kid], last[this.setting.order]);
  914. if (ledgerNexts.length > 0) {
  915. throw '该节点下存在台账节点,不可升级';
  916. }
  917. // nexts = this._.orderBy(this._.concat(ledgerNexts, nexts), [this.setting.order], ['asc']);
  918. }
  919. if (s.is_leaf && nexts.length > 0) {
  920. updateData.is_leaf = false;
  921. this.clearParentingData(updateData);
  922. }
  923. }
  924. await this.transaction.update(this.tableName, updateData);
  925. // 选中节点--全部子节点(含孙) level-1, full_path变更
  926. await this._syncUplevelChildren(s);
  927. }
  928. // 选中节点--全部后兄弟节点 收编为子节点 修改pid, order, full_path
  929. await this._syncUpLevelNexts(last);
  930. await this.transaction.commit();
  931. this.transaction = null;
  932. } catch (err) {
  933. await this.transaction.rollback();
  934. this.transaction = null;
  935. throw err;
  936. }
  937. // 查询修改的数据
  938. let updateData = await this.getNextsData(this.tableName, mid, parent[this.setting.pid], parent[this.setting.order] - 1);
  939. if (!this.newBills) {
  940. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, mid, parent[this.setting.pid], parent[this.setting.order] - 1);
  941. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  942. }
  943. for (const path of newPath) {
  944. const children = await this.getDataByFullPath(this.tableName, mid, path + '-%');
  945. updateData = updateData.concat(children);
  946. if (!this.newBills) {
  947. updateData = updateData.concat(await this.getDataByFullPath(this.ctx.service.ledger.tableName, mid, path + '-%'));
  948. }
  949. }
  950. return { update: updateData };
  951. }
  952. /**
  953. * 降级selectData, 同步修改所有子节点
  954. * @param {Object} selectData - 选中节点
  955. * @param {Object} preData - 选中节点的前一节点(降级后为父节点)
  956. * @return {Promise<*>}
  957. * @private
  958. */
  959. async _syncDownlevelChildren(select, pre) {
  960. this.initSqlBuilder();
  961. this.sqlBuilder.setAndWhere(this.setting.mid, {
  962. value: select[this.setting.mid],
  963. operate: '=',
  964. });
  965. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  966. value: this.db.escape(select[this.setting.fullPath] + '-%'),
  967. operate: 'like',
  968. });
  969. this.sqlBuilder.setUpdateData(this.setting.level, {
  970. value: 1,
  971. selfOperate: '+',
  972. });
  973. this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  974. value: [this.setting.fullPath, this.db.escape(select[this.setting.kid] + '-'), this.db.escape(pre[this.setting.kid] + '-' + select[this.setting.kid] + '-')],
  975. literal: 'Replace',
  976. });
  977. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  978. const data = await this.transaction.query(sql, sqlParam);
  979. return data;
  980. }
  981. async getDataByFullPath(tableName, mid, full_path, transaction = null) {
  982. this.initSqlBuilder();
  983. this.sqlBuilder.setAndWhere(this.setting.mid, {
  984. value: mid,
  985. operate: '=',
  986. });
  987. this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  988. value: this.db.escape(full_path),
  989. operate: 'Like',
  990. });
  991. const [sql, sqlParam] = this.sqlBuilder.build(tableName);
  992. const resultData = transaction ? await transaction.query(sql, sqlParam) : await this.db.query(sql, sqlParam);
  993. return resultData;
  994. }
  995. /**
  996. * 获取最末的子节点
  997. * @param {Number} mid - masterId
  998. * @param {Number} pid - 父节点id
  999. * @return {Object}
  1000. */
  1001. async getLastChildDataFormCR(mid, pid) {
  1002. let preLastChild = await this.getLastChildData(this.tableName, mid, pid);
  1003. if (!this.newBills) {
  1004. const preLedgerLastChild = await this.getLastChildData(this.ctx.service.ledger.tableName, mid, pid);
  1005. if (!preLastChild) {
  1006. preLastChild = preLedgerLastChild;
  1007. } else {
  1008. preLastChild = preLedgerLastChild && preLedgerLastChild[this.setting.order] > preLastChild[this.setting.order] ? preLedgerLastChild : preLastChild;
  1009. }
  1010. }
  1011. return preLastChild;
  1012. }
  1013. async getLastChildData(tableName, mid, pid) {
  1014. this.initSqlBuilder();
  1015. this.sqlBuilder.setAndWhere(this.setting.mid, {
  1016. value: mid,
  1017. operate: '=',
  1018. });
  1019. this.sqlBuilder.setAndWhere(this.setting.pid, {
  1020. value: pid,
  1021. operate: '=',
  1022. });
  1023. this.sqlBuilder.orderBy = [['order', 'DESC']];
  1024. const [sql, sqlParam] = this.sqlBuilder.build(tableName);
  1025. const resultData = await this.db.queryOne(sql, sqlParam);
  1026. return resultData;
  1027. }
  1028. /**
  1029. * 降级节点
  1030. *
  1031. * @param {Number} tenderId - 标段id
  1032. * @param {Number} selectId - 选中节点id
  1033. * @return {Array} - 发生改变的数据
  1034. */
  1035. async downLevelNode(mid, kid, count) {
  1036. if (!count) count = 1;
  1037. this.newBills = false;
  1038. const selects = await this.getDataByKidAndCount(mid, kid, count);
  1039. if (!selects) throw '降级节点数据错误';
  1040. const first = selects[0], last = selects[count - 1];
  1041. const pre = await this.getDataByParentAndOrder(mid, first[this.setting.pid], first[this.setting.order] - 1);
  1042. if (!pre) throw '节点不可降级';
  1043. const preLastChild = await this.getLastChildDataFormCR(mid, pre[this.setting.kid]);
  1044. const newPath = [];
  1045. this.transaction = await this.db.beginTransaction();
  1046. try {
  1047. // 选中节点--全部后节点 order--
  1048. await this._updateChildrenOrder(this.tableName, mid, first[this.setting.pid], last[this.setting.order] + 1, -count);
  1049. if (!this.newBills) {
  1050. await this._updateChildrenOrder(this.ctx.service.ledger.tableName, mid, first[this.setting.pid], last[this.setting.order] + 1, -count);
  1051. }
  1052. for (const [i, s] of selects.entries()) {
  1053. // 选中节点 修改pid, level, order, full_path
  1054. const updateData = { id: s.id };
  1055. updateData[this.setting.pid] = pre[this.setting.kid];
  1056. updateData[this.setting.order] = preLastChild ? preLastChild[this.setting.order] + i + 1 : i + 1;
  1057. updateData[this.setting.level] = s[this.setting.level] + 1;
  1058. const orgLastPath = s[this.setting.level] === 1 ? s[this.setting.kid] : '-' + s[this.setting.kid];
  1059. const newLastPath = s[this.setting.level] === 1 ? pre[this.setting.kid] + '-' + s[this.setting.kid] : '-' + pre[this.setting.kid] + '-' + s[this.setting.kid];
  1060. updateData[this.setting.fullPath] = s[this.setting.fullPath].replace(orgLastPath, newLastPath);
  1061. newPath.push(updateData[this.setting.fullPath]);
  1062. // console.log(updateData);
  1063. await this.transaction.update(this.tableName, updateData);
  1064. // 选中节点--全部子节点(含孙) level++, full_path
  1065. await this._syncDownlevelChildren(s, pre);
  1066. }
  1067. // 选中节点--前兄弟节点 is_leaf应为false, 清空计算相关字段
  1068. if (pre.ccid) {
  1069. const updateData2 = { id: pre.id };
  1070. updateData2[this.setting.isLeaf] = false;
  1071. this.clearParentingData(updateData2);
  1072. await this.transaction.update(this.tableName, updateData2);
  1073. await this._deleteChangeAuditListData(mid, [pre]);
  1074. } else if (!pre.ccid && pre.is_leaf === 1) {
  1075. throw '原台账节点为子项时不能降级成为它的子项';
  1076. }
  1077. await this.transaction.commit();
  1078. this.transaction = null;
  1079. } catch (err) {
  1080. await this.transaction.rollback();
  1081. this.transaction = null;
  1082. throw err;
  1083. }
  1084. // 查询修改的数据
  1085. let updateData = await this.getNextsData(this.tableName, mid, pre[this.setting.pid], pre[this.setting.order] - 1);
  1086. if (!this.newBills) {
  1087. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, mid, pre[this.setting.pid], pre[this.setting.order] - 1);
  1088. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  1089. }
  1090. // 选中节点及子节点
  1091. for (const p of newPath) {
  1092. updateData = updateData.concat(await this.getDataByFullPath(this.tableName, mid, p + '%'));
  1093. if (!this.newBills) {
  1094. updateData = updateData.concat(await this.getDataByFullPath(this.ctx.service.ledger.tableName, mid, p + '%'));
  1095. }
  1096. }
  1097. // 选中节点--原前兄弟节点&全部后兄弟节点
  1098. return { update: updateData };
  1099. }
  1100. async pasteBlockData (tid, sid, pasteData, defaultData) {
  1101. if ((tid <= 0) || (sid <= 0)) return [];
  1102. if (!pasteData || pasteData.length <= 0) throw '复制数据错误';
  1103. for (const pd of pasteData) {
  1104. if (!pd || pd.length <= 0) throw '复制数据错误';
  1105. pd.sort(function (x, y) {
  1106. return x.level - y.level
  1107. });
  1108. if (pd[0].ledger_pid !== pasteData[0][0].ledger_pid) throw '复制数据错误:仅可操作同层节点';
  1109. }
  1110. const selectData = await this.getDataByKid(tid, sid);
  1111. if (!selectData) throw '粘贴数据错误';
  1112. const newParentPath = selectData.full_path.replace(selectData.ledger_id, '');
  1113. const pasteBillsData = [], pastePosData = [], leafBillsId = [];
  1114. const tpDecimal = this.ctx.tender.info.decimal.tp;
  1115. let maxId = await this._getMaxLid(this.ctx.tender.id);
  1116. for (const [i, pd] of pasteData.entries()) {
  1117. for (const d of pd) {
  1118. d.children = pd.filter(function (x) {
  1119. return x.ledger_pid === d.ledger_id;
  1120. });
  1121. }
  1122. const pbd = [];
  1123. for (const [j, d] of pd.entries()) {
  1124. const newBills = {
  1125. id: this.uuid.v4(),
  1126. tender_id: tid,
  1127. ledger_id: maxId + j + 1,
  1128. ledger_pid: j === 0 ? selectData.ledger_pid : d.ledger_pid,
  1129. level: d.level + selectData.level - pd[0].level,
  1130. order: j === 0 ? selectData.order + i + 1 : d.order,
  1131. is_leaf: d.is_leaf,
  1132. code: d.code,
  1133. b_code: d.b_code,
  1134. name: d.name,
  1135. unit: d.unit,
  1136. unit_price: this.ctx.helper.round(d.unit_price, this.ctx.tender.info.decimal.up),
  1137. source: d.source,
  1138. remark: d.remark,
  1139. drawing_code: d.drawing_code,
  1140. memo: d.memo,
  1141. ex_memo1: d.ex_memo1,
  1142. ex_memo2: d.ex_memo2,
  1143. ex_memo3: d.ex_memo3,
  1144. node_type: d.node_type,
  1145. sgfh_expr: d.sgfh_expr,
  1146. sjcl_expr: d.sjcl_expr,
  1147. qtcl_expr: d.qtcl_expr,
  1148. check_calc: 1,
  1149. ccid: this.ctx.change.cid,
  1150. formc: 1,
  1151. features: d.features,
  1152. };
  1153. for (const c of d.children) {
  1154. c.ledger_pid = newBills.ledger_id;
  1155. }
  1156. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, newBills.unit);
  1157. newBills.deal_qty = this.ctx.helper.round(d.deal_qty, precision.value);
  1158. if (d.pos && d.pos.length > 0) {
  1159. for (const pos of d.pos) {
  1160. const newPos = {
  1161. id: this.uuid.v4(),
  1162. tid: tid,
  1163. lid: newBills.id,
  1164. name: pos.name,
  1165. drawing_code: pos.drawing_code,
  1166. add_user: this.ctx.session.sessionUser.accountId,
  1167. in_time: new Date(),
  1168. porder: pos.porder,
  1169. position: pos.position,
  1170. sgfh_expr: pos.sgfh_expr ? pos.sgfh_expr : '',
  1171. sjcl_expr: pos.sjcl_expr ? pos.sjcl_expr : '',
  1172. qtcl_expr: pos.qtcl_expr ? pos.qtcl_expr : '',
  1173. add_stage: 0,
  1174. add_stage_order: 0,
  1175. add_times: 0,
  1176. ex_memo1: pos.ex_memo1,
  1177. ex_memo2: pos.ex_memo2,
  1178. ex_memo3: pos.ex_memo3,
  1179. ccid: this.ctx.change.cid,
  1180. formc: 1,
  1181. };
  1182. this._calcExpr(newPos, 'sgfh_qty', pos.sgfh_expr, pos.sgfh_qty, precision);
  1183. this._calcExpr(newPos, 'sjcl_qty', pos.sjcl_expr, pos.sjcl_qty, precision);
  1184. this._calcExpr(newPos, 'qtcl_qty', pos.qtcl_expr, pos.qtcl_qty, precision);
  1185. newPos.quantity = this.ctx.helper.add(newPos.sgfh_qty,
  1186. this.ctx.helper.add(newPos.sjcl_qty, newPos.qtcl_qty));
  1187. newBills.sgfh_qty = this.ctx.helper.add(newBills.sgfh_qty, newPos.sgfh_qty);
  1188. newBills.sjcl_qty = this.ctx.helper.add(newBills.sjcl_qty, newPos.sjcl_qty);
  1189. newBills.qtcl_qty = this.ctx.helper.add(newBills.qtcl_qty, newPos.qtcl_qty);
  1190. if (defaultData) this.ctx.helper._.assignIn(newPos, defaultData);
  1191. pastePosData.push(newPos);
  1192. }
  1193. } else {
  1194. this._calcExpr(newBills, 'sgfh_qty', newBills.sgfh_expr, d.sgfh_qty, precision);
  1195. this._calcExpr(newBills, 'sjcl_qty', newBills.sjcl_expr, d.sjcl_qty, precision);
  1196. this._calcExpr(newBills, 'qtcl_qty', newBills.qtcl_expr, d.qtcl_qty, precision);
  1197. }
  1198. newBills.quantity = this.ctx.helper.add(newBills.sgfh_qty,
  1199. this.ctx.helper.add(newBills.sjcl_qty, newBills.qtcl_qty));
  1200. newBills.sgfh_tp = this.ctx.helper.mul(newBills.sgfh_qty, newBills.unit_price, tpDecimal);
  1201. newBills.sjcl_tp = this.ctx.helper.mul(newBills.qtcl_qty, newBills.unit_price, tpDecimal);
  1202. newBills.qtcl_tp = this.ctx.helper.mul(newBills.sjcl_qty, newBills.unit_price, tpDecimal);
  1203. newBills.total_price = this.ctx.helper.mul(newBills.quantity, newBills.unit_price, tpDecimal);
  1204. newBills.deal_tp = this.ctx.helper.mul(newBills.deal_qty, newBills.unit_price, tpDecimal);
  1205. if (defaultData) this.ctx.helper._.assignIn(newBills, defaultData);
  1206. pbd.push(newBills);
  1207. }
  1208. for (const d of pbd) {
  1209. const parent = pbd.find(function (x) {
  1210. return x.ledger_id === d.ledger_pid;
  1211. });
  1212. d.full_path = parent
  1213. ? parent.full_path + '-' + d.ledger_id
  1214. : newParentPath + d.ledger_id;
  1215. if (defaultData) this.ctx.helper._.assignIn(pbd, defaultData);
  1216. pasteBillsData.push(d);
  1217. }
  1218. maxId = maxId + pbd.length;
  1219. }
  1220. this.transaction = await this.db.beginTransaction();
  1221. try {
  1222. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  1223. await this._updateChildrenOrder(this.tableName, tid, selectData.ledger_pid, selectData.order + 1, pasteData.length);
  1224. if (!this.newBills) {
  1225. await this._updateChildrenOrder(this.ctx.service.ledger.tableName, tid, selectData.ledger_pid, selectData.order + 1, pasteData.length);
  1226. }
  1227. // 数据库创建新增节点数据
  1228. if (pasteBillsData.length > 0) {
  1229. const newData = await this.transaction.insert(this.tableName, pasteBillsData);
  1230. }
  1231. this._cacheMaxLid(tid, maxId);
  1232. if (pastePosData.length > 0) {
  1233. await this.transaction.insert(this.ctx.service.changePos.tableName, pastePosData);
  1234. }
  1235. await this.transaction.commit();
  1236. } catch (err) {
  1237. await this.transaction.rollback();
  1238. throw err;
  1239. }
  1240. // 查询应返回的结果
  1241. let updateData = await this.getNextsData(this.tableName, selectData.tender_id, selectData.ledger_pid, selectData.order + pasteData.length);
  1242. if (!this.newBills) {
  1243. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, selectData.tender_id, selectData.ledger_pid, selectData.order + pasteData.length);
  1244. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  1245. }
  1246. return {
  1247. ledger: { create: pasteBillsData, update: updateData },
  1248. pos: pastePosData,
  1249. };
  1250. }
  1251. /**
  1252. * 添加标准节点,将选择的标准节点,添加为子节点(排序为末尾)
  1253. * @param {Number} tenderId - 标段Id
  1254. * @param {Number} selectId - 添加目标节点Id
  1255. * @param {Object} stdData - 标准节点数据
  1256. * @returns {Promise<*>}
  1257. */
  1258. async addStdNodeAsChild(tenderId, selectId, stdData, changeId) {
  1259. const newData = this._filterStdData(stdData);
  1260. const result = await this.addChild(tenderId, selectId, newData, changeId);
  1261. return result;
  1262. }
  1263. /**
  1264. * 新增子节点,并排在所有子节点的末尾
  1265. * @param {Number} tenderId - 标段Id
  1266. * @param {Number} selectId - 父节点Id
  1267. * @param {Object} data - 新增节点数据(编号名称等)
  1268. * @returns {Promise<*>}
  1269. */
  1270. async addChild(tenderId, selectId, data, changeId) {
  1271. if ((tenderId <= 0) || (selectId <= 0)) {
  1272. return [];
  1273. }
  1274. this.newBills = false;
  1275. const selectData = await this.getDataByKid(tenderId, selectId);
  1276. if (!selectData) {
  1277. throw '新增节点数据错误';
  1278. }
  1279. let children = await this.getChildrenByParentId(this.tableName, tenderId, selectId);
  1280. if (!this.newBills) {
  1281. const ledgerChildren = await this.getChildrenByParentId(this.ctx.service.ledger.tableName, tenderId, selectId);
  1282. children = this._.orderBy(this._.concat(ledgerChildren, children), [this.setting.order], ['asc']);
  1283. }
  1284. const maxId = await this._getMaxLid(tenderId);
  1285. data.id = this.uuid.v4();
  1286. data.tender_id = tenderId;
  1287. data.ledger_id = maxId + 1;
  1288. data.ledger_pid = selectData.ledger_id;
  1289. data.level = selectData.level + 1;
  1290. data.order = children.length + 1;
  1291. data.full_path = selectData.full_path + '-' + data.ledger_id;
  1292. data.is_leaf = true;
  1293. data.ccid = changeId;
  1294. data.check_calc = 1;
  1295. // if (reviseId) data.crid = reviseId;
  1296. this.transaction = await this.db.beginTransaction();
  1297. try {
  1298. const result = await this.transaction.insert(this.tableName, data);
  1299. if (children.length === 0 && selectData.ccid) {
  1300. await this.transaction.update(this.tableName,
  1301. {
  1302. is_leaf: false,
  1303. sgfh_qty: null, sgfh_tp: null, qtcl_qty: null, qtcl_tp: null, sjcl_qty: null, sjcl_tp: null,
  1304. quantity: null, unit_price: null, total_price: null, deal_qty: null, deal_tp: null
  1305. },
  1306. { where: {tender_id: tenderId, ledger_id: selectData.ledger_id} });
  1307. } else if (!selectData.ccid && children.length === 0) {
  1308. throw '原台账节点为子项时不能添加它的子项';
  1309. }
  1310. await this.transaction.commit();
  1311. } catch (err) {
  1312. this.transaction.rollback();
  1313. throw err;
  1314. }
  1315. this._cacheMaxLid(tenderId, maxId + 1);
  1316. // 查询应返回的结果
  1317. const resultData = {};
  1318. resultData.create = await this.getDataByKid(tenderId, data.ledger_id);
  1319. if (children.length === 0) {
  1320. resultData.update = await this.getDataByKid(tenderId, selectId);
  1321. }
  1322. return resultData;
  1323. }
  1324. /**
  1325. * 根据 父节点id 获取子节点
  1326. * @param tenderId
  1327. * @param nodeId
  1328. * @return {Promise<*>}
  1329. */
  1330. async getChildrenByParentId(tableName, tenderId, nodeId) {
  1331. if (tenderId <= 0 || !nodeId) {
  1332. return undefined;
  1333. }
  1334. const nodeIds = nodeId instanceof Array ? nodeId : [nodeId];
  1335. if (nodeIds.length === 0) {
  1336. return [];
  1337. }
  1338. this.initSqlBuilder();
  1339. this.sqlBuilder.setAndWhere('tender_id', {
  1340. value: tenderId,
  1341. operate: '=',
  1342. });
  1343. this.sqlBuilder.setAndWhere('ledger_pid', {
  1344. value: nodeIds,
  1345. operate: 'in',
  1346. });
  1347. this.sqlBuilder.orderBy = [['order', 'ASC']];
  1348. const [sql, sqlParam] = this.sqlBuilder.build(tableName);
  1349. const data = await this.db.query(sql, sqlParam);
  1350. return data;
  1351. }
  1352. /**
  1353. * 添加节点(来自标准清单)
  1354. * @param {Number} tenderId
  1355. * @param {Number} selectId
  1356. * @param {Object} stdData
  1357. * @return {Promise<*>}
  1358. */
  1359. async addStdNode(tenderId, selectId, stdData, changeId) {
  1360. const newData = this._filterStdData(stdData);
  1361. const result = await this.addBillsNode(tenderId, selectId, newData, changeId);
  1362. return result;
  1363. }
  1364. async addBillsNode(tenderId, selectId, data, changeId) {
  1365. if (data) {
  1366. if (changeId) data.ccid = changeId;
  1367. data.check_calc = 1;
  1368. return await this.addNode(tenderId, selectId, data);
  1369. } else {
  1370. return await this.addNode(tenderId, selectId, {ccid: changeId, check_calc: 1});
  1371. }
  1372. }
  1373. /**
  1374. * 添加节点,并同步添加父节点
  1375. * @param {Number} tenderId - 标段id
  1376. * @param {Number} selectId - 选中节点id
  1377. * @param {Object} stdData - 节点数据
  1378. * @param {StandardLib} stdLib - 标准库
  1379. * @return {Promise<void>}
  1380. */
  1381. async addStdNodeWithParent(tenderId, stdData, stdLib, changeId) {
  1382. // 查询完整标准清单,并按层次排序
  1383. const fullLevel = await stdLib.getFullLevelDataByFullPath(stdData.list_id, stdData.full_path);
  1384. fullLevel.sort(function(x, y) {
  1385. return x.level - y.level;
  1386. });
  1387. let isNew = false,
  1388. node,
  1389. firstNew,
  1390. updateParent,
  1391. addResult;
  1392. const expandIds = [];
  1393. this.transaction = await this.db.beginTransaction();
  1394. try {
  1395. // 从最顶层节点依次查询是否存在,否则添加
  1396. for (let i = 0, len = fullLevel.length; i < len; i++) {
  1397. const stdNode = fullLevel[i];
  1398. if (isNew) {
  1399. const newData = this._filterStdData(stdNode);
  1400. newData.is_leaf = (i === len - 1);
  1401. [addResult, node] = await this._addChildNodeData(tenderId, node, newData, changeId);
  1402. } else {
  1403. const parent = node;
  1404. node = await this.getDataByCondition({
  1405. tender_id: tenderId,
  1406. ledger_pid: parent ? parent.ledger_id : rootId,
  1407. code: stdNode.code,
  1408. name: stdNode.name,
  1409. }) || await this.ctx.service.ledger.getDataByCondition({tender_id: tenderId, ledger_pid: parent ? parent.ledger_id : rootId, code: stdNode.code, name: stdNode.name });
  1410. if (!node) {
  1411. let children = await this.getChildrenByParentId(this.tableName, tenderId, parent.ledger_id);
  1412. if (!this.newBills) {
  1413. const ledgerChildren = await this.getChildrenByParentId(this.ctx.service.ledger.tableName, tenderId, parent.ledger_id);
  1414. children = this._.orderBy(this._.concat(ledgerChildren, children), [this.setting.order], ['asc']);
  1415. }
  1416. if (children.length === 0 && !parent.ccid) {
  1417. throw '原台账节点为子项时不能添加它的子项';
  1418. }
  1419. isNew = true;
  1420. const newData = this._filterStdData(stdNode);
  1421. newData.is_leaf = (i === len - 1);
  1422. [addResult, node] = await this._addChildAutoOrder(tenderId, parent, newData, changeId);
  1423. if (parent && parent.is_leaf && this.newBills) {
  1424. await this.transaction.update(this.tableName, { id: parent.id, is_leaf: false,
  1425. unit_price: null, quantity: null, total_price: null, deal_qty: null, deal_tp: null});
  1426. updateParent = parent;
  1427. }
  1428. firstNew = node;
  1429. } else {
  1430. expandIds.push(node.ledger_id);
  1431. }
  1432. }
  1433. }
  1434. await this.transaction.commit();
  1435. } catch (err) {
  1436. await this.transaction.rollback();
  1437. throw err;
  1438. }
  1439. // 查询应返回的结果
  1440. let createData = [],
  1441. updateData = [];
  1442. if (firstNew) {
  1443. createData = await this.getDataByFullPath(this.tableName, tenderId, firstNew.full_path + '%');
  1444. updateData = await this.getNextsData(this.tableName, tenderId, firstNew.ledger_pid, firstNew.order);
  1445. if (!this.newBills) {
  1446. createData = createData.concat(await this.getDataByFullPath(this.ctx.service.ledger.tableName, tenderId, firstNew.full_path + '%'));
  1447. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, tenderId, firstNew.ledger_pid, firstNew.order);
  1448. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  1449. }
  1450. if (updateParent) {
  1451. updateData.push(await this.getDataByCondition({ id: updateParent.id }));
  1452. }
  1453. }
  1454. return { create: createData, update: updateData };
  1455. }
  1456. /**
  1457. * 根据parentData, data新增数据(新增为parentData的最后一个子项)
  1458. * @param {Number} tenderId - 标段id
  1459. * @param {Object} parentData - 父项数据
  1460. * @param {Object} data - 新增节点,初始数据
  1461. * @return {Promise<*>} - 新增结果
  1462. * @private
  1463. */
  1464. async _addChildNodeData(tenderId, parentData, data, changeId) {
  1465. if (tenderId <= 0) {
  1466. return undefined;
  1467. }
  1468. if (!data) {
  1469. data = {};
  1470. }
  1471. const pid = parentData ? parentData.ledger_id : rootId;
  1472. const maxId = await this._getMaxLid(tenderId);
  1473. data.id = this.uuid.v4();
  1474. data.tender_id = tenderId;
  1475. data.ledger_id = maxId + 1;
  1476. data.ledger_pid = pid;
  1477. if (data.order === undefined) {
  1478. data.order = 1;
  1479. }
  1480. data.level = parentData ? parentData.level + 1 : 1;
  1481. data.full_path = parentData ? parentData.full_path + '-' + data.ledger_id : '' + data.ledger_id;
  1482. if (data.is_leaf === undefined) {
  1483. data.is_leaf = true;
  1484. }
  1485. data.check_calc = 1;
  1486. if (changeId) data.ccid = changeId;
  1487. const result = await this.transaction.insert(this.tableName, data);
  1488. this._cacheMaxLid(tenderId, maxId + 1);
  1489. return [result, data];
  1490. }
  1491. /**
  1492. * 根据parentData, data新增数据(自动排序)
  1493. * @param tenderId
  1494. * @param parentData
  1495. * @param data
  1496. * @return {Promise<void>}
  1497. * @private
  1498. */
  1499. async _addChildAutoOrder(tenderId, parentData, data, changeId) {
  1500. const self = this;
  1501. const findPreData = function(list, a) {
  1502. if (!list || list.length === 0) { return null; }
  1503. for (let i = 0, iLen = list.length; i < iLen; i++) {
  1504. if (billsUtils.compareCode(list[i].code, a.code) > 0) {
  1505. return i > 0 ? list[i - 1] : null;
  1506. }
  1507. }
  1508. return list[list.length - 1];
  1509. };
  1510. const pid = parentData ? parentData.ledger_id : rootId;
  1511. let children = await this.getChildrenByParentId(this.tableName, tenderId, pid);
  1512. if (!this.newBills) {
  1513. const ledgerChildren = await this.getChildrenByParentId(this.ctx.service.ledger.tableName, tenderId, pid);
  1514. children = this._.orderBy(this._.concat(children, ledgerChildren), [this.setting.order], ['asc']);
  1515. }
  1516. const preData = findPreData(children, data);
  1517. if (!preData || children.indexOf(preData) < children.length - 1) {
  1518. await this._updateChildrenOrder(this.tableName, tenderId, pid, preData ? preData.order + 1 : 1);
  1519. if (!this.newBills) {
  1520. await this._updateChildrenOrder(this.ctx.service.ledger.tableName, tenderId, pid, preData ? preData.order + 1 : 1);
  1521. }
  1522. }
  1523. data.order = preData ? preData.order + 1 : 1;
  1524. const [addResult, node] = await this._addChildNodeData(tenderId, parentData, data, changeId);
  1525. return [addResult, node];
  1526. }
  1527. /**
  1528. * 提交数据 - 响应计算(增量方式计算)
  1529. * @param {Number} tenderId
  1530. * @param {Object} data
  1531. * @return {Promise<*>}
  1532. */
  1533. async updateCalc(tenderId, data) {
  1534. const helper = this.ctx.helper;
  1535. // 简单验证数据
  1536. if (tenderId <= 0 || !this.ctx.tender) {
  1537. throw '标段不存在';
  1538. }
  1539. const info = this.ctx.tender.info;
  1540. if (!data) {
  1541. throw '提交数据错误';
  1542. }
  1543. const datas = data instanceof Array ? data : [data];
  1544. const ids = [];
  1545. for (const row of datas) {
  1546. if (tenderId !== row.tender_id) {
  1547. throw '提交数据错误';
  1548. }
  1549. ids.push(row.id);
  1550. }
  1551. this.transaction = await this.db.beginTransaction();
  1552. try {
  1553. const updateDatas = [];
  1554. for (const row of datas) {
  1555. const updateNode = await this.getDataById(row.id);
  1556. if (!updateNode || tenderId !== updateNode.tender_id || row.ledger_id !== updateNode.ledger_id) {
  1557. throw '提交数据错误';
  1558. }
  1559. let updateData;
  1560. // 更新单位或单价,全部数据都应重算
  1561. if (row.unit !== undefined || row.unit_price !== undefined) {
  1562. if (row.sgfh_qty === undefined) { row.sgfh_qty = updateNode.sgfh_qty; }
  1563. if (row.sjcl_qty === undefined) { row.sjcl_qty = updateNode.sjcl_qty; }
  1564. if (row.qtcl_qty === undefined) { row.qtcl_qty = updateNode.qtcl_qty; }
  1565. if (row.deal_qty === undefined) { row.deal_qty = updateNode.deal_qty; }
  1566. }
  1567. // 项目节、工程量清单相关
  1568. if (row.b_code) {
  1569. row.dgn_qty1 = null;
  1570. row.dgn_qty2 = null;
  1571. row.code = null;
  1572. }
  1573. if (row.code) row.b_code = null;
  1574. if (this._checkCalcField(row)) {
  1575. const calcData = JSON.parse(JSON.stringify(row));
  1576. calcData.check_calc = 1;
  1577. const precision = helper.findPrecision(info.precision, row.unit ? row.unit : updateNode.unit);
  1578. // 数量保留小数位数
  1579. helper.checkFieldPrecision(calcData, qtyFields, precision.value);
  1580. // 单位保留小数位数
  1581. helper.checkFieldPrecision(calcData, upFields, info.decimal.up);
  1582. // 未提交单价则读取数据库单价
  1583. if (row.unit_price === undefined) calcData.unit_price = updateNode.unit_price;
  1584. // 计算
  1585. if (row.sgfh_qty !== undefined || row.sjcl_qty !== undefined || row.qtcl_qty !== undefined ||
  1586. row.deal_qty !== undefined || row.unit_price) {
  1587. if (row.sgfh_qty === undefined) calcData.sgfh_qty = updateNode.sgfh_qty;
  1588. if (row.sjcl_qty === undefined) calcData.sjcl_qty = updateNode.sjcl_qty;
  1589. if (row.qtcl_qty === undefined) calcData.qtcl_qty = updateNode.qtcl_qty;
  1590. if (row.deal_qty === undefined) calcData.deal_qty = updateNode.deal_qty;
  1591. calcData.quantity = helper.sum([calcData.sgfh_qty, calcData.sjcl_qty, calcData.qtcl_qty]);
  1592. calcData.sgfh_tp = helper.mul(calcData.sgfh_qty, calcData.unit_price, info.decimal.tp);
  1593. calcData.sjcl_tp = helper.mul(calcData.sjcl_qty, calcData.unit_price, info.decimal.tp);
  1594. calcData.qtcl_tp = helper.mul(calcData.qtcl_qty, calcData.unit_price, info.decimal.tp);
  1595. calcData.total_price = helper.mul(calcData.quantity, calcData.unit_price, info.decimal.tp);
  1596. calcData.deal_tp = helper.mul(calcData.deal_qty, calcData.unit_price, info.decimal.tp);
  1597. } else if (row.sgfh_tp !== undefined || row.sjcl_tp !== undefined || row.qtcl_tp !== undefined || row.deal_tp !== undefined) {
  1598. calcData.sgfh_qty = null;
  1599. calcData.sjcl_qty = null;
  1600. calcData.qtcl_qty = null;
  1601. calcData.quantity = null;
  1602. calcData.deal_qty = null;
  1603. calcData.sgfh_tp = helper.round(row.sgfh_tp !== undefined ? calcData.row.sgfh_tp : updateNode.sgfh_tp, info.decimal.tp);
  1604. calcData.sjcl_tp = helper.round(row.sgfh_tp !== undefined ? calcData.row.sjcl_tp : updateNode.sjcl_tp, info.decimal.tp);
  1605. calcData.qtcl_tp = helper.round(row.sgfh_tp !== undefined ? calcData.row.qtcl_tp : updateNode.qtcl_tp, info.decimal.tp);
  1606. calcData.total_price = helper.sum([calcData.sgfh_tp, calcData.sjcl_tp, calcData.qtcl_tp]);
  1607. calcData.deal_tp = helper.round(row.deal_tp !== undefined ? calcData.row.deal_tp : updateNode.deal_tp, info.decimal.tp);
  1608. } else if (row.unit_price !== undefined) {
  1609. calcData.sgfh_tp = helper.mul(calcData.sgfh_qty, calcData.unit_price, info.decimal.tp);
  1610. calcData.sjcl_tp = helper.mul(calcData.sjcl_qty, calcData.unit_price, info.decimal.tp);
  1611. calcData.qtcl_tp = helper.mul(calcData.qtcl_qty, calcData.unit_price, info.decimal.tp);
  1612. calcData.total_price = helper.mul(calcData.quantity, calcData.unit_price, info.decimal.tp);
  1613. calcData.deal_tp = helper.mul(calcData.deal_qty, calcData.unit_price, info.decimal.tp);
  1614. }
  1615. updateData = this._filterUpdateInvalidField(updateNode.id, calcData);
  1616. } else {
  1617. updateData = this._filterUpdateInvalidField(updateNode.id, row);
  1618. }
  1619. await this.transaction.update(this.tableName, updateData);
  1620. // 如非子节点,需要更新底下所有已选清单的分部分项等数据
  1621. updateDatas.push(updateData);
  1622. }
  1623. // console.log(updateDatas);
  1624. // 如果是子节点 更新了单位或单价,则更新数据并重算变更令总金额
  1625. await this.ctx.service.changeAuditList.updateDataByReviseLedger(this.transaction, tenderId, updateDatas);
  1626. await this.transaction.commit();
  1627. this.transaction = null;
  1628. } catch (err) {
  1629. await this.transaction.rollback();
  1630. this.transaction = null;
  1631. throw err;
  1632. }
  1633. return { update: await this.getDataById(ids) };
  1634. }
  1635. }
  1636. return ChangeLedger;
  1637. };