change_apply_audit.js 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date 2018/8/14
  7. * @version
  8. */
  9. const auditConst = require('../const/audit').changeApply;
  10. const auditType = require('../const/audit').auditType;
  11. const pushType = require('../const/audit').pushType;
  12. const pushOperate = require('../const/spec_3f').pushOperate;
  13. const shenpiConst = require('../const/shenpi');
  14. const smsTypeConst = require('../const/sms_type');
  15. const SMS = require('../lib/sms');
  16. const SmsAliConst = require('../const/sms_alitemplate');
  17. const wxConst = require('../const/wechat_template');
  18. module.exports = app => {
  19. class ChangeApplyAudit extends app.BaseService {
  20. /**
  21. * 构造函数
  22. *
  23. * @param {Object} ctx - egg全局变量
  24. * @return {void}
  25. */
  26. constructor(ctx) {
  27. super(ctx);
  28. this.tableName = 'change_apply_audit';
  29. }
  30. /**
  31. * 获取 审核列表信息
  32. *
  33. * @param {Number} caId - 变更立项id
  34. * @param {Number} times - 第几次审批
  35. * @return {Promise<*>}
  36. */
  37. async getAuditors(caId, times = 1, order_sort = 'asc', noYB = false) {
  38. // const sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`, la.`times`, la.`order`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time`, g.`sort` ' +
  39. // 'FROM ?? AS la, ?? AS pa, (SELECT t1.`aid`,(@i:=@i+1) as `sort` FROM (SELECT t.`aid`, t.`order` FROM (select `aid`, `order` from ?? WHERE `caid` = ? AND `times` = ? ORDER BY `order` LIMIT 200) t GROUP BY t.`aid` ORDER BY t.`order`) t1, (select @i:=0) as it) as g ' +
  40. // 'WHERE la.`caid` = ? and la.`times` = ? and la.`aid` = pa.`id` and g.`aid` = la.`aid` order by la.`order`';
  41. // const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, this.tableName, caId, times, caId, times];
  42. // const result = await this.db.query(sql, sqlParam);
  43. // const sql2 = 'SELECT COUNT(a.`aid`) as num FROM (SELECT `aid` FROM ?? WHERE `caid` = ? AND `times` = ? GROUP BY `aid`) as a';
  44. // const sqlParam2 = [this.tableName, caId, times];
  45. // const count = await this.db.queryOne(sql2, sqlParam2);
  46. // for (const i in result) {
  47. // result[i].max_sort = count.num;
  48. // }
  49. const ybSql = noYB ? ' AND la.audit_order != 0' : '';
  50. const sql = 'SELECT la.id, la.aid, la.times, la.order, la.status, la.opinion, la.begin_time, la.end_time, la.audit_type, la.audit_order,' +
  51. ' pa.name, pa.company, pa.role, pa.mobile, pa.telephone' +
  52. ` FROM ${this.tableName} la LEFT JOIN ${this.ctx.service.projectAccount.tableName} pa ON la.aid = pa.id` +
  53. ' WHERE la.caid = ? AND la.times = ?' + ybSql +
  54. ' ORDER BY la.order ' + order_sort;
  55. const sqlParam = [caId, times];
  56. const result = await this.db.query(sql, sqlParam);
  57. const max_sort = this._.max(result.map(x => { return x.audit_order; }));
  58. for (const i in result) {
  59. result[i].max_sort = max_sort;
  60. }
  61. return result;
  62. }
  63. /**
  64. * 获取 当前审核人
  65. *
  66. * @param {Number} caId - 变更立项id
  67. * @param {Number} times - 第几次审批
  68. * @return {Promise<*>}
  69. */
  70. async getCurAuditor(caId, times = 1) {
  71. const sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`, la.`times`, la.`order`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time` ' +
  72. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  73. ' WHERE la.`caid` = ? and la.`status` = ? and la.`times` = ?';
  74. const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, caId, auditConst.status.checking, times];
  75. return await this.db.queryOne(sql, sqlParam);
  76. }
  77. async getCurAuditors(caId, times = 1) {
  78. const sql =
  79. 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`, la.`times`, la.`order`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time`, la.audit_type, la.audit_order ' +
  80. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id`' +
  81. ' WHERE la.`caid` = ? and la.`status` = ? and la.`times` = ?';
  82. const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, caId, auditConst.status.checking, times];
  83. return await this.db.query(sql, sqlParam);
  84. }
  85. /**
  86. * 获取审核人流程列表
  87. *
  88. * @param auditorId
  89. * @return {Promise<*>}
  90. */
  91. async getAuditGroupByList(changeId, times, transaction = false) {
  92. const sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`caid`, la.`aid`, la.`order`, la.`status`, la.audit_type, la.audit_order ' +
  93. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id`' +
  94. ' WHERE la.`caid` = ? and la.`times` = ? and la.`status` != ? and la.`status` != ? GROUP BY la.`aid` ORDER BY la.`order`';
  95. const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, changeId, times, auditConst.status.revise, auditConst.status.cancelRevise];
  96. return transaction !== false ? await transaction.query(sql, sqlParam) : await this.db.query(sql, sqlParam);
  97. }
  98. /**
  99. * 移除审核人
  100. *
  101. * @param {Number} materialId - 材料调差期id
  102. * @param {Number} status - 期状态
  103. * @param {Number} status - 期次数
  104. * @return {Promise<boolean>}
  105. */
  106. async getAuditorByStatus(caId, status, times = 1) {
  107. let auditor = null;
  108. let sql = '';
  109. let sqlParam = '';
  110. switch (status) {
  111. case auditConst.status.checking :
  112. case auditConst.status.checked :
  113. case auditConst.status.revise :
  114. case auditConst.status.cancelRevise :
  115. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`caid`, la.`aid`, la.`order` ' +
  116. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  117. ' WHERE la.`caid` = ? and la.`status` = ? ' +
  118. ' ORDER BY la.`times` desc, la.`order` desc';
  119. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, caId, status];
  120. auditor = await this.db.queryOne(sql, sqlParam);
  121. break;
  122. case auditConst.status.checkNo :
  123. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`caid`, la.`aid`, la.`order` ' +
  124. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id`' +
  125. ' WHERE la.`caid` = ? and la.`status` = ? and la.`times` = ?' +
  126. ' ORDER BY la.`times` desc, la.`order` desc';
  127. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, caId, auditConst.status.checkNo, parseInt(times) - 1];
  128. auditor = await this.db.queryOne(sql, sqlParam);
  129. break;
  130. case auditConst.status.uncheck :
  131. break;
  132. default:break;
  133. }
  134. return auditor;
  135. }
  136. async getAuditorsByStatus(caId, status, times = 1) {
  137. let auditor = [];
  138. let sql = '';
  139. let sqlParam = '';
  140. let cur;
  141. switch (status) {
  142. case auditConst.status.checking :
  143. case auditConst.status.checked :
  144. case auditConst.status.revise :
  145. case auditConst.status.cancelRevise :
  146. cur = await this.db.queryOne('SELECT * From ?? where caid = ? AND times = ? AND status = ? ORDER By times DESC, `order` DESC', [this.tableName, caId, times, status]);
  147. if (!cur) return [];
  148. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`caid`, la.`order`, la.status, la.audit_order, la.audit_type ' +
  149. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  150. ' WHERE la.`caid` = ? and la.`order` = ? and times = ?';
  151. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, caId, cur.order, times];
  152. auditor = await this.db.query(sql, sqlParam);
  153. break;
  154. case auditConst.status.checkNo :
  155. cur = await this.db.queryOne('SELECT * From ?? where caid = ? AND times = ? AND status = ? ORDER By times DESC, `order` DESC', [this.tableName, caId, parseInt(times) - 1, status]);
  156. if (!cur) return [];
  157. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`caid`, la.`order`, la.status, la.audit_order, la.audit_type ' +
  158. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  159. ' WHERE la.`caid` = ? and la.`order` = ? and la.`times` = ?';
  160. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, caId, cur.order, parseInt(times) - 1];
  161. auditor = await this.db.query(sql, sqlParam);
  162. break;
  163. case auditConst.status.uncheck:
  164. default:
  165. break;
  166. }
  167. return auditor;
  168. }
  169. async getLastAudit(caid, times, transaction = null) {
  170. const sql = 'SELECT * FROM ?? WHERE `caid` = ? AND `times` = ? ORDER BY `order` DESC';
  171. const sqlParam = [this.tableName, caid, times];
  172. return transaction ? await transaction.queryOne(sql, sqlParam) : await this.db.queryOne(sql, sqlParam);
  173. }
  174. /**
  175. * 获取审核人流程列表(包括原报)
  176. * @param {Number} materialId 调差id
  177. * @param {Number} times 审核次数
  178. * @return {Promise<Array>} 查询结果集(包括原报)
  179. */
  180. async getAuditorsWithOwner(caId, times = 1) {
  181. const result = await this.getAuditGroupByList(caId, times);
  182. const sql =
  183. 'SELECT pa.`id` As aid, pa.`name`, pa.`company`, pa.`role`, ? As times, ? As caid, 0 As `order`' +
  184. ' FROM ' +
  185. this.ctx.service.changeApply.tableName +
  186. ' As s' +
  187. ' LEFT JOIN ' +
  188. this.ctx.service.projectAccount.tableName +
  189. ' As pa' +
  190. ' ON s.uid = pa.id' +
  191. ' WHERE s.id = ?';
  192. const sqlParam = [times, caId, caId];
  193. const user = await this.db.queryOne(sql, sqlParam);
  194. result.unshift(user);
  195. return result;
  196. }
  197. /**
  198. * 新增审核人
  199. *
  200. * @param {Number} caId - 立项书id
  201. * @param {Number} auditorId - 审核人id
  202. * @param {Number} times - 第几次审批
  203. * @return {Promise<number>}
  204. */
  205. async addAuditor(caId, auditorId, times = 1, is_gdzs = 0) {
  206. const transaction = await this.db.beginTransaction();
  207. let flag = false;
  208. try {
  209. let [newOrder, newAuditOrder] = await this.getNewOrder(caId, times);
  210. // 判断是否存在固定终审,存在则newOrder - 1并使终审order+1
  211. newOrder = is_gdzs === 1 ? newOrder - 1 : newOrder;
  212. newAuditOrder = is_gdzs === 1 ? newAuditOrder - 1 : newAuditOrder;
  213. if (is_gdzs) await this._syncOrderByDelete(transaction, caId, newOrder, times, '+');
  214. const data = {
  215. tid: this.ctx.tender.id,
  216. caid: caId,
  217. aid: auditorId,
  218. times,
  219. order: newOrder,
  220. status: auditConst.status.uncheck,
  221. audit_order: newAuditOrder,
  222. };
  223. const result = await transaction.insert(this.tableName, data);
  224. await transaction.commit();
  225. flag = result.effectRows = 1;
  226. } catch (err) {
  227. await transaction.rollback();
  228. throw err;
  229. }
  230. return flag;
  231. }
  232. /**
  233. * 获取 最新审核顺序
  234. *
  235. * @param {Number} caId - 立项书id
  236. * @param {Number} times - 第几次审批
  237. * @return {Promise<number>}
  238. */
  239. async getNewOrder(caId, times = 1) {
  240. const sql = 'SELECT Max(`order`) As max_order, Max(audit_order) As max_audit_order FROM ?? Where `caid` = ? and `times` = ?';
  241. const sqlParam = [this.tableName, caId, times];
  242. const result = await this.db.queryOne(sql, sqlParam);
  243. return result && result.max_order ? [result.max_order + 1, result.max_audit_order + 1] : [1, 1];
  244. }
  245. /**
  246. * 移除审核人
  247. *
  248. * @param {Number} caId - 变更立项书id
  249. * @param {Number} auditorId - 审核人id
  250. * @param {Number} times - 第几次审批
  251. * @return {Promise<boolean>}
  252. */
  253. async deleteAuditor(caId, auditorId, times = 1) {
  254. const transaction = await this.db.beginTransaction();
  255. try {
  256. const condition = { caid: caId, aid: auditorId, times };
  257. const auditor = await this.getDataByCondition(condition);
  258. if (!auditor) {
  259. throw '该审核人不存在';
  260. }
  261. // 移除整个流程的人
  262. await transaction.delete(this.tableName, { caid: caId, order: auditor.order, times });
  263. await this._syncOrderByDelete(transaction, caId, auditor.order, times);
  264. await transaction.commit();
  265. } catch (err) {
  266. await transaction.rollback();
  267. throw err;
  268. }
  269. return true;
  270. }
  271. /**
  272. * 移除审核人时,同步其后审核人order
  273. * @param transaction - 事务
  274. * @param {Number} caId - 变更立项书id
  275. * @param {Number} auditorId - 审核人id
  276. * @param {Number} times - 第几次审批
  277. * @return {Promise<*>}
  278. * @private
  279. */
  280. async _syncOrderByDelete(transaction, caId, order, times, selfOperate = '-') {
  281. this.initSqlBuilder();
  282. this.sqlBuilder.setAndWhere('caid', {
  283. value: caId,
  284. operate: '=',
  285. });
  286. this.sqlBuilder.setAndWhere('order', {
  287. value: order,
  288. operate: '>=',
  289. });
  290. this.sqlBuilder.setAndWhere('times', {
  291. value: times,
  292. operate: '=',
  293. });
  294. this.sqlBuilder.setUpdateData('order', {
  295. value: 1,
  296. selfOperate,
  297. });
  298. this.sqlBuilder.setUpdateData('audit_order', {
  299. value: 1,
  300. selfOperate,
  301. });
  302. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  303. const data = await transaction.query(sql, sqlParam);
  304. return data;
  305. }
  306. /**
  307. * 开始审批
  308. * @param {Number} caId - 立项书id
  309. * @param {Number} times - 第几次审批
  310. * @return {Promise<boolean>}
  311. */
  312. async start(caId, times = 1) {
  313. const audits = await this.getAllDataByCondition({ where: { caid: caId, times, order: 1 } });
  314. if (audits.length === 0) {
  315. if (this.ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdspl) {
  316. throw '请联系管理员添加审批人';
  317. } else {
  318. throw '请先选择审批人,再上报数据';
  319. }
  320. }
  321. const transaction = await this.db.beginTransaction();
  322. try {
  323. const begin_time = new Date();
  324. const updateData = audits.map(x => { return { id: x.id, status: auditConst.status.checking, begin_time }; });
  325. await transaction.updateRows(this.tableName, updateData);
  326. await transaction.update(this.ctx.service.changeApply.tableName, {
  327. id: caId, status: auditConst.status.checking,
  328. });
  329. // 微信模板通知
  330. const wechatData = {
  331. type: 'apply',
  332. status: wxConst.status.check,
  333. tips: wxConst.tips.check,
  334. code: this.ctx.session.sessionProject.code,
  335. c_name: this.ctx.change.name,
  336. };
  337. await this.ctx.helper.sendWechat(this._.map(audits, 'aid'), smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  338. for (const audit of audits) {
  339. await this.ctx.service.noticeAgain.addNoticeAgain(transaction, smsTypeConst.const.BG, {
  340. pid: this.ctx.session.sessionProject.id,
  341. tid: this.ctx.tender.id,
  342. uid: audit.aid,
  343. sp_type: 'change',
  344. sp_id: audit.id,
  345. table_name: this.tableName,
  346. template: wxConst.template.change,
  347. wx_data: wechatData,
  348. });
  349. }
  350. await transaction.delete(this.ctx.service.changeApplyHistory.tableName, { caid: caId });
  351. // todo 更新标段tender状态 ?
  352. // 检查三方特殊推送
  353. await this.ctx.service.specMsg.addChangeApplyMsg(transaction, this.ctx.session.sessionProject.id, this.ctx.change, pushOperate.change_apply.flow);
  354. await transaction.commit();
  355. } catch (err) {
  356. await transaction.rollback();
  357. throw err;
  358. }
  359. return true;
  360. }
  361. /**
  362. * 获取审核人需要审核的期列表
  363. *
  364. * @param auditorId
  365. * @return {Promise<*>}
  366. */
  367. async getAuditChangeApply(auditorId) {
  368. const sql = 'SELECT ma.`aid`, ma.`times`, ma.`order`, ma.`begin_time`, ma.`end_time`, ma.`tid`, ma.`caid`,' +
  369. ' m.`status` As `mstatus`, m.`code` As `mcode`,' +
  370. ' t.`name`, t.`project_id`, t.`type`, t.`user_id` ' +
  371. ' FROM ?? AS ma LEFT JOIN ?? AS m ON ma.`caid` = m.`id` LEFT JOIN ?? As t ON ma.`tid` = t.`id`' +
  372. ' WHERE ((ma.`aid` = ? and ma.`status` = ?) OR (m.`uid` = ? and ma.`status` = ? and m.`status` = ? and ma.`times` = (m.`times`-1)))' +
  373. ' ORDER BY ma.`begin_time` DESC';
  374. const sqlParam = [this.tableName, this.ctx.service.changeApply.tableName, this.ctx.service.tender.tableName, auditorId, auditConst.status.checking, auditorId, auditConst.status.checkNo, auditConst.status.checkNo];
  375. const result = await this.db.query(sql, sqlParam);
  376. // 过滤result中存在重复sid的值, 保留最新的一条
  377. const filterResult = [];
  378. const caidArr = [];
  379. for (const r of result) {
  380. if (caidArr.indexOf(r.caid) === -1) {
  381. filterResult.push(r);
  382. caidArr.push(r.caid);
  383. }
  384. }
  385. return filterResult;
  386. }
  387. /**
  388. * 获取审核人审核的次数
  389. *
  390. * @param auditorId
  391. * @return {Promise<*>}
  392. */
  393. async getCountByChecked(auditorId) {
  394. return await this.db.count(this.tableName, { aid: auditorId, status: [auditConst.status.checked, auditConst.status.checkNo] });
  395. }
  396. /**
  397. * 获取最近一次审批结束时间
  398. *
  399. * @param auditorId
  400. * @return {Promise<*>}
  401. */
  402. async getLastEndTimeByChecked(auditorId) {
  403. const sql = 'SELECT `end_time` FROM ?? WHERE `aid` = ? ' +
  404. 'AND `status` in (' + this.ctx.helper.getInArrStrSqlFilter([auditConst.status.checked, auditConst.status.checkNo]) + ') ORDER BY `end_time` DESC';
  405. const sqlParam = [this.tableName, auditorId];
  406. const result = await this.db.queryOne(sql, sqlParam);
  407. return result ? result.end_time : null;
  408. }
  409. /**
  410. * 用于添加推送所需的content内容
  411. * @param {Number} pid 项目id
  412. * @param {Number} tid 台账id
  413. * @param {Number} caId 立项书id
  414. * @param {Number} uid 审批人id
  415. */
  416. async getNoticeContent(pid, tid, caId, uid, opinion = '') {
  417. const noticeSql = 'SELECT * FROM (SELECT ' +
  418. ' t.`id` As `tid`, ma.`caid`, m.`code` as `c_code`, t.`name`, pa.`name` As `su_name`, pa.role As `su_role`' +
  419. ' FROM (SELECT * FROM ?? WHERE `id` = ? ) As t' +
  420. ' LEFT JOIN ?? As m On t.`id` = m.`tid` AND m.`id` = ?' +
  421. ' LEFT JOIN ?? As ma ON m.`id` = ma.`caid`' +
  422. ' LEFT JOIN ?? As pa ON pa.`id` = ?' +
  423. ' WHERE t.`project_id` = ? ) as new_t GROUP BY new_t.`tid`';
  424. const noticeSqlParam = [this.ctx.service.tender.tableName, tid, this.ctx.service.changeApply.tableName, caId, this.tableName, this.ctx.service.projectAccount.tableName, uid, pid];
  425. const content = await this.db.query(noticeSql, noticeSqlParam);
  426. if (content.length) {
  427. content[0].opinion = opinion;
  428. }
  429. return content.length ? JSON.stringify(content[0]) : '';
  430. }
  431. /**
  432. * 审批
  433. * @param {Number} caId - 立项书id
  434. * @param {auditConst.status.checked|auditConst.status.checkNo} checkType - 审批结果
  435. * @param {Number} times - 第几次审批
  436. * @return {Promise<void>}
  437. */
  438. async check(caId, checkData, times = 1) {
  439. if (checkData.checkType !== auditConst.status.checked && checkData.checkType !== auditConst.status.checkNo) {
  440. throw '提交数据错误';
  441. }
  442. const pid = this.ctx.session.sessionProject.id;
  443. switch (checkData.checkType) {
  444. case auditConst.status.checked:
  445. await this._checked(pid, caId, checkData, times);
  446. break;
  447. case auditConst.status.checkNo:
  448. await this._checkNo(pid, caId, checkData, times);
  449. break;
  450. default:
  451. throw '无效审批操作';
  452. }
  453. }
  454. async _checked(pid, caId, checkData, times) {
  455. const accountId = this.ctx.session.sessionUser.accountId;
  456. const time = new Date();
  457. // 整理当前流程审核人状态更新
  458. const audits = await this.getAllDataByCondition({ where: { caid: caId, times, status: auditConst.status.checking } });
  459. if (audits.length === 0) throw '审核数据错误';
  460. const selfAudit = audits.find(x => { return x.aid === accountId; });
  461. if (!selfAudit) throw '当前标段您无权审批';
  462. // const flowAudits = await this.getAllDataByCondition({ where: { caid: caId, times, order: selfAudit.order } });
  463. const nextAudits = await this.getAllDataByCondition({ where: { caid: caId, times, order: selfAudit.order + 1 } });
  464. const transaction = await this.db.beginTransaction();
  465. try {
  466. await transaction.update(this.tableName, {
  467. id: selfAudit.id,
  468. status: checkData.checkType,
  469. opinion: checkData.opinion,
  470. end_time: time,
  471. });
  472. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, selfAudit.id);
  473. // 获取推送必要信息
  474. const noticeContent = await this.getNoticeContent(pid, selfAudit.tid, caId, selfAudit.aid, checkData.opinion);
  475. // 添加推送
  476. const records = [];
  477. const auditors = await this.getAuditorsWithOwner(caId, times);
  478. auditors.forEach(audit => {
  479. records.push({ pid, type: pushType.changeApply, uid: audit.aid, status: auditConst.status.checked, content: noticeContent });
  480. });
  481. await transaction.insert('zh_notice', records);
  482. if (audits.length === 1 || selfAudit.audit_type !== auditType.key.and) {
  483. // 或签更新他人审批状态
  484. if (selfAudit.audit_type === auditType.key.or) {
  485. const updateOther = [];
  486. for (const audit of audits) {
  487. if (audit.aid === selfAudit.aid) continue;
  488. updateOther.push({
  489. id: audit.id,
  490. status: auditConst.status.checkSkip,
  491. opinion: '',
  492. end_time: time,
  493. });
  494. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, audit.id);
  495. }
  496. if (updateOther.length > 0) transaction.updateRows(this.tableName, updateOther);
  497. }
  498. // 无下一审核人表示,审核结束
  499. if (nextAudits.length > 0) {
  500. // 流程至下一审批人
  501. const updateData = nextAudits.map(x => { return { id: x.id, status: auditConst.status.checking, begin_time: time }; });
  502. await transaction.updateRows(this.tableName, updateData);
  503. // 同步 期信息
  504. await transaction.update(this.ctx.service.changeApply.tableName, {
  505. id: caId, status: auditConst.status.checking,
  506. });
  507. // 微信模板通知
  508. const wechatData = {
  509. type: 'apply',
  510. status: wxConst.status.check,
  511. tips: wxConst.tips.check,
  512. code: this.ctx.session.sessionProject.code,
  513. c_name: this.ctx.change.name,
  514. };
  515. await this.ctx.helper.sendWechat(this._.map(nextAudits, 'aid'), smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  516. for (const nextAudit of nextAudits) {
  517. await this.ctx.service.noticeAgain.addNoticeAgain(transaction, smsTypeConst.const.BG, {
  518. pid: this.ctx.session.sessionProject.id,
  519. tid: this.ctx.tender.id,
  520. uid: nextAudit.aid,
  521. sp_type: 'change',
  522. sp_id: nextAudit.id,
  523. table_name: this.tableName,
  524. template: wxConst.template.change,
  525. wx_data: wechatData,
  526. });
  527. }
  528. // 检查三方特殊推送
  529. await this.ctx.service.specMsg.addChangeApplyMsg(transaction, pid, this.ctx.change, pushOperate.change_apply.flow);
  530. } else {
  531. // 本期结束
  532. // 生成截止本期数据 final数据
  533. // 同步 期信息
  534. await transaction.update(this.ctx.service.changeApply.tableName, {
  535. id: caId, status: checkData.checkType,
  536. notice_code: checkData.notice_code,
  537. notice_uid: checkData.notice_uid,
  538. decimal: JSON.stringify(this.ctx.change.decimal),
  539. });
  540. // 微信模板通知
  541. const users = this._.uniq(this._.concat(this._.map(auditors, 'aid'), this.ctx.change.uid));
  542. const wechatData = {
  543. type: 'apply',
  544. status: wxConst.status.success,
  545. tips: wxConst.tips.success,
  546. code: this.ctx.session.sessionProject.code,
  547. c_name: this.ctx.change.name,
  548. };
  549. await this.ctx.helper.sendWechat(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), wxConst.template.change, wechatData);
  550. // 检查三方特殊推送
  551. await this.ctx.service.specMsg.addChangeApplyMsg(transaction, pid, this.ctx.change, pushOperate.change_apply.flow);
  552. await this.ctx.service.specMsg.addChangeApplyMsg(transaction, pid, this.ctx.change, pushOperate.change_apply.checked);
  553. }
  554. } else {
  555. // 同步 期信息
  556. await transaction.update(this.ctx.service.changeApply.tableName, {
  557. id: caId,
  558. status: auditConst.status.checking,
  559. });
  560. }
  561. await transaction.commit();
  562. } catch (err) {
  563. await transaction.rollback();
  564. throw err;
  565. }
  566. }
  567. async _checkNo(pid, caId, checkData, times) {
  568. const accountId = this.ctx.session.sessionUser.accountId;
  569. const time = new Date();
  570. const changeData = await this.ctx.service.changeApply.getDataById(caId);
  571. // 整理当前流程审核人状态更新
  572. const audits = await this.getAllDataByCondition({ where: { caid: caId, times, status: auditConst.status.checking } });
  573. if (!audits) throw '审核数据错误';
  574. const selfAudit = audits.find(x => { return x.aid === accountId; });
  575. if (!selfAudit) throw '当前标段您无权审批';
  576. const auditors = await this.getUniqAuditor(caId, times); // 全部参与的审批人
  577. const newAuditors = auditors.map(x => {
  578. return {
  579. aid: x.aid, tid: selfAudit.tid, caid: selfAudit.caid,
  580. times: times + 1, order: x.audit_order, status: auditConst.status.uncheck,
  581. audit_type: x.audit_type, audit_order: x.audit_order,
  582. };
  583. });
  584. const transaction = await this.db.beginTransaction();
  585. try {
  586. const updateData = [];
  587. audits.forEach(x => {
  588. updateData.push({
  589. id: x.id,
  590. status: x.aid === selfAudit.aid ? checkData.checkType : auditConst.status.checkSkip,
  591. opinion: x.aid === selfAudit.aid ? checkData.opinion : '',
  592. end_time: x.aid === selfAudit.aid ? time : null,
  593. });
  594. });
  595. await transaction.updateRows(this.tableName, updateData);
  596. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, this._.map(updateData, 'id'));
  597. // 添加到消息推送表
  598. const noticeContent = await this.getNoticeContent(pid, selfAudit.tid, caId, selfAudit.aid, checkData.opinion);
  599. const records = [{ pid, type: pushType.changeApply, uid: this.ctx.change.uid, status: auditConst.status.checkNo, content: noticeContent }];
  600. auditors.forEach(audit => {
  601. records.push({ pid, type: pushType.changeApply, uid: audit.aid, status: auditConst.status.checkNo, content: noticeContent });
  602. });
  603. await transaction.insert(this.ctx.service.noticePush.tableName, records);
  604. // 同步期信息
  605. await transaction.update(this.ctx.service.changeApply.tableName, {
  606. id: caId, status: checkData.checkType,
  607. times: times + 1,
  608. });
  609. // 拷贝新一次审核流程列表
  610. await transaction.insert(this.tableName, newAuditors);
  611. // 微信模板通知
  612. const users = this._.uniq(this._.concat(this._.map(auditors, 'aid'), this.ctx.change.uid));
  613. const wechatData = {
  614. type: 'apply',
  615. status: wxConst.status.back,
  616. tips: wxConst.tips.back,
  617. code: this.ctx.session.sessionProject.code,
  618. c_name: this.ctx.change.name,
  619. };
  620. await this.ctx.helper.sendWechat(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), wxConst.template.change, wechatData);
  621. // 生成内容保存表至zh_change_project_history中,用于撤回
  622. // 回退spamount值数据
  623. const changeList = await this.ctx.service.changeApplyList.getAllDataByCondition({ where: { caid: caId } });
  624. await this.ctx.service.changeApplyHistory.saveHistory(transaction, changeData, changeList);
  625. // 检查三方特殊推送
  626. await this.ctx.service.specMsg.addChangeApplyMsg(transaction, pid, this.ctx.change, pushOperate.change_apply.flow);
  627. await transaction.commit();
  628. } catch (err) {
  629. await transaction.rollback();
  630. throw err;
  631. }
  632. }
  633. /**
  634. * 复制上一期的审批人列表给最新一期
  635. *
  636. * @param transaction - 新增一期的事务
  637. * @param {Object} preMaterial - 上一期
  638. * @param {Object} newaMaterial - 最新一期
  639. * @return {Promise<*>}
  640. */
  641. async copyPreChangeApplyAuditors(transaction, preChange, newChange) {
  642. const auditList = await this.getUniqAuditor(preChange.id, preChange.times); // 全部参与的审批人
  643. const newAuditors = [];
  644. for (const x of auditList) {
  645. if (x.audit_order !== 0) {
  646. newAuditors.push({
  647. tid: preChange.tid, caid: newChange.id, aid: x.aid,
  648. times: 1, order: x.audit_order, status: auditConst.status.uncheck,
  649. audit_type: x.audit_type, audit_order: x.audit_order,
  650. });
  651. }
  652. }
  653. const result = newAuditors.length > 0 ? await transaction.insert(this.tableName, newAuditors) : null;
  654. return result ? result.affectedRows === newAuditors.length : true;
  655. }
  656. async getAllAuditors(tenderId) {
  657. const sql = 'SELECT ma.aid, ma.tid FROM ' + this.tableName + ' ma' +
  658. ' LEFT JOIN ' + this.ctx.service.tender.tableName + ' t On ma.tid = t.id' +
  659. ' WHERE t.id = ?' +
  660. ' GROUP BY ma.aid';
  661. const sqlParam = [tenderId];
  662. return this.db.query(sql, sqlParam);
  663. }
  664. /**
  665. * 审批撤回
  666. * @param {Number} stageId - 标段id
  667. * @param {Number} times - 第几次审批
  668. * @return {Promise<void>}
  669. */
  670. async checkCancel(change) {
  671. // 分3种情况,根据ctx.cancancel值判断:
  672. // 1.原报发起撤回,当前流程删除,并回到待上报
  673. // 2.审批人撤回审批通过,增加流程,并回到它审批中
  674. // 4.审批人撤回退回原报操作,删除新增的审批流,增加流程,回滚到它审批中
  675. // 5.会签审批人撤回审批通过(还有其他审批人未审批通过),仅修改本人流程状态
  676. switch (change.cancancel) {
  677. case 1: await this._userCheckCancel(change); break;
  678. case 2: await this._auditCheckCancel(change); break;
  679. case 4: await this._auditCheckCancelNo(change); break;
  680. case 5: await this._auditCheckCancelAnd(change); break;
  681. default: throw '不可撤回,请刷新页面重试';
  682. }
  683. }
  684. /**
  685. * 原报撤回,直接改动审批人状态
  686. * 如果存在审批人数据,将其改为原报流程数据,但保留原提交人
  687. *
  688. * 一审 1 A checking -> A uncheck status改 pay/jl:删0(jl为增量数据,只删重复部分) 1->0 删1
  689. * ...
  690. *
  691. * @param stage
  692. * @returns {Promise<void>}
  693. * @private
  694. */
  695. async _userCheckCancel(change) {
  696. const transaction = await this.db.beginTransaction();
  697. try {
  698. const updateData = change.curAuditors.map(x => {
  699. return {
  700. id: x.id,
  701. status: auditConst.status.uncheck,
  702. begin_time: null, opinion: null,
  703. };
  704. });
  705. await transaction.updateRows(this.tableName, updateData);
  706. await this.ctx.service.noticeAgain.deleteNoticeAgain(transaction, this.tableName, this._.map(updateData, 'id'));
  707. // 变成待上报状态
  708. await transaction.update(this.ctx.service.changeApply.tableName, {
  709. id: change.id,
  710. status: change.times === 1 ? auditConst.status.uncheck : auditConst.status.checkNo,
  711. });
  712. await transaction.commit();
  713. } catch (err) {
  714. await transaction.rollback();
  715. throw err;
  716. }
  717. }
  718. /**
  719. * 审批人撤回审批通过,插入两条数据
  720. *
  721. * 一审 1 A checked 一审 1 A checked
  722. * 二审 2 B checked pre -> 二审 2 B checked
  723. * 三审 3 C checking cur 二审 3 B checkCancel 增 增extra_his 增tp_his
  724. * 四审 4 D uncheck 二审 4 B checking 增 增pay_cur
  725. * 三审 5 C uncheck order、status改
  726. * 四审 6 D uncheck order改
  727. *
  728. * @param stage
  729. * @returns {Promise<void>}
  730. * @private
  731. */
  732. async _auditCheckCancel(change) {
  733. if (change.curAuditors.length === 0 || change.curAuditors[0].order <= 1) {
  734. throw '撤回用户数据错误';
  735. }
  736. const accountId = this.ctx.session.sessionUser.accountId;
  737. const selfAuditor = change.preAuditors.find(x => { return x.aid === accountId; });
  738. if (!selfAuditor) throw '撤回用户数据错误';
  739. const time = new Date();
  740. const transaction = await this.db.beginTransaction();
  741. try {
  742. // 顺移其后审核人流程顺序
  743. const sql = 'UPDATE ' + this.tableName + ' SET `order` = `order` + 2 WHERE caid = ? AND times = ? AND `order` > ?';
  744. await transaction.query(sql, [change.id, selfAuditor.times, change.curAuditors[0].order]);
  745. // 当前审批人2次添加至流程中
  746. const checkCancelAuditors = [],
  747. checkingAuditors = [];
  748. change.preAuditors.forEach(x => {
  749. checkCancelAuditors.push({
  750. tid: change.tid, caid: change.id, aid: x.aid,
  751. times: x.times, order: x.order + 1,
  752. status: x.aid === selfAuditor.aid ? auditConst.status.checkCancel : auditConst.status.checkSkip,
  753. begin_time: time, end_time: time, opinion: '',
  754. audit_type: x.audit_type, audit_order: x.audit_order,
  755. });
  756. });
  757. change.preAuditors.forEach(x => {
  758. checkingAuditors.push({
  759. tid: change.tid, caid: change.id, aid: x.aid,
  760. times: x.times, order: x.order + 2,
  761. status: auditConst.status.checking,
  762. begin_time: time, end_time: time, opinion: '',
  763. audit_type: x.audit_type, audit_order: x.audit_order,
  764. });
  765. });
  766. await transaction.insert(this.tableName, [...checkCancelAuditors, ...checkingAuditors]);
  767. // 当前审批人变成待审批
  768. await transaction.updateRows(this.tableName, change.curAuditors.map(x => {
  769. return { id: x.id, begin_time: null, status: auditConst.status.uncheck, order: x.order + 2 };
  770. }));
  771. await this.ctx.service.noticeAgain.deleteNoticeAgain(transaction, this.tableName, this._.map(change.curAuditors, 'id'));
  772. await transaction.commit();
  773. } catch (err) {
  774. await transaction.rollback();
  775. throw err;
  776. }
  777. }
  778. /**
  779. * 审批人撤回审批退回原报
  780. *
  781. * 1# 一审 1 A checked 1# 一审 1 A checked
  782. * 二审 2 B checkNo pre -> 二审 2 B checkNo
  783. * 三审 3 C uncheck 二审 3 B checkCancel 增 pay: 2#0 -> 1#3 jl: 2#0 -> 1#3 增tp_his 增extra_his
  784. * 二审 4 B checking 增 pay: 2#0 -> 1#4
  785. * 三审 5 C uncheck order改
  786. *
  787. * 2# 一审 1 A uncheck 2# 删 pay: 2#0删 jl: 2#0删
  788. * 二审 2 B uncheck
  789. * 三审 3 C uncheck
  790. *
  791. * @param stage
  792. * @returns {Promise<void>}
  793. * @private
  794. */
  795. async _auditCheckCancelNo(change) {
  796. const accountId = this.ctx.session.sessionUser.accountId;
  797. const selfAuditor = change.preAuditors.find(x => { return x.aid === accountId && x.status === auditConst.status.checkNo; });
  798. if (!selfAuditor) throw '该标段由他人审批退回,您不可撤回';
  799. const time = new Date();
  800. const transaction = await this.db.beginTransaction();
  801. try {
  802. // 整理上一个流程审核人状态更新
  803. // 顺移其后审核人流程顺序
  804. const sql = 'UPDATE ' + this.tableName + ' SET `order` = `order` + 2 WHERE caid = ? AND times = ? AND `order` > ?';
  805. await transaction.query(sql, [change.id, selfAuditor.times, selfAuditor.order]);
  806. // 当前审批人2次添加至流程中
  807. const checkCancelAuditors = [],
  808. checkingAuditors = [];
  809. change.preAuditors.forEach(x => {
  810. checkCancelAuditors.push({
  811. tid: change.tid, caid: change.id, aid: x.aid,
  812. times: x.times, order: x.order + 1,
  813. status: x.aid === selfAuditor.aid ? auditConst.status.checkCancel : auditConst.status.checkSkip,
  814. begin_time: time, end_time: time, opinion: '',
  815. audit_type: x.audit_type, audit_order: x.audit_order,
  816. });
  817. });
  818. change.preAuditors.forEach(x => {
  819. checkingAuditors.push({
  820. tid: change.tid, caid: change.id, aid: x.aid,
  821. times: x.times, order: x.order + 2,
  822. status: auditConst.status.checking,
  823. begin_time: time, end_time: time, opinion: '',
  824. audit_type: x.audit_type, audit_order: x.audit_order,
  825. });
  826. });
  827. await transaction.insert(this.tableName, [...checkCancelAuditors, ...checkingAuditors]);
  828. // 删除当前次审批流
  829. await transaction.delete(this.tableName, { caid: change.id, times: change.times });
  830. // 回退数据
  831. await this.ctx.service.changeApplyHistory.returnHistory(transaction, change.id);
  832. await transaction.delete(this.ctx.service.changeApplyHistory.tableName, { caid: change.id });
  833. // // 设置变更立项为审批中
  834. // await transaction.update(this.ctx.service.changeApply.tableName, {
  835. // id: change.id,
  836. // time: change.times - 1,
  837. // status: auditConst.status.checking,
  838. // });
  839. await transaction.commit();
  840. } catch (err) {
  841. await transaction.rollback();
  842. throw err;
  843. }
  844. }
  845. /**
  846. * 会签未全部审批通过时,撤回仅修改本人状态
  847. *
  848. * @param stage
  849. * @returns {Promise<void>}
  850. * @private
  851. */
  852. async _auditCheckCancelAnd(change) {
  853. const accountId = this.ctx.session.sessionUser.accountId;
  854. const selfAuditor = change.flowAuditors.find(x => { return x.aid === accountId; });
  855. if (!selfAuditor || selfAuditor.status !== auditConst.status.checked) throw '不可撤回';
  856. const transaction = await this.db.beginTransaction();
  857. try {
  858. await transaction.update(this.tableName, {
  859. id: selfAuditor.id, status: auditConst.status.checking, opinion: '', end_time: null,
  860. });
  861. await transaction.commit();
  862. } catch (err) {
  863. await transaction.rollback();
  864. throw err;
  865. }
  866. }
  867. /**
  868. * 重新审批变更令
  869. * @param { string } cid - 查询的清单
  870. * @return {Promise<*>} - 可用的变更令列表
  871. */
  872. async checkRevise(change) {
  873. const accountId = this.ctx.session.sessionUser.accountId;
  874. const time = new Date();
  875. // 初始化事务
  876. const transaction = await this.db.beginTransaction();
  877. let result = false;
  878. try {
  879. const pid = this.ctx.session.sessionProject.id;
  880. // 获取审核人列表
  881. const auditors = await this.getUniqAuditor(change.id, change.times); // 全部参与的审批人
  882. // 添加到消息推送表
  883. const noticeContent = await this.getNoticeContent(pid, change.tid, change.id, this.ctx.session.sessionUser.accountId, '发起修订');
  884. const records = [{ pid, type: pushType.changeProject, uid: change.uid, status: auditConst.status.revise, content: noticeContent }];
  885. auditors.forEach(auditor => {
  886. records.push({
  887. pid,
  888. type: pushType.changeApply,
  889. uid: auditor.aid,
  890. status: auditConst.status.revise,
  891. content: noticeContent,
  892. });
  893. });
  894. await transaction.insert('zh_notice', records);
  895. const order = change.auditors.length > 0 ? change.auditors.reduce((rst, a) => { return Math.max(rst, a.order); }, 0) + 1 : 1; // 最大值 + 1
  896. // 当前审批人添加至流程中
  897. const checkReviseAuditor = {
  898. tid: change.tid, caid: change.id, aid: change.uid,
  899. times: change.times, order,
  900. status: auditConst.status.revise,
  901. begin_time: time, end_time: time, opinion: '',
  902. audit_type: auditType.key.common, audit_order: 0,
  903. };
  904. await transaction.insert(this.tableName, checkReviseAuditor);
  905. // 修订人加入审批流程
  906. const newAuditors = auditors.map(x => {
  907. return {
  908. aid: x.aid, tid: change.tid, caid: change.id,
  909. times: change.times + 1, order: x.audit_order, status: auditConst.status.uncheck,
  910. audit_type: x.audit_type, audit_order: x.audit_order,
  911. };
  912. });
  913. await transaction.insert(this.tableName, newAuditors);
  914. // 生成内容保存表至zh_change_history中,用于撤销修订回退
  915. const changeData = await transaction.get(this.ctx.service.changeApply.tableName, { id: change.id });
  916. const changeList = await this.ctx.service.changeApplyList.getAllDataByCondition({ where: { caid: change.id } });
  917. await this.ctx.service.changeApplyHistory.saveHistory(transaction, changeData, changeList);
  918. // 设置变更立项修订状态
  919. await transaction.update(this.ctx.service.changeApply.tableName, {
  920. id: change.id,
  921. notice_code: null,
  922. notice_uid: null,
  923. decimal: null,
  924. status: auditConst.status.revise,
  925. times: change.times + 1,
  926. final_auditor_str: '',
  927. });
  928. await transaction.commit();
  929. result = true;
  930. } catch (error) {
  931. console.log(error);
  932. await transaction.rollback();
  933. result = false;
  934. }
  935. return result;
  936. }
  937. /**
  938. * 撤销修订变更令
  939. * @param { string } cid - 查询的清单
  940. * @return {Promise<*>} - 可用的变更令列表
  941. */
  942. async cancelRevise(change) {
  943. const time = new Date();
  944. // 初始化事务
  945. const transaction = await this.db.beginTransaction();
  946. let result = false;
  947. try {
  948. const pid = this.ctx.session.sessionProject.id;
  949. // 获取审核人列表
  950. const auditors = await this.getUniqAuditor(change.id, change.times - 1); // 全部参与的审批人
  951. // 添加到消息推送表
  952. const noticeContent = await this.getNoticeContent(pid, change.tid, change.id, this.ctx.session.sessionUser.accountId, '撤销修订');
  953. const records = [{ pid, type: pushType.changeProject, uid: change.uid, status: auditConst.status.cancelRevise, content: noticeContent }];
  954. auditors.forEach(auditor => {
  955. records.push({
  956. pid,
  957. type: pushType.changeApply,
  958. uid: auditor.aid,
  959. status: auditConst.status.cancelRevise,
  960. content: noticeContent,
  961. });
  962. });
  963. await transaction.insert('zh_notice', records);
  964. const lastAudit = await this.getLastAudit(change.id, change.times - 1);
  965. // 新增一个撤销修订状态到审批流程中
  966. const revise_audit = {
  967. tid: change.tid, caid: change.id, aid: this.ctx.session.sessionUser.accountId,
  968. times: change.times - 1, order: lastAudit.order + 1, status: auditConst.status.cancelRevise,
  969. begin_time: time, end_time: time, opinion: '',
  970. audit_type: lastAudit.audit_type, audit_order: lastAudit.audit_order,
  971. };
  972. await transaction.insert(this.tableName, revise_audit);
  973. await transaction.delete(this.tableName, { caid: change.id, times: change.times });
  974. await this.ctx.service.changeApplyHistory.returnHistory(transaction, change.id);
  975. await transaction.delete(this.ctx.service.changeApplyHistory.tableName, { caid: change.id });
  976. await transaction.commit();
  977. result = true;
  978. } catch (error) {
  979. console.log(error);
  980. await transaction.rollback();
  981. result = false;
  982. }
  983. return result;
  984. }
  985. /**
  986. * 重新审批变更申请
  987. * @param { string } cid - 查询的清单
  988. * @return {Promise<*>} - 可用的变更令列表
  989. */
  990. async checkAgain(change) {
  991. const accountId = this.ctx.session.sessionUser.accountId;
  992. // 初始化事务
  993. const time = new Date();
  994. const transaction = await this.db.beginTransaction();
  995. let result = false;
  996. try {
  997. const noYbAuditors = change.auditors.filter(x => { return x.audit_order !== 0; });
  998. const noYbMaxOrder = noYbAuditors[noYbAuditors.length - 1].order;
  999. const maxOrder = change.auditors[change.auditors.length - 1].order;
  1000. const audits = change.auditors.filter(x => { return x.order === noYbMaxOrder; });
  1001. if (!audits || audits.length === 0 || maxOrder < 1) throw '审核数据错误';
  1002. const selfAudit = audits.find(x => { return x.aid === accountId; });
  1003. if (!selfAudit) throw '当前标段您无权审批';
  1004. // 当前审批人2次添加至流程中
  1005. const checkAgainAuditors = [];
  1006. audits.forEach(x => {
  1007. checkAgainAuditors.push({
  1008. tid: change.tid, caid: change.id, aid: x.aid,
  1009. times: x.times, order: maxOrder + 1,
  1010. status: !selfAudit || x.aid === selfAudit.aid ? auditConst.status.checkAgain : auditConst.status.checkSkip,
  1011. begin_time: time, end_time: time, opinion: '',
  1012. audit_type: x.audit_type, audit_order: x.audit_order,
  1013. });
  1014. });
  1015. const checkingAuditors = [];
  1016. audits.forEach(x => {
  1017. checkingAuditors.push({
  1018. tid: change.tid, caid: change.id, aid: x.aid,
  1019. times: x.times, order: maxOrder + 2,
  1020. status: auditConst.status.checking,
  1021. begin_time: time,
  1022. audit_type: x.audit_type, audit_order: x.audit_order,
  1023. });
  1024. });
  1025. await transaction.insert(this.tableName, checkAgainAuditors);
  1026. const checkingAuditors_result = await transaction.insert(this.tableName, checkingAuditors);
  1027. // 获取刚批量添加的所有list
  1028. // for (let j = 0; j < checkingAuditors.length; j++) {
  1029. // checkingAuditors[j].id = checkingAuditors_result.insertId + j;
  1030. // }
  1031. // 设置变更令审批中
  1032. await transaction.update(this.ctx.service.changeApply.tableName, {
  1033. id: change.id,
  1034. status: auditConst.status.checking,
  1035. notice_code: null,
  1036. notice_uid: null,
  1037. decimal: null,
  1038. final_auditor_str: '',
  1039. });
  1040. // 检查三方特殊推送
  1041. await this.ctx.service.specMsg.addChangeApplyMsg(transaction, this.ctx.session.sessionProject.id, this.ctx.change, pushOperate.change_apply.flow);
  1042. await transaction.commit();
  1043. result = true;
  1044. } catch (error) {
  1045. await transaction.rollback();
  1046. result = false;
  1047. }
  1048. return result;
  1049. }
  1050. async getAuditorGroup(caId, times) {
  1051. const auditors = await this.getAuditors(caId, times); // 全部参与的审批人
  1052. return this.ctx.helper.groupAuditors(auditors, 'order', true);
  1053. }
  1054. async getUserGroup(caId, times) {
  1055. const group = await this.getAuditorGroup(caId, times);
  1056. const sql =
  1057. 'SELECT pa.`id` As aid, pa.`name`, pa.`company`, pa.`role`, ? As times, ? As caid, 0 As `order`, 1 As audit_type, 0 As audit_order' +
  1058. ' FROM ' + this.ctx.service.changeApply.tableName + ' As s' +
  1059. ' LEFT JOIN ' + this.ctx.service.projectAccount.tableName + ' As pa' +
  1060. ' ON s.uid = pa.id' +
  1061. ' WHERE s.id = ?';
  1062. const sqlParam = [times, caId, caId];
  1063. const user = await this.db.queryOne(sql, sqlParam);
  1064. user.audit_order = 0;
  1065. group.unshift([ user ]);
  1066. return group;
  1067. }
  1068. async getUniqUserGroup(caId, times) {
  1069. const group = await this.getAuditorGroup(caId, times);
  1070. const sql =
  1071. 'SELECT pa.`id` As aid, pa.`name`, pa.`company`, pa.`role`, ? As times, ? As caid, 0 As `order`, 1 As audit_type, 0 As audit_order' +
  1072. ' FROM ' + this.ctx.service.changeApply.tableName + ' As s' +
  1073. ' LEFT JOIN ' + this.ctx.service.projectAccount.tableName + ' As pa' +
  1074. ' ON s.uid = pa.id' +
  1075. ' WHERE s.id = ?';
  1076. const sqlParam = [times, caId, caId];
  1077. const user = await this.db.queryOne(sql, sqlParam);
  1078. user.audit_order = 0;
  1079. group.unshift([ user ]);
  1080. return this.ctx.helper.groupAuditorsUniq(group);
  1081. }
  1082. async getAuditorHistory(caId, times, reverse = false) {
  1083. const history = [];
  1084. if (times >= 1) {
  1085. for (let i = 1; i <= times; i++) {
  1086. const auditors = await this.getAuditors(caId, i);
  1087. const group = this.ctx.helper.groupAuditors(auditors);
  1088. const historyGroup = [];
  1089. // 找出group里audit_order最大值
  1090. const max_info = group.length > 0 ? this._.maxBy(group, function(item) {
  1091. return item && item[0] && item[0].audit_order;
  1092. }) : null;
  1093. const max_order = max_info ? max_info[0].audit_order : -1;
  1094. for (const g of group) {
  1095. const his = {
  1096. beginYear: '', beginDate: '', beginTime: '', endYear: '', endDate: '', endTime: '', begin_time: null, end_time: null,
  1097. audit_type: g[0].audit_type, audit_order: g[0].audit_order,
  1098. auditors: g,
  1099. };
  1100. if (his.audit_type === auditType.key.common) {
  1101. his.name = g[0].name;
  1102. } else {
  1103. his.name = this.ctx.helper.transFormToChinese(his.audit_order) + '审';
  1104. }
  1105. his.is_final = his.audit_order === max_order;
  1106. if (g[0].begin_time) {
  1107. his.begin_time = g[0].begin_time;
  1108. const beginTime = this.ctx.moment(g[0].begin_time);
  1109. his.beginYear = beginTime.format('YYYY');
  1110. his.beginDate = beginTime.format('MM-DD');
  1111. his.beginTime = beginTime.format('HH:mm:ss');
  1112. }
  1113. let end_time;
  1114. g.forEach(x => {
  1115. if (x.status === auditConst.status.checkSkip) return;
  1116. if (!his.status || x.status === auditConst.status.checking) his.status = x.status;
  1117. if (x.end_time && (!end_time || x.end_time > end_time)) {
  1118. end_time = x.end_time;
  1119. if (his.status !== auditConst.status.checking) his.status = x.status;
  1120. }
  1121. });
  1122. if (end_time) {
  1123. his.end_time = end_time;
  1124. const endTime = this.ctx.moment(end_time);
  1125. his.endYear = endTime.format('YYYY');
  1126. his.endDate = endTime.format('MM-DD');
  1127. his.endTime = endTime.format('HH:mm:ss');
  1128. }
  1129. historyGroup.push(his);
  1130. }
  1131. if (reverse) {
  1132. history.push(historyGroup.reverse());
  1133. } else {
  1134. history.push(historyGroup);
  1135. }
  1136. }
  1137. }
  1138. return history;
  1139. }
  1140. async getUniqAuditor(caId, times) {
  1141. const auditors = await this.getAuditors(caId, times); // 全部参与的审批人
  1142. const result = [];
  1143. auditors.forEach(x => {
  1144. if (result.findIndex(r => { return x.aid === r.aid && x.audit_order === r.audit_order; }) < 0) {
  1145. result.push(x);
  1146. }
  1147. });
  1148. return result;
  1149. }
  1150. async saveAudit(caId, times, sp_group, data) {
  1151. const transaction = await this.db.beginTransaction();
  1152. try {
  1153. const auditors = await this.getAuditGroupByList(caId, times);
  1154. const now_audit = this._.find(auditors, { aid: data.old_aid });
  1155. if (data.operate !== 'del') {
  1156. const exist = await this.getDataByCondition({ caid: caId, times, aid: data.new_aid });
  1157. if (exist) throw '该审核人已存在,请勿重复添加';
  1158. }
  1159. if (data.operate === 'add') {
  1160. if (now_audit.status !== auditConst.status.uncheck && now_audit.status !== auditConst.status.checking) {
  1161. throw '当前人下无法操作新增';
  1162. }
  1163. const newAudit = {
  1164. tid: this.ctx.tender.id, caid: caId, aid: data.new_aid,
  1165. order: now_audit.order + 1,
  1166. audit_order: now_audit.audit_order + 1, audit_type: auditType.key.common,
  1167. times, status: auditConst.status.uncheck,
  1168. };
  1169. // order+1
  1170. await this._syncOrderByDelete(transaction, caId, now_audit.order + 1, times, '+');
  1171. await transaction.insert(this.tableName, newAudit);
  1172. // 更新审批流程页数据,如果存在
  1173. } else if (data.operate === 'add-sibling') {
  1174. if (now_audit.status !== auditConst.status.uncheck && now_audit.status !== auditConst.status.checking) {
  1175. throw '当前人下无法操作新增';
  1176. }
  1177. const newAudit = {
  1178. tid: this.ctx.tender.id, caid: caId, aid: data.new_aid,
  1179. order: now_audit.order,
  1180. audit_order: now_audit.audit_order, audit_type: now_audit.audit_type,
  1181. times, status: auditConst.status.uncheck,
  1182. };
  1183. await transaction.insert(this.tableName, newAudit);
  1184. } else if (data.operate === 'del') {
  1185. if (now_audit.status !== auditConst.status.uncheck) {
  1186. throw '当前人无法操作删除';
  1187. }
  1188. const flowAuditors = auditors.filter(x => { return x.audit_order === now_audit.audit_order; });
  1189. await transaction.delete(this.tableName, { caid: caId, times, aid: now_audit.aid, order: now_audit.order });
  1190. if (flowAuditors.length === 1) await this._syncOrderByDelete(transaction, caId, now_audit.order, times);
  1191. // 旧的更新为is_old为1
  1192. // await transaction.update(this.tableName, { is_old: 1 }, {
  1193. // where: {
  1194. // sid: stageId,
  1195. // times,
  1196. // aid: data.old_aid,
  1197. // }
  1198. // });
  1199. } else if (data.operate === 'change') {
  1200. const nowAudit = await this.getDataByCondition({ caid: caId, times, aid: now_audit.aid, order: now_audit.order });
  1201. if (now_audit.status !== auditConst.status.uncheck || !nowAudit) {
  1202. throw '当前人无法操作替换';
  1203. }
  1204. nowAudit.aid = data.new_aid;
  1205. await transaction.update(this.tableName, nowAudit);
  1206. // 旧的更新为is_old为1
  1207. // await transaction.update(this.tableName, { is_old: 1 }, {
  1208. // where: {
  1209. // sid: stageId,
  1210. // times,
  1211. // aid: data.old_aid,
  1212. // }
  1213. // });
  1214. }
  1215. if (this.ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdspl) {
  1216. const newAuditors = await transaction.select(this.tableName, { where: { caid: caId, times }, orders: [['order', 'asc']] });
  1217. const newAuditorGroup = this.ctx.helper.groupAuditors(newAuditors, 'order', true);
  1218. const uniqNewAuditorGroup = this.ctx.helper.groupAuditorsUniq(newAuditorGroup);
  1219. // await this.ctx.service.shenpiAudit.updateAuditListWithAuditType(transaction, this.ctx.tender.id, this.ctx.tender.info.shenpi.change, shenpiConst.sp_type.change, uniqNewAuditorGroup, sp_group);
  1220. } else if (this.ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdzs) {
  1221. const newAuditors = await this.getAuditGroupByList(caId, times, transaction);
  1222. await this.ctx.service.shenpiAudit.updateAuditList(transaction, this.ctx.tender.id, this.ctx.tender.info.shenpi.change, shenpiConst.sp_type.change, this._.map(newAuditors, 'aid'));
  1223. }
  1224. // 更新到审批流程方法
  1225. await transaction.commit();
  1226. } catch (err) {
  1227. await transaction.rollback();
  1228. throw err;
  1229. }
  1230. }
  1231. async changeSpGroup(change, sp_group) {
  1232. const transaction = await this.db.beginTransaction();
  1233. try {
  1234. const group = await this.ctx.service.shenpiGroup.getDataById(sp_group);
  1235. if (!group) {
  1236. throw '该固定审批组不存在,请刷新页面重新获取';
  1237. }
  1238. const shenpiList = await this.ctx.service.shenpiAudit.getAllDataByCondition({ where: { tid: this.ctx.tender.id, sp_type: shenpiConst.sp_type.change, sp_status: shenpiConst.sp_status.gdspl, sp_group: group.id } });
  1239. await this.ctx.service.shenpiAudit.noYbShenpiList(change.uid, shenpiList);
  1240. await this.updateNewAuditors(change, shenpiList, transaction);
  1241. await transaction.update(this.ctx.service.changeApply.tableName, { id: change.id, sp_group: group.id });
  1242. await transaction.commit();
  1243. } catch (err) {
  1244. await transaction.rollback();
  1245. throw err;
  1246. }
  1247. return true;
  1248. }
  1249. async updateNewAuditList(change, newList) {
  1250. const transaction = await this.db.beginTransaction();
  1251. try {
  1252. await this.updateNewAuditors(change, newList, transaction);
  1253. await transaction.commit();
  1254. } catch (err) {
  1255. await transaction.rollback();
  1256. throw err;
  1257. }
  1258. }
  1259. async updateNewAuditors(change, newList, transaction) {
  1260. // 先删除旧的审批流,再添加新的
  1261. await transaction.delete(this.tableName, { caid: change.id, times: change.times });
  1262. const newAuditors = [];
  1263. for (const auditor of newList) {
  1264. newAuditors.push({
  1265. tid: change.tid, caid: change.id, aid: auditor.audit_id,
  1266. times: change.times, order: auditor.audit_order, status: auditConst.status.uncheck,
  1267. audit_type: auditor.audit_type, audit_order: auditor.audit_order,
  1268. });
  1269. }
  1270. if (newAuditors.length > 0) await transaction.insert(this.tableName, newAuditors);
  1271. }
  1272. async updateLastAudit(change, auditList, lastId) {
  1273. const transaction = await this.db.beginTransaction();
  1274. try {
  1275. // 先判断auditList里的aid是否与lastId相同,相同则删除并重新更新order
  1276. const existAudit = auditList.find(x => { return x.aid === lastId; });
  1277. let order = auditList.length > 0 ? auditList.reduce((rst, a) => { return Math.max(rst, a.order); }, 0) + 1 : 1; // 最大值 + 1
  1278. if (existAudit) {
  1279. await transaction.delete(this.tableName, { caid: change.id, times: change.times, aid: lastId });
  1280. const sameOrder = auditList.filter(x => { return x.order === existAudit.order; });
  1281. if (sameOrder.length === 1) {
  1282. const updateData = [];
  1283. auditList.forEach(x => {
  1284. if (x.order <= existAudit.order) return;
  1285. updateData.push({ id: x.id, order: x.order - 1, audit_order: x.audit_order - 1 });
  1286. });
  1287. if (updateData.length > 0) {
  1288. await transaction.updateRows(updateData);
  1289. }
  1290. order = order - 1;
  1291. }
  1292. }
  1293. // 添加终审
  1294. const newAuditor = {
  1295. tid: change.tid, caid: change.id, aid: lastId,
  1296. times: change.times, order, status: auditConst.status.uncheck,
  1297. audit_type: auditType.key.common, audit_order: order,
  1298. };
  1299. await transaction.insert(this.tableName, newAuditor);
  1300. await transaction.commit();
  1301. } catch (err) {
  1302. await transaction.rollback();
  1303. throw err;
  1304. }
  1305. }
  1306. }
  1307. return ChangeApplyAudit;
  1308. };