contract_tree.js 64 KB

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