contract_tree.js 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  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) {
  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 = this._filterUpdateInvalidField(contractNode.id, row)
  179. updateContractDatas.push(updateContractData);
  180. continue;
  181. }
  182. throw '提交数据错误';
  183. }
  184. const updateData = this._filterUpdateInvalidField(updateNode.id, 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. } else {
  356. await transaction.delete(this.tableName, { id: select.id });
  357. const delOptions = this._.cloneDeep(options);
  358. delOptions.contract_id = this._.map(deleteData, 'contract_id');
  359. await transaction.delete(this.ctx.service.contractTreeAudit.tableName, delOptions);
  360. const contracts = this.ctx.helper._.filter(deleteData, function (item) {
  361. return item.c_code;
  362. });
  363. if (contracts.length > 0) {
  364. const contractUids = this.ctx.helper._.uniq(this.ctx.helper._.map(contracts, 'uid'));
  365. if (contractUids.length > 1 || !(contractUids[0] === this.ctx.session.sessionUser.accountId || this.ctx.session.sessionUser.is_admin)) throw '存在合同你无权删除';
  366. const contractPays = await transaction.select(this.ctx.service.contractPay.tableName, { where: { cid: this.ctx.helper._.map(contracts, 'id') } });
  367. if (contractPays.length > 0) throw '还存在合同支付项,无法删除';
  368. const attList = await this.ctx.service.contractAtt.getAllDataByCondition({ where: { cid: this.ctx.helper._.map(contracts, 'id') } });
  369. await this.ctx.helper.delFiles(attList);
  370. await transaction.delete(this.ctx.service.contractAtt.tableName, { cid: this.ctx.helper._.map(contracts, 'id') });
  371. }
  372. const operate = await this._deletePosterity(options, select, transaction);
  373. }
  374. // 选中节点--父节点 只有一个子节点时,应升级isLeaf
  375. if (parent) {
  376. const condition = { ...options };
  377. condition[this.setting.pid] = select[this.setting.pid];
  378. const count = await this.db.count(this.tableName, condition);
  379. const count1 = await this.db.count(this.ctx.service.contract.tableName, condition);
  380. const sum = count + count1;
  381. if (sum === 1) {
  382. const updateParent = {id: parent.id };
  383. updateParent[this.setting.isLeaf] = true;
  384. await transaction.update(this.tableName, updateParent);
  385. }
  386. }
  387. // 选中节点--全部后节点 order--
  388. await this._updateChildrenOrder(options, select[this.setting.pid], select[this.setting.order] + 1, -1, transaction);
  389. await transaction.commit();
  390. } catch (err) {
  391. await transaction.rollback();
  392. throw err;
  393. }
  394. // 查询结果
  395. const updateData = await this.getNextsData(options, select[this.setting.pid], select[this.setting.order] - 1);
  396. if (parent) {
  397. const updateData1 = await this.getDataByKid(options, select[this.setting.pid]);
  398. if (updateData1[this.setting.isLeaf]) {
  399. updateData.push(updateData1);
  400. }
  401. }
  402. return { delete: deleteData, update: updateData };
  403. }
  404. async deleteNodes(options, kid, count) {
  405. const _ = this.ctx.helper._;
  406. if ((kid <= 0) || (count <= 0)) return [];
  407. const selects = await this.getDataByKidAndCount(options, kid, count);
  408. const first = selects[0];
  409. const parent = await this.getDataByKid(options, first[this.setting.pid]);
  410. const condition = { ...options };
  411. condition[this.setting.pid] = parent[this.setting.kid];
  412. const childCount1 = parent ? await this.count(condition) : -1;
  413. const childCount2 = parent ? await this.db.count(this.ctx.service.contract.tableName, condition) : -1;
  414. const childCount = childCount1 + childCount2;
  415. let deleteData = [];
  416. for (const s of selects) {
  417. deleteData = deleteData.concat(await this.getDataByFullPath(options, s[this.setting.fullPath] + '-%'));
  418. deleteData.push(s);
  419. }
  420. const transaction = await this.db.beginTransaction();
  421. try {
  422. // 删除
  423. for (const s of selects) {
  424. if (s.c_code) {
  425. if (s.uid !== this.ctx.session.sessionUser.accountId && !this.ctx.session.sessionUser.is_admin) throw '存在合同你无权删除';
  426. const contractPays = await this.ctx.service.contractPay.getDataByCondition({ cid: s.id });
  427. if (contractPays) throw '部分合同还存在合同支付项,无法删除';
  428. await transaction.delete(this.ctx.service.contract.tableName, { id: s.id });
  429. const attList = await this.ctx.service.contractAtt.getAllDataByCondition({ where: { cid: s.id } });
  430. await this.ctx.helper.delFiles(attList);
  431. await transaction.delete(this.ctx.service.contractAtt.tableName, { cid: s.id });
  432. } else {
  433. await transaction.delete(this.tableName, { id: s.id });
  434. const contracts = _.filter(deleteData, function (item) {
  435. return item.c_code && _.includes(s.full_path, item.full_path);
  436. });
  437. if (contracts.length > 0) {
  438. const contractUids = _.uniq(_.map(contracts, 'uid'));
  439. if (contractUids.length > 1 || !(contractUids[0] === this.ctx.session.sessionUser.accountId || this.ctx.session.sessionUser.is_admin)) throw '存在合同你无权删除';
  440. const contractPays = await transaction.select(this.ctx.service.contractPay.tableName, { where: { cid: _.map(contracts, 'id') } });
  441. if (contractPays.length > 0) throw '还存在合同支付项,无法删除';
  442. const attList = await this.ctx.service.contractAtt.getAllDataByCondition({ where: { cid: _.map(contracts, 'id') } });
  443. await this.ctx.helper.delFiles(attList);
  444. await transaction.delete(this.ctx.service.contractAtt.tableName, { cid: _.map(contracts, 'id') });
  445. }
  446. }
  447. const operate = await this._deletePosterity(options, s, transaction);
  448. }
  449. // 选中节点--父节点 只有一个子节点时,应升级isLeaf
  450. if (parent && childCount === count) {
  451. const updateParent = {id: parent.id };
  452. updateParent[this.setting.isLeaf] = true;
  453. await transaction.update(this.tableName, updateParent);
  454. }
  455. // 选中节点--全部后节点 order--
  456. await this._updateChildrenOrder(options, first[this.setting.pid], first[this.setting.order] + count, -count, transaction);
  457. const delOptions = this._.cloneDeep(options);
  458. delOptions.contract_id = this._.map(deleteData, 'contract_id');
  459. await transaction.delete(this.ctx.service.contractTreeAudit.tableName, delOptions);
  460. await transaction.commit();
  461. } catch (err) {
  462. await transaction.rollback();
  463. throw err;
  464. }
  465. const updateData = await this.getNextsData(options, first[this.setting.pid], first[this.setting.order] - 1);
  466. if (parent && childCount === count) {
  467. const updateData1 = await this.getDataByKid(options, parent[this.setting.kid]);
  468. updateData.push(updateData1);
  469. }
  470. return { delete: deleteData, update: updateData };
  471. }
  472. async delete(options, kid, count = null) {
  473. if (count && count > 1) {
  474. return await this.deleteNodes(options, kid, count);
  475. } else {
  476. return await this.deleteNode(options, kid);
  477. }
  478. }
  479. /**
  480. * 上移节点
  481. *
  482. * @param {Number} mid - master id
  483. * @param {Number} kid - 选中节点id
  484. * @return {Array} - 发生改变的数据
  485. */
  486. async upMoveNode(options, kid, count) {
  487. if (!count) count = 1;
  488. if (!kid || (kid <= 0)) return null;
  489. const selects = await this.getDataByKidAndCount(options, kid, count);
  490. if (selects.length !== count) throw '上移节点数据错误';
  491. const first = selects[0];
  492. const pre = await this.getDataByParentAndOrder(options, first[this.setting.pid], first[this.setting.order] - 1);
  493. if (!pre) throw '节点不可上移';
  494. const order = [];
  495. const transaction = await this.db.beginTransaction();
  496. try {
  497. for (const s of selects) {
  498. const sData = { id: s.id };
  499. sData[this.setting.order] = s[this.setting.order] - 1;
  500. !s.c_code ? await transaction.update(this.tableName, sData) : await transaction.update(this.ctx.service.contract.tableName, sData);
  501. order.push(s[this.setting.order] - 1);
  502. }
  503. const pData = { id: pre.id };
  504. pData[this.setting.order] = pre[this.setting.order] + count;
  505. !pre.c_code ? await transaction.update(this.tableName, pData) : await transaction.update(this.ctx.service.contract.tableName, pData);
  506. order.push(pre[this.setting.order] + count);
  507. await transaction.commit();
  508. } catch (err) {
  509. await transaction.rollback();
  510. throw err;
  511. }
  512. const resultData = await this.getDataByParentAndOrder(options, first[this.setting.pid], order);
  513. return { update: resultData };
  514. }
  515. /**
  516. * 下移节点
  517. *
  518. * @param {Number} mid - master id
  519. * @param {Number} kid - 选中节点id
  520. * @return {Array} - 发生改变的数据
  521. */
  522. async downMoveNode(options, kid, count) {
  523. if (!count) count = 1;
  524. if (!kid || (kid <= 0)) return null;
  525. const selects = await this.getDataByKidAndCount(options, kid, count);
  526. if (selects.length !== count) {
  527. throw '下移节点数据错误';
  528. }
  529. const last = selects[count - 1];
  530. const next = await this.getDataByParentAndOrder(options, last[this.setting.pid], last[this.setting.order] + 1);
  531. if (!next) {
  532. throw '节点不可下移';
  533. }
  534. const order = [];
  535. const transaction = await this.db.beginTransaction();
  536. try {
  537. for (const s of selects) {
  538. const sData = { id: s.id };
  539. sData[this.setting.order] = s[this.setting.order] + 1;
  540. !s.c_code ? await transaction.update(this.tableName, sData) : await transaction.update(this.ctx.service.contract.tableName, sData);
  541. order.push(s[this.setting.order] + 1);
  542. }
  543. const nData = { id: next.id };
  544. nData[this.setting.order] = next[this.setting.order] - count;
  545. !next.c_code ? await transaction.update(this.tableName, nData) : await transaction.update(this.ctx.service.contract.tableName, nData);
  546. order.push(next[this.setting.order] - count);
  547. await transaction.commit();
  548. } catch (err) {
  549. await transaction.rollback();
  550. throw err;
  551. }
  552. const resultData = await this.getDataByParentAndOrder(options, last[this.setting.pid], order);
  553. return { update: resultData };
  554. }
  555. /**
  556. * 升级节点
  557. *
  558. * @param {Number} tenderId - 标段id
  559. * @param {Number} selectId - 选中节点id
  560. * @return {Array} - 发生改变的数据
  561. */
  562. async upLevelNode(options, kid, count) {
  563. if (!count) count = 1;
  564. const selects = await this.getDataByKidAndCount(options, kid, count);
  565. if (selects.length !== count) throw '升级节点数据错误';
  566. if (this._.findIndex(selects, function (item) {
  567. return item.c_code;
  568. }) !== -1) {
  569. throw '存在合同节点不可升级';
  570. }
  571. const first = selects[0], last = selects[count - 1];
  572. const parent = await this.getDataByKid(options, first[this.setting.pid]);
  573. if (!parent) throw '升级节点数据错误';
  574. const newPath = [];
  575. const transaction = await this.db.beginTransaction();
  576. try {
  577. // 选中节点--父节点 选中节点为firstChild时,修改isLeaf
  578. if (first[this.setting.order] === 1) {
  579. const updateParentData = { id: parent.id };
  580. updateParentData[this.setting.isLeaf] = true;
  581. await transaction.update(this.tableName, updateParentData);
  582. }
  583. // 选中节点--父节点--全部后兄弟节点 order+1
  584. await this._updateChildrenOrder(options, parent[this.setting.pid], parent[this.setting.order] + 1, count, transaction);
  585. for (const [i, s] of selects.entries()) {
  586. // 选中节点 修改pid, order, fullPath, level, isLeaf, 清空计算项
  587. const updateData = { id: s.id };
  588. updateData[this.setting.pid] = parent[this.setting.pid];
  589. updateData[this.setting.order] = parent[this.setting.order] + i + 1;
  590. updateData[this.setting.level] = s[this.setting.level] - 1;
  591. updateData[this.setting.fullPath] = s[this.setting.fullPath].replace(`-${s[this.setting.pid]}-`, '-');
  592. newPath.push(updateData[this.setting.fullPath]);
  593. if (s[this.setting.isLeaf] && s.id === last.id) {
  594. const nexts = await this.getNextsData(options, parent[this.setting.kid], last[this.setting.order]);
  595. if (nexts.length > 0) {
  596. updateData[this.setting.isLeaf] = false;
  597. }
  598. }
  599. await transaction.update(this.tableName, updateData);
  600. // 选中节点--全部子节点(含孙) level-1, fullPath变更
  601. await this._syncUplevelChildren(options, s, transaction);
  602. }
  603. // 选中节点--全部后兄弟节点 收编为子节点 修改pid, order, fullPath
  604. await this._syncUpLevelNexts(options, last, transaction);
  605. await transaction.commit();
  606. } catch (err) {
  607. await transaction.rollback();
  608. throw err;
  609. }
  610. // 查询修改的数据
  611. let updateData = await this.getNextsData(options, parent[this.setting.pid], parent[this.setting.order] - 1);
  612. for (const path of newPath) {
  613. const children = await this.getDataByFullPath(options, path + '-%');
  614. updateData = updateData.concat(children);
  615. }
  616. return { update: updateData };
  617. }
  618. /**
  619. * 降级节点
  620. *
  621. * @param {Number} tenderId - 标段id
  622. * @param {Number} selectId - 选中节点id
  623. * @return {Array} - 发生改变的数据
  624. */
  625. async downLevelNode(options, kid, count) {
  626. if (!count) count = 1;
  627. const selects = await this.getDataByKidAndCount(options, kid, count);
  628. if (!selects) throw '降级节点数据错误';
  629. // if (this._.findIndex(selects, function (item) {
  630. // return item.c_code;
  631. // }) !== -1) {
  632. // throw '存在合同节点不可降级';
  633. // }
  634. const first = selects[0], last = selects[count - 1];
  635. const pre = await this.getDataByParentAndOrder(options, first[this.setting.pid], first[this.setting.order] - 1);
  636. if (!pre) throw '节点不可降级';
  637. const preLastChild = await this.getLastChildData(options, pre[this.setting.kid]);
  638. const newPath = [];
  639. const transaction = await this.db.beginTransaction();
  640. try {
  641. // 选中节点--全部后节点 order--
  642. await this._updateChildrenOrder(options, first[this.setting.pid], last[this.setting.order] + 1, -count, transaction);
  643. for (const [i, s] of selects.entries()) {
  644. // 选中节点 修改pid, level, order, fullPath
  645. const updateData = { id: s.id };
  646. updateData[this.setting.pid] = pre[this.setting.kid];
  647. updateData[this.setting.order] = preLastChild ? preLastChild[this.setting.order] + i + 1 : i + 1;
  648. updateData[this.setting.level] = s[this.setting.level] + 1;
  649. if (s[this.setting.level] === 1) {
  650. updateData[this.setting.fullPath] = pre[this.setting.kid] + '-' + s[this.setting.kid];
  651. } else {
  652. const index = s[this.setting.fullPath].lastIndexOf(s[this.setting.kid]);
  653. updateData[this.setting.fullPath] = s[this.setting.fullPath].substring(0, index-1) + '-' + pre[this.setting.kid] + '-' + s[this.setting.kid];
  654. }
  655. newPath.push(updateData[this.setting.fullPath]);
  656. s.c_code ? await transaction.update(this.ctx.service.contract.tableName, updateData) : await transaction.update(this.tableName, updateData);
  657. // 选中节点--全部子节点(含孙) level++, fullPath
  658. await this._syncDownlevelChildren(options, s, updateData[this.setting.fullPath], transaction);
  659. }
  660. // 选中节点--前兄弟节点 isLeaf应为false, 清空计算相关字段
  661. const updateData2 = { id: pre.id };
  662. updateData2[this.setting.isLeaf] = false;
  663. await transaction.update(this.tableName, updateData2);
  664. await transaction.commit();
  665. } catch (err) {
  666. await transaction.rollback();
  667. throw err;
  668. }
  669. // 查询修改的数据
  670. let updateData = await this.getNextsData(options, pre[this.setting.pid], pre[this.setting.order] - 1);
  671. // 选中节点及子节点
  672. for (const p of newPath) {
  673. updateData = updateData.concat(await this.getDataByFullPath(options, p + '-%'));
  674. }
  675. const contractSelects = selects.filter(x => x.c_code);
  676. const treeSelects = selects.filter(x => !x.c_code);
  677. if (treeSelects.length > 0) updateData = updateData.concat(await this.getDataById(treeSelects.map(x => { return x.id; })));
  678. if (contractSelects.length > 0) updateData = updateData.concat(await this.ctx.service.contract.getDataById(contractSelects.map(x => { return x.id; })));
  679. // 选中节点--原前兄弟节点&全部后兄弟节点
  680. return { update: updateData };
  681. }
  682. async pasteBlockData(options, kid, pasteData, defaultData) {
  683. if (!options[this.setting.type]) throw '参数有误';
  684. if (!pasteData || pasteData.length <= 0) throw '复制数据错误';
  685. for (const pd of pasteData) {
  686. if (!pd || pd.length <= 0) throw '复制数据错误';
  687. pd.sort(function (x, y) {
  688. return x.level - y.level
  689. });
  690. if (pd[0].contract_pid !== pasteData[0][0].contract_pid) throw '复制数据错误:仅可操作同层节点';
  691. }
  692. const selectData = await this.getDataByKid(options, kid);
  693. if (!selectData) throw '粘贴数据错误';
  694. const newParentPath = selectData.full_path.replace(selectData.contract_id, '');
  695. const pasteBillsData = [];
  696. let maxId = await this._getMaxLid(options);
  697. for (const [i, pd] of pasteData.entries()) {
  698. for (const d of pd) {
  699. d.children = pd.filter(function (x) {
  700. return x.contract_pid === d.contract_id;
  701. });
  702. }
  703. const pbd = [];
  704. for (const [j, d] of pd.entries()) {
  705. const newBills = {
  706. id: this.uuid.v4(),
  707. spid: options.spid || null,
  708. tid: options.tid || null,
  709. contract_type: options.contract_type,
  710. contract_id: maxId + j + 1,
  711. contract_pid: j === 0 ? selectData.contract_pid : d.contract_pid,
  712. level: d.level + selectData.level - pd[0].level,
  713. order: j === 0 ? selectData.order + i + 1 : d.order,
  714. is_leaf: d.is_leaf,
  715. code: d.code,
  716. name: d.name,
  717. remark: d.remark,
  718. };
  719. for (const c of d.children) {
  720. c.contract_pid = newBills.contract_id;
  721. }
  722. pbd.push(newBills);
  723. }
  724. for (const d of pbd) {
  725. const parent = pbd.find(function (x) {
  726. return x.contract_id === d.contract_pid;
  727. });
  728. d.full_path = parent
  729. ? parent.full_path + '-' + d.contract_id
  730. : newParentPath + d.contract_id;
  731. if (defaultData) this.ctx.helper._.assignIn(pbd, defaultData);
  732. pasteBillsData.push(d);
  733. }
  734. maxId = maxId + pbd.length;
  735. }
  736. const transaction = await this.db.beginTransaction();
  737. try {
  738. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  739. await this._updateChildrenOrder(options, selectData.ledger_pid, selectData.order + 1, pasteData.length, transaction);
  740. // 数据库创建新增节点数据
  741. if (pasteBillsData.length > 0) {
  742. const newData = await transaction.insert(this.tableName, pasteBillsData);
  743. }
  744. this._cacheMaxLid(options, maxId);
  745. await transaction.commit();
  746. } catch (err) {
  747. await transaction.rollback();
  748. throw err;
  749. }
  750. // 查询应返回的结果
  751. const updateData = await this.getNextsData(options, selectData.contract_pid, selectData.order + pasteData.length);
  752. return {
  753. ledger: { create: pasteBillsData, update: updateData },
  754. };
  755. }
  756. /**
  757. * 删除节点
  758. * @param {Number} tenderId - 标段id
  759. * @param {Object} deleteData - 删除节点数据
  760. * @return {Promise<*>}
  761. * @private
  762. */
  763. async _deletePosterity(options, node, transaction = null) {
  764. const sql = 'DELETE FROM ?? WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.fullPath + ' LIKE ?';
  765. const sqlParam = [this.tableName, node[this.setting.fullPath] + '-%'];
  766. const result = transaction ? await transaction.query(sql, sqlParam) : await this.db.query(sql, sqlParam)
  767. const sql1 = 'DELETE FROM ?? WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.fullPath + ' LIKE ?';
  768. const sqlParam1 = [this.ctx.service.contract.tableName, node[this.setting.fullPath] + '-%'];
  769. const result1 = transaction ? await transaction.query(sql1, sqlParam1) : await this.db.query(sql1, sqlParam1)
  770. return result;
  771. }
  772. /**
  773. * 根据fullPath获取数据 fullPath Like ‘1.2.3%’(传参fullPath = '1.2.3%')
  774. * @param {Number} tenderId - 标段id
  775. * @param {String} fullPath - 路径
  776. * @return {Promise<void>}
  777. */
  778. async getDataByFullPath(options, fullPath) {
  779. const sql = 'SELECT * FROM ?? WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.fullPath + ' LIKE ?';
  780. const sqlParam = [this.tableName, fullPath];
  781. const resultData = await this.db.query(sql, sqlParam);
  782. const sql1 = 'SELECT * FROM ?? WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.fullPath + ' LIKE ?';
  783. const sqlParam1 = [this.ctx.service.contract.tableName, fullPath];
  784. const resultData1 = await this.db.query(sql1, sqlParam1);
  785. return resultData.concat(resultData1).sort((a, b) => a.order - b.order);
  786. }
  787. async getChildBetween(options, pid, order1, order2) {
  788. const sql = 'SELECT * FROM ?? WHERE '+ this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.pid + ' = ? AND `order` > ? AND `order` < ? ORDER BY `order` ASC';
  789. const sqlParam = [this.tableName, pid, order1, order2];
  790. const data = await this.db.query(sql, sqlParam);
  791. const sql1 = 'SELECT * FROM ?? WHERE '+ this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.pid + ' = ? AND `order` > ? AND `order` < ? ORDER BY `order` ASC';
  792. const sqlParam1 = [this.ctx.service.contract.tableName, pid, order1, order2];
  793. const data1 = await this.db.query(sql1, sqlParam1);
  794. const resultData = data.concat(data1).sort((a, b) => a.order - b.order);
  795. return resultData;
  796. }
  797. /**
  798. * 根据 父节点ID 和 节点排序order 获取全部后节点数据
  799. * @param {Number} mid - master id
  800. * @param {Number} pid - 父节点id
  801. * @param {Number} order - 排序
  802. * @return {Array}
  803. */
  804. async getNextsData(options, pid, order) {
  805. const sql = 'SELECT * FROM ?? WHERE '+ this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.pid + ' = ? AND `order` > ? ORDER BY `order` ASC';
  806. const sqlParam = [this.tableName, pid, order];
  807. const data = await this.db.query(sql, sqlParam);
  808. const sql1 = 'SELECT * FROM ?? WHERE '+ this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.pid + ' = ? AND `order` > ? ORDER BY `order` ASC';
  809. const sqlParam1 = [this.ctx.service.contract.tableName, pid, order];
  810. const data1 = await this.db.query(sql1, sqlParam1);
  811. // data和data1合并且按order排序
  812. const resultData = data.concat(data1).sort((a, b) => a.order - b.order);
  813. return resultData;
  814. }
  815. /**
  816. * 获取最末的子节点
  817. * @param {Number} mid - masterId
  818. * @param {Number} pid - 父节点id
  819. * @return {Object}
  820. */
  821. async getLastChildData(options, pid, transaction = null) {
  822. const sql = 'SELECT * FROM ?? WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.pid + ' = ? ORDER BY `order` DESC';
  823. const sqlParam = [this.tableName, pid];
  824. const resultData = await this.db.queryOne(sql, sqlParam);
  825. const sql1 = 'SELECT * FROM ?? WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.pid + ' = ? ORDER BY `order` DESC';
  826. const sqlParam1 = [this.ctx.service.contract.tableName, pid];
  827. const resultData1 = await this.db.queryOne(sql1, sqlParam1);
  828. // 比较两个结果,返回order大的
  829. if (resultData && resultData1) {
  830. return resultData.order > resultData1.order ? resultData : resultData1;
  831. } else {
  832. return resultData || resultData1;
  833. }
  834. }
  835. /**
  836. * 选中节点的后兄弟节点,全部变为当前节点的子节点
  837. * @param {Object} selectData - 选中节点
  838. * @return {Object}
  839. * @private
  840. */
  841. async _syncUpLevelNexts(options, select, transaction = null) {
  842. // 查询selectData的lastChild
  843. const lastChild = await this.getLastChildData(options, select[this.setting.kid]);
  844. const nexts = await this.getNextsData(options, select[this.setting.pid], select[this.setting.order]);
  845. if (this._.findIndex(nexts, function (item) {
  846. return item.c_code;
  847. }) !== -1) {
  848. throw '存在合同节点不可升级';
  849. }
  850. if (nexts && nexts.length > 0) {
  851. // 修改nextsData pid, 排序
  852. // this.initSqlBuilder();
  853. // this.sqlBuilder.setUpdateData(this.setting.pid, {
  854. // value: select[this.setting.kid],
  855. // });
  856. // const orderInc = lastChild ? lastChild[this.setting.order] - select[this.setting.order] : - select[this.setting.order];
  857. // this.sqlBuilder.setUpdateData(this.setting.order, {
  858. // value: Math.abs(orderInc),
  859. // selfOperate: orderInc > 0 ? '+' : '-',
  860. // });
  861. // this.sqlBuilder.setAndWhere(this.setting.mid, {
  862. // value: select[this.setting.mid],
  863. // operate: '=',
  864. // });
  865. // this.sqlBuilder.setAndWhere(this.setting.pid, {
  866. // value: select[this.setting.pid],
  867. // operate: '=',
  868. // });
  869. // this.sqlBuilder.setAndWhere(this.setting.order, {
  870. // value: select[this.setting.order],
  871. // operate: '>',
  872. // });
  873. // const [sql1, sqlParam1] = this.sqlBuilder.build(this.tableName, 'update');
  874. const orderInc = lastChild ? lastChild[this.setting.order] - select[this.setting.order] : - select[this.setting.order];
  875. 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 + '` > ?';
  876. const sqlParam1 = [this.tableName, select[this.setting.pid], select[this.setting.order]];
  877. transaction ? await transaction.query(sql1, sqlParam1) : await this.db.query(sql1, sqlParam1);
  878. // 选中节点 isLeaf应为false
  879. if (select[this.setting.isLeaf]) {
  880. const updateData = { id: select.id };
  881. updateData[this.setting.isLeaf] = false;
  882. transaction ? await transaction.update(this.tableName, updateData) : await this.db.update(this.tableName, updateData);
  883. }
  884. // 修改nextsData及其子节点的fullPath
  885. const oldSubStr = this.db.escape(select[this.setting.pid] + '-');
  886. const newSubStr = this.db.escape(select[this.setting.kid] + '-');
  887. const sqlArr = [];
  888. sqlArr.push('Update ?? SET `' + this.setting.fullPath + '` = Replace(`' + this.setting.fullPath + '`,' + oldSubStr + ',' + newSubStr + ') Where ');
  889. sqlArr.push(this.ctx.helper._getOptionsSql(options));
  890. sqlArr.push(' And (');
  891. for (const data of nexts) {
  892. sqlArr.push('`' + this.setting.fullPath + '` Like ' + this.db.escape(data[this.setting.fullPath] + '%'));
  893. if (nexts.indexOf(data) < nexts.length - 1) {
  894. sqlArr.push(' Or ');
  895. }
  896. }
  897. sqlArr.push(')');
  898. const sql = sqlArr.join('');
  899. const resultData = transaction ? await transaction.query(sql, [this.tableName]) : await this.db.query(sql, [this.tableName]);
  900. transaction ? await transaction.query(sql, [this.ctx.service.contract.tableName]) : await this.db.query(sql, [this.ctx.service.contract.tableName]);
  901. return resultData;
  902. }
  903. }
  904. /**
  905. * 升级selectData, 同步修改所有子节点
  906. * @param {Object} selectData - 升级操作,选中节点
  907. * @return {Object}
  908. * @private
  909. */
  910. async _syncUplevelChildren(options, select, transaction = null) {
  911. // const children = await this.getDataByFullPath(options, select[this.setting.fullPath] + '-%');
  912. // if (this._.findIndex(children, function (item) {
  913. // return item.c_code;
  914. // }) !== -1) {
  915. // throw '存在合同节点不可升级';
  916. // }
  917. // this.initSqlBuilder();
  918. // this.sqlBuilder.setAndWhere(this.setting.mid, {
  919. // value: select[this.setting.mid],
  920. // operate: '=',
  921. // });
  922. // this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  923. // value: this.db.escape(select[this.setting.fullPath] + '-%'),
  924. // operate: 'like',
  925. // });
  926. // this.sqlBuilder.setUpdateData(this.setting.level, {
  927. // value: 1,
  928. // selfOperate: '-',
  929. // });
  930. // this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  931. // value: [this.setting.fullPath, this.db.escape(`-${select[this.setting.pid]}-`), this.db.escape('-')],
  932. // literal: 'Replace',
  933. // });
  934. // const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  935. const sql = 'UPDATE ?? SET ' + this.setting.level + ' = ' + this.setting.level + ' -1, ' + this.setting.fullPath + ' = ' +
  936. 'Replace('+ [this.setting.fullPath, this.db.escape(`-${select[this.setting.pid]}-`), this.db.escape('-')].join(',') +') ' +
  937. 'WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.fullPath + ' LIKE ?';
  938. const sqlParam = [this.tableName, select[this.setting.fullPath] + '-%'];
  939. const data = transaction ? await transaction.query(sql, sqlParam) : await this.db.query(sql, sqlParam);
  940. 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] + '-%']);
  941. return data;
  942. }
  943. /**
  944. * 降级selectData, 同步修改所有子节点
  945. * @param {Object} selectData - 选中节点
  946. * @param {Object} preData - 选中节点的前一节点(降级后为父节点)
  947. * @return {Promise<*>}
  948. * @private
  949. */
  950. async _syncDownlevelChildren(options, select, newFullPath, transaction = null) {
  951. // const children = await this.getDataByFullPath(options, select[this.setting.fullPath] + '-%');
  952. // if (this._.findIndex(children, function (item) {
  953. // return item.c_code;
  954. // }) !== -1) {
  955. // throw '存在合同节点不可降级';
  956. // }
  957. // this.initSqlBuilder();
  958. // this.sqlBuilder.setAndWhere(this.setting.mid, {
  959. // value: select[this.setting.mid],
  960. // operate: '=',
  961. // });
  962. // this.sqlBuilder.setAndWhere(this.setting.fullPath, {
  963. // value: this.db.escape(select[this.setting.fullPath] + '-%'),
  964. // operate: 'like',
  965. // });
  966. // this.sqlBuilder.setUpdateData(this.setting.level, {
  967. // value: 1,
  968. // selfOperate: '+',
  969. // });
  970. // this.sqlBuilder.setUpdateData(this.setting.fullPath, {
  971. // value: [this.setting.fullPath, this.db.escape(select[this.setting.fullPath] + '-'), this.db.escape(newFullPath + '-')],
  972. // literal: 'Replace',
  973. // });
  974. // const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  975. const sql = 'UPDATE ?? SET ' + this.setting.level + ' = ' + this.setting.level + ' + 1, ' + this.setting.fullPath + ' = ' +
  976. 'Replace(' + [[this.setting.fullPath, this.db.escape(select[this.setting.fullPath] + '-'), this.db.escape(newFullPath + '-')]].join(',') + ') ' +
  977. 'WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.fullPath + ' LIKE ?';
  978. const sqlParam = [this.tableName, select[this.setting.fullPath] + '-%'];
  979. const data = transaction ? await transaction.query(sql, sqlParam) : await this.db.query(sql, sqlParam);
  980. 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] + '-%']);
  981. return data;
  982. }
  983. /**
  984. * 添加节点,并同步添加父节点
  985. * @param {Number} tenderId - 标段id
  986. * @param {Number} selectId - 选中节点id
  987. * @param {Object} stdData - 节点数据
  988. * @param {StandardLib} stdLib - 标准库
  989. * @return {Promise<void>}
  990. */
  991. async addStdNodeWithParent(options, kid, stdData, stdLib) {
  992. if (!options[this.setting.type]) throw '参数有误';
  993. const select = kid ? await this.getDataByKid(options, kid) : null;
  994. if (!select) throw '新增子节点数据错误';
  995. if (select && select.c_code) throw '合同无法新增子节点';
  996. // 查询完整标准清单,并按层次排序
  997. const fullLevel = await stdLib.getFullLevelDataByFullPath(stdData.list_id, stdData.full_path);
  998. fullLevel.sort(function(x, y) {
  999. return x.level - y.level;
  1000. });
  1001. let isNew = false,
  1002. node,
  1003. firstNew,
  1004. updateParent,
  1005. addResult;
  1006. const expandIds = [];
  1007. this.transaction = await this.db.beginTransaction();
  1008. try {
  1009. // 从最顶层节点依次查询是否存在,否则添加
  1010. for (let i = 0, len = fullLevel.length; i < len; i++) {
  1011. const stdNode = fullLevel[i];
  1012. if (isNew) {
  1013. const newData = {
  1014. name: stdNode.name,
  1015. unit: stdNode.unit,
  1016. };
  1017. newData.code = stdNode.code ? stdNode.code : '';
  1018. newData.is_leaf = (i === len - 1) ? 1 : 0;
  1019. [addResult, node] = await this._addChildNodeData(options, node, newData);
  1020. } else {
  1021. const parent = node;
  1022. const condition = this._.cloneDeep(options);
  1023. condition.code = stdNode.code;
  1024. condition.name = stdNode.name;
  1025. node = await this.getDataByCondition(condition);
  1026. if (!node) {
  1027. // let children = await this.getChildrenByParentId(options, parent[this.setting.pid]);
  1028. // if (children.length === 0) {
  1029. // throw '原台账节点为子项时不能添加它的子项';
  1030. // }
  1031. isNew = true;
  1032. const newData = {
  1033. name: stdNode.name,
  1034. unit: stdNode.unit,
  1035. };
  1036. newData.code = stdNode.code ? stdNode.code : '';
  1037. newData.is_leaf = (i === len - 1) ? 1 : 0;
  1038. [addResult, node] = await this._addChildAutoOrder(options, parent, newData);
  1039. if (parent && parent.is_leaf) {
  1040. await this.transaction.update(this.tableName, { id: parent.id, is_leaf: 0 });
  1041. updateParent = parent;
  1042. }
  1043. firstNew = node;
  1044. } else {
  1045. expandIds.push(node[this.setting.pid]);
  1046. }
  1047. }
  1048. }
  1049. await this.transaction.commit();
  1050. } catch (err) {
  1051. await this.transaction.rollback();
  1052. throw err;
  1053. }
  1054. // 查询应返回的结果
  1055. let createData = [],
  1056. updateData = [];
  1057. if (firstNew) {
  1058. createData = await this.getDataByFullPath(options, firstNew[this.setting.fullPath] + '%');
  1059. updateData = await this.getNextsData(options, firstNew[this.setting.pid], firstNew[this.setting.order]);
  1060. if (updateParent) {
  1061. updateData.push(await this.getDataByCondition({ id: updateParent.id }));
  1062. }
  1063. }
  1064. return { create: createData, update: updateData };
  1065. }
  1066. /**
  1067. * 根据 父节点id 获取子节点
  1068. * @param tenderId
  1069. * @param nodeId
  1070. * @return {Promise<*>}
  1071. */
  1072. async getChildrenByParentId(options, pid) {
  1073. const sql = 'SELECT * FROM ?? WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.pid + ' = ? ORDER BY `order` ASC';
  1074. const sqlParam = [this.tableName, pid];
  1075. const data = await this.db.query(sql, sqlParam);
  1076. const sql1 = 'SELECT * FROM ?? WHERE ' + this.ctx.helper._getOptionsSql(options) + ' AND ' + this.setting.pid + ' = ? ORDER BY `order` ASC';
  1077. const sqlParam1 = [this.ctx.service.contract.tableName, pid];
  1078. const data1 = await this.db.query(sql1, sqlParam1);
  1079. // data和data1合并且按order排序
  1080. const resultData = data.concat(data1).sort((a, b) => a.order - b.order);
  1081. return resultData;
  1082. }
  1083. /**
  1084. * 根据parentData, data新增数据(新增为parentData的最后一个子项)
  1085. * @param {Number} tenderId - 标段id
  1086. * @param {Object} parentData - 父项数据
  1087. * @param {Object} data - 新增节点,初始数据
  1088. * @return {Promise<*>} - 新增结果
  1089. * @private
  1090. */
  1091. async _addChildNodeData(options, parentData, data) {
  1092. if (!data) {
  1093. data = {};
  1094. }
  1095. const pid = parentData ? parentData[this.setting.kid] : rootId;
  1096. const maxId = await this._getMaxLid(options);
  1097. data.id = this.uuid.v4();
  1098. data[this.setting.spid] = options.spid || null;
  1099. data[this.setting.pid] = pid;
  1100. data[this.setting.kid] = maxId + 1;
  1101. data[this.setting.type] = options[this.setting.type];
  1102. data[this.setting.mid] = options.tid || null;
  1103. data[this.setting.level] = parentData ? parentData[this.setting.level] + 1 : 1;
  1104. if (data[this.setting.order] === undefined) {
  1105. data[this.setting.order] = 1;
  1106. }
  1107. data.full_path = parentData ? parentData.full_path + '-' + data[this.setting.kid] : '' + data[this.setting.kid];
  1108. if (data[this.setting.isLeaf] === undefined) {
  1109. data[this.setting.isLeaf] = true;
  1110. }
  1111. const result = await this.transaction.insert(this.tableName, data);
  1112. this._cacheMaxLid(options, maxId + 1);
  1113. return [result, data];
  1114. }
  1115. /**
  1116. * 根据parentData, data新增数据(自动排序)
  1117. * @param tenderId
  1118. * @param parentData
  1119. * @param data
  1120. * @return {Promise<void>}
  1121. * @private
  1122. */
  1123. async _addChildAutoOrder(options, parentData, data) {
  1124. const self = this;
  1125. const findPreData = function(list, a) {
  1126. if (!list || list.length === 0) { return null; }
  1127. for (let i = 0, iLen = list.length; i < iLen; i++) {
  1128. if (billsUtils.compareCode(list[i].code, a.code) > 0) {
  1129. return i > 0 ? list[i - 1] : null;
  1130. }
  1131. }
  1132. return list[list.length - 1];
  1133. };
  1134. const pid = parentData ? parentData[this.setting.kid] : rootId;
  1135. const children = await this.getChildrenByParentId(options, pid);
  1136. const preData = findPreData(children, data);
  1137. if (!preData || children.indexOf(preData) < children.length - 1) {
  1138. await this._updateChildrenOrder(options, pid, preData ? preData.order + 1 : 1);
  1139. }
  1140. data.order = preData ? preData.order + 1 : 1;
  1141. const [addResult, node] = await this._addChildNodeData(options, parentData, data);
  1142. return [addResult, node];
  1143. }
  1144. }
  1145. return ContractTree;
  1146. };