refactor: 显示消息中心

This commit is contained in:
Captain.B 2021-08-18 17:00:42 +08:00 committed by 刘瑞斌
parent 720e52f911
commit 51db39b341
7 changed files with 437 additions and 452 deletions

View File

@ -10,7 +10,7 @@
<select id="listNotification" resultMap="io.metersphere.base.mapper.NotificationMapper.ResultMapWithBLOBs">
select * from notification
where receiver = #{receiver}
where receiver = #{receiver} and create_time &gt; (unix_timestamp() - 90 * 24 * 3600) * 1000
<if test='search != null and search != ""'>
and ( title like #{search} or content like #{search} )
</if>
@ -44,9 +44,7 @@
<if test="notification.status != null">
and status = #{notification.status}
</if>
<if test="notification.uuid != null">
and uuid = #{notification.uuid}
</if>
</select>

View File

@ -17,7 +17,6 @@ import io.metersphere.log.vo.OperatingLogDetails;
import io.metersphere.log.vo.StatusReference;
import io.metersphere.log.vo.system.SystemReference;
import io.metersphere.notice.domain.MessageDetail;
import io.metersphere.service.ProjectService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

View File

@ -48,7 +48,10 @@ public class NotificationService {
}
public int countNotification(Notification notification) {
notification.setReceiver(SessionUtils.getUser().getId());
if (StringUtils.isBlank(notification.getReceiver())) {
notification.setReceiver(SessionUtils.getUser().getId());
}
notification.setStatus(NotificationConstants.Status.UNREAD.name());
return extNotificationMapper.countNotification(notification);
}
@ -65,7 +68,13 @@ public class NotificationService {
if (StringUtils.isNotBlank(notification.getTitle())) {
search = "%" + notification.getTitle() + "%";
}
return extNotificationMapper.listNotification(search, SessionUtils.getUser().getId());
String receiver;
if (StringUtils.isBlank(notification.getReceiver())) {
receiver = SessionUtils.getUser().getId();
} else {
receiver = notification.getReceiver();
}
return extNotificationMapper.listNotification(search, receiver);
}
public List<Notification> listReadNotification(Notification notification) {

View File

@ -0,0 +1,107 @@
package io.metersphere.websocket;
import io.metersphere.base.domain.Notification;
import io.metersphere.commons.constants.NotificationConstants;
import io.metersphere.commons.utils.LogUtil;
import io.metersphere.notice.service.NotificationService;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint("/notification/count/{userId}")
@Component
public class NotificationWebSocket {
private static NotificationService notificationService;
private static ConcurrentHashMap<Session, Timer> refreshTasks = new ConcurrentHashMap<>();
@Resource
public void setNotificationService(NotificationService notificationService) {
NotificationWebSocket.notificationService = notificationService;
}
/**
* 开启连接的操作
*/
@OnOpen
public void onOpen(@PathParam("userId") String userId, Session session) {
Timer timer = new Timer(true);
NotificationCenter task = new NotificationCenter(session, userId);
timer.schedule(task, 0, 10 * 1000);
refreshTasks.putIfAbsent(session, timer);
}
/**
* 连接关闭的操作
*/
@OnClose
public void onClose(Session session) {
Timer timer = refreshTasks.get(session);
if (timer != null) {
timer.cancel();
refreshTasks.remove(session);
}
}
/**
* 推送消息
*/
@OnMessage
public void onMessage(@PathParam("userId") String userId, Session session, String message) {
int refreshTime = 10;
try {
refreshTime = Integer.parseInt(message);
} catch (Exception e) {
}
try {
Timer timer = refreshTasks.get(session);
timer.cancel();
Timer newTimer = new Timer(true);
newTimer.schedule(new NotificationCenter(session, userId), 0, refreshTime * 1000L);
refreshTasks.put(session, newTimer);
} catch (Exception e) {
LogUtil.error(e.getMessage(), e);
}
}
/**
* 出错的操作
*/
@OnError
public void onError(Throwable error) {
System.out.println(error);
error.printStackTrace();
}
public static class NotificationCenter extends TimerTask {
private Session session;
private String userId;
NotificationCenter(Session session, String userId) {
this.session = session;
this.userId = userId;
}
@Override
public void run() {
try {
if (!session.isOpen()) {
return;
}
Notification notification = new Notification();
notification.setReceiver(userId);
notification.setStatus(NotificationConstants.Status.UNREAD.name());
int count = notificationService.countNotification(notification);
session.getBasicRemote().sendText(count + "");
} catch (Exception e) {
LogUtil.error(e.getMessage(), e);
}
}
}
}

View File

@ -17,7 +17,7 @@
<ms-language-switch :color="color"/>
<ms-header-org-ws :color="color"/>
<ms-task-center :color="color"/>
<ms-notice-center :color="color"/>
<ms-notification :color="color"/>
</el-col>
</el-row>
@ -37,7 +37,7 @@ import {hasLicense, saveLocalStorage, setColor, setDefaultTheme} from "@/common/
import {registerRequestHeaders} from "@/common/js/ajax";
import {ORIGIN_COLOR} from "@/common/js/constants";
import MsTaskCenter from "@/business/components/task/TaskCenter";
import MsNoticeCenter from "@/business/components/notice/NoticeCenter";
import MsNotification from "@/business/components/notice/Notification";
const requireComponent = require.context('@/business/components/xpack/', true, /\.vue$/);
const header = requireComponent.keys().length > 0 ? requireComponent("./license/LicenseMessage.vue") : {};
const display = requireComponent.keys().length > 0 ? requireComponent("./display/Display.vue") : {};
@ -183,7 +183,7 @@ export default {
}
},
components: {
MsNoticeCenter,
MsNotification,
MsTaskCenter,
MsLanguageSwitch,
MsUser,

View File

@ -1,442 +0,0 @@
<template>
<div>
<el-menu :unique-opened="true" class="header-user-menu align-right header-top-menu"
mode="horizontal"
:background-color="color"
text-color="#fff"
active-text-color="#fff">
<el-menu-item onselectstart="return false">
<el-tooltip effect="light">
<template v-slot:content>
<span>{{ $t('commons.notice_center') }}</span>
</template>
<div @click="showNoticeCenter" v-if="runningTotal > 0">
<el-badge :value="runningTotal" class="item" type="primary">
<font-awesome-icon class="icon global focusing" :icon="['fas', 'bell']"/>
</el-badge>
</div>
<font-awesome-icon @click="showNoticeCenter" class="icon global focusing" :icon="['fas', 'bell']" v-else/>
</el-tooltip>
</el-menu-item>
</el-menu>
<el-drawer :visible.sync="taskVisible" :destroy-on-close="true" direction="rtl"
:withHeader="true" :modal="false" :title="$t('commons.task_center')" size="600px"
custom-class="ms-drawer-task">
<div style="color: #2B415C;margin: 0px 20px 0px">
<el-form label-width="68px">
<el-row>
<el-col :span="8">
<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-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="8">
<el-form-item :label="$t('commons.status')" prop="status">
<el-select size="small" style="margin-right: 10px" v-model="condition.executionStatus" @change="init">
<el-option v-for="item in runStatus" :key="item.id" :value="item.id" :label="item.label"/>
</el-select>
</el-form-item>
</el-col>
<el-col :span="8">
<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">
<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-row>
</el-form>
</div>
<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,$event)">
<span><el-link type="primary">{{ getModeName(item.executionModule) }} </el-link>: {{
item.name
}} </span><br/>
<span>
执行器{{ item.actuator }} {{ item.executor }}
{{ item.executionTime | timestampFormatDate }}
{{ 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">
<span v-if="item.executionStatus && item.executionStatus.toLowerCase() === 'error'"
class="ms-task-error">
error
</span>
<span v-else-if="item.executionStatus && item.executionStatus.toLowerCase() === 'success'"
class="ms-task-success">
success
</span>
<span v-else>{{
item.executionStatus ? item.executionStatus.toLowerCase() : item.executionStatus
}}</span>
</el-col>
</el-row>
</el-card>
</div>
</div>
</el-drawer>
</div>
</template>
<script>
import MsDrawer from "../common/components/MsDrawer";
import {getCurrentProjectID, getCurrentUser, hasPermissions} from "@/common/js/utils";
import MsRequestResultTail from "../../components/api/definition/components/response/RequestResultTail";
export default {
name: "MsNoticeCenter",
components: {
MsDrawer,
MsRequestResultTail
},
inject: [
'reload'
],
data() {
return {
runningTotal: 0,
taskVisible: false,
result: {},
taskData: [],
response: {},
initEnd: false,
visible: false,
showType: "",
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: 'API'}
],
runStatus: [
{id: '', label: this.$t('api_test.definition.document.data_set.all')},
{id: 'Saved', label: 'Saved'},
{id: 'Starting', label: 'Starting'},
{id: 'Running', label: 'Running'},
{id: 'Reporting', label: 'Reporting'},
{id: 'Completed', label: 'Completed'},
{id: 'error', label: 'Error'},
{id: 'success', label: 'Success'}
],
condition: {triggerMode: "", executionStatus: ""},
maintainerOptions: [],
websocket: Object,
};
},
props: {
color: String
},
created() {
if (hasPermissions('PROJECT_API_SCENARIO:READ')) {
this.condition.executor = getCurrentUser().id;
}
},
watch: {
taskVisible(v) {
if (!v) {
this.close();
}
}
},
methods: {
format(item) {
return '';
},
getMaintainerOptions() {
this.$post('/user/project/member/tester/list', {projectId: getCurrentProjectID()}, response => {
this.maintainerOptions = response.data;
this.condition.executor = getCurrentUser().id;
});
},
initWebSocket() {
let protocol = "ws://";
if (window.location.protocol === 'https:') {
protocol = "wss://";
}
const uri = protocol + window.location.host + "/task/center/count/running/" + getCurrentProjectID();
this.websocket = new WebSocket(uri);
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) {
let taskTotal = e.data;
this.runningTotal = taskTotal;
this.initIndex++;
if (this.taskVisible && taskTotal > 0 && this.initEnd) {
setTimeout(() => {
this.initEnd = false;
this.init();
}, 3000);
}
},
onClose(e) {
},
showNoticeCenter() {
this.getTaskRunning();
this.getMaintainerOptions();
this.init();
this.taskVisible = true;
},
close() {
this.visible = false;
this.taskVisible = false;
this.showType = "";
if (this.websocket && this.websocket.close instanceof Function) {
this.websocket.close();
}
},
open() {
this.showNoticeCenter();
this.initIndex = 0;
},
getPercentage(status) {
if (status) {
status = status.toLowerCase();
if (status === "waiting") {
return 0;
}
if (status === 'saved' || status === 'completed' || status === 'success' || status === 'error') {
return 100;
}
}
return 60;
},
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, env) {
let status = row.executionStatus;
if (status) {
status = row.executionStatus.toLowerCase();
if (status === 'saved' || status === 'completed' || status === 'success' || status === 'error') {
this.taskVisible = false;
switch (row.executionModule) {
case "SCENARIO":
this.$router.push({
path: '/api/automation/report/view/' + row.id,
});
break;
case "PERFORMANCE":
this.$router.push({
path: '/performance/report/view/' + row.id,
});
break;
case "API":
this.getExecResult(row.id);
break;
}
} else {
this.$warning("正在运行中,请稍后查看");
}
}
},
getExecResult(reportId) {
if (reportId) {
let url = "/api/definition/report/get/" + reportId;
this.$get(url, response => {
if (response.data) {
let data = JSON.parse(response.data.content);
this.response = data;
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 === 'API') {
return this.$t('commons.trigger_mode.api');
}
if (mode === 'BATCH') {
return this.$t('api_test.automation.batch_execute');
}
return mode;
},
getTaskRunning() {
this.initWebSocket();
},
calculationRunningTotal() {
if (this.taskData) {
let total = 0;
this.taskData.forEach(item => {
if (this.getPercentage(item.executionStatus) !== 100) {
total++;
}
});
this.runningTotal = total;
}
},
init() {
if (this.showType === "CASE" || this.showType === "SCENARIO") {
return;
}
this.result.loading = true;
this.condition.projectId = getCurrentProjectID();
this.result = this.$post('/task/center/list', this.condition, response => {
this.taskData = response.data;
this.calculationRunningTotal();
this.initEnd = true;
});
},
initCaseHistory(id) {
this.result = this.$get('/task/center/case/' + id, response => {
this.taskData = response.data;
});
},
openHistory(id) {
this.initCaseHistory(id);
this.taskVisible = true;
this.showType = "CASE";
},
openScenarioHistory(id) {
this.result = this.$get('/task/center/scenario/' + id, response => {
this.taskData = response.data;
});
this.showType = "SCENARIO";
this.taskVisible = true;
}
}
};
</script>
<style>
.ms-drawer-task {
top: 42px !important;
}
</style>
<style scoped>
.el-icon-check {
color: #44b349;
margin-left: 10px;
}
.report-container {
height: calc(100vh - 180px);
min-height: 600px;
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: 10px;
}
.ms-card-task >>> .el-card__body {
padding: 10px;
}
.global {
color: #fff;
}
.header-top-menu {
height: 40px;
line-height: 40px;
color: inherit;
}
.header-top-menu.el-menu--horizontal > li {
height: 40px;
line-height: 40px;
color: inherit;
}
.header-top-menu.el-menu--horizontal > li.el-submenu > * {
height: 39px;
line-height: 40px;
color: inherit;
}
.header-top-menu.el-menu--horizontal > li.is-active {
background: var(--color_shallow) !important;
}
.ms-card-task:hover {
cursor: pointer;
border-color: #783887;
}
/deep/ .el-progress-bar {
padding-right: 20px;
}
/deep/ .el-menu-item {
padding-left: 0;
padding-right: 0;
}
/deep/ .el-badge__content.is-fixed {
top: 25px;
}
/deep/ .el-badge__content {
border-radius: 10px;
height: 10px;
line-height: 10px;
}
.item {
margin-right: 10px;
}
.ms-task-error {
color: #F56C6C;
}
.ms-task-success {
color: #67C23A;
}
</style>

View File

@ -0,0 +1,314 @@
<template>
<div>
<el-menu :unique-opened="true" class="header-user-menu align-right header-top-menu"
mode="horizontal"
:background-color="color"
text-color="#fff"
active-text-color="#fff">
<el-menu-item onselectstart="return false">
<el-tooltip effect="light">
<template v-slot:content>
<span>{{ $t('commons.notice_center') }}</span>
</template>
<div @click="showNoticeCenter" v-if="runningTotal > 0">
<el-badge is-dot class="item" type="danger">
<font-awesome-icon class="icon global focusing" :icon="['fas', 'bell']"/>
</el-badge>
</div>
<font-awesome-icon @click="showNoticeCenter" class="icon global focusing" :icon="['fas', 'bell']" v-else/>
</el-tooltip>
</el-menu-item>
</el-menu>
<el-drawer :visible.sync="taskVisible" :destroy-on-close="true" direction="rtl"
:withHeader="true" :modal="false" :title="$t('commons.notice_center')" size="600px"
custom-class="ms-drawer-task">
<div style="margin: 0px 20px 0px">
<el-tabs :active-name="activeName">
<!-- <el-tab-pane label="@提到我的" name="mentionedMe">-->
<!-- </el-tab-pane>-->
<el-tab-pane label="系统通知" name="systemNotice">
<div style="padding-left: 320px; padding-bottom: 5px; width: 100%">
<span style="color: gray; padding-right: 10px">({{ totalCount }} 条消息)</span>
<el-dropdown @command="handleCommand" style="padding-right: 10px">
<span class="el-dropdown-link">
{{ goPage }}/{{ totalPage }}<i class="el-icon-arrow-down el-icon--right"></i>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item v-for="i in totalPage" :key="i" :command="i">{{ i }}</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<el-button icon="el-icon-arrow-left" size="mini" :disabled="goPage === 1" @click="prevPage"/>
<el-button icon="el-icon-arrow-right" size="mini" :disabled="goPage === totalPage" @click="nextPage"/>
</div>
<div class="report-container">
<div v-for="item in taskData" :key="item.id" style="margin-bottom: 5px">
<el-card class="ms-card-task">
<el-row type="flex" justify="space-between">
<el-col :span="12">
{{ item.title }}
</el-col>
<el-col :span="6">
{{ item.createTime | timestampFormatDate }}
</el-col>
</el-row>
<span>
{{ item.content }}
</span>
<br/>
<el-row>
</el-row>
</el-card>
</div>
</div>
<div style="color: black; padding-top: 50px; text-align: center">
- 仅显示最近3个月的站内消息 -
</div>
</el-tab-pane>
</el-tabs>
</div>
</el-drawer>
</div>
</template>
<script>
import MsDrawer from "../common/components/MsDrawer";
import {getCurrentProjectID} from "@/common/js/utils";
import MsRequestResultTail from "../../components/api/definition/components/response/RequestResultTail";
import MsTipButton from "@/business/components/common/components/MsTipButton";
export default {
name: "MsNotification",
components: {
MsTipButton,
MsDrawer,
MsRequestResultTail
},
inject: [
'reload'
],
data() {
return {
runningTotal: 0,
taskVisible: false,
result: {},
taskData: [],
response: {},
initEnd: false,
visible: false,
showType: "",
maintainerOptions: [],
websocket: Object,
activeName: 'systemNotice',
pageSize: 20,
goPage: 1,
totalPage: 0,
totalCount: 0,
};
},
props: {
color: String
},
created() {
this.init();
},
watch: {
taskVisible(v) {
if (!v) {
this.close();
}
}
},
methods: {
initWebSocket() {
let protocol = "ws://";
if (window.location.protocol === 'https:') {
protocol = "wss://";
}
const uri = protocol + window.location.host + "/notification/count/" + getCurrentProjectID();
this.websocket = new WebSocket(uri);
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) {
let taskTotal = e.data;
this.runningTotal = taskTotal;
this.initIndex++;
if (this.taskVisible && taskTotal > 0 && this.initEnd) {
setTimeout(() => {
this.initEnd = false;
this.init();
}, 3000);
}
},
onClose(e) {
},
showNoticeCenter() {
this.getTaskRunning();
this.init();
this.readAll();
this.taskVisible = true;
},
close() {
this.visible = false;
this.taskVisible = false;
this.showType = "";
if (this.websocket && this.websocket.close instanceof Function) {
this.websocket.close();
}
},
open() {
this.showNoticeCenter();
this.initIndex = 0;
},
init() {
this.result.loading = true;
this.result = this.$post('/notification/list/all/' + this.goPage + '/' + this.pageSize, {}, response => {
this.taskData = response.data.listObject;
this.totalPage = response.data.pageCount;
this.totalCount = response.data.itemCount;
this.calculationRunningTotal();
this.initEnd = true;
});
},
handleCommand(i) {
this.goPage = i;
this.init();
},
readAll() {
this.$get('/notification/read/all');
},
getTaskRunning() {
this.initWebSocket();
},
calculationRunningTotal() {
if (this.taskData) {
this.runningTotal = this.taskData.filter(t => t.status === 'UNREAD').length;
}
},
prevPage() {
if (this.goPage < 1) {
this.goPage = 1;
} else {
this.goPage--;
}
this.init();
},
nextPage() {
if (this.goPage > this.totalPage) {
this.goPage = this.totalPage;
} else {
this.goPage++;
}
this.init();
}
}
};
</script>
<style>
.ms-drawer-task {
top: 42px !important;
}
</style>
<style scoped>
.el-icon-check {
color: #44b349;
margin-left: 10px;
}
.report-container {
height: calc(100vh - 180px);
min-height: 600px;
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: 10px;
}
.ms-card-task >>> .el-card__body {
padding: 10px;
}
.global {
color: #fff;
}
.header-top-menu {
height: 40px;
line-height: 40px;
color: inherit;
}
.header-top-menu.el-menu--horizontal > li {
height: 40px;
line-height: 40px;
color: inherit;
}
.header-top-menu.el-menu--horizontal > li.el-submenu > * {
height: 39px;
line-height: 40px;
color: inherit;
}
.header-top-menu.el-menu--horizontal > li.is-active {
background: var(--color_shallow) !important;
}
.ms-card-task:hover {
cursor: pointer;
border-color: #783887;
}
/deep/ .el-menu-item {
padding-left: 0;
padding-right: 0;
}
/deep/ .el-badge__content.is-fixed {
top: 25px;
}
/deep/ .el-badge__content {
border-radius: 10px;
/*height: 10px;*/
/*line-height: 10px;*/
}
.item {
margin-right: 10px;
}
.ms-task-error {
color: #F56C6C;
}
.ms-task-success {
color: #67C23A;
}
</style>