change_ledger.js 80 KB

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