feat: Swagger定时同步增加任务通知

This commit is contained in:
wenyann 2021-08-03 17:08:31 +08:00 committed by 刘瑞斌
parent 603268cd0c
commit dd59a9bc13
13 changed files with 463 additions and 9 deletions

View File

@ -16,6 +16,7 @@ public class ApiTestImportRequest {
private Boolean useEnvironment;
private String swaggerUrl;
private String fileName;
private String resourceId;
//导入策略
private String modeId;
private String userId;

View File

@ -38,11 +38,14 @@ import io.metersphere.log.vo.DetailColumn;
import io.metersphere.log.vo.OperatingLogDetails;
import io.metersphere.log.vo.StatusReference;
import io.metersphere.log.vo.api.DefinitionReference;
import io.metersphere.notice.sender.NoticeModel;
import io.metersphere.notice.service.NoticeSendService;
import io.metersphere.service.FileService;
import io.metersphere.service.ScheduleService;
import io.metersphere.service.SystemParameterService;
import io.metersphere.track.request.testcase.ApiCaseRelevanceRequest;
import io.metersphere.track.request.testcase.QueryTestPlanRequest;
import io.metersphere.track.request.testreview.SaveTestCaseReviewRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.ExecutorType;
@ -109,6 +112,8 @@ public class ApiDefinitionService {
private SystemParameterService systemParameterService;
@Resource
private TestPlanMapper testPlanMapper;
@Resource
private NoticeSendService noticeSendService;
private static Cache cache = Cache.newHardMemoryCache(0, 3600 * 24);
@ -473,6 +478,7 @@ public class ApiDefinitionService {
} else {
_importCreate(sameRequest, batchMapper, apiDefinition, apiTestCaseMapper, apiTestImportRequest, cases);
}
return apiDefinition;
}
@ -766,6 +772,7 @@ public class ApiDefinitionService {
}
public ApiDefinitionImport apiTestImport(MultipartFile file, ApiTestImportRequest request) {
ApiImportParser apiImportParser = ApiDefinitionImportParserFactory.getApiImportParser(request.getPlatform());
ApiDefinitionImport apiImport = null;
try {
@ -773,6 +780,22 @@ public class ApiDefinitionService {
} catch (Exception e) {
LogUtil.error(e.getMessage(), e);
MSException.throwException(Translator.get("parse_data_error"));
// 发送通知
if (StringUtils.equals(request.getType(), "schedule")) {
String scheduleId = scheduleService.getScheduleInfo(request.getResourceId());
String context = request.getSwaggerUrl() + "导入失败";
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("url", request.getSwaggerUrl());
NoticeModel noticeModel = NoticeModel.builder()
.context(context)
.testId(scheduleId)
.subject(Translator.get("swagger_url_scheduled_import_notification"))
.failedMailTemplate("SwaggerImportFaild")
.paramMap(paramMap)
.event(NoticeConstants.Event.IMPORT)
.build();
noticeSendService.send(NoticeConstants.TaskType.SWAGGER_TASK, noticeModel);
}
}
importApi(request, apiImport);
if (CollectionUtils.isNotEmpty(apiImport.getData())) {
@ -781,6 +804,22 @@ public class ApiDefinitionService {
List<String> ids = apiImport.getData().stream().map(ApiDefinitionWithBLOBs::getId).collect(Collectors.toList());
request.setId(JSON.toJSONString(ids));
}
// 发送通知
if (StringUtils.equals(request.getType(), "schedule")) {
String scheduleId = scheduleService.getScheduleInfo(request.getResourceId());
String context = request.getSwaggerUrl() + "导入成功";
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("url", request.getSwaggerUrl());
NoticeModel noticeModel = NoticeModel.builder()
.context(context)
.testId(scheduleId)
.subject(Translator.get("swagger_url_scheduled_import_notification"))
.successMailTemplate("SwaggerImport")
.paramMap(paramMap)
.event(NoticeConstants.Event.EXECUTE_SUCCESSFUL)
.build();
noticeSendService.send(NoticeConstants.Mode.SCHEDULE, noticeModel);
}
return apiImport;
}

View File

@ -7,6 +7,7 @@ public interface NoticeConstants {
String TEST_PLAN_TASK = "TEST_PLAN_TASK";
String REVIEW_TASK = "REVIEW_TASK";
String DEFECT_TASK = "DEFECT_TASK";
String SWAGGER_TASK = "SWAGGER_TASK";
}
interface Mode {
@ -28,6 +29,7 @@ public interface NoticeConstants {
String UPDATE = "UPDATE";
String DELETE = "DELETE";
String COMMENT = "COMMENT";
String IMPORT = "IMPORT";
}
interface RelatedUser {

View File

@ -2,6 +2,7 @@ package io.metersphere.job.sechedule;
import io.metersphere.api.dto.ApiTestImportRequest;
import io.metersphere.api.service.ApiDefinitionService;
import io.metersphere.base.domain.Schedule;
import io.metersphere.base.domain.SwaggerUrlProject;
import io.metersphere.commons.constants.ScheduleGroup;
import io.metersphere.commons.utils.CommonBeanFactory;
@ -30,6 +31,7 @@ public class SwaggerUrlImportJob extends MsScheduleJob {
request.setUserId(jobDataMap.getString("userId"));
request.setType("schedule");
request.setUserId(jobDataMap.getString("userId"));
request.setResourceId(resourceId);
apiDefinitionService.apiTestImport(null, request);
}

View File

@ -289,10 +289,22 @@ public class ScheduleService {
}
this.editSchedule(request);
this.addOrUpdateCronJob(request,jobKey ,triggerKey , clazz);
this.addOrUpdateCronJob(request, jobKey, triggerKey, clazz);
}
public Object getCurrentlyExecutingJobs() {
return scheduleManager.getCurrentlyExecutingJobs();
}
public String getScheduleInfo(String id) {
ScheduleExample schedule = new ScheduleExample();
schedule.createCriteria().andResourceIdEqualTo(id);
List<Schedule> list = scheduleMapper.selectByExample(schedule);
if (list.size() > 0) {
return list.get(0).getKey();
} else {
return "";
}
}
}

View File

@ -196,6 +196,7 @@ import_xmind_count_error=The number of use cases imported into the mind map cann
import_xmind_not_found=Test case not found
license_valid_license_error=Authorization authentication failed
test_review_task_notice=Test review task notice
swagger_url_scheduled_import_notification=SwaggerUrl Scheduled import notification
test_track.length_less_than=The title is too long, the length must be less than
# check owner
check_owner_project=The current user does not have permission to operate this project

View File

@ -196,6 +196,7 @@ import_xmind_count_error=思维导图导入用例数量不能超过 500 条
license_valid_license_error=授权认证失败
import_xmind_not_found=未找到测试用例
test_review_task_notice=测试评审任务通知
swagger_url_scheduled_import_notification=swagger_url定时导入通知
test_track.length_less_than=标题过长,字数必须小于
# check owner
check_owner_project=当前用户没有操作此项目的权限

View File

@ -197,6 +197,7 @@ license_valid_license_code=授權碼已經存在
import_xmind_count_error=思維導圖導入用例數量不能超過 500 條
import_xmind_not_found=未找到测试用例
test_review_task_notice=測試評審任務通知
swagger_url_scheduled_import_notification=swagger_url定時導入通知
test_track.length_less_than=標題過長,字數必須小於
# check owner
check_owner_project=當前用戶沒有操作此項目的權限

View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MeterSphere</title>
</head>
<body>
<div>
<p style="text-align: left">
${url}<br>
导入成功!
</p>
</div>
</body>
</html>

View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MeterSphere</title>
</head>
<body>
<div>
<p style="text-align: left">
${url}<br>
导入失败!
</p>
</div>
</body>
</html>

View File

@ -43,11 +43,25 @@
</el-form>
<div style="margin-top: 20px;" class="clearfix">
<el-button v-if="!formData.id" type="primary" style="float: right" size="mini" @click="saveCron">{{$t('commons.add')}}</el-button>
<el-row>
<el-col :span="4">
<el-button type="primary" style="float: right" size="mini" @click="openSchedule">
{{ $t('schedule.task_notification') }}
</el-button>
</el-col>
<el-col :span="20">
<el-button v-if="!formData.id" type="primary" style="float: right" size="mini" @click="saveCron">
{{ $t('commons.add') }}
</el-button>
<div v-else>
<el-button type="primary" style="float: right;margin-left: 10px" size="mini" @click="clear">{{$t('commons.clear')}}</el-button>
<el-button type="primary" style="float: right" size="mini" @click="saveCron">{{$t('commons.update')}}</el-button>
<el-button type="primary" style="float: right;margin-left: 10px" size="mini" @click="clear">
{{ $t('commons.clear') }}
</el-button>
<el-button type="primary" style="float: right" size="mini" @click="saveCron">{{ $t('commons.update') }}
</el-button>
</div>
</el-col>
</el-row>
</div>
</div>
@ -62,6 +76,17 @@
<el-dialog width="60%" :title="$t('schedule.generate_expression')" :visible.sync="showCron" :modal="false">
<crontab @hide="showCron=false" @fill="crontabFill" :expression="formData.value" ref="crontab"/>
</el-dialog>
<el-dialog
:title="$t('schedule.task_notification')"
:visible.sync="dialogVisible"
width="60%"
>
<swagger-task-notification :api-test-id="formData.id" :scheduleReceiverOptions="scheduleReceiverOptions"
ref="schedule-task-notification">
</swagger-task-notification>
</el-dialog>
</el-main>
</template>
@ -72,11 +97,17 @@ import SwaggerTaskList from "@/business/components/api/definition/components/imp
import CrontabResult from "@/business/components/common/cron/CrontabResult";
import Crontab from "@/business/components/common/cron/Crontab";
import {cronValidate} from "@/common/js/cron";
import {getCurrentProjectID, getCurrentUser, getCurrentWorkspaceId} from "@/common/js/utils";
import {getCurrentOrganizationId, getCurrentProjectID, getCurrentUser, getCurrentWorkspaceId} from "@/common/js/utils";
import SelectTree from "@/business/components/common/select-tree/SelectTree";
import ScheduleTaskNotification from "@/business/components/settings/organization/components/ScheduleTaskNotification";
import SwaggerTaskNotification from "@/business/components/api/definition/components/import/SwaggerTaskNotification";
export default {
name: "ApiSchedule",
components: {SelectTree, MsFormDivider,SwaggerTaskList, CrontabResult, Crontab},
components: {
SwaggerTaskNotification,
ScheduleTaskNotification, SelectTree, MsFormDivider, SwaggerTaskList, CrontabResult, Crontab
},
props: {
customValidate: {
type: Function,
@ -116,6 +147,8 @@ export default {
schedule: {
value: "",
},
scheduleReceiverOptions: [],
dialogVisible: false,
showCron: false,
activeName: 'first',
swaggerUrl: String,
@ -153,6 +186,25 @@ export default {
},
methods: {
openSchedule() {
if (this.formData.id !== null && this.formData.id !== undefined) {
this.dialogVisible = true;
this.initUserList();
} else {
this.$warning("请先选择您要添加通知的定时任务");
}
},
initUserList() {
let param = {
name: '',
organizationId: getCurrentOrganizationId()
};
this.result = this.$post('user/org/member/list/all', param, response => {
this.scheduleReceiverOptions = response.data;
});
},
currentUser: () => {
return getCurrentUser();
},

View File

@ -0,0 +1,313 @@
<template>
<div>
<el-row>
<el-col :span="20">
<el-button icon="el-icon-circle-plus-outline" plain size="mini"
@click="handleAddTaskModel">
{{ $t('organization.message.create_new_notification') }}
</el-button>
<el-popover
placement="right-end"
title="示例"
width="600"
trigger="click">
<ms-code-edit :read-only="true" height="400px" :data.sync="title" :modes="modes" :mode="'html'"/>
<el-button icon="el-icon-warning" plain size="mini" slot="reference" style="margin-left: 10px">
{{ $t('organization.message.mail_template_example') }}
</el-button>
</el-popover>
<el-popover
placement="right-end"
title="示例"
width="200"
trigger="click">
<ms-code-edit :read-only="true" height="200px" :data.sync="robotTitle" :modes="modes" :mode="'text'"/>
<el-button icon="el-icon-warning" plain size="mini" slot="reference" style="margin-left: 10px">
{{ $t('organization.message.robot_template') }}
</el-button>
</el-popover>
</el-col>
</el-row>
<el-row>
<el-col :span="24">
<el-table
:data="scheduleTask"
class="tb-edit"
border
:cell-style="rowClass"
:header-cell-style="headClass">
<el-table-column :label="$t('schedule.event')" prop="events" min-width="13%">
<template slot-scope="scope">
<el-select v-model="scope.row.event" size="mini"
:placeholder="$t('organization.message.select_events')"
prop="events" :disabled="!scope.row.isSet">
<el-option
v-for="item in scheduleEventOptions"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
</el-table-column>
<el-table-column :label="$t('schedule.receiver')" prop="userIds" min-width="18%">
<template v-slot:default="{row}">
<el-select v-model="row.userIds" filterable multiple size="mini"
:placeholder="$t('commons.please_select')" style="width: 100%;" :disabled="!row.isSet">
<el-option
v-for="item in scheduleReceiverOptions"
:key="item.id"
:label="item.name"
:value="item.id">
</el-option>
</el-select>
</template>
</el-table-column>
<el-table-column :label="$t('schedule.receiving_mode')" prop="type" min-width="15%">
<template slot-scope="scope">
<el-select v-model="scope.row.type" :placeholder="$t('organization.message.select_receiving_method')"
size="mini"
:disabled="!scope.row.isSet" @change="handleEdit(scope.$index, scope.row)"
>
<el-option
v-for="item in receiveTypeOptions"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
</el-table-column>
<el-table-column label="webhook" min-width="20%" prop="webhook">
<template v-slot:default="scope">
<el-input v-model="scope.row.webhook" placeholder="webhook地址" size="mini"
:disabled="!scope.row.isSet||!scope.row.isReadOnly"></el-input>
</template>
</el-table-column>
<el-table-column :label="$t('commons.operating')" prop="result" min-width="25%">
<template v-slot:default="scope">
<el-button
type="success"
size="mini"
v-if="scope.row.isSet"
v-xpack
@click="handleTemplate(scope.$index,scope.row)"
>{{ $t('organization.message.template') }}
</el-button>
<el-button
type="primary"
size="mini"
v-show="scope.row.isSet"
@click="handleAddTask(scope.$index,scope.row)"
>{{ $t('commons.add') }}
</el-button>
<el-button
size="mini"
v-show="scope.row.isSet"
@click.native.prevent="removeRowTask(scope.$index,scheduleTask)"
>{{ $t('commons.cancel') }}
</el-button>
<el-button
type="primary"
size="mini"
v-show="!scope.row.isSet"
@click="handleEditTask(scope.$index,scope.row)"
>{{ $t('commons.edit') }}
</el-button>
<el-button
type="danger"
icon="el-icon-delete"
size="mini"
v-show="!scope.row.isSet"
@click.native.prevent="deleteRowTask(scope.$index,scope.row)"
></el-button>
</template>
</el-table-column>
</el-table>
</el-col>
</el-row>
<notice-template v-xpack ref="noticeTemplate"/>
</div>
</template>
<script>
import {hasLicense} from "@/common/js/utils";
import MsCodeEdit from "@/business/components/common/components/MsCodeEdit";
const requireComponent = require.context('@/business/components/xpack/', true, /\.vue$/);
const noticeTemplate = requireComponent.keys().length > 0 ? requireComponent("./notice/NoticeTemplate.vue") : {};
export default {
name: "SwaggerTaskNotification",
components: {
MsCodeEdit,
"NoticeTemplate": noticeTemplate.default
},
props: {
apiTestId: String,
scheduleReceiverOptions: Array,
isTesterPermission: {
type: Boolean,
default: true
}
},
data() {
return {
modes: ['text', 'html'],
title: '<!DOCTYPE html>\n' +
'<html lang="en">\n' +
'<head>\n' +
' <meta charset="UTF-8">\n' +
' <title>MeterSphere</title>\n' +
'</head>\n' +
'<body>\n' +
'<div>\n' +
' <div style="margin-left: 100px">\n' +
' swagger:${url}导入成功 ' +
' </div>\n' +
'\n' +
'</div>\n' +
'</body>\n' +
'</html>',
robotTitle:
"swagger:${url}导入成功",
scheduleTask: [{
taskType: "swaggerTask",
event: "",
userIds: [],
type: [],
webhook: "",
isSet: true,
identification: "",
isReadOnly: false,
testId: this.apiTestId,
}],
scheduleEventOptions: [
{value: 'EXECUTE_SUCCESSFUL', label: this.$t('schedule.event_success')},
{value: 'EXECUTE_FAILED', label: this.$t('schedule.event_failed')}
],
receiveTypeOptions: [
{value: 'EMAIL', label: this.$t('organization.message.mail')},
{value: 'NAIL_ROBOT', label: this.$t('organization.message.nail_robot')},
{value: 'WECHAT_ROBOT', label: this.$t('organization.message.enterprise_wechat_robot')},
{value: 'LARK', label: this.$t('organization.message.lark')}
],
};
},
mounted() {
this.initForm();
},
methods: {
initForm() {
this.result = this.$get('/notice/search/message/' + this.apiTestId, response => {
// console.log(response.data);
this.scheduleTask = response.data;
});
},
handleEdit(index, data) {
data.isReadOnly = true;
if (data.type === 'EMAIL') {
data.isReadOnly = !data.isReadOnly;
data.webhook = '';
}
},
handleAddTaskModel() {
let Task = {};
Task.event = [];
Task.userIds = [];
Task.type = '';
Task.webhook = '';
Task.isSet = true;
Task.identification = '';
Task.taskType = 'SWAGGER_URL';
Task.testId = this.testId;
this.scheduleTask.push(Task);
},
handleEditTask(index, data) {
data.isSet = true;
data.testId = this.testId;
if (data.type === 'EMAIL') {
data.isReadOnly = false;
data.webhook = '';
} else {
data.isReadOnly = true;
}
},
handleAddTask(index, data) {
if (data.event && data.userIds.length > 0 && data.type) {
if (data.type === 'NAIL_ROBOT' || data.type === 'WECHAT_ROBOT' || data.type === 'LARK') {
if (!data.webhook) {
this.$warning(this.$t('organization.message.message_webhook'));
} else {
this.addTask(data);
}
} else {
this.addTask(data);
}
} else {
this.$warning(this.$t('organization.message.message'));
}
},
addTask(data) {
console.log(data);
data.testId = this.apiTestId;
this.$success(this.$t('commons.save_success'));
this.result = this.$post("/notice/save/message/task", data, () => {
this.initForm();
this.$success(this.$t('commons.save_success'));
});
},
removeRowTask(index, data) { //
if (!data[index].identification) {
data.splice(index, 1);
} else {
data[index].isSet = false;
}
},
deleteRowTask(index, data) { //
this.result = this.$get("/notice/delete/message/" + data.identification, response => {
this.$success(this.$t('commons.delete_success'));
this.initForm();
});
},
rowClass() {
return "text-align:center";
},
headClass() {
return "text-align:center;background:'#ededed'";
},
handleTemplate(index, row) {
if (hasLicense()) {
this.$refs.noticeTemplate.open(row);
}
}
},
watch: {
testId() {
this.initForm();
}
}
};
</script>
<style scoped>
.el-row {
margin-bottom: 10px;
}
/deep/ .el-select .el-input.is-disabled .el-input__inner {
background-color: #F5F7FA;
border-color: #E4E7ED;
color: #0a0a0a;
cursor: not-allowed;
}
/deep/ .el-input.is-disabled .el-input__inner {
background-color: #F5F7FA;
border-color: #E4E7ED;
color: #0a0a0a;
cursor: not-allowed;
}
</style>