change_apply_audit.js 72 KB

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