change_apply_audit.js 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411
  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 shenpiUrl = await this.ctx.helper.urlToShort(
  331. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/change/apply/' + caId + '/information#shenpi'
  332. );
  333. // 微信模板通知
  334. const wechatData = {
  335. type: 'apply',
  336. wap_url: shenpiUrl,
  337. status: wxConst.status.check,
  338. tips: wxConst.tips.check,
  339. code: this.ctx.session.sessionProject.code,
  340. c_name: this.ctx.change.name,
  341. };
  342. await this.ctx.helper.sendWechat(this._.map(audits, 'aid'), smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  343. for (const audit of audits) {
  344. await this.ctx.service.noticeAgain.addNoticeAgain(transaction, smsTypeConst.const.BG, {
  345. pid: this.ctx.session.sessionProject.id,
  346. tid: this.ctx.tender.id,
  347. uid: audit.aid,
  348. sp_type: 'change',
  349. sp_id: audit.id,
  350. table_name: this.tableName,
  351. template: wxConst.template.change,
  352. wx_data: wechatData,
  353. });
  354. }
  355. await transaction.delete(this.ctx.service.changeApplyHistory.tableName, { caid: caId });
  356. // todo 更新标段tender状态 ?
  357. // 检查三方特殊推送
  358. await this.ctx.service.specMsg.addChangeApplyMsg(transaction, this.ctx.session.sessionProject.id, this.ctx.change, pushOperate.change_apply.flow);
  359. await transaction.commit();
  360. } catch (err) {
  361. await transaction.rollback();
  362. throw err;
  363. }
  364. return true;
  365. }
  366. /**
  367. * 获取审核人需要审核的期列表
  368. *
  369. * @param auditorId
  370. * @return {Promise<*>}
  371. */
  372. async getAuditChangeApply(auditorId) {
  373. const sql = 'SELECT ma.`aid`, ma.`times`, ma.`order`, ma.`begin_time`, ma.`end_time`, ma.`tid`, ma.`caid`,' +
  374. ' m.`status` As `mstatus`, m.`code` As `mcode`,' +
  375. ' t.`name`, t.`project_id`, t.`type`, t.`user_id` ' +
  376. ' FROM ?? AS ma LEFT JOIN ?? AS m ON ma.`caid` = m.`id` LEFT JOIN ?? As t ON ma.`tid` = t.`id`' +
  377. ' WHERE ((ma.`aid` = ? and ma.`status` = ?) OR (m.`uid` = ? and ma.`status` = ? and m.`status` = ? and ma.`times` = (m.`times`-1)))' +
  378. ' ORDER BY ma.`begin_time` DESC';
  379. 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];
  380. const result = await this.db.query(sql, sqlParam);
  381. // 过滤result中存在重复sid的值, 保留最新的一条
  382. const filterResult = [];
  383. const caidArr = [];
  384. for (const r of result) {
  385. if (caidArr.indexOf(r.caid) === -1) {
  386. filterResult.push(r);
  387. caidArr.push(r.caid);
  388. }
  389. }
  390. return filterResult;
  391. }
  392. /**
  393. * 获取审核人审核的次数
  394. *
  395. * @param auditorId
  396. * @return {Promise<*>}
  397. */
  398. async getCountByChecked(auditorId) {
  399. return await this.db.count(this.tableName, { aid: auditorId, status: [auditConst.status.checked, auditConst.status.checkNo] });
  400. }
  401. /**
  402. * 获取最近一次审批结束时间
  403. *
  404. * @param auditorId
  405. * @return {Promise<*>}
  406. */
  407. async getLastEndTimeByChecked(auditorId) {
  408. const sql = 'SELECT `end_time` FROM ?? WHERE `aid` = ? ' +
  409. 'AND `status` in (' + this.ctx.helper.getInArrStrSqlFilter([auditConst.status.checked, auditConst.status.checkNo]) + ') ORDER BY `end_time` DESC';
  410. const sqlParam = [this.tableName, auditorId];
  411. const result = await this.db.queryOne(sql, sqlParam);
  412. return result ? result.end_time : null;
  413. }
  414. /**
  415. * 用于添加推送所需的content内容
  416. * @param {Number} pid 项目id
  417. * @param {Number} tid 台账id
  418. * @param {Number} caId 立项书id
  419. * @param {Number} uid 审批人id
  420. */
  421. async getNoticeContent(pid, tid, caId, uid, opinion = '') {
  422. const noticeSql = 'SELECT * FROM (SELECT ' +
  423. ' t.`id` As `tid`, ma.`caid`, m.`code` as `c_code`, t.`name`, pa.`name` As `su_name`, pa.role As `su_role`' +
  424. ' FROM (SELECT * FROM ?? WHERE `id` = ? ) As t' +
  425. ' LEFT JOIN ?? As m On t.`id` = m.`tid` AND m.`id` = ?' +
  426. ' LEFT JOIN ?? As ma ON m.`id` = ma.`caid`' +
  427. ' LEFT JOIN ?? As pa ON pa.`id` = ?' +
  428. ' WHERE t.`project_id` = ? ) as new_t GROUP BY new_t.`tid`';
  429. const noticeSqlParam = [this.ctx.service.tender.tableName, tid, this.ctx.service.changeApply.tableName, caId, this.tableName, this.ctx.service.projectAccount.tableName, uid, pid];
  430. const content = await this.db.query(noticeSql, noticeSqlParam);
  431. if (content.length) {
  432. content[0].opinion = opinion;
  433. }
  434. return content.length ? JSON.stringify(content[0]) : '';
  435. }
  436. /**
  437. * 审批
  438. * @param {Number} caId - 立项书id
  439. * @param {auditConst.status.checked|auditConst.status.checkNo} checkType - 审批结果
  440. * @param {Number} times - 第几次审批
  441. * @return {Promise<void>}
  442. */
  443. async check(caId, checkData, times = 1) {
  444. if (checkData.checkType !== auditConst.status.checked && checkData.checkType !== auditConst.status.checkNo) {
  445. throw '提交数据错误';
  446. }
  447. const pid = this.ctx.session.sessionProject.id;
  448. switch (checkData.checkType) {
  449. case auditConst.status.checked:
  450. await this._checked(pid, caId, checkData, times);
  451. break;
  452. case auditConst.status.checkNo:
  453. await this._checkNo(pid, caId, checkData, times);
  454. break;
  455. default:
  456. throw '无效审批操作';
  457. }
  458. }
  459. async _checked(pid, caId, checkData, times) {
  460. const accountId = this.ctx.session.sessionUser.accountId;
  461. const time = new Date();
  462. // 整理当前流程审核人状态更新
  463. const audits = await this.getAllDataByCondition({ where: { caid: caId, times, status: auditConst.status.checking } });
  464. if (audits.length === 0) throw '审核数据错误';
  465. const selfAudit = audits.find(x => { return x.aid === accountId; });
  466. if (!selfAudit) throw '当前标段您无权审批';
  467. // const flowAudits = await this.getAllDataByCondition({ where: { caid: caId, times, order: selfAudit.order } });
  468. const nextAudits = await this.getAllDataByCondition({ where: { caid: caId, times, order: selfAudit.order + 1 } });
  469. const transaction = await this.db.beginTransaction();
  470. try {
  471. await transaction.update(this.tableName, {
  472. id: selfAudit.id,
  473. status: checkData.checkType,
  474. opinion: checkData.opinion,
  475. end_time: time,
  476. });
  477. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, selfAudit.id);
  478. // 获取推送必要信息
  479. const noticeContent = await this.getNoticeContent(pid, selfAudit.tid, caId, selfAudit.aid, checkData.opinion);
  480. // 添加推送
  481. const records = [];
  482. const auditors = await this.getAuditorsWithOwner(caId, times);
  483. auditors.forEach(audit => {
  484. records.push({ pid, type: pushType.changeApply, uid: audit.aid, status: auditConst.status.checked, content: noticeContent });
  485. });
  486. await transaction.insert('zh_notice', records);
  487. if (audits.length === 1 || selfAudit.audit_type !== auditType.key.and) {
  488. // 或签更新他人审批状态
  489. if (selfAudit.audit_type === auditType.key.or) {
  490. const updateOther = [];
  491. for (const audit of audits) {
  492. if (audit.aid === selfAudit.aid) continue;
  493. updateOther.push({
  494. id: audit.id,
  495. status: auditConst.status.checkSkip,
  496. opinion: '',
  497. end_time: time,
  498. });
  499. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, audit.id);
  500. }
  501. if (updateOther.length > 0) transaction.updateRows(this.tableName, updateOther);
  502. }
  503. // 无下一审核人表示,审核结束
  504. if (nextAudits.length > 0) {
  505. // 流程至下一审批人
  506. const updateData = nextAudits.map(x => { return { id: x.id, status: auditConst.status.checking, begin_time: time }; });
  507. await transaction.updateRows(this.tableName, updateData);
  508. // 同步 期信息
  509. await transaction.update(this.ctx.service.changeApply.tableName, {
  510. id: caId, status: auditConst.status.checking,
  511. });
  512. // 微信模板通知
  513. const shenpiUrl = await this.ctx.helper.urlToShort(
  514. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/change/apply/' + caId + '/information#shenpi'
  515. );
  516. // 微信模板通知
  517. const wechatData = {
  518. type: 'apply',
  519. wap_url: shenpiUrl,
  520. status: wxConst.status.check,
  521. tips: wxConst.tips.check,
  522. code: this.ctx.session.sessionProject.code,
  523. c_name: this.ctx.change.name,
  524. };
  525. await this.ctx.helper.sendWechat(this._.map(nextAudits, 'aid'), smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  526. for (const nextAudit of nextAudits) {
  527. await this.ctx.service.noticeAgain.addNoticeAgain(transaction, smsTypeConst.const.BG, {
  528. pid: this.ctx.session.sessionProject.id,
  529. tid: this.ctx.tender.id,
  530. uid: nextAudit.aid,
  531. sp_type: 'change',
  532. sp_id: nextAudit.id,
  533. table_name: this.tableName,
  534. template: wxConst.template.change,
  535. wx_data: wechatData,
  536. });
  537. }
  538. // 检查三方特殊推送
  539. await this.ctx.service.specMsg.addChangeApplyMsg(transaction, pid, this.ctx.change, pushOperate.change_apply.flow);
  540. } else {
  541. // 本期结束
  542. // 生成截止本期数据 final数据
  543. // 同步 期信息
  544. await transaction.update(this.ctx.service.changeApply.tableName, {
  545. id: caId, status: checkData.checkType,
  546. notice_code: checkData.notice_code,
  547. notice_uid: checkData.notice_uid,
  548. decimal: JSON.stringify(this.ctx.change.decimal),
  549. });
  550. // 微信模板通知
  551. const users = this._.uniq(this._.concat(this._.map(auditors, 'aid'), this.ctx.change.uid));
  552. // 微信模板通知
  553. const shenpiUrl = await this.ctx.helper.urlToShort(
  554. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/change/apply/' + caId + '/information#shenpi'
  555. );
  556. const wechatData = {
  557. type: 'apply',
  558. wap_url: shenpiUrl,
  559. status: wxConst.status.success,
  560. tips: wxConst.tips.success,
  561. code: this.ctx.session.sessionProject.code,
  562. c_name: this.ctx.change.name,
  563. };
  564. await this.ctx.helper.sendWechat(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), wxConst.template.change, wechatData);
  565. // 检查三方特殊推送
  566. await this.ctx.service.specMsg.addChangeApplyMsg(transaction, pid, this.ctx.change, pushOperate.change_apply.flow);
  567. await this.ctx.service.specMsg.addChangeApplyMsg(transaction, pid, this.ctx.change, pushOperate.change_apply.checked);
  568. }
  569. } else {
  570. // 同步 期信息
  571. await transaction.update(this.ctx.service.changeApply.tableName, {
  572. id: caId,
  573. status: auditConst.status.checking,
  574. });
  575. }
  576. await transaction.commit();
  577. } catch (err) {
  578. await transaction.rollback();
  579. throw err;
  580. }
  581. }
  582. async _checkNo(pid, caId, checkData, times) {
  583. const accountId = this.ctx.session.sessionUser.accountId;
  584. const time = new Date();
  585. const changeData = await this.ctx.service.changeApply.getDataById(caId);
  586. // 整理当前流程审核人状态更新
  587. const audits = await this.getAllDataByCondition({ where: { caid: caId, times, status: auditConst.status.checking } });
  588. if (!audits) throw '审核数据错误';
  589. const selfAudit = audits.find(x => { return x.aid === accountId; });
  590. if (!selfAudit) throw '当前标段您无权审批';
  591. const auditors = await this.getUniqAuditor(caId, times); // 全部参与的审批人
  592. const newAuditors = auditors.map(x => {
  593. return {
  594. aid: x.aid, tid: selfAudit.tid, caid: selfAudit.caid,
  595. times: times + 1, order: x.audit_order, status: auditConst.status.uncheck,
  596. audit_type: x.audit_type, audit_order: x.audit_order,
  597. };
  598. });
  599. const transaction = await this.db.beginTransaction();
  600. try {
  601. const updateData = [];
  602. audits.forEach(x => {
  603. updateData.push({
  604. id: x.id,
  605. status: x.aid === selfAudit.aid ? checkData.checkType : auditConst.status.checkSkip,
  606. opinion: x.aid === selfAudit.aid ? checkData.opinion : '',
  607. end_time: x.aid === selfAudit.aid ? time : null,
  608. });
  609. });
  610. await transaction.updateRows(this.tableName, updateData);
  611. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, this._.map(updateData, 'id'));
  612. // 添加到消息推送表
  613. const noticeContent = await this.getNoticeContent(pid, selfAudit.tid, caId, selfAudit.aid, checkData.opinion);
  614. const records = [{ pid, type: pushType.changeApply, uid: this.ctx.change.uid, status: auditConst.status.checkNo, content: noticeContent }];
  615. auditors.forEach(audit => {
  616. records.push({ pid, type: pushType.changeApply, uid: audit.aid, status: auditConst.status.checkNo, content: noticeContent });
  617. });
  618. await transaction.insert(this.ctx.service.noticePush.tableName, records);
  619. // 同步期信息
  620. await transaction.update(this.ctx.service.changeApply.tableName, {
  621. id: caId, status: checkData.checkType,
  622. times: times + 1,
  623. });
  624. // 拷贝新一次审核流程列表
  625. await transaction.insert(this.tableName, newAuditors);
  626. // 微信模板通知
  627. const users = this._.uniq(this._.concat(this._.map(auditors, 'aid'), this.ctx.change.uid));
  628. // 微信模板通知
  629. const shenpiUrl = await this.ctx.helper.urlToShort(
  630. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/change/apply/' + caId + '/information#shenpi'
  631. );
  632. const wechatData = {
  633. type: 'apply',
  634. wap_url: shenpiUrl,
  635. status: wxConst.status.back,
  636. tips: wxConst.tips.back,
  637. code: this.ctx.session.sessionProject.code,
  638. c_name: this.ctx.change.name,
  639. };
  640. await this.ctx.helper.sendWechat(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), wxConst.template.change, wechatData);
  641. // 生成内容保存表至zh_change_project_history中,用于撤回
  642. // 回退spamount值数据
  643. const changeList = await this.ctx.service.changeApplyList.getAllDataByCondition({ where: { caid: caId } });
  644. await this.ctx.service.changeApplyHistory.saveHistory(transaction, changeData, changeList);
  645. // 检查三方特殊推送
  646. await this.ctx.service.specMsg.addChangeApplyMsg(transaction, pid, this.ctx.change, pushOperate.change_apply.flow);
  647. await transaction.commit();
  648. } catch (err) {
  649. await transaction.rollback();
  650. throw err;
  651. }
  652. }
  653. /**
  654. * 复制上一期的审批人列表给最新一期
  655. *
  656. * @param transaction - 新增一期的事务
  657. * @param {Object} preMaterial - 上一期
  658. * @param {Object} newaMaterial - 最新一期
  659. * @return {Promise<*>}
  660. */
  661. async copyPreChangeApplyAuditors(transaction, preChange, newChange) {
  662. const auditList = await this.getUniqAuditor(preChange.id, preChange.times); // 全部参与的审批人
  663. const newAuditors = [];
  664. for (const x of auditList) {
  665. if (x.audit_order !== 0) {
  666. newAuditors.push({
  667. tid: preChange.tid, caid: newChange.id, aid: x.aid,
  668. times: 1, order: x.audit_order, status: auditConst.status.uncheck,
  669. audit_type: x.audit_type, audit_order: x.audit_order,
  670. });
  671. }
  672. }
  673. const result = newAuditors.length > 0 ? await transaction.insert(this.tableName, newAuditors) : null;
  674. return result ? result.affectedRows === newAuditors.length : true;
  675. }
  676. async getAllAuditors(tenderId) {
  677. const sql = 'SELECT ma.aid, ma.tid FROM ' + this.tableName + ' ma' +
  678. ' LEFT JOIN ' + this.ctx.service.tender.tableName + ' t On ma.tid = t.id' +
  679. ' WHERE t.id = ?' +
  680. ' GROUP BY ma.aid';
  681. const sqlParam = [tenderId];
  682. return this.db.query(sql, sqlParam);
  683. }
  684. /**
  685. * 审批撤回
  686. * @param {Number} stageId - 标段id
  687. * @param {Number} times - 第几次审批
  688. * @return {Promise<void>}
  689. */
  690. async checkCancel(change) {
  691. // 分3种情况,根据ctx.cancancel值判断:
  692. // 1.原报发起撤回,当前流程删除,并回到待上报
  693. // 2.审批人撤回审批通过,增加流程,并回到它审批中
  694. // 4.审批人撤回退回原报操作,删除新增的审批流,增加流程,回滚到它审批中
  695. // 5.会签审批人撤回审批通过(还有其他审批人未审批通过),仅修改本人流程状态
  696. switch (change.cancancel) {
  697. case 1: await this._userCheckCancel(change); break;
  698. case 2: await this._auditCheckCancel(change); break;
  699. case 4: await this._auditCheckCancelNo(change); break;
  700. case 5: await this._auditCheckCancelAnd(change); break;
  701. default: throw '不可撤回,请刷新页面重试';
  702. }
  703. }
  704. /**
  705. * 原报撤回,直接改动审批人状态
  706. * 如果存在审批人数据,将其改为原报流程数据,但保留原提交人
  707. *
  708. * 一审 1 A checking -> A uncheck status改 pay/jl:删0(jl为增量数据,只删重复部分) 1->0 删1
  709. * ...
  710. *
  711. * @param stage
  712. * @returns {Promise<void>}
  713. * @private
  714. */
  715. async _userCheckCancel(change) {
  716. const transaction = await this.db.beginTransaction();
  717. try {
  718. const updateData = change.curAuditors.map(x => {
  719. return {
  720. id: x.id,
  721. status: auditConst.status.uncheck,
  722. begin_time: null, opinion: null,
  723. };
  724. });
  725. await transaction.updateRows(this.tableName, updateData);
  726. await this.ctx.service.noticeAgain.deleteNoticeAgain(transaction, this.tableName, this._.map(updateData, 'id'));
  727. // 变成待上报状态
  728. await transaction.update(this.ctx.service.changeApply.tableName, {
  729. id: change.id,
  730. status: change.times === 1 ? auditConst.status.uncheck : auditConst.status.checkNo,
  731. });
  732. await transaction.commit();
  733. } catch (err) {
  734. await transaction.rollback();
  735. throw err;
  736. }
  737. }
  738. /**
  739. * 审批人撤回审批通过,插入两条数据
  740. *
  741. * 一审 1 A checked 一审 1 A checked
  742. * 二审 2 B checked pre -> 二审 2 B checked
  743. * 三审 3 C checking cur 二审 3 B checkCancel 增 增extra_his 增tp_his
  744. * 四审 4 D uncheck 二审 4 B checking 增 增pay_cur
  745. * 三审 5 C uncheck order、status改
  746. * 四审 6 D uncheck order改
  747. *
  748. * @param stage
  749. * @returns {Promise<void>}
  750. * @private
  751. */
  752. async _auditCheckCancel(change) {
  753. if (change.curAuditors.length === 0 || change.curAuditors[0].order <= 1) {
  754. throw '撤回用户数据错误';
  755. }
  756. const accountId = this.ctx.session.sessionUser.accountId;
  757. const selfAuditor = change.preAuditors.find(x => { return x.aid === accountId; });
  758. if (!selfAuditor) throw '撤回用户数据错误';
  759. const time = new Date();
  760. const transaction = await this.db.beginTransaction();
  761. try {
  762. // 顺移其后审核人流程顺序
  763. const sql = 'UPDATE ' + this.tableName + ' SET `order` = `order` + 2 WHERE caid = ? AND times = ? AND `order` > ?';
  764. await transaction.query(sql, [change.id, selfAuditor.times, change.curAuditors[0].order]);
  765. // 当前审批人2次添加至流程中
  766. const checkCancelAuditors = [],
  767. checkingAuditors = [];
  768. change.preAuditors.forEach(x => {
  769. checkCancelAuditors.push({
  770. tid: change.tid, caid: change.id, aid: x.aid,
  771. times: x.times, order: x.order + 1,
  772. status: x.aid === selfAuditor.aid ? auditConst.status.checkCancel : auditConst.status.checkSkip,
  773. begin_time: time, end_time: time, opinion: '',
  774. audit_type: x.audit_type, audit_order: x.audit_order,
  775. });
  776. });
  777. change.preAuditors.forEach(x => {
  778. checkingAuditors.push({
  779. tid: change.tid, caid: change.id, aid: x.aid,
  780. times: x.times, order: x.order + 2,
  781. status: auditConst.status.checking,
  782. begin_time: time, end_time: time, opinion: '',
  783. audit_type: x.audit_type, audit_order: x.audit_order,
  784. });
  785. });
  786. await transaction.insert(this.tableName, [...checkCancelAuditors, ...checkingAuditors]);
  787. // 当前审批人变成待审批
  788. await transaction.updateRows(this.tableName, change.curAuditors.map(x => {
  789. return { id: x.id, begin_time: null, status: auditConst.status.uncheck, order: x.order + 2 };
  790. }));
  791. await this.ctx.service.noticeAgain.deleteNoticeAgain(transaction, this.tableName, this._.map(change.curAuditors, 'id'));
  792. await transaction.commit();
  793. } catch (err) {
  794. await transaction.rollback();
  795. throw err;
  796. }
  797. }
  798. /**
  799. * 审批人撤回审批退回原报
  800. *
  801. * 1# 一审 1 A checked 1# 一审 1 A checked
  802. * 二审 2 B checkNo pre -> 二审 2 B checkNo
  803. * 三审 3 C uncheck 二审 3 B checkCancel 增 pay: 2#0 -> 1#3 jl: 2#0 -> 1#3 增tp_his 增extra_his
  804. * 二审 4 B checking 增 pay: 2#0 -> 1#4
  805. * 三审 5 C uncheck order改
  806. *
  807. * 2# 一审 1 A uncheck 2# 删 pay: 2#0删 jl: 2#0删
  808. * 二审 2 B uncheck
  809. * 三审 3 C uncheck
  810. *
  811. * @param stage
  812. * @returns {Promise<void>}
  813. * @private
  814. */
  815. async _auditCheckCancelNo(change) {
  816. const accountId = this.ctx.session.sessionUser.accountId;
  817. const selfAuditor = change.preAuditors.find(x => { return x.aid === accountId && x.status === auditConst.status.checkNo; });
  818. if (!selfAuditor) throw '该标段由他人审批退回,您不可撤回';
  819. const time = new Date();
  820. const transaction = await this.db.beginTransaction();
  821. try {
  822. // 整理上一个流程审核人状态更新
  823. // 顺移其后审核人流程顺序
  824. const sql = 'UPDATE ' + this.tableName + ' SET `order` = `order` + 2 WHERE caid = ? AND times = ? AND `order` > ?';
  825. await transaction.query(sql, [change.id, selfAuditor.times, selfAuditor.order]);
  826. // 当前审批人2次添加至流程中
  827. const checkCancelAuditors = [],
  828. checkingAuditors = [];
  829. change.preAuditors.forEach(x => {
  830. checkCancelAuditors.push({
  831. tid: change.tid, caid: change.id, aid: x.aid,
  832. times: x.times, order: x.order + 1,
  833. status: x.aid === selfAuditor.aid ? auditConst.status.checkCancel : auditConst.status.checkSkip,
  834. begin_time: time, end_time: time, opinion: '',
  835. audit_type: x.audit_type, audit_order: x.audit_order,
  836. });
  837. });
  838. change.preAuditors.forEach(x => {
  839. checkingAuditors.push({
  840. tid: change.tid, caid: change.id, aid: x.aid,
  841. times: x.times, order: x.order + 2,
  842. status: auditConst.status.checking,
  843. begin_time: time, end_time: time, opinion: '',
  844. audit_type: x.audit_type, audit_order: x.audit_order,
  845. });
  846. });
  847. await transaction.insert(this.tableName, [...checkCancelAuditors, ...checkingAuditors]);
  848. // 删除当前次审批流
  849. await transaction.delete(this.tableName, { caid: change.id, times: change.times });
  850. // 回退数据
  851. await this.ctx.service.changeApplyHistory.returnHistory(transaction, change.id);
  852. await transaction.delete(this.ctx.service.changeApplyHistory.tableName, { caid: change.id });
  853. // // 设置变更立项为审批中
  854. // await transaction.update(this.ctx.service.changeApply.tableName, {
  855. // id: change.id,
  856. // time: change.times - 1,
  857. // status: auditConst.status.checking,
  858. // });
  859. await transaction.commit();
  860. } catch (err) {
  861. await transaction.rollback();
  862. throw err;
  863. }
  864. }
  865. /**
  866. * 会签未全部审批通过时,撤回仅修改本人状态
  867. *
  868. * @param stage
  869. * @returns {Promise<void>}
  870. * @private
  871. */
  872. async _auditCheckCancelAnd(change) {
  873. const accountId = this.ctx.session.sessionUser.accountId;
  874. const selfAuditor = change.flowAuditors.find(x => { return x.aid === accountId; });
  875. if (!selfAuditor || selfAuditor.status !== auditConst.status.checked) throw '不可撤回';
  876. const transaction = await this.db.beginTransaction();
  877. try {
  878. await transaction.update(this.tableName, {
  879. id: selfAuditor.id, status: auditConst.status.checking, opinion: '', end_time: null,
  880. });
  881. await transaction.commit();
  882. } catch (err) {
  883. await transaction.rollback();
  884. throw err;
  885. }
  886. }
  887. /**
  888. * 重新审批变更令
  889. * @param { string } cid - 查询的清单
  890. * @return {Promise<*>} - 可用的变更令列表
  891. */
  892. async checkRevise(change) {
  893. const accountId = this.ctx.session.sessionUser.accountId;
  894. const time = new Date();
  895. // 初始化事务
  896. const transaction = await this.db.beginTransaction();
  897. let result = false;
  898. try {
  899. const pid = this.ctx.session.sessionProject.id;
  900. // 获取审核人列表
  901. const auditors = await this.getUniqAuditor(change.id, change.times); // 全部参与的审批人
  902. // 添加到消息推送表
  903. const noticeContent = await this.getNoticeContent(pid, change.tid, change.id, this.ctx.session.sessionUser.accountId, '发起修订');
  904. const records = [{ pid, type: pushType.changeProject, uid: change.uid, status: auditConst.status.revise, content: noticeContent }];
  905. auditors.forEach(auditor => {
  906. records.push({
  907. pid,
  908. type: pushType.changeApply,
  909. uid: auditor.aid,
  910. status: auditConst.status.revise,
  911. content: noticeContent,
  912. });
  913. });
  914. await transaction.insert('zh_notice', records);
  915. const order = change.auditors.length > 0 ? change.auditors.reduce((rst, a) => { return Math.max(rst, a.order); }, 0) + 1 : 1; // 最大值 + 1
  916. // 当前审批人添加至流程中
  917. const checkReviseAuditor = {
  918. tid: change.tid, caid: change.id, aid: change.uid,
  919. times: change.times, order,
  920. status: auditConst.status.revise,
  921. begin_time: time, end_time: time, opinion: '',
  922. audit_type: auditType.key.common, audit_order: 0,
  923. };
  924. await transaction.insert(this.tableName, checkReviseAuditor);
  925. // 修订人加入审批流程
  926. const newAuditors = auditors.map(x => {
  927. return {
  928. aid: x.aid, tid: change.tid, caid: change.id,
  929. times: change.times + 1, order: x.audit_order, status: auditConst.status.uncheck,
  930. audit_type: x.audit_type, audit_order: x.audit_order,
  931. };
  932. });
  933. await transaction.insert(this.tableName, newAuditors);
  934. // 生成内容保存表至zh_change_history中,用于撤销修订回退
  935. const changeData = await transaction.get(this.ctx.service.changeApply.tableName, { id: change.id });
  936. const changeList = await this.ctx.service.changeApplyList.getAllDataByCondition({ where: { caid: change.id } });
  937. await this.ctx.service.changeApplyHistory.saveHistory(transaction, changeData, changeList);
  938. // 设置变更立项修订状态
  939. await transaction.update(this.ctx.service.changeApply.tableName, {
  940. id: change.id,
  941. notice_code: null,
  942. notice_uid: null,
  943. decimal: null,
  944. status: auditConst.status.revise,
  945. times: change.times + 1,
  946. final_auditor_str: '',
  947. });
  948. await transaction.commit();
  949. result = true;
  950. } catch (error) {
  951. console.log(error);
  952. await transaction.rollback();
  953. result = false;
  954. }
  955. return result;
  956. }
  957. /**
  958. * 撤销修订变更令
  959. * @param { string } cid - 查询的清单
  960. * @return {Promise<*>} - 可用的变更令列表
  961. */
  962. async cancelRevise(change) {
  963. const time = new Date();
  964. // 初始化事务
  965. const transaction = await this.db.beginTransaction();
  966. let result = false;
  967. try {
  968. const pid = this.ctx.session.sessionProject.id;
  969. // 获取审核人列表
  970. const auditors = await this.getUniqAuditor(change.id, change.times - 1); // 全部参与的审批人
  971. // 添加到消息推送表
  972. const noticeContent = await this.getNoticeContent(pid, change.tid, change.id, this.ctx.session.sessionUser.accountId, '撤销修订');
  973. const records = [{ pid, type: pushType.changeProject, uid: change.uid, status: auditConst.status.cancelRevise, content: noticeContent }];
  974. auditors.forEach(auditor => {
  975. records.push({
  976. pid,
  977. type: pushType.changeApply,
  978. uid: auditor.aid,
  979. status: auditConst.status.cancelRevise,
  980. content: noticeContent,
  981. });
  982. });
  983. await transaction.insert('zh_notice', records);
  984. const lastAudit = await this.getLastAudit(change.id, change.times - 1);
  985. // 新增一个撤销修订状态到审批流程中
  986. const revise_audit = {
  987. tid: change.tid, caid: change.id, aid: this.ctx.session.sessionUser.accountId,
  988. times: change.times - 1, order: lastAudit.order + 1, status: auditConst.status.cancelRevise,
  989. begin_time: time, end_time: time, opinion: '',
  990. audit_type: lastAudit.audit_type, audit_order: lastAudit.audit_order,
  991. };
  992. await transaction.insert(this.tableName, revise_audit);
  993. await transaction.delete(this.tableName, { caid: change.id, times: change.times });
  994. await this.ctx.service.changeApplyHistory.returnHistory(transaction, change.id);
  995. await transaction.delete(this.ctx.service.changeApplyHistory.tableName, { caid: change.id });
  996. await transaction.commit();
  997. result = true;
  998. } catch (error) {
  999. console.log(error);
  1000. await transaction.rollback();
  1001. result = false;
  1002. }
  1003. return result;
  1004. }
  1005. /**
  1006. * 重新审批变更申请
  1007. * @param { string } cid - 查询的清单
  1008. * @return {Promise<*>} - 可用的变更令列表
  1009. */
  1010. async checkAgain(change) {
  1011. const accountId = this.ctx.session.sessionUser.accountId;
  1012. // 初始化事务
  1013. const time = new Date();
  1014. const transaction = await this.db.beginTransaction();
  1015. let result = false;
  1016. try {
  1017. const noYbAuditors = change.auditors.filter(x => { return x.audit_order !== 0; });
  1018. const noYbMaxOrder = noYbAuditors[noYbAuditors.length - 1].order;
  1019. const maxOrder = change.auditors[change.auditors.length - 1].order;
  1020. const audits = change.auditors.filter(x => { return x.order === noYbMaxOrder; });
  1021. if (!audits || audits.length === 0 || maxOrder < 1) throw '审核数据错误';
  1022. const selfAudit = audits.find(x => { return x.aid === accountId; });
  1023. if (!selfAudit) throw '当前标段您无权审批';
  1024. // 当前审批人2次添加至流程中
  1025. const checkAgainAuditors = [];
  1026. audits.forEach(x => {
  1027. checkAgainAuditors.push({
  1028. tid: change.tid, caid: change.id, aid: x.aid,
  1029. times: x.times, order: maxOrder + 1,
  1030. status: !selfAudit || x.aid === selfAudit.aid ? auditConst.status.checkAgain : auditConst.status.checkSkip,
  1031. begin_time: time, end_time: time, opinion: '',
  1032. audit_type: x.audit_type, audit_order: x.audit_order,
  1033. });
  1034. });
  1035. const checkingAuditors = [];
  1036. audits.forEach(x => {
  1037. checkingAuditors.push({
  1038. tid: change.tid, caid: change.id, aid: x.aid,
  1039. times: x.times, order: maxOrder + 2,
  1040. status: auditConst.status.checking,
  1041. begin_time: time,
  1042. audit_type: x.audit_type, audit_order: x.audit_order,
  1043. });
  1044. });
  1045. await transaction.insert(this.tableName, checkAgainAuditors);
  1046. const checkingAuditors_result = await transaction.insert(this.tableName, checkingAuditors);
  1047. // 获取刚批量添加的所有list
  1048. // for (let j = 0; j < checkingAuditors.length; j++) {
  1049. // checkingAuditors[j].id = checkingAuditors_result.insertId + j;
  1050. // }
  1051. // 设置变更令审批中
  1052. await transaction.update(this.ctx.service.changeApply.tableName, {
  1053. id: change.id,
  1054. status: auditConst.status.checking,
  1055. notice_code: null,
  1056. notice_uid: null,
  1057. decimal: null,
  1058. final_auditor_str: '',
  1059. });
  1060. // 检查三方特殊推送
  1061. await this.ctx.service.specMsg.addChangeApplyMsg(transaction, this.ctx.session.sessionProject.id, this.ctx.change, pushOperate.change_apply.flow);
  1062. await transaction.commit();
  1063. result = true;
  1064. } catch (error) {
  1065. await transaction.rollback();
  1066. result = false;
  1067. }
  1068. return result;
  1069. }
  1070. async getAuditorGroup(caId, times) {
  1071. const auditors = await this.getAuditors(caId, times); // 全部参与的审批人
  1072. return this.ctx.helper.groupAuditors(auditors, 'order', true);
  1073. }
  1074. async getUserGroup(caId, times) {
  1075. const group = await this.getAuditorGroup(caId, times);
  1076. const sql =
  1077. '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' +
  1078. ' FROM ' + this.ctx.service.changeApply.tableName + ' As s' +
  1079. ' LEFT JOIN ' + this.ctx.service.projectAccount.tableName + ' As pa' +
  1080. ' ON s.uid = pa.id' +
  1081. ' WHERE s.id = ?';
  1082. const sqlParam = [times, caId, caId];
  1083. const user = await this.db.queryOne(sql, sqlParam);
  1084. user.audit_order = 0;
  1085. group.unshift([ user ]);
  1086. return group;
  1087. }
  1088. async getUniqUserGroup(caId, times) {
  1089. const group = await this.getAuditorGroup(caId, times);
  1090. const sql =
  1091. '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' +
  1092. ' FROM ' + this.ctx.service.changeApply.tableName + ' As s' +
  1093. ' LEFT JOIN ' + this.ctx.service.projectAccount.tableName + ' As pa' +
  1094. ' ON s.uid = pa.id' +
  1095. ' WHERE s.id = ?';
  1096. const sqlParam = [times, caId, caId];
  1097. const user = await this.db.queryOne(sql, sqlParam);
  1098. user.audit_order = 0;
  1099. group.unshift([ user ]);
  1100. return this.ctx.helper.groupAuditorsUniq(group);
  1101. }
  1102. async getAuditorHistory(caId, times, reverse = false) {
  1103. const history = [];
  1104. if (times >= 1) {
  1105. for (let i = 1; i <= times; i++) {
  1106. const auditors = await this.getAuditors(caId, i);
  1107. const group = this.ctx.helper.groupAuditors(auditors);
  1108. const historyGroup = [];
  1109. // 找出group里audit_order最大值
  1110. const max_info = group.length > 0 ? this._.maxBy(group, function(item) {
  1111. return item && item[0] && item[0].audit_order;
  1112. }) : null;
  1113. const max_order = max_info ? max_info[0].audit_order : -1;
  1114. for (const g of group) {
  1115. const his = {
  1116. beginYear: '', beginDate: '', beginTime: '', endYear: '', endDate: '', endTime: '', begin_time: null, end_time: null,
  1117. audit_type: g[0].audit_type, audit_order: g[0].audit_order,
  1118. auditors: g,
  1119. };
  1120. if (his.audit_type === auditType.key.common) {
  1121. his.name = g[0].name;
  1122. } else {
  1123. his.name = this.ctx.helper.transFormToChinese(his.audit_order) + '审';
  1124. }
  1125. his.is_final = his.audit_order === max_order;
  1126. if (g[0].begin_time) {
  1127. his.begin_time = g[0].begin_time;
  1128. const beginTime = this.ctx.moment(g[0].begin_time);
  1129. his.beginYear = beginTime.format('YYYY');
  1130. his.beginDate = beginTime.format('MM-DD');
  1131. his.beginTime = beginTime.format('HH:mm:ss');
  1132. }
  1133. let end_time;
  1134. g.forEach(x => {
  1135. if (x.status === auditConst.status.checkSkip) return;
  1136. if (!his.status || x.status === auditConst.status.checking) his.status = x.status;
  1137. if (x.end_time && (!end_time || x.end_time > end_time)) {
  1138. end_time = x.end_time;
  1139. if (his.status !== auditConst.status.checking) his.status = x.status;
  1140. }
  1141. });
  1142. if (end_time) {
  1143. his.end_time = end_time;
  1144. const endTime = this.ctx.moment(end_time);
  1145. his.endYear = endTime.format('YYYY');
  1146. his.endDate = endTime.format('MM-DD');
  1147. his.endTime = endTime.format('HH:mm:ss');
  1148. }
  1149. historyGroup.push(his);
  1150. }
  1151. if (reverse) {
  1152. history.push(historyGroup.reverse());
  1153. } else {
  1154. history.push(historyGroup);
  1155. }
  1156. }
  1157. }
  1158. return history;
  1159. }
  1160. async getUniqAuditor(caId, times) {
  1161. const auditors = await this.getAuditors(caId, times); // 全部参与的审批人
  1162. const result = [];
  1163. auditors.forEach(x => {
  1164. if (result.findIndex(r => { return x.aid === r.aid && x.audit_order === r.audit_order; }) < 0) {
  1165. result.push(x);
  1166. }
  1167. });
  1168. return result;
  1169. }
  1170. async saveAudit(caId, times, sp_group, data) {
  1171. const transaction = await this.db.beginTransaction();
  1172. try {
  1173. const auditors = await this.getAuditGroupByList(caId, times);
  1174. const now_audit = this._.find(auditors, { aid: data.old_aid });
  1175. if (data.operate !== 'del') {
  1176. const exist = await this.getDataByCondition({ caid: caId, times, aid: data.new_aid });
  1177. if (exist) throw '该审核人已存在,请勿重复添加';
  1178. }
  1179. if (data.operate === 'add') {
  1180. if (now_audit.status !== auditConst.status.uncheck && now_audit.status !== auditConst.status.checking) {
  1181. throw '当前人下无法操作新增';
  1182. }
  1183. const newAudit = {
  1184. tid: this.ctx.tender.id, caid: caId, aid: data.new_aid,
  1185. order: now_audit.order + 1,
  1186. audit_order: now_audit.audit_order + 1, audit_type: auditType.key.common,
  1187. times, status: auditConst.status.uncheck,
  1188. };
  1189. // order+1
  1190. await this._syncOrderByDelete(transaction, caId, now_audit.order + 1, times, '+');
  1191. await transaction.insert(this.tableName, newAudit);
  1192. // 更新审批流程页数据,如果存在
  1193. } else if (data.operate === 'add-sibling') {
  1194. if (now_audit.status !== auditConst.status.uncheck && now_audit.status !== auditConst.status.checking) {
  1195. throw '当前人下无法操作新增';
  1196. }
  1197. const newAudit = {
  1198. tid: this.ctx.tender.id, caid: caId, aid: data.new_aid,
  1199. order: now_audit.order,
  1200. audit_order: now_audit.audit_order, audit_type: now_audit.audit_type,
  1201. times, status: auditConst.status.uncheck,
  1202. };
  1203. await transaction.insert(this.tableName, newAudit);
  1204. } else if (data.operate === 'del') {
  1205. if (now_audit.status !== auditConst.status.uncheck) {
  1206. throw '当前人无法操作删除';
  1207. }
  1208. const flowAuditors = auditors.filter(x => { return x.audit_order === now_audit.audit_order; });
  1209. await transaction.delete(this.tableName, { caid: caId, times, aid: now_audit.aid, order: now_audit.order });
  1210. if (flowAuditors.length === 1) await this._syncOrderByDelete(transaction, caId, now_audit.order, times);
  1211. // 旧的更新为is_old为1
  1212. // await transaction.update(this.tableName, { is_old: 1 }, {
  1213. // where: {
  1214. // sid: stageId,
  1215. // times,
  1216. // aid: data.old_aid,
  1217. // }
  1218. // });
  1219. } else if (data.operate === 'change') {
  1220. const nowAudit = await this.getDataByCondition({ caid: caId, times, aid: now_audit.aid, order: now_audit.order });
  1221. if (now_audit.status !== auditConst.status.uncheck || !nowAudit) {
  1222. throw '当前人无法操作替换';
  1223. }
  1224. nowAudit.aid = data.new_aid;
  1225. await transaction.update(this.tableName, nowAudit);
  1226. // 旧的更新为is_old为1
  1227. // await transaction.update(this.tableName, { is_old: 1 }, {
  1228. // where: {
  1229. // sid: stageId,
  1230. // times,
  1231. // aid: data.old_aid,
  1232. // }
  1233. // });
  1234. }
  1235. if (this.ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdspl) {
  1236. const newAuditors = await transaction.select(this.tableName, { where: { caid: caId, times }, orders: [['order', 'asc']] });
  1237. const newAuditorGroup = this.ctx.helper.groupAuditors(newAuditors, 'order', true);
  1238. const uniqNewAuditorGroup = this.ctx.helper.groupAuditorsUniq(newAuditorGroup);
  1239. // await this.ctx.service.shenpiAudit.updateAuditListWithAuditType(transaction, this.ctx.tender.id, this.ctx.tender.info.shenpi.change, shenpiConst.sp_type.change, uniqNewAuditorGroup, sp_group);
  1240. } else if (this.ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdzs) {
  1241. const newAuditors = await this.getAuditGroupByList(caId, times, transaction);
  1242. 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'));
  1243. }
  1244. // 更新到审批流程方法
  1245. await transaction.commit();
  1246. } catch (err) {
  1247. await transaction.rollback();
  1248. throw err;
  1249. }
  1250. }
  1251. async changeSpGroup(change, sp_group) {
  1252. const transaction = await this.db.beginTransaction();
  1253. try {
  1254. const group = await this.ctx.service.shenpiGroup.getDataById(sp_group);
  1255. if (!group) {
  1256. throw '该固定审批组不存在,请刷新页面重新获取';
  1257. }
  1258. 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 } });
  1259. await this.ctx.service.shenpiAudit.noYbShenpiList(change.uid, shenpiList);
  1260. await this.updateNewAuditors(change, shenpiList, transaction);
  1261. await transaction.update(this.ctx.service.changeApply.tableName, { id: change.id, sp_group: group.id });
  1262. await transaction.commit();
  1263. } catch (err) {
  1264. await transaction.rollback();
  1265. throw err;
  1266. }
  1267. return true;
  1268. }
  1269. async updateNewAuditList(change, newList) {
  1270. const transaction = await this.db.beginTransaction();
  1271. try {
  1272. await this.updateNewAuditors(change, newList, transaction);
  1273. await transaction.commit();
  1274. } catch (err) {
  1275. await transaction.rollback();
  1276. throw err;
  1277. }
  1278. }
  1279. async updateNewAuditors(change, newList, transaction) {
  1280. // 先删除旧的审批流,再添加新的
  1281. await transaction.delete(this.tableName, { caid: change.id, times: change.times });
  1282. const newAuditors = [];
  1283. for (const auditor of newList) {
  1284. newAuditors.push({
  1285. tid: change.tid, caid: change.id, aid: auditor.audit_id,
  1286. times: change.times, order: auditor.audit_order, status: auditConst.status.uncheck,
  1287. audit_type: auditor.audit_type, audit_order: auditor.audit_order,
  1288. });
  1289. }
  1290. if (newAuditors.length > 0) await transaction.insert(this.tableName, newAuditors);
  1291. }
  1292. async updateLastAudit(change, auditList, lastId) {
  1293. const transaction = await this.db.beginTransaction();
  1294. try {
  1295. // 先判断auditList里的aid是否与lastId相同,相同则删除并重新更新order
  1296. const existAudit = auditList.find(x => { return x.aid === lastId; });
  1297. let order = auditList.length > 0 ? auditList.reduce((rst, a) => { return Math.max(rst, a.order); }, 0) + 1 : 1; // 最大值 + 1
  1298. if (existAudit) {
  1299. await transaction.delete(this.tableName, { caid: change.id, times: change.times, aid: lastId });
  1300. const sameOrder = auditList.filter(x => { return x.order === existAudit.order; });
  1301. if (sameOrder.length === 1) {
  1302. const updateData = [];
  1303. auditList.forEach(x => {
  1304. if (x.order <= existAudit.order) return;
  1305. updateData.push({ id: x.id, order: x.order - 1, audit_order: x.audit_order - 1 });
  1306. });
  1307. if (updateData.length > 0) {
  1308. await transaction.updateRows(updateData);
  1309. }
  1310. order = order - 1;
  1311. }
  1312. }
  1313. // 添加终审
  1314. const newAuditor = {
  1315. tid: change.tid, caid: change.id, aid: lastId,
  1316. times: change.times, order, status: auditConst.status.uncheck,
  1317. audit_type: auditType.key.common, audit_order: order,
  1318. };
  1319. await transaction.insert(this.tableName, newAuditor);
  1320. await transaction.commit();
  1321. } catch (err) {
  1322. await transaction.rollback();
  1323. throw err;
  1324. }
  1325. }
  1326. /**
  1327. * 取待审批期列表(wap用)
  1328. *
  1329. * @param auditorId
  1330. * @return {Promise<*>}
  1331. */
  1332. async getAuditChangeApplyByWap(auditorId) {
  1333. const sql =
  1334. 'SELECT sa.`aid`, sa.`times`, sa.`begin_time`, sa.`end_time`, sa.`tid`, sa.`caid`,' +
  1335. ' s.*,' +
  1336. ' t.`name` as `t_name`, t.`project_id`, t.`type`, t.`user_id`, t.`spid`, ' +
  1337. ' ti.`deal_info`, ti.`decimal` ' +
  1338. ' FROM ?? AS sa' +
  1339. ' Left Join ?? AS s On sa.`caid` = s.`id`' +
  1340. ' Left Join ?? As t On sa.`tid` = t.`id`' +
  1341. ' Left Join ?? AS ti ON ti.`tid` = t.`id`' +
  1342. ' WHERE sa.`aid` = ? and sa.`status` = ?';
  1343. const sqlParam = [
  1344. this.tableName,
  1345. this.ctx.service.changeApply.tableName,
  1346. this.ctx.service.tender.tableName,
  1347. this.ctx.service.tenderInfo.tableName,
  1348. auditorId,
  1349. auditConst.status.checking,
  1350. ];
  1351. return await this.db.query(sql, sqlParam);
  1352. }
  1353. }
  1354. return ChangeApplyAudit;
  1355. };