style and refactor: 分离出一期二期代码, 并针对二期代码做出重构, token中添加了hospitalId相关字段

This commit is contained in:
republicline 2024-08-27 17:31:17 +08:00
parent 1585ca80e5
commit 2da508646e
107 changed files with 2580 additions and 640 deletions

View File

@ -1,19 +1,12 @@
package com.rax.auth.support.base; package com.rax.auth.support.base;
import cn.hutool.core.codec.Base64;
import cn.hutool.extra.spring.SpringUtil; import cn.hutool.extra.spring.SpringUtil;
import com.rax.admin.api.entity.SysOauthClientDetails;
import com.rax.admin.api.feign.RemoteClientDetailsService; import com.rax.admin.api.feign.RemoteClientDetailsService;
import com.rax.admin.api.feign.RemoteUserService;
import com.rax.common.core.constant.SecurityConstants;
import com.rax.common.core.util.R;
import com.rax.common.core.util.SpringContextHolder;
import com.rax.common.security.util.OAuth2ErrorCodesExpand; import com.rax.common.security.util.OAuth2ErrorCodesExpand;
import com.rax.common.security.util.ScopeException; import com.rax.common.security.util.ScopeException;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.springframework.context.support.MessageSourceAccessor; import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.*; import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
@ -31,12 +24,10 @@ import org.springframework.security.oauth2.server.authorization.token.OAuth2Toke
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator; import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.security.Principal; import java.security.Principal;
import java.time.Instant; import java.time.Instant;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier; import java.util.function.Supplier;
/** /**

View File

@ -1,8 +1,6 @@
package com.rax.auth.support.core; package com.rax.auth.support.core;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES; import cn.hutool.crypto.symmetric.AES;
import cn.hutool.extra.spring.SpringUtil; import cn.hutool.extra.spring.SpringUtil;
import com.rax.common.core.constant.SecurityConstants; import com.rax.common.core.constant.SecurityConstants;
@ -28,7 +26,6 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.authentication.www.BasicAuthenticationConverter; import org.springframework.security.web.authentication.www.BasicAuthenticationConverter;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.SecretKeySpec;

View File

@ -1,7 +1,6 @@
package com.rax.auth.support.password; package com.rax.auth.support.password;
import com.rax.admin.api.feign.RemoteClientDetailsService; import com.rax.admin.api.feign.RemoteClientDetailsService;
import com.rax.admin.api.feign.RemoteUserService;
import com.rax.auth.support.base.OAuth2ResourceOwnerBaseAuthenticationProvider; import com.rax.auth.support.base.OAuth2ResourceOwnerBaseAuthenticationProvider;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;

View File

@ -2,11 +2,11 @@ package com.rax.common.log.aspect;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.rax.common.core.util.SpringContextHolder; import com.rax.common.core.util.SpringContextHolder;
import com.rax.common.log.annotation.SysLog;
import com.rax.common.log.event.SysLogEvent; import com.rax.common.log.event.SysLogEvent;
import com.rax.common.log.event.SysLogEventSource; import com.rax.common.log.event.SysLogEventSource;
import com.rax.common.log.util.LogTypeEnum; import com.rax.common.log.util.LogTypeEnum;
import com.rax.common.log.util.SysLogUtils; import com.rax.common.log.util.SysLogUtils;
import com.rax.common.log.annotation.SysLog;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows; import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;

View File

@ -18,8 +18,8 @@ package com.rax.common.mybatis;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.rax.common.mybatis.plugins.RaxPaginationInnerInterceptor;
import com.rax.common.mybatis.config.MybatisPlusMetaObjectHandler; import com.rax.common.mybatis.config.MybatisPlusMetaObjectHandler;
import com.rax.common.mybatis.plugins.RaxPaginationInnerInterceptor;
import com.rax.common.mybatis.resolver.SqlFilterArgumentResolver; import com.rax.common.mybatis.resolver.SqlFilterArgumentResolver;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;

View File

@ -1,8 +1,8 @@
package com.rax.common.file; package com.rax.common.file;
import com.rax.common.file.core.FileProperties; import com.rax.common.file.core.FileProperties;
import com.rax.common.file.oss.OssAutoConfiguration;
import com.rax.common.file.local.LocalFileAutoConfiguration; import com.rax.common.file.local.LocalFileAutoConfiguration;
import com.rax.common.file.oss.OssAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;

View File

@ -1,8 +1,8 @@
package com.rax.common.file.oss; package com.rax.common.file.oss;
import com.rax.common.file.core.FileProperties; import com.rax.common.file.core.FileProperties;
import com.rax.common.file.oss.http.OssEndpoint;
import com.rax.common.file.core.FileTemplate; import com.rax.common.file.core.FileTemplate;
import com.rax.common.file.oss.http.OssEndpoint;
import com.rax.common.file.oss.service.OssTemplate; import com.rax.common.file.oss.service.OssTemplate;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;

View File

@ -19,6 +19,7 @@ package com.rax.common.security.service;
import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Getter; import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion; import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.User;
@ -26,6 +27,7 @@ import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
@ -59,6 +61,14 @@ public class RaxUser extends User implements OAuth2AuthenticatedPrincipal {
@JsonSerialize(using = ToStringSerializer.class) @JsonSerialize(using = ToStringSerializer.class)
private final Long hospitalId; private final Long hospitalId;
/**
* 角色Code集合
*/
@Getter
@Setter
@JsonSerialize(using = ToStringSerializer.class)
private List<String> roleCodeList;
/** /**
* 手机号 * 手机号
*/ */
@ -68,10 +78,11 @@ public class RaxUser extends User implements OAuth2AuthenticatedPrincipal {
@Getter @Getter
private final String chineseName; private final String chineseName;
public RaxUser(Long id, Long deptId, Long hospitalId, String username, String password, String phone, boolean enabled, public RaxUser(Long id, Long deptId, Long hospitalId, String username, String password, String phone,List<String> roleCodeList,boolean enabled,
boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, String chineseName, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, String chineseName,
Collection<? extends GrantedAuthority> authorities) { Collection<? extends GrantedAuthority> authorities) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
this.roleCodeList = roleCodeList;
this.id = id; this.id = id;
this.deptId = deptId; this.deptId = deptId;
this.hospitalId = hospitalId; this.hospitalId = hospitalId;

View File

@ -67,7 +67,7 @@ public interface RaxUserDetailsService extends UserDetailsService, Ordered {
// 构造security用户 // 构造security用户
return new RaxUser(user.getUserId(), user.getDeptId(), user.getHospitalId(), user.getUsername(), return new RaxUser(user.getUserId(), user.getDeptId(), user.getHospitalId(), user.getUsername(),
SecurityConstants.BCRYPT + user.getPassword(), user.getPhone(), true, true, true, SecurityConstants.BCRYPT + user.getPassword(), user.getPhone(),info.getRoleCodeList(), true, true, true,
StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL), user.getName(), authorities); StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL), user.getName(), authorities);
} }

View File

@ -29,7 +29,6 @@ import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager; import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
/** /**
* 用户详细信息 * 用户详细信息

View File

@ -17,8 +17,8 @@
package com.rax.common.security.util; package com.rax.common.security.util;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.rax.common.security.service.RaxUser;
import com.rax.common.core.constant.SecurityConstants; import com.rax.common.core.constant.SecurityConstants;
import com.rax.common.security.service.RaxUser;
import lombok.experimental.UtilityClass; import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
@ -83,4 +83,13 @@ public class SecurityUtils {
return roleIds; return roleIds;
} }
/**
* 判断用户的角色标识信息
*/
public Boolean hasRoleCode(String roleCode) {
Authentication authentication = getAuthentication();
RaxUser user = getUser(authentication);
List<String> roleCodeList = user.getRoleCodeList();
return roleCodeList.contains(roleCode);
}
} }

View File

@ -16,8 +16,8 @@
package com.rax.common.swagger.annotation; package com.rax.common.swagger.annotation;
import com.rax.common.swagger.config.OpenAPIDefinitionImportSelector;
import com.rax.common.core.factory.YamlPropertySourceFactory; import com.rax.common.core.factory.YamlPropertySourceFactory;
import com.rax.common.swagger.config.OpenAPIDefinitionImportSelector;
import com.rax.common.swagger.support.SwaggerProperties; import com.rax.common.swagger.support.SwaggerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;

View File

@ -18,10 +18,6 @@ package com.rax.common.xss;
import com.rax.common.xss.config.RaxXssProperties; import com.rax.common.xss.config.RaxXssProperties;
import com.rax.common.xss.core.*; import com.rax.common.xss.core.*;
import com.rax.common.xss.core.DefaultXssCleaner;
import com.rax.common.xss.core.FormXssClean;
import com.rax.common.xss.core.JacksonXssClean;
import com.rax.common.xss.core.XssCleaner;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;

View File

@ -16,9 +16,9 @@
package com.rax.common.xss.core; package com.rax.common.xss.core;
import com.rax.common.core.util.SpringContextHolder;
import com.rax.common.xss.config.RaxXssProperties; import com.rax.common.xss.config.RaxXssProperties;
import com.rax.common.xss.utils.XssUtil; import com.rax.common.xss.utils.XssUtil;
import com.rax.common.core.util.SpringContextHolder;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import java.io.IOException; import java.io.IOException;

View File

@ -2,6 +2,7 @@ package com.rax.excel.aop;
import com.rax.excel.annotation.ResponseExcel; import com.rax.excel.annotation.ResponseExcel;
import com.rax.excel.handler.SheetWriteHandler; import com.rax.excel.handler.SheetWriteHandler;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter; import org.springframework.core.MethodParameter;
@ -10,7 +11,6 @@ import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler; import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.method.support.ModelAndViewContainer;
import jakarta.servlet.http.HttpServletResponse;
import java.util.List; import java.util.List;
/** /**

View File

@ -4,7 +4,6 @@ import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder; import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.rax.excel.annotation.ResponseExcel; import com.rax.excel.annotation.ResponseExcel;
import com.rax.excel.head.HeadGenerator; import com.rax.excel.head.HeadGenerator;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
/** /**

View File

@ -1,7 +1,6 @@
package com.rax.excel.handler; package com.rax.excel.handler;
import com.rax.excel.annotation.ResponseExcel; import com.rax.excel.annotation.ResponseExcel;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
/** /**

View File

@ -9,7 +9,9 @@ import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@RequestMapping("/dailyPlan") @RequestMapping("/dailyPlan")

View File

@ -1,6 +1,5 @@
package com.rax.dailyplan.dto; package com.rax.dailyplan.dto;
import com.baomidou.mybatisplus.annotation.*;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data; import lombok.Data;

View File

@ -5,7 +5,6 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data; import lombok.Data;
import java.io.Serializable; import java.io.Serializable;
import java.sql.Timestamp;
@Data @Data
@Schema(description = "日常计划") @Schema(description = "日常计划")

View File

@ -5,7 +5,6 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rax.common.core.util.R; import com.rax.common.core.util.R;
import com.rax.common.security.service.RaxUser; import com.rax.common.security.service.RaxUser;
import com.rax.common.security.util.SecurityUtils;
import com.rax.dailyplan.dto.DailyPlanDTO; import com.rax.dailyplan.dto.DailyPlanDTO;
import com.rax.dailyplan.entity.DailyPlan; import com.rax.dailyplan.entity.DailyPlan;
import com.rax.dailyplan.mapper.DailyPlanMapper; import com.rax.dailyplan.mapper.DailyPlanMapper;

View File

@ -51,4 +51,17 @@ public class UserDTO extends SysUser {
@Schema(description = "随机值") @Schema(description = "随机值")
private String randomStr; private String randomStr;
@Override
public String toString() {
return "UserDTO{" +
"userId=" + getUserId() + '\'' +
", username='" + getUsername() + '\'' +
"role=" + role +
", deptId=" + deptId +
", post=" + post +
", newpassword1='" + newpassword1 + '\'' +
", code='" + code + '\'' +
", randomStr='" + randomStr + '\'' +
'}';
}
} }

View File

@ -5,6 +5,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data; import lombok.Data;
import java.io.Serializable; import java.io.Serializable;
import java.util.List;
/** /**
* @author lengleng * @author lengleng
@ -32,4 +33,10 @@ public class UserInfo implements Serializable {
@Schema(description = "角色标识集合") @Schema(description = "角色标识集合")
private Long[] roles; private Long[] roles;
/**
* 角色Code集合
*/
@Schema(description = "角色Code集合")
private List<String> roleCodeList;
} }

View File

@ -132,4 +132,14 @@ public class UserVO implements Serializable {
@Schema(description = "邮箱") @Schema(description = "邮箱")
private String email; private String email;
/**
* 所属医院相关信息
*/
private String hospitalName;
/**
* 医院ID
*/
private Long hospitalId;
} }

View File

@ -5,6 +5,9 @@ import com.rax.common.swagger.annotation.EnableRaxDoc;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.scheduling.annotation.EnableScheduling;
/** /**
* @author lengleng * @author lengleng
@ -15,7 +18,13 @@ import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
*/ */
@EnableRaxDoc(value = "admin") @EnableRaxDoc(value = "admin")
@EnableRaxResourceServer @EnableRaxResourceServer
@EnableScheduling // 开启定时任务 -> 清除日志相关内容
@SpringBootApplication(exclude = MongoAutoConfiguration.class) @SpringBootApplication(exclude = MongoAutoConfiguration.class)
@ComponentScan(
basePackages = {"com.rax"},
excludeFilters = {
@ComponentScan.Filter(type = FilterType.REGEX, pattern = "com.rax.vital.v1.*")
})
public class RaxAdminApplication { public class RaxAdminApplication {
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -14,7 +14,6 @@ import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;

View File

@ -8,6 +8,8 @@ import com.rax.admin.api.vo.SysMessageVO;
import com.rax.admin.service.SysHospitalService; import com.rax.admin.service.SysHospitalService;
import com.rax.admin.service.SysMessageService; import com.rax.admin.service.SysMessageService;
import com.rax.common.core.util.R; import com.rax.common.core.util.R;
import com.rax.common.security.service.RaxUser;
import com.rax.common.security.util.SecurityUtils;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
@ -41,13 +43,13 @@ public class SysMessageController {
@PostMapping("/page") @PostMapping("/page")
public R page(Page page, SysMessageVO sysMessageVO) { public R page(Page page, SysMessageVO sysMessageVO) {
String hospitalId = sysHospitalService.getCurrentHospital(); RaxUser user = SecurityUtils.getUser();
return R.ok(sysMessageService.page(page, Wrappers.<SysMessage>lambdaQuery() return R.ok(sysMessageService.page(page, Wrappers.<SysMessage>lambdaQuery()
.eq(StringUtils.hasText(sysMessageVO.getCategory()), .eq(StringUtils.hasText(sysMessageVO.getCategory()),
SysMessage::getCategory, SysMessage::getCategory,
sysMessageVO.getCategory()) sysMessageVO.getCategory())
.eq(SysMessage::getDelFlag, 0) .eq(SysMessage::getDelFlag, 0)
.eq(SysMessage::getHospital, hospitalId) .eq(SysMessage::getHospital, user.getHospitalId())
.like(StringUtils.hasText(sysMessageVO.getMessage()), .like(StringUtils.hasText(sysMessageVO.getMessage()),
SysMessage::getMessage, SysMessage::getMessage,
sysMessageVO.getMessage())) sysMessageVO.getMessage()))

View File

@ -39,6 +39,8 @@ public class SysRoleController {
private final SysRoleService sysRoleService; private final SysRoleService sysRoleService;
/** /**
* 通过ID查询角色信息 * 通过ID查询角色信息
* @param id ID * @param id ID

View File

@ -1,10 +1,10 @@
package com.rax.admin.controller; package com.rax.admin.controller;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rax.admin.api.dto.UserDTO; import com.rax.admin.api.dto.UserDTO;
import com.rax.admin.api.entity.SysRole;
import com.rax.admin.api.entity.SysUser; import com.rax.admin.api.entity.SysUser;
import com.rax.admin.api.vo.UserExcelVO; import com.rax.admin.api.vo.UserExcelVO;
import com.rax.admin.service.SysHospitalService; import com.rax.admin.service.SysHospitalService;
@ -29,8 +29,6 @@ import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -72,33 +70,25 @@ public class SysUserController {
.lambda() .lambda()
.eq(StrUtil.isNotBlank(username), SysUser::getUsername, username) .eq(StrUtil.isNotBlank(username), SysUser::getUsername, username)
.eq(StrUtil.isNotBlank(phone), SysUser::getPhone, phone)); .eq(StrUtil.isNotBlank(phone), SysUser::getPhone, phone));
SysUser user1 = userService.getOne(Wrappers.<SysUser>query()
.lambda()
.eq(StrUtil.isNotBlank(username), SysUser::getUsername, username)
.eq(StrUtil.isNotBlank(phone), SysUser::getPhone, phone));
if (user == null) { if (user == null) {
if (user1 == null) {
return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_USERINFO_EMPTY, username)); return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_USERINFO_EMPTY, username));
} else { } else {
List<SysRole> rolesByUserId = roleService.findRolesByUserId(user1.getUserId()); // List<SysRole> rolesByUserId = roleService.findRolesByUserId(user.getUserId());
boolean isAdmin = false; // boolean isAdmin = false;
for (SysRole role: rolesByUserId) { // for (SysRole role : rolesByUserId) {
if (ADMIN_ROLE_CODE.equals(role.getRoleCode())) { // if (ADMIN_ROLE_CODE.equals(role.getRoleCode())) {
isAdmin = true; // isAdmin = true;
break; // break;
} // }
} // }
if (isAdmin) { // if (isAdmin) {
sysHospitalService.changeHospital("", String.valueOf(user1.getUserId())); // sysHospitalService.changeHospital("", String.valueOf(user.getUserId()));
return R.ok(userService.findUserInfo(user1)); // } else {
} else { // sysHospitalService.changeHospital(String.valueOf(user.getHospitalId()), String.valueOf(user.getUserId()));
return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_USERINFO_EMPTY, username)); // }
}
}
}
sysHospitalService.changeHospital(String.valueOf(user.getHospitalId()), String.valueOf(user.getUserId()));
return R.ok(userService.findUserInfo(user)); return R.ok(userService.findUserInfo(user));
} }
}
/** /**
* 获取当前用户全部信息 * 获取当前用户全部信息
@ -192,28 +182,20 @@ public class SysUserController {
} }
/** /**
* 分页查询用户 * 分页查询用户信息, 查询当前医院, 如果当前医院为null且具有管理员权限, 则查询所有
* * 只能查询到当前医院的医生信息.
* @param page 参数集 * @param page 参数集
* @param userDTO 查询参数列表 * @param userDTO 查询参数列表
* @return 用户集合 * @return 用户集合
*/ */
@PostMapping("/page") @PostMapping("/page")
public R getUserPage(Page page, UserDTO userDTO) { public R getUserPage(Page page, UserDTO userDTO) {
String hospitalId = sysHospitalService.getCurrentHospital(); RaxUser user = SecurityUtils.getUser();
if (StringUtils.hasText(hospitalId) && !"null".equals(hospitalId)) { if (ObjectUtil.isNotNull(user.getHospitalId())) {
userDTO.setHospitalId(Long.valueOf(hospitalId)); userDTO.setHospitalId(user.getHospitalId());
} else { } else {
RaxUser raxUser = (RaxUser) SecurityUtils.getAuthentication().getPrincipal(); Boolean adminRole = SecurityUtils.hasRoleCode(ADMIN_ROLE_CODE);
List<SysRole> rolesByUserId = roleService.findRolesByUserId(raxUser.getId()); if (!adminRole) {
boolean isAdmin = false;
for (SysRole role: rolesByUserId) {
if (ADMIN_ROLE_CODE.equals(role.getRoleCode())) {
isAdmin = true;
break;
}
}
if (!isAdmin) {
return R.ok(new Page<>()); return R.ok(new Page<>());
} }
} }
@ -222,7 +204,7 @@ public class SysUserController {
/** /**
* 分页查询用户 * 分页查询用户
* * 查询所有的用户信息, 属于系统后台管理功能
* @return 用户集合 * @return 用户集合
*/ */
@PostMapping("/list") @PostMapping("/list")

View File

@ -0,0 +1,11 @@
package com.rax.admin.immu;
/**
* project_name:remote-control-backend
* time:2024/8/27 16:42
*/
public record RoleRecord() {
public static final String ADMIN_ROLE_CODE = "ROLE_ADMIN";
public static final String SITE_ROLE_CODE = "ROLE_CHIEF";
}

View File

@ -1,6 +1,5 @@
package com.rax.admin.service; package com.rax.admin.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
import com.rax.admin.api.entity.SysMessage; import com.rax.admin.api.entity.SysMessage;
import com.rax.admin.api.vo.SysMessageVO; import com.rax.admin.api.vo.SysMessageVO;

View File

@ -5,16 +5,15 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rax.admin.api.dto.HospitalDTO; import com.rax.admin.api.dto.HospitalDTO;
import com.rax.admin.api.entity.SysHospital; import com.rax.admin.api.entity.SysHospital;
import com.rax.admin.api.entity.SysRole;
import com.rax.admin.mapper.SysHospitalMapper; import com.rax.admin.mapper.SysHospitalMapper;
import com.rax.admin.service.SysHospitalService; import com.rax.admin.service.SysHospitalService;
import com.rax.admin.service.SysRoleService; import com.rax.admin.service.SysRoleService;
import com.rax.common.core.constant.CacheConstants; import com.rax.common.core.constant.CacheConstants;
import com.rax.common.core.util.R; import com.rax.common.core.util.R;
import com.rax.common.security.service.RaxUser; import com.rax.common.security.service.RaxUser;
import com.rax.common.security.util.SecurityUtils;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -96,28 +95,21 @@ public class SysHospitalServiceImpl extends ServiceImpl<SysHospitalMapper, SysHo
@Override @Override
public List getMyHospitalList() { public List getMyHospitalList() {
RaxUser raxUser = (RaxUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Long hospitalId = SecurityUtils.getUser().getHospitalId();
List<SysRole> roleList = roleService.findRolesByUserId(raxUser.getId()); if (hospitalId != null) {
List<SysRole> adminRoleList = roleList.stream().filter(predicate -> ADMIN_ROLE_CODE.contains(predicate.getRoleCode())).toList(); List<SysHospital> oneHospitalList = this.lambdaQuery()
List sysHospitals = null; .eq(SysHospital::getId, hospitalId)
if (!adminRoleList.isEmpty()) { .list();
QueryWrapper<SysHospital> queryWrapper = new QueryWrapper<>(); return oneHospitalList;
queryWrapper.eq("del_flag", 0);
queryWrapper.orderByDesc("create_time");
queryWrapper.select(new String[]{"id", "name", "code", "status", "domain", "province", "city"});
sysHospitals = sysHospitalMapper.selectMaps(queryWrapper);
SysHospital hospital = new SysHospital();
hospital.setName("");
sysHospitals.add(0, hospital);
} else {
QueryWrapper<SysHospital> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("id", raxUser.getHospitalId());
queryWrapper.eq("del_flag", 0);
queryWrapper.orderByDesc("create_time");
queryWrapper.select(new String[]{"id", "name", "code", "status", "domain", "province", "city"});
sysHospitals = sysHospitalMapper.selectMaps(queryWrapper);
} }
return sysHospitals; if (SecurityUtils.hasRoleCode(ADMIN_ROLE_CODE)) {
List<SysHospital> list = this.lambdaQuery().list();
SysHospital sysHospital = new SysHospital();
sysHospital.setName("全部医院");
list.add(0,sysHospital);
return list;
}
return null;
} }
@Override @Override

View File

@ -1,25 +1,22 @@
package com.rax.admin.service.impl; package com.rax.admin.service.impl;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rax.admin.api.dto.SysLogDTO; import com.rax.admin.api.dto.SysLogDTO;
import com.rax.admin.api.entity.SysLog; import com.rax.admin.api.entity.SysLog;
import com.rax.admin.api.entity.SysRole; import com.rax.admin.immu.RoleRecord;
import com.rax.admin.api.entity.SysUser;
import com.rax.admin.mapper.SysLogMapper; import com.rax.admin.mapper.SysLogMapper;
import com.rax.admin.service.SysLogService; import com.rax.admin.service.SysLogService;
import com.rax.admin.service.SysRoleService; import com.rax.admin.service.SysRoleService;
import com.rax.admin.service.SysUserService; import com.rax.admin.service.SysUserService;
import com.rax.common.security.service.RaxUser; import com.rax.common.security.service.RaxUser;
import com.rax.common.security.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -43,48 +40,71 @@ public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> impleme
@Autowired @Autowired
private SysUserService userService; private SysUserService userService;
/**
* 三种情况
* 系统管理员可以查看全部的日志信息
* 站点管理员可以查看自己所属医院的日志信息
* 普通用户只能查看自己的日志信息
*/
@Override @Override
public Page getLogByPage(Page page, SysLogDTO sysLog) { public Page getLogByPage(Page page, SysLogDTO sysLog) {
RaxUser raxUser = (RaxUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); RaxUser user = SecurityUtils.getUser();
List<SysRole> roleList = roleService.findRolesByUserId(raxUser.getId()); List<String> roleCodeList = user.getRoleCodeList();
List<SysRole> adminRoleList = roleList.stream().filter(predicate -> ADMIN_ROLE_CODE.contains(predicate.getRoleCode())).toList(); if (roleCodeList.isEmpty()) {
List<SysRole> siteRoleList = roleList.stream().filter(predicate -> SITE_ROLE_CODE.contains(predicate.getRoleCode())).toList(); return null;
LambdaQueryWrapper<SysLog> wrapper = Wrappers.lambdaQuery();
if (StrUtil.isNotBlank(sysLog.getLogType())) {
wrapper.eq(SysLog::getLogType, sysLog.getLogType());
} }
// 获取当前日期时间
if (adminRoleList.isEmpty()) { LocalDateTime now = LocalDateTime.now();
if (siteRoleList.isEmpty()) { // 获取当月的第一天
wrapper.eq(SysLog::getCreateBy, raxUser.getName()); LocalDateTime firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());
} else { // 当月的最后一天
SysUser sysUser = userService.getById(raxUser.getId()); LocalDateTime lastDayOfMonth = now.with(TemporalAdjusters.lastDayOfMonth());
wrapper.eq(SysLog::getHospitalId, sysUser.getHospitalId()); if (roleCodeList.contains(RoleRecord.ADMIN_ROLE_CODE)) {
// 查看三十天的所有日志信息
List<SysLog> list = this.lambdaQuery()
.ge(SysLog::getCreateTime, firstDayOfMonth)
.le(SysLog::getCreateTime, lastDayOfMonth)
.orderByDesc(SysLog::getCreateTime).list();
Page<SysLog> logPage = new Page<>();
logPage.setRecords(list)
.setTotal(list.size());
return logPage;
} }
if (roleCodeList.contains(RoleRecord.SITE_ROLE_CODE)) {
// 查看自己所属医院的日志信息
List<SysLog> list = this.lambdaQuery()
.eq(SysLog::getHospitalId, user.getHospitalId())
.ge(SysLog::getCreateTime, firstDayOfMonth)
.le(SysLog::getCreateTime, lastDayOfMonth)
.orderByDesc(SysLog::getCreateTime).list();
Page<SysLog> logPage = new Page<>();
logPage.setRecords(list)
.setTotal(list.size());
return logPage;
} }
// 返回自己的日志信息
if (ArrayUtil.isNotEmpty(sysLog.getTimeInterval())) { List<SysLog> list = this.lambdaQuery()
wrapper.ge(SysLog::getCreateTime, sysLog.getTimeInterval()[0]) .eq(SysLog::getCreateBy, user.getName())
.le(SysLog::getCreateTime, sysLog.getTimeInterval()[1]); .ge(SysLog::getCreateTime, firstDayOfMonth)
} .le(SysLog::getCreateTime, lastDayOfMonth)
.orderByDesc(SysLog::getCreateTime).list();
wrapper.orderByDesc(SysLog::getCreateTime); Page<SysLog> logPage = new Page<>();
logPage.setRecords(list)
return baseMapper.selectPage(page, wrapper); .setTotal(list.size());
return logPage;
} }
/** /**
* 插入日志 * 插入日志
*
* @param sysLog 日志对象 * @param sysLog 日志对象
* @return true/false * @return true/false
*/ */
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public Boolean saveLog(SysLog sysLog) { public Boolean saveLog(SysLog sysLog) {
System.out.println("sysLog = " + sysLog); sysLog.setHospitalId(SecurityUtils.getUser().getHospitalId());
SysUser sysUser = userService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, sysLog.getCreateBy()));
sysLog.setHospitalId(sysUser.getHospitalId());
baseMapper.insert(sysLog); baseMapper.insert(sysLog);
return Boolean.TRUE; return Boolean.TRUE;
} }

View File

@ -24,11 +24,13 @@ import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.*; import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.stream.Collectors; import java.util.stream.Collectors;

View File

@ -14,6 +14,7 @@ import com.rax.admin.service.SysMessageUserService;
import com.rax.admin.service.SysUserService; import com.rax.admin.service.SysUserService;
import com.rax.common.core.util.R; import com.rax.common.core.util.R;
import com.rax.common.security.service.RaxUser; import com.rax.common.security.service.RaxUser;
import com.rax.common.security.util.SecurityUtils;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
@ -36,14 +37,15 @@ public class SysMessageServiceImpl extends ServiceImpl<SysMessageMapper, SysMess
@Override @Override
public R saveMessage(SysMessageVO sysMessageVO) { public R saveMessage(SysMessageVO sysMessageVO) {
String hospitalId = sysHospitalService.getCurrentHospital(); RaxUser user = SecurityUtils.getUser();
Long hospitalId = user.getHospitalId();
SysMessage sysMessage = new SysMessage(); SysMessage sysMessage = new SysMessage();
BeanUtils.copyProperties(sysMessageVO, sysMessage); BeanUtils.copyProperties(sysMessageVO, sysMessage);
RaxUser raxUser = (RaxUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); RaxUser raxUser = (RaxUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
sysMessage.setCreator(raxUser.getId()); sysMessage.setCreator(raxUser.getId());
SysUser sysUser = sysUserService.getById(raxUser.getId()); SysUser sysUser = sysUserService.getById(raxUser.getId());
sysMessage.setCreatorName(sysUser.getName()); sysMessage.setCreatorName(sysUser.getName());
sysMessage.setHospital(Long.valueOf(hospitalId)); sysMessage.setHospital(hospitalId);
sysMessage.setCreateTime(DateUtil.now()); sysMessage.setCreateTime(DateUtil.now());
sysMessage.setUpdateTime(DateUtil.now()); sysMessage.setUpdateTime(DateUtil.now());
boolean status = save(sysMessage); boolean status = save(sysMessage);

View File

@ -64,7 +64,7 @@ public class SysMobileServiceImpl implements SysMobileService {
String code = RandomUtil.randomNumbers(Integer.parseInt(SecurityConstants.CODE_SIZE)); String code = RandomUtil.randomNumbers(Integer.parseInt(SecurityConstants.CODE_SIZE));
log.debug("手机号生成验证码成功:{},{}", mobile, code); log.debug("手机号生成验证码成功:{},{}", mobile, code);
// 调用短信服务发送验证码 // 调用短信服务发送验证码
smsClient.sendCode(code, mobile); // smsClient.sendCode(code, mobile);
// 保存验证码到redis, 有效期60s // 保存验证码到redis, 有效期60s
redisTemplate.opsForValue() redisTemplate.opsForValue()
.set(CacheConstants.DEFAULT_CODE_KEY + mobile, code, SecurityConstants.CODE_TIME, TimeUnit.SECONDS); .set(CacheConstants.DEFAULT_CODE_KEY + mobile, code, SecurityConstants.CODE_TIME, TimeUnit.SECONDS);

View File

@ -3,7 +3,6 @@ package com.rax.admin.service.impl;
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
@ -18,6 +17,7 @@ import com.rax.common.core.constant.CacheConstants;
import com.rax.common.core.exception.ErrorCodes; import com.rax.common.core.exception.ErrorCodes;
import com.rax.common.core.util.MsgUtils; import com.rax.common.core.util.MsgUtils;
import com.rax.common.core.util.R; import com.rax.common.core.util.R;
import com.rax.common.security.util.SecurityUtils;
import com.rax.excel.vo.ErrorMessage; import com.rax.excel.vo.ErrorMessage;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Cacheable;
@ -26,10 +26,7 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
import java.util.Arrays; import java.util.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
@ -46,6 +43,8 @@ public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> impl
private SysRoleMenuService roleMenuService; private SysRoleMenuService roleMenuService;
private final String ROLE_ADMIN = "ROLE_ADMIN";
@Override @Override
public R saveRole(SysRole sysRole, String menuIds) { public R saveRole(SysRole sysRole, String menuIds) {
boolean saveStatus = save(sysRole); boolean saveStatus = save(sysRole);
@ -115,10 +114,22 @@ public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> impl
} }
public R getRoleTree(Page page, String roleName) { public R getRoleTree(Page page, String roleName) {
List roleTree = baseMapper.getRoleTree(page, roleName); List<Map> roleTree = baseMapper.getRoleTree(page, roleName);
Integer total = baseMapper.getTotal(roleName); Integer total = baseMapper.getTotal(roleName);
page.setRecords(roleTree); if (SecurityUtils.hasRoleCode(ROLE_ADMIN)) {
page.setTotal(total); page.setRecords(roleTree)
.setTotal(total);
}else {
List<Map> roleTreeFilter = new ArrayList<>();
for (Map map : roleTree) {
if (!ROLE_ADMIN.equals(map.get("roleCode"))) {
roleTreeFilter.add(map);
}
}
total-=1;
page.setRecords(roleTreeFilter)
.setTotal(total);
}
return R.ok(page); return R.ok(page);
} }

View File

@ -96,10 +96,16 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
sysUser.setDelFlag(CommonConstants.STATUS_NORMAL); sysUser.setDelFlag(CommonConstants.STATUS_NORMAL);
sysUser.setCreateBy(userDto.getUsername()); sysUser.setCreateBy(userDto.getUsername());
sysUser.setPassword(ENCODER.encode(userDto.getPassword())); sysUser.setPassword(ENCODER.encode(userDto.getPassword()));
String hosptital = sysHospitalService.getCurrentHospital(); // String hosptital = sysHospitalService.getCurrentHospital();
if (StringUtils.hasText(hosptital) && !"null".equals(hosptital)) { // if (StringUtils.hasText(hosptital) && !"null".equals(hosptital)) {
sysUser.setHospitalId(Long.valueOf(hosptital)); // sysUser.setHospitalId(Long.valueOf(hospitalId));
// }
Long hospitalId = SecurityUtils.getUser().getHospitalId();
if (hospitalId != null){
sysUser.setHospitalId(hospitalId);
} }
baseMapper.insert(sysUser); baseMapper.insert(sysUser);
// 保存用户岗位信息 // 保存用户岗位信息
Optional.ofNullable(userDto.getPost()).ifPresent(posts -> { Optional.ofNullable(userDto.getPost()).ifPresent(posts -> {
@ -141,13 +147,23 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
public UserInfo findUserInfo(SysUser sysUser) { public UserInfo findUserInfo(SysUser sysUser) {
UserInfo userInfo = new UserInfo(); UserInfo userInfo = new UserInfo();
userInfo.setSysUser(sysUser); userInfo.setSysUser(sysUser);
// 设置角色列表 ID // 设置角色列表 ID
List<Long> roleIds = sysRoleService.findRolesByUserId(sysUser.getUserId()) List<SysRole> roleList = sysRoleService.findRolesByUserId(sysUser.getUserId());
List<Long> roleIds = roleList
.stream() .stream()
.map(SysRole::getRoleId) .map(SysRole::getRoleId)
.collect(Collectors.toList()); .collect(Collectors.toList());
userInfo.setRoles(ArrayUtil.toArray(roleIds, Long.class)); userInfo.setRoles(ArrayUtil.toArray(roleIds, Long.class));
// 设置user的roleCodeList
List<String> roleCodeList = roleList.stream()
.map(SysRole::getRoleCode)
.toList();
userInfo.setRoleCodeList(roleCodeList);
// 设置权限列表menu.permission // 设置权限列表menu.permission
Set<String> permissions = new HashSet<>(); Set<String> permissions = new HashSet<>();
roleIds.forEach(roleId -> { roleIds.forEach(roleId -> {

View File

@ -1,4 +1,4 @@
package com.rax.vital.datasource; package com.rax.vital.common.datasource;
import lombok.Getter; import lombok.Getter;

View File

@ -1,4 +1,4 @@
package com.rax.vital.datasource; package com.rax.vital.common.datasource;
import com.mongodb.ConnectionString; import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings; import com.mongodb.MongoClientSettings;

View File

@ -1,4 +1,4 @@
package com.rax.vital.datasource; package com.rax.vital.common.datasource;
import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection; import com.alibaba.druid.pool.DruidPooledConnection;

View File

@ -1,4 +1,4 @@
package com.rax.vital.util; package com.rax.vital.common.util;

View File

@ -1,4 +1,4 @@
package com.rax.vital.util; package com.rax.vital.common.util;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;

View File

@ -1,4 +1,4 @@
package com.rax.vital.util; package com.rax.vital.common.util;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;

View File

@ -1,29 +0,0 @@
package com.rax.vital.handler;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;
public class MedicineHandlerV2 extends AbstractWebSocketHandler {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
super.afterConnectionEstablished(session);
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
super.handleMessage(session, message);
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
super.handleTransportError(session, exception);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
super.afterConnectionClosed(session, status);
}
}

View File

@ -1,4 +0,0 @@
package com.rax.vital.medicine.vo;
public class MedicineVO {
}

View File

@ -0,0 +1,56 @@
package com.rax.vital.v1.config;
import com.rax.vital.v1.handler.AddMedicineHandler;
import com.rax.vital.v1.handler.ChatHandler;
import com.rax.vital.v1.handler.MachineFeedbackHandler;
import com.rax.vital.v1.handler.MedicineHandler;
import com.rax.vital.v1.interceptor.WebSocketInterceptors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
@EnableWebSocket
@Configuration
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(medicineHandler(), "/rax/vitalSignsMedicine")
.addHandler(chatHandler(), "/rax/chatRoom")
.addHandler(addMedicineHandler(), "/rax/addMedicine")
.addHandler(machineFeedbackHandler(),"/rax/getMedicine")
.addInterceptors(new HttpSessionHandshakeInterceptor())
.addInterceptors(webSocketInterceptors())
.setAllowedOrigins("*");
}
@Bean
public WebSocketHandler medicineHandler() {
return new MedicineHandler();
}
@Bean
public WebSocketHandler chatHandler() {
return new ChatHandler();
}
@Bean
public WebSocketHandler addMedicineHandler() {
return new AddMedicineHandler();
}
@Bean
public WebSocketHandler machineFeedbackHandler() {
return new MachineFeedbackHandler();
}
@Bean
public HandshakeInterceptor webSocketInterceptors() {
return new WebSocketInterceptors();
}
}

View File

@ -1,6 +1,6 @@
package com.rax.vital.config; package com.rax.vital.v1.config;
import com.rax.vital.interceptor.WSChannelInterceptor; import com.rax.vital.v1.interceptor.WSChannelInterceptor;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration; import org.springframework.messaging.simp.config.ChannelRegistration;

View File

@ -1,13 +1,12 @@
package com.rax.vital.handler.mysql; package com.rax.vital.v1.handler;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.rax.vital.timer.VitalSignTimerWS; import com.rax.vital.common.util.GetHttpParamUtil;
import com.rax.vital.util.GetHttpParamUtil; import com.rax.vital.v1.timer.VitalSignTimerWS;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType; import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*; import org.springframework.web.socket.*;
import java.io.IOException; import java.io.IOException;

View File

@ -1,8 +1,8 @@
package com.rax.vital.handler.mysql; package com.rax.vital.v1.handler;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.rax.vital.medicine.service.ChatService; import com.rax.vital.common.util.GetHttpParamUtil;
import com.rax.vital.util.GetHttpParamUtil; import com.rax.vital.v1.medicine.service.ChatService;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
@ -11,8 +11,6 @@ import org.springframework.web.socket.*;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.Map; import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;

View File

@ -1,7 +1,7 @@
package com.rax.vital.handler.mysql; package com.rax.vital.v1.handler;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.rax.vital.timer.VitalSignTimerWS; import com.rax.vital.v1.timer.VitalSignTimerWS;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.web.socket.*; import org.springframework.web.socket.*;

View File

@ -1,20 +1,20 @@
package com.rax.vital.handler.mysql; package com.rax.vital.v1.handler;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.rax.vital.timer.VitalSignTimerWS; import com.rax.vital.common.util.GetHttpParamUtil;
import com.rax.vital.util.GetHttpParamUtil; import com.rax.vital.v1.timer.VitalSignTimerWS;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType; import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.web.socket.*; import org.springframework.web.socket.*;
import java.io.IOException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.Map; import java.util.Map;
import java.util.Timer; import java.util.concurrent.ConcurrentHashMap;
import java.util.TimerTask; import java.util.concurrent.Executors;
import java.util.concurrent.*; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class MedicineHandler implements WebSocketHandler { public class MedicineHandler implements WebSocketHandler {

View File

@ -1,7 +1,6 @@
package com.rax.vital.interceptor; package com.rax.vital.v1.interceptor;
import com.rax.vital.medicine.service.ChatService; import com.rax.vital.v1.medicine.service.ChatService;
import com.rax.vital.timer.VitalSignTimer;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message; import org.springframework.messaging.Message;

View File

@ -1,6 +1,6 @@
package com.rax.vital.interceptor; package com.rax.vital.v1.interceptor;
import com.rax.vital.util.GetHttpParamUtil; import com.rax.vital.common.util.GetHttpParamUtil;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServerHttpResponse;

View File

@ -1,7 +1,7 @@
package com.rax.vital.medicine.controller; package com.rax.vital.v1.medicine.controller;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.rax.vital.medicine.service.ChatService; import com.rax.vital.v1.medicine.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.MessageMapping;

View File

@ -1,11 +1,11 @@
package com.rax.vital.medicine.controller; package com.rax.vital.v1.medicine.controller;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.rax.common.core.util.R; import com.rax.common.core.util.R;
import com.rax.vital.medicine.service.DoctorMedicineService; import com.rax.vital.common.util.DatabaseNameUtil;
import com.rax.vital.medicine.service.VitalSignsService; import com.rax.vital.v1.medicine.service.DoctorMedicineService;
import com.rax.vital.timer.VitalSignTimer; import com.rax.vital.v1.medicine.service.VitalSignsService;
import com.rax.vital.util.DatabaseNameUtil; import com.rax.vital.v1.timer.VitalSignTimer;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -33,8 +33,8 @@ import java.util.ArrayList;
@RequestMapping("/medicine") @RequestMapping("/medicine")
public class MedicineController { public class MedicineController {
// @Autowired @Autowired
// private VitalSignTimer vitalSignTimer; private VitalSignTimer vitalSignTimer;
@Autowired @Autowired
private OAuth2AuthorizationService authorizationService; private OAuth2AuthorizationService authorizationService;
@ -45,52 +45,51 @@ public class MedicineController {
@Autowired @Autowired
private DoctorMedicineService doctorMedicineService; private DoctorMedicineService doctorMedicineService;
// @MessageMapping("/getSurgeryData") @MessageMapping("/getSurgeryData")
// public void doctorMedicine(MessageHeaders messageHeaders, String body) { public void doctorMedicine(MessageHeaders messageHeaders, String body) {
// LinkedMultiValueMap nativeHeaders = (LinkedMultiValueMap) messageHeaders.get("nativeHeaders"); LinkedMultiValueMap nativeHeaders = (LinkedMultiValueMap) messageHeaders.get("nativeHeaders");
// ArrayList tokenList = (ArrayList) nativeHeaders.get("token"); ArrayList tokenList = (ArrayList) nativeHeaders.get("token");
// String token = (String) tokenList.get(0); String token = (String) tokenList.get(0);
// OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
//
// String username = authorization.getPrincipalName();
// String simpSessionId = messageHeaders.get("simpSessionId", String.class);
//
// JSONObject params = JSONObject.parseObject(body);
// // 病人名
// String patientName = params.getString("patientName");
// // 病人身份证
// String idNum = params.getString("idNum");
// // yyyyMMdd
// String date = params.getString("date");
// String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date;
// vitalSignTimer.createAndSendMessageMongo(databaseName, username, simpSessionId);
// }
// @MessageMapping("/changeAIFlag") String username = authorization.getPrincipalName();
// public void changeAIFlag(MessageHeaders messageHeaders, String body) { String simpSessionId = messageHeaders.get("simpSessionId", String.class);
// LinkedMultiValueMap nativeHeaders = (LinkedMultiValueMap) messageHeaders.get("nativeHeaders");
// ArrayList tokenList = (ArrayList) nativeHeaders.get("token"); JSONObject params = JSONObject.parseObject(body);
// String token = (String) tokenList.get(0); // 病人名
// OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); String patientName = params.getString("patientName");
// // 病人身份证
// String username = authorization.getPrincipalName(); String idNum = params.getString("idNum");
// String simpSessionId = messageHeaders.get("simpSessionId", String.class); // yyyyMMdd
// String date = params.getString("date");
// JSONObject params = JSONObject.parseObject(body); String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date;
// // 病人名 vitalSignTimer.createAndSendMessageMongo(databaseName, username, simpSessionId);
// String patientName = params.getString("patientName"); }
// // 病人身份证
// String idNum = params.getString("idNum"); @MessageMapping("/changeAIFlag")
// // yyyyMMdd public void changeAIFlag(MessageHeaders messageHeaders, String body) {
// String date = params.getString("date"); LinkedMultiValueMap nativeHeaders = (LinkedMultiValueMap) messageHeaders.get("nativeHeaders");
// String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date; ArrayList tokenList = (ArrayList) nativeHeaders.get("token");
// vitalSignTimer.changeAIFlag(databaseName, username, simpSessionId, params.getString("flag"), String token = (String) tokenList.get(0);
// params.getString("medicine"), params.getString("value")); OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
// }
String username = authorization.getPrincipalName();
String simpSessionId = messageHeaders.get("simpSessionId", String.class);
JSONObject params = JSONObject.parseObject(body);
// 病人名
String patientName = params.getString("patientName");
// 病人身份证
String idNum = params.getString("idNum");
// yyyyMMdd
String date = params.getString("date");
String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date;
vitalSignTimer.changeAIFlag(databaseName, username, simpSessionId, params.getString("flag"),
params.getString("medicine"), params.getString("value"));
}
@PostMapping("/getPatientInfo") @PostMapping("/getPatientInfo")
public R getPatientInfo(String patientName, String idNum, String date) { public R getPatientInfo(String patientName, String idNum, String date) {
// todo : 存疑
String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date; String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date;
return vitalSignsService.getPatientInfo(databaseName); return vitalSignsService.getPatientInfo(databaseName);
} }

View File

@ -0,0 +1,7 @@
package com.rax.vital.v1.medicine.dto;
import lombok.Data;
@Data
public class MedicineDTO {
}

View File

@ -1,4 +1,4 @@
package com.rax.vital.medicine.entity; package com.rax.vital.v1.medicine.entity;
import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableId;

View File

@ -1,4 +1,4 @@
package com.rax.vital.medicine.entity; package com.rax.vital.v1.medicine.entity;
import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableId;

View File

@ -1,4 +1,4 @@
package com.rax.vital.medicine.entity; package com.rax.vital.v1.medicine.entity;
import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableId;

View File

@ -1,7 +1,7 @@
package com.rax.vital.medicine.mapper; package com.rax.vital.v1.medicine.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.rax.vital.medicine.entity.AIMedicine; import com.rax.vital.v1.medicine.entity.AIMedicine;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
@Mapper @Mapper

View File

@ -1,7 +1,7 @@
package com.rax.vital.medicine.mapper; package com.rax.vital.v1.medicine.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.rax.vital.medicine.entity.DoctorMedicine; import com.rax.vital.v1.medicine.entity.DoctorMedicine;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
@Mapper @Mapper

View File

@ -0,0 +1,18 @@
package com.rax.vital.v1.medicine.service;
import org.springframework.data.mongodb.core.MongoTemplate;
import java.sql.Connection;
import java.util.List;
import java.util.Map;
/**
* AI给药
*/
public interface AIMedicineService {
List<Map> getAIMedicine(MongoTemplate template);
List<Map> getAIMedicine(Connection connection);
void changeAIFlagMedicine(MongoTemplate template, String flag, String medicine, String value);
}

View File

@ -1,4 +1,4 @@
package com.rax.vital.medicine.service; package com.rax.vital.v1.medicine.service;
import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.WebSocketSession;
@ -7,7 +7,7 @@ import java.io.IOException;
public interface ChatService { public interface ChatService {
void sendMessage(String username, String patientName, String idNum, String date, String simpSessionId, String msg); void sendMessage(String username, String patientName, String idNum, String date, String simpSessionId, String msg);
void sendMessage(String dbName, String username, WebSocketSession session, String msg) throws IOException; void sendMessage(String username, String patientName, String idNum, String date, WebSocketSession session, String msg) throws IOException;
void sendMessageMysql(String username, String patientName, String idNum, String date, WebSocketSession session, String msg) throws Exception; void sendMessageMysql(String username, String patientName, String idNum, String date, WebSocketSession session, String msg) throws Exception;

View File

@ -0,0 +1,17 @@
package com.rax.vital.v1.medicine.service;
import org.springframework.data.mongodb.core.MongoTemplate;
import java.sql.Connection;
import java.util.List;
import java.util.Map;
/**
* 医生给药
*/
public interface DoctorMedicineService {
List<Map> getDocMedicine(MongoTemplate template);
List<Map> getDocMedicine(Connection connection);
}

View File

@ -1,4 +1,4 @@
package com.rax.vital.medicine.service; package com.rax.vital.v1.medicine.service;
import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.MongoTemplate;

View File

@ -1,4 +1,4 @@
package com.rax.vital.medicine.service; package com.rax.vital.v1.medicine.service;
import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.MongoTemplate;

View File

@ -1,4 +1,4 @@
package com.rax.vital.medicine.service; package com.rax.vital.v1.medicine.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rax.common.core.util.R; import com.rax.common.core.util.R;

View File

@ -0,0 +1,143 @@
package com.rax.vital.v1.medicine.service.impl;
import com.mongodb.BasicDBObject;
import com.rax.vital.v1.medicine.service.AIMedicineService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* AI给药
*/
@Slf4j
@Service
@AllArgsConstructor
public class AIMedicineServiceImpl implements AIMedicineService {
private static final Map<String, String> doctorMedicineKeyMap = new HashMap() {
{
put("丙泊酚", "丙泊酚");
put("舒芬太尼", "舒芬太尼");
put("瑞芬太尼", "瑞芬太尼");
put("顺阿曲库胺", "顺阿曲库胺");
put("尼卡地平", "尼卡地平");
put("艾司洛尔", "艾司洛尔");
put("麻黄素", "麻黄素");
put("阿托品", "阿托品");
}
};
@Override
public List<Map> getAIMedicine(MongoTemplate template) {
Query query = new Query();
query.limit(1);
query.with(Sort.by(Sort.Order.desc("Time")));
List<Map> aiMedicines = template.find(query, Map.class, "aimedicinetable");
return aiMedicines;
}
@Override
public List<Map> getAIMedicine(Connection connection) {
List<Map> medicineList = new ArrayList<>();
try {
Statement statement = connection.createStatement();
/*ResultSet resultSet = statement.executeQuery("SELECT id, phase, `丙泊酚`, `舒芬太尼`, `瑞芬太尼`, `顺阿曲库胺`, `尼卡地平`, `艾司洛尔`, `麻黄素`, `阿托品`, time FROM `aimedicinetable` ORDER BY time DESC LIMIT 1;");
Map medicine = new HashMap();
while (resultSet.next()) {
medicine.put("id", resultSet.getString("id"));
medicine.put("phase", resultSet.getString("phase"));
medicine.put("丙泊酚", resultSet.getString("丙泊酚"));
medicine.put("舒芬太尼", resultSet.getString("舒芬太尼"));
medicine.put("瑞芬太尼", resultSet.getString("瑞芬太尼"));
medicine.put("顺阿曲库胺", resultSet.getString("顺阿曲库胺"));
medicine.put("尼卡地平", resultSet.getString("尼卡地平"));
medicine.put("艾司洛尔", resultSet.getString("艾司洛尔"));
medicine.put("麻黄素", resultSet.getString("麻黄素"));
medicine.put("阿托品", resultSet.getString("阿托品"));
medicine.put("Time", resultSet.getString("time"));
}
String sql = "SELECT sum(`丙泊酚`) \"丙泊酚sum\", sum(`舒芬太尼`) \"舒芬太尼sum\", " +
"sum(`瑞芬太尼`) \"瑞芬太尼sum\", sum(`顺阿曲库胺`) \"顺阿曲库胺sum\", " +
"sum(`尼卡地平`) \"尼卡地平sum\", sum(`艾司洛尔`) \"艾司洛尔sum\", " +
"sum(`麻黄素`) \"麻黄素sum\", sum(`阿托品`) \"阿托品sum\" FROM `aimedicinetable`";
ResultSet sumSet = statement.executeQuery(sql);
while (sumSet.next()) {
medicine.put("丙泊酚sum", sumSet.getString("丙泊酚sum"));
medicine.put("舒芬太尼sum", sumSet.getString("舒芬太尼sum"));
medicine.put("瑞芬太尼sum", sumSet.getString("瑞芬太尼sum"));
medicine.put("顺阿曲库胺sum", sumSet.getString("顺阿曲库胺sum"));
medicine.put("尼卡地平sum", sumSet.getString("尼卡地平sum"));
medicine.put("艾司洛尔sum", sumSet.getString("艾司洛尔sum"));
medicine.put("麻黄素sum", sumSet.getString("麻黄素sum"));
medicine.put("阿托品sum", sumSet.getString("阿托品sum"));
}*/
String sql = " SELECT " +
"rate_1, cumu_1, rate_2, cumu_2,rate_3, cumu_3,rate_4, cumu_4, rate_5, cumu_5,rate_6, cumu_6,rate_7, cumu_7,rate_8, cumu_8, time " +
" FROM fktable " +
" ORDER BY time DESC LIMIT 1; ";
ResultSet resultSet = statement.executeQuery(sql);
Map medicine = new HashMap();
while (resultSet.next()) {
medicine.put("丙泊酚", resultSet.getString("rate_1"));
medicine.put("丙泊酚sum", resultSet.getString("cumu_1"));
medicine.put("舒芬太尼", resultSet.getString("rate_2"));
medicine.put("舒芬太尼sum", resultSet.getString("cumu_2"));
medicine.put("瑞芬太尼", resultSet.getString("rate_3"));
medicine.put("瑞芬太尼sum", resultSet.getString("cumu_3"));
medicine.put("顺阿曲库胺", resultSet.getString("rate_4"));
medicine.put("顺阿曲库胺sum", resultSet.getString("cumu_4"));
medicine.put("尼卡地平", resultSet.getString("rate_5"));
medicine.put("尼卡地平sum", resultSet.getString("cumu_5"));
medicine.put("艾司洛尔", resultSet.getString("rate_6"));
medicine.put("艾司洛尔sum", resultSet.getString("cumu_6"));
medicine.put("麻黄素", resultSet.getString("rate_7"));
medicine.put("麻黄素sum", resultSet.getString("cumu_7"));
medicine.put("阿托品", resultSet.getString("rate_8"));
medicine.put("阿托品sum", resultSet.getString("cumu_8"));
medicine.put("Time", resultSet.getString("time"));
}
medicineList.add(medicine);
} catch (SQLException e) {
throw new RuntimeException(e);
}
return medicineList;
}
@Override
public void changeAIFlagMedicine(MongoTemplate template, String flag, String medicine, String value) {
BasicDBObject obj = new BasicDBObject();
obj.put("Flag", flag);
obj.put("Time", LocalDateTime.now());
obj.put("ConvertFlag", "2".equals(flag) ? 1 : 0);
template.insert(obj, "aiflagtable");
if (StringUtils.hasText(value) && StringUtils.hasText(medicine)) {
BasicDBObject medicineObj = new BasicDBObject();
for (String key : doctorMedicineKeyMap.keySet()) {
if (key.equals(medicine)) {
medicineObj.put(medicine, value);
} else {
medicineObj.put(key, 0);
}
}
medicineObj.put("phase", "");
medicineObj.put("Time", LocalDateTime.now());
template.insert(medicineObj, "doctormedicinetable");
}
}
}

View File

@ -1,15 +1,15 @@
package com.rax.vital.medicine.service.impl; package com.rax.vital.v1.medicine.service.impl;
import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rax.admin.api.entity.SysUser; import com.rax.admin.api.entity.SysUser;
import com.rax.admin.service.SysUserService; import com.rax.admin.service.SysUserService;
import com.rax.vital.datasource.CustomDataSource; import com.rax.vital.common.datasource.CustomDataSource;
import com.rax.vital.datasource.MongoDBSource; import com.rax.vital.common.datasource.MongoDBSource;
import com.rax.vital.datasource.MySQLSource; import com.rax.vital.common.datasource.MySQLSource;
import com.rax.vital.medicine.service.ChatService; import com.rax.vital.common.util.DatabaseNameUtil;
import com.rax.vital.util.DatabaseNameUtil; import com.rax.vital.v1.medicine.service.ChatService;
import org.bson.Document; import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
@ -71,7 +71,6 @@ public class ChatServiceImpl implements ChatService {
@Override @Override
public void sendMessage(String username, String patientName, String idNum, String date, String simpSessionId, String msg) { public void sendMessage(String username, String patientName, String idNum, String date, String simpSessionId, String msg) {
CustomDataSource mongoDBSource = datasourceMap.get(simpSessionId); CustomDataSource mongoDBSource = datasourceMap.get(simpSessionId);
if (mongoDBSource == null) { if (mongoDBSource == null) {
String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date; String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date;
mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, databaseName); mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, databaseName);
@ -79,6 +78,7 @@ public class ChatServiceImpl implements ChatService {
mongoDBSource.open(); mongoDBSource.open();
} }
SysUser sysUser = SysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username)); SysUser sysUser = SysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
Map param = new HashMap(); Map param = new HashMap();
@ -102,9 +102,10 @@ public class ChatServiceImpl implements ChatService {
} }
@Override @Override
public void sendMessage(String databaseName,String username, WebSocketSession session, String msg) throws IOException { public void sendMessage(String username, String patientName, String idNum, String date, WebSocketSession session, String msg) throws IOException {
CustomDataSource mongoDBSource = datasourceMap.get(session.getId()); CustomDataSource mongoDBSource = datasourceMap.get(session.getId());
// synchronized (username) { String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date;
synchronized (username) {
if (mongoDBSource == null) { if (mongoDBSource == null) {
mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, databaseName); mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, databaseName);
mongoDBSource.open(); mongoDBSource.open();
@ -120,13 +121,12 @@ public class ChatServiceImpl implements ChatService {
sessionMap.put(session.getId(), session); sessionMap.put(session.getId(), session);
} }
} }
}
} }
// }
SysUser sysUser = SysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username)); SysUser sysUser = SysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
// 将聊天消息保存在mongo中
if (StringUtils.hasText(msg)) { if (StringUtils.hasText(msg)) {
JSONObject param = new JSONObject(); JSONObject param = new JSONObject();
MongoTemplate template = mongoDBSource.getConnection(); MongoTemplate template = mongoDBSource.getConnection();

View File

@ -0,0 +1,80 @@
package com.rax.vital.v1.medicine.service.impl;
import com.rax.vital.v1.medicine.service.DoctorMedicineService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 医生给药
*/
@Slf4j
@Service
@AllArgsConstructor
public class DoctorMedicineServiceImpl implements DoctorMedicineService {
@Override
public List<Map> getDocMedicine(MongoTemplate template) {
Query query = new Query();
query.limit(1);
query.with(Sort.by(Sort.Order.desc("Time")));
List<Map> doctorMedicineTable = template.find(query, Map.class, "doctormedicinetable");
return doctorMedicineTable;
}
@Override
public List<Map> getDocMedicine(Connection connection) {
List<Map> medicineList = new ArrayList<>();
try {
Map medicine = new HashMap();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT id, phase, `丙泊酚`, `舒芬太尼`, `瑞芬太尼`, `顺阿曲库胺`, `尼卡地平`, `艾司洛尔`, `麻黄素`, `阿托品`, time FROM `doctormedicinetable` ORDER BY time DESC LIMIT 1;");
while (resultSet.next()) {
medicine.put("id", resultSet.getString("id"));
medicine.put("phase", resultSet.getString("phase"));
medicine.put("丙泊酚", resultSet.getString("丙泊酚"));
medicine.put("舒芬太尼", resultSet.getString("舒芬太尼"));
medicine.put("瑞芬太尼", resultSet.getString("瑞芬太尼"));
medicine.put("顺阿曲库胺", resultSet.getString("顺阿曲库胺"));
medicine.put("尼卡地平", resultSet.getString("尼卡地平"));
medicine.put("艾司洛尔", resultSet.getString("艾司洛尔"));
medicine.put("麻黄素", resultSet.getString("麻黄素"));
medicine.put("阿托品", resultSet.getString("阿托品"));
medicine.put("Time", resultSet.getString("time"));
}
String sql = "SELECT sum(`丙泊酚`) \"丙泊酚sum\", sum(`舒芬太尼`) \"舒芬太尼sum\", " +
"sum(`瑞芬太尼`) \"瑞芬太尼sum\", sum(`顺阿曲库胺`) \"顺阿曲库胺sum\", " +
"sum(`尼卡地平`) \"尼卡地平sum\", sum(`艾司洛尔`) \"艾司洛尔sum\", " +
"sum(`麻黄素`) \"麻黄素sum\", sum(`阿托品`) \"阿托品sum\" FROM `doctormedicinetable`";
ResultSet sumSet = statement.executeQuery(sql);
while (sumSet.next()) {
medicine.put("丙泊酚sum", sumSet.getString("丙泊酚sum"));
medicine.put("舒芬太尼sum", sumSet.getString("舒芬太尼sum"));
medicine.put("瑞芬太尼sum", sumSet.getString("瑞芬太尼sum"));
medicine.put("顺阿曲库胺sum", sumSet.getString("顺阿曲库胺sum"));
medicine.put("尼卡地平sum", sumSet.getString("尼卡地平sum"));
medicine.put("艾司洛尔sum", sumSet.getString("艾司洛尔sum"));
medicine.put("麻黄素sum", sumSet.getString("麻黄素sum"));
medicine.put("阿托品sum", sumSet.getString("阿托品sum"));
}
medicineList.add(medicine);
} catch (SQLException e) {
throw new RuntimeException(e);
}
return medicineList;
}
}

View File

@ -0,0 +1,155 @@
package com.rax.vital.v1.medicine.service.impl;
import com.rax.vital.v1.medicine.service.FlagService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 标志位
*/
@Slf4j
@Service
@AllArgsConstructor
public class FlagServiceImpl implements FlagService {
/**
* 新标志位接口MongoDB
* flag 0:诱导期给药 1:维持期AI给药 2:维持期人工给药
*
* @param template
* @return
*/
@Override
public Map getFlags(MongoTemplate template) {
Map flagMap = new HashMap();
Query query = new Query();
query.limit(1);
query.with(Sort.by(Sort.Order.desc("_id")));
List<Map> linkTable = template.find(query, Map.class, "linktable");
flagMap.put("linktable", linkTable);
List<Map> aiFlagTable = template.find(query, Map.class, "aiflagtable");
flagMap.put("aiflagtable", aiFlagTable);
List<Map> endFlagTable = template.find(query, Map.class, "endflagtable");
flagMap.put("endflagtable", endFlagTable);
return flagMap;
}
/**
* 标志位接口MongoDB
*
* @param template
* @return
*/
@Deprecated
@Override
public Map getFlag(MongoTemplate template) {
Map allFlag = new HashMap();
Query query1 = new Query();
query1.limit(1);
query1.with(Sort.by(Sort.Order.desc("_id")));
List<Map> endFlagTable = template.find(query1, Map.class, "EndFlagTable");
if (!endFlagTable.isEmpty()) {
allFlag.put("endFlag", endFlagTable.get(1));
}
Query query2 = new Query();
query2.limit(1);
query2.with(Sort.by(Sort.Order.desc("_id")));
List<Map> aiFlagTable = template.find(query2, Map.class, "AIFlagTable");
if (!aiFlagTable.isEmpty()) {
allFlag.put("aiFlag", aiFlagTable);
}
Query query3 = new Query();
query3.limit(1);
query3.with(Sort.by(Sort.Order.desc("_id")));
List<Map> reFlagTable = template.find(query3, Map.class, "ReFlagTable");
if (!reFlagTable.isEmpty()) {
allFlag.put("reFlagTable", reFlagTable);
}
return allFlag;
}
/**
* 标志位接口MySQL
*
* @param connection
* @return
*/
@Override
@Deprecated
public Map getFlag(Connection connection) {
Map allFlag = new HashMap();
try {
Statement statement = connection.createStatement();
// 0代表手术未开始或已结束1代表手术进行中
ResultSet resultSet = statement.executeQuery("SELECT * FROM `endflagtable` ORDER BY time DESC LIMIT 1;");
List<Map> endFlagList = new ArrayList<>();
while (resultSet.next()) {
Map flag = new HashMap();
flag.put("id", resultSet.getString(1));
flag.put("Flag", resultSet.getString(2));
flag.put("Time", resultSet.getString(3));
endFlagList.add(flag);
}
allFlag.put("endflagtable", endFlagList);
// Flag默认为10代表诱导期给药1代表维持期AI给药2代表维持期医生给药
// ConvertFlag默认为00代表无需切换1代表由AI给药转为医生给药
ResultSet aiRe = statement.executeQuery("SELECT * FROM `aiflagtable` ORDER BY time DESC LIMIT 1;");
List<Map> aiFlagList = new ArrayList<>();
while (aiRe.next()) {
Map flag = new HashMap();
flag.put("id", aiRe.getString(1));
flag.put("Flag", aiRe.getString(2));
flag.put("ConvertFlag", aiRe.getString(3));
flag.put("Time", aiRe.getString(4));
aiFlagList.add(flag);
}
allFlag.put("aiflagtable", aiFlagList);
// 诱导期标志符 0是诱导期 1是维持期
ResultSet reRe = statement.executeQuery("SELECT * FROM `reflagtable` ORDER BY time DESC LIMIT 1;");
List<Map> reFlagList = new ArrayList<>();
while (reRe.next()) {
Map flag = new HashMap();
flag.put("id", reRe.getString(1));
flag.put("Flag", reRe.getString(2));
flag.put("Time", reRe.getString(3));
reFlagList.add(flag);
}
allFlag.put("reflagtable", reFlagList);
// Flag默认为1: 0代表泵站通讯正常1代表泵站通讯异常
ResultSet link = statement.executeQuery("SELECT * FROM `linktable` ORDER BY time DESC LIMIT 1;");
List<Map> linkFlagList = new ArrayList<>();
while (link.next()) {
Map flag = new HashMap();
flag.put("id", link.getString(1));
flag.put("Flag", link.getString(2));
flag.put("Time", link.getString(3));
linkFlagList.add(flag);
}
allFlag.put("linktable", linkFlagList);
} catch (SQLException e) {
throw new RuntimeException(e);
}
return allFlag;
}
}

View File

@ -1,6 +1,6 @@
package com.rax.vital.medicine.service.impl; package com.rax.vital.v1.medicine.service.impl;
import com.rax.vital.medicine.service.RevulsionService; import com.rax.vital.v1.medicine.service.RevulsionService;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;

View File

@ -1,4 +1,4 @@
package com.rax.vital.medicine.service.impl; package com.rax.vital.v1.medicine.service.impl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mongodb.ConnectionString; import com.mongodb.ConnectionString;
@ -7,15 +7,14 @@ import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients; import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoIterable; import com.mongodb.client.MongoIterable;
import com.rax.common.core.util.R; import com.rax.common.core.util.R;
import com.rax.vital.datasource.MongoDBSource; import com.rax.vital.common.datasource.MongoDBSource;
import com.rax.vital.datasource.MySQLSource; import com.rax.vital.common.datasource.MySQLSource;
import com.rax.vital.medicine.service.VitalSignsService; import com.rax.vital.common.util.DatabaseNameUtil;
import com.rax.vital.util.DatabaseNameUtil; import com.rax.vital.v1.medicine.service.VitalSignsService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.bson.BsonRegularExpression; import org.bson.BsonRegularExpression;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.domain.ScrollPosition;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.SpringDataMongoDB; import org.springframework.data.mongodb.SpringDataMongoDB;
import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.MongoTemplate;
@ -80,17 +79,17 @@ public class VitalSignServiceImpl implements VitalSignsService {
if (vitalList != null && vitalList.size() > 0) { if (vitalList != null && vitalList.size() > 0) {
Map map = vitalList.get(0); Map map = vitalList.get(0);
Double bis = Double.valueOf((String) map.get("BIS")); Double bis = (Double) map.get("BIS");
map.put("BIS_except", bis <= 40 || bis >= 60); map.put("BIS_except", bis <= 40 || bis >= 60);
Double hr = Double.valueOf((String) map.get("HR")); Double hr = (Double) map.get("HR");
map.put("HR_except", hr <= 50 || hr >= 80); map.put("HR_except", hr <= 50 || hr >= 80);
Double sbp = Double.valueOf((String) map.get("SBP")); Double sbp = (Double) map.get("SBP");
map.put("SBP_except", sbp <= 90 || sbp >= 120); map.put("SBP_except", sbp <= 90 || sbp >= 120);
Double dbp = Double.valueOf((String) map.get("DBP")); Double dbp = (Double) map.get("DBP");
map.put("DBP_except", dbp <= 60 || dbp >= 90); map.put("DBP_except", dbp <= 60 || dbp >= 90);
Double st = Double.valueOf((String) map.get("ST")); Double st = (Double) map.get("ST");
map.put("ST_except", st <= -0.2 || st >= 0.2); map.put("ST_except", st <= -0.2 || st >= 0.2);
Double etCO2 = Double.valueOf((String) map.get("EtCO2")); Double etCO2 = (Double) map.get("EtCO2");
map.put("EtCO2_except", etCO2 <= 30 || etCO2 >= 45); map.put("EtCO2_except", etCO2 <= 30 || etCO2 >= 45);
} }
return vitalList; return vitalList;

View File

@ -1,9 +1,9 @@
package com.rax.vital.timer; package com.rax.vital.v1.timer;
import com.rax.common.security.util.SecurityUtils; import com.rax.common.security.util.SecurityUtils;
import com.rax.vital.datasource.MongoDBSource; import com.rax.vital.common.datasource.MongoDBSource;
import com.rax.vital.datasource.MySQLSource; import com.rax.vital.common.datasource.MySQLSource;
import com.rax.vital.medicine.service.*; import com.rax.vital.v1.medicine.service.*;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.context.config.annotation.RefreshScope;
@ -22,6 +22,7 @@ import java.util.concurrent.ConcurrentHashMap;
* @date 2024/2/29 * @date 2024/2/29
*/ */
@RefreshScope @RefreshScope
@Component
@RequiredArgsConstructor @RequiredArgsConstructor
public class VitalSignTimer { public class VitalSignTimer {
@ -80,52 +81,52 @@ public class VitalSignTimer {
* *
* @author zhaoyz * @author zhaoyz
*/ */
// public void createAndSendMessageMongo(String database, String username, String simpSessionId) { public void createAndSendMessageMongo(String database, String username, String simpSessionId) {
//
// synchronized (username) { synchronized (username) {
// if (!masterControlMap.containsKey(database)) { if (!masterControlMap.containsKey(database)) {
// masterControlMap.put(database, username); masterControlMap.put(database, username);
// } }
// } }
//
// TimerTask task = timerMongoTaskMap.get(simpSessionId); TimerTask task = timerMongoTaskMap.get(simpSessionId);
// if (task != null) { if (task != null) {
// return; return;
// } }
//
// MongoDBSource mongoDBSource = mongoDBSourceMap.get(simpSessionId); MongoDBSource mongoDBSource = mongoDBSourceMap.get(simpSessionId);
// if (mongoDBSource == null) { if (mongoDBSource == null) {
// mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, database); mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, database);
// mongoDBSourceMap.put(simpSessionId, mongoDBSource); mongoDBSourceMap.put(simpSessionId, mongoDBSource);
// mongoDBSource.open(); mongoDBSource.open();
// } }
//
// MongoDBSource finalMongoDBSource = mongoDBSource; MongoDBSource finalMongoDBSource = mongoDBSource;
// TimerTask timerTask = new TimerTask() { TimerTask timerTask = new TimerTask() {
// @Override @Override
// public void run() { public void run() {
//
// MongoTemplate template = finalMongoDBSource.getConnection(); MongoTemplate template = finalMongoDBSource.getConnection();
// HashMap<String, Object> result = new HashMap(); HashMap<String, Object> result = new HashMap();
// List vitalSignsList = vitalSignsService.getVitalSignsList(template); List vitalSignsList = vitalSignsService.getVitalSignsList(template);
// result.put("vitalSignsList", vitalSignsList); result.put("vitalSignsList", vitalSignsList);
// List aiMedicineList = aiMedicineService.getAIMedicine(template); List aiMedicineList = aiMedicineService.getAIMedicine(template);
// result.put("aiMedicineList", aiMedicineList); result.put("aiMedicineList", aiMedicineList);
// List docMedicineList = doctorMedicineService.getDocMedicine(template); List docMedicineList = doctorMedicineService.getDocMedicine(template);
// result.put("docMedicineList", docMedicineList); result.put("docMedicineList", docMedicineList);
// List revulsionList = revulsionService.getRevulsionServiceList(template); List revulsionList = revulsionService.getRevulsionServiceList(template);
// result.put("revulsionList", revulsionList); result.put("revulsionList", revulsionList);
// Map flags = flagService.getFlags(template); Map flags = flagService.getFlags(template);
// result.put("flags", flags); result.put("flags", flags);
//
// simpMessagingTemplate.convertAndSendToUser(username + ":" + database, "/surgeryData", result); simpMessagingTemplate.convertAndSendToUser(username + ":" + database, "/surgeryData", result);
// } }
// }; };
// // 定时任务设置1秒 // 定时任务设置1秒
// Timer timer = new Timer(); Timer timer = new Timer();
// timer.schedule(timerTask, 0, 1000); timer.schedule(timerTask, 0, 1000);
// timerMongoTaskMap.put(simpSessionId, timerTask); timerMongoTaskMap.put(simpSessionId, timerTask);
// } }
/** /**

View File

@ -1,11 +1,10 @@
package com.rax.vital.timer; package com.rax.vital.v1.timer;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.rax.vital.datasource.CustomDataSource; import com.rax.vital.common.datasource.CustomDataSource;
import com.rax.vital.datasource.MongoDBSource; import com.rax.vital.common.datasource.MongoDBSource;
import com.rax.vital.datasource.MySQLSource; import com.rax.vital.common.datasource.MySQLSource;
import com.rax.vital.medicine.dto.MedicineDTO; import com.rax.vital.v1.medicine.service.*;
import com.rax.vital.medicine.service.*;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.context.config.annotation.RefreshScope;
@ -17,7 +16,10 @@ import org.springframework.web.socket.WebSocketSession;
import java.io.IOException; import java.io.IOException;
import java.sql.Connection; import java.sql.Connection;
import java.util.*; import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@RefreshScope @RefreshScope
@ -52,22 +54,22 @@ public class VitalSignTimerWS {
// 定时任务容器 // 定时任务容器
private static final Map<String, TimerTask> timerTaskMap = new ConcurrentHashMap<>(); private static final Map<String, TimerTask> timerTaskMap = new ConcurrentHashMap<>();
// 链接工具类容器 ket // 链接工具类容器
private static final Map<String, CustomDataSource> dataSourceMap = new ConcurrentHashMap<>(); private static final Map<String, CustomDataSource> dataSourceMap = new ConcurrentHashMap<>();
// 主控人员容器, 建立连接放入存值,生命体征信息 key:数据库名 value:网页解析的token用户名 // 主控人员容器
private static final Map<String, String> masterControlMap = new ConcurrentHashMap<>(); private static final Map<String, String> masterControlMap = new ConcurrentHashMap<>();
// session容器网站端操作员 // session容器
private static final Map<String, WebSocketSession> userSessionMap = new ConcurrentHashMap<>(); private static final Map<String, WebSocketSession> userSessionMap = new ConcurrentHashMap<>();
// sessionId容器(数据库名, sessionId) // sessionId容器(数据库名, sessionId)
private static final Map<String, String> userDatabaseSessionMap = new ConcurrentHashMap<>(); private static final Map<String, String> userDatabaseSessionMap = new ConcurrentHashMap<>();
// 设备端session容器U3D // 设备端session容器
private static final Map<String, WebSocketSession> machineSessionMap = new ConcurrentHashMap<>(); private static final Map<String, WebSocketSession> machineSessionMap = new ConcurrentHashMap<>();
// sessionId容器(数据库名, sessionId) 数据库名称, u3d获取药物的sessionId // sessionId容器(数据库名, sessionId)
private static final Map<String, String> machineDatabaseSessionMap = new ConcurrentHashMap<>(); private static final Map<String, String> machineDatabaseSessionMap = new ConcurrentHashMap<>();
private final VitalSignsService vitalSignsService; private final VitalSignsService vitalSignsService;
@ -81,9 +83,13 @@ public class VitalSignTimerWS {
private final RevulsionService revulsionService; private final RevulsionService revulsionService;
public void createAndSendWSMessageMongo(String database, String username, WebSocketSession session) { public void createAndSendWSMessageMongo(String database, String username, WebSocketSession session) {
synchronized (username) {
if (!masterControlMap.containsKey(database)) { if (!masterControlMap.containsKey(database)) {
masterControlMap.put(database, username); masterControlMap.put(database, username);
} }
}
String sessionId = session.getId(); String sessionId = session.getId();
TimerTask task = timerTaskMap.get(sessionId); TimerTask task = timerTaskMap.get(sessionId);
@ -97,7 +103,7 @@ public class VitalSignTimerWS {
dataSourceMap.put(sessionId, dataSource); dataSourceMap.put(sessionId, dataSource);
dataSource.open(); dataSource.open();
} }
System.out.println("mongoDBName = " + database);
CustomDataSource finalMongoDBSource = dataSource; CustomDataSource finalMongoDBSource = dataSource;
TimerTask timerTask = new TimerTask() { TimerTask timerTask = new TimerTask() {
@Override @Override
@ -105,71 +111,19 @@ public class VitalSignTimerWS {
MongoTemplate template = finalMongoDBSource.getConnection(); MongoTemplate template = finalMongoDBSource.getConnection();
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
// 生命体征信息
List vitalSignsList = vitalSignsService.getVitalSignsList(template); List vitalSignsList = vitalSignsService.getVitalSignsList(template);
jsonObject.put("vitalSignsList", vitalSignsList); jsonObject.put("vitalSignsList", vitalSignsList);
List aiMedicineList = aiMedicineService.getAIMedicine(template);
// // 诱导期给药信息 jsonObject.put("aiMedicineList", aiMedicineList);
// List revulsionList = revulsionService.getRevulsionServiceList(template); List docMedicineList = doctorMedicineService.getDocMedicine(template);
// jsonObject.put("revulsionList", revulsionList); jsonObject.put("docMedicineList", docMedicineList);
// 标记信息 List revulsionList = revulsionService.getRevulsionServiceList(template);
jsonObject.put("revulsionList", revulsionList);
Map flags = flagService.getFlags(template); Map flags = flagService.getFlags(template);
// flag
// aiFlag 1代表AI给药 0代表医生给药
// reFlag 1代表维持期 0代表诱导期
// endFlag 1代表手术进行 0代表手术结束
// linkFlag 1泵异常 0正常
jsonObject.put("flags", flags); jsonObject.put("flags", flags);
Map<String, Object> medicineRateMap = new HashMap<>();
if (flags.get("aiFlag") != null && flags.get("aiFlag").equals("1")) {
// ai给药信息
medicineRateMap = aiMedicineService.getAiMedicine(template);
} else if (flags.get("aiFlag") != null && flags.get("aiFlag").equals("0")) {
// 医生给药信息
medicineRateMap = doctorMedicineService.getDocMedicine(template);
}
System.out.println("medicineRateMap = " + medicineRateMap);
// 写上面会存在线程安全问题
ArrayList<MedicineDTO> medicineList = new ArrayList<>();
medicineList.add(new MedicineDTO("1", "丙泊酚", "0", "0"));
medicineList.add(new MedicineDTO("2", "舒芬太尼", "0", "0"));
medicineList.add(new MedicineDTO("3", "瑞芬太尼", "0", "0"));
medicineList.add(new MedicineDTO("4", "顺阿曲库胺", "0", "0"));
medicineList.add(new MedicineDTO("5", "尼卡地平", "0", "0"));
medicineList.add(new MedicineDTO("6", "艾司洛尔", "0", "0"));
medicineList.add(new MedicineDTO("7", "麻黄素", "0", "0"));
medicineList.add(new MedicineDTO("8", "阿托品", "0", "0"));
if (medicineRateMap != null && !medicineRateMap.isEmpty()) {
for (String key : medicineRateMap.keySet()) {
for (MedicineDTO medicineDTO : medicineList) {
if (medicineDTO.getMedicineName().equals(key)) {
medicineDTO.setMedicineRate(medicineRateMap.get(key).toString());
}
}
}
jsonObject.put("rateModTime",medicineRateMap.get("Time"));
}else {
jsonObject.put("rateModTime","0");
}
// 总的药量信息
Map<String, Object> countMedicineMap = aiMedicineService.getCountMedicine(template);
if (countMedicineMap != null && !countMedicineMap.isEmpty()) {
for (String key : countMedicineMap.keySet()) {
for (MedicineDTO medicineDTO : medicineList) {
if ((medicineDTO.getMedicineName() + "Sum").equals(key)) {
medicineDTO.setMedicineRate(countMedicineMap.get(key).toString());
}
}
}
}
jsonObject.put("medicineList", medicineList);
jsonObject.put("msgType", "msg"); jsonObject.put("msgType", "msg");
System.out.println("medicineList = " + medicineList);
// 如果是人工给药展示人工给药的内容
WebSocketMessage message = new TextMessage(jsonObject.toJSONString().getBytes());
WebSocketMessage message = new TextMessage(jsonObject.toJSONString().getBytes());
try { try {
session.sendMessage(message); session.sendMessage(message);
} catch (IOException e) { } catch (IOException e) {
@ -185,7 +139,7 @@ public class VitalSignTimerWS {
} }
public void createAndSendMessageMySQL(String database, String username, WebSocketSession session) { public void createAndSendMessageMySQL(String database, String username, WebSocketSession session) {
synchronized (this) { synchronized (username) {
if (!masterControlMap.containsKey(database)) { if (!masterControlMap.containsKey(database)) {
masterControlMap.put(database, username); masterControlMap.put(database, username);
} }
@ -269,21 +223,19 @@ public class VitalSignTimerWS {
} }
public void changeWSAIFlag(String database, String username, WebSocketSession session, String flag, String medicine, String value) throws IOException { public void changeWSAIFlag(String database, String username, WebSocketSession session, String flag, String medicine, String value) throws IOException {
synchronized (this) { synchronized (username) {
JSONObject result = new JSONObject(); JSONObject result = new JSONObject();
if (masterControlMap.containsKey(database) && masterControlMap.get(database).equals(username)) { if (masterControlMap.containsKey(database) && masterControlMap.get(database).equals(username)) {
if (!userDatabaseSessionMap.containsKey(database)) { if (!userDatabaseSessionMap.containsKey(database)) {
userDatabaseSessionMap.put(database, session.getId()); userDatabaseSessionMap.put(database, session.getId());
} }
// machineDatabaseSessionMap.containsKey(database)
if (machineDatabaseSessionMap.containsKey(database)) { if (machineDatabaseSessionMap.containsKey(database)) {
String sessionId = machineDatabaseSessionMap.get(database); String sessionId = machineDatabaseSessionMap.get(database);
WebSocketSession machineSession = machineSessionMap.get(sessionId); WebSocketSession machineSession = machineSessionMap.get(sessionId);
if (machineSession != null) { if (machineSession != null) {
result.put("medicine",medicine); result.put(medicine, value);
result.put("value",value);
result.put("flag", flag); result.put("flag", flag);
result.put("msgType", "addMedicine"); result.put("msgType", "msg");
machineSession.sendMessage(new TextMessage(result.toJSONString().getBytes())); machineSession.sendMessage(new TextMessage(result.toJSONString().getBytes()));
} else { } else {
result.put("flag", flag); result.put("flag", flag);
@ -349,7 +301,7 @@ public class VitalSignTimerWS {
String userSessionId = userDatabaseSessionMap.get(database); String userSessionId = userDatabaseSessionMap.get(database);
WebSocketSession webSocketSession = userSessionMap.get(userSessionId); WebSocketSession webSocketSession = userSessionMap.get(userSessionId);
result.put("status", code); result.put("status", code);
result.put("msg", "网站已进行远程连接"); result.put("msg", "");
result.put("msgType", "msg"); result.put("msgType", "msg");
webSocketSession.sendMessage(new TextMessage(result.toJSONString().getBytes())); webSocketSession.sendMessage(new TextMessage(result.toJSONString().getBytes()));
} else { } else {
@ -376,13 +328,4 @@ public class VitalSignTimerWS {
} }
} }
public void initUnity(String databaseName, WebSocketSession session) {
machineDatabaseSessionMap.put(databaseName, session.getId());
machineSessionMap.put(session.getId(), session);
}
public void initWeb(String databaseName, WebSocketSession session) {
userDatabaseSessionMap.put(databaseName, session.getId());
userSessionMap.put(session.getId(), session);
}
} }

View File

@ -1,10 +1,10 @@
package com.rax.vital.config; package com.rax.vital.v2.config;
import com.rax.vital.handler.AddMedicineHandler; import com.rax.vital.v2.handler.AddMedicineHandler;
import com.rax.vital.handler.ChatHandler; import com.rax.vital.v2.handler.ChatHandler;
import com.rax.vital.handler.MachineFeedbackHandler; import com.rax.vital.v2.handler.MachineFeedbackHandler;
import com.rax.vital.handler.MedicineHandler; import com.rax.vital.v2.handler.MedicineHandler;
import com.rax.vital.interceptor.WebSocketInterceptors; import com.rax.vital.v2.interceptor.WebSocketInterceptors;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.WebSocketHandler;

View File

@ -0,0 +1,47 @@
package com.rax.vital.v2.config;
import com.rax.vital.v2.interceptor.WSChannelInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketStompConfig implements WebSocketMessageBrokerConfigurer {
@Autowired
private WSChannelInterceptor wsChannelInterceptor;
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/rax/chat", "/rax/SurgeryData")
.setAllowedOrigins("*");
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
// 第一个值表示客户端发送心跳消息的间隔时间第二个值表示服务端发送心跳消息的间隔时间
long [] heartbeat = {60000, 60000};
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.initialize();
registry.enableSimpleBroker("/topic").setTaskScheduler(threadPoolTaskScheduler).setHeartbeatValue(heartbeat);
registry.setApplicationDestinationPrefixes("/front");
registry.setUserDestinationPrefix("/topic/user");
}
/**
* stomp未登录验证
*
* @param registration
*/
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(wsChannelInterceptor);
}
}

View File

@ -1,11 +1,12 @@
package com.rax.vital.handler; package com.rax.vital.v2.handler;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.rax.vital.timer.AIMedicineTimer; import com.rax.vital.common.util.DatabaseNameUtil;
import com.rax.vital.timer.VitalSignTimerWS; import com.rax.vital.common.util.GetHttpParamUtil;
import com.rax.vital.util.DatabaseNameUtil; import com.rax.vital.v2.timer.AIMedicineTimer;
import com.rax.vital.util.GetHttpParamUtil; import com.rax.vital.v2.timer.VitalSignTimerV2;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
@ -15,17 +16,17 @@ import org.springframework.web.socket.*;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.Date; import java.util.Date;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/** /**
* 网站发送给仪器给药信息 * 网站发送给仪器给药信息
*/ */
@Slf4j
public class AddMedicineHandler implements WebSocketHandler { public class AddMedicineHandler implements WebSocketHandler {
@Resource
private VitalSignTimerWS vitalSignTimerWS;
@Autowired
private VitalSignTimerV2 vitalSignTimerV2;
@Resource @Resource
private OAuth2AuthorizationService authorizationService; private OAuth2AuthorizationService authorizationService;
@ -33,13 +34,13 @@ public class AddMedicineHandler implements WebSocketHandler {
// 发送心跳任务的定时任务容器 // 发送心跳任务的定时任务容器
private Map<String, ScheduledExecutorService> timerTaskMap = new ConcurrentHashMap<>(); private Map<String, ScheduledExecutorService> timerTaskMap = new ConcurrentHashMap<>();
@Autowired @Autowired
private AIMedicineTimer aiMedicineTimer; private AIMedicineTimer aiMedicineTimer;
@Override @Override
public void afterConnectionEstablished(WebSocketSession session) { public void afterConnectionEstablished(WebSocketSession session) {
vitalSignTimerWS.setWSAIFlagSession(session);
startHeartbeat(session); startHeartbeat(session);
} }
@ -65,7 +66,6 @@ public class AddMedicineHandler implements WebSocketHandler {
// 将网站端的dbName作为key session作为Value存入Map 以便后续判断状态 // 将网站端的dbName作为key session作为Value存入Map 以便后续判断状态
if ("init".equals(msgType)) { if ("init".equals(msgType)) {
aiMedicineTimer.initWeb(databaseName, session); aiMedicineTimer.initWeb(databaseName, session);
vitalSignTimerWS.initWeb(databaseName, session);
} }
// 处理网页端接收到消息后的相应内容 // 处理网页端接收到消息后的相应内容
@ -81,37 +81,36 @@ public class AddMedicineHandler implements WebSocketHandler {
aiMedicineTimer.sendWebRequestConnectionMsg(patientName, idNum, date, databaseName, webRequestFlag); aiMedicineTimer.sendWebRequestConnectionMsg(patientName, idNum, date, databaseName, webRequestFlag);
} }
if (aiMedicineTimer.getUnitySession(databaseName) != null) { // if (aiMedicineTimer.getUnitySession(databaseName) != null) {
JSONObject result = new JSONObject(); // JSONObject result = new JSONObject();
result.put("msg", "unity端已登录"); // result.put("msg", "unity端已登录");
result.put("msgType", "msg"); // result.put("msgType", "msg");
session.sendMessage(new TextMessage(result.toJSONString().getBytes())); // session.sendMessage(new TextMessage(result.toJSONString().getBytes()));
} else { // } else {
JSONObject result = new JSONObject(); // JSONObject result = new JSONObject();
result.put("msg", "unity端未登录"); // result.put("msg", "unity端未登录");
result.put("msgType", "msg"); // result.put("msgType", "msg");
session.sendMessage(new TextMessage(result.toJSONString().getBytes())); // session.sendMessage(new TextMessage(result.toJSONString().getBytes()));
} // }
//
if (aiMedicineTimer.getWebSession(databaseName) != null) { // if (aiMedicineTimer.getWebSession(databaseName) != null) {
JSONObject result = new JSONObject(); // JSONObject result = new JSONObject();
result.put("msg", "网页端已登录"); // result.put("msg", "网页端已登录");
result.put("msgType", "msg"); // result.put("msgType", "msg");
session.sendMessage(new TextMessage(result.toJSONString().getBytes())); // session.sendMessage(new TextMessage(result.toJSONString().getBytes()));
WebSocketSession unitySession = aiMedicineTimer.getUnitySession(databaseName); // WebSocketSession unitySession = aiMedicineTimer.getUnitySession(databaseName);
if (unitySession != null) { // if (unitySession != null) {
unitySession.sendMessage(new TextMessage(result.toJSONString().getBytes())); // unitySession.sendMessage(new TextMessage(result.toJSONString().getBytes()));
} // }
} // }
// 处理发送给药相关 // 处理发送给药相关
if ("addMedicine".equals(msgType) && aiMedicineTimer.getWebSession(databaseName) != null && aiMedicineTimer.getUnitySession(databaseName) != null if ("addMedicine".equals(msgType) && aiMedicineTimer.getWebSession(databaseName) != null && aiMedicineTimer.getUnitySession(databaseName) != null
&& aiMedicineTimer.isReady(databaseName)) { && aiMedicineTimer.isReady(databaseName)) {
// todo 注意修改 // todo 注意修改
// flag 0 代表人工给药, 1代表AI给药 // flag 0 代表人工给药, 1代表AI给药
vitalSignTimerWS.changeWSAIFlag(databaseName, username, session, jsonObject.getString("flag"), vitalSignTimerV2.sendMedicalMessageToUnity(databaseName, username, session, jsonObject.getString("flag"),
jsonObject.getString("medicine"), jsonObject.getString("value")); jsonObject.getString("medicine"), jsonObject.getString("value"));
} }
// 展示网页端延迟信息 // 展示网页端延迟信息
@ -119,24 +118,35 @@ public class AddMedicineHandler implements WebSocketHandler {
Long timeStamp = jsonObject.getLong("msg"); Long timeStamp = jsonObject.getLong("msg");
JSONObject result = new JSONObject(); JSONObject result = new JSONObject();
result.put("msgType", "pong"); result.put("msgType", "pong");
if (aiMedicineTimer.getWebSession(databaseName) != null) {
result.put("webMsg", "网页端已登陆");
} else {
result.put("webMsg", "网页端未登陆");
}
if (aiMedicineTimer.getUnitySession(databaseName) != null) {
result.put("unityMsg", "unity端已登录");
} else {
result.put("unityMsg", "unity端未登录");
}
// 当前时间戳 // 当前时间戳
Long diff = new Date().getTime() - timeStamp; Long diff = new Date().getTime() - timeStamp;
result.put("msg", diff); result.put("msg", diff);
session.sendMessage(new TextMessage(result.toJSONString().getBytes())); sendMsgAsync(session,result);
} }
} }
} }
@Override @Override
public void handleTransportError(WebSocketSession session, Throwable exception) { public void handleTransportError(WebSocketSession session, Throwable exception) {
stopHeartbeat(session);
aiMedicineTimer.closeConnection(session);
} }
@Override @Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) { public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
stopHeartbeat(session); stopHeartbeat(session);
vitalSignTimerWS.removeWSAIFlagSession(session);
aiMedicineTimer.closeConnection(session); aiMedicineTimer.closeConnection(session);
} }
@ -156,7 +166,7 @@ public class AddMedicineHandler implements WebSocketHandler {
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes())); session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
} else { } else {
stopHeartbeat(session); stopHeartbeat(session);
vitalSignTimerWS.removeWSAIFlagSession(session); aiMedicineTimer.closeConnection(session);
session.close(); session.close();
} }
} catch (Exception e) { } catch (Exception e) {
@ -173,5 +183,24 @@ public class AddMedicineHandler implements WebSocketHandler {
heartbeatExecutor.shutdownNow(); heartbeatExecutor.shutdownNow();
} }
// 异步发送消息
private void sendMsgAsync(WebSocketSession session, JSONObject jsonObject) {
CompletableFuture.runAsync(() -> {
try {
if (session.isOpen()) {
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
}else {
stopHeartbeat(session);
aiMedicineTimer.closeConnection(session);
session.close();
}
}catch (Exception e) {
stopHeartbeat(session);
aiMedicineTimer.closeConnection(session);
log.error("addMedicineHandler-sendMsgAsync error: {}", e.getMessage());
}
});
}
} }

View File

@ -1,16 +1,12 @@
package com.rax.vital.handler; package com.rax.vital.v2.handler;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.rax.vital.medicine.service.ChatService; import com.rax.vital.common.util.DatabaseNameUtil;
import com.rax.vital.util.DatabaseNameUtil; import com.rax.vital.v2.medicine.service.ChatService;
import com.rax.vital.util.GetHttpParamUtil;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.web.socket.*; import org.springframework.web.socket.*;
import java.net.URLDecoder;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
@ -33,13 +29,12 @@ public class ChatHandler implements WebSocketHandler {
@Override @Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
String decode = URLDecoder.decode(session.getUri().getQuery()); // String decode = URLDecoder.decode(session.getUri().getQuery());
Map params = GetHttpParamUtil.getParams(decode); // Map params = GetHttpParamUtil.getParams(decode);
String token = (String) params.get("token"); // String token = (String) params.get("token");
OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); // OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
if (authorization != null) { // if (authorization != null) {
String username = authorization.getPrincipalName(); // String username = authorization.getPrincipalName();
String payload = (String) message.getPayload(); String payload = (String) message.getPayload();
JSONObject jsonObject = JSONObject.parseObject(payload); JSONObject jsonObject = JSONObject.parseObject(payload);
if (!"heartbeat".equals(jsonObject.getString("msgType"))) { if (!"heartbeat".equals(jsonObject.getString("msgType"))) {
@ -48,12 +43,10 @@ public class ChatHandler implements WebSocketHandler {
String date = jsonObject.getString("date"); String date = jsonObject.getString("date");
// 消息内容 // 消息内容
String msg = jsonObject.getString("msg"); String msg = jsonObject.getString("msg");
System.out.println("chatHandler-jsonObject = " + jsonObject.toJSONString());
String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date; String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date;
System.out.println("chatHandler-databaseName = " + databaseName); chatService.sendMessage(databaseName,"admin",session, msg);
chatService.sendMessage(databaseName,username,session, msg);
}
} }
// }
} }
@Override @Override

View File

@ -1,28 +1,26 @@
package com.rax.vital.handler; package com.rax.vital.v2.handler;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.rax.vital.timer.AIMedicineTimer; import com.rax.vital.common.util.DatabaseNameUtil;
import com.rax.vital.timer.VitalSignTimerWS; import com.rax.vital.v2.timer.AIMedicineTimer;
import com.rax.vital.util.DatabaseNameUtil; import com.rax.vital.v2.timer.VitalSignTimerV2;
import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.*; import org.springframework.web.socket.*;
import java.io.IOException;
import java.util.Date; import java.util.Date;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/** /**
* 仪器获取网站给药信息 * 仪器获取网站给药信息
*/ */
@Slf4j
public class MachineFeedbackHandler implements WebSocketHandler { public class MachineFeedbackHandler implements WebSocketHandler {
@Resource @Autowired
private VitalSignTimerWS vitalSignTimerWS; private VitalSignTimerV2 vitalSignTimerV2;
private Map<String, ScheduledExecutorService> timerTaskMap = new ConcurrentHashMap(); private Map<String, ScheduledExecutorService> timerTaskMap = new ConcurrentHashMap();
@ -30,8 +28,11 @@ public class MachineFeedbackHandler implements WebSocketHandler {
private AIMedicineTimer aiMedicineTimer; private AIMedicineTimer aiMedicineTimer;
@Override @Override
public void afterConnectionEstablished(WebSocketSession session) { public void afterConnectionEstablished(WebSocketSession session) throws IOException {
vitalSignTimerWS.setMachineSessionMap(session); JSONObject msg = new JSONObject();
msg.put("msgType", "msg");
msg.put("msg", "已成功连接服务器!");
session.sendMessage(new TextMessage(msg.toJSONString().getBytes()));
startHeartbeat(session); startHeartbeat(session);
} }
@ -53,7 +54,7 @@ public class MachineFeedbackHandler implements WebSocketHandler {
if ("init".equals(msgType)) { if ("init".equals(msgType)) {
aiMedicineTimer.initUnity(databaseName, session); aiMedicineTimer.initUnity(databaseName, session);
vitalSignTimerWS.initUnity(databaseName, session); // vitalSignTimerWS.initUnity(databaseName, session);
} }
// Unity获取到给药信息后回复 // Unity获取到给药信息后回复
@ -81,33 +82,15 @@ public class MachineFeedbackHandler implements WebSocketHandler {
aiMedicineTimer.sendConnectionResponseToWeb(patientName, idNum, date,databaseName, unityConnectionFlag); aiMedicineTimer.sendConnectionResponseToWeb(patientName, idNum, date,databaseName, unityConnectionFlag);
} }
if (aiMedicineTimer.getWebSession(databaseName) != null) {
JSONObject result = new JSONObject();
result.put("msg", "网页端已登录");
result.put("msgType", "msg");
session.sendMessage(new TextMessage(result.toJSONString().getBytes()));
} else {
JSONObject result = new JSONObject();
result.put("msg", "网页端未登录");
result.put("msgType", "msg");
session.sendMessage(new TextMessage(result.toJSONString().getBytes()));
}
if (aiMedicineTimer.getUnitySession(databaseName) != null) {
JSONObject result = new JSONObject();
result.put("msg", "unity端已登录");
result.put("msgType", "msg");
session.sendMessage(new TextMessage(result.toJSONString().getBytes()));
WebSocketSession webSession = aiMedicineTimer.getWebSession(databaseName);
if (webSession != null) {
webSession.sendMessage(new TextMessage(result.toJSONString().getBytes()));
}
}
if (aiMedicineTimer.getUnitySession(databaseName) != null && aiMedicineTimer.getWebSession(databaseName) != null if (aiMedicineTimer.getUnitySession(databaseName) != null && aiMedicineTimer.getWebSession(databaseName) != null
&& aiMedicineTimer.isReady(databaseName)) { && aiMedicineTimer.isReady(databaseName)) {
vitalSignTimerWS.sendMachineFlag(databaseName, code, session); // vitalSignTimerWS.sendMachineFlag(databaseName, code, session);
JSONObject msg = new JSONObject();
msg.put("status", code);
msg.put("msg", "网站已进行远程连接");
msg.put("msgType", "msg");
WebSocketSession unitySession = aiMedicineTimer.getUnitySession(databaseName);
unitySession.sendMessage(new TextMessage(msg.toJSONString().getBytes()));
} }
// 展示unity端延迟信息 // 展示unity端延迟信息
@ -115,10 +98,21 @@ public class MachineFeedbackHandler implements WebSocketHandler {
Long timeStamp = jsonObject.getLong("msg"); Long timeStamp = jsonObject.getLong("msg");
JSONObject result = new JSONObject(); JSONObject result = new JSONObject();
result.put("msgType", "pong"); result.put("msgType", "pong");
if (aiMedicineTimer.getWebSession(databaseName) != null) {
result.put("webMsg", "网页端已登陆");
} else {
result.put("webMsg", "网页端未登陆");
}
if (aiMedicineTimer.getUnitySession(databaseName) != null) {
result.put("unityMsg", "unity端已登录");
}else {
result.put("unityMsg", "unity端未登录");
}
// 当前时间戳 // 当前时间戳
Long diff = new Date().getTime() - timeStamp; Long diff = new Date().getTime() - timeStamp;
result.put("msg", diff); result.put("msg", diff);
session.sendMessage(new TextMessage(result.toJSONString().getBytes())); sendMsgAsync(session, result);
} }
// unity收到给药信息后回复把此消息推送给web // unity收到给药信息后回复把此消息推送给web
@ -139,12 +133,13 @@ public class MachineFeedbackHandler implements WebSocketHandler {
@Override @Override
public void handleTransportError(WebSocketSession session, Throwable exception) { public void handleTransportError(WebSocketSession session, Throwable exception) {
stopHeartbeat(session);
aiMedicineTimer.closeConnection(session);
} }
@Override @Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) { public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
stopHeartbeat(session); stopHeartbeat(session);
vitalSignTimerWS.removeMachineSessionMap(session);
aiMedicineTimer.closeConnection(session); aiMedicineTimer.closeConnection(session);
} }
@ -164,7 +159,7 @@ public class MachineFeedbackHandler implements WebSocketHandler {
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes())); session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
} else { } else {
stopHeartbeat(session); stopHeartbeat(session);
vitalSignTimerWS.removeMachineSessionMap(session); aiMedicineTimer.closeConnection(session);
session.close(); session.close();
} }
} catch (Exception e) { } catch (Exception e) {
@ -180,4 +175,23 @@ public class MachineFeedbackHandler implements WebSocketHandler {
ScheduledExecutorService heartbeatExecutor = timerTaskMap.get(session.getId()); ScheduledExecutorService heartbeatExecutor = timerTaskMap.get(session.getId());
heartbeatExecutor.shutdownNow(); heartbeatExecutor.shutdownNow();
} }
// 异步发送消息
private void sendMsgAsync(WebSocketSession session, JSONObject jsonObject) {
CompletableFuture.runAsync(() -> {
try {
if (session.isOpen()) {
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
} else {
stopHeartbeat(session);
aiMedicineTimer.closeConnection(session);
session.close();
}
} catch (Exception e) {
stopHeartbeat(session);
aiMedicineTimer.closeConnection(session);
log.error("addMedicineHandler-sendMsgAsync error: {}", e.getMessage());
}
});
}
} }

View File

@ -1,12 +1,16 @@
package com.rax.vital.handler; package com.rax.vital.v2.handler;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.rax.vital.timer.VitalSignTimerWS; import com.rax.vital.common.util.DatabaseNameUtil;
import com.rax.vital.util.DatabaseNameUtil; import com.rax.vital.common.util.GetHttpParamUtil;
import com.rax.vital.v2.timer.VitalSignTimerV2;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.web.socket.*; import org.springframework.web.socket.*;
import java.net.URLDecoder;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
@ -18,8 +22,9 @@ import java.util.concurrent.TimeUnit;
*/ */
public class MedicineHandler implements WebSocketHandler { public class MedicineHandler implements WebSocketHandler {
@Resource @Resource
private VitalSignTimerWS vitalSignTimerWS; private VitalSignTimerV2 vitalSignTimerV2;
@Resource @Resource
private OAuth2AuthorizationService authorizationService; private OAuth2AuthorizationService authorizationService;
@ -33,11 +38,11 @@ public class MedicineHandler implements WebSocketHandler {
@Override @Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) { public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) {
// String decode = URLDecoder.decode(session.getUri().getQuery()); String decode = URLDecoder.decode(session.getUri().getQuery());
// Map params = GetHttpParamUtil.getParams(decode); Map params = GetHttpParamUtil.getParams(decode);
// String token = (String) params.get("token"); String token = (String) params.get("token");
// OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
// String username = authorization.getPrincipalName(); String username = authorization.getPrincipalName();
String payload = (String) message.getPayload(); String payload = (String) message.getPayload();
JSONObject jsonObject = JSONObject.parseObject(payload); JSONObject jsonObject = JSONObject.parseObject(payload);
@ -47,20 +52,22 @@ public class MedicineHandler implements WebSocketHandler {
String idNum = jsonObject.getString("idNum"); String idNum = jsonObject.getString("idNum");
String date = jsonObject.getString("date"); String date = jsonObject.getString("date");
String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date; String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date;
vitalSignTimerWS.createAndSendWSMessageMongo(databaseName, "admin", session); vitalSignTimerV2.sendMedicalMessage(databaseName, username, session);
} }
} }
@Override @Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
System.out.println("Error: " + exception.getMessage()); System.out.println("Error: " + exception.getMessage());
stopHeartbeat(session);
vitalSignTimerV2.stopTimerTask(session.getId());
} }
@Override @Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
System.out.println("MedicineHandler Connection closed:" + closeStatus.getReason()); System.out.println("MedicineHandler Connection closed:" + closeStatus.getReason());
stopHeartbeat(session); stopHeartbeat(session);
vitalSignTimerWS.stopTimerTask(session.getId()); vitalSignTimerV2.stopTimerTask(session.getId());
} }
@Override @Override
@ -80,7 +87,7 @@ public class MedicineHandler implements WebSocketHandler {
} else { } else {
session.close(); session.close();
stopHeartbeat(session); stopHeartbeat(session);
vitalSignTimerWS.stopTimerTask(session.getId()); vitalSignTimerV2.stopTimerTask(session.getId());
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -0,0 +1,55 @@
package com.rax.vital.v2.interceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.stereotype.Component;
import java.util.List;
@Slf4j
@Component
public class WSChannelInterceptor implements ChannelInterceptor {
@Autowired
private OAuth2AuthorizationService authorizationService;
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
if (accessor != null) {
List<String> accessToken = accessor.getNativeHeader("token");
if (accessToken != null && !accessToken.isEmpty()) {
String token = accessToken.get(0);
OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
if (StompCommand.CONNECT.equals(accessor.getCommand()) || StompCommand.SEND.equals(accessor.getCommand())) {
if (authorization == null) {
throw new AccessDeniedException("Access is denied");
}
}
}
if (StompCommand.DISCONNECT.equals(accessor.getCommand())
|| StompCommand.UNSUBSCRIBE.equals(accessor.getCommand()) || StompCommand.ABORT.equals(accessor.getCommand())) {
// String simpSessionId = (String) accessor.getHeader("simpSessionId");
// vitalSignTimer.stopTimerTaskMongo(simpSessionId);
// chatService.stopTimerTask(simpSessionId);
}
}
return message;
}
}

View File

@ -0,0 +1,38 @@
package com.rax.vital.v2.interceptor;
import com.rax.vital.common.util.GetHttpParamUtil;
import jakarta.annotation.Resource;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import java.net.URLDecoder;
import java.util.Map;
public class WebSocketInterceptors implements HandshakeInterceptor {
@Resource
private OAuth2AuthorizationService authorizationService;
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
String decode = URLDecoder.decode(request.getURI().getQuery());
Map params = GetHttpParamUtil.getParams(decode);
String token = (String) params.get("token");
OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
if (authorization == null ) {
return false;
}
return true;
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
System.out.println("request = " + request + ", response = " + response + ", wsHandler = " + wsHandler + ", exception = " + exception);
}
}

View File

@ -0,0 +1,50 @@
package com.rax.vital.v2.medicine.controller;
import com.alibaba.fastjson.JSONObject;
import com.rax.vital.v2.medicine.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import java.util.ArrayList;
@Controller
public class ChatController {
@Autowired
private ChatService chatService;
@Autowired
private OAuth2AuthorizationService authorizationService;
@MessageMapping("/sendMessage")
public void sendMessage(MessageHeaders messageHeaders, String body) {
LinkedMultiValueMap nativeHeaders = (LinkedMultiValueMap) messageHeaders.get("nativeHeaders");
ArrayList tokenList = (ArrayList) nativeHeaders.get("token");
String token = (String) tokenList.get(0);
OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
if (authorization != null) {
String username = authorization.getPrincipalName();
String simpSessionId = messageHeaders.get("simpSessionId", String.class);
JSONObject params = JSONObject.parseObject(body);
// 病人名
String patientName = params.getString("patientName");
// 病人身份证
String idNum = params.getString("idNum");
// yyyyMMdd
String date = params.getString("date");
// 消息内容
String msg = params.getString("msg");
chatService.sendMessage(username, patientName, idNum, date, simpSessionId, msg);
} else {
throw new AccessDeniedException("Access is denied");
}
}
}

View File

@ -0,0 +1,104 @@
package com.rax.vital.v2.medicine.controller;
import com.rax.common.core.util.R;
import com.rax.vital.common.util.DatabaseNameUtil;
import com.rax.vital.v2.medicine.service.DoctorMedicineService;
import com.rax.vital.v2.medicine.service.SurgeryServiceV2;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 用药
*
* @date 2024.2.19
*/
@RestController
@Tag(description = "medicine", name = "人工和AI用药管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
@RequestMapping("/medicine")
public class MedicineController {
// @Autowired
// private VitalSignTimer vitalSignTimer;
@Autowired
private OAuth2AuthorizationService authorizationService;
@Autowired
private DoctorMedicineService doctorMedicineService;
@Autowired
private SurgeryServiceV2 surgeryServiceV2;
@PostMapping("/getPatientInfo")
public R getPatientInfo(String patientName, String idNum, String date) {
// todo : 存疑
String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date;
return surgeryServiceV2.getPatientInfo(databaseName);
}
@PostMapping("/getPatientPage")
public R getPatientPage(String name, String dept, long offset, int limit) {
return R.ok(surgeryServiceV2.getPatientPage(name, dept, offset, limit));
}
/**
* 某月手术每天台数
*/
@PostMapping("/getSurgeryCount")
public R getSurgeryCount(String start, String end) {
return R.ok(surgeryServiceV2.getSurgeryCount(start, end));
}
/**
* 某月手术每天时长
*/
@PostMapping("/getSurgeryDuration")
public R getSurgeryDuration(String start, String end) {
return R.ok(surgeryServiceV2.getSurgeryDuration(start, end));
}
/**
* 某月手术类型数量
*/
@PostMapping("/getSurgeryTypeProportion")
public R getSurgeryTypeProportion(String start, String end) {
return R.ok(surgeryServiceV2.getSurgeryTypeProportion(start, end));
}
/**
* 某周的麻醉和人工给药时长
*/
@PostMapping("/getSurgeryOtherDuration")
public R getSurgeryOtherDuration(String start, String end) {
return R.ok(surgeryServiceV2.getSurgeryOtherDuration(start, end));
}
/**
* 获取用户的手术列表
*/
@PostMapping("/getPatientSurgeryList")
public R getPatientSurgeryList(String name, String code, String surgery, String type) {
return R.ok(surgeryServiceV2.getPatientSurgeryList(name, code, surgery, type));
}
/**
* 根据手术表名来获取所有数据
*/
@PostMapping("/getSurgeryTableData")
public R getSurgeryTableData(String name, String code, String date, String table) {
return R.ok(surgeryServiceV2.getSurgeryTableData(name, code, date, table));
}
}

View File

@ -1,4 +1,4 @@
package com.rax.vital.medicine.dto; package com.rax.vital.v2.medicine.dto;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;

View File

@ -0,0 +1,50 @@
package com.rax.vital.v2.medicine.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.sql.Timestamp;
@Data
@Schema(description = "AI给药")
public class AIMedicine implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "id")
private Long id;
@Schema(description = "phase")
private Long phase;
@Schema(description = "丙泊酚")
private Double 丙泊酚;
@Schema(description = "舒芬太尼")
private Double 舒芬太尼;
@Schema(description = "瑞芬太尼")
private Double 瑞芬太尼;
@Schema(description = "顺阿曲库胺")
private Double 顺阿曲库胺;
@Schema(description = "尼卡地平")
private Double 尼卡地平;
@Schema(description = "艾司洛尔")
private Double 艾司洛尔;
@Schema(description = "麻黄素")
private Double 麻黄素;
@Schema(description = "阿托品")
private Double 阿托品;
@Schema(description = "创建时间")
private Timestamp time;
}

View File

@ -0,0 +1,49 @@
package com.rax.vital.v2.medicine.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.sql.Timestamp;
@Data
@Schema(description = "医生给药")
public class DoctorMedicine implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "id")
private Long id;
@Schema(description = "phase")
private Long phase;
@Schema(description = "丙泊酚")
private Double 丙泊酚;
@Schema(description = "舒芬太尼")
private Double 舒芬太尼;
@Schema(description = "瑞芬太尼")
private Double 瑞芬太尼;
@Schema(description = "顺阿曲库胺")
private Double 顺阿曲库胺;
@Schema(description = "尼卡地平")
private Double 尼卡地平;
@Schema(description = "艾司洛尔")
private Double 艾司洛尔;
@Schema(description = "麻黄素")
private Double 麻黄素;
@Schema(description = "阿托品")
private Double 阿托品;
@Schema(description = "创建时间")
private Timestamp time;
}

View File

@ -0,0 +1,49 @@
package com.rax.vital.v2.medicine.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.sql.Timestamp;
@Data
@Schema(description = "诱导期给药")
public class Revulsion implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "id")
private Long id;
@Schema(description = "phase")
private Long phase;
@Schema(description = "丙泊酚")
private Double 丙泊酚;
@Schema(description = "舒芬太尼")
private Double 舒芬太尼;
@Schema(description = "瑞芬太尼")
private Double 瑞芬太尼;
@Schema(description = "顺阿曲库胺")
private Double 顺阿曲库胺;
@Schema(description = "尼卡地平")
private Double 尼卡地平;
@Schema(description = "艾司洛尔")
private Double 艾司洛尔;
@Schema(description = "麻黄素")
private Double 麻黄素;
@Schema(description = "阿托品")
private Double 阿托品;
@Schema(description = "创建时间")
private Timestamp time;
}

View File

@ -1,4 +1,4 @@
package com.rax.vital.medicine.service; package com.rax.vital.v2.medicine.service;
import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.MongoTemplate;

View File

@ -0,0 +1,15 @@
package com.rax.vital.v2.medicine.service;
import org.springframework.web.socket.WebSocketSession;
import java.io.IOException;
public interface ChatService {
void sendMessage(String username, String patientName, String idNum, String date, String simpSessionId, String msg);
void sendMessage(String dbName, String username, WebSocketSession session, String msg) throws IOException;
void stopTimerTask(String simpSessionId);
void stopTask(String simpSessionId);
}

View File

@ -1,4 +1,4 @@
package com.rax.vital.medicine.service; package com.rax.vital.v2.medicine.service;
import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.MongoTemplate;

View File

@ -0,0 +1,14 @@
package com.rax.vital.v2.medicine.service;
import org.springframework.data.mongodb.core.MongoTemplate;
import java.sql.Connection;
import java.util.Map;
public interface FlagService {
Map getFlags(MongoTemplate template);
Map getFlag(MongoTemplate template);
Map getFlag(Connection connection);
}

View File

@ -0,0 +1,27 @@
package com.rax.vital.v2.medicine.service;
import org.springframework.data.mongodb.core.MongoTemplate;
import java.sql.Connection;
import java.util.List;
import java.util.Map;
/**
* 诱导期给药数据
*/
public interface RevulsionService {
/**
* 获取诱导期给药数据MongoDB
*
* @return
*/
List<Map> getRevulsionServiceList(MongoTemplate template);
/**
* 获取诱导期给药数据MySQL
*
* @return
*/
List<Map> getRevulsionServiceList(Connection connection);
}

View File

@ -0,0 +1,102 @@
package com.rax.vital.v2.medicine.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rax.common.core.util.R;
import org.springframework.data.mongodb.core.MongoTemplate;
import java.util.List;
import java.util.Map;
/**
* project_name:remote-control-backend
* time:2024/8/23 16:00
* author: republicline
* 二期版本: 获取术中过程中的各种信息接口
*/
public interface SurgeryServiceV2 {
/**
* 获取MongoDB最新一条生命体征数据
*
* @return
*/
List<Map> getVitalSignsList(MongoTemplate template);
/**
* 获取患者基本信息
*
* @param databaseName
* @return
*/
R getPatientInfo(String databaseName);
/**
* 获取患者列表, informationDB中获取, 查询 surgery_info
*
* @param name
* @param dept
* @param offset
* @param limit
* @return
*/
Page getPatientPage(String name, String dept, long offset, int limit);
/**
* 统计手术的数量
*
* @param start
* @param end
* @return
*/
List getSurgeryCount(String start, String end);
/**
* 统计手术时长
*
* @param start
* @param end
* @return
*/
List getSurgeryDuration(String start, String end);
/**
* 统计手术类型比例
*
* @param start
* @param end
* @return
*/
List getSurgeryTypeProportion(String start, String end);
/**
* 代补充
*
* @param start
* @param end
* @return
*/
List getSurgeryOtherDuration(String start, String end);
/**
* 获取患者手术列表
*
* @param name
* @param code
* @param surgery
* @param type
* @return
*/
List getPatientSurgeryList(String name, String code, String surgery, String type);
/**
* 根据患者名称 or 入院号, 查询术后患者的各项信息 -> 用药信息, 给药信息, 生命体征信息
*
* @param name
* @param code
* @param date
* @param table
* @return
*/
List getSurgeryTableData(String name, String code, String date, String table);
}

View File

@ -1,8 +1,7 @@
package com.rax.vital.medicine.service.impl; package com.rax.vital.v2.medicine.service.impl;
import cn.hutool.core.collection.ListUtil;
import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObject;
import com.rax.vital.medicine.service.AIMedicineService; import com.rax.vital.v2.medicine.service.AIMedicineService;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
@ -200,6 +199,9 @@ public class AIMedicineServiceImpl implements AIMedicineService {
query.limit(1); query.limit(1);
query.with(Sort.by(Sort.Order.desc("Time"))); query.with(Sort.by(Sort.Order.desc("Time")));
List<Map> aimedicinetable = template.find(query, Map.class, "aimedicinetable"); List<Map> aimedicinetable = template.find(query, Map.class, "aimedicinetable");
if (aimedicinetable.isEmpty()) {
return null;
}
return aimedicinetable.get(0); return aimedicinetable.get(0);
} }
} }

View File

@ -0,0 +1,178 @@
package com.rax.vital.v2.medicine.service.impl;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rax.admin.api.entity.SysUser;
import com.rax.admin.service.SysUserService;
import com.rax.vital.common.datasource.CustomDataSource;
import com.rax.vital.common.datasource.MongoDBSource;
import com.rax.vital.common.util.DatabaseNameUtil;
import com.rax.vital.v2.medicine.service.ChatService;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@RefreshScope
@Service
public class ChatServiceImpl implements ChatService {
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
@Autowired
private SysUserService SysUserService;
private static final Map<String, CustomDataSource> datasourceMap = new ConcurrentHashMap<>();
// key: databaseName, value: Map<simpSessionId, WebSocketSession>
private static final Map<String, Map<String, WebSocketSession>> databaseSessionMap = new ConcurrentHashMap<>();
private static final Map<String, String> sessionDatabaseMap = new ConcurrentHashMap<>();
// MongoDB的地址
@Value("${vital-sign.mongodb.host}")
private String mongoDBHost;
// MongoDB的用户名
@Value("${vital-sign.mongodb.username}")
private String mongoUsername;
// MongoDB的用户的密码
@Value("${vital-sign.mongodb.password}")
private String mongoPassword;
// mysql地址
@Value("${vital-sign.mysql.host}")
private String mysqlHost;
// mysql用户名
@Value("${vital-sign.mysql.username}")
private String mysqlUsername;
// mysql用户密码
@Value("${vital-sign.mysql.password}")
private String mysqlPassword;
@Override
public void sendMessage(String username, String patientName, String idNum, String date, String simpSessionId, String msg) {
CustomDataSource mongoDBSource = datasourceMap.get(simpSessionId);
if (mongoDBSource == null) {
String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date;
mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, databaseName);
datasourceMap.put(simpSessionId, mongoDBSource);
mongoDBSource.open();
}
SysUser sysUser = SysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
Map param = new HashMap();
MongoTemplate template = mongoDBSource.getConnection();
Document document = new Document();
document.put("content", msg);
param.put("content", msg);
String now = DateUtil.now();
document.put("create_time", now);
param.put("createTime", now);
document.put("create_user", username);
String name = sysUser.getName();
document.put("create_name", name);
param.put("createName", name);
document.put("deleted", 0);
document.put("revoked", 0);
template.insert(document, "t_chat");
simpMessagingTemplate.convertAndSendToUser(patientName + idNum + date, "/chatroomMessage", param);
}
@Override
public void sendMessage(String databaseName, String username, WebSocketSession session, String msg) throws IOException {
CustomDataSource mongoDBSource = datasourceMap.get(session.getId());
if (mongoDBSource == null) {
mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, databaseName);
mongoDBSource.open();
datasourceMap.put(session.getId(), mongoDBSource);
sessionDatabaseMap.put(session.getId(), databaseName);
Map<String, WebSocketSession> sessionMap = databaseSessionMap.get(databaseName);
if (sessionMap == null) {
sessionMap = new HashMap();
sessionMap.put(session.getId(), session);
databaseSessionMap.put(databaseName, sessionMap);
} else {
if (!sessionMap.containsKey(session.getId())) {
sessionMap.put(session.getId(), session);
}
}
}
SysUser sysUser = SysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
// 将聊天消息保存在mongo中
if (StringUtils.hasText(msg)) {
JSONObject param = new JSONObject();
MongoTemplate template = mongoDBSource.getConnection();
Document document = new Document();
document.put("content", msg);
param.put("content", msg);
String now = DateUtil.now();
document.put("create_time", now);
param.put("createTime", now);
document.put("create_user", username);
String name = sysUser.getName();
document.put("create_name", name);
param.put("createName", name);
document.put("deleted", 0);
document.put("revoked", 0);
template.insert(document, "t_chat");
param.put("msgType", "msg");
Map<String, WebSocketSession> sessionMap = databaseSessionMap.get(databaseName);
for (Map.Entry<String, WebSocketSession> entry : sessionMap.entrySet()) {
WebSocketSession value = entry.getValue();
value.sendMessage(new TextMessage(param.toJSONString().getBytes()));
}
}
}
@Override
public synchronized void stopTimerTask(String simpSessionId) {
CustomDataSource mongoDBSource = datasourceMap.get(simpSessionId);
if (mongoDBSource != null) {
mongoDBSource.close();
datasourceMap.remove(simpSessionId);
}
}
@Override
public synchronized void stopTask(String simpSessionId) {
CustomDataSource mongoDBSource = datasourceMap.get(simpSessionId);
if (mongoDBSource != null) {
mongoDBSource.close();
datasourceMap.remove(simpSessionId);
}
String databaseName = sessionDatabaseMap.get(simpSessionId);
if (databaseName != null) {
sessionDatabaseMap.remove(simpSessionId);
Map<String, WebSocketSession> stringWebSocketSessionMap = databaseSessionMap.get(databaseName);
stringWebSocketSessionMap.remove(simpSessionId);
if (stringWebSocketSessionMap.isEmpty()) {
databaseSessionMap.remove(databaseName);
}
}
}
}

View File

@ -1,6 +1,6 @@
package com.rax.vital.medicine.service.impl; package com.rax.vital.v2.medicine.service.impl;
import com.rax.vital.medicine.service.DoctorMedicineService; import com.rax.vital.v2.medicine.service.DoctorMedicineService;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
@ -31,6 +31,9 @@ public class DoctorMedicineServiceImpl implements DoctorMedicineService {
query.limit(1); query.limit(1);
query.with(Sort.by(Sort.Order.desc("Time"))); query.with(Sort.by(Sort.Order.desc("Time")));
List<Map> doctorMedicineTable = template.find(query, Map.class, "doctormedicinetable"); List<Map> doctorMedicineTable = template.find(query, Map.class, "doctormedicinetable");
if (doctorMedicineTable.isEmpty()){
return null;
}
return doctorMedicineTable.get(0); return doctorMedicineTable.get(0);
} }

View File

@ -1,6 +1,6 @@
package com.rax.vital.medicine.service.impl; package com.rax.vital.v2.medicine.service.impl;
import com.rax.vital.medicine.service.FlagService; import com.rax.vital.v2.medicine.service.FlagService;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;

Some files were not shown because too many files have changed in this diff Show More