refactor(任务中心): 优化任务中心按照任务类型加载

This commit is contained in:
fit2-zhao 2022-11-01 19:16:17 +08:00 committed by fit2-zhao
parent c75ac75894
commit 45ee9be773
21 changed files with 645 additions and 813 deletions

View File

@ -408,7 +408,7 @@ export default {
MsTestPlanList: () => import("./testplan/TestPlanList"), MsTestPlanList: () => import("./testplan/TestPlanList"),
MsTableOperatorButton: () => import("metersphere-frontend/src/components/MsTableOperatorButton"), MsTableOperatorButton: () => import("metersphere-frontend/src/components/MsTableOperatorButton"),
MsRunMode: () => import("./common/RunMode"), MsRunMode: () => import("./common/RunMode"),
MsTaskCenter: () => import("@/business/history/task/ApiTaskCenter"), MsTaskCenter: () => import("metersphere-frontend/src/components/task/TaskCenter"),
MsRun: () => import("./DebugRun"), MsRun: () => import("./DebugRun"),
MxRelationshipGraphDrawer: () => import("metersphere-frontend/src/components/graph/MxRelationshipGraphDrawer") MxRelationshipGraphDrawer: () => import("metersphere-frontend/src/components/graph/MxRelationshipGraphDrawer")
}, },
@ -985,7 +985,7 @@ export default {
if (this.batchReportId) { if (this.batchReportId) {
this.result = false; this.result = false;
this.$success(this.$t('commons.run_message')); this.$success(this.$t('commons.run_message'));
this.$refs.taskCenter.open(); this.$refs.taskCenter.open("SCENARIO");
} }
}, },
buildBatchParam(param) { buildBatchParam(param) {

View File

@ -457,7 +457,7 @@ export default {
MsDrawer: () => import("metersphere-frontend/src/components/MsDrawer"), MsDrawer: () => import("metersphere-frontend/src/components/MsDrawer"),
MsSelectTree: () => import("metersphere-frontend/src/components/select-tree/SelectTree"), MsSelectTree: () => import("metersphere-frontend/src/components/select-tree/SelectTree"),
MsChangeHistory: () => import("@/business/history/ApiHistory"), MsChangeHistory: () => import("@/business/history/ApiHistory"),
MsTaskCenter: () => import("@/business/history/task/ApiTaskCenter"), MsTaskCenter: () => import("metersphere-frontend/src/components/task/TaskCenter"),
MsApiVariableAdvance: () => import("./../../definition/components/ApiVariableAdvance"), MsApiVariableAdvance: () => import("./../../definition/components/ApiVariableAdvance"),
MsMainContainer: () => import("metersphere-frontend/src/components/MsMainContainer"), MsMainContainer: () => import("metersphere-frontend/src/components/MsMainContainer"),
MsAsideContainer: () => import("metersphere-frontend/src/components/MsAsideContainer"), MsAsideContainer: () => import("metersphere-frontend/src/components/MsAsideContainer"),

View File

@ -1066,10 +1066,6 @@ export default {
margin: 0 0 0px; margin: 0 0 0px;
} }
:deep(.el-tabs__nav-scroll) {
width: calc(100% - 200px);
}
:deep( .el-card) { :deep( .el-card) {
/*border: 1px solid #EBEEF5;*/ /*border: 1px solid #EBEEF5;*/
/*border-style: none;*/ /*border-style: none;*/

View File

@ -78,7 +78,7 @@ export default {
ApiCaseHeader, ApiCaseHeader,
MsRun: () => import("../Run"), MsRun: () => import("../Run"),
ApiCaseItem: () => import("./ApiCaseItem"), ApiCaseItem: () => import("./ApiCaseItem"),
MsTaskCenter: () => import("@/business/history/task/ApiTaskCenter"), MsTaskCenter: () => import("metersphere-frontend/src/components/task/TaskCenter"),
}, },
props: { props: {
createCase: String, createCase: String,

View File

@ -374,7 +374,7 @@ export default {
SyncSetting, SyncSetting,
MsApiReportStatus: () => import("../../../automation/report/ApiReportStatus"), MsApiReportStatus: () => import("../../../automation/report/ApiReportStatus"),
PlanStatusTableItem: () => import("@/business/commons/PlanStatusTableItem"), PlanStatusTableItem: () => import("@/business/commons/PlanStatusTableItem"),
MsTaskCenter: () => import("@/business/history/task/ApiTaskCenter"), MsTaskCenter: () => import("metersphere-frontend/src/components/task/TaskCenter"),
}, },
data() { data() {
return { return {
@ -701,7 +701,7 @@ export default {
} else { } else {
store.currentApiCase = {case: true}; store.currentApiCase = {case: true};
} }
this.$refs.taskCenter.open(); this.$refs.taskCenter.open("API");
}); });
}, },
customHeader() { customHeader() {

View File

@ -1,544 +0,0 @@
<template>
<div v-permission="['PROJECT_API_SCENARIO:READ','WORKSPACE_USER:READ']">
<div class="ms-header-menu align-right">
<el-tooltip effect="light" v-if="showMenu">
<template v-slot:content>
<span>{{ $t('commons.task_center') }}</span>
</template>
<div @click="showTaskCenter" v-if="runningTotal > 0">
<el-badge :value="runningTotal" class="item" type="primary">
<font-awesome-icon class="icon global focusing" :icon="['fas', 'tasks']"/>
</el-badge>
</div>
<font-awesome-icon @click="showTaskCenter" class="icon global focusing" :icon="['fas', 'tasks']" v-else/>
</el-tooltip>
</div>
<el-drawer
:visible.sync="taskVisible"
:destroy-on-close="true"
direction="rtl"
:withHeader="true"
:modal="false"
:title="$t('commons.task_center')"
:size="size.toString()"
custom-class="ms-drawer-task">
<el-card style="float: left;" :style="{'width': (size - 550)+'px'}" v-if="size > 550 ">
<div class="ms-task-opt-btn" @click="packUp">{{ $t('commons.task_close') }}</div>
<!-- 接口用例结果 -->
<slot name="report"/>
<!-- todo -->
<ms-request-result-tail :response="response" ref="debugResult"
v-if="executionModule === 'API' && reportType !=='API_INTEGRATED'"/>
<ms-api-report-detail :showCancelButton="false" :reportId="reportId"
v-if="executionModule === 'SCENARIO'|| reportType ==='API_INTEGRATED'"/>
</el-card>
<el-card style="width: 550px;float: right" v-loading="loading">
<div style="color: #2B415C;margin: 0px 20px 0px;">
<el-form label-width="95px" class="ms-el-form-item">
<el-row>
<el-col :span="12">
<el-form-item :label="$t('test_track.report.list.trigger_mode')" prop="runMode">
<el-select size="small" style="margin-right: 10px" v-model="condition.triggerMode" @change="init"
:disabled="isDebugHistory">
<el-option v-for="item in runMode" :key="item.id" :value="item.id" :label="item.label"/>
</el-select>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item :label="$t('commons.status')" prop="status">
<el-select size="small" style="margin-right: 10px" v-model="condition.executionStatus" @change="init"
:disabled="isDebugHistory">
<el-option v-for="item in runStatus" :key="item.id" :value="item.id" :label="item.label"/>
</el-select>
</el-form-item>
</el-col>
</el-row>
<el-row>
<el-col :span="12">
<el-form-item :label="$t('commons.executor')" prop="status">
<el-select v-model="condition.executor" :placeholder="$t('commons.executor')" filterable size="small"
style="margin-right: 10px" @change="init" :disabled="isDebugHistory">
<el-option
v-for="item in maintainerOptions"
:key="item.id"
:label="item.id + ' (' + item.name + ')'"
:value="item.id">
</el-option>
</el-select>
</el-form-item>
</el-col>
<el-col :span="12">
<el-button size="small" class="ms-task-stop" @click="stop(null)" :disabled="isDebugHistory">
{{ $t('report.stop_btn_all') }}
</el-button>
</el-col>
</el-row>
</el-form>
</div>
<el-divider direction="horizontal" style="width: 100%"/>
<div class="report-container">
<div v-for="item in taskData" :key="item.id" style="margin-bottom: 5px;">
<el-card class="ms-card-task" @click.native="showReport(item)">
<span>
{{ getModeName(item.executionModule) }} : <el-link type="primary" class="ms-task-name-width"> {{
item.name
}} </el-link>
</span>
<el-button size="mini" class="ms-task-stop" @click.stop @click="stop(item)"
v-if="showStop(item.executionStatus)">
{{ $t('report.stop_btn') }}
</el-button>
<br/>
<span>
{{ $t('commons.actuator') }}{{ item.actuator }} {{ $t('commons.from') }} {{ item.executor }} {{
item.executionTime | datetimeFormat
}} {{ getMode(item.triggerMode) }}
</span>
<br/>
<el-row>
<el-col :span="20">
<el-progress :percentage="getPercentage(item.executionStatus)" :format="format"/>
</el-col>
<el-col :span="4">
<ms-api-report-status :status="item.executionStatus"/>
</el-col>
</el-row>
</el-card>
</div>
</div>
<div class="report-bottom">
<ms-table-pagination
:change="init"
:current-page.sync="currentPage" :page-size.sync="pageSize" :total="total"
small v-if="showType !== 'SCENARIO' && showType !== 'CASE'"/>
<span v-else> {{ $t('commons.task_center_remark') }}</span>
</div>
</el-card>
</el-drawer>
</div>
</template>
<script>
import MsDrawer from "metersphere-frontend/src/components/MsDrawer";
import {getCurrentProjectID, getCurrentUser} from "metersphere-frontend/src/utils/token";
import {hasPermissions} from "metersphere-frontend/src/utils/permission";
import {getProjectUsers} from "metersphere-frontend/src/api/user";
import {getScenarioData, getCaseData, getTaskSocket, getTaskList} from "metersphere-frontend/src/api/task";
import {getApiReportDetail} from "@/api/definition-report";
import {execBatchStop} from "@/api/scenario";
export default {
name: "MsApiTaskCenter",
components: {
MsDrawer,
MsApiReportStatus: () => import("../../automation/report/ApiReportStatus"),
MsRequestResultTail: () => import("@/business/definition/components/response/RequestResultTail"),
MsApiReportDetail: () => import("@/business/automation/report/ApiReportDetail"),
MsTablePagination: () => import("./ApiTaskPagination"),
},
inject: [
'reload'
],
data() {
return {
runningTotal: 0,
taskVisible: false,
result: {},
loading: false,
taskData: [],
response: {},
initEnd: false,
visible: false,
showType: "",
pageSize: 10,
currentPage: 1,
total: 0,
runMode: [
{id: '', label: this.$t('api_test.definition.document.data_set.all')},
{id: 'BATCH', label: this.$t('api_test.automation.batch_execute')},
{id: 'SCHEDULE', label: this.$t('commons.trigger_mode.schedule')},
{id: 'MANUAL', label: this.$t('commons.trigger_mode.manual')},
{id: 'API', label: this.$t('commons.trigger_mode.api')}
],
runStatus: [
{id: '', label: this.$t('api_test.definition.document.data_set.all')},
{id: 'STARTING', label: 'Starting'},
{id: 'PENDING', label: 'Pending'},
{id: 'RUNNING', label: 'Running'},
{id: 'REPORTING', label: 'Reporting'},
{id: 'SUCCESS', label: 'Success'},
{id: "FAKE_ERROR", label: 'FakeError'},
{id: 'ERROR', label: 'Error'},
{id: 'STOPPED', label: 'Stopped'},
{id: 'COMPLETED', label: 'Completed'},
],
condition: {triggerMode: "", executionStatus: ""},
maintainerOptions: [],
websocket: Object,
size: 550,
reportId: "",
executionModule: "",
reportType: "",
isDebugHistory: false
};
},
props: {
showMenu: {
type: Boolean,
default: true
}
},
computed: {
disabled() {
return this.loading
},
},
created() {
if (hasPermissions('PROJECT_API_SCENARIO:READ')) {
this.condition.executor = getCurrentUser().id;
}
},
watch: {
taskVisible(v) {
if (!v) {
this.close();
}
}
},
methods: {
nextData() {
this.loading = true;
this.init();
},
format(item) {
return '';
},
packUp() {
this.size = 550;
},
stop(row) {
let array = [];
if (row) {
let request = {type: row.executionModule, reportId: row.id};
array = [request];
} else {
array.push({type: 'API', projectId: getCurrentProjectID(), userId: getCurrentUser().id});
array.push({type: 'SCENARIO', projectId: getCurrentProjectID(), userId: getCurrentUser().id});
array.push({type: 'PERFORMANCE', projectId: getCurrentProjectID(), userId: getCurrentUser().id});
}
execBatchStop(array).then(response => {
this.$success(this.$t('report.test_stop_success'));
this.init();
});
},
getMaintainerOptions() {
getProjectUsers()
.then(response => {
this.maintainerOptions = response.data;
this.condition.executor = getCurrentUser().id;
})
},
initWebSocket() {
this.websocket = getTaskSocket();
this.websocket.onmessage = this.onMessage;
this.websocket.onopen = this.onOpen;
this.websocket.onerror = this.onError;
this.websocket.onclose = this.onClose;
},
onOpen() {
},
onError(e) {
},
onMessage(e) {
this.currentPage = 1;
this.loading = false;
let taskTotal = e.data;
this.runningTotal = taskTotal;
this.initIndex++;
if (this.taskVisible && this.initEnd) {
setTimeout(() => {
this.initEnd = false;
this.init();
}, 3000);
}
},
onClose(e) {
},
showTaskCenter() {
this.getTaskRunning();
this.getMaintainerOptions();
this.init();
this.taskVisible = true;
},
close() {
this.visible = false;
this.size = 550;
this.showType = "";
this.currentPage = 1;
if (this.websocket && this.websocket.close instanceof Function) {
this.websocket.close();
}
},
open() {
this.showTaskCenter();
this.initIndex = 0;
this.noMore = false;
this.currentPage = 1;
},
getPercentage(status) {
if (status) {
status = status.toLowerCase();
if (status === "pending" || status === 'stopped') {
return 0;
}
if (status === 'saved' || status === 'completed' || status === 'success' || status === 'error' || status ===
'pending' || status === 'fake_error') {
return 100;
}
}
return 60;
},
showStop(status) {
if (status) {
status = status.toLowerCase();
if (status === "stopped" || status === 'saved' || status === 'completed' || status === 'success' || status ===
'error' || status === 'pending' || status === 'fake_error') {
return false;
}
}
return true;
},
getModeName(executionModule) {
switch (executionModule) {
case "SCENARIO":
return this.$t('test_track.scenario_test_case');
case "PERFORMANCE":
return this.$t('test_track.performance_test_case');
case "API":
return this.$t('test_track.api_test_case');
}
},
showReport(row) {
if (this.size > 550 && this.reportId === row.id) {
this.packUp();
return;
}
let status = row.executionStatus;
if (status) {
status = row.executionStatus.toLowerCase();
if (status === 'saved' || status === 'completed' || status === 'success' || status === 'error' || status ===
'pending' || status === 'fake_error') {
this.size = window.innerWidth - 50;
this.reportId = row.id;
this.executionModule = row.executionModule;
this.reportType = row.reportType;
if (row.executionModule === "API" && row.reportType !== 'API_INTEGRATED') {
this.getExecResult(row.id);
}
} else if (status === 'stopped') {
this.$warning(this.$t('commons.run_stop'));
} else {
this.$warning(this.$t('commons.run_warning'))
}
}
},
getExecResult(reportId) {
if (reportId) {
getApiReportDetail(reportId).then(response => {
if (response.data) {
try {
let data = JSON.parse(response.data.content);
this.response = data;
this.visible = true;
} catch (error) {
this.visible = true;
}
}
});
}
},
getMode(mode) {
if (mode === 'MANUAL') {
return this.$t('commons.trigger_mode.manual');
}
if (mode === 'SCHEDULE') {
return this.$t('commons.trigger_mode.schedule');
}
if (mode === 'TEST_PLAN_SCHEDULE') {
return this.$t('commons.trigger_mode.schedule');
}
if (mode.startsWith('JENKINS')) {
return this.$t('commons.trigger_mode.api');
}
if (mode === 'BATCH') {
return this.$t('api_test.automation.batch_execute');
}
return mode;
},
getTaskRunning() {
this.initWebSocket();
},
init() {
if (this.showType === "CASE" || this.showType === "SCENARIO") {
return;
}
this.condition.projectId = getCurrentProjectID();
this.condition.userId = getCurrentUser().id;
this.result = getTaskList(this.condition, this.currentPage, this.pageSize)
.then(response => {
this.total = response.data.itemCount;
this.taskData = response.data.listObject;
this.initEnd = true;
this.loading = false;
});
},
initCaseHistory(id) {
getCaseData(id)
.then(response => {
this.taskData = response.data;
})
},
openHistory(id) {
this.initCaseHistory(id);
this.taskVisible = true;
this.isDebugHistory = true;
this.condition.triggerMode = "MANUAL";
this.showType = "CASE";
},
openScenarioHistory(id) {
getScenarioData(id)
.then(response => {
this.taskData = response.data;
});
this.showType = "SCENARIO";
this.isDebugHistory = true;
this.condition.triggerMode = "MANUAL";
this.taskVisible = true;
}
}
};
</script>
<style scoped>
.report-container {
height: calc(100vh - 270px);
overflow-y: auto;
}
.align-right {
float: right;
}
.icon {
width: 24px;
}
:deep(.el-drawer__header) {
font-size: 18px;
color: #0a0a0a;
border-bottom: 1px solid #E6E6E6;
background-color: #FFF;
margin-bottom: 10px;
padding-top: 6px;
padding-bottom: 6px;
}
.ms-card-task :deep(.el-card__body) {
padding: 10px;
}
.global {
color: rgb(96, 98, 102);
font-size: 14px
}
.ms-card-task:hover {
cursor: pointer;
border-color: #783887;
}
.ms-header-menu {
padding-top: 12px;
width: 24px;
}
.ms-header-menu:hover {
cursor: pointer;
border-color: var(--color);
}
:deep(.el-progress-bar) {
padding-right: 20px;
}
.item {
margin-right: 10px;
}
.ms-task-stop {
color: #F56C6C;
float: right;
margin-right: 20px;
}
.ms-task-stop {
color: #909399;
}
.ms-task-name-width {
display: inline-block;
overflow-x: hidden;
padding-bottom: 0;
text-overflow: ellipsis;
vertical-align: middle;
white-space: nowrap;
width: 300px;
}
.ms-el-form-item :deep(.el-form-item) {
margin-bottom: 6px;
}
.ms-task-opt-btn {
position: fixed;
right: calc(98% - var(--asideWidth));
top: 50%;
z-index: 5;
width: 20px;
height: 60px;
padding: 3px;
line-height: 30px;
border-radius: 0 15px 15px 0;
background-color: #783887;
color: white;
display: inline-block;
cursor: pointer;
opacity: 0.5;
font-size: 10px;
font-weight: bold;
margin-left: 1px;
}
.ms-task-opt-btn i {
margin-left: -2px;
}
.ms-task-opt-btn:hover {
opacity: 0.8;
}
.ms-task-opt-btn:hover i {
margin-left: 0;
color: white;
}
.report-bottom {
margin-top: 10px;
}
</style>

View File

@ -1,62 +0,0 @@
<template>
<el-row type="flex" justify="end">
<div class="table-page">
<el-pagination
background
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="pageSizes"
:page-size="pageSize"
:page-count="5"
small
layout="total, sizes, prev, pager, next"
:total="total">
</el-pagination>
</div>
</el-row>
</template>
<script>
export default {
name: "MsTaskPagination",
props: {
page: Object,
currentPage: {
type: Number,
default: 1
},
pageSize: {
type: Number,
default: 5
},
pageSizes: {
type: Array,
default: function () {
return [5, 10, 20, 50, 100]
}
},
total: {
type: Number,
default: 0
},
change: Function
},
methods: {
handleSizeChange: function (size) {
this.$emit('update:pageSize', size)
this.change();
},
handleCurrentChange(current) {
this.$emit('update:currentPage', current)
this.change();
}
}
}
</script>
<style scoped>
.table-page {
padding-top: 10px;
}
</style>

View File

@ -5,8 +5,8 @@ import packageInfo from '@/../package.json'
const currentModuleName = packageInfo.name; const currentModuleName = packageInfo.name;
export function getTaskSocket() { export function getTaskSocket(hasLicense) {
return socket("/websocket/task/running/" + getCurrentProjectID() + "/" + getCurrentUser().id) return socket("/websocket/task/running/" + getCurrentProjectID() + "/" + getCurrentUser().id + "/" + hasLicense)
} }
export function getCaseData(id) { export function getCaseData(id) {

View File

@ -22,7 +22,7 @@
:title="$t('commons.task_center')" :title="$t('commons.task_center')"
:size="size.toString()" :size="size.toString()"
custom-class="ms-drawer-task"> custom-class="ms-drawer-task">
<el-card style="float: left;" :style="{'width': (size - 550)+'px'}" v-if="size > 550 "> <el-card style="float: left;margin-top: 0px" :style="{'width': (size - 600)+'px'}" v-if="size > 600 ">
<div class="ms-task-opt-btn" @click="packUp">{{ $t('commons.task_close') }}</div> <div class="ms-task-opt-btn" @click="packUp">{{ $t('commons.task_close') }}</div>
<!-- 接口用例结果 --> <!-- 接口用例结果 -->
<micro-app :to="`/definition/report/view/${reportId}`" service="api" <micro-app :to="`/definition/report/view/${reportId}`" service="api"
@ -37,14 +37,13 @@
<micro-app :to="`/ui/report/view/${reportId}?showCancelButton=false`" service="ui" <micro-app :to="`/ui/report/view/${reportId}?showCancelButton=false`" service="ui"
v-if="executionModule === 'UI_SCENARIO'"/> v-if="executionModule === 'UI_SCENARIO'"/>
</el-card> </el-card>
<el-card style="width: 550px;float: right">
<el-card style="width: 550px;float: right" v-loading="loading"> <div style="color: #2B415C;margin: 0px;">
<div style="color: #2B415C;margin: 0px 20px 0px;">
<el-form label-width="95px" class="ms-el-form-item"> <el-form label-width="95px" class="ms-el-form-item">
<el-row> <el-row>
<el-col :span="12"> <el-col :span="12">
<el-form-item :label="$t('test_track.report.list.trigger_mode')" prop="runMode"> <el-form-item :label="$t('test_track.report.list.trigger_mode')" prop="runMode">
<el-select size="small" style="margin-right: 10px" v-model="condition.triggerMode" @change="init" <el-select size="mini" style="margin-right: 10px" v-model="condition.triggerMode" @change="init"
:disabled="isDebugHistory"> :disabled="isDebugHistory">
<el-option v-for="item in runMode" :key="item.id" :value="item.id" :label="item.label"/> <el-option v-for="item in runMode" :key="item.id" :value="item.id" :label="item.label"/>
</el-select> </el-select>
@ -52,7 +51,7 @@
</el-col> </el-col>
<el-col :span="12"> <el-col :span="12">
<el-form-item :label="$t('commons.status')" prop="status"> <el-form-item :label="$t('commons.status')" prop="status">
<el-select size="small" style="margin-right: 10px" v-model="condition.executionStatus" @change="init" <el-select size="mini" style="margin-right: 10px" v-model="condition.executionStatus" @change="init"
:disabled="isDebugHistory"> :disabled="isDebugHistory">
<el-option v-for="item in runStatus" :key="item.id" :value="item.id" :label="item.label"/> <el-option v-for="item in runStatus" :key="item.id" :value="item.id" :label="item.label"/>
</el-select> </el-select>
@ -62,7 +61,7 @@
<el-row> <el-row>
<el-col :span="12"> <el-col :span="12">
<el-form-item :label="$t('commons.executor')" prop="status"> <el-form-item :label="$t('commons.executor')" prop="status">
<el-select v-model="condition.executor" :placeholder="$t('commons.executor')" filterable size="small" <el-select v-model="condition.executor" :placeholder="$t('commons.executor')" filterable size="mini"
style="margin-right: 10px" @change="init" :disabled="isDebugHistory"> style="margin-right: 10px" @change="init" :disabled="isDebugHistory">
<el-option <el-option
v-for="item in maintainerOptions" v-for="item in maintainerOptions"
@ -74,7 +73,7 @@
</el-form-item> </el-form-item>
</el-col> </el-col>
<el-col :span="12"> <el-col :span="12">
<el-button size="small" class="ms-task-stop" @click="stop(null)" :disabled="isDebugHistory"> <el-button size="mini" class="ms-task-stop" @click="stop(null)" :disabled="isDebugHistory">
{{ $t('report.stop_btn_all') }} {{ $t('report.stop_btn_all') }}
</el-button> </el-button>
</el-col> </el-col>
@ -82,45 +81,27 @@
</el-form> </el-form>
</div> </div>
<el-divider direction="horizontal" style="width: 100%"/> <el-divider direction="horizontal" style="width: 100%"/>
<el-tabs v-model="activeName" @tab-click="init" v-loading="loading">
<div class="ms-body-container"> <el-tab-pane :name="tab.id" :label="tab.label" v-for="tab in tabs" :disabled="isDebugHistory">
<div v-for="item in taskData" :key="item.id" style="margin-bottom: 5px;"> <span slot="label">
<el-card class="ms-card-task" @click.native="showReport(item)"> <el-badge class="ms-badge-item" v-if="showBadge(tab.id) > 0" :value="showBadge(tab.id)">
<span> {{ tab.label }}
{{ getModeName(item.executionModule) }} : <el-link type="primary" class="ms-task-name-width"> {{ </el-badge>
item.name <span v-else>{{ tab.label }}</span>
}} </el-link> </span>
</span> <task-center-item
<el-button size="mini" class="ms-task-stop" @click.stop @click="stop(item)" :task-data="taskData"
v-if="showStop(item.executionStatus)"> :is-debug-history="isDebugHistory"
{{ $t('report.stop_btn') }} :show-type="showType"
</el-button> :total="total"
<br/> :maintainer-options="maintainerOptions"
<span> @packUp="packUp"
{{ $t('commons.actuator') }}{{ item.actuator }} {{ $t('commons.from') }} {{ item.executor }} {{ @nextPage="nextPage"
item.executionTime | datetimeFormat @showReport="showReport"
}} {{ getMode(item.triggerMode) }} />
</span> </el-tab-pane>
<br/> </el-tabs>
<el-row>
<el-col :span="20">
<el-progress :percentage="getPercentage(item.executionStatus)" :format="format"/>
</el-col>
<el-col :span="4">
<ms-task-report-status :status="item.executionStatus"/>
</el-col>
</el-row>
</el-card>
</div>
</div>
<div class="report-bottom">
<ms-table-pagination v-if="showType !== 'SCENARIO' && showType !== 'CASE'" :change="init"
:current-page.sync="currentPage" :page-size.sync="pageSize" :total="total"
small/>
<span v-else> {{ $t('commons.task_center_remark') }}</span>
</div>
</el-card> </el-card>
</el-drawer> </el-drawer>
</div> </div>
</template> </template>
@ -128,17 +109,19 @@
<script> <script>
import MsDrawer from "../MsDrawer"; import MsDrawer from "../MsDrawer";
import {getCurrentProjectID, getCurrentUser} from "../../utils/token"; import {getCurrentProjectID, getCurrentUser} from "../../utils/token";
import {hasPermissions} from "../../utils/permission"; import {hasPermissions, hasLicense} from "../../utils/permission";
import {getProjectUsers} from "../../api/user"; import {getProjectUsers} from "../../api/user";
import {getCaseData, getScenarioData, getTaskList, getTaskSocket, stopBatchTask, stopTask} from "../../api/task"; import {getCaseData, getScenarioData, getTaskList, getTaskSocket, stopBatchTask, stopTask} from "../../api/task";
import MicroApp from "../../components/MicroApp"; import MicroApp from "../../components/MicroApp";
import {prefetchApps} from "qiankun"; import {prefetchApps} from "qiankun";
import TaskCenterItem from "./TaskCenterItem";
export default { export default {
name: "MsTaskCenter", name: "MsTaskCenter",
components: { components: {
MicroApp, MicroApp,
MsDrawer, MsDrawer,
TaskCenterItem,
MsTaskReportStatus: () => import("./TaskReportStatus"), MsTaskReportStatus: () => import("./TaskReportStatus"),
MsTablePagination: () => import("./TaskPagination"), MsTablePagination: () => import("./TaskPagination"),
}, },
@ -147,6 +130,11 @@ export default {
], ],
data() { data() {
return { return {
runningData: {},
pageSize: 10,
currentPage: 1,
total: 0,
activeName: "API",
runningTotal: 0, runningTotal: 0,
taskVisible: false, taskVisible: false,
result: {}, result: {},
@ -156,9 +144,6 @@ export default {
initEnd: false, initEnd: false,
visible: false, visible: false,
showType: "", showType: "",
pageSize: 10,
currentPage: 1,
total: 0,
runMode: [ runMode: [
{id: '', label: this.$t('api_test.definition.document.data_set.all')}, {id: '', label: this.$t('api_test.definition.document.data_set.all')},
{id: 'BATCH', label: this.$t('api_test.automation.batch_execute')}, {id: 'BATCH', label: this.$t('api_test.automation.batch_execute')},
@ -166,6 +151,11 @@ export default {
{id: 'MANUAL', label: this.$t('commons.trigger_mode.manual')}, {id: 'MANUAL', label: this.$t('commons.trigger_mode.manual')},
{id: 'API', label: this.$t('commons.trigger_mode.api')} {id: 'API', label: this.$t('commons.trigger_mode.api')}
], ],
tabs: [
{id: 'API', label: this.$t('task.api_title')},
{id: 'SCENARIO', label: this.$t('task.scenario_title')},
{id: 'PERF', label: this.$t('task.perf_title')}
],
runStatus: [ runStatus: [
{id: '', label: this.$t('api_test.definition.document.data_set.all')}, {id: '', label: this.$t('api_test.definition.document.data_set.all')},
{id: 'STARTING', label: 'Starting'}, {id: 'STARTING', label: 'Starting'},
@ -182,7 +172,7 @@ export default {
condition: {triggerMode: "", executionStatus: ""}, condition: {triggerMode: "", executionStatus: ""},
maintainerOptions: [], maintainerOptions: [],
websocket: Object, websocket: Object,
size: 550, size: 600,
reportId: "", reportId: "",
executionModule: "", executionModule: "",
reportType: "", reportType: "",
@ -205,7 +195,9 @@ export default {
if (hasPermissions('PROJECT_API_SCENARIO:READ')) { if (hasPermissions('PROJECT_API_SCENARIO:READ')) {
this.condition.executor = getCurrentUser().id; this.condition.executor = getCurrentUser().id;
} }
// if (hasLicense()) {
this.tabs.push({id: 'UI', label: this.$t('task.ui_title')})
}
this.prefetchApps(); this.prefetchApps();
}, },
watch: { watch: {
@ -216,15 +208,23 @@ export default {
} }
}, },
methods: { methods: {
nextData() { showBadge(executionModule) {
this.loading = true; switch (executionModule) {
this.init(); case "SCENARIO":
return this.runningData.scenarioTotal;
case "PERF":
return this.runningData.perfTotal;
case "API":
return this.runningData.apiTotal;
case "UI":
return this.runningData.uiTotal;
}
}, },
format(item) { format(item) {
return ''; return '';
}, },
packUp() { packUp() {
this.size = 550; this.size = 600;
}, },
stop(row) { stop(row) {
if (row) { if (row) {
@ -253,7 +253,7 @@ export default {
}) })
}, },
initWebSocket() { initWebSocket() {
this.websocket = getTaskSocket(); this.websocket = getTaskSocket(hasLicense());
this.websocket.onmessage = this.onMessage; this.websocket.onmessage = this.onMessage;
this.websocket.onopen = this.onOpen; this.websocket.onopen = this.onOpen;
this.websocket.onerror = this.onError; this.websocket.onerror = this.onError;
@ -264,10 +264,9 @@ export default {
onError(e) { onError(e) {
}, },
onMessage(e) { onMessage(e) {
this.currentPage = 1;
this.loading = false; this.loading = false;
let taskTotal = e.data; this.runningData = JSON.parse(e.data);
this.runningTotal = taskTotal; this.runningTotal = this.runningData.total;
this.initIndex++; this.initIndex++;
if (this.taskVisible && this.initEnd) { if (this.taskVisible && this.initEnd) {
setTimeout(() => { setTimeout(() => {
@ -286,18 +285,18 @@ export default {
}, },
close() { close() {
this.visible = false; this.visible = false;
this.size = 550; this.size = 600;
this.showType = ""; this.showType = "";
this.currentPage = 1;
if (this.websocket && this.websocket.close instanceof Function) { if (this.websocket && this.websocket.close instanceof Function) {
this.websocket.close(); this.websocket.close();
} }
}, },
open() { open(activeName) {
if (activeName) {
this.activeName = activeName;
}
this.showTaskCenter(); this.showTaskCenter();
this.initIndex = 0; this.initIndex = 0;
this.noMore = false;
this.currentPage = 1;
}, },
getPercentage(status) { getPercentage(status) {
if (status) { if (status) {
@ -335,7 +334,7 @@ export default {
} }
}, },
showReport(row) { showReport(row) {
if (this.size > 550 && this.reportId === row.id) { if (this.size > 600 && this.reportId === row.id) {
this.packUp(); this.packUp();
return; return;
} }
@ -382,12 +381,22 @@ export default {
getTaskRunning() { getTaskRunning() {
this.initWebSocket(); this.initWebSocket();
}, },
nextPage(currentPage, pageSize) {
this.currentPage = currentPage;
this.pageSize = pageSize;
this.init();
},
init() { init() {
if (this.showType === "CASE" || this.showType === "SCENARIO") { if (this.showType === "CASE" || this.showType === "SCENARIO") {
return; return;
} }
this.condition.projectId = getCurrentProjectID(); this.condition.projectId = getCurrentProjectID();
this.condition.userId = getCurrentUser().id; this.condition.userId = getCurrentUser().id;
if (this.runningData) {
this.setActiveName();
}
this.condition.activeName = this.activeName;
this.loading = true;
this.result = getTaskList(this.condition, this.currentPage, this.pageSize) this.result = getTaskList(this.condition, this.currentPage, this.pageSize)
.then(response => { .then(response => {
this.total = response.data.itemCount; this.total = response.data.itemCount;
@ -396,6 +405,17 @@ export default {
this.loading = false; this.loading = false;
}); });
}, },
setActiveName() {
if (this.runningData.apiTotal > 0) {
this.activeName = 'API';
} else if (this.runningData.scenarioTotal > 0) {
this.activeName = 'SCENARIO';
} else if (this.runningData.perfTotal > 0) {
this.activeName = 'PERF';
} else if (this.runningData.uiTotal > 0) {
this.activeName = 'UI';
}
},
initCaseHistory(id) { initCaseHistory(id) {
getCaseData(id) getCaseData(id)
.then(response => { .then(response => {
@ -403,6 +423,7 @@ export default {
}) })
}, },
openHistory(id) { openHistory(id) {
this.activeName = 'API';
this.initCaseHistory(id); this.initCaseHistory(id);
this.taskVisible = true; this.taskVisible = true;
this.isDebugHistory = true; this.isDebugHistory = true;
@ -410,6 +431,7 @@ export default {
this.showType = "CASE"; this.showType = "CASE";
}, },
openScenarioHistory(id) { openScenarioHistory(id) {
this.activeName = 'SCENARIO';
getScenarioData(id) getScenarioData(id)
.then(response => { .then(response => {
this.taskData = response.data; this.taskData = response.data;
@ -460,11 +482,11 @@ export default {
} }
:deep(.el-drawer__header) { :deep(.el-drawer__header) {
font-size: 18px; font-size: 14px;
color: #0a0a0a; color: #0a0a0a;
border-bottom: 1px solid #E6E6E6; border-bottom: 1px solid #E6E6E6;
background-color: #FFF; background-color: #FFF;
margin-bottom: 10px; margin-bottom: 0px;
padding-top: 6px; padding-top: 6px;
padding-bottom: 6px; padding-bottom: 6px;
} }
@ -523,7 +545,7 @@ export default {
} }
.ms-el-form-item :deep(.el-form-item) { .ms-el-form-item :deep(.el-form-item) {
margin-bottom: 6px; margin-bottom: 0px;
} }
.ms-task-opt-btn { .ms-task-opt-btn {
@ -568,4 +590,14 @@ export default {
min-height: 600px; min-height: 600px;
overflow-y: auto; overflow-y: auto;
} }
.ms-badge-item {
margin-top: 0px;
margin-right: 0px;
font-size: 12px;
}
:deep(.el-badge__content.is-fixed) {
transform: translateY(-10%) translateX(100%);
}
</style> </style>

View File

@ -0,0 +1,303 @@
<template>
<div>
<div class="ms-body-container">
<div v-for="item in taskData" :key="item.id" style="margin-bottom: 5px;">
<el-card class="ms-card-task" @click.native="showReport(item)">
<span>
{{ getModeName(item.executionModule) }} :
<el-link type="primary" class="ms-task-name-width"> {{ item.name }} </el-link>
</span>
<el-button size="mini" class="ms-task-stop"
@click.stop @click="stop(item)"
v-if="showStop(item.executionStatus)">
{{ $t('report.stop_btn') }}
</el-button>
<br/>
<span>
{{ $t('commons.actuator') }}
{{ item.actuator }}
{{ $t('commons.from') }}
{{ item.executor }}
{{ item.executionTime | datetimeFormat }}
{{ getMode(item.triggerMode) }}
</span>
<br/>
<el-row>
<el-col :span="20">
<el-progress :percentage="getPercentage(item.executionStatus)" :format="format"/>
</el-col>
<el-col :span="4">
<ms-task-report-status :status="item.executionStatus"/>
</el-col>
</el-row>
</el-card>
</div>
</div>
<div class="report-bottom">
<ms-table-pagination
:current-page.sync="currentPage"
:page-size.sync="pageSize"
:total="total"
:change="init"
v-if="showType !== 'SCENARIO' && showType !== 'CASE'" small/>
<span v-else> {{ $t('commons.task_center_remark') }}</span>
</div>
</div>
</template>
<script>
import {getCurrentProjectID, getCurrentUser} from "../../utils/token";
import {stopBatchTask, stopTask} from "../../api/task";
export default {
name: "TaskCenterItem",
components: {
MsTaskReportStatus: () => import("./TaskReportStatus"),
MsTablePagination: () => import("./TaskPagination"),
},
inject: [
'reload'
],
data() {
return {
pageSize: 10,
currentPage: 1,
runMode: [
{id: '', label: this.$t('api_test.definition.document.data_set.all')},
{id: 'BATCH', label: this.$t('api_test.automation.batch_execute')},
{id: 'SCHEDULE', label: this.$t('commons.trigger_mode.schedule')},
{id: 'MANUAL', label: this.$t('commons.trigger_mode.manual')},
{id: 'API', label: this.$t('commons.trigger_mode.api')}
],
runStatus: [
{id: '', label: this.$t('api_test.definition.document.data_set.all')},
{id: 'STARTING', label: 'Starting'},
{id: 'PENDING', label: 'Pending'},
{id: 'RUNNING', label: 'Running'},
{id: 'RERUNNING', label: 'Rerunning'},
{id: 'REPORTING', label: 'Reporting'},
{id: 'SUCCESS', label: 'Success'},
{id: "FAKE_ERROR", label: 'FakeError'},
{id: 'ERROR', label: 'Error'},
{id: 'STOPPED', label: 'Stopped'},
{id: 'COMPLETED', label: 'Completed'},
],
}
},
props: {
total: Number,
taskData: Array,
isDebugHistory: Boolean,
showType: String,
maintainerOptions: Array
},
methods: {
format(item) {
return '';
},
stop(row) {
if (row) {
let request = {type: row.executionModule, reportId: row.id};
stopTask(request).then(response => {
this.$success(this.$t('report.test_stop_success'));
this.init();
});
} else {
let array = [];
array.push({type: 'API', projectId: getCurrentProjectID(), userId: getCurrentUser().id});
array.push({type: 'SCENARIO', projectId: getCurrentProjectID(), userId: getCurrentUser().id});
array.push({type: 'PERFORMANCE', projectId: getCurrentProjectID(), userId: getCurrentUser().id});
array.push({type: 'UI_SCENARIO', projectId: getCurrentProjectID(), userId: getCurrentUser().id});
stopBatchTask(array).then(response => {
this.$success(this.$t('report.test_stop_success'));
this.init();
});
}
},
getPercentage(status) {
if (status) {
status = status.toLowerCase();
if (status === "pending" || status === 'stopped') {
return 0;
}
if (status === 'saved' || status === 'completed' || status === 'success' || status === 'error' || status ===
'pending' || status === 'fake_error') {
return 100;
}
}
return 60;
},
showStop(status) {
if (status) {
status = status.toLowerCase();
if (status === "stopped" || status === 'saved' || status === 'completed' || status === 'success' || status ===
'error' || status === 'pending' || status === 'fake_error') {
return false;
}
}
return true;
},
getModeName(executionModule) {
switch (executionModule) {
case "SCENARIO":
return this.$t('test_track.scenario_test_case');
case "PERFORMANCE":
return this.$t('test_track.performance_test_case');
case "API":
return this.$t('test_track.api_test_case');
case "UI_SCENARIO":
return this.$t("test_track.ui_scenario_test_case");
}
},
packUp() {
this.$emit("packUp")
},
showReport(row) {
this.$emit("showReport", row)
},
getMode(mode) {
if (mode === 'MANUAL') {
return this.$t('commons.trigger_mode.manual');
}
if (mode === 'SCHEDULE') {
return this.$t('commons.trigger_mode.schedule');
}
if (mode === 'TEST_PLAN_SCHEDULE') {
return this.$t('commons.trigger_mode.schedule');
}
if (mode === 'API') {
return this.$t('commons.trigger_mode.api');
}
if (mode === 'BATCH') {
return this.$t('api_test.automation.batch_execute');
}
if (mode.startsWith('JENKINS')) {
return this.$t('commons.trigger_mode.api');
}
return mode;
},
init() {
if (this.showType === "CASE" || this.showType === "SCENARIO") {
return;
}
this.$emit("nextPage", this.currentPage, this.pageSize);
},
}
};
</script>
<style scoped>
.ms-body-container {
height: calc(100vh - 290px);
overflow-y: auto;
}
.align-right {
float: right;
}
.icon {
width: 24px;
}
.ms-card-task :deep(.el-card__body) {
padding: 10px;
}
.global {
color: rgb(96, 98, 102);
font-size: 14px
}
.ms-card-task:hover {
cursor: pointer;
border-color: #783887;
}
.ms-header-menu {
padding-top: 12px;
width: 24px;
}
.ms-header-menu:hover {
cursor: pointer;
border-color: var(--color);
}
:deep(.el-progress-bar) {
padding-right: 20px;
}
.item {
margin-right: 10px;
}
.ms-task-stop {
color: #F56C6C;
float: right;
margin-right: 20px;
}
.ms-task-stop {
color: #909399;
}
.ms-task-name-width {
display: inline-block;
overflow-x: hidden;
padding-bottom: 0;
text-overflow: ellipsis;
vertical-align: middle;
white-space: nowrap;
width: 300px;
}
.ms-el-form-item :deep(.el-form-item) {
margin-bottom: 6px;
}
.ms-task-opt-btn {
position: fixed;
right: calc(98% - var(--asideWidth));
top: 50%;
z-index: 5;
width: 20px;
height: 60px;
padding: 3px;
line-height: 30px;
border-radius: 0 15px 15px 0;
background-color: #783887;
color: white;
display: inline-block;
cursor: pointer;
opacity: 0.5;
font-size: 10px;
font-weight: bold;
margin-left: 1px;
}
.ms-task-opt-btn i {
margin-left: -2px;
}
.ms-task-opt-btn:hover {
opacity: 0.8;
}
.ms-task-opt-btn:hover i {
margin-left: 0;
color: white;
}
.report-bottom {
margin-top: 10px;
}
:deep(.report-container) {
height: calc(100vh - 155px) !important;
min-height: 600px;
overflow-y: auto;
}
</style>

View File

@ -3003,6 +3003,12 @@ const message = {
go_to_case_message: 'CASE update message notification', go_to_case_message: 'CASE update message notification',
update_case_tip: 'When the CASE changes, the creator of the automation scene referring to the CASE will receive an in-site message reminder' update_case_tip: 'When the CASE changes, the creator of the automation scene referring to the CASE will receive an in-site message reminder'
} }
},
task: {
api_title: "Api testing tasks",
scenario_title: "Scenario testing tasks",
ui_title: "UI testing tasks",
perf_title: "Perf testing tasks"
} }
} }

View File

@ -3016,6 +3016,12 @@ const message = {
go_to_case_message: 'CASE更新消息通知', go_to_case_message: 'CASE更新消息通知',
update_case_tip: '当CASE发生变化时引用CASE的自动化场景创建人会收到站内消息提醒' update_case_tip: '当CASE发生变化时引用CASE的自动化场景创建人会收到站内消息提醒'
} }
},
task: {
api_title: "接口测试任务",
scenario_title: "场景测试任务",
ui_title: "UI测试任务",
perf_title: "性能测试任务"
} }
} }

View File

@ -2994,6 +2994,12 @@ const message = {
go_to_case_message: 'CASE更新消息通知', go_to_case_message: 'CASE更新消息通知',
update_case_tip: '當CASE發生變化時引用CASE的自動化場景創建人會收到站內消息提醒' update_case_tip: '當CASE發生變化時引用CASE的自動化場景創建人會收到站內消息提醒'
} }
},
task: {
api_title: "接口測試任務",
scenario_title: "場景測試任務",
ui_title: "UI測試任務",
perf_title: "性能測試任務"
} }
} }

View File

@ -2,15 +2,19 @@ package io.metersphere.base.mapper.ext;
import io.metersphere.task.dto.TaskCenterDTO; import io.metersphere.task.dto.TaskCenterDTO;
import io.metersphere.task.dto.TaskCenterRequest; import io.metersphere.task.dto.TaskCenterRequest;
import io.metersphere.task.dto.TaskStatisticsDTO;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import java.util.List; import java.util.List;
public interface BaseTaskMapper { public interface BaseTaskMapper {
List<TaskCenterDTO> getTasks(@Param("request") TaskCenterRequest request, @Param("uiPermission") Boolean uiPermission); List<TaskCenterDTO> getApiTasks(@Param("request") TaskCenterRequest request);
List<TaskCenterDTO> getScenarioTasks(@Param("request") TaskCenterRequest request);
List<TaskCenterDTO> getPerfTasks(@Param("request") TaskCenterRequest request);
List<TaskCenterDTO> getUiTasks(@Param("request") TaskCenterRequest request, @Param("uiPermission") Boolean uiPermission);
int getRunningTasks(@Param("request") TaskCenterRequest request); TaskStatisticsDTO getRunningTasks(@Param("request") TaskCenterRequest request);
List<TaskCenterDTO> getCases(@Param("id") String id); List<TaskCenterDTO> getCases(@Param("id") String id);

View File

@ -1,38 +1,8 @@
<?xml version="1.0" encoding="UTF-8" ?> <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="io.metersphere.base.mapper.ext.BaseTaskMapper"> <mapper namespace="io.metersphere.base.mapper.ext.BaseTaskMapper">
<select id="getTasks" resultType="io.metersphere.task.dto.TaskCenterDTO" <select id="getApiTasks" resultType="io.metersphere.task.dto.TaskCenterDTO" parameterType="java.lang.String">
parameterType="java.lang.String"> SELECT t.id,t.name,'API' AS executionModule, t.report_type, ifnull(t2.name,'LOCAL') AS actuator, t1.`name` AS
SELECT tt.* FROM (
(SELECT t.id,t.name AS name ,'SCENARIO' AS
executionModule,t.report_type, ifnull(t2.name,'LOCAL') AS actuator, t1.`name` AS executor,t.create_time AS
executionTime, t.trigger_mode AS triggerMode ,t.status AS executionStatus
FROM api_scenario_report t INNER JOIN `user` t1 ON t.user_id = t1.id LEFT JOIN test_resource_pool t2 ON
t.actuator = t2.id
WHERE to_days(FROM_UNIXTIME(t.create_time/1000))= to_days(now()) AND t.execute_type !='Debug' AND t.execute_type
!='Marge' AND t.project_id IN
<foreach collection="request.projects" item="id" separator="," open="(" close=")">
#{id}
</foreach>
<if test="request.triggerMode != null and request.triggerMode != ''">
<choose>
<when test="request.triggerMode== 'API'">
AND t.trigger_mode in ('JENKINS_API_PLAN', 'JENKINS_SCENARIO_PLAN', 'JENKINS_PERFORMANCE_TEST', 'JENKINS')
</when>
<otherwise>
AND t.trigger_mode = #{request.triggerMode}
</otherwise>
</choose>
</if>
<if test="request.executionStatus != null and request.executionStatus != ''">
AND t.status = #{request.executionStatus}
</if>
<if test="request.executor != null and request.executor != ''">
AND t.user_id = #{request.executor}
</if>
)
UNION ALL
(SELECT t.id,t.name,'API' AS executionModule, t.report_type, ifnull(t2.name,'LOCAL') AS actuator, t1.`name` AS
executor,t.create_time AS executionTime, ifnull(t.trigger_mode,'MANUAL') AS triggerMode executor,t.create_time AS executionTime, ifnull(t.trigger_mode,'MANUAL') AS triggerMode
,ifnull(t.status,'Saved') AS executionStatus ,ifnull(t.status,'Saved') AS executionStatus
FROM api_definition_exec_result t INNER JOIN `user` t1 ON t.user_id = t1.id LEFT JOIN test_resource_pool t2 ON FROM api_definition_exec_result t INNER JOIN `user` t1 ON t.user_id = t1.id LEFT JOIN test_resource_pool t2 ON
@ -59,9 +29,41 @@
AND t.user_id = #{request.executor} AND t.user_id = #{request.executor}
</if> </if>
AND (t.integrated_report_id IS NULL OR t.integrated_report_id = 'null') AND (t.integrated_report_id IS NULL OR t.integrated_report_id = 'null')
) ORDER BY t.create_time DESC
UNION ALL </select>
(SELECT t.id,t.name,'PERFORMANCE' AS executionModule,'PERFORMANCE' AS report_type, ifnull(t2.name,'LOCAL') AS
<select id="getScenarioTasks" resultType="io.metersphere.task.dto.TaskCenterDTO" parameterType="java.lang.String">
SELECT t.id,t.name AS name ,'SCENARIO' AS
executionModule,t.report_type, ifnull(t2.name,'LOCAL') AS actuator, t1.`name` AS executor,t.create_time AS
executionTime, t.trigger_mode AS triggerMode ,t.status AS executionStatus
FROM api_scenario_report t INNER JOIN `user` t1 ON t.user_id = t1.id LEFT JOIN test_resource_pool t2 ON
t.actuator = t2.id
WHERE to_days(FROM_UNIXTIME(t.create_time/1000))= to_days(now()) AND t.execute_type !='Debug' AND t.execute_type
!='Marge' AND t.project_id IN
<foreach collection="request.projects" item="id" separator="," open="(" close=")">
#{id}
</foreach>
<if test="request.triggerMode != null and request.triggerMode != ''">
<choose>
<when test="request.triggerMode== 'API'">
AND t.trigger_mode in ('JENKINS_API_PLAN', 'JENKINS_SCENARIO_PLAN', 'JENKINS_PERFORMANCE_TEST', 'JENKINS')
</when>
<otherwise>
AND t.trigger_mode = #{request.triggerMode}
</otherwise>
</choose>
</if>
<if test="request.executionStatus != null and request.executionStatus != ''">
AND t.status = #{request.executionStatus}
</if>
<if test="request.executor != null and request.executor != ''">
AND t.user_id = #{request.executor}
</if>
ORDER BY t.create_time DESC
</select>
<select id="getPerfTasks" resultType="io.metersphere.task.dto.TaskCenterDTO" parameterType="java.lang.String">
SELECT t.id,t.name,'PERFORMANCE' AS executionModule,'PERFORMANCE' AS report_type, ifnull(t2.name,'LOCAL') AS
actuator, t1.`name` AS executor,t.create_time AS executionTime, t.trigger_mode AS triggerMode ,t.`status` AS actuator, t1.`name` AS executor,t.create_time AS executionTime, t.trigger_mode AS triggerMode ,t.`status` AS
executionStatus executionStatus
FROM load_test_report t INNER JOIN `user` t1 ON t.user_id = t1.id LEFT JOIN test_resource_pool t2 ON FROM load_test_report t INNER JOIN `user` t1 ON t.user_id = t1.id LEFT JOIN test_resource_pool t2 ON
@ -86,10 +88,12 @@
<if test="request.executor != null and request.executor != ''"> <if test="request.executor != null and request.executor != ''">
AND t.user_id = #{request.executor} AND t.user_id = #{request.executor}
</if> </if>
) ORDER BY t.create_time DESC
</select>
<select id="getUiTasks" resultType="io.metersphere.task.dto.TaskCenterDTO" parameterType="java.lang.String">
<if test="uiPermission"> <if test="uiPermission">
UNION ALL SELECT t.id,t.name AS name ,'UI_SCENARIO' AS
(SELECT t.id,t.name AS name ,'UI_SCENARIO' AS
executionModule,t.report_type, ifnull(t2.name,'LOCAL') AS actuator, t1.`name` AS executor,t.create_time AS executionModule,t.report_type, ifnull(t2.name,'LOCAL') AS actuator, t1.`name` AS executor,t.create_time AS
executionTime, t.trigger_mode AS triggerMode ,t.status AS executionStatus executionTime, t.trigger_mode AS triggerMode ,t.status AS executionStatus
FROM ui_scenario_report t INNER JOIN `user` t1 ON t.user_id = t1.id LEFT JOIN test_resource_pool t2 ON FROM ui_scenario_report t INNER JOIN `user` t1 ON t.user_id = t1.id LEFT JOIN test_resource_pool t2 ON
@ -108,9 +112,8 @@
<if test="request.executor != null and request.executor != ''"> <if test="request.executor != null and request.executor != ''">
AND t.user_id = #{request.executor} AND t.user_id = #{request.executor}
</if> </if>
) ORDER BY t.create_time DESC
</if> </if>
)tt ORDER BY tt.executionTime DESC
</select> </select>
<select id="getCases" resultType="io.metersphere.task.dto.TaskCenterDTO" parameterType="java.lang.String"> <select id="getCases" resultType="io.metersphere.task.dto.TaskCenterDTO" parameterType="java.lang.String">
@ -130,14 +133,19 @@
WHERE t.execute_type ='Debug' AND t.scenario_id=#{id} ORDER BY t.create_time DESC LIMIT 5; WHERE t.execute_type ='Debug' AND t.scenario_id=#{id} ORDER BY t.create_time DESC LIMIT 5;
</select> </select>
<select id="getRunningTasks" resultType="java.lang.Integer" parameterType="java.lang.String"> <select id="getRunningTasks" resultType="io.metersphere.task.dto.TaskStatisticsDTO" parameterType="java.lang.String">
SELECT COUNT(tt.id) FROM ( SELECT (
(SELECT t.id,'SCENARIO' AS executionModule,t.report_type, ifnull(t2.name,'LOCAL') AS actuator, t1.`name` AS SELECT
executor,t.create_time AS executionTime, t.trigger_mode AS triggerMode ,t.status AS executionStatus count( t.id )
FROM api_scenario_report t LEFT JOIN `user` t1 ON t.user_id = t1.id LEFT JOIN test_resource_pool t2 ON FROM
t.actuator = t2.id api_scenario_report t
WHERE to_days(FROM_UNIXTIME(t.create_time/1000))= to_days(now()) AND t.execute_type !='Debug' AND t.execute_type LEFT JOIN `user` t1 ON t.user_id = t1.id
!='Marge' AND t.project_id IN LEFT JOIN test_resource_pool t2 ON t.actuator = t2.id
WHERE
to_days(FROM_UNIXTIME( t.create_time / 1000 ))= to_days(now())
AND t.execute_type != 'Debug'
AND t.execute_type != 'Marge'
AND t.project_id IN
<foreach collection="request.projects" item="id" separator="," open="(" close=")"> <foreach collection="request.projects" item="id" separator="," open="(" close=")">
#{id} #{id}
</foreach> </foreach>
@ -157,43 +165,52 @@
<if test="request.executor != null and request.executor != ''"> <if test="request.executor != null and request.executor != ''">
AND t.user_id = #{request.executor} AND t.user_id = #{request.executor}
</if> </if>
AND t.status IN ("running","starting","waiting") AND t.status IN ("running","starting","pending")
) ) as scenarioTotal ,
UNION ALL <if test="request.hasLicense">
(SELECT t.id,'SCENARIO' AS executionModule,t.report_type, ifnull(t2.name,'LOCAL') AS actuator, t1.`name` AS (SELECT
executor,t.create_time AS executionTime, t.trigger_mode AS triggerMode ,t.status AS executionStatus count( t.id )
FROM ui_scenario_report t LEFT JOIN `user` t1 ON t.user_id = t1.id LEFT JOIN test_resource_pool t2 ON FROM
t.actuator = t2.id ui_scenario_report t
WHERE to_days(FROM_UNIXTIME(t.create_time/1000))= to_days(now()) AND t.execute_type !='Debug' AND t.execute_type LEFT JOIN `user` t1 ON t.user_id = t1.id
!='Marge' AND t.project_id IN LEFT JOIN test_resource_pool t2 ON t.actuator = t2.id
<foreach collection="request.projects" item="id" separator="," open="(" close=")"> WHERE
#{id} to_days( FROM_UNIXTIME( t.create_time / 1000 ))= to_days(now())
</foreach> AND t.execute_type != 'Debug'
<if test="request.triggerMode != null and request.triggerMode != ''"> AND t.execute_type != 'Marge'
<choose> AND t.project_id IN
<when test="request.triggerMode== 'API'"> <foreach collection="request.projects" item="id" separator="," open="(" close=")">
AND t.trigger_mode in ('JENKINS_API_PLAN', 'JENKINS_SCENARIO_PLAN', 'JENKINS_PERFORMANCE_TEST', 'JENKINS') #{id}
</when> </foreach>
<otherwise> <if test="request.triggerMode != null and request.triggerMode != ''">
AND t.trigger_mode = #{request.triggerMode} <choose>
</otherwise> <when test="request.triggerMode== 'API'">
</choose> AND t.trigger_mode in ('JENKINS_API_PLAN', 'JENKINS_SCENARIO_PLAN', 'JENKINS_PERFORMANCE_TEST',
'JENKINS')
</when>
<otherwise>
AND t.trigger_mode = #{request.triggerMode}
</otherwise>
</choose>
</if>
<if test="request.executionStatus != null and request.executionStatus != ''">
AND t.status = #{request.executionStatus}
</if>
<if test="request.executor != null and request.executor != ''">
AND t.user_id = #{request.executor}
</if>
AND t.status IN ("running","starting","pending")
),
</if> </if>
<if test="request.executionStatus != null and request.executionStatus != ''"> (SELECT
AND t.status = #{request.executionStatus} count( t.id )
</if> FROM
<if test="request.executor != null and request.executor != ''"> api_definition_exec_result t
AND t.user_id = #{request.executor} LEFT JOIN `user` t1 ON t.user_id = t1.id
</if> LEFT JOIN test_resource_pool t2 ON t.actuator = t2.id
AND t.status IN ("running","starting","waiting") WHERE
) to_days( FROM_UNIXTIME( t.create_time / 1000 ))= to_days(now())
UNION ALL AND t.project_id IN
(SELECT t.id,'API' AS executionModule, t.report_type, ifnull(t2.name,'LOCAL') AS actuator, t1.`name` AS
executor,t.create_time AS executionTime, ifnull(t.trigger_mode,'MANUAL') AS triggerMode
,ifnull(t.status,'Saved') AS executionStatus
FROM api_definition_exec_result t LEFT JOIN `user` t1 ON t.user_id = t1.id LEFT JOIN test_resource_pool t2 ON
t.actuator = t2.id
WHERE to_days(FROM_UNIXTIME(t.create_time/1000))= to_days(now()) AND t.project_id IN
<foreach collection="request.projects" item="id" separator="," open="(" close=")"> <foreach collection="request.projects" item="id" separator="," open="(" close=")">
#{id} #{id}
</foreach> </foreach>
@ -215,15 +232,17 @@
AND t.user_id = #{request.executor} AND t.user_id = #{request.executor}
</if> </if>
AND (t.integrated_report_id IS NULL OR t.integrated_report_id = 'null') AND (t.integrated_report_id IS NULL OR t.integrated_report_id = 'null')
AND t.status IN ("running","starting","waiting") AND t.status IN ("running","starting","pending")
) ) as apiTotal ,
UNION ALL (SELECT
(SELECT t.id,'PERFORMANCE' AS executionModule,'PERFORMANCE' AS report_type, ifnull(t2.name,'LOCAL') AS actuator, count( t.id )
t1.`name` AS executor,t.create_time AS executionTime, t.trigger_mode AS triggerMode ,t.`status` AS FROM
executionStatus load_test_report t
FROM load_test_report t LEFT JOIN `user` t1 ON t.user_id = t1.id LEFT JOIN test_resource_pool t2 ON LEFT JOIN `user` t1 ON t.user_id = t1.id
t.test_resource_pool_id = t2.id LEFT JOIN test_resource_pool t2 ON t.test_resource_pool_id = t2.id
WHERE to_days(FROM_UNIXTIME(t.create_time/1000))= to_days(now()) AND t.project_id IN WHERE
to_days(FROM_UNIXTIME( t.create_time / 1000 ))= to_days(now())
AND t.project_id IN
<foreach collection="request.projects" item="id" separator="," open="(" close=")"> <foreach collection="request.projects" item="id" separator="," open="(" close=")">
#{id} #{id}
</foreach> </foreach>
@ -243,9 +262,8 @@
<if test="request.executor != null and request.executor != ''"> <if test="request.executor != null and request.executor != ''">
AND t.user_id = #{request.executor} AND t.user_id = #{request.executor}
</if> </if>
AND t.status IN ("running","starting","waiting") AND t.status IN ("running","starting","pending")
) ) as perfTotal
)tt;
</select> </select>
<select id="checkActuator" resultType="java.lang.String" parameterType="java.lang.String"> <select id="checkActuator" resultType="java.lang.String" parameterType="java.lang.String">
@ -255,7 +273,7 @@
api_scenario_report api_scenario_report
WHERE WHERE
actuator =#{actuator} actuator =#{actuator}
AND `status` IN ('Running','Waiting') AND `status` IN ('Running','pending')
UNION ALL UNION ALL
@ -265,11 +283,11 @@
api_definition_exec_result api_definition_exec_result
WHERE WHERE
actuator = #{actuator} actuator = #{actuator}
AND `status` IN ('Running','Waiting') AND `status` IN ('Running','pending')
</select> </select>
<update id="stopScenario"> <update id="stopScenario">
UPDATE api_scenario_report SET status ='STOPPED' WHERE status IN ("running","starting","waiting") AND UPDATE api_scenario_report SET status ='STOPPED' WHERE status IN ("running","starting","pending") AND
project_id IN project_id IN
<foreach collection="request.projects" item="id" separator="," open="(" close=")"> <foreach collection="request.projects" item="id" separator="," open="(" close=")">
#{id} #{id}
@ -278,7 +296,7 @@
<update id="stopApi"> <update id="stopApi">
UPDATE api_definition_exec_result SET status ='STOPPED' WHERE status IN ("running","starting","waiting") AND UPDATE api_definition_exec_result SET status ='STOPPED' WHERE status IN ("running","starting","pending") AND
project_id IN project_id IN
<foreach collection="request.projects" item="id" separator="," open="(" close=")"> <foreach collection="request.projects" item="id" separator="," open="(" close=")">
#{id} #{id}

View File

@ -0,0 +1,5 @@
package io.metersphere.commons.constants;
public enum TaskCenterType {
API, SCENARIO, UI, PERF
}

View File

@ -1,15 +1,13 @@
package io.metersphere.task.controller; package io.metersphere.task.controller;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.metersphere.commons.utils.CronUtils; import io.metersphere.commons.utils.CronUtils;
import io.metersphere.commons.utils.PageUtils;
import io.metersphere.commons.utils.Pager; import io.metersphere.commons.utils.Pager;
import io.metersphere.dto.TaskInfoResult; import io.metersphere.dto.TaskInfoResult;
import io.metersphere.request.BaseQueryRequest; import io.metersphere.request.BaseQueryRequest;
import io.metersphere.task.dto.TaskCenterDTO; import io.metersphere.task.dto.TaskCenterDTO;
import io.metersphere.task.dto.TaskCenterRequest; import io.metersphere.task.dto.TaskCenterRequest;
import io.metersphere.task.dto.TaskRequestDTO; import io.metersphere.task.dto.TaskRequestDTO;
import io.metersphere.task.dto.TaskStatisticsDTO;
import io.metersphere.task.service.TaskService; import io.metersphere.task.service.TaskService;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -28,8 +26,7 @@ public class TaskController {
request.setProjects(taskService.getOwnerProjectIds(request.getUserId())); request.setProjects(taskService.getOwnerProjectIds(request.getUserId()));
request.setGoPage(goPage); request.setGoPage(goPage);
request.setPageSize(pageSize); request.setPageSize(pageSize);
Page<Object> page = PageHelper.startPage(goPage, pageSize, true); return taskService.getTasks(request);
return PageUtils.setPageInfo(page, taskService.getTasks(request));
} }
@GetMapping("/case/{id}") @GetMapping("/case/{id}")
@ -43,7 +40,7 @@ public class TaskController {
} }
@PostMapping("/count/running") @PostMapping("/count/running")
public int getRunningTasks(@RequestBody TaskCenterRequest request) { public TaskStatisticsDTO getRunningTasks(@RequestBody TaskCenterRequest request) {
return taskService.getRunningTasks(request); return taskService.getRunningTasks(request);
} }

View File

@ -28,5 +28,9 @@ public class TaskCenterRequest {
private int pageSize; private int pageSize;
private String activeName;
private boolean hasLicense;
List<String> projects; List<String> projects;
} }

View File

@ -0,0 +1,17 @@
package io.metersphere.task.dto;
import lombok.Data;
@Data
public class TaskStatisticsDTO {
private int apiTotal;
private int scenarioTotal;
private int perfTotal;
private int uiTotal;
// 总量
private int total;
public int getTotal() {
return apiTotal + scenarioTotal + perfTotal + uiTotal;
}
}

View File

@ -1,9 +1,15 @@
package io.metersphere.task.service; package io.metersphere.task.service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.metersphere.base.mapper.ext.BaseInformationSchemaTableMapper; import io.metersphere.base.mapper.ext.BaseInformationSchemaTableMapper;
import io.metersphere.base.mapper.ext.BaseScheduleMapper; import io.metersphere.base.mapper.ext.BaseScheduleMapper;
import io.metersphere.base.mapper.ext.BaseTaskMapper; import io.metersphere.base.mapper.ext.BaseTaskMapper;
import io.metersphere.commons.constants.MicroServiceName; import io.metersphere.commons.constants.MicroServiceName;
import io.metersphere.commons.constants.TaskCenterType;
import io.metersphere.commons.utils.LogUtil;
import io.metersphere.commons.utils.PageUtils;
import io.metersphere.commons.utils.Pager;
import io.metersphere.dto.TaskInfoResult; import io.metersphere.dto.TaskInfoResult;
import io.metersphere.request.BaseQueryRequest; import io.metersphere.request.BaseQueryRequest;
import io.metersphere.service.BaseCheckPermissionService; import io.metersphere.service.BaseCheckPermissionService;
@ -11,6 +17,7 @@ import io.metersphere.service.MicroService;
import io.metersphere.task.dto.TaskCenterDTO; import io.metersphere.task.dto.TaskCenterDTO;
import io.metersphere.task.dto.TaskCenterRequest; import io.metersphere.task.dto.TaskCenterRequest;
import io.metersphere.task.dto.TaskRequestDTO; import io.metersphere.task.dto.TaskRequestDTO;
import io.metersphere.task.dto.TaskStatisticsDTO;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -56,17 +63,51 @@ public class TaskService {
return new ArrayList<>(userRelatedProjectIds); return new ArrayList<>(userRelatedProjectIds);
} }
public List<TaskCenterDTO> getTasks(TaskCenterRequest request) { public Pager<List<TaskCenterDTO>> getTasks(TaskCenterRequest request) {
Page<Object> page = PageHelper.startPage(request.getGoPage(), request.getPageSize(), true);
if (StringUtils.equals(request.getActiveName(), TaskCenterType.UI.name())) {
return PageUtils.setPageInfo(page, getUiTasks(request));
} else if (StringUtils.equals(request.getActiveName(), TaskCenterType.SCENARIO.name())) {
return PageUtils.setPageInfo(page, getScenarioTasks(request));
} else if (StringUtils.equals(request.getActiveName(), TaskCenterType.PERF.name())) {
return PageUtils.setPageInfo(page, getPerfTasks(request));
} else {
return PageUtils.setPageInfo(page, getApiTasks(request));
}
}
public List<TaskCenterDTO> getApiTasks(TaskCenterRequest request) {
if (CollectionUtils.isEmpty(request.getProjects())) { if (CollectionUtils.isEmpty(request.getProjects())) {
return new ArrayList<>(); return new ArrayList<>();
} }
return baseTaskMapper.getTasks(request,checkUiPermission()); return baseTaskMapper.getApiTasks(request);
} }
public int getRunningTasks(TaskCenterRequest request) { public List<TaskCenterDTO> getUiTasks(TaskCenterRequest request) {
if (CollectionUtils.isEmpty(request.getProjects())) {
return new ArrayList<>();
}
return baseTaskMapper.getUiTasks(request, checkUiPermission());
}
public List<TaskCenterDTO> getPerfTasks(TaskCenterRequest request) {
if (CollectionUtils.isEmpty(request.getProjects())) {
return new ArrayList<>();
}
return baseTaskMapper.getPerfTasks(request);
}
public List<TaskCenterDTO> getScenarioTasks(TaskCenterRequest request) {
if (CollectionUtils.isEmpty(request.getProjects())) {
return new ArrayList<>();
}
return baseTaskMapper.getScenarioTasks(request);
}
public TaskStatisticsDTO getRunningTasks(TaskCenterRequest request) {
request.setProjects(this.getOwnerProjectIds(request.getUserId())); request.setProjects(this.getOwnerProjectIds(request.getUserId()));
if (CollectionUtils.isEmpty(request.getProjects())) { if (CollectionUtils.isEmpty(request.getProjects())) {
return 0; return new TaskStatisticsDTO();
} }
return baseTaskMapper.getRunningTasks(request); return baseTaskMapper.getRunningTasks(request);
} }
@ -95,7 +136,7 @@ public class TaskService {
if (taskRequestMap.containsKey(PERF)) { if (taskRequestMap.containsKey(PERF)) {
microService.postForData(MicroServiceName.PERFORMANCE_TEST, "/performance/stop/batch", taskRequestMap.get(PERF)); microService.postForData(MicroServiceName.PERFORMANCE_TEST, "/performance/stop/batch", taskRequestMap.get(PERF));
} }
if(taskRequestMap.containsKey(UI)){ if (taskRequestMap.containsKey(UI)) {
microService.postForData(MicroServiceName.UI_TEST, "/ui/automation/stop/batch", reportIds); microService.postForData(MicroServiceName.UI_TEST, "/ui/automation/stop/batch", reportIds);
} }
} }
@ -115,13 +156,14 @@ public class TaskService {
} }
} }
private boolean checkUiPermission(){ private boolean checkUiPermission() {
try { try {
String uiScenarioReport = baseInformationSchemaTableMapper.checkExist(UI_SCENARIO_REPORT); String uiScenarioReport = baseInformationSchemaTableMapper.checkExist(UI_SCENARIO_REPORT);
if(StringUtils.isNotEmpty(uiScenarioReport)){ if (StringUtils.isNotEmpty(uiScenarioReport)) {
return true; return true;
} }
}catch (Exception e){ } catch (Exception e) {
LogUtil.error(e);
} }
return false; return false;
} }

View File

@ -1,9 +1,10 @@
package io.metersphere.websocket; package io.metersphere.websocket;
import io.metersphere.commons.utils.JSON;
import io.metersphere.commons.utils.LogUtil; import io.metersphere.commons.utils.LogUtil;
import io.metersphere.task.dto.TaskCenterRequest; import io.metersphere.task.dto.TaskCenterRequest;
import io.metersphere.task.dto.TaskStatisticsDTO;
import io.metersphere.task.service.TaskService; import io.metersphere.task.service.TaskService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.annotation.Resource; import javax.annotation.Resource;
@ -14,7 +15,7 @@ import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint("/websocket/task/running/{projectId}/{userId}") @ServerEndpoint("/websocket/task/running/{projectId}/{userId}/{hasLicense}")
@Component @Component
public class TaskCenterWebSocket { public class TaskCenterWebSocket {
private static TaskService taskService; private static TaskService taskService;
@ -29,9 +30,9 @@ public class TaskCenterWebSocket {
* 开启连接的操作 * 开启连接的操作
*/ */
@OnOpen @OnOpen
public void onOpen(@PathParam("projectId") String projectId, @PathParam("userId") String userId, Session session) { public void onOpen(@PathParam("projectId") String projectId, @PathParam("userId") String userId, @PathParam("hasLicense") boolean hasLicense, Session session) {
Timer timer = new Timer(true); Timer timer = new Timer(true);
TaskCenter task = new TaskCenter(session, projectId, userId); TaskCenter task = new TaskCenter(session, projectId, userId, hasLicense);
timer.schedule(task, 0, 10 * 1000); timer.schedule(task, 0, 10 * 1000);
refreshTasks.putIfAbsent(session, timer); refreshTasks.putIfAbsent(session, timer);
} }
@ -52,7 +53,7 @@ public class TaskCenterWebSocket {
* 推送消息 * 推送消息
*/ */
@OnMessage @OnMessage
public void onMessage(@PathParam("projectId") String projectId, @PathParam("userId") String userId, Session session, String message) { public void onMessage(@PathParam("projectId") String projectId, @PathParam("userId") String userId, @PathParam("hasLicense") boolean hasLicense, Session session, String message) {
int refreshTime = 10; int refreshTime = 10;
try { try {
refreshTime = Integer.parseInt(message); refreshTime = Integer.parseInt(message);
@ -63,7 +64,7 @@ public class TaskCenterWebSocket {
timer.cancel(); timer.cancel();
Timer newTimer = new Timer(true); Timer newTimer = new Timer(true);
newTimer.schedule(new TaskCenter(session, projectId, userId), 0, refreshTime * 1000L); newTimer.schedule(new TaskCenter(session, projectId, userId, hasLicense), 0, refreshTime * 1000L);
refreshTasks.put(session, newTimer); refreshTasks.put(session, newTimer);
} catch (Exception e) { } catch (Exception e) {
LogUtil.error(e.getMessage(), e); LogUtil.error(e.getMessage(), e);
@ -83,23 +84,24 @@ public class TaskCenterWebSocket {
private Session session; private Session session;
private TaskCenterRequest request; private TaskCenterRequest request;
TaskCenter(Session session, String projectId, String userId) { TaskCenter(Session session, String projectId, String userId, boolean hasLicense) {
this.session = session; this.session = session;
TaskCenterRequest request = new TaskCenterRequest(); TaskCenterRequest request = new TaskCenterRequest();
request.setProjectId(projectId); request.setProjectId(projectId);
request.setUserId(userId); request.setUserId(userId);
request.setHasLicense(hasLicense);
this.request = request; this.request = request;
} }
@Override @Override
public void run() { public void run() {
try { try {
int taskTotal = taskService.getRunningTasks(request); TaskStatisticsDTO task = taskService.getRunningTasks(request);
if (!session.isOpen()) { if (!session.isOpen()) {
return; return;
} }
session.getBasicRemote().sendText(taskTotal + StringUtils.EMPTY); session.getBasicRemote().sendText(JSON.toJSONString(task));
if (taskTotal == 0) { if (task.getTotal() == 0) {
session.close(); session.close();
} }
} catch (Exception e) { } catch (Exception e) {