contract_tree.js 65 KB

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