From 22a0a946138f885568c29aef6ad8fc63160354ae Mon Sep 17 00:00:00 2001 From: "Captain.B" Date: Tue, 1 Dec 2020 15:43:32 +0800 Subject: [PATCH 1/2] =?UTF-8?q?refactor:=20=E9=87=8D=E6=9E=84=E5=8F=91?= =?UTF-8?q?=E9=80=81=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../api/jmeter/APIBackendListenerClient.java | 108 +-- .../api/service/APITestService.java | 8 +- .../io/metersphere/base/domain/Notice.java | 21 - .../base/domain/NoticeExample.java | 620 ------------------ .../metersphere/base/mapper/NoticeMapper.java | 30 - .../metersphere/base/mapper/NoticeMapper.xml | 228 ------- .../base/mapper/ext/ExtMessageMapper.java | 12 - .../base/mapper/ext/ExtMessageMapper.xml | 23 - .../commons/constants/NoticeConstants.java | 49 +- .../commons/utils/SessionUtils.java | 4 +- .../io/metersphere/config/AsyncConfig.java | 21 + .../notice/controller/NoticeController.java | 14 +- .../controller/request/NoticeRequest.java | 12 - .../notice/domain/NoticeDetail.java | 12 - .../notice/sender/AbstractNoticeSender.java | 127 ++++ .../notice/sender/NoticeModel.java | 47 ++ .../notice/sender/NoticeSender.java | 9 + .../notice/sender/impl/DingNoticeSender.java | 47 ++ .../notice/sender/impl/MailNoticeSender.java | 62 ++ .../notice/sender/impl/WeComNoticeSender.java | 39 ++ .../notice/service/DingTaskService.java | 74 --- .../notice/service/MailService.java | 400 +---------- .../notice/service/NoticeSendService.java | 63 ++ .../notice/service/NoticeService.java | 182 +++-- .../notice/service/WxChatTaskService.java | 66 -- .../notice/PerformanceNoticeTask.java | 133 +--- .../service/PerformanceTestService.java | 2 +- .../track/service/IssuesService.java | 55 +- .../track/service/TestCaseCommentService.java | 68 +- .../track/service/TestCaseReviewService.java | 189 +++--- .../track/service/TestPlanService.java | 198 +++--- .../components/DefectTaskNotification.vue | 47 +- .../components/JenkinsNotification.vue | 42 +- .../components/TestPlanTaskNotification.vue | 47 +- .../components/TestReviewNotification.vue | 47 +- 35 files changed, 916 insertions(+), 2190 deletions(-) delete mode 100644 backend/src/main/java/io/metersphere/base/domain/Notice.java delete mode 100644 backend/src/main/java/io/metersphere/base/domain/NoticeExample.java delete mode 100644 backend/src/main/java/io/metersphere/base/mapper/NoticeMapper.java delete mode 100644 backend/src/main/java/io/metersphere/base/mapper/NoticeMapper.xml delete mode 100644 backend/src/main/java/io/metersphere/base/mapper/ext/ExtMessageMapper.java delete mode 100644 backend/src/main/java/io/metersphere/base/mapper/ext/ExtMessageMapper.xml create mode 100644 backend/src/main/java/io/metersphere/config/AsyncConfig.java delete mode 100644 backend/src/main/java/io/metersphere/notice/controller/request/NoticeRequest.java delete mode 100644 backend/src/main/java/io/metersphere/notice/domain/NoticeDetail.java create mode 100644 backend/src/main/java/io/metersphere/notice/sender/AbstractNoticeSender.java create mode 100644 backend/src/main/java/io/metersphere/notice/sender/NoticeModel.java create mode 100644 backend/src/main/java/io/metersphere/notice/sender/NoticeSender.java create mode 100644 backend/src/main/java/io/metersphere/notice/sender/impl/DingNoticeSender.java create mode 100644 backend/src/main/java/io/metersphere/notice/sender/impl/MailNoticeSender.java create mode 100644 backend/src/main/java/io/metersphere/notice/sender/impl/WeComNoticeSender.java delete mode 100644 backend/src/main/java/io/metersphere/notice/service/DingTaskService.java create mode 100644 backend/src/main/java/io/metersphere/notice/service/NoticeSendService.java delete mode 100644 backend/src/main/java/io/metersphere/notice/service/WxChatTaskService.java diff --git a/backend/src/main/java/io/metersphere/api/jmeter/APIBackendListenerClient.java b/backend/src/main/java/io/metersphere/api/jmeter/APIBackendListenerClient.java index 440d97e4d7..b89acef861 100644 --- a/backend/src/main/java/io/metersphere/api/jmeter/APIBackendListenerClient.java +++ b/backend/src/main/java/io/metersphere/api/jmeter/APIBackendListenerClient.java @@ -12,12 +12,9 @@ import io.metersphere.commons.constants.TestPlanTestCaseStatus; import io.metersphere.commons.utils.CommonBeanFactory; import io.metersphere.commons.utils.LogUtil; import io.metersphere.dto.BaseSystemConfigDTO; -import io.metersphere.notice.domain.MessageDetail; -import io.metersphere.notice.domain.MessageSettingDetail; -import io.metersphere.notice.service.DingTaskService; -import io.metersphere.notice.service.MailService; -import io.metersphere.notice.service.NoticeService; -import io.metersphere.notice.service.WxChatTaskService; +import io.metersphere.i18n.Translator; +import io.metersphere.notice.sender.NoticeModel; +import io.metersphere.notice.service.NoticeSendService; import io.metersphere.service.SystemParameterService; import io.metersphere.track.service.TestPlanTestCaseService; import org.apache.commons.lang3.StringUtils; @@ -50,12 +47,6 @@ public class APIBackendListenerClient extends AbstractBackendListenerClient impl private APIReportService apiReportService; - private TestPlanTestCaseService testPlanTestCaseService; - - private NoticeService noticeService; - - private MailService mailService; - private ApiDefinitionService apiDefinitionService; private ApiDefinitionExecResultService apiDefinitionExecResultService; @@ -92,18 +83,6 @@ public class APIBackendListenerClient extends AbstractBackendListenerClient impl if (apiReportService == null) { LogUtil.error("apiReportService is required"); } - testPlanTestCaseService = CommonBeanFactory.getBean(TestPlanTestCaseService.class); - if (testPlanTestCaseService == null) { - LogUtil.error("testPlanTestCaseService is required"); - } - noticeService = CommonBeanFactory.getBean(NoticeService.class); - if (noticeService == null) { - LogUtil.error("noticeService is required"); - } - mailService = CommonBeanFactory.getBean(MailService.class); - if (mailService == null) { - LogUtil.error("mailService is required"); - } apiDefinitionService = CommonBeanFactory.getBean(ApiDefinitionService.class); if (apiDefinitionService == null) { LogUtil.error("apiDefinitionService is required"); @@ -211,61 +190,38 @@ public class APIBackendListenerClient extends AbstractBackendListenerClient impl } private static void sendTask(ApiTestReport report, TestResult testResult) { - NoticeService noticeService = CommonBeanFactory.getBean(NoticeService.class); - MailService mailService = CommonBeanFactory.getBean(MailService.class); - DingTaskService dingTaskService = CommonBeanFactory.getBean(DingTaskService.class); - WxChatTaskService wxChatTaskService = CommonBeanFactory.getBean(WxChatTaskService.class); SystemParameterService systemParameterService = CommonBeanFactory.getBean(SystemParameterService.class); - if (StringUtils.equals(NoticeConstants.API, report.getTriggerMode()) || StringUtils.equals(NoticeConstants.SCHEDULE, report.getTriggerMode())) { - List userIds = new ArrayList<>(); - List taskList = new ArrayList<>(); - String successContext = ""; - String failedContext = ""; - BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo(); - String url = baseSystemConfigDTO.getUrl() + "/#/api/report/view/" + report.getId(); - if (StringUtils.equals(NoticeConstants.API, report.getTriggerMode())) { - MessageSettingDetail messageSettingDetail = noticeService.searchMessage(); - taskList = messageSettingDetail.getJenkinsTask(); - successContext = "ApiJenkins任务通知:'" + report.getName() + "'执行成功" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url; - failedContext = "ApiJenkins任务通知:'" + report.getName() + "'执行失败" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url; - } - if (StringUtils.equals(NoticeConstants.SCHEDULE, report.getTriggerMode())) { - taskList = noticeService.searchMessageSchedule(testResult.getTestId()); - successContext = "Api定时任务通知:'" + report.getName() + "'执行成功" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url; - failedContext = "Api定时任务通知:'" + report.getName() + "'执行失败" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url; - } - String finalSuccessContext = successContext; - String finalFailedContext = failedContext; - taskList.forEach(r -> { - switch (r.getType()) { - case NoticeConstants.NAIL_ROBOT: - if (StringUtils.equals(NoticeConstants.EXECUTE_SUCCESSFUL, r.getEvent()) && StringUtils.equals(report.getStatus(), "Success")) { - dingTaskService.sendNailRobot(r, userIds, finalSuccessContext, NoticeConstants.EXECUTE_SUCCESSFUL); - } - if (StringUtils.equals(NoticeConstants.EXECUTE_FAILED, r.getEvent()) && StringUtils.equals(report.getStatus(), "Error")) { - dingTaskService.sendNailRobot(r, userIds, finalFailedContext, NoticeConstants.EXECUTE_FAILED); - } - break; - case NoticeConstants.WECHAT_ROBOT: - if (StringUtils.equals(NoticeConstants.EXECUTE_SUCCESSFUL, r.getEvent()) && StringUtils.equals(report.getStatus(), "Success")) { - wxChatTaskService.sendWechatRobot(r, userIds, finalSuccessContext, NoticeConstants.EXECUTE_SUCCESSFUL); - } - if (StringUtils.equals(NoticeConstants.EXECUTE_FAILED, r.getEvent()) && StringUtils.equals(report.getStatus(), "Error")) { - wxChatTaskService.sendWechatRobot(r, userIds, finalFailedContext, NoticeConstants.EXECUTE_FAILED); - } - break; - case NoticeConstants.EMAIL: - if (StringUtils.equals(NoticeConstants.EXECUTE_SUCCESSFUL, r.getEvent()) && StringUtils.equals(report.getStatus(), "Success")) { - mailService.sendApiNotification(r, report, NoticeConstants.EXECUTE_SUCCESSFUL); - } - if (StringUtils.equals(NoticeConstants.EXECUTE_FAILED, r.getEvent()) && StringUtils.equals(report.getStatus(), "Error")) { - mailService.sendApiNotification(r, report, NoticeConstants.EXECUTE_FAILED); - } - break; - } + NoticeSendService noticeSendService = CommonBeanFactory.getBean(NoticeSendService.class); + assert systemParameterService != null; + assert noticeSendService != null; - }); + BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo(); + String url = baseSystemConfigDTO.getUrl() + "/#/api/report/view/" + report.getId(); + + String successContext = ""; + String failedContext = ""; + String subject = ""; + if (StringUtils.equals(NoticeConstants.Mode.API, report.getTriggerMode())) { + successContext = "接口测试 API任务通知:'" + report.getName() + "'执行成功" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url; + failedContext = "接口测试 API任务通知:'" + report.getName() + "'执行失败" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url; + subject = Translator.get("task_notification_jenkins"); } + if (StringUtils.equals(NoticeConstants.Mode.SCHEDULE, report.getTriggerMode())) { + successContext = "接口测试定时任务通知:'" + report.getName() + "'执行成功" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url; + failedContext = "接口测试定时任务通知:'" + report.getName() + "'执行失败" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url; + subject = Translator.get("task_notification"); + } + + NoticeModel noticeModel = NoticeModel.builder() + .successContext(successContext) + .successMailTemplate("ApiSuccessfulNotification") + .failedContext(failedContext) + .failedMailTemplate("ApiFailedNotification") + .testId(testResult.getTestId()) + .status(report.getStatus()) + .subject(subject) + .build(); + noticeSendService.send(report.getTriggerMode(), noticeModel); } private RequestResult getRequestResult(SampleResult result) { diff --git a/backend/src/main/java/io/metersphere/api/service/APITestService.java b/backend/src/main/java/io/metersphere/api/service/APITestService.java index 9dcac1c29f..9b1e621284 100644 --- a/backend/src/main/java/io/metersphere/api/service/APITestService.java +++ b/backend/src/main/java/io/metersphere/api/service/APITestService.java @@ -23,8 +23,6 @@ import io.metersphere.controller.request.QueryScheduleRequest; import io.metersphere.dto.ScheduleDao; import io.metersphere.i18n.Translator; import io.metersphere.job.sechedule.ApiTestJob; -import io.metersphere.notice.service.MailService; -import io.metersphere.notice.service.NoticeService; import io.metersphere.service.FileService; import io.metersphere.service.QuotaService; import io.metersphere.service.ScheduleService; @@ -64,11 +62,6 @@ public class APITestService { private ScheduleService scheduleService; @Resource private TestCaseService testCaseService; - @Resource - private MailService mailService; - @Resource - private NoticeService noticeService; - private static final String BODY_FILE_DIR = "/opt/metersphere/data/body"; @@ -91,6 +84,7 @@ public class APITestService { ApiTest test = createTest(request, file); createBodyFiles(test, bodyUploadIds, bodyFiles); } + private ApiTest createTest(SaveAPITestRequest request, MultipartFile file) { if (file == null) { throw new IllegalArgumentException(Translator.get("file_cannot_be_null")); diff --git a/backend/src/main/java/io/metersphere/base/domain/Notice.java b/backend/src/main/java/io/metersphere/base/domain/Notice.java deleted file mode 100644 index 3597afa97a..0000000000 --- a/backend/src/main/java/io/metersphere/base/domain/Notice.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.metersphere.base.domain; - -import java.io.Serializable; -import lombok.Data; - -@Data -public class Notice implements Serializable { - private String id; - - private String event; - - private String testId; - - private String enable; - - private String type; - - private String userId; - - private static final long serialVersionUID = 1L; -} \ No newline at end of file diff --git a/backend/src/main/java/io/metersphere/base/domain/NoticeExample.java b/backend/src/main/java/io/metersphere/base/domain/NoticeExample.java deleted file mode 100644 index 685ba0c3e9..0000000000 --- a/backend/src/main/java/io/metersphere/base/domain/NoticeExample.java +++ /dev/null @@ -1,620 +0,0 @@ -package io.metersphere.base.domain; - -import java.util.ArrayList; -import java.util.List; - -public class NoticeExample { - protected String orderByClause; - - protected boolean distinct; - - protected List oredCriteria; - - public NoticeExample() { - oredCriteria = new ArrayList(); - } - - public void setOrderByClause(String orderByClause) { - this.orderByClause = orderByClause; - } - - public String getOrderByClause() { - return orderByClause; - } - - public void setDistinct(boolean distinct) { - this.distinct = distinct; - } - - public boolean isDistinct() { - return distinct; - } - - public List getOredCriteria() { - return oredCriteria; - } - - public void or(Criteria criteria) { - oredCriteria.add(criteria); - } - - public Criteria or() { - Criteria criteria = createCriteriaInternal(); - oredCriteria.add(criteria); - return criteria; - } - - public Criteria createCriteria() { - Criteria criteria = createCriteriaInternal(); - if (oredCriteria.size() == 0) { - oredCriteria.add(criteria); - } - return criteria; - } - - protected Criteria createCriteriaInternal() { - Criteria criteria = new Criteria(); - return criteria; - } - - public void clear() { - oredCriteria.clear(); - orderByClause = null; - distinct = false; - } - - protected abstract static class GeneratedCriteria { - protected List criteria; - - protected GeneratedCriteria() { - super(); - criteria = new ArrayList(); - } - - public boolean isValid() { - return criteria.size() > 0; - } - - public List getAllCriteria() { - return criteria; - } - - public List getCriteria() { - return criteria; - } - - protected void addCriterion(String condition) { - if (condition == null) { - throw new RuntimeException("Value for condition cannot be null"); - } - criteria.add(new Criterion(condition)); - } - - protected void addCriterion(String condition, Object value, String property) { - if (value == null) { - throw new RuntimeException("Value for " + property + " cannot be null"); - } - criteria.add(new Criterion(condition, value)); - } - - protected void addCriterion(String condition, Object value1, Object value2, String property) { - if (value1 == null || value2 == null) { - throw new RuntimeException("Between values for " + property + " cannot be null"); - } - criteria.add(new Criterion(condition, value1, value2)); - } - - public Criteria andIdIsNull() { - addCriterion("id is null"); - return (Criteria) this; - } - - public Criteria andIdIsNotNull() { - addCriterion("id is not null"); - return (Criteria) this; - } - - public Criteria andIdEqualTo(String value) { - addCriterion("id =", value, "id"); - return (Criteria) this; - } - - public Criteria andIdNotEqualTo(String value) { - addCriterion("id <>", value, "id"); - return (Criteria) this; - } - - public Criteria andIdGreaterThan(String value) { - addCriterion("id >", value, "id"); - return (Criteria) this; - } - - public Criteria andIdGreaterThanOrEqualTo(String value) { - addCriterion("id >=", value, "id"); - return (Criteria) this; - } - - public Criteria andIdLessThan(String value) { - addCriterion("id <", value, "id"); - return (Criteria) this; - } - - public Criteria andIdLessThanOrEqualTo(String value) { - addCriterion("id <=", value, "id"); - return (Criteria) this; - } - - public Criteria andIdLike(String value) { - addCriterion("id like", value, "id"); - return (Criteria) this; - } - - public Criteria andIdNotLike(String value) { - addCriterion("id not like", value, "id"); - return (Criteria) this; - } - - public Criteria andIdIn(List values) { - addCriterion("id in", values, "id"); - return (Criteria) this; - } - - public Criteria andIdNotIn(List values) { - addCriterion("id not in", values, "id"); - return (Criteria) this; - } - - public Criteria andIdBetween(String value1, String value2) { - addCriterion("id between", value1, value2, "id"); - return (Criteria) this; - } - - public Criteria andIdNotBetween(String value1, String value2) { - addCriterion("id not between", value1, value2, "id"); - return (Criteria) this; - } - - public Criteria andEventIsNull() { - addCriterion("EVENT is null"); - return (Criteria) this; - } - - public Criteria andEventIsNotNull() { - addCriterion("EVENT is not null"); - return (Criteria) this; - } - - public Criteria andEventEqualTo(String value) { - addCriterion("EVENT =", value, "event"); - return (Criteria) this; - } - - public Criteria andEventNotEqualTo(String value) { - addCriterion("EVENT <>", value, "event"); - return (Criteria) this; - } - - public Criteria andEventGreaterThan(String value) { - addCriterion("EVENT >", value, "event"); - return (Criteria) this; - } - - public Criteria andEventGreaterThanOrEqualTo(String value) { - addCriterion("EVENT >=", value, "event"); - return (Criteria) this; - } - - public Criteria andEventLessThan(String value) { - addCriterion("EVENT <", value, "event"); - return (Criteria) this; - } - - public Criteria andEventLessThanOrEqualTo(String value) { - addCriterion("EVENT <=", value, "event"); - return (Criteria) this; - } - - public Criteria andEventLike(String value) { - addCriterion("EVENT like", value, "event"); - return (Criteria) this; - } - - public Criteria andEventNotLike(String value) { - addCriterion("EVENT not like", value, "event"); - return (Criteria) this; - } - - public Criteria andEventIn(List values) { - addCriterion("EVENT in", values, "event"); - return (Criteria) this; - } - - public Criteria andEventNotIn(List values) { - addCriterion("EVENT not in", values, "event"); - return (Criteria) this; - } - - public Criteria andEventBetween(String value1, String value2) { - addCriterion("EVENT between", value1, value2, "event"); - return (Criteria) this; - } - - public Criteria andEventNotBetween(String value1, String value2) { - addCriterion("EVENT not between", value1, value2, "event"); - return (Criteria) this; - } - - public Criteria andTestIdIsNull() { - addCriterion("TEST_ID is null"); - return (Criteria) this; - } - - public Criteria andTestIdIsNotNull() { - addCriterion("TEST_ID is not null"); - return (Criteria) this; - } - - public Criteria andTestIdEqualTo(String value) { - addCriterion("TEST_ID =", value, "testId"); - return (Criteria) this; - } - - public Criteria andTestIdNotEqualTo(String value) { - addCriterion("TEST_ID <>", value, "testId"); - return (Criteria) this; - } - - public Criteria andTestIdGreaterThan(String value) { - addCriterion("TEST_ID >", value, "testId"); - return (Criteria) this; - } - - public Criteria andTestIdGreaterThanOrEqualTo(String value) { - addCriterion("TEST_ID >=", value, "testId"); - return (Criteria) this; - } - - public Criteria andTestIdLessThan(String value) { - addCriterion("TEST_ID <", value, "testId"); - return (Criteria) this; - } - - public Criteria andTestIdLessThanOrEqualTo(String value) { - addCriterion("TEST_ID <=", value, "testId"); - return (Criteria) this; - } - - public Criteria andTestIdLike(String value) { - addCriterion("TEST_ID like", value, "testId"); - return (Criteria) this; - } - - public Criteria andTestIdNotLike(String value) { - addCriterion("TEST_ID not like", value, "testId"); - return (Criteria) this; - } - - public Criteria andTestIdIn(List values) { - addCriterion("TEST_ID in", values, "testId"); - return (Criteria) this; - } - - public Criteria andTestIdNotIn(List values) { - addCriterion("TEST_ID not in", values, "testId"); - return (Criteria) this; - } - - public Criteria andTestIdBetween(String value1, String value2) { - addCriterion("TEST_ID between", value1, value2, "testId"); - return (Criteria) this; - } - - public Criteria andTestIdNotBetween(String value1, String value2) { - addCriterion("TEST_ID not between", value1, value2, "testId"); - return (Criteria) this; - } - - public Criteria andEnableIsNull() { - addCriterion("`ENABLE` is null"); - return (Criteria) this; - } - - public Criteria andEnableIsNotNull() { - addCriterion("`ENABLE` is not null"); - return (Criteria) this; - } - - public Criteria andEnableEqualTo(String value) { - addCriterion("`ENABLE` =", value, "enable"); - return (Criteria) this; - } - - public Criteria andEnableNotEqualTo(String value) { - addCriterion("`ENABLE` <>", value, "enable"); - return (Criteria) this; - } - - public Criteria andEnableGreaterThan(String value) { - addCriterion("`ENABLE` >", value, "enable"); - return (Criteria) this; - } - - public Criteria andEnableGreaterThanOrEqualTo(String value) { - addCriterion("`ENABLE` >=", value, "enable"); - return (Criteria) this; - } - - public Criteria andEnableLessThan(String value) { - addCriterion("`ENABLE` <", value, "enable"); - return (Criteria) this; - } - - public Criteria andEnableLessThanOrEqualTo(String value) { - addCriterion("`ENABLE` <=", value, "enable"); - return (Criteria) this; - } - - public Criteria andEnableLike(String value) { - addCriterion("`ENABLE` like", value, "enable"); - return (Criteria) this; - } - - public Criteria andEnableNotLike(String value) { - addCriterion("`ENABLE` not like", value, "enable"); - return (Criteria) this; - } - - public Criteria andEnableIn(List values) { - addCriterion("`ENABLE` in", values, "enable"); - return (Criteria) this; - } - - public Criteria andEnableNotIn(List values) { - addCriterion("`ENABLE` not in", values, "enable"); - return (Criteria) this; - } - - public Criteria andEnableBetween(String value1, String value2) { - addCriterion("`ENABLE` between", value1, value2, "enable"); - return (Criteria) this; - } - - public Criteria andEnableNotBetween(String value1, String value2) { - addCriterion("`ENABLE` not between", value1, value2, "enable"); - return (Criteria) this; - } - - public Criteria andTypeIsNull() { - addCriterion("`type` is null"); - return (Criteria) this; - } - - public Criteria andTypeIsNotNull() { - addCriterion("`type` is not null"); - return (Criteria) this; - } - - public Criteria andTypeEqualTo(String value) { - addCriterion("`type` =", value, "type"); - return (Criteria) this; - } - - public Criteria andTypeNotEqualTo(String value) { - addCriterion("`type` <>", value, "type"); - return (Criteria) this; - } - - public Criteria andTypeGreaterThan(String value) { - addCriterion("`type` >", value, "type"); - return (Criteria) this; - } - - public Criteria andTypeGreaterThanOrEqualTo(String value) { - addCriterion("`type` >=", value, "type"); - return (Criteria) this; - } - - public Criteria andTypeLessThan(String value) { - addCriterion("`type` <", value, "type"); - return (Criteria) this; - } - - public Criteria andTypeLessThanOrEqualTo(String value) { - addCriterion("`type` <=", value, "type"); - return (Criteria) this; - } - - public Criteria andTypeLike(String value) { - addCriterion("`type` like", value, "type"); - return (Criteria) this; - } - - public Criteria andTypeNotLike(String value) { - addCriterion("`type` not like", value, "type"); - return (Criteria) this; - } - - public Criteria andTypeIn(List values) { - addCriterion("`type` in", values, "type"); - return (Criteria) this; - } - - public Criteria andTypeNotIn(List values) { - addCriterion("`type` not in", values, "type"); - return (Criteria) this; - } - - public Criteria andTypeBetween(String value1, String value2) { - addCriterion("`type` between", value1, value2, "type"); - return (Criteria) this; - } - - public Criteria andTypeNotBetween(String value1, String value2) { - addCriterion("`type` not between", value1, value2, "type"); - return (Criteria) this; - } - - public Criteria andUserIdIsNull() { - addCriterion("user_id is null"); - return (Criteria) this; - } - - public Criteria andUserIdIsNotNull() { - addCriterion("user_id is not null"); - return (Criteria) this; - } - - public Criteria andUserIdEqualTo(String value) { - addCriterion("user_id =", value, "userId"); - return (Criteria) this; - } - - public Criteria andUserIdNotEqualTo(String value) { - addCriterion("user_id <>", value, "userId"); - return (Criteria) this; - } - - public Criteria andUserIdGreaterThan(String value) { - addCriterion("user_id >", value, "userId"); - return (Criteria) this; - } - - public Criteria andUserIdGreaterThanOrEqualTo(String value) { - addCriterion("user_id >=", value, "userId"); - return (Criteria) this; - } - - public Criteria andUserIdLessThan(String value) { - addCriterion("user_id <", value, "userId"); - return (Criteria) this; - } - - public Criteria andUserIdLessThanOrEqualTo(String value) { - addCriterion("user_id <=", value, "userId"); - return (Criteria) this; - } - - public Criteria andUserIdLike(String value) { - addCriterion("user_id like", value, "userId"); - return (Criteria) this; - } - - public Criteria andUserIdNotLike(String value) { - addCriterion("user_id not like", value, "userId"); - return (Criteria) this; - } - - public Criteria andUserIdIn(List values) { - addCriterion("user_id in", values, "userId"); - return (Criteria) this; - } - - public Criteria andUserIdNotIn(List values) { - addCriterion("user_id not in", values, "userId"); - return (Criteria) this; - } - - public Criteria andUserIdBetween(String value1, String value2) { - addCriterion("user_id between", value1, value2, "userId"); - return (Criteria) this; - } - - public Criteria andUserIdNotBetween(String value1, String value2) { - addCriterion("user_id not between", value1, value2, "userId"); - return (Criteria) this; - } - } - - public static class Criteria extends GeneratedCriteria { - - protected Criteria() { - super(); - } - } - - public static class Criterion { - private String condition; - - private Object value; - - private Object secondValue; - - private boolean noValue; - - private boolean singleValue; - - private boolean betweenValue; - - private boolean listValue; - - private String typeHandler; - - public String getCondition() { - return condition; - } - - public Object getValue() { - return value; - } - - public Object getSecondValue() { - return secondValue; - } - - public boolean isNoValue() { - return noValue; - } - - public boolean isSingleValue() { - return singleValue; - } - - public boolean isBetweenValue() { - return betweenValue; - } - - public boolean isListValue() { - return listValue; - } - - public String getTypeHandler() { - return typeHandler; - } - - protected Criterion(String condition) { - super(); - this.condition = condition; - this.typeHandler = null; - this.noValue = true; - } - - protected Criterion(String condition, Object value, String typeHandler) { - super(); - this.condition = condition; - this.value = value; - this.typeHandler = typeHandler; - if (value instanceof List) { - this.listValue = true; - } else { - this.singleValue = true; - } - } - - protected Criterion(String condition, Object value) { - this(condition, value, null); - } - - protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { - super(); - this.condition = condition; - this.value = value; - this.secondValue = secondValue; - this.typeHandler = typeHandler; - this.betweenValue = true; - } - - protected Criterion(String condition, Object value, Object secondValue) { - this(condition, value, secondValue, null); - } - } -} \ No newline at end of file diff --git a/backend/src/main/java/io/metersphere/base/mapper/NoticeMapper.java b/backend/src/main/java/io/metersphere/base/mapper/NoticeMapper.java deleted file mode 100644 index c0eeb6e74e..0000000000 --- a/backend/src/main/java/io/metersphere/base/mapper/NoticeMapper.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.metersphere.base.mapper; - -import io.metersphere.base.domain.Notice; -import io.metersphere.base.domain.NoticeExample; -import java.util.List; -import org.apache.ibatis.annotations.Param; - -public interface NoticeMapper { - long countByExample(NoticeExample example); - - int deleteByExample(NoticeExample example); - - int deleteByPrimaryKey(String id); - - int insert(Notice record); - - int insertSelective(Notice record); - - List selectByExample(NoticeExample example); - - Notice selectByPrimaryKey(String id); - - int updateByExampleSelective(@Param("record") Notice record, @Param("example") NoticeExample example); - - int updateByExample(@Param("record") Notice record, @Param("example") NoticeExample example); - - int updateByPrimaryKeySelective(Notice record); - - int updateByPrimaryKey(Notice record); -} \ No newline at end of file diff --git a/backend/src/main/java/io/metersphere/base/mapper/NoticeMapper.xml b/backend/src/main/java/io/metersphere/base/mapper/NoticeMapper.xml deleted file mode 100644 index 96feecd148..0000000000 --- a/backend/src/main/java/io/metersphere/base/mapper/NoticeMapper.xml +++ /dev/null @@ -1,228 +0,0 @@ - - - - - - - - - - - - - - - - - - - - and ${criterion.condition} - - - and ${criterion.condition} #{criterion.value} - - - and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} - - - and ${criterion.condition} - - #{listItem} - - - - - - - - - - - - - - - - - - and ${criterion.condition} - - - and ${criterion.condition} #{criterion.value} - - - and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} - - - and ${criterion.condition} - - #{listItem} - - - - - - - - - - - id, EVENT, TEST_ID, `ENABLE`, `type`, user_id - - - - - delete from notice - where id = #{id,jdbcType=VARCHAR} - - - delete from notice - - - - - - insert into notice (id, EVENT, TEST_ID, - `ENABLE`, `type`, user_id - ) - values (#{id,jdbcType=VARCHAR}, #{event,jdbcType=VARCHAR}, #{testId,jdbcType=VARCHAR}, - #{enable,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR}, #{userId,jdbcType=VARCHAR} - ) - - - insert into notice - - - id, - - - EVENT, - - - TEST_ID, - - - `ENABLE`, - - - `type`, - - - user_id, - - - - - #{id,jdbcType=VARCHAR}, - - - #{event,jdbcType=VARCHAR}, - - - #{testId,jdbcType=VARCHAR}, - - - #{enable,jdbcType=VARCHAR}, - - - #{type,jdbcType=VARCHAR}, - - - #{userId,jdbcType=VARCHAR}, - - - - - - update notice - - - id = #{record.id,jdbcType=VARCHAR}, - - - EVENT = #{record.event,jdbcType=VARCHAR}, - - - TEST_ID = #{record.testId,jdbcType=VARCHAR}, - - - `ENABLE` = #{record.enable,jdbcType=VARCHAR}, - - - `type` = #{record.type,jdbcType=VARCHAR}, - - - user_id = #{record.userId,jdbcType=VARCHAR}, - - - - - - - - update notice - set id = #{record.id,jdbcType=VARCHAR}, - EVENT = #{record.event,jdbcType=VARCHAR}, - TEST_ID = #{record.testId,jdbcType=VARCHAR}, - `ENABLE` = #{record.enable,jdbcType=VARCHAR}, - `type` = #{record.type,jdbcType=VARCHAR}, - user_id = #{record.userId,jdbcType=VARCHAR} - - - - - - update notice - - - EVENT = #{event,jdbcType=VARCHAR}, - - - TEST_ID = #{testId,jdbcType=VARCHAR}, - - - `ENABLE` = #{enable,jdbcType=VARCHAR}, - - - `type` = #{type,jdbcType=VARCHAR}, - - - user_id = #{userId,jdbcType=VARCHAR}, - - - where id = #{id,jdbcType=VARCHAR} - - - update notice - set EVENT = #{event,jdbcType=VARCHAR}, - TEST_ID = #{testId,jdbcType=VARCHAR}, - `ENABLE` = #{enable,jdbcType=VARCHAR}, - `type` = #{type,jdbcType=VARCHAR}, - user_id = #{userId,jdbcType=VARCHAR} - where id = #{id,jdbcType=VARCHAR} - - \ No newline at end of file diff --git a/backend/src/main/java/io/metersphere/base/mapper/ext/ExtMessageMapper.java b/backend/src/main/java/io/metersphere/base/mapper/ext/ExtMessageMapper.java deleted file mode 100644 index f3714f646f..0000000000 --- a/backend/src/main/java/io/metersphere/base/mapper/ext/ExtMessageMapper.java +++ /dev/null @@ -1,12 +0,0 @@ -package io.metersphere.base.mapper.ext; - -import io.metersphere.base.domain.MessageTask; -import org.apache.ibatis.annotations.Param; - -import java.util.List; - -public interface ExtMessageMapper { - List searchMessageByTestId(@Param("testId") String testId); - - List searchMessageByOrganizationId(@Param("organizationId") String organizationId); -} diff --git a/backend/src/main/java/io/metersphere/base/mapper/ext/ExtMessageMapper.xml b/backend/src/main/java/io/metersphere/base/mapper/ext/ExtMessageMapper.xml deleted file mode 100644 index f53c48c594..0000000000 --- a/backend/src/main/java/io/metersphere/base/mapper/ext/ExtMessageMapper.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/backend/src/main/java/io/metersphere/commons/constants/NoticeConstants.java b/backend/src/main/java/io/metersphere/commons/constants/NoticeConstants.java index 565c998094..7708f1e78a 100644 --- a/backend/src/main/java/io/metersphere/commons/constants/NoticeConstants.java +++ b/backend/src/main/java/io/metersphere/commons/constants/NoticeConstants.java @@ -1,24 +1,37 @@ package io.metersphere.commons.constants; public interface NoticeConstants { - String EXECUTE_SUCCESSFUL = "EXECUTE_SUCCESSFUL"; - String EXECUTE_FAILED = "EXECUTE_FAILED"; - String EMAIL = "EMAIL"; - String NAIL_ROBOT = "NAIL_ROBOT"; - String WECHAT_ROBOT = "WECHAT_ROBOT"; - String CREATE = "CREATE"; - String UPDATE = "UPDATE"; - String DELETE = "DELETE"; - String COMMENT = "COMMENT"; - String JENKINS_TASK = "JENKINS_TASK"; - String TEST_PLAN_TASK = "TEST_PLAN_TASK"; - String REVIEW_TASK = "REVIEW_TASK"; - String DEFECT_TASK = "DEFECT_TASK"; - String FOUNDER = "FOUNDER";//创建人 - String EXECUTOR = "EXECUTOR";//负责人(评审人) - String MAINTAINER = "MAINTAINER";//维护人 - String API = "API"; - String SCHEDULE = "SCHEDULE"; + interface TaskType { + String JENKINS_TASK = "JENKINS_TASK"; + String TEST_PLAN_TASK = "TEST_PLAN_TASK"; + String REVIEW_TASK = "REVIEW_TASK"; + String DEFECT_TASK = "DEFECT_TASK"; + } + interface Mode { + String API = "API"; + String SCHEDULE = "SCHEDULE"; + } + + interface Type { + String EMAIL = "EMAIL"; + String NAIL_ROBOT = "NAIL_ROBOT"; + String WECHAT_ROBOT = "WECHAT_ROBOT"; + } + + interface Event { + String EXECUTE_SUCCESSFUL = "EXECUTE_SUCCESSFUL"; + String EXECUTE_FAILED = "EXECUTE_FAILED"; + String CREATE = "CREATE"; + String UPDATE = "UPDATE"; + String DELETE = "DELETE"; + String COMMENT = "COMMENT"; + } + + interface RelatedUser { + String FOUNDER = "FOUNDER";//创建人 + String EXECUTOR = "EXECUTOR";//负责人(评审人) + String MAINTAINER = "MAINTAINER";//维护人 + } } diff --git a/backend/src/main/java/io/metersphere/commons/utils/SessionUtils.java b/backend/src/main/java/io/metersphere/commons/utils/SessionUtils.java index 62462a6432..df5059a920 100644 --- a/backend/src/main/java/io/metersphere/commons/utils/SessionUtils.java +++ b/backend/src/main/java/io/metersphere/commons/utils/SessionUtils.java @@ -24,7 +24,9 @@ public class SessionUtils { try { Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(); - return (SessionUser) session.getAttribute(ATTR_USER); + SessionUser user = (SessionUser) session.getAttribute(ATTR_USER); + assert user != null; + return user; } catch (Exception e) { return null; } diff --git a/backend/src/main/java/io/metersphere/config/AsyncConfig.java b/backend/src/main/java/io/metersphere/config/AsyncConfig.java new file mode 100644 index 0000000000..c54fafcd71 --- /dev/null +++ b/backend/src/main/java/io/metersphere/config/AsyncConfig.java @@ -0,0 +1,21 @@ +package io.metersphere.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.task.AsyncTaskExecutor; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +@EnableAsync +@Configuration +public class AsyncConfig { + + @Bean + public AsyncTaskExecutor taskExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setThreadNamePrefix("Async-Executor"); + executor.setCorePoolSize(5); + executor.setMaxPoolSize(10); + return executor; + } +} diff --git a/backend/src/main/java/io/metersphere/notice/controller/NoticeController.java b/backend/src/main/java/io/metersphere/notice/controller/NoticeController.java index 67583ce4b0..461cdaaf58 100644 --- a/backend/src/main/java/io/metersphere/notice/controller/NoticeController.java +++ b/backend/src/main/java/io/metersphere/notice/controller/NoticeController.java @@ -1,8 +1,6 @@ package io.metersphere.notice.controller; -import io.metersphere.notice.controller.request.MessageRequest; import io.metersphere.notice.domain.MessageDetail; -import io.metersphere.notice.domain.MessageSettingDetail; import io.metersphere.notice.service.NoticeService; import org.springframework.web.bind.annotation.*; @@ -16,18 +14,18 @@ public class NoticeController { private NoticeService noticeService; @PostMapping("save/message/task") - public void saveMessage(@RequestBody MessageRequest messageRequest) { - noticeService.saveMessageTask(messageRequest); + public void saveMessage(@RequestBody MessageDetail messageDetail) { + noticeService.saveMessageTask(messageDetail); } - @GetMapping("/search/message") - public MessageSettingDetail searchMessage() { - return noticeService.searchMessage(); + @GetMapping("/search/message/type/{type}") + public List searchMessage(@PathVariable String type) { + return noticeService.searchMessageByType(type); } @GetMapping("/search/message/{testId}") public List searchMessageSchedule(@PathVariable String testId) { - return noticeService.searchMessageSchedule(testId); + return noticeService.searchMessageByTestId(testId); } @GetMapping("/delete/message/{identification}") diff --git a/backend/src/main/java/io/metersphere/notice/controller/request/NoticeRequest.java b/backend/src/main/java/io/metersphere/notice/controller/request/NoticeRequest.java deleted file mode 100644 index 4c7b19e151..0000000000 --- a/backend/src/main/java/io/metersphere/notice/controller/request/NoticeRequest.java +++ /dev/null @@ -1,12 +0,0 @@ -package io.metersphere.notice.controller.request; - -import io.metersphere.notice.domain.NoticeDetail; -import lombok.Data; - -import java.util.List; - -@Data -public class NoticeRequest { - private String testId; - private List notices; -} diff --git a/backend/src/main/java/io/metersphere/notice/domain/NoticeDetail.java b/backend/src/main/java/io/metersphere/notice/domain/NoticeDetail.java deleted file mode 100644 index f92a7baf7f..0000000000 --- a/backend/src/main/java/io/metersphere/notice/domain/NoticeDetail.java +++ /dev/null @@ -1,12 +0,0 @@ -package io.metersphere.notice.domain; - -import io.metersphere.base.domain.Notice; -import lombok.Data; - -import java.util.ArrayList; -import java.util.List; - -@Data -public class NoticeDetail extends Notice { - private List userIds = new ArrayList<>(); -} diff --git a/backend/src/main/java/io/metersphere/notice/sender/AbstractNoticeSender.java b/backend/src/main/java/io/metersphere/notice/sender/AbstractNoticeSender.java new file mode 100644 index 0000000000..27da4a75dc --- /dev/null +++ b/backend/src/main/java/io/metersphere/notice/sender/AbstractNoticeSender.java @@ -0,0 +1,127 @@ +package io.metersphere.notice.sender; + +import io.metersphere.commons.constants.NoticeConstants; +import io.metersphere.commons.utils.LogUtil; +import io.metersphere.notice.domain.MessageDetail; +import io.metersphere.notice.domain.UserDetail; +import io.metersphere.service.UserService; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; + +import javax.annotation.Resource; +import java.io.IOException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public abstract class AbstractNoticeSender implements NoticeSender { + @Resource + private UserService userService; + + protected String getContext(MessageDetail messageDetail, NoticeModel noticeModel) { + // 处理 userIds 中包含的特殊值 + List realUserIds = getRealUserIds(messageDetail.getUserIds(), noticeModel.getRelatedUsers(), messageDetail.getEvent()); + messageDetail.setUserIds(realUserIds); + + // 处理 WeCom Ding context + String context = ""; + String status = noticeModel.getStatus(); + switch (messageDetail.getEvent()) { + case NoticeConstants.Event.CREATE: + case NoticeConstants.Event.UPDATE: + case NoticeConstants.Event.DELETE: + case NoticeConstants.Event.COMMENT: + context = noticeModel.getContext(); + break; + case NoticeConstants.Event.EXECUTE_FAILED: + context = noticeModel.getFailedContext(); + break; + case NoticeConstants.Event.EXECUTE_SUCCESSFUL: + context = noticeModel.getSuccessContext(); + break; + default: + break; + } + return context; + } + + protected String getHtmlContext(MessageDetail messageDetail, NoticeModel noticeModel) { + // 处理 userIds 中包含的特殊值 + List realUserIds = getRealUserIds(messageDetail.getUserIds(), noticeModel.getRelatedUsers(), messageDetail.getEvent()); + messageDetail.setUserIds(realUserIds); + + // 处理 mail context + String context = ""; + try { + switch (messageDetail.getEvent()) { + case NoticeConstants.Event.CREATE: + case NoticeConstants.Event.UPDATE: + case NoticeConstants.Event.DELETE: + case NoticeConstants.Event.COMMENT: + URL resource = this.getClass().getResource("/mail/" + noticeModel.getMailTemplate() + ".html"); + context = IOUtils.toString(resource, StandardCharsets.UTF_8); + break; + case NoticeConstants.Event.EXECUTE_FAILED: + URL resource1 = this.getClass().getResource("/mail/" + noticeModel.getFailedMailTemplate() + ".html"); + context = IOUtils.toString(resource1, StandardCharsets.UTF_8); + break; + case NoticeConstants.Event.EXECUTE_SUCCESSFUL: + URL resource2 = this.getClass().getResource("/mail/" + noticeModel.getSuccessMailTemplate() + ".html"); + context = IOUtils.toString(resource2, StandardCharsets.UTF_8); + break; + default: + break; + } + } catch (IOException e) { + LogUtil.error(e); + } + return context; + } + + protected List getUserPhones(List userIds) { + List list = userService.queryTypeByIds(userIds); + List phoneList = new ArrayList<>(); + list.forEach(u -> phoneList.add(u.getPhone())); + LogUtil.info("收件人地址: " + phoneList); + return phoneList.stream().distinct().collect(Collectors.toList()); + } + + protected List getUserEmails(List userIds) { + List list = userService.queryTypeByIds(userIds); + List phoneList = new ArrayList<>(); + list.forEach(u -> phoneList.add(u.getEmail())); + LogUtil.info("收件人地址: " + phoneList); + return phoneList.stream().distinct().collect(Collectors.toList()); + } + + private List getRealUserIds(List userIds, List relatedUsers, String event) { + List toUserIds = new ArrayList<>(); + for (String userId : userIds) { + switch (userId) { + case NoticeConstants.RelatedUser.EXECUTOR: + if (StringUtils.equals(NoticeConstants.Event.CREATE, event)) { + toUserIds.addAll(relatedUsers); + } + break; + case NoticeConstants.RelatedUser.FOUNDER: + if (StringUtils.equals(NoticeConstants.Event.UPDATE, event) + || StringUtils.equals(NoticeConstants.Event.DELETE, event)) { + toUserIds.addAll(relatedUsers); + } + break; + case NoticeConstants.RelatedUser.MAINTAINER: + if (StringUtils.equals(NoticeConstants.Event.COMMENT, event)) { + toUserIds.addAll(relatedUsers); + } + break; + default: + toUserIds.add(userId); + break; + } + } + + return toUserIds; + } +} diff --git a/backend/src/main/java/io/metersphere/notice/sender/NoticeModel.java b/backend/src/main/java/io/metersphere/notice/sender/NoticeModel.java new file mode 100644 index 0000000000..bdfec0b3d0 --- /dev/null +++ b/backend/src/main/java/io/metersphere/notice/sender/NoticeModel.java @@ -0,0 +1,47 @@ +package io.metersphere.notice.sender; + +import lombok.Builder; +import lombok.Data; + +import java.util.List; +import java.util.Map; + +@Data +@Builder +public class NoticeModel { + /** + * 保存 测试id + */ + private String testId; + /** + * 保存状态 + */ + private String status; + /** + * 消息主题 + */ + private String subject; + /** + * 消息内容 + */ + private String context; + private String successContext; + private String failedContext; + + /** + * html 消息模版 + */ + private String mailTemplate; + private String failedMailTemplate; + private String successMailTemplate; + + /** + * 保存特殊的用户 + */ + private List relatedUsers; + + /** + * 模版里的参数信息 + */ + private Map paramMap; +} diff --git a/backend/src/main/java/io/metersphere/notice/sender/NoticeSender.java b/backend/src/main/java/io/metersphere/notice/sender/NoticeSender.java new file mode 100644 index 0000000000..11d348d365 --- /dev/null +++ b/backend/src/main/java/io/metersphere/notice/sender/NoticeSender.java @@ -0,0 +1,9 @@ +package io.metersphere.notice.sender; + +import io.metersphere.notice.domain.MessageDetail; +import org.springframework.scheduling.annotation.Async; + +public interface NoticeSender { + @Async + void send(MessageDetail messageDetail, NoticeModel noticeModel); +} diff --git a/backend/src/main/java/io/metersphere/notice/sender/impl/DingNoticeSender.java b/backend/src/main/java/io/metersphere/notice/sender/impl/DingNoticeSender.java new file mode 100644 index 0000000000..e739c9f448 --- /dev/null +++ b/backend/src/main/java/io/metersphere/notice/sender/impl/DingNoticeSender.java @@ -0,0 +1,47 @@ +package io.metersphere.notice.sender.impl; + +import com.dingtalk.api.DefaultDingTalkClient; +import com.dingtalk.api.DingTalkClient; +import com.dingtalk.api.request.OapiRobotSendRequest; +import com.taobao.api.ApiException; +import io.metersphere.commons.utils.LogUtil; +import io.metersphere.notice.domain.MessageDetail; +import io.metersphere.notice.sender.AbstractNoticeSender; +import io.metersphere.notice.sender.NoticeModel; +import org.apache.commons.collections4.CollectionUtils; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +public class DingNoticeSender extends AbstractNoticeSender { + + public void sendNailRobot(MessageDetail messageDetail, String context) { + List userIds = messageDetail.getUserIds(); + if (CollectionUtils.isEmpty(userIds)) { + return; + } + DingTalkClient client = new DefaultDingTalkClient(messageDetail.getWebhook()); + OapiRobotSendRequest request = new OapiRobotSendRequest(); + request.setMsgtype("text"); + OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text(); + text.setContent(context); + request.setText(text); + OapiRobotSendRequest.At at = new OapiRobotSendRequest.At(); + List phoneList = super.getUserPhones(userIds); + LogUtil.info("收件人地址: " + phoneList); + at.setAtMobiles(phoneList); + request.setAt(at); + try { + client.execute(request); + } catch (ApiException e) { + LogUtil.error(e.getMessage(), e); + } + } + + @Override + public void send(MessageDetail messageDetail, NoticeModel noticeModel) { + String context = super.getContext(messageDetail, noticeModel); + sendNailRobot(messageDetail, context); + } +} diff --git a/backend/src/main/java/io/metersphere/notice/sender/impl/MailNoticeSender.java b/backend/src/main/java/io/metersphere/notice/sender/impl/MailNoticeSender.java new file mode 100644 index 0000000000..5e1c0f3edd --- /dev/null +++ b/backend/src/main/java/io/metersphere/notice/sender/impl/MailNoticeSender.java @@ -0,0 +1,62 @@ +package io.metersphere.notice.sender.impl; + +import io.metersphere.commons.utils.LogUtil; +import io.metersphere.notice.domain.MessageDetail; +import io.metersphere.notice.sender.AbstractNoticeSender; +import io.metersphere.notice.sender.NoticeModel; +import io.metersphere.notice.service.MailService; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.RegExUtils; +import org.springframework.mail.javamail.JavaMailSenderImpl; +import org.springframework.mail.javamail.MimeMessageHelper; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import javax.mail.MessagingException; +import javax.mail.internet.MimeMessage; +import java.util.List; +import java.util.Map; + +@Component +public class MailNoticeSender extends AbstractNoticeSender { + @Resource + private MailService mailService; + + private void sendMail(MessageDetail messageDetail, String template, NoticeModel noticeModel) throws MessagingException { + JavaMailSenderImpl javaMailSender = mailService.getMailSender(); + MimeMessage mimeMessage = javaMailSender.createMimeMessage(); + MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); + helper.setFrom(javaMailSender.getUsername()); + helper.setSubject("MeterSphere " + noticeModel.getSubject()); + List emails = super.getUserEmails(messageDetail.getUserIds()); + String[] users = emails.toArray(new String[0]); + LogUtil.info("收件人地址: " + emails); + helper.setText(this.getContent(template, noticeModel.getParamMap()), true); + helper.setTo(users); + javaMailSender.send(mimeMessage); + } + + + public String getContent(String template, Map context) { + if (MapUtils.isNotEmpty(context)) { + for (String k : context.keySet()) { + if (context.get(k) != null) { + template = RegExUtils.replaceAll(template, "\\$\\{" + k + "}", context.get(k).toString()); + } else { + template = RegExUtils.replaceAll(template, "\\$\\{" + k + "}", "未设置"); + } + } + } + return template; + } + + @Override + public void send(MessageDetail messageDetail, NoticeModel noticeModel) { + String context = super.getHtmlContext(messageDetail, noticeModel); + try { + sendMail(messageDetail, context, noticeModel); + } catch (Exception e) { + LogUtil.error(e); + } + } +} diff --git a/backend/src/main/java/io/metersphere/notice/sender/impl/WeComNoticeSender.java b/backend/src/main/java/io/metersphere/notice/sender/impl/WeComNoticeSender.java new file mode 100644 index 0000000000..bb1073d9cd --- /dev/null +++ b/backend/src/main/java/io/metersphere/notice/sender/impl/WeComNoticeSender.java @@ -0,0 +1,39 @@ +package io.metersphere.notice.sender.impl; + +import io.metersphere.commons.utils.LogUtil; +import io.metersphere.notice.domain.MessageDetail; +import io.metersphere.notice.message.TextMessage; +import io.metersphere.notice.sender.AbstractNoticeSender; +import io.metersphere.notice.sender.NoticeModel; +import io.metersphere.notice.util.WxChatbotClient; +import org.apache.commons.collections4.CollectionUtils; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.util.List; + +@Component +public class WeComNoticeSender extends AbstractNoticeSender { + + + public void sendWechatRobot(MessageDetail messageDetail, String context) { + List userIds = messageDetail.getUserIds(); + if (CollectionUtils.isEmpty(userIds)) { + return; + } + TextMessage message = new TextMessage(context); + List phoneLists = super.getUserPhones(userIds); + message.setMentionedMobileList(phoneLists); + try { + WxChatbotClient.send(messageDetail.getWebhook(), message); + } catch (IOException e) { + LogUtil.error(e.getMessage(), e); + } + } + + @Override + public void send(MessageDetail messageDetail, NoticeModel noticeModel) { + String context = super.getContext(messageDetail, noticeModel); + sendWechatRobot(messageDetail, context); + } +} diff --git a/backend/src/main/java/io/metersphere/notice/service/DingTaskService.java b/backend/src/main/java/io/metersphere/notice/service/DingTaskService.java deleted file mode 100644 index 9f2047f6ce..0000000000 --- a/backend/src/main/java/io/metersphere/notice/service/DingTaskService.java +++ /dev/null @@ -1,74 +0,0 @@ -package io.metersphere.notice.service; - -import com.dingtalk.api.DefaultDingTalkClient; -import com.dingtalk.api.DingTalkClient; -import com.dingtalk.api.request.OapiRobotSendRequest; -import com.dingtalk.api.response.OapiRobotSendResponse; -import com.taobao.api.ApiException; -import io.metersphere.commons.constants.NoticeConstants; -import io.metersphere.commons.utils.LogUtil; -import io.metersphere.notice.domain.MessageDetail; -import io.metersphere.notice.domain.UserDetail; -import io.metersphere.service.UserService; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; - -import javax.annotation.Resource; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -@Service -@Transactional(propagation = Propagation.NOT_SUPPORTED) -public class DingTaskService { - @Resource - private UserService userService; - - public void sendNailRobot(MessageDetail messageDetail, List userIds, String context, String eventType) { - List addresseeIdList = new ArrayList<>(); - if (StringUtils.equals(eventType, messageDetail.getEvent())) { - messageDetail.getUserIds().forEach(u -> { - if (!StringUtils.equals(NoticeConstants.EXECUTOR, u) && !StringUtils.equals(NoticeConstants.FOUNDER, u) && !StringUtils.equals(NoticeConstants.MAINTAINER, u)) { - addresseeIdList.add(u); - }else{ - addresseeIdList.addAll(userIds); - } - - }); - sendDingTask(context, addresseeIdList, messageDetail.getWebhook()); - } - } - - public void sendDingTask(String context, List userIds, String Webhook) { - if (CollectionUtils.isEmpty(userIds)) { - return; - } - DingTalkClient client = new DefaultDingTalkClient(Webhook); - OapiRobotSendRequest request = new OapiRobotSendRequest(); - request.setMsgtype("text"); - OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text(); - text.setContent(context); - request.setText(text); - OapiRobotSendRequest.At at = new OapiRobotSendRequest.At(); - List list = userService.queryTypeByIds(userIds); - List phoneList = new ArrayList<>(); - list.forEach(u -> { - phoneList.add(u.getPhone()); - }); - LogUtil.info("收件人地址" + phoneList); - List phoneLists = phoneList.stream().distinct().collect(Collectors.toList()); - at.setAtMobiles(phoneLists); - request.setAt(at); - OapiRobotSendResponse response = null; - try { - response = client.execute(request); - } catch (ApiException e) { - LogUtil.error(e.getMessage(), e); - } - System.out.println(response.getErrcode()); - } - -} diff --git a/backend/src/main/java/io/metersphere/notice/service/MailService.java b/backend/src/main/java/io/metersphere/notice/service/MailService.java index 1dea8d0ea8..418abd4573 100644 --- a/backend/src/main/java/io/metersphere/notice/service/MailService.java +++ b/backend/src/main/java/io/metersphere/notice/service/MailService.java @@ -1,375 +1,26 @@ package io.metersphere.notice.service; -import io.metersphere.base.domain.*; -import io.metersphere.base.mapper.UserMapper; -import io.metersphere.commons.constants.*; -import io.metersphere.commons.user.SessionUser; +import io.metersphere.base.domain.SystemParameter; +import io.metersphere.commons.constants.ParamConstants; import io.metersphere.commons.utils.EncryptUtils; -import io.metersphere.commons.utils.LogUtil; -import io.metersphere.dto.BaseSystemConfigDTO; -import io.metersphere.i18n.Translator; -import io.metersphere.notice.domain.MessageDetail; -import io.metersphere.notice.domain.UserDetail; import io.metersphere.service.SystemParameterService; -import io.metersphere.service.UserService; -import io.metersphere.track.request.testcase.IssuesRequest; -import io.metersphere.track.request.testplan.AddTestPlanRequest; -import io.metersphere.track.request.testreview.SaveCommentRequest; -import io.metersphere.track.request.testreview.SaveTestCaseReviewRequest; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.collections4.MapUtils; -import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.BooleanUtils; -import org.apache.commons.lang3.RegExUtils; -import org.apache.commons.lang3.StringUtils; -import org.springframework.mail.MailException; import org.springframework.mail.javamail.JavaMailSenderImpl; -import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; -import javax.mail.MessagingException; -import javax.mail.internet.MimeMessage; -import java.nio.charset.StandardCharsets; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.stream.Collectors; +import java.util.List; +import java.util.Properties; @Service @Transactional(propagation = Propagation.NOT_SUPPORTED) public class MailService { - @Resource - private UserService userService; @Resource private SystemParameterService systemParameterService; - @Resource - private UserMapper userMapper; - //接口和性能测试 - public void sendLoadNotification(MessageDetail messageDetail, LoadTestReportWithBLOBs loadTestReport, String eventType) { - List userIds = new ArrayList<>(); - BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo(); - Map context = new HashMap<>(); - context.put("testName", loadTestReport.getName()); - context.put("id", loadTestReport.getId()); - context.put("type", "performance"); - context.put("url", baseSystemConfigDTO.getUrl()); - String performanceTemplate = ""; - try { - if (StringUtils.equals(loadTestReport.getStatus(), PerformanceTestStatus.Completed.name())) { - performanceTemplate = IOUtils.toString(this.getClass().getResource("/mail/PerformanceApiSuccessNotification.html"), StandardCharsets.UTF_8); - } else if (StringUtils.equals(loadTestReport.getStatus(), PerformanceTestStatus.Error.name())) { - performanceTemplate = IOUtils.toString(this.getClass().getResource("/mail/PerformanceFailedNotification.html"), StandardCharsets.UTF_8); - } - sendApiOrLoadNotification(addresseeIdList(messageDetail, userIds, eventType), context, performanceTemplate, loadTestReport.getTriggerMode()); - } catch (Exception e) { - LogUtil.error(e.getMessage(), e); - } - } - - public void sendApiNotification(MessageDetail messageDetail, ApiTestReport apiTestReport, String eventType) { - List userIds = new ArrayList<>(); - BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo(); - Map context = new HashMap<>(); - context.put("testName", apiTestReport.getName()); - context.put("type", "api"); - context.put("url", baseSystemConfigDTO.getUrl()); - context.put("id", apiTestReport.getId()); - String apiTemplate = ""; - try { - if (StringUtils.equals(APITestStatus.Success.name(), apiTestReport.getStatus())) { - apiTemplate = IOUtils.toString(this.getClass().getResource("/mail/ApiSuccessfulNotification.html"), StandardCharsets.UTF_8); - } else if (StringUtils.equals(APITestStatus.Error.name(), apiTestReport.getStatus())) { - apiTemplate = IOUtils.toString(this.getClass().getResource("/mail/ApiFailedNotification.html"), StandardCharsets.UTF_8); - } - sendApiOrLoadNotification(addresseeIdList(messageDetail, userIds, eventType), context, apiTemplate, apiTestReport.getTriggerMode()); - } catch (Exception e) { - LogUtil.error(e.getMessage(), e); - } - } - - private void sendApiOrLoadNotification(List userIds, Map context, String Template, String type) throws MessagingException { - if (CollectionUtils.isEmpty(userIds)) { - return; - } - JavaMailSenderImpl javaMailSender = getMailSender(); - MimeMessage mimeMessage = javaMailSender.createMimeMessage(); - MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); - helper.setFrom(javaMailSender.getUsername()); - if (StringUtils.equals(type, NoticeConstants.API)) { - helper.setSubject("MeterSphere平台" + Translator.get("task_notification_jenkins")); - } - if (StringUtils.equals(type, NoticeConstants.SCHEDULE)) { - helper.setSubject("MeterSphere平台" + Translator.get("task_notification")); - } - String[] users; - List emails = new ArrayList<>(); - List list = userService.queryTypeByIds(userIds); - list.forEach(u -> { - emails.add(u.getEmail()); - }); - List email = emails.stream().distinct().collect(Collectors.toList()); - users = email.toArray(new String[0]); - LogUtil.info("收件人地址" + users); - helper.setText(getContent(Template, context), true); - helper.setTo(users); - try { - javaMailSender.send(mimeMessage); - } catch (MailException e) { - LogUtil.error(e.getMessage(), e); - } - } - //测试评审 - - public void sendEndNotice(MessageDetail messageDetail, List userIds, SaveTestCaseReviewRequest reviewRequest, String eventType) { - Map context = getReviewContext(reviewRequest); - try { - String endTemplate = IOUtils.toString(this.getClass().getResource("/mail/ReviewEnd.html"), StandardCharsets.UTF_8); - sendReviewNotice(addresseeIdList(messageDetail, userIds, eventType), context, endTemplate); - } catch (Exception e) { - LogUtil.error(e.getMessage(), e); - } - } - - public void sendDeleteNotice(MessageDetail messageDetail, List userIds, SaveTestCaseReviewRequest reviewRequest, String eventType) { - Map context = getReviewContext(reviewRequest); - try { - String endTemplate = IOUtils.toString(this.getClass().getResource("/mail/ReviewDelete.html"), StandardCharsets.UTF_8); - sendReviewNotice(addresseeIdList(messageDetail, userIds, eventType), context, endTemplate); - } catch (Exception e) { - LogUtil.error(e.getMessage(), e); - } - } - - public void sendCommentNotice(MessageDetail messageDetail, List userIds, SaveCommentRequest request, TestCaseWithBLOBs testCaseWithBLOBs, String eventType) { - User user = userMapper.selectByPrimaryKey(testCaseWithBLOBs.getMaintainer()); - BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo(); - Map context = new HashMap<>(); - context.put("maintainer", user.getName()); - context.put("testCaseName", testCaseWithBLOBs.getName()); - context.put("description", request.getDescription()); - context.put("url", baseSystemConfigDTO.getUrl()); - context.put("id", request.getReviewId()); - try { - String commentTemplate = IOUtils.toString(this.getClass().getResource("/mail/ReviewComments.html"), StandardCharsets.UTF_8); - sendReviewNotice(addresseeIdList(messageDetail, userIds, eventType), context, commentTemplate); - } catch (Exception e) { - LogUtil.error(e.getMessage(), e); - } - } - - public void sendReviewerNotice(MessageDetail messageDetail, List userIds, SaveTestCaseReviewRequest reviewRequest, String eventType) { - Map context = getReviewContext(reviewRequest); - try { - String reviewerTemplate = IOUtils.toString(this.getClass().getResource("/mail/ReviewInitiate.html"), StandardCharsets.UTF_8); - sendReviewNotice(addresseeIdList(messageDetail, userIds, eventType), context, reviewerTemplate); - } catch (Exception e) { - LogUtil.error(e.getMessage(), e); - } - } - - private void sendReviewNotice(List userIds, Map context, String Template) throws MessagingException { - if (CollectionUtils.isEmpty(userIds)) { - return; - } - JavaMailSenderImpl javaMailSender = getMailSender(); - MimeMessage mimeMessage = javaMailSender.createMimeMessage(); - MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); - helper.setFrom(javaMailSender.getUsername()); - helper.setSubject("MeterSphere平台" + Translator.get("test_review_task_notice")); - String[] users; - List emails = new ArrayList<>(); - List list = userService.queryTypeByIds(userIds); - list.forEach(u -> { - emails.add(u.getEmail()); - }); - List email = emails.stream().distinct().collect(Collectors.toList()); - users = email.toArray(new String[0]); - LogUtil.info("收件人地址" + users); - helper.setText(getContent(Template, context), true); - helper.setTo(users); - if (users.length > 0) { - javaMailSender.send(mimeMessage); - } - } - - //测试计划 - - public void sendTestPlanStartNotice(MessageDetail messageDetail, List userIds, AddTestPlanRequest testPlan, String eventType) { - Map context = getTestPlanContext(testPlan); - User user = userMapper.selectByPrimaryKey(testPlan.getCreator()); - context.put("creator", user.getName()); - try { - String endTemplate = IOUtils.toString(this.getClass().getResource("/mail/TestPlanStart.html"), StandardCharsets.UTF_8); - sendTestPlanNotice(addresseeIdList(messageDetail, userIds, eventType), context, endTemplate); - } catch (Exception e) { - LogUtil.error(e.getMessage(), e); - } - } - - public void sendTestPlanEndNotice(MessageDetail messageDetail, List userIds, AddTestPlanRequest testPlan, String eventType) { - User user = userMapper.selectByPrimaryKey(testPlan.getCreator()); - Map context = getTestPlanContext(testPlan); - context.put("creator", user.getName()); - try { - String endTemplate = IOUtils.toString(this.getClass().getResource("/mail/TestPlanEnd.html"), StandardCharsets.UTF_8); - sendTestPlanNotice(addresseeIdList(messageDetail, userIds, eventType), context, endTemplate); - } catch (Exception e) { - LogUtil.error(e.getMessage(), e); - } - } - - public void sendTestPlanDeleteNotice(MessageDetail messageDetail, List userIds, AddTestPlanRequest testPlan, String eventType) { - User user = userMapper.selectByPrimaryKey(testPlan.getCreator()); - Map context = getTestPlanContext(testPlan); - context.put("creator", user.getName()); - try { - String endTemplate = IOUtils.toString(this.getClass().getResource("/mail/TestPlanDelete.html"), StandardCharsets.UTF_8); - sendTestPlanNotice(addresseeIdList(messageDetail, userIds, eventType), context, endTemplate); - } catch (Exception e) { - LogUtil.error(e.getMessage(), e); - } - } - - private void sendTestPlanNotice(List userIds, Map context, String Template) throws MessagingException { - if (CollectionUtils.isEmpty(userIds)) { - return; - } - JavaMailSenderImpl javaMailSender = getMailSender(); - MimeMessage mimeMessage = javaMailSender.createMimeMessage(); - MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); - helper.setFrom(javaMailSender.getUsername()); - helper.setSubject("MeterSphere平台" + Translator.get("test_plan_notification")); - String[] users; - List emails = new ArrayList<>(); - List list = userService.queryTypeByIds(userIds); - list.forEach(u -> { - emails.add(u.getEmail()); - }); - List email = emails.stream().distinct().collect(Collectors.toList()); - users = email.toArray(new String[0]); - LogUtil.info("收件人地址" + users); - helper.setText(getContent(Template, context), true); - helper.setTo(users); - javaMailSender.send(mimeMessage); - - } - - //缺陷任务 - public void sendIssuesNotice(MessageDetail messageDetail, List userIds, IssuesRequest issuesRequest, String eventType, SessionUser user) { - Map context = new HashMap<>(); - context.put("issuesName", issuesRequest.getTitle()); - context.put("creator", user.getName()); - try { - String endTemplate = IOUtils.toString(this.getClass().getResource("/mail/IssuesCreate.html"), StandardCharsets.UTF_8); - sendIssuesNotice(addresseeIdList(messageDetail, userIds, eventType), context, endTemplate); - } catch (Exception e) { - LogUtil.error(e.getMessage(), e); - } - } - - private void sendIssuesNotice(List userIds, Map context, String Template) throws MessagingException { - if (CollectionUtils.isEmpty(userIds)) { - return; - } - JavaMailSenderImpl javaMailSender = getMailSender(); - MimeMessage mimeMessage = javaMailSender.createMimeMessage(); - MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); - helper.setFrom(javaMailSender.getUsername()); - helper.setSubject("MeterSphere平台" + Translator.get("task_defect_notification")); - String[] users; - List emails = new ArrayList<>(); - List list = userService.queryTypeByIds(userIds); - list.forEach(u -> { - emails.add(u.getEmail()); - }); - List email = emails.stream().distinct().collect(Collectors.toList()); - users = email.toArray(new String[0]); - LogUtil.info("收件人地址" + users); - helper.setText(getContent(Template, context), true); - helper.setTo(users); - javaMailSender.send(mimeMessage); - - } - - //评审内容 - private Map getReviewContext(SaveTestCaseReviewRequest reviewRequest) { - Long startTime = reviewRequest.getCreateTime(); - Long endTime = reviewRequest.getEndTime(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - String start = null; - String sTime = String.valueOf(startTime); - String eTime = String.valueOf(endTime); - if (!sTime.equals("null")) { - start = sdf.format(new Date(Long.parseLong(sTime))); - } - String end = null; - if (!eTime.equals("null")) { - end = sdf.format(new Date(Long.parseLong(eTime))); - } - - Map context = new HashMap<>(); - BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo(); - context.put("url", baseSystemConfigDTO.getUrl()); - User user = userMapper.selectByPrimaryKey(reviewRequest.getCreator()); - context.put("creator", user.getName()); - context.put("reviewName", reviewRequest.getName()); - context.put("start", start); - context.put("end", end); - context.put("id", reviewRequest.getId()); - String status = ""; - if (StringUtils.equals(TestPlanStatus.Underway.name(), reviewRequest.getStatus())) { - status = "进行中"; - } else if (StringUtils.equals(TestPlanStatus.Prepare.name(), reviewRequest.getStatus())) { - status = "未开始"; - } else if (StringUtils.equals(TestPlanStatus.Completed.name(), reviewRequest.getStatus())) { - status = "已完成"; - } - context.put("status", status); - return context; - } - - //计划内容 - private Map getTestPlanContext(AddTestPlanRequest testPlan) { - Long startTime = testPlan.getPlannedStartTime(); - Long endTime = testPlan.getPlannedEndTime(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - String start = null; - String sTime = String.valueOf(startTime); - String eTime = String.valueOf(endTime); - if (!sTime.equals("null")) { - start = sdf.format(new Date(Long.parseLong(sTime))); - } - String end = null; - if (!eTime.equals("null")) { - end = sdf.format(new Date(Long.parseLong(eTime))); - } - - Map context = new HashMap<>(); - BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo(); - context.put("url", baseSystemConfigDTO.getUrl()); - context.put("testPlanName", testPlan.getName()); - context.put("start", start); - context.put("end", end); - context.put("id", testPlan.getId()); - String status = ""; - if (StringUtils.equals(TestPlanStatus.Underway.name(), testPlan.getStatus())) { - status = "进行中"; - } else if (StringUtils.equals(TestPlanStatus.Prepare.name(), testPlan.getStatus())) { - status = "未开始"; - } else if (StringUtils.equals(TestPlanStatus.Completed.name(), testPlan.getStatus())) { - status = "已完成"; - } - context.put("status", status); - User user = userMapper.selectByPrimaryKey(testPlan.getCreator()); - context.put("creator", user.getName()); - return context; - } - - - private JavaMailSenderImpl getMailSender() { + public JavaMailSenderImpl getMailSender() { Properties props = new Properties(); JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl(); List paramList = systemParameterService.getParamList(ParamConstants.Classify.MAIL.getValue()); @@ -420,47 +71,6 @@ public class MailService { javaMailSender.setJavaMailProperties(props); return javaMailSender; } - - private String getContent(String template, Map context) { - if (MapUtils.isNotEmpty(context)) { - for (String k : context.keySet()) { - if (StringUtils.isNotBlank(context.get(k))) { - template = RegExUtils.replaceAll(template, "\\$\\{" + k + "}", context.get(k)); - } else { - template = RegExUtils.replaceAll(template, "\\$\\{" + k + "}", "未设置"); - } - - } - } - return template; - } - - private List addresseeIdList(MessageDetail messageDetail, List userIds, String eventType) { - List addresseeIdList = new ArrayList<>(); - if (StringUtils.equals(eventType, messageDetail.getEvent())) { - messageDetail.getUserIds().forEach(u -> { - if (!StringUtils.equals(NoticeConstants.EXECUTOR, u) && !StringUtils.equals(NoticeConstants.FOUNDER, u) && !StringUtils.equals(NoticeConstants.MAINTAINER, u)) { - addresseeIdList.add(u); - } - if (StringUtils.equals(NoticeConstants.CREATE, eventType) && StringUtils.equals(NoticeConstants.EXECUTOR, u)) { - addresseeIdList.addAll(userIds); - } - if (StringUtils.equals(NoticeConstants.UPDATE, eventType) && StringUtils.equals(NoticeConstants.FOUNDER, u)) { - addresseeIdList.addAll(userIds); - } - if (StringUtils.equals(NoticeConstants.DELETE, eventType) && StringUtils.equals(NoticeConstants.FOUNDER, u)) { - addresseeIdList.addAll(userIds); - } - if (StringUtils.equals(NoticeConstants.COMMENT, eventType) && StringUtils.equals(NoticeConstants.MAINTAINER, u)) { - addresseeIdList.addAll(userIds); - } - - - }); - } - return addresseeIdList; - } - } diff --git a/backend/src/main/java/io/metersphere/notice/service/NoticeSendService.java b/backend/src/main/java/io/metersphere/notice/service/NoticeSendService.java new file mode 100644 index 0000000000..597820a06a --- /dev/null +++ b/backend/src/main/java/io/metersphere/notice/service/NoticeSendService.java @@ -0,0 +1,63 @@ +package io.metersphere.notice.service; + +import io.metersphere.commons.constants.NoticeConstants; +import io.metersphere.commons.utils.CommonBeanFactory; +import io.metersphere.notice.domain.MessageDetail; +import io.metersphere.notice.sender.NoticeModel; +import io.metersphere.notice.sender.NoticeSender; +import io.metersphere.notice.sender.impl.DingNoticeSender; +import io.metersphere.notice.sender.impl.MailNoticeSender; +import io.metersphere.notice.sender.impl.WeComNoticeSender; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.List; + +@Component +public class NoticeSendService { + @Resource + private MailNoticeSender mailNoticeSender; + @Resource + private WeComNoticeSender weComNoticeSender; + @Resource + private DingNoticeSender dingNoticeSender; + + private NoticeSender getNoticeSender(MessageDetail messageDetail) { + NoticeSender noticeSender = null; + switch (messageDetail.getType()) { + case NoticeConstants.Type.EMAIL: + noticeSender = mailNoticeSender; + break; + case NoticeConstants.Type.WECHAT_ROBOT: + noticeSender = weComNoticeSender; + break; + case NoticeConstants.Type.NAIL_ROBOT: + noticeSender = dingNoticeSender; + break; + default: + break; + } + + return noticeSender; + } + + public void send(String taskType, NoticeModel noticeModel) { + NoticeService noticeService = CommonBeanFactory.getBean(NoticeService.class); + assert noticeService != null; + List messageDetails; + switch (taskType) { + case NoticeConstants.Mode.API: + messageDetails = noticeService.searchMessageByType(NoticeConstants.TaskType.JENKINS_TASK); + break; + case NoticeConstants.Mode.SCHEDULE: + messageDetails = noticeService.searchMessageByTestId(noticeModel.getTestId()); + break; + default: + messageDetails = noticeService.searchMessageByType(taskType); + break; + } + messageDetails.forEach(messageDetail -> + this.getNoticeSender(messageDetail).send(messageDetail, noticeModel) + ); + } +} diff --git a/backend/src/main/java/io/metersphere/notice/service/NoticeService.java b/backend/src/main/java/io/metersphere/notice/service/NoticeService.java index dd0a6237b1..d4abf85876 100644 --- a/backend/src/main/java/io/metersphere/notice/service/NoticeService.java +++ b/backend/src/main/java/io/metersphere/notice/service/NoticeService.java @@ -3,15 +3,11 @@ package io.metersphere.notice.service; import io.metersphere.base.domain.MessageTask; import io.metersphere.base.domain.MessageTaskExample; import io.metersphere.base.mapper.MessageTaskMapper; -import io.metersphere.base.mapper.ext.ExtMessageMapper; -import io.metersphere.commons.constants.NoticeConstants; import io.metersphere.commons.exception.MSException; import io.metersphere.commons.user.SessionUser; import io.metersphere.commons.utils.SessionUtils; import io.metersphere.i18n.Translator; -import io.metersphere.notice.controller.request.MessageRequest; import io.metersphere.notice.domain.MessageDetail; -import io.metersphere.notice.domain.MessageSettingDetail; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; @@ -26,129 +22,123 @@ import java.util.stream.Collectors; public class NoticeService { @Resource private MessageTaskMapper messageTaskMapper; - @Resource - private ExtMessageMapper extMessageMapper; - - public void saveMessageTask(MessageRequest messageRequest) { - messageRequest.getMessageDetail().forEach(list -> { - MessageTaskExample example = new MessageTaskExample(); - example.createCriteria().andIdentificationEqualTo(list.getIdentification()); - List messageTaskLists = messageTaskMapper.selectByExample(example); - if (messageTaskLists.size() > 0) { - delMessage(list.getIdentification()); - getSaveMessageTask(list); - } - if (messageTaskLists.size() <= 0) { - getSaveMessageTask(list); - } - }); - } - - public void getSaveMessageTask(MessageDetail list) { + public void saveMessageTask(MessageDetail messageDetail) { + MessageTaskExample example = new MessageTaskExample(); + example.createCriteria().andIdentificationEqualTo(messageDetail.getIdentification()); + List messageTaskLists = messageTaskMapper.selectByExample(example); + if (messageTaskLists.size() > 0) { + delMessage(messageDetail.getIdentification()); + } SessionUser user = SessionUtils.getUser(); - assert user != null; String orgId = user.getLastOrganizationId(); long time = System.currentTimeMillis(); String identification = UUID.randomUUID().toString(); - list.getUserIds().forEach(m -> { - checkUserIdExist(m, list,orgId); - MessageTask message = new MessageTask(); - message.setId(UUID.randomUUID().toString()); - message.setEvent(list.getEvent()); - message.setTaskType(list.getTaskType()); - message.setUserId(m); - message.setType(list.getType()); - message.setWebhook(list.getWebhook()); - message.setIdentification(identification); - message.setIsSet(false); - message.setOrganizationId(orgId); - message.setTestId(list.getTestId()); - message.setCreateTime(time); - messageTaskMapper.insert(message); + messageDetail.getUserIds().forEach(m -> { + checkUserIdExist(m, messageDetail, orgId); + MessageTask messageTask = new MessageTask(); + messageTask.setId(UUID.randomUUID().toString()); + messageTask.setEvent(messageDetail.getEvent()); + messageTask.setTaskType(messageDetail.getTaskType()); + messageTask.setUserId(m); + messageTask.setType(messageDetail.getType()); + messageTask.setWebhook(messageDetail.getWebhook()); + messageTask.setIdentification(identification); + messageTask.setIsSet(false); + messageTask.setOrganizationId(orgId); + messageTask.setTestId(messageDetail.getTestId()); + messageTask.setCreateTime(time); + messageTaskMapper.insert(messageTask); }); } - private void checkUserIdExist(String userId, MessageDetail list,String orgId) { + private void checkUserIdExist(String userId, MessageDetail list, String orgId) { MessageTaskExample example = new MessageTaskExample(); if (StringUtils.isBlank(list.getTestId())) { - example.createCriteria().andUserIdEqualTo(userId).andEventEqualTo(list.getEvent()).andTypeEqualTo(list.getType()).andTaskTypeEqualTo(list.getTaskType()).andWebhookEqualTo(list.getWebhook()).andOrganizationIdEqualTo(orgId); + example.createCriteria() + .andUserIdEqualTo(userId) + .andEventEqualTo(list.getEvent()) + .andTypeEqualTo(list.getType()) + .andTaskTypeEqualTo(list.getTaskType()) + .andWebhookEqualTo(list.getWebhook()) + .andOrganizationIdEqualTo(orgId); } else { - example.createCriteria().andUserIdEqualTo(userId).andEventEqualTo(list.getEvent()).andTypeEqualTo(list.getType()).andTaskTypeEqualTo(list.getTaskType()).andWebhookEqualTo(list.getWebhook()).andTestIdEqualTo(list.getTestId()).andOrganizationIdEqualTo(orgId); + example.createCriteria() + .andUserIdEqualTo(userId) + .andEventEqualTo(list.getEvent()) + .andTypeEqualTo(list.getType()) + .andTaskTypeEqualTo(list.getTaskType()) + .andWebhookEqualTo(list.getWebhook()) + .andTestIdEqualTo(list.getTestId()) + .andOrganizationIdEqualTo(orgId); } if (messageTaskMapper.countByExample(example) > 0) { MSException.throwException(Translator.get("message_task_already_exists")); } } - public List searchMessageSchedule(String testId) { - List messageTaskLists = extMessageMapper.searchMessageByTestId(testId); + public List searchMessageByTestId(String testId) { + MessageTaskExample example = new MessageTaskExample(); + example.createCriteria().andTestIdEqualTo(testId); + List messageTaskLists = messageTaskMapper.selectByExample(example); List scheduleMessageTask = new ArrayList<>(); Map> MessageTaskMap = messageTaskLists.stream().collect(Collectors.groupingBy(MessageTask::getIdentification)); MessageTaskMap.forEach((k, v) -> { - Set userIds = new HashSet<>(); - MessageDetail messageDetail = new MessageDetail(); - for (MessageTask m : v) { - userIds.add(m.getUserId()); - messageDetail.setEvent(m.getEvent()); - messageDetail.setTaskType(m.getTaskType()); - messageDetail.setWebhook(m.getWebhook()); - messageDetail.setIdentification(m.getIdentification()); - messageDetail.setType(m.getType()); - messageDetail.setIsSet(m.getIsSet()); - messageDetail.setCreateTime(m.getCreateTime()); - } - if (CollectionUtils.isNotEmpty(userIds)) { - messageDetail.setUserIds(new ArrayList<>(userIds)); - } + MessageDetail messageDetail = getMessageDetail(v); scheduleMessageTask.add(messageDetail); }); scheduleMessageTask.sort(Comparator.comparing(MessageDetail::getCreateTime, Comparator.nullsLast(Long::compareTo)).reversed()); return scheduleMessageTask; } - public MessageSettingDetail searchMessage() { + public List searchMessageByType(String type) { SessionUser user = SessionUtils.getUser(); - assert user != null; String orgId = user.getLastOrganizationId(); - List messageTaskLists; - MessageSettingDetail messageSettingDetail = new MessageSettingDetail(); - List MessageDetailList = new ArrayList<>(); - messageTaskLists = extMessageMapper.searchMessageByOrganizationId(orgId); - Map> MessageTaskMap = messageTaskLists.stream().collect(Collectors.groupingBy(NoticeService::fetchGroupKey)); - MessageTaskMap.forEach((k, v) -> { - Set userIds = new HashSet<>(); - MessageDetail messageDetail = new MessageDetail(); - for (MessageTask m : v) { - userIds.add(m.getUserId()); - messageDetail.setEvent(m.getEvent()); - messageDetail.setTaskType(m.getTaskType()); - messageDetail.setWebhook(m.getWebhook()); - messageDetail.setIdentification(m.getIdentification()); - messageDetail.setType(m.getType()); - messageDetail.setIsSet(m.getIsSet()); - messageDetail.setCreateTime(m.getCreateTime()); - } - messageDetail.setUserIds(new ArrayList(userIds)); - MessageDetailList.add(messageDetail); + List messageDetails = new ArrayList<>(); + + MessageTaskExample example = new MessageTaskExample(); + example.createCriteria() + .andTaskTypeEqualTo(type) + .andOrganizationIdEqualTo(orgId); + List messageTaskLists = messageTaskMapper.selectByExample(example); + + Map> messageTaskMap = messageTaskLists.stream() + .collect(Collectors.groupingBy(NoticeService::fetchGroupKey)); + messageTaskMap.forEach((k, v) -> { + MessageDetail messageDetail = getMessageDetail(v); + messageDetails.add(messageDetail); }); - List jenkinsTask = (MessageDetailList.stream().filter(a -> a.getTaskType().equals(NoticeConstants.JENKINS_TASK)).sorted(Comparator.comparing( - MessageDetail::getCreateTime, Comparator.nullsLast(Long::compareTo)).reversed()).collect(Collectors.toList())).stream().distinct().collect(Collectors.toList()); - List testCasePlanTask = (MessageDetailList.stream().filter(a -> a.getTaskType().equals(NoticeConstants.TEST_PLAN_TASK)).sorted(Comparator.comparing( - MessageDetail::getCreateTime, Comparator.nullsLast(Long::compareTo)).reversed()).collect(Collectors.toList())).stream().distinct().collect(Collectors.toList()); - List reviewTask = (MessageDetailList.stream().filter(a -> a.getTaskType().equals(NoticeConstants.REVIEW_TASK)).sorted(Comparator.comparing( - MessageDetail::getCreateTime, Comparator.nullsLast(Long::compareTo)).reversed()).collect(Collectors.toList())).stream().distinct().collect(Collectors.toList()); - List defectTask = (MessageDetailList.stream().filter(a -> a.getTaskType().equals(NoticeConstants.DEFECT_TASK)).sorted(Comparator.comparing( - MessageDetail::getCreateTime, Comparator.nullsLast(Long::compareTo)).reversed()).collect(Collectors.toList())).stream().distinct().collect(Collectors.toList()); - messageSettingDetail.setJenkinsTask(jenkinsTask); - messageSettingDetail.setTestCasePlanTask(testCasePlanTask); - messageSettingDetail.setReviewTask(reviewTask); - messageSettingDetail.setDefectTask(defectTask); - return messageSettingDetail; + + return messageDetails.stream() + .sorted(Comparator.comparing(MessageDetail::getCreateTime, Comparator.nullsLast(Long::compareTo)).reversed()) + .collect(Collectors.toList()) + .stream() + .distinct() + .collect(Collectors.toList()); } - private static String fetchGroupKey(MessageTask user) { - return user.getTaskType() + "#" + user.getIdentification(); + private MessageDetail getMessageDetail(List messageTasks) { + Set userIds = new HashSet<>(); + + MessageDetail messageDetail = new MessageDetail(); + for (MessageTask m : messageTasks) { + userIds.add(m.getUserId()); + messageDetail.setEvent(m.getEvent()); + messageDetail.setTaskType(m.getTaskType()); + messageDetail.setWebhook(m.getWebhook()); + messageDetail.setIdentification(m.getIdentification()); + messageDetail.setType(m.getType()); + messageDetail.setIsSet(m.getIsSet()); + messageDetail.setCreateTime(m.getCreateTime()); + } + if (CollectionUtils.isNotEmpty(userIds)) { + messageDetail.setUserIds(new ArrayList<>(userIds)); + } + return messageDetail; + } + + private static String fetchGroupKey(MessageTask messageTask) { + return messageTask.getTaskType() + "#" + messageTask.getIdentification(); } public int delMessage(String identification) { diff --git a/backend/src/main/java/io/metersphere/notice/service/WxChatTaskService.java b/backend/src/main/java/io/metersphere/notice/service/WxChatTaskService.java deleted file mode 100644 index 89249b2b43..0000000000 --- a/backend/src/main/java/io/metersphere/notice/service/WxChatTaskService.java +++ /dev/null @@ -1,66 +0,0 @@ -package io.metersphere.notice.service; - -import io.metersphere.commons.constants.NoticeConstants; -import io.metersphere.commons.utils.LogUtil; -import io.metersphere.notice.domain.MessageDetail; -import io.metersphere.notice.domain.UserDetail; -import io.metersphere.notice.message.TextMessage; -import io.metersphere.notice.util.SendResult; -import io.metersphere.notice.util.WxChatbotClient; -import io.metersphere.service.UserService; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; - -import javax.annotation.Resource; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -@Service -@Transactional(propagation = Propagation.NOT_SUPPORTED) -public class WxChatTaskService { - @Resource - private UserService userService; - - public void sendWechatRobot(MessageDetail messageDetail, List userIds, String context, String eventType) { - List addresseeIdList = new ArrayList<>(); - if (StringUtils.equals(eventType, messageDetail.getEvent())) { - messageDetail.getUserIds().forEach(u -> { - if (!StringUtils.equals(NoticeConstants.EXECUTOR, u) && !StringUtils.equals(NoticeConstants.FOUNDER, u) && !StringUtils.equals(NoticeConstants.MAINTAINER, u)) { - addresseeIdList.add(u); - }else{ - addresseeIdList.addAll(userIds); - } - }); - enterpriseWechatTask(context, addresseeIdList, messageDetail.getWebhook()); - } - } - - public void enterpriseWechatTask(String context, List userIds, String Webhook) { - if (CollectionUtils.isEmpty(userIds)) { - return; - } - TextMessage message = new TextMessage(context); - List mentionedMobileList = new ArrayList<>(); - List list = userService.queryTypeByIds(userIds); - List phoneList = new ArrayList<>(); - list.forEach(u -> { - phoneList.add(u.getPhone()); - }); - LogUtil.info("收件人地址" + phoneList); - List phoneLists = phoneList.stream().distinct().collect(Collectors.toList()); - mentionedMobileList.addAll(phoneLists); - message.setMentionedMobileList(mentionedMobileList); - try { - SendResult result = WxChatbotClient.send(Webhook, message); - System.out.println(result); - } catch (IOException e) { - LogUtil.error(e.getMessage(), e); - } - } - -} diff --git a/backend/src/main/java/io/metersphere/performance/notice/PerformanceNoticeTask.java b/backend/src/main/java/io/metersphere/performance/notice/PerformanceNoticeTask.java index b3ca8d57c4..8525f51a34 100644 --- a/backend/src/main/java/io/metersphere/performance/notice/PerformanceNoticeTask.java +++ b/backend/src/main/java/io/metersphere/performance/notice/PerformanceNoticeTask.java @@ -6,60 +6,46 @@ import io.metersphere.commons.constants.NoticeConstants; import io.metersphere.commons.constants.PerformanceTestStatus; import io.metersphere.commons.utils.LogUtil; import io.metersphere.dto.BaseSystemConfigDTO; -import io.metersphere.notice.domain.MessageDetail; -import io.metersphere.notice.domain.MessageSettingDetail; -import io.metersphere.notice.service.DingTaskService; -import io.metersphere.notice.service.MailService; -import io.metersphere.notice.service.NoticeService; -import io.metersphere.notice.service.WxChatTaskService; +import io.metersphere.i18n.Translator; +import io.metersphere.notice.sender.NoticeModel; +import io.metersphere.notice.service.NoticeSendService; import io.metersphere.service.SystemParameterService; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import javax.annotation.PreDestroy; import javax.annotation.Resource; -import java.util.ArrayList; -import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @Component public class PerformanceNoticeTask { - @Resource - private NoticeService noticeService; - @Resource - private DingTaskService dingTaskService; - @Resource - private WxChatTaskService wxChatTaskService; - @Resource - private MailService mailService; @Resource private SystemParameterService systemParameterService; @Resource private LoadTestReportMapper loadTestReportMapper; + @Resource + private NoticeSendService noticeSendService; private final ExecutorService executorService = Executors.newFixedThreadPool(20); - private boolean isRunning=false; + private boolean isRunning = false; - /*@PreDestroy + @PreDestroy public void preDestroy() { isRunning = false; - }*/ + } public void registerNoticeTask(LoadTestReportWithBLOBs loadTestReport) { - isRunning=true; + isRunning = true; executorService.submit(() -> { LogUtil.info("性能测试定时任务"); while (isRunning) { LoadTestReportWithBLOBs loadTestReportFromDatabase = loadTestReportMapper.selectByPrimaryKey(loadTestReport.getId()); - if (StringUtils.equals(loadTestReportFromDatabase.getStatus(), PerformanceTestStatus.Completed.name())) { - sendSuccessNotice(loadTestReportFromDatabase); - isRunning=false; - } - if (StringUtils.equals(loadTestReportFromDatabase.getStatus(), PerformanceTestStatus.Error.name())) { - sendFailNotice(loadTestReportFromDatabase); - isRunning=false; + if (StringUtils.equalsAny(loadTestReportFromDatabase.getStatus(), + PerformanceTestStatus.Completed.name(), PerformanceTestStatus.Error.name())) { + sendNotice(loadTestReportFromDatabase); + isRunning = false; } try { //查询定时任务是否关闭 @@ -71,81 +57,32 @@ public class PerformanceNoticeTask { }); } - public void sendSuccessNotice(LoadTestReportWithBLOBs loadTestReport) { - List userIds = new ArrayList<>(); - List taskList = new ArrayList<>(); + public void sendNotice(LoadTestReportWithBLOBs loadTestReport) { + BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo(); + String url = baseSystemConfigDTO.getUrl() + "/#/performance/report/view/" + loadTestReport.getId(); String successContext = ""; - BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo(); - String url = baseSystemConfigDTO.getUrl() + "/#/performance/report/view/" + loadTestReport.getId(); - if (StringUtils.equals(NoticeConstants.API, loadTestReport.getTriggerMode())) { - MessageSettingDetail messageSettingDetail = noticeService.searchMessage(); - taskList = messageSettingDetail.getJenkinsTask(); - successContext = "LoadJenkins任务通知:" + loadTestReport.getName() + "执行成功" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url; - } - if (StringUtils.equals(NoticeConstants.SCHEDULE, loadTestReport.getTriggerMode())) { - taskList = noticeService.searchMessageSchedule(loadTestReport.getTestId()); - successContext = "Load定时任务通知:" + loadTestReport.getName() + "执行成功" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url; - } - String finalSuccessContext = successContext; - taskList.forEach(r -> { - switch (r.getType()) { - case NoticeConstants.NAIL_ROBOT: - if (StringUtils.equals(NoticeConstants.EXECUTE_SUCCESSFUL, r.getEvent()) && StringUtils.equals(loadTestReport.getStatus(), PerformanceTestStatus.Completed.name())) { - dingTaskService.sendNailRobot(r, userIds, finalSuccessContext, NoticeConstants.EXECUTE_SUCCESSFUL); - } - break; - case NoticeConstants.WECHAT_ROBOT: - if (StringUtils.equals(NoticeConstants.EXECUTE_SUCCESSFUL, r.getEvent()) && StringUtils.equals(loadTestReport.getStatus(), PerformanceTestStatus.Completed.name())) { - wxChatTaskService.sendWechatRobot(r, userIds, finalSuccessContext, NoticeConstants.EXECUTE_SUCCESSFUL); - } - break; - case NoticeConstants.EMAIL: - if (StringUtils.equals(NoticeConstants.EXECUTE_SUCCESSFUL, r.getEvent()) && StringUtils.equals(loadTestReport.getStatus(), PerformanceTestStatus.Completed.name())) { - mailService.sendLoadNotification(r, loadTestReport, NoticeConstants.EXECUTE_SUCCESSFUL); - } - break; - } - - }); - } - - - public void sendFailNotice(LoadTestReportWithBLOBs loadTestReport) { - List userIds = new ArrayList<>(); - List taskList = new ArrayList<>(); String failedContext = ""; - BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo(); - String url = baseSystemConfigDTO.getUrl() + "/#/performance/report/view/" + loadTestReport.getId(); - if (StringUtils.equals(NoticeConstants.API, loadTestReport.getTriggerMode())) { - MessageSettingDetail messageSettingDetail = noticeService.searchMessage(); - taskList = messageSettingDetail.getJenkinsTask(); - failedContext = "LoadJenkins任务通知:" + loadTestReport.getName() + "执行失败" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url; + String subject = ""; + if (StringUtils.equals(NoticeConstants.Mode.API, loadTestReport.getTriggerMode())) { + successContext = "性能测试 API任务通知:" + loadTestReport.getName() + "执行成功" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url; + failedContext = "性能测试 API任务通知:" + loadTestReport.getName() + "执行失败" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url; + subject = Translator.get("task_notification_jenkins"); } - if (StringUtils.equals(NoticeConstants.SCHEDULE, loadTestReport.getTriggerMode())) { - taskList = noticeService.searchMessageSchedule(loadTestReport.getTestId()); - failedContext = "Load定时任务通知:" + loadTestReport.getName() + "执行失败" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url; + if (StringUtils.equals(NoticeConstants.Mode.SCHEDULE, loadTestReport.getTriggerMode())) { + successContext = "性能测试定时任务通知:" + loadTestReport.getName() + "执行成功" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url; + failedContext = "性能测试定时任务通知:" + loadTestReport.getName() + "执行失败" + "\n" + "请点击下面链接进入测试报告页面" + "\n" + url; + subject = Translator.get("task_notification"); } - String finalFailedContext = failedContext; - taskList.forEach(r -> { - switch (r.getType()) { - case NoticeConstants.NAIL_ROBOT: - if (StringUtils.equals(NoticeConstants.EXECUTE_FAILED, r.getEvent()) && StringUtils.equals(loadTestReport.getStatus(), PerformanceTestStatus.Error.name())) { - dingTaskService.sendNailRobot(r, userIds, finalFailedContext, NoticeConstants.EXECUTE_FAILED); - } - break; - case NoticeConstants.WECHAT_ROBOT: - if (StringUtils.equals(NoticeConstants.EXECUTE_FAILED, r.getEvent()) && StringUtils.equals(loadTestReport.getStatus(), PerformanceTestStatus.Error.name())) { - wxChatTaskService.sendWechatRobot(r, userIds, finalFailedContext, NoticeConstants.EXECUTE_FAILED); - } - break; - case NoticeConstants.EMAIL: - if (StringUtils.equals(NoticeConstants.EXECUTE_FAILED, r.getEvent()) && StringUtils.equals(loadTestReport.getStatus(), PerformanceTestStatus.Error.name())) { - mailService.sendLoadNotification(r, loadTestReport, NoticeConstants.EXECUTE_FAILED); - } - break; - } - }); + NoticeModel noticeModel = NoticeModel.builder() + .successContext(successContext) + .successMailTemplate("PerformanceApiSuccessNotification") + .failedContext(failedContext) + .failedMailTemplate("PerformanceFailedNotification") + .testId(loadTestReport.getTestId()) + .status(loadTestReport.getStatus()) + .subject(subject) + .build(); + noticeSendService.send(loadTestReport.getTriggerMode(), noticeModel); } - } \ No newline at end of file diff --git a/backend/src/main/java/io/metersphere/performance/service/PerformanceTestService.java b/backend/src/main/java/io/metersphere/performance/service/PerformanceTestService.java index 544a2eaefd..add70f7054 100644 --- a/backend/src/main/java/io/metersphere/performance/service/PerformanceTestService.java +++ b/backend/src/main/java/io/metersphere/performance/service/PerformanceTestService.java @@ -232,7 +232,7 @@ public class PerformanceTestService { startEngine(loadTest, engine, request.getTriggerMode()); LoadTestReportWithBLOBs loadTestReport = loadTestReportMapper.selectByPrimaryKey(engine.getReportId()); - if (StringUtils.equals(NoticeConstants.API, loadTestReport.getTriggerMode()) || StringUtils.equals(NoticeConstants.SCHEDULE, loadTestReport.getTriggerMode())) { + if (StringUtils.equals(NoticeConstants.Mode.API, loadTestReport.getTriggerMode()) || StringUtils.equals(NoticeConstants.Mode.SCHEDULE, loadTestReport.getTriggerMode())) { performanceNoticeTask.registerNoticeTask(loadTestReport); } return engine.getReportId(); diff --git a/backend/src/main/java/io/metersphere/track/service/IssuesService.java b/backend/src/main/java/io/metersphere/track/service/IssuesService.java index fbe799157f..c2aefecbf9 100644 --- a/backend/src/main/java/io/metersphere/track/service/IssuesService.java +++ b/backend/src/main/java/io/metersphere/track/service/IssuesService.java @@ -8,15 +8,11 @@ import io.metersphere.base.mapper.IssuesMapper; import io.metersphere.commons.constants.IssuesManagePlatform; import io.metersphere.commons.constants.NoticeConstants; import io.metersphere.commons.user.SessionUser; -import io.metersphere.commons.utils.LogUtil; import io.metersphere.commons.utils.SessionUtils; import io.metersphere.controller.request.IntegrationRequest; -import io.metersphere.notice.domain.MessageDetail; -import io.metersphere.notice.domain.MessageSettingDetail; -import io.metersphere.notice.service.DingTaskService; -import io.metersphere.notice.service.MailService; -import io.metersphere.notice.service.NoticeService; -import io.metersphere.notice.service.WxChatTaskService; +import io.metersphere.i18n.Translator; +import io.metersphere.notice.sender.NoticeModel; +import io.metersphere.notice.service.NoticeSendService; import io.metersphere.service.IntegrationService; import io.metersphere.service.ProjectService; import io.metersphere.track.issue.*; @@ -27,7 +23,9 @@ import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; @Service @Transactional(rollbackFor = Exception.class) @@ -42,13 +40,7 @@ public class IssuesService { @Resource private IssuesMapper issuesMapper; @Resource - MailService mailService; - @Resource - DingTaskService dingTaskService; - @Resource - WxChatTaskService wxChatTaskService; - @Resource - NoticeService noticeService; + private NoticeSendService noticeSendService; public void testAuth(String platform) { AbstractIssuePlatform abstractPlatform = IssueFactory.createPlatform(platform, new IssuesRequest()); @@ -98,27 +90,18 @@ public class IssuesService { }); List userIds = new ArrayList<>(); userIds.add(orgId); - try { - String context = getIssuesContext(user, issuesRequest, NoticeConstants.CREATE); - MessageSettingDetail messageSettingDetail = noticeService.searchMessage(); - List taskList = messageSettingDetail.getDefectTask(); - taskList.forEach(r -> { - switch (r.getType()) { - case NoticeConstants.NAIL_ROBOT: - dingTaskService.sendNailRobot(r, userIds, context, NoticeConstants.CREATE); - break; - case NoticeConstants.WECHAT_ROBOT: - wxChatTaskService.sendWechatRobot(r, userIds, context, NoticeConstants.CREATE); - break; - case NoticeConstants.EMAIL: - mailService.sendIssuesNotice(r, userIds, issuesRequest, NoticeConstants.CREATE, user); - break; - } - }); - } catch (Exception e) { - LogUtil.error(e.getMessage(), e); - } - + String context = getIssuesContext(user, issuesRequest, NoticeConstants.Event.CREATE); + Map paramMap = new HashMap<>(); + paramMap.put("issuesName", issuesRequest.getTitle()); + paramMap.put("creator", user.getName()); + NoticeModel noticeModel = NoticeModel.builder() + .context(context) + .relatedUsers(userIds) + .subject(Translator.get("task_defect_notification")) + .mailTemplate("IssuesCreate") + .paramMap(paramMap) + .build(); + noticeSendService.send(NoticeConstants.TaskType.DEFECT_TASK, noticeModel); } public List getIssues(String caseId) { @@ -222,7 +205,7 @@ public class IssuesService { private static String getIssuesContext(SessionUser user, IssuesRequest issuesRequest, String type) { String context = ""; - if (StringUtils.equals(NoticeConstants.CREATE, type)) { + if (StringUtils.equals(NoticeConstants.Event.CREATE, type)) { context = "缺陷任务通知:" + user.getName() + "发起了一个缺陷" + "'" + issuesRequest.getTitle() + "'" + "请跟进"; } return context; diff --git a/backend/src/main/java/io/metersphere/track/service/TestCaseCommentService.java b/backend/src/main/java/io/metersphere/track/service/TestCaseCommentService.java index b51e6716c4..1aa688a420 100644 --- a/backend/src/main/java/io/metersphere/track/service/TestCaseCommentService.java +++ b/backend/src/main/java/io/metersphere/track/service/TestCaseCommentService.java @@ -10,15 +10,12 @@ import io.metersphere.base.mapper.UserMapper; import io.metersphere.base.mapper.ext.ExtTestCaseCommentMapper; import io.metersphere.commons.constants.NoticeConstants; import io.metersphere.commons.exception.MSException; -import io.metersphere.commons.utils.LogUtil; import io.metersphere.commons.utils.SessionUtils; +import io.metersphere.dto.BaseSystemConfigDTO; import io.metersphere.i18n.Translator; -import io.metersphere.notice.domain.MessageDetail; -import io.metersphere.notice.domain.MessageSettingDetail; -import io.metersphere.notice.service.DingTaskService; -import io.metersphere.notice.service.MailService; -import io.metersphere.notice.service.NoticeService; -import io.metersphere.notice.service.WxChatTaskService; +import io.metersphere.notice.sender.NoticeModel; +import io.metersphere.notice.service.NoticeSendService; +import io.metersphere.service.SystemParameterService; import io.metersphere.track.dto.TestCaseCommentDTO; import io.metersphere.track.request.testreview.SaveCommentRequest; import org.apache.commons.lang3.StringUtils; @@ -27,10 +24,7 @@ import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.UUID; +import java.util.*; @Service @Transactional(rollbackFor = Exception.class) @@ -39,19 +33,15 @@ public class TestCaseCommentService { @Resource private TestCaseCommentMapper testCaseCommentMapper; @Resource - private MailService mailService; - @Resource private TestCaseMapper testCaseMapper; @Resource - private DingTaskService dingTaskService; - @Resource - private WxChatTaskService wxChatTaskService; - @Resource - private NoticeService noticeService; - @Resource private ExtTestCaseCommentMapper extTestCaseCommentMapper; @Resource private UserMapper userMapper; + @Resource + private NoticeSendService noticeSendService; + @Resource + private SystemParameterService systemParameterService; public void saveComment(SaveCommentRequest request) { TestCaseComment testCaseComment = new TestCaseComment(); @@ -64,29 +54,27 @@ public class TestCaseCommentService { testCaseCommentMapper.insert(testCaseComment); TestCaseWithBLOBs testCaseWithBLOBs; testCaseWithBLOBs = testCaseMapper.selectByPrimaryKey(request.getCaseId()); + + // 发送通知 + User user = userMapper.selectByPrimaryKey(testCaseWithBLOBs.getMaintainer()); + BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo(); List userIds = new ArrayList<>(); userIds.add(testCaseWithBLOBs.getMaintainer());//用例维护人 - try { - String context = getReviewContext(testCaseComment, testCaseWithBLOBs); - MessageSettingDetail messageSettingDetail = noticeService.searchMessage(); - List taskList = messageSettingDetail.getReviewTask(); - taskList.forEach(r -> { - switch (r.getType()) { - case NoticeConstants.NAIL_ROBOT: - dingTaskService.sendNailRobot(r, userIds, context, NoticeConstants.COMMENT); - break; - case NoticeConstants.WECHAT_ROBOT: - wxChatTaskService.sendWechatRobot(r, userIds, context, NoticeConstants.COMMENT); - break; - case NoticeConstants.EMAIL: - mailService.sendCommentNotice(r, userIds, request, testCaseWithBLOBs, NoticeConstants.COMMENT); - break; - } - }); - } catch (Exception e) { - LogUtil.error(e.getMessage(), e); - } - + String context = getReviewContext(testCaseComment, testCaseWithBLOBs); + Map paramMap = new HashMap<>(); + paramMap.put("maintainer", user.getName()); + paramMap.put("testCaseName", testCaseWithBLOBs.getName()); + paramMap.put("description", request.getDescription()); + paramMap.put("url", baseSystemConfigDTO.getUrl()); + paramMap.put("id", request.getReviewId()); + NoticeModel noticeModel = NoticeModel.builder() + .context(context) + .relatedUsers(userIds) + .subject(Translator.get("test_review_task_notice")) + .mailTemplate("ReviewComments") + .paramMap(paramMap) + .build(); + noticeSendService.send(NoticeConstants.TaskType.REVIEW_TASK, noticeModel); } public List getCaseComments(String caseId) { diff --git a/backend/src/main/java/io/metersphere/track/service/TestCaseReviewService.java b/backend/src/main/java/io/metersphere/track/service/TestCaseReviewService.java index 617295d1f9..a3ab852fa1 100644 --- a/backend/src/main/java/io/metersphere/track/service/TestCaseReviewService.java +++ b/backend/src/main/java/io/metersphere/track/service/TestCaseReviewService.java @@ -16,12 +16,11 @@ import io.metersphere.commons.utils.LogUtil; import io.metersphere.commons.utils.ServiceUtils; import io.metersphere.commons.utils.SessionUtils; import io.metersphere.controller.request.member.QueryMemberRequest; -import io.metersphere.notice.domain.MessageDetail; -import io.metersphere.notice.domain.MessageSettingDetail; -import io.metersphere.notice.service.DingTaskService; -import io.metersphere.notice.service.MailService; -import io.metersphere.notice.service.NoticeService; -import io.metersphere.notice.service.WxChatTaskService; +import io.metersphere.dto.BaseSystemConfigDTO; +import io.metersphere.i18n.Translator; +import io.metersphere.notice.sender.NoticeModel; +import io.metersphere.notice.service.NoticeSendService; +import io.metersphere.service.SystemParameterService; import io.metersphere.service.UserService; import io.metersphere.track.dto.TestCaseReviewDTO; import io.metersphere.track.dto.TestReviewCaseDTO; @@ -75,14 +74,9 @@ public class TestCaseReviewService { @Resource ExtTestCaseMapper extTestCaseMapper; @Resource - NoticeService noticeService; + private NoticeSendService noticeSendService; @Resource - MailService mailService; - @Resource - DingTaskService dingTaskService; - @Resource - WxChatTaskService wxChatTaskService; - + private SystemParameterService systemParameterService; public void saveTestCaseReview(SaveTestCaseReviewRequest reviewRequest) { checkCaseReviewExist(reviewRequest); @@ -109,27 +103,54 @@ public class TestCaseReviewService { reviewRequest.setCreator(SessionUtils.getUser().getId());//创建人 reviewRequest.setStatus(TestCaseReviewStatus.Prepare.name()); testCaseReviewMapper.insert(reviewRequest); - try { - String context = getReviewContext(reviewRequest, NoticeConstants.CREATE); - MessageSettingDetail messageSettingDetail = noticeService.searchMessage(); - List taskList = messageSettingDetail.getReviewTask(); - taskList.forEach(r -> { - switch (r.getType()) { - case NoticeConstants.NAIL_ROBOT: - dingTaskService.sendNailRobot(r, userIds, context, NoticeConstants.CREATE); - break; - case NoticeConstants.WECHAT_ROBOT: - wxChatTaskService.sendWechatRobot(r, userIds, context, NoticeConstants.CREATE); - break; - case NoticeConstants.EMAIL: - mailService.sendReviewerNotice(r, userIds, reviewRequest, NoticeConstants.CREATE); - break; - } - }); - } catch (Exception e) { - LogUtil.error(e.getMessage(), e); + // 发送通知 + String context = getReviewContext(reviewRequest, NoticeConstants.Event.CREATE); + Map paramMap = new HashMap<>(getReviewParamMap(reviewRequest)); + NoticeModel noticeModel = NoticeModel.builder() + .context(context) + .relatedUsers(userIds) + .subject(Translator.get("test_review_task_notice")) + .mailTemplate("ReviewInitiate") + .paramMap(paramMap) + .build(); + noticeSendService.send(NoticeConstants.TaskType.REVIEW_TASK, noticeModel); + } + + //评审内容 + private Map getReviewParamMap(SaveTestCaseReviewRequest reviewRequest) { + Long startTime = reviewRequest.getCreateTime(); + Long endTime = reviewRequest.getEndTime(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String start = null; + String sTime = String.valueOf(startTime); + String eTime = String.valueOf(endTime); + if (!sTime.equals("null")) { + start = sdf.format(new Date(Long.parseLong(sTime))); + } + String end = null; + if (!eTime.equals("null")) { + end = sdf.format(new Date(Long.parseLong(eTime))); } + Map paramMap = new HashMap<>(); + BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo(); + paramMap.put("url", baseSystemConfigDTO.getUrl()); + User user = userMapper.selectByPrimaryKey(reviewRequest.getCreator()); + paramMap.put("creator", user.getName()); + paramMap.put("reviewName", reviewRequest.getName()); + paramMap.put("start", start); + paramMap.put("end", end); + paramMap.put("id", reviewRequest.getId()); + String status = ""; + if (StringUtils.equals(TestPlanStatus.Underway.name(), reviewRequest.getStatus())) { + status = "进行中"; + } else if (StringUtils.equals(TestPlanStatus.Prepare.name(), reviewRequest.getStatus())) { + status = "未开始"; + } else if (StringUtils.equals(TestPlanStatus.Completed.name(), reviewRequest.getStatus())) { + status = "已完成"; + } + paramMap.put("status", status); + return paramMap; } public List listCaseReview(QueryCaseReviewRequest request) { @@ -185,29 +206,18 @@ public class TestCaseReviewService { testCaseReview.setUpdateTime(System.currentTimeMillis()); checkCaseReviewExist(testCaseReview); testCaseReviewMapper.updateByPrimaryKeySelective(testCaseReview); - List userIds = new ArrayList<>(); - userIds.addAll(testCaseReview.getUserIds()); - try { - String context = getReviewContext(testCaseReview, NoticeConstants.UPDATE); - MessageSettingDetail messageSettingDetail = noticeService.searchMessage(); - List taskList = messageSettingDetail.getReviewTask(); - taskList.forEach(r -> { - switch (r.getType()) { - case NoticeConstants.NAIL_ROBOT: - dingTaskService.sendNailRobot(r, userIds, context, NoticeConstants.UPDATE); - break; - case NoticeConstants.WECHAT_ROBOT: - wxChatTaskService.sendWechatRobot(r, userIds, context, NoticeConstants.UPDATE); - break; - case NoticeConstants.EMAIL: - mailService.sendEndNotice(r, userIds, testCaseReview, NoticeConstants.UPDATE); - break; - } - }); - } catch (Exception e) { - LogUtil.error(e.getMessage(), e); - } - + // 发送通知 + List userIds = new ArrayList<>(testCaseReview.getUserIds()); + String context = getReviewContext(testCaseReview, NoticeConstants.Event.UPDATE); + Map paramMap = new HashMap<>(getReviewParamMap(testCaseReview)); + NoticeModel noticeModel = NoticeModel.builder() + .context(context) + .relatedUsers(userIds) + .subject(Translator.get("test_review_task_notice")) + .mailTemplate("ReviewEnd") + .paramMap(paramMap) + .build(); + noticeSendService.send(NoticeConstants.TaskType.REVIEW_TASK, noticeModel); } private void editCaseReviewer(SaveTestCaseReviewRequest testCaseReview) { @@ -294,31 +304,25 @@ public class TestCaseReviewService { deleteCaseReviewUsers(reviewId); deleteCaseReviewTestCase(reviewId); testCaseReviewMapper.deleteByPrimaryKey(reviewId); - List userIds = new ArrayList<>(); - userIds.add(SessionUtils.getUser().getId()); - SaveTestCaseReviewRequest testCaseReviewRequest = new SaveTestCaseReviewRequest(); + // 发送通知 try { + List userIds = new ArrayList<>(); + userIds.add(SessionUtils.getUser().getId()); + SaveTestCaseReviewRequest testCaseReviewRequest = new SaveTestCaseReviewRequest(); BeanUtils.copyProperties(testCaseReviewRequest, testCaseReview); - String context = getReviewContext(testCaseReviewRequest, NoticeConstants.DELETE); - MessageSettingDetail messageSettingDetail = noticeService.searchMessage(); - List taskList = messageSettingDetail.getReviewTask(); - taskList.forEach(r -> { - switch (r.getType()) { - case NoticeConstants.NAIL_ROBOT: - dingTaskService.sendNailRobot(r, userIds, context, NoticeConstants.DELETE); - break; - case NoticeConstants.WECHAT_ROBOT: - wxChatTaskService.sendWechatRobot(r, userIds, context, NoticeConstants.DELETE); - break; - case NoticeConstants.EMAIL: - mailService.sendDeleteNotice(r, userIds, testCaseReviewRequest, NoticeConstants.DELETE); - break; - } - }); + String context = getReviewContext(testCaseReviewRequest, NoticeConstants.Event.DELETE); + Map paramMap = new HashMap<>(getReviewParamMap(testCaseReviewRequest)); + NoticeModel noticeModel = NoticeModel.builder() + .context(context) + .relatedUsers(userIds) + .subject(Translator.get("test_review_task_notice")) + .mailTemplate("ReviewDelete") + .paramMap(paramMap) + .build(); + noticeSendService.send(NoticeConstants.TaskType.REVIEW_TASK, noticeModel); } catch (Exception e) { - LogUtil.error(e.getMessage(), e); + LogUtil.error(e); } - } private void deleteCaseReviewProject(String reviewId) { @@ -446,25 +450,18 @@ public class TestCaseReviewService { List userIds = new ArrayList<>(); userIds.add(_testCaseReview.getCreator()); if (StringUtils.equals(TestCaseReviewStatus.Completed.name(), _testCaseReview.getStatus())) { - try { BeanUtils.copyProperties(testCaseReviewRequest, _testCaseReview); - String context = getReviewContext(testCaseReviewRequest, NoticeConstants.UPDATE); - MessageSettingDetail messageSettingDetail = noticeService.searchMessage(); - List taskList = messageSettingDetail.getReviewTask(); - taskList.forEach(r -> { - switch (r.getType()) { - case NoticeConstants.NAIL_ROBOT: - dingTaskService.sendNailRobot(r, userIds, context, NoticeConstants.UPDATE); - break; - case NoticeConstants.WECHAT_ROBOT: - wxChatTaskService.sendWechatRobot(r, userIds, context, NoticeConstants.UPDATE); - break; - case NoticeConstants.EMAIL: - mailService.sendEndNotice(r, userIds, testCaseReviewRequest, NoticeConstants.UPDATE); - break; - } - }); + String context = getReviewContext(testCaseReviewRequest, NoticeConstants.Event.UPDATE); + Map paramMap = new HashMap<>(getReviewParamMap(testCaseReviewRequest)); + NoticeModel noticeModel = NoticeModel.builder() + .context(context) + .relatedUsers(userIds) + .subject(Translator.get("test_review_task_notice")) + .mailTemplate("ReviewEnd") + .paramMap(paramMap) + .build(); + noticeSendService.send(NoticeConstants.TaskType.REVIEW_TASK, noticeModel); } catch (Exception e) { LogUtil.error(e.getMessage(), e); } @@ -580,9 +577,9 @@ public class TestCaseReviewService { start = "未设置"; } String context = ""; - if (StringUtils.equals(NoticeConstants.CREATE, type)) { + if (StringUtils.equals(NoticeConstants.Event.CREATE, type)) { context = "测试评审任务通知:" + user.getName() + "发起的" + "'" + reviewRequest.getName() + "'" + "待开始,计划开始时间是" + start + "计划结束时间为" + end + "请跟进"; - } else if (StringUtils.equals(NoticeConstants.UPDATE, type)) { + } else if (StringUtils.equals(NoticeConstants.Event.UPDATE, type)) { String status = ""; if (StringUtils.equals(TestPlanStatus.Underway.name(), reviewRequest.getStatus())) { status = "进行中"; @@ -592,7 +589,7 @@ public class TestCaseReviewService { status = "已完成"; } context = "测试评审任务通知:" + user.getName() + "发起的" + "'" + reviewRequest.getName() + "'" + "计划开始时间是" + start + "计划结束时间为" + end + status; - } else if (StringUtils.equals(NoticeConstants.DELETE, type)) { + } else if (StringUtils.equals(NoticeConstants.Event.DELETE, type)) { context = "测试评审任务通知:" + user.getName() + "发起的" + "'" + reviewRequest.getName() + "'" + "计划开始时间是" + start + "计划结束时间为" + end + "已删除"; } diff --git a/backend/src/main/java/io/metersphere/track/service/TestPlanService.java b/backend/src/main/java/io/metersphere/track/service/TestPlanService.java index 35827a7299..850e9fd3e8 100644 --- a/backend/src/main/java/io/metersphere/track/service/TestPlanService.java +++ b/backend/src/main/java/io/metersphere/track/service/TestPlanService.java @@ -15,13 +15,11 @@ import io.metersphere.commons.constants.TestPlanTestCaseStatus; import io.metersphere.commons.exception.MSException; import io.metersphere.commons.user.SessionUser; import io.metersphere.commons.utils.*; +import io.metersphere.dto.BaseSystemConfigDTO; import io.metersphere.i18n.Translator; -import io.metersphere.notice.domain.MessageDetail; -import io.metersphere.notice.domain.MessageSettingDetail; -import io.metersphere.notice.service.DingTaskService; -import io.metersphere.notice.service.MailService; -import io.metersphere.notice.service.NoticeService; -import io.metersphere.notice.service.WxChatTaskService; +import io.metersphere.notice.sender.NoticeModel; +import io.metersphere.notice.service.NoticeSendService; +import io.metersphere.service.SystemParameterService; import io.metersphere.track.Factory.ReportComponentFactory; import io.metersphere.track.domain.ReportComponent; import io.metersphere.track.dto.TestCaseReportMetricDTO; @@ -51,32 +49,23 @@ import java.util.stream.Collectors; public class TestPlanService { @Resource TestPlanMapper testPlanMapper; - @Resource ExtTestPlanMapper extTestPlanMapper; - @Resource ExtTestPlanTestCaseMapper extTestPlanTestCaseMapper; - @Resource TestCaseMapper testCaseMapper; - @Resource TestPlanTestCaseMapper testPlanTestCaseMapper; - @Resource SqlSessionFactory sqlSessionFactory; - @Lazy @Resource TestPlanTestCaseService testPlanTestCaseService; - @Resource ExtProjectMapper extProjectMapper; - @Resource TestCaseReportMapper testCaseReportMapper; - @Resource TestPlanProjectMapper testPlanProjectMapper; @Resource @@ -86,15 +75,11 @@ public class TestPlanService { @Resource ExtTestCaseMapper extTestCaseMapper; @Resource - NoticeService noticeService; - @Resource - MailService mailService; - @Resource - DingTaskService dingTaskService; - @Resource - WxChatTaskService wxChatTaskService; - @Resource UserMapper userMapper; + @Resource + private NoticeSendService noticeSendService; + @Resource + private SystemParameterService systemParameterService; public synchronized void addTestPlan(AddTestPlanRequest testPlan) { if (getTestPlanByName(testPlan.getName()).size() > 0) { @@ -117,28 +102,21 @@ public class TestPlanService { testPlan.setUpdateTime(System.currentTimeMillis()); testPlan.setCreator(SessionUtils.getUser().getId()); testPlanMapper.insert(testPlan); + List userIds = new ArrayList<>(); userIds.add(testPlan.getPrincipal()); - try { - String context = getTestPlanContext(testPlan, NoticeConstants.CREATE); - MessageSettingDetail messageSettingDetail = noticeService.searchMessage(); - List taskList = messageSettingDetail.getTestCasePlanTask(); - taskList.forEach(r -> { - switch (r.getType()) { - case NoticeConstants.NAIL_ROBOT: - dingTaskService.sendNailRobot(r, userIds, context, NoticeConstants.CREATE); - break; - case NoticeConstants.WECHAT_ROBOT: - wxChatTaskService.sendWechatRobot(r, userIds, context, NoticeConstants.CREATE); - break; - case NoticeConstants.EMAIL: - mailService.sendTestPlanStartNotice(r, userIds, testPlan, NoticeConstants.CREATE); - break; - } - }); - } catch (Exception e) { - LogUtil.error(e.getMessage(), e); - } + String context = getTestPlanContext(testPlan, NoticeConstants.Event.CREATE); + User user = userMapper.selectByPrimaryKey(testPlan.getCreator()); + Map paramMap = getTestPlanParamMap(testPlan); + paramMap.put("creator", user.getName()); + NoticeModel noticeModel = NoticeModel.builder() + .context(context) + .relatedUsers(userIds) + .subject(Translator.get("test_plan_notification")) + .mailTemplate("TestPlanStart") + .paramMap(paramMap) + .build(); + noticeSendService.send(NoticeConstants.TaskType.TEST_PLAN_TASK, noticeModel); } public List getTestPlanByName(String name) { @@ -169,27 +147,19 @@ public class TestPlanService { AddTestPlanRequest testPlans = new AddTestPlanRequest(); int i = testPlanMapper.updateByPrimaryKeySelective(testPlan); if (!StringUtils.isBlank(testPlan.getStatus())) { - try { - BeanUtils.copyBean(testPlans, getTestPlan(testPlan.getId())); - String context = getTestPlanContext(testPlans, NoticeConstants.UPDATE); - MessageSettingDetail messageSettingDetail = noticeService.searchMessage(); - List taskList = messageSettingDetail.getTestCasePlanTask(); - taskList.forEach(r -> { - switch (r.getType()) { - case NoticeConstants.NAIL_ROBOT: - dingTaskService.sendNailRobot(r, userIds, context, NoticeConstants.UPDATE); - break; - case NoticeConstants.WECHAT_ROBOT: - wxChatTaskService.sendWechatRobot(r, userIds, context, NoticeConstants.UPDATE); - break; - case NoticeConstants.EMAIL: - mailService.sendTestPlanEndNotice(r, userIds, testPlans, NoticeConstants.UPDATE); - break; - } - }); - } catch (Exception e) { - LogUtil.error(e.getMessage(), e); - } + BeanUtils.copyBean(testPlans, getTestPlan(testPlan.getId())); + String context = getTestPlanContext(testPlans, NoticeConstants.Event.UPDATE); + User user = userMapper.selectByPrimaryKey(testPlan.getCreator()); + Map paramMap = getTestPlanParamMap(testPlan); + paramMap.put("creator", user.getName()); + NoticeModel noticeModel = NoticeModel.builder() + .context(context) + .relatedUsers(userIds) + .subject(Translator.get("test_plan_notification")) + .mailTemplate("TestPlanEnd") + .paramMap(paramMap) + .build(); + noticeSendService.send(NoticeConstants.TaskType.TEST_PLAN_TASK, noticeModel); } return i; } @@ -232,6 +202,44 @@ public class TestPlanService { } } + //计划内容 + private Map getTestPlanParamMap(TestPlan testPlan) { + Long startTime = testPlan.getPlannedStartTime(); + Long endTime = testPlan.getPlannedEndTime(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String start = null; + String sTime = String.valueOf(startTime); + String eTime = String.valueOf(endTime); + if (!sTime.equals("null")) { + start = sdf.format(new Date(Long.parseLong(sTime))); + } + String end = null; + if (!eTime.equals("null")) { + end = sdf.format(new Date(Long.parseLong(eTime))); + } + + Map context = new HashMap<>(); + BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo(); + context.put("url", baseSystemConfigDTO.getUrl()); + context.put("testPlanName", testPlan.getName()); + context.put("start", start); + context.put("end", end); + context.put("id", testPlan.getId()); + String status = ""; + if (StringUtils.equals(TestPlanStatus.Underway.name(), testPlan.getStatus())) { + status = "进行中"; + } else if (StringUtils.equals(TestPlanStatus.Prepare.name(), testPlan.getStatus())) { + status = "未开始"; + } else if (StringUtils.equals(TestPlanStatus.Completed.name(), testPlan.getStatus())) { + status = "已完成"; + } + context.put("status", status); + User user = userMapper.selectByPrimaryKey(testPlan.getCreator()); + context.put("creator", user.getName()); + return context; + } + + private void checkTestPlanExist(TestPlan testPlan) { if (testPlan.getName() != null) { TestPlanExample example = new TestPlanExample(); @@ -255,22 +263,18 @@ public class TestPlanService { userIds.add(testPlan.getCreator()); try { BeanUtils.copyBean(testPlans, testPlan); - String context = getTestPlanContext(testPlans, NoticeConstants.DELETE); - MessageSettingDetail messageSettingDetail = noticeService.searchMessage(); - List taskList = messageSettingDetail.getTestCasePlanTask(); - taskList.forEach(r -> { - switch (r.getType()) { - case NoticeConstants.NAIL_ROBOT: - dingTaskService.sendNailRobot(r, userIds, context, NoticeConstants.DELETE); - break; - case NoticeConstants.WECHAT_ROBOT: - wxChatTaskService.sendWechatRobot(r, userIds, context, NoticeConstants.DELETE); - break; - case NoticeConstants.EMAIL: - mailService.sendTestPlanDeleteNotice(r, userIds, testPlans, NoticeConstants.DELETE); - break; - } - }); + String context = getTestPlanContext(testPlans, NoticeConstants.Event.DELETE); + User user = userMapper.selectByPrimaryKey(testPlan.getCreator()); + Map paramMap = getTestPlanParamMap(testPlan); + paramMap.put("creator", user.getName()); + NoticeModel noticeModel = NoticeModel.builder() + .context(context) + .relatedUsers(userIds) + .subject(Translator.get("test_plan_notification")) + .mailTemplate("TestPlanDelete") + .paramMap(paramMap) + .build(); + noticeSendService.send(NoticeConstants.TaskType.TEST_PLAN_TASK, noticeModel); } catch (Exception e) { LogUtil.error(e.getMessage(), e); } @@ -496,22 +500,18 @@ public class TestPlanService { if (StringUtils.equals(TestPlanStatus.Completed.name(), testPlans.getStatus())) { try { BeanUtils.copyBean(_testPlans, testPlans); - String context = getTestPlanContext(_testPlans, NoticeConstants.UPDATE); - MessageSettingDetail messageSettingDetail = noticeService.searchMessage(); - List taskList = messageSettingDetail.getTestCasePlanTask(); - taskList.forEach(r -> { - switch (r.getType()) { - case NoticeConstants.NAIL_ROBOT: - dingTaskService.sendNailRobot(r, userIds, context, NoticeConstants.UPDATE); - break; - case NoticeConstants.WECHAT_ROBOT: - wxChatTaskService.sendWechatRobot(r, userIds, context, NoticeConstants.UPDATE); - break; - case NoticeConstants.EMAIL: - mailService.sendTestPlanEndNotice(r, userIds, _testPlans, NoticeConstants.UPDATE); - break; - } - }); + String context = getTestPlanContext(_testPlans, NoticeConstants.Event.UPDATE); + User user = userMapper.selectByPrimaryKey(testPlan.getCreator()); + Map paramMap = getTestPlanParamMap(testPlan); + paramMap.put("creator", user.getName()); + NoticeModel noticeModel = NoticeModel.builder() + .context(context) + .relatedUsers(userIds) + .subject(Translator.get("test_plan_notification")) + .mailTemplate("TestPlanEnd") + .paramMap(paramMap) + .build(); + noticeSendService.send(NoticeConstants.TaskType.TEST_PLAN_TASK, noticeModel); } catch (Exception e) { LogUtil.error(e.getMessage(), e); } @@ -558,9 +558,9 @@ public class TestPlanService { end = "未设置"; } String context = ""; - if (StringUtils.equals(NoticeConstants.CREATE, type)) { + if (StringUtils.equals(NoticeConstants.Event.CREATE, type)) { context = "测试计划任务通知:" + user.getName() + "创建的" + "'" + testPlan.getName() + "'" + "待开始,计划开始时间是:" + "'" + start + "'" + ";" + "计划结束时间是:" + "'" + end + "'" + " " + "请跟进"; - } else if (StringUtils.equals(NoticeConstants.UPDATE, type)) { + } else if (StringUtils.equals(NoticeConstants.Event.UPDATE, type)) { String status = ""; if (StringUtils.equals(TestPlanStatus.Underway.name(), testPlan.getStatus())) { status = "进行中"; @@ -570,7 +570,7 @@ public class TestPlanService { status = "已完成"; } context = "测试计划任务通知:" + user.getName() + "创建的" + "'" + testPlan.getName() + "'" + "计划开始时间是:" + "'" + start + "'" + ";" + "计划结束时间是:" + "'" + end + "'" + " " + status; - } else if (StringUtils.equals(NoticeConstants.DELETE, type)) { + } else if (StringUtils.equals(NoticeConstants.Event.DELETE, type)) { context = "测试计划任务通知:" + user.getName() + "创建的" + "'" + testPlan.getName() + "'" + "计划开始时间是:" + "'" + start + "'" + ";" + "计划结束时间是:" + "'" + end + "'" + " " + "已删除"; } return context; diff --git a/frontend/src/business/components/settings/organization/components/DefectTaskNotification.vue b/frontend/src/business/components/settings/organization/components/DefectTaskNotification.vue index f3d86d02c5..27f3aa6c24 100644 --- a/frontend/src/business/components/settings/organization/components/DefectTaskNotification.vue +++ b/frontend/src/business/components/settings/organization/components/DefectTaskNotification.vue @@ -3,7 +3,7 @@

{{ $t('organization.message.defect_task_notification') }}

- + {{ $t('organization.message.create_new_notification') }}
@@ -14,13 +14,12 @@ :data="form.defectTask" class="tb-edit" border - size="mini" :cell-style="rowClass" :header-cell-style="headClass" >