change_ledger.js 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733
  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. } else if (!pre.ccid && pre.is_leaf === 1) {
  1060. throw '原台账节点为子项时不能降级成为它的子项';
  1061. }
  1062. await this.transaction.commit();
  1063. this.transaction = null;
  1064. } catch (err) {
  1065. await this.transaction.rollback();
  1066. this.transaction = null;
  1067. throw err;
  1068. }
  1069. // 查询修改的数据
  1070. let updateData = await this.getNextsData(this.tableName, mid, pre[this.setting.pid], pre[this.setting.order] - 1);
  1071. if (!this.newBills) {
  1072. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, mid, pre[this.setting.pid], pre[this.setting.order] - 1);
  1073. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  1074. }
  1075. // 选中节点及子节点
  1076. for (const p of newPath) {
  1077. updateData = updateData.concat(await this.getDataByFullPath(this.tableName, mid, p + '%'));
  1078. if (!this.newBills) {
  1079. updateData = updateData.concat(await this.getDataByFullPath(this.ctx.service.ledger.tableName, mid, p + '%'));
  1080. }
  1081. }
  1082. // 选中节点--原前兄弟节点&全部后兄弟节点
  1083. return { update: updateData };
  1084. }
  1085. async pasteBlockData (tid, sid, pasteData, defaultData) {
  1086. if ((tid <= 0) || (sid <= 0)) return [];
  1087. if (!pasteData || pasteData.length <= 0) throw '复制数据错误';
  1088. for (const pd of pasteData) {
  1089. if (!pd || pd.length <= 0) throw '复制数据错误';
  1090. pd.sort(function (x, y) {
  1091. return x.level - y.level
  1092. });
  1093. if (pd[0].ledger_pid !== pasteData[0][0].ledger_pid) throw '复制数据错误:仅可操作同层节点';
  1094. }
  1095. const selectData = await this.getDataByKid(tid, sid);
  1096. if (!selectData) throw '粘贴数据错误';
  1097. const newParentPath = selectData.full_path.replace(selectData.ledger_id, '');
  1098. const pasteBillsData = [], pastePosData = [], leafBillsId = [];
  1099. const tpDecimal = this.ctx.tender.info.decimal.tp;
  1100. let maxId = await this._getMaxLid(this.ctx.tender.id);
  1101. for (const [i, pd] of pasteData.entries()) {
  1102. for (const d of pd) {
  1103. d.children = pd.filter(function (x) {
  1104. return x.ledger_pid === d.ledger_id;
  1105. });
  1106. }
  1107. const pbd = [];
  1108. for (const [j, d] of pd.entries()) {
  1109. const newBills = {
  1110. id: this.uuid.v4(),
  1111. tender_id: tid,
  1112. ledger_id: maxId + j + 1,
  1113. ledger_pid: j === 0 ? selectData.ledger_pid : d.ledger_pid,
  1114. level: d.level + selectData.level - pd[0].level,
  1115. order: j === 0 ? selectData.order + i + 1 : d.order,
  1116. is_leaf: d.is_leaf,
  1117. code: d.code,
  1118. b_code: d.b_code,
  1119. name: d.name,
  1120. unit: d.unit,
  1121. unit_price: this.ctx.helper.round(d.unit_price, this.ctx.tender.info.decimal.up),
  1122. source: d.source,
  1123. remark: d.remark,
  1124. drawing_code: d.drawing_code,
  1125. memo: d.memo,
  1126. ex_memo1: d.ex_memo1,
  1127. ex_memo2: d.ex_memo2,
  1128. ex_memo3: d.ex_memo3,
  1129. node_type: d.node_type,
  1130. sgfh_expr: d.sgfh_expr,
  1131. sjcl_expr: d.sjcl_expr,
  1132. qtcl_expr: d.qtcl_expr,
  1133. check_calc: 1,
  1134. ccid: this.ctx.change.cid,
  1135. formc: 1,
  1136. };
  1137. for (const c of d.children) {
  1138. c.ledger_pid = newBills.ledger_id;
  1139. }
  1140. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, newBills.unit);
  1141. newBills.deal_qty = this.ctx.helper.round(d.deal_qty, precision.value);
  1142. if (d.pos && d.pos.length > 0) {
  1143. for (const pos of d.pos) {
  1144. const newPos = {
  1145. id: this.uuid.v4(),
  1146. tid: tid,
  1147. lid: newBills.id,
  1148. name: pos.name,
  1149. drawing_code: pos.drawing_code,
  1150. add_user: this.ctx.session.sessionUser.accountId,
  1151. in_time: new Date(),
  1152. porder: pos.porder,
  1153. position: pos.position,
  1154. sgfh_expr: pos.sgfh_expr ? pos.sgfh_expr : '',
  1155. sjcl_expr: pos.sjcl_expr ? pos.sjcl_expr : '',
  1156. qtcl_expr: pos.qtcl_expr ? pos.qtcl_expr : '',
  1157. add_stage: 0,
  1158. add_stage_order: 0,
  1159. add_times: 0,
  1160. ex_memo1: pos.ex_memo1,
  1161. ex_memo2: pos.ex_memo2,
  1162. ex_memo3: pos.ex_memo3,
  1163. ccid: this.ctx.change.cid,
  1164. formc: 1,
  1165. };
  1166. this._calcExpr(newPos, 'sgfh_qty', pos.sgfh_expr, pos.sgfh_qty, precision);
  1167. this._calcExpr(newPos, 'sjcl_qty', pos.sjcl_expr, pos.sjcl_qty, precision);
  1168. this._calcExpr(newPos, 'qtcl_qty', pos.qtcl_expr, pos.qtcl_qty, precision);
  1169. newPos.quantity = this.ctx.helper.add(newPos.sgfh_qty,
  1170. this.ctx.helper.add(newPos.sjcl_qty, newPos.qtcl_qty));
  1171. newBills.sgfh_qty = this.ctx.helper.add(newBills.sgfh_qty, newPos.sgfh_qty);
  1172. newBills.sjcl_qty = this.ctx.helper.add(newBills.sjcl_qty, newPos.sjcl_qty);
  1173. newBills.qtcl_qty = this.ctx.helper.add(newBills.qtcl_qty, newPos.qtcl_qty);
  1174. if (defaultData) this.ctx.helper._.assignIn(newPos, defaultData);
  1175. pastePosData.push(newPos);
  1176. }
  1177. } else {
  1178. this._calcExpr(newBills, 'sgfh_qty', newBills.sgfh_expr, d.sgfh_qty, precision);
  1179. this._calcExpr(newBills, 'sjcl_qty', newBills.sjcl_expr, d.sjcl_qty, precision);
  1180. this._calcExpr(newBills, 'qtcl_qty', newBills.qtcl_expr, d.qtcl_qty, precision);
  1181. }
  1182. newBills.quantity = this.ctx.helper.add(newBills.sgfh_qty,
  1183. this.ctx.helper.add(newBills.sjcl_qty, newBills.qtcl_qty));
  1184. newBills.sgfh_tp = this.ctx.helper.mul(newBills.sgfh_qty, newBills.unit_price, tpDecimal);
  1185. newBills.sjcl_tp = this.ctx.helper.mul(newBills.qtcl_qty, newBills.unit_price, tpDecimal);
  1186. newBills.qtcl_tp = this.ctx.helper.mul(newBills.sjcl_qty, newBills.unit_price, tpDecimal);
  1187. newBills.total_price = this.ctx.helper.mul(newBills.quantity, newBills.unit_price, tpDecimal);
  1188. newBills.deal_tp = this.ctx.helper.mul(newBills.deal_qty, newBills.unit_price, tpDecimal);
  1189. if (defaultData) this.ctx.helper._.assignIn(newBills, defaultData);
  1190. pbd.push(newBills);
  1191. }
  1192. for (const d of pbd) {
  1193. const parent = pbd.find(function (x) {
  1194. return x.ledger_id === d.ledger_pid;
  1195. });
  1196. d.full_path = parent
  1197. ? parent.full_path + '-' + d.ledger_id
  1198. : newParentPath + d.ledger_id;
  1199. if (defaultData) this.ctx.helper._.assignIn(pbd, defaultData);
  1200. pasteBillsData.push(d);
  1201. }
  1202. maxId = maxId + pbd.length;
  1203. }
  1204. this.transaction = await this.db.beginTransaction();
  1205. try {
  1206. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  1207. await this._updateChildrenOrder(this.tableName, tid, selectData.ledger_pid, selectData.order + 1, pasteData.length);
  1208. if (!this.newBills) {
  1209. await this._updateChildrenOrder(this.ctx.service.ledger.tableName, tid, selectData.ledger_pid, selectData.order + 1, pasteData.length);
  1210. }
  1211. // 数据库创建新增节点数据
  1212. if (pasteBillsData.length > 0) {
  1213. const newData = await this.transaction.insert(this.tableName, pasteBillsData);
  1214. }
  1215. this._cacheMaxLid(tid, maxId);
  1216. if (pastePosData.length > 0) {
  1217. await this.transaction.insert(this.ctx.service.changePos.tableName, pastePosData);
  1218. }
  1219. await this.transaction.commit();
  1220. } catch (err) {
  1221. await this.transaction.rollback();
  1222. throw err;
  1223. }
  1224. // 查询应返回的结果
  1225. let updateData = await this.getNextsData(this.tableName, selectData.tender_id, selectData.ledger_pid, selectData.order + pasteData.length);
  1226. if (!this.newBills) {
  1227. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, selectData.tender_id, selectData.ledger_pid, selectData.order + pasteData.length);
  1228. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  1229. }
  1230. return {
  1231. ledger: { create: pasteBillsData, update: updateData },
  1232. pos: pastePosData,
  1233. };
  1234. }
  1235. /**
  1236. * 添加标准节点,将选择的标准节点,添加为子节点(排序为末尾)
  1237. * @param {Number} tenderId - 标段Id
  1238. * @param {Number} selectId - 添加目标节点Id
  1239. * @param {Object} stdData - 标准节点数据
  1240. * @returns {Promise<*>}
  1241. */
  1242. async addStdNodeAsChild(tenderId, selectId, stdData, changeId) {
  1243. const newData = this._filterStdData(stdData);
  1244. const result = await this.addChild(tenderId, selectId, newData, changeId);
  1245. return result;
  1246. }
  1247. /**
  1248. * 新增子节点,并排在所有子节点的末尾
  1249. * @param {Number} tenderId - 标段Id
  1250. * @param {Number} selectId - 父节点Id
  1251. * @param {Object} data - 新增节点数据(编号名称等)
  1252. * @returns {Promise<*>}
  1253. */
  1254. async addChild(tenderId, selectId, data, changeId) {
  1255. if ((tenderId <= 0) || (selectId <= 0)) {
  1256. return [];
  1257. }
  1258. this.newBills = false;
  1259. const selectData = await this.getDataByKid(tenderId, selectId);
  1260. if (!selectData) {
  1261. throw '新增节点数据错误';
  1262. }
  1263. let children = await this.getChildrenByParentId(this.tableName, tenderId, selectId);
  1264. if (!this.newBills) {
  1265. const ledgerChildren = await this.getChildrenByParentId(this.ctx.service.ledger.tableName, tenderId, selectId);
  1266. children = this._.orderBy(this._.concat(ledgerChildren, children), [this.setting.order], ['asc']);
  1267. }
  1268. const maxId = await this._getMaxLid(tenderId);
  1269. data.id = this.uuid.v4();
  1270. data.tender_id = tenderId;
  1271. data.ledger_id = maxId + 1;
  1272. data.ledger_pid = selectData.ledger_id;
  1273. data.level = selectData.level + 1;
  1274. data.order = children.length + 1;
  1275. data.full_path = selectData.full_path + '-' + data.ledger_id;
  1276. data.is_leaf = true;
  1277. data.ccid = changeId;
  1278. data.check_calc = 1;
  1279. // if (reviseId) data.crid = reviseId;
  1280. this.transaction = await this.db.beginTransaction();
  1281. try {
  1282. const result = await this.transaction.insert(this.tableName, data);
  1283. if (children.length === 0 && selectData.ccid) {
  1284. await this.transaction.update(this.tableName,
  1285. {
  1286. is_leaf: false,
  1287. sgfh_qty: null, sgfh_tp: null, qtcl_qty: null, qtcl_tp: null, sjcl_qty: null, sjcl_tp: null,
  1288. quantity: null, unit_price: null, total_price: null, deal_qty: null, deal_tp: null
  1289. },
  1290. { where: {tender_id: tenderId, ledger_id: selectData.ledger_id} });
  1291. } else if (!selectData.ccid && children.length === 0) {
  1292. throw '原台账节点为子项时不能添加它的子项';
  1293. }
  1294. await this.transaction.commit();
  1295. } catch (err) {
  1296. this.transaction.rollback();
  1297. throw err;
  1298. }
  1299. this._cacheMaxLid(tenderId, maxId + 1);
  1300. // 查询应返回的结果
  1301. const resultData = {};
  1302. resultData.create = await this.getDataByKid(tenderId, data.ledger_id);
  1303. if (children.length === 0) {
  1304. resultData.update = await this.getDataByKid(tenderId, selectId);
  1305. }
  1306. return resultData;
  1307. }
  1308. /**
  1309. * 根据 父节点id 获取子节点
  1310. * @param tenderId
  1311. * @param nodeId
  1312. * @return {Promise<*>}
  1313. */
  1314. async getChildrenByParentId(tableName, tenderId, nodeId) {
  1315. if (tenderId <= 0 || !nodeId) {
  1316. return undefined;
  1317. }
  1318. const nodeIds = nodeId instanceof Array ? nodeId : [nodeId];
  1319. if (nodeIds.length === 0) {
  1320. return [];
  1321. }
  1322. this.initSqlBuilder();
  1323. this.sqlBuilder.setAndWhere('tender_id', {
  1324. value: tenderId,
  1325. operate: '=',
  1326. });
  1327. this.sqlBuilder.setAndWhere('ledger_pid', {
  1328. value: nodeIds,
  1329. operate: 'in',
  1330. });
  1331. this.sqlBuilder.orderBy = [['order', 'ASC']];
  1332. const [sql, sqlParam] = this.sqlBuilder.build(tableName);
  1333. const data = await this.db.query(sql, sqlParam);
  1334. return data;
  1335. }
  1336. /**
  1337. * 添加节点(来自标准清单)
  1338. * @param {Number} tenderId
  1339. * @param {Number} selectId
  1340. * @param {Object} stdData
  1341. * @return {Promise<*>}
  1342. */
  1343. async addStdNode(tenderId, selectId, stdData, changeId) {
  1344. const newData = this._filterStdData(stdData);
  1345. const result = await this.addBillsNode(tenderId, selectId, newData, changeId);
  1346. return result;
  1347. }
  1348. async addBillsNode(tenderId, selectId, data, changeId) {
  1349. if (data) {
  1350. if (changeId) data.ccid = changeId;
  1351. data.check_calc = 1;
  1352. return await this.addNode(tenderId, selectId, data);
  1353. } else {
  1354. return await this.addNode(tenderId, selectId, {ccid: changeId, check_calc: 1});
  1355. }
  1356. }
  1357. /**
  1358. * 添加节点,并同步添加父节点
  1359. * @param {Number} tenderId - 标段id
  1360. * @param {Number} selectId - 选中节点id
  1361. * @param {Object} stdData - 节点数据
  1362. * @param {StandardLib} stdLib - 标准库
  1363. * @return {Promise<void>}
  1364. */
  1365. async addStdNodeWithParent(tenderId, stdData, stdLib, changeId) {
  1366. // 查询完整标准清单,并按层次排序
  1367. const fullLevel = await stdLib.getFullLevelDataByFullPath(stdData.list_id, stdData.full_path);
  1368. fullLevel.sort(function(x, y) {
  1369. return x.level - y.level;
  1370. });
  1371. let isNew = false,
  1372. node,
  1373. firstNew,
  1374. updateParent,
  1375. addResult;
  1376. const expandIds = [];
  1377. this.transaction = await this.db.beginTransaction();
  1378. try {
  1379. // 从最顶层节点依次查询是否存在,否则添加
  1380. for (let i = 0, len = fullLevel.length; i < len; i++) {
  1381. const stdNode = fullLevel[i];
  1382. if (isNew) {
  1383. const newData = this._filterStdData(stdNode);
  1384. newData.is_leaf = (i === len - 1);
  1385. [addResult, node] = await this._addChildNodeData(tenderId, node, newData, changeId);
  1386. } else {
  1387. const parent = node;
  1388. node = await this.getDataByCondition({
  1389. tender_id: tenderId,
  1390. ledger_pid: parent ? parent.ledger_id : rootId,
  1391. code: stdNode.code,
  1392. name: stdNode.name,
  1393. }) || await this.ctx.service.ledger.getDataByCondition({tender_id: tenderId, ledger_pid: parent ? parent.ledger_id : rootId, code: stdNode.code, name: stdNode.name });
  1394. if (!node) {
  1395. let children = await this.getChildrenByParentId(this.tableName, tenderId, parent.ledger_id);
  1396. if (!this.newBills) {
  1397. const ledgerChildren = await this.getChildrenByParentId(this.ctx.service.ledger.tableName, tenderId, parent.ledger_id);
  1398. children = this._.orderBy(this._.concat(ledgerChildren, children), [this.setting.order], ['asc']);
  1399. }
  1400. if (children.length === 0 && !parent.ccid) {
  1401. throw '原台账节点为子项时不能添加它的子项';
  1402. }
  1403. isNew = true;
  1404. const newData = this._filterStdData(stdNode);
  1405. newData.is_leaf = (i === len - 1);
  1406. [addResult, node] = await this._addChildAutoOrder(tenderId, parent, newData, changeId);
  1407. if (parent && parent.is_leaf && this.newBills) {
  1408. await this.transaction.update(this.tableName, { id: parent.id, is_leaf: false,
  1409. unit_price: null, quantity: null, total_price: null, deal_qty: null, deal_tp: null});
  1410. updateParent = parent;
  1411. }
  1412. firstNew = node;
  1413. } else {
  1414. expandIds.push(node.ledger_id);
  1415. }
  1416. }
  1417. }
  1418. await this.transaction.commit();
  1419. } catch (err) {
  1420. await this.transaction.rollback();
  1421. throw err;
  1422. }
  1423. // 查询应返回的结果
  1424. let createData = [],
  1425. updateData = [];
  1426. if (firstNew) {
  1427. createData = await this.getDataByFullPath(this.tableName, tenderId, firstNew.full_path + '%');
  1428. updateData = await this.getNextsData(this.tableName, tenderId, firstNew.ledger_pid, firstNew.order);
  1429. if (!this.newBills) {
  1430. createData = createData.concat(await this.getDataByFullPath(this.ctx.service.ledger.tableName, tenderId, firstNew.full_path + '%'));
  1431. const ledgerUpdateData = await this.getNextsData(this.ctx.service.ledger.tableName, tenderId, firstNew.ledger_pid, firstNew.order);
  1432. updateData = this._.orderBy(this._.concat(updateData, ledgerUpdateData), [this.setting.order], ['asc']);
  1433. }
  1434. if (updateParent) {
  1435. updateData.push(await this.getDataByCondition({ id: updateParent.id }));
  1436. }
  1437. }
  1438. return { create: createData, update: updateData };
  1439. }
  1440. /**
  1441. * 根据parentData, data新增数据(新增为parentData的最后一个子项)
  1442. * @param {Number} tenderId - 标段id
  1443. * @param {Object} parentData - 父项数据
  1444. * @param {Object} data - 新增节点,初始数据
  1445. * @return {Promise<*>} - 新增结果
  1446. * @private
  1447. */
  1448. async _addChildNodeData(tenderId, parentData, data, changeId) {
  1449. if (tenderId <= 0) {
  1450. return undefined;
  1451. }
  1452. if (!data) {
  1453. data = {};
  1454. }
  1455. const pid = parentData ? parentData.ledger_id : rootId;
  1456. const maxId = await this._getMaxLid(tenderId);
  1457. data.id = this.uuid.v4();
  1458. data.tender_id = tenderId;
  1459. data.ledger_id = maxId + 1;
  1460. data.ledger_pid = pid;
  1461. if (data.order === undefined) {
  1462. data.order = 1;
  1463. }
  1464. data.level = parentData ? parentData.level + 1 : 1;
  1465. data.full_path = parentData ? parentData.full_path + '-' + data.ledger_id : '' + data.ledger_id;
  1466. if (data.is_leaf === undefined) {
  1467. data.is_leaf = true;
  1468. }
  1469. data.check_calc = 1;
  1470. if (changeId) data.ccid = changeId;
  1471. const result = await this.transaction.insert(this.tableName, data);
  1472. this._cacheMaxLid(tenderId, maxId + 1);
  1473. return [result, data];
  1474. }
  1475. /**
  1476. * 根据parentData, data新增数据(自动排序)
  1477. * @param tenderId
  1478. * @param parentData
  1479. * @param data
  1480. * @return {Promise<void>}
  1481. * @private
  1482. */
  1483. async _addChildAutoOrder(tenderId, parentData, data, changeId) {
  1484. const self = this;
  1485. const findPreData = function(list, a) {
  1486. if (!list || list.length === 0) { return null; }
  1487. for (let i = 0, iLen = list.length; i < iLen; i++) {
  1488. if (billsUtils.compareCode(list[i].code, a.code) > 0) {
  1489. return i > 0 ? list[i - 1] : null;
  1490. }
  1491. }
  1492. return list[list.length - 1];
  1493. };
  1494. const pid = parentData ? parentData.ledger_id : rootId;
  1495. let children = await this.getChildrenByParentId(this.tableName, tenderId, pid);
  1496. if (!this.newBills) {
  1497. const ledgerChildren = await this.getChildrenByParentId(this.ctx.service.ledger.tableName, tenderId, pid);
  1498. children = this._.orderBy(this._.concat(children, ledgerChildren), [this.setting.order], ['asc']);
  1499. }
  1500. const preData = findPreData(children, data);
  1501. if (!preData || children.indexOf(preData) < children.length - 1) {
  1502. await this._updateChildrenOrder(this.tableName, tenderId, pid, preData ? preData.order + 1 : 1);
  1503. if (!this.newBills) {
  1504. await this._updateChildrenOrder(this.ctx.service.ledger.tableName, tenderId, pid, preData ? preData.order + 1 : 1);
  1505. }
  1506. }
  1507. data.order = preData ? preData.order + 1 : 1;
  1508. const [addResult, node] = await this._addChildNodeData(tenderId, parentData, data, changeId);
  1509. return [addResult, node];
  1510. }
  1511. /**
  1512. * 提交数据 - 响应计算(增量方式计算)
  1513. * @param {Number} tenderId
  1514. * @param {Object} data
  1515. * @return {Promise<*>}
  1516. */
  1517. async updateCalc(tenderId, data) {
  1518. const helper = this.ctx.helper;
  1519. // 简单验证数据
  1520. if (tenderId <= 0 || !this.ctx.tender) {
  1521. throw '标段不存在';
  1522. }
  1523. const info = this.ctx.tender.info;
  1524. if (!data) {
  1525. throw '提交数据错误';
  1526. }
  1527. const datas = data instanceof Array ? data : [data];
  1528. const ids = [];
  1529. for (const row of datas) {
  1530. if (tenderId !== row.tender_id) {
  1531. throw '提交数据错误';
  1532. }
  1533. ids.push(row.id);
  1534. }
  1535. this.transaction = await this.db.beginTransaction();
  1536. try {
  1537. const updateDatas = [];
  1538. for (const row of datas) {
  1539. const updateNode = await this.getDataById(row.id);
  1540. if (!updateNode || tenderId !== updateNode.tender_id || row.ledger_id !== updateNode.ledger_id) {
  1541. throw '提交数据错误';
  1542. }
  1543. let updateData;
  1544. // 更新单位或单价,全部数据都应重算
  1545. if (row.unit !== undefined || row.unit_price !== undefined) {
  1546. if (row.sgfh_qty === undefined) { row.sgfh_qty = updateNode.sgfh_qty; }
  1547. if (row.sjcl_qty === undefined) { row.sjcl_qty = updateNode.sjcl_qty; }
  1548. if (row.qtcl_qty === undefined) { row.qtcl_qty = updateNode.qtcl_qty; }
  1549. if (row.deal_qty === undefined) { row.deal_qty = updateNode.deal_qty; }
  1550. }
  1551. // 项目节、工程量清单相关
  1552. if (row.b_code) {
  1553. row.dgn_qty1 = null;
  1554. row.dgn_qty2 = null;
  1555. row.code = null;
  1556. }
  1557. if (row.code) row.b_code = null;
  1558. if (this._checkCalcField(row)) {
  1559. const calcData = JSON.parse(JSON.stringify(row));
  1560. calcData.check_calc = 1;
  1561. const precision = helper.findPrecision(info.precision, row.unit ? row.unit : updateNode.unit);
  1562. // 数量保留小数位数
  1563. helper.checkFieldPrecision(calcData, qtyFields, precision.value);
  1564. // 单位保留小数位数
  1565. helper.checkFieldPrecision(calcData, upFields, info.decimal.up);
  1566. // 未提交单价则读取数据库单价
  1567. if (row.unit_price === undefined) calcData.unit_price = updateNode.unit_price;
  1568. // 计算
  1569. if (row.sgfh_qty !== undefined || row.sjcl_qty !== undefined || row.qtcl_qty !== undefined ||
  1570. row.deal_qty !== undefined || row.unit_price) {
  1571. if (row.sgfh_qty === undefined) calcData.sgfh_qty = updateNode.sgfh_qty;
  1572. if (row.sjcl_qty === undefined) calcData.sjcl_qty = updateNode.sjcl_qty;
  1573. if (row.qtcl_qty === undefined) calcData.qtcl_qty = updateNode.qtcl_qty;
  1574. if (row.deal_qty === undefined) calcData.deal_qty = updateNode.deal_qty;
  1575. calcData.quantity = helper.sum([calcData.sgfh_qty, calcData.sjcl_qty, calcData.qtcl_qty]);
  1576. calcData.sgfh_tp = helper.mul(calcData.sgfh_qty, calcData.unit_price, info.decimal.tp);
  1577. calcData.sjcl_tp = helper.mul(calcData.sjcl_qty, calcData.unit_price, info.decimal.tp);
  1578. calcData.qtcl_tp = helper.mul(calcData.qtcl_qty, calcData.unit_price, info.decimal.tp);
  1579. calcData.total_price = helper.mul(calcData.quantity, calcData.unit_price, info.decimal.tp);
  1580. calcData.deal_tp = helper.mul(calcData.deal_qty, calcData.unit_price, info.decimal.tp);
  1581. } else if (row.sgfh_tp !== undefined || row.sjcl_tp !== undefined || row.qtcl_tp !== undefined || row.deal_tp !== undefined) {
  1582. calcData.sgfh_qty = null;
  1583. calcData.sjcl_qty = null;
  1584. calcData.qtcl_qty = null;
  1585. calcData.quantity = null;
  1586. calcData.deal_qty = null;
  1587. calcData.sgfh_tp = helper.round(row.sgfh_tp !== undefined ? calcData.row.sgfh_tp : updateNode.sgfh_tp, info.decimal.tp);
  1588. calcData.sjcl_tp = helper.round(row.sgfh_tp !== undefined ? calcData.row.sjcl_tp : updateNode.sjcl_tp, info.decimal.tp);
  1589. calcData.qtcl_tp = helper.round(row.sgfh_tp !== undefined ? calcData.row.qtcl_tp : updateNode.qtcl_tp, info.decimal.tp);
  1590. calcData.total_price = helper.sum([calcData.sgfh_tp, calcData.sjcl_tp, calcData.qtcl_tp]);
  1591. calcData.deal_tp = helper.round(row.deal_tp !== undefined ? calcData.row.deal_tp : updateNode.deal_tp, info.decimal.tp);
  1592. } else if (row.unit_price !== undefined) {
  1593. calcData.sgfh_tp = helper.mul(calcData.sgfh_qty, calcData.unit_price, info.decimal.tp);
  1594. calcData.sjcl_tp = helper.mul(calcData.sjcl_qty, calcData.unit_price, info.decimal.tp);
  1595. calcData.qtcl_tp = helper.mul(calcData.qtcl_qty, calcData.unit_price, info.decimal.tp);
  1596. calcData.total_price = helper.mul(calcData.quantity, calcData.unit_price, info.decimal.tp);
  1597. calcData.deal_tp = helper.mul(calcData.deal_qty, calcData.unit_price, info.decimal.tp);
  1598. }
  1599. updateData = this._filterUpdateInvalidField(updateNode.id, calcData);
  1600. } else {
  1601. updateData = this._filterUpdateInvalidField(updateNode.id, row);
  1602. }
  1603. await this.transaction.update(this.tableName, updateData);
  1604. // 如非子节点,需要更新底下所有已选清单的分部分项等数据
  1605. updateDatas.push(updateData);
  1606. }
  1607. // console.log(updateDatas);
  1608. // 如果是子节点 更新了单位或单价,则更新数据并重算变更令总金额
  1609. await this.ctx.service.changeAuditList.updateDataByReviseLedger(this.transaction, tenderId, updateDatas);
  1610. await this.transaction.commit();
  1611. this.transaction = null;
  1612. } catch (err) {
  1613. await this.transaction.rollback();
  1614. this.transaction = null;
  1615. throw err;
  1616. }
  1617. return { update: await this.getDataById(ids) };
  1618. }
  1619. }
  1620. return ChangeLedger;
  1621. };