contract_tree.js 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. 'use strict';
  2. /**
  3. * Created by EllisRan on 2020/3/3.
  4. */
  5. const BaseService = require('../base/base_service');
  6. const contractConst = require('../const/contract');
  7. const rootId = -1;
  8. const billsUtils = require('../lib/bills_utils');
  9. module.exports = app => {
  10. class ContractTree extends app.BaseBillsService {
  11. /**
  12. * 构造函数
  13. *
  14. * @param {Object} ctx - egg全局变量
  15. * @return {void}
  16. */
  17. constructor(ctx) {
  18. const setting = {
  19. spid: 'spid',
  20. mid: 'tid',
  21. type: 'contract_type',
  22. kid: 'contract_id',
  23. pid: 'contract_pid',
  24. order: 'order',
  25. level: 'level',
  26. isLeaf: 'is_leaf',
  27. fullPath: 'full_path',
  28. keyPre: 'contract_maxLid:', // 换个名称,防止缓存导致旧数据出问题
  29. uuid: true,
  30. };
  31. super(ctx, setting, 'pos');
  32. this.setting = setting;
  33. this.depart = 0;
  34. this.tableName = 'contract_tree';
  35. }
  36. _getStringOptions(options) {
  37. const optionStr = [];
  38. for (const key in options) {
  39. if (options.hasOwnProperty(key)) {
  40. optionStr.push(options[key]);
  41. }
  42. }
  43. return optionStr.join('&&');
  44. }
  45. /**
  46. * 获取最大节点id
  47. *
  48. * @param {Number} mid - master id
  49. * @return {Number}
  50. * @private
  51. */
  52. async _getMaxLid(options) {
  53. const cacheKey = this.setting.keyPre + this._getStringOptions(options);
  54. let maxId = parseInt(await this.cache.get(cacheKey)) || 0;
  55. if (!maxId) {
  56. const sql = 'SELECT Max(??) As max_id FROM ?? Where ' + this.ctx.helper._getOptionsSql(options);
  57. const sqlParam = [this.setting.kid, this.tableName];
  58. const queryResult = await this.db.queryOne(sql, sqlParam);
  59. if (maxId < queryResult.max_id || 0) {
  60. maxId = queryResult.max_id || 0;
  61. }
  62. const sql1 = 'SELECT Max(??) As max_id FROM ?? Where ' + this.ctx.helper._getOptionsSql(options);
  63. const sqlParam1 = [this.setting.kid, this.ctx.service.contract.tableName];
  64. const queryResult1 = await this.db.queryOne(sql1, sqlParam1);
  65. if (maxId < queryResult1.max_id || 0) {
  66. maxId = queryResult1.max_id || 0;
  67. }
  68. this.cache.set(cacheKey, maxId, 'EX', this.ctx.app.config.cacheTime);
  69. }
  70. return maxId;
  71. }
  72. _cacheMaxLid(options, maxId) {
  73. const cacheKey = this.setting.keyPre + this._getStringOptions(options);
  74. this.cache.set(cacheKey, maxId, 'EX', this.ctx.app.config.cacheTime);
  75. }
  76. /**
  77. * 更新order
  78. * @param {Number} mid - master id
  79. * @param {Number} pid - 父节点id
  80. * @param {Number} order - 开始更新的order
  81. * @param {Number} incre - 更新的增量
  82. * @returns {Promise<*>}
  83. * @private
  84. */
  85. async _updateChildrenOrder(options, pid, order, incre = 1, transaction = null) {
  86. const optionSql = this.ctx.helper._getOptionsSql(options);
  87. const sql = 'UPDATE ?? SET `' + this.setting.order + '` = `' + this.setting.order + '` ' + (incre > 0 ? '+' : '-') + Math.abs(incre) + ' WHERE ' + optionSql + ' AND `' + this.setting.order + '` >= ? AND ' + this.setting.pid + ' = ?';
  88. const sqlParam = [this.tableName, order, pid];
  89. const data = transaction ? await transaction.query(sql, sqlParam) : await this.db.query(sql, sqlParam);
  90. const sql1 = 'UPDATE ?? SET `' + this.setting.order + '` = `' + this.setting.order + '` ' + (incre > 0 ? '+' : '-') + Math.abs(incre) + ' WHERE ' + optionSql + ' AND `' + this.setting.order + '` >= ? AND ' + this.setting.pid + ' = ?';
  91. const sqlParam1 = [this.ctx.service.contract.tableName, order, pid];
  92. transaction ? await transaction.query(sql1, sqlParam1) : await this.db.query(sql1, sqlParam1);
  93. return data;
  94. }
  95. _getOptionsSql(options) {
  96. const optionSql = [];
  97. for (const key in options) {
  98. if (options.hasOwnProperty(key)) {
  99. optionSql.push(key + ' = ' + this.db.escape(options[key]));
  100. }
  101. }
  102. return optionSql.join(' AND ');
  103. }
  104. async insertTree(options, subInfo) {
  105. const hadTree = await this.getDataByCondition(options);
  106. if (!hadTree) {
  107. if (options.tid && !subInfo.spid) {
  108. throw '该标段未绑定项目';
  109. }
  110. const subProj = options.spid ? subInfo : await this.ctx.service.subProject.getDataById(subInfo.spid);
  111. if (subProj.std_id === 0) {
  112. throw '该项目未绑定概预算标准';
  113. }
  114. const stdInfo = await this.ctx.service.budgetStd.getDataById(subProj.std_id);
  115. if (!stdInfo) {
  116. throw '概预算标准不存在';
  117. } else if (options.spid && !stdInfo.ht_project_template_id) {
  118. throw '概预算标准未绑定项目合同模板';
  119. } else if (options.tid && !stdInfo.ht_tender_template_id) {
  120. throw '概预算标准未绑定标段合同模板';
  121. }
  122. const ht_template_id = options.spid ? stdInfo.ht_project_template_id.split(',')[0] : stdInfo.ht_tender_template_id.split(',')[0];
  123. const ht_template_datas = await this.ctx.service.tenderNodeTemplate.getData(ht_template_id);
  124. if (!ht_template_datas.length) throw '模板数据有误';
  125. const expensesDatas = [];
  126. const incomeDatas = [];
  127. for (const t of ht_template_datas) {
  128. const insertData = {
  129. spid: options.spid || null,
  130. tid: options.tid || null,
  131. contract_id: t.template_id,
  132. contract_pid: t.pid,
  133. level: t.level,
  134. order: t.order,
  135. full_path: t.full_path,
  136. is_leaf: t.is_leaf,
  137. code: t.code,
  138. name: t.name,
  139. unit: t.unit,
  140. };
  141. const expensesData = this.ctx.helper._.cloneDeep(insertData);
  142. expensesData.id = this.uuid.v4();
  143. expensesData.contract_type = contractConst.type.expenses;
  144. expensesDatas.push(expensesData);
  145. const incomeData = this.ctx.helper._.cloneDeep(insertData);
  146. incomeData.id = this.uuid.v4();
  147. incomeData.contract_type = contractConst.type.income;
  148. incomeDatas.push(incomeData);
  149. }
  150. await this.db.insert(this.tableName, [...expensesDatas, ...incomeDatas]);
  151. }
  152. }
  153. /**
  154. * 提交数据 - 响应计算(增量方式计算)
  155. * @param {Number} tenderId
  156. * @param {Object} data
  157. * @return {Promise<*>}
  158. */
  159. async updateCalc(options, data, updateAll = false) {
  160. const helper = this.ctx.helper;
  161. if (!data) {
  162. throw '提交数据错误';
  163. }
  164. const datas = data instanceof Array ? data : [data];
  165. const ids = [];
  166. for (const row of datas) {
  167. ids.push(row.id);
  168. }
  169. const transaction = await this.db.beginTransaction();
  170. try {
  171. const updateDatas = [];
  172. const updateContractDatas = [];
  173. for (const row of datas) {
  174. const updateNode = await this.getDataById(row.id);
  175. if (!updateNode) {
  176. const contractNode = await this.ctx.service.contract.getDataById(row.id);
  177. if (contractNode) {
  178. const updateContractData = !updateAll ? this._filterUpdateInvalidField(contractNode.id, row) : row;
  179. updateContractDatas.push(updateContractData);
  180. continue;
  181. }
  182. throw '提交数据错误';
  183. }
  184. const updateData = !updateAll ? this._filterUpdateInvalidField(updateNode.id, row) : row;
  185. // 如非子节点,需要更新底下所有已选清单的分部分项等数据
  186. updateDatas.push(updateData);
  187. }
  188. if (updateDatas.length > 0) await transaction.updateRows(this.tableName, updateDatas);
  189. if (updateContractDatas.length > 0) await transaction.updateRows(this.ctx.service.contract.tableName, updateContractDatas);
  190. await transaction.commit();
  191. } catch (err) {
  192. await transaction.rollback();
  193. throw err;
  194. }
  195. return { update: await this.getDataByIds(ids) };
  196. }
  197. async getDataByIds(ids) {
  198. const resultData = []
  199. for (const id of ids) {
  200. resultData.push(await this.getDataByCondition({ id }) || await this.ctx.service.contract.getDataByCondition({ id }));
  201. }
  202. return resultData;
  203. }
  204. async getDataByKid(options, kid) {
  205. const condition = { ...options };
  206. condition[this.setting.kid] = kid;
  207. return await this.getDataByCondition(condition) || await this.ctx.service.contract.getDataByCondition(condition);
  208. }
  209. async getDataByKidAndCount(options, kid, count) {
  210. if (kid <= 0) return [];
  211. const select = await this.getDataByKid(options, kid);
  212. if (!select) throw '数据错误';
  213. if (count > 1) {
  214. const selects = await this.getNextsData(options, select[this.setting.pid], select[this.setting.order] - 1);
  215. if (selects.length < count) throw '数据错误';
  216. return selects.slice(0, count);
  217. } else {
  218. return [select];
  219. }
  220. }
  221. /**
  222. * 根据 父节点id 和 节点排序order 获取数据
  223. *
  224. * @param {Number} mid - master id
  225. * @param {Number} pid - 父节点id
  226. * @param {Number|Array} order - 排序
  227. * @return {Object|Array} - 查询结果
  228. */
  229. async getDataByParentAndOrder(options, pid, order) {
  230. const condition = { ...options };
  231. condition[this.setting.pid] = pid;
  232. condition[this.setting.order] = order;
  233. const result = await this.db.select(this.tableName, {
  234. where: condition,
  235. });
  236. const result1 = await this.db.select(this.ctx.service.contract.tableName, {
  237. where: condition,
  238. });
  239. // data和data1合并且按order排序
  240. const resultData = result.concat(result1).sort((a, b) => a.order - b.order);
  241. return order instanceof Array ? resultData : (resultData.length > 0 ? resultData[0] : null);
  242. }
  243. async addNodeBatch(options, kid, count = 1) {
  244. if (!options[this.setting.type]) throw '参数有误';
  245. const select = kid ? await this.getDataByKid(options, kid) : null;
  246. if (kid && !select) throw '新增节点数据错误';
  247. const transaction = await this.db.beginTransaction();
  248. try {
  249. // 判断select的父节点是否是变更新增的,如果是则修改自己的表就行了,否则修改2个ledger,changeLedger表
  250. if (select) await this._updateChildrenOrder(options, select[this.setting.pid], select[this.setting.order] + 1, count, transaction);
  251. const newDatas = [];
  252. const maxId = await this._getMaxLid(options);
  253. for (let i = 1; i < count + 1; i++) {
  254. const newData = [];
  255. if (this.setting.uuid) newData.id = this.uuid.v4();
  256. newData[this.setting.kid] = maxId + i;
  257. newData[this.setting.pid] = select ? select[this.setting.pid] : rootId;
  258. newData[this.setting.spid] = options.spid || null;
  259. newData[this.setting.type] = options[this.setting.type];
  260. newData[this.setting.mid] = options.tid || null;
  261. newData[this.setting.level] = select ? select[this.setting.level] : 1;
  262. newData[this.setting.order] = select ? select[this.setting.order] + i : i;
  263. newData[this.setting.fullPath] = newData[this.setting.level] > 1
  264. ? select[this.setting.fullPath].replace('-' + select[this.setting.kid], '-' + newData[this.setting.kid])
  265. : newData[this.setting.kid] + '';
  266. newData[this.setting.isLeaf] = true;
  267. newDatas.push(newData);
  268. }
  269. const insertResult = await transaction.insert(this.tableName, newDatas);
  270. this._cacheMaxLid(options, maxId + count);
  271. if (insertResult.affectedRows !== count) throw '新增节点数据错误';
  272. await transaction.commit();
  273. } catch (err) {
  274. await transaction.rollback();
  275. throw err;
  276. }
  277. if (select) {
  278. let createData = await this.getChildBetween(options, select[this.setting.pid], select[this.setting.order], select[this.setting.order] + count + 1);
  279. let updateData = await this.getNextsData(options, select[this.setting.pid], select[this.setting.order] + count);
  280. return { create: createData, update: updateData };
  281. } else {
  282. const createData = await this.getChildBetween(options, -1, 0, count + 1);
  283. return { create: createData };
  284. }
  285. }
  286. async addChildNode(options, kid, count = 1) {
  287. if (!options[this.setting.type]) throw '参数有误';
  288. const select = kid ? await this.getDataByKid(options, kid) : null;
  289. if (!select) throw '新增子节点数据错误';
  290. if (select && select.c_code) throw '合同无法新增子节点';
  291. const transaction = await this.db.beginTransaction();
  292. try {
  293. // 判断select的父节点是否是变更新增的,如果是则修改自己的表就行了,否则修改2个ledger,changeLedger表
  294. // if (select) await this._updateChildrenOrder(options, select[this.setting.pid], select[this.setting.order] + 1, count, transaction);
  295. const maxOrder = await this.ctx.service.contract.getMaxOrder(options, select[this.setting.kid], transaction);
  296. const newDatas = [];
  297. const maxId = await this._getMaxLid(options);
  298. for (let i = 1; i < count + 1; i++) {
  299. const newData = [];
  300. if (this.setting.uuid) newData.id = this.uuid.v4();
  301. newData[this.setting.kid] = maxId + i;
  302. newData[this.setting.pid] = select[this.setting.kid];
  303. newData[this.setting.spid] = options.spid || null;
  304. newData[this.setting.type] = options[this.setting.type];
  305. newData[this.setting.mid] = options.tid || null;
  306. newData[this.setting.level] = select[this.setting.level] + 1;
  307. newData[this.setting.order] = maxOrder - 1 + i;
  308. newData[this.setting.fullPath] = select[this.setting.fullPath] + '-' + newData[this.setting.kid];
  309. newData[this.setting.isLeaf] = true;
  310. newDatas.push(newData);
  311. }
  312. const insertResult = await transaction.insert(this.tableName, newDatas);
  313. this._cacheMaxLid(options, maxId + count);
  314. if (insertResult.affectedRows !== count) throw '新增子节点数据错误';
  315. if (select[this.setting.isLeaf]) {
  316. select.is_leaf = 0;
  317. await transaction.update(this.tableName, { id: select.id, is_leaf: 0 });
  318. }
  319. await transaction.commit();
  320. } catch (err) {
  321. await transaction.rollback();
  322. throw err;
  323. }
  324. let createData = await this.getLastChildData(options, select[this.setting.kid]);
  325. let updateData = select;
  326. return { create: [createData], update: [updateData] };
  327. }
  328. /**
  329. * tenderId标段中, 删除选中节点及其子节点
  330. *
  331. * @param {Number} tenderId - 标段id
  332. * @param {Number} selectId - 选中节点id
  333. * @return {Array} - 被删除的数据
  334. */
  335. async deleteNode(options, kid) {
  336. if (kid <= 0) return [];
  337. const select = await this.getDataByKid(options, kid);
  338. if (!select) throw '删除节点数据错误';
  339. const parent = await this.getDataByKid(options, select[this.setting.pid]);
  340. // 获取将要被删除的数据
  341. const deleteData = await this.getDataByFullPath(options, select[this.setting.fullPath] + '-%');
  342. deleteData.unshift(select);
  343. if (deleteData.length === 0) throw '删除节点数据错误';
  344. const transaction = await this.db.beginTransaction();
  345. try {
  346. // 删除
  347. if (select.c_code) {
  348. if (select.uid !== this.ctx.session.sessionUser.accountId && !this.ctx.session.sessionUser.is_admin) throw '当前合同无权删除';
  349. const contractPays = await this.ctx.service.contractPay.getDataByCondition({ cid: select.id });
  350. if (contractPays) throw '还存在合同支付项,无法删除';
  351. await transaction.delete(this.ctx.service.contract.tableName, { id: select.id });
  352. const attList = await this.ctx.service.contractAtt.getAllDataByCondition({ where: { cid: select.id } });
  353. await this.ctx.helper.delFiles(attList);
  354. await transaction.delete(this.ctx.service.contractAtt.tableName, { cid: select.id });
  355. await transaction.delete(this.ctx.service.contractSpAudit.tableName, { cid: select.id, cpid: null });
  356. } else {
  357. await transaction.delete(this.tableName, { id: select.id });
  358. const delOptions = this._.cloneDeep(options);
  359. delOptions.contract_id = this._.map(deleteData, 'contract_id');
  360. await transaction.delete(this.ctx.service.contractTreeAudit.tableName, delOptions);
  361. const contracts = this.ctx.helper._.filter(deleteData, function (item) {
  362. return item.c_code;
  363. });
  364. if (contracts.length > 0) {
  365. const contractUids = this.ctx.helper._.uniq(this.ctx.helper._.map(contracts, 'uid'));
  366. if (contractUids.length > 1 || !(contractUids[0] === this.ctx.session.sessionUser.accountId || this.ctx.session.sessionUser.is_admin)) throw '存在合同你无权删除';
  367. const contractPays = await transaction.select(this.ctx.service.contractPay.tableName, { where: { cid: this.ctx.helper._.map(contracts, 'id') } });
  368. if (contractPays.length > 0) throw '还存在合同支付项,无法删除';
  369. const attList = await this.ctx.service.contractAtt.getAllDataByCondition({ where: { cid: this.ctx.helper._.map(contracts, 'id') } });
  370. await this.ctx.helper.delFiles(attList);
  371. await transaction.delete(this.ctx.service.contractAtt.tableName, { cid: this.ctx.helper._.map(contracts, 'id') });
  372. await transaction.delete(this.ctx.service.contractSpAudit.tableName, { cid: this.ctx.helper._.map(contracts, 'id'), cpid: null });
  373. }
  374. const operate = await this._deletePosterity(options, select, transaction);
  375. }
  376. // 选中节点--父节点 只有一个子节点时,应升级isLeaf
  377. if (parent) {
  378. const condition = { ...options };
  379. condition[this.setting.pid] = select[this.setting.pid];
  380. const count = await this.db.count(this.tableName, condition);
  381. const count1 = await this.db.count(this.ctx.service.contract.tableName, condition);
  382. const sum = count + count1;
  383. if (sum === 1) {
  384. const updateParent = {id: parent.id };
  385. updateParent[this.setting.isLeaf] = true;
  386. await transaction.update(this.tableName, updateParent);
  387. }
  388. }
  389. // 选中节点--全部后节点 order--
  390. await this._updateChildrenOrder(options, select[this.setting.pid], select[this.setting.order] + 1, -1, transaction);
  391. await transaction.commit();
  392. } catch (err) {
  393. await transaction.rollback();
  394. throw err;
  395. }
  396. // 查询结果
  397. const updateData = await this.getNextsData(options, select[this.setting.pid], select[this.setting.order] - 1);
  398. if (parent) {
  399. const updateData1 = await this.getDataByKid(options, select[this.setting.pid]);
  400. if (updateData1[this.setting.isLeaf]) {
  401. updateData.push(updateData1);
  402. }
  403. }
  404. return { delete: deleteData, update: updateData };
  405. }
  406. async deleteNodes(options, kid, count) {
  407. const _ = this.ctx.helper._;
  408. if ((kid <= 0) || (count <= 0)) return [];
  409. const selects = await this.getDataByKidAndCount(options, kid, count);
  410. const first = selects[0];
  411. const parent = await this.getDataByKid(options, first[this.setting.pid]);
  412. const condition = { ...options };
  413. condition[this.setting.pid] = parent[this.setting.kid];
  414. const childCount1 = parent ? await this.count(condition) : -1;
  415. const childCount2 = parent ? await this.db.count(this.ctx.service.contract.tableName, condition) : -1;
  416. const childCount = childCount1 + childCount2;
  417. let deleteData = [];
  418. for (const s of selects) {
  419. deleteData = deleteData.concat(await this.getDataByFullPath(options, s[this.setting.fullPath] + '-%'));
  420. deleteData.push(s);
  421. }
  422. const transaction = await this.db.beginTransaction();
  423. try {
  424. // 删除
  425. for (const s of selects) {
  426. if (s.c_code) {
  427. if (s.uid !== this.ctx.session.sessionUser.accountId && !this.ctx.session.sessionUser.is_admin) throw '存在合同你无权删除';
  428. const contractPays = await this.ctx.service.contractPay.getDataByCondition({ cid: s.id });
  429. if (contractPays) throw '部分合同还存在合同支付项,无法删除';
  430. await transaction.delete(this.ctx.service.contract.tableName, { id: s.id });
  431. const attList = await this.ctx.service.contractAtt.getAllDataByCondition({ where: { cid: s.id } });
  432. await this.ctx.helper.delFiles(attList);
  433. await transaction.delete(this.ctx.service.contractAtt.tableName, { cid: s.id });
  434. await transaction.delete(this.ctx.service.contractSpAudit.tableName, { cid: s.id, cpid: null });
  435. } else {
  436. await transaction.delete(this.tableName, { id: s.id });
  437. const contracts = _.filter(deleteData, function (item) {
  438. return item.c_code && _.includes(s.full_path, item.full_path);
  439. });
  440. if (contracts.length > 0) {
  441. const contractUids = _.uniq(_.map(contracts, 'uid'));
  442. if (contractUids.length > 1 || !(contractUids[0] === this.ctx.session.sessionUser.accountId || this.ctx.session.sessionUser.is_admin)) throw '存在合同你无权删除';
  443. const contractPays = await transaction.select(this.ctx.service.contractPay.tableName, { where: { cid: _.map(contracts, 'id') } });
  444. if (contractPays.length > 0) throw '还存在合同支付项,无法删除';
  445. const attList = await this.ctx.service.contractAtt.getAllDataByCondition({ where: { cid: _.map(contracts, 'id') } });
  446. await this.ctx.helper.delFiles(attList);
  447. await transaction.delete(this.ctx.service.contractAtt.tableName, { cid: _.map(contracts, 'id') });
  448. await transaction.delete(this.ctx.service.contractSpAudit.tableName, { cid: _.map(contracts, 'id'), cpid: null });
  449. }
  450. }
  451. const operate = await this._deletePosterity(options, s, transaction);
  452. }
  453. // 选中节点--父节点 只有一个子节点时,应升级isLeaf
  454. if (parent && childCount === count) {
  455. const updateParent = {id: parent.id };
  456. updateParent[this.setting.isLeaf] = true;
  457. await transaction.update(this.tableName, updateParent);
  458. }
  459. // 选中节点--全部后节点 order--
  460. await this._updateChildrenOrder(options, first[this.setting.pid], first[this.setting.order] + count, -count, transaction);
  461. const delOptions = this._.cloneDeep(options);
  462. delOptions.contract_id = this._.map(deleteData, 'contract_id');
  463. await transaction.delete(this.ctx.service.contractTreeAudit.tableName, delOptions);
  464. await transaction.commit();
  465. } catch (err) {
  466. await transaction.rollback();
  467. throw err;
  468. }
  469. const updateData = await this.getNextsData(options, first[this.setting.pid], first[this.setting.order] - 1);
  470. if (parent && childCount === count) {
  471. const updateData1 = await this.getDataByKid(options, parent[this.setting.kid]);
  472. updateData.push(updateData1);
  473. }
  474. return { delete: deleteData, update: updateData };
  475. }
  476. async delete(options, kid, count = null) {
  477. if (count && count > 1) {
  478. return await this.deleteNodes(options, kid, count);
  479. } else {
  480. return await this.deleteNode(options, kid);
  481. }
  482. }
  483. /**
  484. * 上移节点
  485. *
  486. * @param {Number} mid - master id
  487. * @param {Number} kid - 选中节点id
  488. * @return {Array} - 发生改变的数据
  489. */
  490. async upMoveNode(options, kid, count) {
  491. if (!count) count = 1;
  492. if (!kid || (kid <= 0)) return null;
  493. const selects = await this.getDataByKidAndCount(options, kid, count);
  494. if (selects.length !== count) throw '上移节点数据错误';
  495. const first = selects[0];
  496. const pre = await this.getDataByParentAndOrder(options, first[this.setting.pid], first[this.setting.order] - 1);
  497. if (!pre) throw '节点不可上移';
  498. const order = [];
  499. const transaction = await this.db.beginTransaction();
  500. try {
  501. for (const s of selects) {
  502. const sData = { id: s.id };
  503. sData[this.setting.order] = s[this.setting.order] - 1;
  504. !s.c_code ? await transaction.update(this.tableName, sData) : await transaction.update(this.ctx.service.contract.tableName, sData);
  505. order.push(s[this.setting.order] - 1);
  506. }
  507. const pData = { id: pre.id };
  508. pData[this.setting.order] = pre[this.setting.order] + count;
  509. !pre.c_code ? await transaction.update(this.tableName, pData) : await transaction.update(this.ctx.service.contract.tableName, pData);
  510. order.push(pre[this.setting.order] + count);
  511. await transaction.commit();
  512. } catch (err) {
  513. await transaction.rollback();
  514. throw err;
  515. }
  516. const resultData = await this.getDataByParentAndOrder(options, first[this.setting.pid], order);
  517. return { update: resultData };
  518. }
  519. /**
  520. * 下移节点
  521. *
  522. * @param {Number} mid - master id
  523. * @param {Number} kid - 选中节点id
  524. * @return {Array} - 发生改变的数据
  525. */
  526. async downMoveNode(options, kid, count) {
  527. if (!count) count = 1;
  528. if (!kid || (kid <= 0)) return null;
  529. const selects = await this.getDataByKidAndCount(options, kid, count);
  530. if (selects.length !== count) {
  531. throw '下移节点数据错误';
  532. }
  533. const last = selects[count - 1];
  534. const next = await this.getDataByParentAndOrder(options, last[this.setting.pid], last[this.setting.order] + 1);
  535. if (!next) {
  536. throw '节点不可下移';
  537. }
  538. const order = [];
  539. const transaction = await this.db.beginTransaction();
  540. try {
  541. for (const s of selects) {
  542. const sData = { id: s.id };
  543. sData[this.setting.order] = s[this.setting.order] + 1;
  544. !s.c_code ? await transaction.update(this.tableName, sData) : await transaction.update(this.ctx.service.contract.tableName, sData);
  545. order.push(s[this.setting.order] + 1);
  546. }
  547. const nData = { id: next.id };
  548. nData[this.setting.order] = next[this.setting.order] - count;
  549. !next.c_code ? await transaction.update(this.tableName, nData) : await transaction.update(this.ctx.service.contract.tableName, nData);
  550. order.push(next[this.setting.order] - count);
  551. await transaction.commit();
  552. } catch (err) {
  553. await transaction.rollback();
  554. throw err;
  555. }
  556. const resultData = await this.getDataByParentAndOrder(options, last[this.setting.pid], order);
  557. return { update: resultData };
  558. }
  559. /**
  560. * 升级节点
  561. *
  562. * @param {Number} tenderId - 标段id
  563. * @param {Number} selectId - 选中节点id
  564. * @return {Array} - 发生改变的数据
  565. */
  566. async upLevelNode(options, kid, count) {
  567. if (!count) count = 1;
  568. const selects = await this.getDataByKidAndCount(options, kid, count);
  569. if (selects.length !== count) throw '升级节点数据错误';
  570. if (this._.findIndex(selects, function (item) {
  571. return item.c_code;
  572. }) !== -1) {
  573. throw '存在合同节点不可升级';
  574. }
  575. const first = selects[0], last = selects[count - 1];
  576. const parent = await this.getDataByKid(options, first[this.setting.pid]);
  577. if (!parent) throw '升级节点数据错误';
  578. const newPath = [];
  579. const transaction = await this.db.beginTransaction();
  580. try {
  581. // 选中节点--父节点 选中节点为firstChild时,修改isLeaf
  582. if (first[this.setting.order] === 1) {
  583. const updateParentData = { id: parent.id };
  584. updateParentData[this.setting.isLeaf] = true;
  585. await transaction.update(this.tableName, updateParentData);
  586. }
  587. // 选中节点--父节点--全部后兄弟节点 order+1
  588. await this._updateChildrenOrder(options, parent[this.setting.pid], parent[this.setting.order] + 1, count, transaction);
  589. for (const [i, s] of selects.entries()) {
  590. // 选中节点 修改pid, order, fullPath, level, isLeaf, 清空计算项
  591. const updateData = { id: s.id };
  592. updateData[this.setting.pid] = parent[this.setting.pid];
  593. updateData[this.setting.order] = parent[this.setting.order] + i + 1;
  594. updateData[this.setting.level] = s[this.setting.level] - 1;
  595. updateData[this.setting.fullPath] = s[this.setting.fullPath].replace(`-${s[this.setting.pid]}-`, '-');
  596. newPath.push(updateData[this.setting.fullPath]);
  597. if (s[this.setting.isLeaf] && s.id === last.id) {
  598. const nexts = await this.getNextsData(options, parent[this.setting.kid], last[this.setting.order]);
  599. if (nexts.length > 0) {
  600. updateData[this.setting.isLeaf] = false;
  601. }
  602. }
  603. await transaction.update(this.tableName, updateData);
  604. // 选中节点--全部子节点(含孙) level-1, fullPath变更
  605. await this._syncUplevelChildren(options, s, transaction);
  606. }
  607. // 选中节点--全部后兄弟节点 收编为子节点 修改pid, order, fullPath
  608. await this._syncUpLevelNexts(options, last, transaction);
  609. await transaction.commit();
  610. } catch (err) {
  611. await transaction.rollback();
  612. throw err;
  613. }
  614. // 查询修改的数据
  615. let updateData = await this.getNextsData(options, parent[this.setting.pid], parent[this.setting.order] - 1);
  616. for (const path of newPath) {
  617. const children = await this.getDataByFullPath(options, path + '-%');
  618. updateData = updateData.concat(children);
  619. }
  620. return { update: updateData };
  621. }
  622. /**
  623. * 降级节点
  624. *
  625. * @param {Number} tenderId - 标段id
  626. * @param {Number} selectId - 选中节点id
  627. * @return {Array} - 发生改变的数据
  628. */
  629. async downLevelNode(options, kid, count) {
  630. if (!count) count = 1;
  631. const selects = await this.getDataByKidAndCount(options, kid, count);
  632. if (!selects) throw '降级节点数据错误';
  633. // if (this._.findIndex(selects, function (item) {
  634. // return item.c_code;
  635. // }) !== -1) {
  636. // throw '存在合同节点不可降级';
  637. // }
  638. const first = selects[0], last = selects[count - 1];
  639. const pre = await this.getDataByParentAndOrder(options, first[this.setting.pid], first[this.setting.order] - 1);
  640. if (!pre) throw '节点不可降级';
  641. const preLastChild = await this.getLastChildData(options, pre[this.setting.kid]);
  642. const newPath = [];
  643. const transaction = await this.db.beginTransaction();
  644. try {
  645. // 选中节点--全部后节点 order--
  646. await this._updateChildrenOrder(options, first[this.setting.pid], last[this.setting.order] + 1, -count, transaction);
  647. for (const [i, s] of selects.entries()) {
  648. // 选中节点 修改pid, level, order, fullPath
  649. const updateData = { id: s.id };
  650. updateData[this.setting.pid] = pre[this.setting.kid];
  651. updateData[this.setting.order] = preLastChild ? preLastChild[this.setting.order] + i + 1 : i + 1;
  652. updateData[this.setting.level] = s[this.setting.level] + 1;
  653. if (s[this.setting.level] === 1) {
  654. updateData[this.setting.fullPath] = pre[this.setting.kid] + '-' + s[this.setting.kid];
  655. } else {
  656. const index = s[this.setting.fullPath].lastIndexOf(s[this.setting.kid]);
  657. updateData[this.setting.fullPath] = s[this.setting.fullPath].substring(0, index-1) + '-' + pre[this.setting.kid] + '-' + s[this.setting.kid];
  658. }
  659. newPath.push(updateData[this.setting.fullPath]);
  660. s.c_code ? await transaction.update(this.ctx.service.contract.tableName, updateData) : await transaction.update(this.tableName, updateData);
  661. // 选中节点--全部子节点(含孙) level++, fullPath
  662. await this._syncDownlevelChildren(options, s, updateData[this.setting.fullPath], transaction);
  663. }
  664. // 选中节点--前兄弟节点 isLeaf应为false, 清空计算相关字段
  665. const updateData2 = { id: pre.id };
  666. updateData2[this.setting.isLeaf] = false;
  667. await transaction.update(this.tableName, updateData2);
  668. await transaction.commit();
  669. } catch (err) {
  670. await transaction.rollback();
  671. throw err;
  672. }
  673. // 查询修改的数据
  674. let updateData = await this.getNextsData(options, pre[this.setting.pid], pre[this.setting.order] - 1);
  675. // 选中节点及子节点
  676. for (const p of newPath) {
  677. updateData = updateData.concat(await this.getDataByFullPath(options, p + '-%'));
  678. }
  679. const contractSelects = selects.filter(x => x.c_code);
  680. const treeSelects = selects.filter(x => !x.c_code);
  681. if (treeSelects.length > 0) updateData = updateData.concat(await this.getDataById(treeSelects.map(x => { return x.id; })));
  682. if (contractSelects.length > 0) updateData = updateData.concat(await this.ctx.service.contract.getDataById(contractSelects.map(x => { return x.id; })));
  683. // 选中节点--原前兄弟节点&全部后兄弟节点
  684. return { update: updateData };
  685. }
  686. async pasteBlockData(options, kid, pasteData, defaultData) {
  687. if (!options[this.setting.type]) throw '参数有误';
  688. if (!pasteData || pasteData.length <= 0) throw '复制数据错误';
  689. for (const pd of pasteData) {
  690. if (!pd || pd.length <= 0) throw '复制数据错误';
  691. pd.sort(function (x, y) {
  692. return x.level - y.level
  693. });
  694. if (pd[0].contract_pid !== pasteData[0][0].contract_pid) throw '复制数据错误:仅可操作同层节点';
  695. }
  696. const selectData = await this.getDataByKid(options, kid);
  697. if (!selectData) throw '粘贴数据错误';
  698. const newParentPath = selectData.full_path.replace(selectData.contract_id, '');
  699. const pasteBillsData = [];
  700. let maxId = await this._getMaxLid(options);
  701. for (const [i, pd] of pasteData.entries()) {
  702. for (const d of pd) {
  703. d.children = pd.filter(function (x) {
  704. return x.contract_pid === d.contract_id;
  705. });
  706. }
  707. const pbd = [];
  708. for (const [j, d] of pd.entries()) {
  709. const newBills = {
  710. id: this.uuid.v4(),
  711. spid: options.spid || null,
  712. tid: options.tid || null,
  713. contract_type: options.contract_type,
  714. contract_id: maxId + j + 1,
  715. contract_pid: j === 0 ? selectData.contract_pid : d.contract_pid,
  716. level: d.level + selectData.level - pd[0].level,
  717. order: j === 0 ? selectData.order + i + 1 : d.order,
  718. is_leaf: d.is_leaf,
  719. code: d.code,
  720. name: d.name,
  721. remark: d.remark,
  722. };
  723. for (const c of d.children) {
  724. c.contract_pid = newBills.contract_id;
  725. }
  726. pbd.push(newBills);
  727. }
  728. for (const d of pbd) {
  729. const parent = pbd.find(function (x) {
  730. return x.contract_id === d.contract_pid;
  731. });
  732. d.full_path = parent
  733. ? parent.full_path + '-' + d.contract_id
  734. : newParentPath + d.contract_id;
  735. if (defaultData) this.ctx.helper._.assignIn(pbd, defaultData);
  736. pasteBillsData.push(d);
  737. }
  738. maxId = maxId + pbd.length;
  739. }
  740. const transaction = await this.db.beginTransaction();
  741. try {
  742. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  743. await this._updateChildrenOrder(options, selectData.ledger_pid, selectData.order + 1, pasteData.length, transaction);
  744. // 数据库创建新增节点数据
  745. if (pasteBillsData.length > 0) {
  746. const newData = await transaction.insert(this.tableName, pasteBillsData);
  747. }
  748. this._cacheMaxLid(options, maxId);
  749. await transaction.commit();
  750. } catch (err) {
  751. await transaction.rollback();
  752. throw err;
  753. }
  754. // 查询应返回的结果
  755. const updateData = await this.getNextsData(options, selectData.contract_pid, selectData.order + pasteData.length);
  756. return {
  757. ledger: { create: pasteBillsData, update: updateData },
  758. };
  759. }
  760. /**
  761. * 删除节点
  762. * @param {Number} tenderId - 标段id
  763. * @param {Object} deleteData - 删除节点数据
  764. * @return {Promise<*>}
  765. * @private
  766. */
  767. async _deletePosterity(options, node, transaction = null) {
  768. const sql = 'DELETE FROM ?? WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.fullPath + ' LIKE ?';
  769. const sqlParam = [this.tableName, node[this.setting.fullPath] + '-%'];
  770. const result = transaction ? await transaction.query(sql, sqlParam) : await this.db.query(sql, sqlParam)
  771. const sql1 = 'DELETE FROM ?? WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.fullPath + ' LIKE ?';
  772. const sqlParam1 = [this.ctx.service.contract.tableName, node[this.setting.fullPath] + '-%'];
  773. const result1 = transaction ? await transaction.query(sql1, sqlParam1) : await this.db.query(sql1, sqlParam1)
  774. return result;
  775. }
  776. /**
  777. * 根据fullPath获取数据 fullPath Like ‘1.2.3%’(传参fullPath = '1.2.3%')
  778. * @param {Number} tenderId - 标段id
  779. * @param {String} fullPath - 路径
  780. * @return {Promise<void>}
  781. */
  782. async getDataByFullPath(options, fullPath) {
  783. const sql = 'SELECT * FROM ?? WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.fullPath + ' LIKE ?';
  784. const sqlParam = [this.tableName, fullPath];
  785. const resultData = await this.db.query(sql, sqlParam);
  786. const sql1 = 'SELECT * FROM ?? WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.fullPath + ' LIKE ?';
  787. const sqlParam1 = [this.ctx.service.contract.tableName, fullPath];
  788. const resultData1 = await this.db.query(sql1, sqlParam1);
  789. return resultData.concat(resultData1).sort((a, b) => a.order - b.order);
  790. }
  791. async getChildBetween(options, pid, order1, order2) {
  792. const sql = 'SELECT * FROM ?? WHERE '+ this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.pid + ' = ? AND `order` > ? AND `order` < ? ORDER BY `order` ASC';
  793. const sqlParam = [this.tableName, pid, order1, order2];
  794. const data = await this.db.query(sql, sqlParam);
  795. const sql1 = 'SELECT * FROM ?? WHERE '+ this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.pid + ' = ? AND `order` > ? AND `order` < ? ORDER BY `order` ASC';
  796. const sqlParam1 = [this.ctx.service.contract.tableName, pid, order1, order2];
  797. const data1 = await this.db.query(sql1, sqlParam1);
  798. const resultData = data.concat(data1).sort((a, b) => a.order - b.order);
  799. return resultData;
  800. }
  801. /**
  802. * 根据 父节点ID 和 节点排序order 获取全部后节点数据
  803. * @param {Number} mid - master id
  804. * @param {Number} pid - 父节点id
  805. * @param {Number} order - 排序
  806. * @return {Array}
  807. */
  808. async getNextsData(options, pid, order) {
  809. const sql = 'SELECT * FROM ?? WHERE '+ this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.pid + ' = ? AND `order` > ? ORDER BY `order` ASC';
  810. const sqlParam = [this.tableName, pid, order];
  811. const data = await this.db.query(sql, sqlParam);
  812. const sql1 = 'SELECT * FROM ?? WHERE '+ this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.pid + ' = ? AND `order` > ? ORDER BY `order` ASC';
  813. const sqlParam1 = [this.ctx.service.contract.tableName, pid, order];
  814. const data1 = await this.db.query(sql1, sqlParam1);
  815. // data和data1合并且按order排序
  816. const resultData = data.concat(data1).sort((a, b) => a.order - b.order);
  817. return resultData;
  818. }
  819. /**
  820. * 获取最末的子节点
  821. * @param {Number} mid - masterId
  822. * @param {Number} pid - 父节点id
  823. * @return {Object}
  824. */
  825. async getLastChildData(options, pid, transaction = null) {
  826. const sql = 'SELECT * FROM ?? WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.pid + ' = ? ORDER BY `order` DESC';
  827. const sqlParam = [this.tableName, pid];
  828. const resultData = await this.db.queryOne(sql, sqlParam);
  829. const sql1 = 'SELECT * FROM ?? WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.pid + ' = ? ORDER BY `order` DESC';
  830. const sqlParam1 = [this.ctx.service.contract.tableName, pid];
  831. const resultData1 = await this.db.queryOne(sql1, sqlParam1);
  832. // 比较两个结果,返回order大的
  833. if (resultData && resultData1) {
  834. return resultData.order > resultData1.order ? resultData : resultData1;
  835. } else {
  836. return resultData || resultData1;
  837. }
  838. }
  839. /**
  840. * 选中节点的后兄弟节点,全部变为当前节点的子节点
  841. * @param {Object} selectData - 选中节点
  842. * @return {Object}
  843. * @private
  844. */
  845. async _syncUpLevelNexts(options, select, transaction = null) {
  846. // 查询selectData的lastChild
  847. const lastChild = await this.getLastChildData(options, select[this.setting.kid]);
  848. const nexts = await this.getNextsData(options, select[this.setting.pid], select[this.setting.order]);
  849. if (this._.findIndex(nexts, function (item) {
  850. return item.c_code;
  851. }) !== -1) {
  852. throw '存在合同节点不可升级';
  853. }
  854. if (nexts && nexts.length > 0) {
  855. // 修改nextsData pid, 排序
  856. // this.initSqlBuilder();
  857. // this.sqlBuilder.setUpdateData(this.setting.pid, {
  858. // value: select[this.setting.kid],
  859. // });
  860. // const orderInc = lastChild ? lastChild[this.setting.order] - select[this.setting.order] : - select[this.setting.order];
  861. // this.sqlBuilder.setUpdateData(this.setting.order, {
  862. // value: Math.abs(orderInc),
  863. // selfOperate: orderInc > 0 ? '+' : '-',
  864. // });
  865. // this.sqlBuilder.setAndWhere(this.setting.mid, {
  866. // value: select[this.setting.mid],
  867. // operate: '=',
  868. // });
  869. // this.sqlBuilder.setAndWhere(this.setting.pid, {
  870. // value: select[this.setting.pid],
  871. // operate: '=',
  872. // });
  873. // this.sqlBuilder.setAndWhere(this.setting.order, {
  874. // value: select[this.setting.order],
  875. // operate: '>',
  876. // });
  877. // const [sql1, sqlParam1] = this.sqlBuilder.build(this.tableName, 'update');
  878. const orderInc = lastChild ? lastChild[this.setting.order] - select[this.setting.order] : - select[this.setting.order];
  879. const sql1 = 'UPDATE ?? SET `'+ this.setting.pid + '` = '+ select[this.setting.kid] +' , `' + this.setting.order + '` = `'+ this.setting.order + '`' + (orderInc > 0 ? '+' : '-') + Math.abs(orderInc) + ' WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.pid + ' = ? AND `' + this.setting.order + '` > ?';
  880. const sqlParam1 = [this.tableName, select[this.setting.pid], select[this.setting.order]];
  881. transaction ? await transaction.query(sql1, sqlParam1) : await this.db.query(sql1, sqlParam1);
  882. // 选中节点 isLeaf应为false
  883. if (select[this.setting.isLeaf]) {
  884. const updateData = { id: select.id };
  885. updateData[this.setting.isLeaf] = false;
  886. transaction ? await transaction.update(this.tableName, updateData) : await this.db.update(this.tableName, updateData);
  887. }
  888. // 修改nextsData及其子节点的fullPath
  889. const oldSubStr = this.db.escape(select[this.setting.pid] + '-');
  890. const newSubStr = this.db.escape(select[this.setting.kid] + '-');
  891. const sqlArr = [];
  892. sqlArr.push('Update ?? SET `' + this.setting.fullPath + '` = Replace(`' + this.setting.fullPath + '`,' + oldSubStr + ',' + newSubStr + ') Where ');
  893. sqlArr.push(this.ctx.helper._getOptionsSql(options));
  894. sqlArr.push(' And (');
  895. for (const data of nexts) {
  896. sqlArr.push('`' + this.setting.fullPath + '` Like ' + this.db.escape(data[this.setting.fullPath] + '%'));
  897. if (nexts.indexOf(data) < nexts.length - 1) {
  898. sqlArr.push(' Or ');
  899. }
  900. }
  901. sqlArr.push(')');
  902. const sql = sqlArr.join('');
  903. const resultData = transaction ? await transaction.query(sql, [this.tableName]) : await this.db.query(sql, [this.tableName]);
  904. transaction ? await transaction.query(sql, [this.ctx.service.contract.tableName]) : await this.db.query(sql, [this.ctx.service.contract.tableName]);
  905. return resultData;
  906. }
  907. }
  908. /**
  909. * 升级selectData, 同步修改所有子节点
  910. * @param {Object} selectData - 升级操作,选中节点
  911. * @return {Object}
  912. * @private
  913. */
  914. async _syncUplevelChildren(options, select, transaction = null) {
  915. // const children = await this.getDataByFullPath(options, select[this.setting.fullPath] + '-%');
  916. // if (this._.findIndex(children, function (item) {
  917. // return item.c_code;
  918. // }) !== -1) {
  919. // throw '存在合同节点不可升级';
  920. // }
  921. // this.initSqlBuilder();
  922. // this.sqlBuilder.setAndWhere(this.setting.mid, {
  923. // value: select[this.setting.mid],
  924. // operate: '=',
  925. // });
  926. // this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  927. // value: this.db.escape(select[this.setting.fullPath] + '-%'),
  928. // operate: 'like',
  929. // });
  930. // this.sqlBuilder.setUpdateData(this.setting.level, {
  931. // value: 1,
  932. // selfOperate: '-',
  933. // });
  934. // this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  935. // value: [this.setting.fullPath, this.db.escape(`-${select[this.setting.pid]}-`), this.db.escape('-')],
  936. // literal: 'Replace',
  937. // });
  938. // const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  939. const sql = 'UPDATE ?? SET ' + this.setting.level + ' = ' + this.setting.level + ' -1, ' + this.setting.fullPath + ' = ' +
  940. 'Replace('+ [this.setting.fullPath, this.db.escape(`-${select[this.setting.pid]}-`), this.db.escape('-')].join(',') +') ' +
  941. 'WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.fullPath + ' LIKE ?';
  942. const sqlParam = [this.tableName, select[this.setting.fullPath] + '-%'];
  943. const data = transaction ? await transaction.query(sql, sqlParam) : await this.db.query(sql, sqlParam);
  944. transaction ? await transaction.query(sql, [this.ctx.service.contract.tableName, select[this.setting.fullPath] + '-%']) : await this.db.query(sql, [this.ctx.service.contract.tableName, select[this.setting.fullPath] + '-%']);
  945. return data;
  946. }
  947. /**
  948. * 降级selectData, 同步修改所有子节点
  949. * @param {Object} selectData - 选中节点
  950. * @param {Object} preData - 选中节点的前一节点(降级后为父节点)
  951. * @return {Promise<*>}
  952. * @private
  953. */
  954. async _syncDownlevelChildren(options, select, newFullPath, transaction = null) {
  955. // const children = await this.getDataByFullPath(options, select[this.setting.fullPath] + '-%');
  956. // if (this._.findIndex(children, function (item) {
  957. // return item.c_code;
  958. // }) !== -1) {
  959. // throw '存在合同节点不可降级';
  960. // }
  961. // this.initSqlBuilder();
  962. // this.sqlBuilder.setAndWhere(this.setting.mid, {
  963. // value: select[this.setting.mid],
  964. // operate: '=',
  965. // });
  966. // this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  967. // value: this.db.escape(select[this.setting.fullPath] + '-%'),
  968. // operate: 'like',
  969. // });
  970. // this.sqlBuilder.setUpdateData(this.setting.level, {
  971. // value: 1,
  972. // selfOperate: '+',
  973. // });
  974. // this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  975. // value: [this.setting.fullPath, this.db.escape(select[this.setting.fullPath] + '-'), this.db.escape(newFullPath + '-')],
  976. // literal: 'Replace',
  977. // });
  978. // const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  979. const sql = 'UPDATE ?? SET ' + this.setting.level + ' = ' + this.setting.level + ' + 1, ' + this.setting.fullPath + ' = ' +
  980. 'Replace(' + [[this.setting.fullPath, this.db.escape(select[this.setting.fullPath] + '-'), this.db.escape(newFullPath + '-')]].join(',') + ') ' +
  981. 'WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.fullPath + ' LIKE ?';
  982. const sqlParam = [this.tableName, select[this.setting.fullPath] + '-%'];
  983. const data = transaction ? await transaction.query(sql, sqlParam) : await this.db.query(sql, sqlParam);
  984. transaction ? await transaction.query(sql, [this.ctx.service.contract.tableName, select[this.setting.fullPath] + '-%']) : await this.db.query(sql, [this.ctx.service.contract.tableName, select[this.setting.fullPath] + '-%']);
  985. return data;
  986. }
  987. /**
  988. * 添加节点,并同步添加父节点
  989. * @param {Number} tenderId - 标段id
  990. * @param {Number} selectId - 选中节点id
  991. * @param {Object} stdData - 节点数据
  992. * @param {StandardLib} stdLib - 标准库
  993. * @return {Promise<void>}
  994. */
  995. async addStdNodeWithParent(options, kid, stdData, stdLib) {
  996. if (!options[this.setting.type]) throw '参数有误';
  997. const select = kid ? await this.getDataByKid(options, kid) : null;
  998. if (!select) throw '新增子节点数据错误';
  999. if (select && select.c_code) throw '合同无法新增子节点';
  1000. // 查询完整标准清单,并按层次排序
  1001. const fullLevel = await stdLib.getFullLevelDataByFullPath(stdData.list_id, stdData.full_path);
  1002. fullLevel.sort(function(x, y) {
  1003. return x.level - y.level;
  1004. });
  1005. let isNew = false,
  1006. node,
  1007. firstNew,
  1008. updateParent,
  1009. addResult;
  1010. const expandIds = [];
  1011. this.transaction = await this.db.beginTransaction();
  1012. try {
  1013. // 从最顶层节点依次查询是否存在,否则添加
  1014. for (let i = 0, len = fullLevel.length; i < len; i++) {
  1015. const stdNode = fullLevel[i];
  1016. if (isNew) {
  1017. const newData = {
  1018. name: stdNode.name,
  1019. unit: stdNode.unit,
  1020. };
  1021. newData.code = stdNode.code ? stdNode.code : '';
  1022. newData.is_leaf = (i === len - 1) ? 1 : 0;
  1023. [addResult, node] = await this._addChildNodeData(options, node, newData);
  1024. } else {
  1025. const parent = node;
  1026. const condition = this._.cloneDeep(options);
  1027. condition.code = stdNode.code;
  1028. condition.name = stdNode.name;
  1029. node = await this.getDataByCondition(condition);
  1030. if (!node) {
  1031. // let children = await this.getChildrenByParentId(options, parent[this.setting.pid]);
  1032. // if (children.length === 0) {
  1033. // throw '原台账节点为子项时不能添加它的子项';
  1034. // }
  1035. isNew = true;
  1036. const newData = {
  1037. name: stdNode.name,
  1038. unit: stdNode.unit,
  1039. };
  1040. newData.code = stdNode.code ? stdNode.code : '';
  1041. newData.is_leaf = (i === len - 1) ? 1 : 0;
  1042. [addResult, node] = await this._addChildAutoOrder(options, parent, newData);
  1043. if (parent && parent.is_leaf) {
  1044. await this.transaction.update(this.tableName, { id: parent.id, is_leaf: 0 });
  1045. updateParent = parent;
  1046. }
  1047. firstNew = node;
  1048. } else {
  1049. expandIds.push(node[this.setting.pid]);
  1050. }
  1051. }
  1052. }
  1053. await this.transaction.commit();
  1054. } catch (err) {
  1055. await this.transaction.rollback();
  1056. throw err;
  1057. }
  1058. // 查询应返回的结果
  1059. let createData = [],
  1060. updateData = [];
  1061. if (firstNew) {
  1062. createData = await this.getDataByFullPath(options, firstNew[this.setting.fullPath] + '%');
  1063. updateData = await this.getNextsData(options, firstNew[this.setting.pid], firstNew[this.setting.order]);
  1064. if (updateParent) {
  1065. updateData.push(await this.getDataByCondition({ id: updateParent.id }));
  1066. }
  1067. }
  1068. return { create: createData, update: updateData };
  1069. }
  1070. /**
  1071. * 根据 父节点id 获取子节点
  1072. * @param tenderId
  1073. * @param nodeId
  1074. * @return {Promise<*>}
  1075. */
  1076. async getChildrenByParentId(options, pid) {
  1077. const sql = 'SELECT * FROM ?? WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.pid + ' = ? ORDER BY `order` ASC';
  1078. const sqlParam = [this.tableName, pid];
  1079. const data = await this.db.query(sql, sqlParam);
  1080. const sql1 = 'SELECT * FROM ?? WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.pid + ' = ? ORDER BY `order` ASC';
  1081. const sqlParam1 = [this.ctx.service.contract.tableName, pid];
  1082. const data1 = await this.db.query(sql1, sqlParam1);
  1083. // data和data1合并且按order排序
  1084. const resultData = data.concat(data1).sort((a, b) => a.order - b.order);
  1085. return resultData;
  1086. }
  1087. /**
  1088. * 根据parentData, data新增数据(新增为parentData的最后一个子项)
  1089. * @param {Number} tenderId - 标段id
  1090. * @param {Object} parentData - 父项数据
  1091. * @param {Object} data - 新增节点,初始数据
  1092. * @return {Promise<*>} - 新增结果
  1093. * @private
  1094. */
  1095. async _addChildNodeData(options, parentData, data) {
  1096. if (!data) {
  1097. data = {};
  1098. }
  1099. const pid = parentData ? parentData[this.setting.kid] : rootId;
  1100. const maxId = await this._getMaxLid(options);
  1101. data.id = this.uuid.v4();
  1102. data[this.setting.spid] = options.spid || null;
  1103. data[this.setting.pid] = pid;
  1104. data[this.setting.kid] = maxId + 1;
  1105. data[this.setting.type] = options[this.setting.type];
  1106. data[this.setting.mid] = options.tid || null;
  1107. data[this.setting.level] = parentData ? parentData[this.setting.level] + 1 : 1;
  1108. if (data[this.setting.order] === undefined) {
  1109. data[this.setting.order] = 1;
  1110. }
  1111. data.full_path = parentData ? parentData.full_path + '-' + data[this.setting.kid] : '' + data[this.setting.kid];
  1112. if (data[this.setting.isLeaf] === undefined) {
  1113. data[this.setting.isLeaf] = true;
  1114. }
  1115. const result = await this.transaction.insert(this.tableName, data);
  1116. this._cacheMaxLid(options, maxId + 1);
  1117. return [result, data];
  1118. }
  1119. /**
  1120. * 根据parentData, data新增数据(自动排序)
  1121. * @param tenderId
  1122. * @param parentData
  1123. * @param data
  1124. * @return {Promise<void>}
  1125. * @private
  1126. */
  1127. async _addChildAutoOrder(options, parentData, data) {
  1128. const self = this;
  1129. const findPreData = function(list, a) {
  1130. if (!list || list.length === 0) { return null; }
  1131. for (let i = 0, iLen = list.length; i < iLen; i++) {
  1132. if (billsUtils.compareCode(list[i].code, a.code) > 0) {
  1133. return i > 0 ? list[i - 1] : null;
  1134. }
  1135. }
  1136. return list[list.length - 1];
  1137. };
  1138. const pid = parentData ? parentData[this.setting.kid] : rootId;
  1139. const children = await this.getChildrenByParentId(options, pid);
  1140. const preData = findPreData(children, data);
  1141. if (!preData || children.indexOf(preData) < children.length - 1) {
  1142. await this._updateChildrenOrder(options, pid, preData ? preData.order + 1 : 1);
  1143. }
  1144. data.order = preData ? preData.order + 1 : 1;
  1145. const [addResult, node] = await this._addChildNodeData(options, parentData, data);
  1146. return [addResult, node];
  1147. }
  1148. }
  1149. return ContractTree;
  1150. };