package cn.besteam.modules.system.service.impl; import cn.besteam.common.constant.CacheKey; import cn.besteam.common.constant.CommonConstant; import cn.besteam.common.constant.DepartmentEnum; import cn.besteam.common.constant.ErrorCode; import cn.besteam.common.exception.BusinessException; import cn.besteam.common.util.IPUtils; import cn.besteam.common.util.MD5Util; import cn.besteam.common.util.RedisUtil; import cn.besteam.common.util.StringUtil; import cn.besteam.config.AliSmsConfig; import cn.besteam.modules.medical.entity.MwDeviceValidateRecord; import cn.besteam.modules.medical.entity.MwServicePeriod; import cn.besteam.modules.medical.service.IMwDeviceValidateRecordService; import cn.besteam.modules.medical.service.IMwServicePeriodService; import cn.besteam.modules.medical.vo.MwServicePeriodListDTO; import cn.besteam.modules.shiro.authc.util.EnvUtils; import cn.besteam.modules.system.biz.AliSmsService; import cn.besteam.modules.system.dto.*; import cn.besteam.modules.system.entity.*; import cn.besteam.modules.system.mapper.SysUserMapper; import cn.besteam.modules.system.service.*; import cn.besteam.modules.system.util.NouNouPayUtil; import cn.besteam.modules.system.util.vo.PaymentOrderVO; import cn.besteam.modules.system.vo.*; import cn.hutool.poi.excel.ExcelReader; import cn.hutool.poi.excel.ExcelUtil; import cn.hutool.poi.excel.ExcelWriter; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StopWatch; import javax.annotation.Resource; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * @Description: 用户 * @author: besteam * @date: 2020-04-16 * @version: V1.0 */ @Service @Slf4j public class SysUserServiceImpl extends ServiceImpl implements ISysUserService { private static final String PASSWORD_SALT = "?me^&di^&!c#al@zy"; @Value("${medical.domain}") private String medicalDomain; @Autowired private RedisUtil redisUtil; @Autowired private ISysUserRoleService sysUserRoleService; @Autowired private ISysUserDepartmentService sysUserDepartmentService; @Autowired private ISysRoleService sysRoleService; @Autowired private ISysDepartmentService sysDepartmentService; @Autowired private IMwDeviceValidateRecordService mwDeviceValidateRecordService; @Autowired private AliSmsService aliSmsService; @Resource private AliSmsConfig aliSmsConfig; @Autowired private ISysRolePermissionService sysRolePermissionService; @Autowired private ISysDepartmentInformationService sysDepartmentInformationService; @Autowired private ISysDictItemService dictItemService; @Autowired private IMwServicePeriodService servicePeriodService; @Autowired private ISysDepartmentService departmentService; @Autowired private NouNouPayUtil nouNouPayUtil; @Value("${nuonuo.callbackUrl}") private String callbackUrl;//支付回调地址 /** * 用户登录 * * @param response * @param dto * @return */ @Override public SysUserVO login(HttpServletRequest request,HttpServletResponse response, SysUserLoginDTO dto) { SysUser sysUser = getOne(new QueryWrapper().lambda().eq(SysUser::getAccount, dto.getAccount())); if (sysUser == null) { throw new BusinessException(ErrorCode.LOGIN_USER_NOT_FOUND); } if (!sysUser.getStatus().equals(CommonConstant.STATUS_NORMAL)) { throw new BusinessException(ErrorCode.USER_HAS_BEEN_FROZEN); } if (!sysUser.getDelFlag().equals(CommonConstant.DEL_FLAG_0)) { throw new BusinessException(ErrorCode.USER_NOT_FOUND); } String passwordEncode = dto.getPassword(); if(dto.getPassword().length()!=32){//需要加密 passwordEncode = MD5Util.MD5Encode(dto.getPassword() + PASSWORD_SALT, null); } String ip=IPUtils.getIpAddr(request).trim().replace(".",""); Integer wrongPasswordCountR = redisUtil.get(CacheKey.getWrongPasswordCount()+ip); Integer wrongPasswordCount = 0; if(wrongPasswordCountR!=null){ if(wrongPasswordCountR>=10){//用户冻结 throw new BusinessException(ErrorCode.USER_LOGIN_WRONG); } } if (!passwordEncode.equals(sysUser.getPassword())) { if (wrongPasswordCountR!=null) { wrongPasswordCount = wrongPasswordCountR; } redisUtil.set(CacheKey.getWrongPasswordCount()+ip, wrongPasswordCount+1, 10*60); throw new BusinessException(ErrorCode.LOGIN_USER_OR_PASSWORD_INVALID); }else { if (wrongPasswordCountR!=null) { redisUtil.del(CacheKey.getWrongPasswordCount()+ip); } } SysUserVO vo = new SysUserVO(); //增加判断是否到期 SysDepartment myDepartment = departmentService.getMyDepartment(sysUser.getId()); if(null != myDepartment) { if(myDepartment.getOrgType() == 3 || myDepartment.getOrgType() == 4){ SysDepartment hospital = departmentService.getHospital(myDepartment.getParentId()); if (null != hospital) { if(null != hospital.getExpireDate() && hospital.getExpireDate().getTime() <= System.currentTimeMillis()){ throw new BusinessException(ErrorCode.ACCOUNT_EXPIRED, hospital.getId().toString()+"-0"); } } } if(myDepartment.getOrgType() == 2){ if(null != myDepartment.getExpireDate() && myDepartment.getExpireDate().getTime() <= System.currentTimeMillis()){ String a ="-"; Integer id = myDepartment.getId(); List mwServicePeriods = servicePeriodService.getBaseMapper().selectList(new LambdaQueryWrapper().eq(MwServicePeriod::getDepartmentId, id).orderByDesc(MwServicePeriod::getCreateTime)); if(mwServicePeriods.size()>0){ a = myDepartment.getServiceCharge().toString(); } throw new BusinessException(ErrorCode.ACCOUNT_EXPIRED, myDepartment.getId().toString()+a); } } } sysUser.setPassword(null); String token = StringUtil.uuidNotLine(); // BeanUtils.copyProperties(sysUser, vo); //生成人员二维码 String content = "{\"id\":" + sysUser.getId() + ",\"type\":\"2\",\"code\":\"" + sysUser.getCode() + "\"}"; String qrUrl=Base64.getEncoder().encodeToString(content.getBytes()); vo.setQrUrl(qrUrl); vo.setToken(token); fillSysUserVO(vo); sysUser.setHospitalId(vo.getDepartmentId()); setByToken(response, token, sysUser); Integer count=sysDepartmentInformationService.queryOneCount(vo.getDepartmentId()); if(count!=null && count>0){ vo.setIsCompleteInformation(1); } if(vo.getOrgType()==1 && vo.getIsCompleteInformation()==0){ vo.setIsCompleteInformation(1); } myDepartment = departmentService.getMyDepartment(sysUser.getId()); SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if(null != myDepartment){ if(myDepartment.getOrgType() == 3 || myDepartment.getOrgType() == 4) { SysDepartment hospital = departmentService.getHospital(myDepartment.getParentId()); if (null != hospital) { vo.setExpireDate(null == hospital.getExpireDate() ? "" : sdf.format(hospital.getExpireDate())); vo.setHospitalId(hospital.getId()); vo.setReminderDays(hospital.getReminderDays()); } } if(myDepartment.getOrgType() == 2){ vo.setExpireDate(null == myDepartment.getExpireDate() ? "" : sdf.format(myDepartment.getExpireDate())); vo.setHospitalId(myDepartment.getId()); vo.setReminderDays(myDepartment.getReminderDays()); } } return vo; } private void fillSysUserVO(SysUserVO vo) { SysUserRole sysUserRole = sysUserRoleService.getOne(new QueryWrapper().lambda().eq(SysUserRole::getUserId, vo.getId())); if (sysUserRole != null) { SysRole sysRole = sysRoleService.getById(sysUserRole.getRoleId()); if (sysRole != null) { vo.setRoleId(sysRole.getId()); vo.setRoleLogo(sysRole.getLogo()); vo.setRoleType(sysRole.getType()); } } // SysDepartment department = sysDepartmentService.getMyDepartment(vo.getId()); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if (department != null) { if (department.getOrgType().equals(DepartmentEnum.OrgTypeEnum.DEPARTMENT.getType()) || department.getOrgType().equals(DepartmentEnum.OrgTypeEnum.OFFICE.getType())) { SysDepartment hospital = sysDepartmentService.getHospital(department.getParentId()); if (hospital != null) { vo.setDepartmentId(hospital.getId()); vo.setDepartmentName(hospital.getDepartName()); vo.setOrgCode(hospital.getOrgCode()); vo.setSelectSwitch(hospital.getSelectSwitch()); vo.setCheckallSwitch(hospital.getCheckallSwitch()); vo.setSignatureSwitch(hospital.getSignatureSwitch()); vo.setReminderDays(hospital.getReminderDays()); if(hospital.getExpireDate()!=null){ vo.setExpireDate(simpleDateFormat.format(hospital.getExpireDate())); } vo.setEnvironmentalHandoverSwitch(hospital.getEnvironmentalHandoverSwitch()); vo.setOutboundWeighingSwitch(hospital.getOutboundWeighingSwitch()); vo.setOutboundPrintingSwitch(hospital.getOutboundPrintingSwitch()); vo.setBluetoothPrintSwitch(hospital.getBluetoothPrintSwitch()); vo.setBluetoothWeighSwitch(hospital.getBluetoothWeighSwitch()); vo.setChipBoxSwitch(hospital.getChipBoxSwitch()); vo.setCustomNumber(hospital.getCustomNumber()==null?"":hospital.getCustomNumber()); } } else { vo.setDepartmentId(department.getId()); vo.setDepartmentName(department.getDepartName()); vo.setOrgCode(department.getOrgCode()); vo.setSelectSwitch(department.getSelectSwitch()); vo.setCheckallSwitch(department.getCheckallSwitch()); vo.setReminderDays(department.getReminderDays()); if(department.getExpireDate()!=null){ vo.setExpireDate(simpleDateFormat.format(department.getExpireDate())); } vo.setSignatureSwitch(department.getSignatureSwitch()); vo.setEnvironmentalHandoverSwitch(department.getEnvironmentalHandoverSwitch()); vo.setOutboundWeighingSwitch(department.getOutboundWeighingSwitch()); vo.setOutboundPrintingSwitch(department.getOutboundPrintingSwitch()); vo.setBluetoothPrintSwitch(department.getBluetoothPrintSwitch()); vo.setBluetoothWeighSwitch(department.getBluetoothWeighSwitch()); vo.setChipBoxSwitch(department.getChipBoxSwitch()); vo.setCustomNumber(department.getCustomNumber()==null?"":department.getCustomNumber()); } vo.setDepartmentIdList(sysDepartmentService.getParentIdList(department.getId())); vo.setOrgType(department.getOrgType()); } } @Override public SysUserVO current() { SysUser sysUser = EnvUtils.getUser(); SysUserVO vo = new SysUserVO(); BeanUtils.copyProperties(sysUser, vo); fillSysUserVO(vo); return vo; } private void setByToken(HttpServletResponse response, String token, SysUser sysUser) { redisUtil.set(CacheKey.getUserCacheKey(token), sysUser, CacheKey.USER_SESSION_TIMEOUT); Cookie cookie = new Cookie(CommonConstant.X_ACCESS_TOKEN, token); cookie.setPath("/"); cookie.setDomain(medicalDomain); cookie.setMaxAge(-1); response.addCookie(cookie); } public String getToken(HttpServletRequest request) { String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN); if (token == null && request.getCookies() != null) { for (Cookie cookie : request.getCookies()) { if (CommonConstant.X_ACCESS_TOKEN.equals(cookie.getName())) { token = cookie.getValue(); break; } } } return token; } @Override public SysUser getByToken(String token) { return redisUtil.get(CacheKey.getUserCacheKey(token)); } @Override public AppSysUserVO appLogin(SysUserLoginDTO dto) { SysUser sysUser = getOne(new QueryWrapper().lambda().eq(SysUser::getAccount, dto.getAccount())); if (sysUser == null) { throw new BusinessException(ErrorCode.LOGIN_USER_NOT_FOUND); } if (!sysUser.getStatus().equals(CommonConstant.STATUS_NORMAL)) { throw new BusinessException(ErrorCode.USER_HAS_BEEN_FROZEN); } if (!sysUser.getDelFlag().equals(CommonConstant.DEL_FLAG_0)) { throw new BusinessException(ErrorCode.USER_NOT_FOUND); } String passwordEncode = MD5Util.MD5Encode(dto.getPassword() + PASSWORD_SALT, null); if (!passwordEncode.equals(sysUser.getPassword())) { throw new BusinessException(ErrorCode.LOGIN_USER_PASSWORD_INVALID); } //增加判断是否到期 SysDepartment myDepartment = departmentService.getMyDepartment(sysUser.getId()); if(null != myDepartment) { if(myDepartment.getOrgType() == 3 || myDepartment.getOrgType() == 4){ SysDepartment hospital = departmentService.getHospital(myDepartment.getParentId()); if (null != hospital) { if(null != hospital.getExpireDate() && hospital.getExpireDate().getTime() <= System.currentTimeMillis()){ throw new BusinessException(ErrorCode.ACCOUNT_EXPIRED, hospital.getId().toString()); } } } if(myDepartment.getOrgType() == 2){ if(null != myDepartment.getExpireDate() && myDepartment.getExpireDate().getTime() <= System.currentTimeMillis()){ throw new BusinessException(ErrorCode.ACCOUNT_EXPIRED, myDepartment.getId().toString()); } } } //增加小程序登录的判断 if(null == dto.getSn()){ myDepartment = sysDepartmentService.getMyDepartment(sysUser.getId()); if(null == myDepartment){//部门 throw new BusinessException(ErrorCode.LOGIN_USER_NOT_FOUND); } SysDepartment hospital = sysDepartmentService.getHospital(myDepartment.getParentId()); if(null == hospital){//所在医院 throw new BusinessException(ErrorCode.LOGIN_USER_NOT_FOUND); } if(hospital.getAppletSwitch() == 0){//医院开关 throw new BusinessException(ErrorCode.ERR_500, "未授权设备"); } } // sysUser.setPassword(null); String token = StringUtil.uuidNotLine(); // AppSysUserVO vo = new AppSysUserVO(); BeanUtils.copyProperties(sysUser, vo); //生成人员二维码 String content = "{\"id\":" + sysUser.getId() + ",\"type\":\"2\",\"code\":\"" + sysUser.getCode() + "\"}"; String qrUrl=Base64.getEncoder().encodeToString(content.getBytes()); vo.setQrUrl(qrUrl); vo.setToken(token); fillSysUserVO(vo); sysUser.setHospitalId(vo.getDepartmentId()); setByAppToken(token, sysUser); mwDeviceValidateRecordService.save(new MwDeviceValidateRecord(dto.getSn(), sysUser.getId(), vo.getDepartmentId())); return vo; } @Override public AppSysUserVO appLoginByCode(String code, String sn) { SysUser sysUser = getOne(new QueryWrapper().lambda().eq(SysUser::getCode, code)); if (sysUser == null) { throw new BusinessException(ErrorCode.USER_NOT_FOUND); } if (!sysUser.getStatus().equals(CommonConstant.STATUS_NORMAL)) { throw new BusinessException(ErrorCode.USER_HAS_BEEN_FROZEN); } if (!sysUser.getDelFlag().equals(CommonConstant.DEL_FLAG_0)) { throw new BusinessException(ErrorCode.USER_NOT_FOUND); } // sysUser.setPassword(null); String token = StringUtil.uuidNotLine(); // AppSysUserVO vo = new AppSysUserVO(); BeanUtils.copyProperties(sysUser, vo); //生成人员二维码 String content = "{\"id\":" + sysUser.getId() + ",\"type\":\"2\",\"code\":\"" + sysUser.getCode() + "\"}"; String qrUrl=Base64.getEncoder().encodeToString(content.getBytes()); vo.setQrUrl(qrUrl); vo.setToken(token); fillSysUserVO(vo); sysUser.setHospitalId(vo.getDepartmentId()); setByAppToken(token, sysUser); mwDeviceValidateRecordService.save(new MwDeviceValidateRecord(sn, sysUser.getId(), vo.getDepartmentId())); return vo; } private void setByAppToken(String token, SysUser sysUser) { redisUtil.set(CacheKey.getUserCacheKey(token), sysUser, CacheKey.USER_SESSION_TIMEOUT); } @Override public SysUser getByAppToken(String token) { // TODO 考虑下App端的key要不要区分 return redisUtil.get(CacheKey.getUserCacheKey(token)); } /** * 用户列表 * * @param pageNo * @param pageSize * @param req * @param keyword * @return */ @Override public IPage queryPageList(Integer pageNo, Integer pageSize, HttpServletRequest req, String keyword, Integer hospitalId,String roleName) { SysDepartment sysDepartment = null; if (hospitalId == null) { sysDepartment = sysDepartmentService.getMyDepartment(EnvUtils.getUser().getId()); if (sysDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.DEPARTMENT.getType()) || sysDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.OFFICE.getType())) { sysDepartment = sysDepartmentService.getHospital(sysDepartment.getParentId()); } } else { sysDepartment = sysDepartmentService.getById(hospitalId); } List sysDepartmentList = sysDepartmentService.list(new QueryWrapper().lambda().likeRight(SysDepartment::getTreeCode, sysDepartment.getTreeCode())); Set sysDepartmentIdSet = sysDepartmentList.stream().map(SysDepartment::getId).collect(Collectors.toSet()); Map sysDepartmentMap = sysDepartmentList.stream().collect(Collectors.toMap(SysDepartment::getId, e -> e)); // IPage page = new Page<>(pageNo, pageSize); // List roleTypeList = sysUserRoleService.getRoleTypeList(EnvUtils.getUser().getId()); if (CollectionUtils.isEmpty(roleTypeList)) { return page; } // //获取用户列表 List sysUserList = baseMapper.getSysUserList(page, sysDepartmentIdSet, roleTypeList, keyword,roleName); for (SysUserRespListDTO vo : sysUserList) { vo.setDepartmentIdList(new ArrayList<>()); fillDepartmentPath(sysDepartmentMap, vo, "/"); //获取角色列表 Set roleIdSet = getRoleIdSet(vo.getId()); vo.setRoleIdSet(roleIdSet.stream().map(SysRoleDTO::getId).collect(Collectors.toSet())); vo.setRoleName(String.join(",", new ArrayList<>(roleIdSet.stream().map(SysRoleDTO::getRoleName).collect(Collectors.toSet())))); } page.setRecords(sysUserList); return page; } /** * 填充用户列表中的区域、医院、部门、科室字段 * * @param vo */ private void fillDepartmentPath(Map sysDepartmentMap, SysUserRespListDTO vo, String separateChar) { if (StringUtils.isEmpty(separateChar)) { separateChar = "/"; } if (vo.getDepartmentId() != null) { SysDepartment sysDepartment = sysDepartmentMap.get(vo.getDepartmentId()); if (sysDepartment == null) { sysDepartment = sysDepartmentService.getById(vo.getDepartmentId()); if (sysDepartment != null) { sysDepartmentMap.put(sysDepartment.getId(), sysDepartment); } } if (sysDepartment != null && sysDepartment.getId().equals(-1)) { vo.setArea(sysDepartment.getDepartName()); vo.getDepartmentIdList().add(0, sysDepartment.getId()); return; } while (sysDepartment != null && !sysDepartment.getId().equals(-1)) { //科室 if (sysDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.OFFICE.getType())) { vo.setOffice(sysDepartment.getDepartName()); } //部门 else if (sysDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.DEPARTMENT.getType())) { if (StringUtils.isNotEmpty(vo.getDepartment())) { vo.setDepartment(sysDepartment.getDepartName() + separateChar + vo.getDepartment()); } else { vo.setDepartment(sysDepartment.getDepartName()); } } //医院 else if (sysDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.HOSPITAL.getType())) { vo.setHospital(sysDepartment.getDepartName()); } //区域 else { if (StringUtils.isNotEmpty(vo.getArea())) { vo.setArea(sysDepartment.getDepartName() + separateChar + vo.getArea()); } else { vo.setArea(sysDepartment.getDepartName()); } } vo.getDepartmentIdList().add(0, sysDepartment.getId()); if (sysDepartmentMap.get(sysDepartment.getParentId()) == null) { sysDepartment = sysDepartmentService.getById(sysDepartment.getParentId()); if (sysDepartment != null) { sysDepartmentMap.put(sysDepartment.getId(), sysDepartment); } } else { sysDepartment = sysDepartmentMap.get(sysDepartment.getParentId()); } } } } /** * 添加用户 * * @param dto * @return */ @Override @Transactional(rollbackFor = Exception.class) public void saveOrUpdate(SysUserReqDTO dto) { SysDepartment myDepartment = sysDepartmentService.getMyDepartment(EnvUtils.getUser().getId()); //判断编辑后的组织是否是自身下属组织 SysDepartment sysDepartment = sysDepartmentService.getById(dto.getDepartmentId()); if (sysDepartment == null) { throw new BusinessException(ErrorCode.DEPARTMENT_NOT_FOUND); } if (!sysDepartment.getTreeCode().startsWith(myDepartment.getTreeCode())) { throw new BusinessException(ErrorCode.ERR_500, "无操作权限"); } isCanUpdateUserPermission(dto.getRoleIdList().get(0), EnvUtils.getUser().getId()); if (dto.getId() == null || dto.getId() <= 0) { SysUser sysUser = getOne(Wrappers.lambdaQuery().eq(SysUser::getAccount, dto.getAccount())); if (sysUser != null) { throw new BusinessException(ErrorCode.USER_REPEAT); } sysUser = new SysUser(); BeanUtils.copyProperties(dto, sysUser); String passwordEncode = MD5Util.MD5Encode(dto.getPassword() + PASSWORD_SALT, null); sysUser.setPassword(passwordEncode); sysUser.setDelFlag(CommonConstant.DEL_FLAG_0); sysUser.setStatus(CommonConstant.STATUS_NORMAL); // sysUser.setCode(StringUtil.uuidNotLine().toUpperCase()); sysUser.setCode(MD5Util.MD5Encode(StringUtil.uuidNotLine(), null).substring(4, 12).toUpperCase()); save(sysUser); //角色权限新增 sysUserRoleSaveBatch(dto.getRoleIdList(), sysUser); //部门权限新增 SysUserDepartment sysUserDepartment = new SysUserDepartment(); sysUserDepartment.setUserId(sysUser.getId()); sysUserDepartment.setDepartmentId(sysDepartment.getId()); sysUserDepartment.setTreeCode(sysDepartment.getTreeCode()); sysUserDepartmentService.save(sysUserDepartment); } else { SysUser sysUser = getById(dto.getId()); if (sysUser == null) { throw new BusinessException(ErrorCode.USER_NOT_FOUND); } SysUser sysUserEntity = getOne(new QueryWrapper().lambda().eq(SysUser::getAccount, dto.getAccount()).ne(SysUser::getId, dto.getId())); if (sysUserEntity != null) { throw new BusinessException(ErrorCode.USER_REPEAT); } //判断编辑前的组织是否是自身下属组织 SysDepartment originDepartment = sysDepartmentService.getMyDepartment(dto.getId()); if (originDepartment == null) { throw new BusinessException(ErrorCode.DEPARTMENT_NOT_FOUND); } if (!originDepartment.getTreeCode().startsWith(myDepartment.getTreeCode())) { throw new BusinessException(ErrorCode.ERR_500, "无操作权限"); } BeanUtils.copyProperties(dto, sysUser); if (StringUtils.isNotEmpty(dto.getPassword())) { String passwordEncode = MD5Util.MD5Encode(dto.getPassword() + PASSWORD_SALT, null); sysUser.setPassword(passwordEncode); } updateById(sysUser); //先删后增 Set roleIdSet = sysUserRoleService.list(new QueryWrapper().lambda().eq(SysUserRole::getUserId, sysUser.getId())).stream().map(SysUserRole::getId).collect(Collectors.toSet()); if (CollectionUtils.isNotEmpty(roleIdSet)) { sysUserRoleService.removeByIds(roleIdSet); } //角色权限新增 sysUserRoleSaveBatch(dto.getRoleIdList(), sysUser); //部门权限新增 SysUserDepartment sysUserDepartment = sysUserDepartmentService.getOne(new QueryWrapper().lambda().eq(SysUserDepartment::getUserId, sysUser.getId())); if (sysUserDepartment != null) { sysUserDepartmentService.removeById(sysUserDepartment.getId()); } sysUserDepartment = new SysUserDepartment(); sysUserDepartment.setUserId(sysUser.getId()); sysUserDepartment.setDepartmentId(sysDepartment.getId()); sysUserDepartment.setTreeCode(sysDepartment.getTreeCode()); sysUserDepartmentService.save(sysUserDepartment); } } private boolean isCanUpdateUserPermission(Integer roleId, Integer userId) { List roleTypeList = sysUserRoleService.getRoleTypeList(userId); if (CollectionUtils.isEmpty(roleTypeList)) { throw new BusinessException(ErrorCode.ERR_500, "无操作权限"); } List sysRoleList = sysRoleService.list(new QueryWrapper().lambda().in(SysRole::getType, roleTypeList)); for (SysRole sysRole : sysRoleList) { if (sysRole.getId().equals(roleId)) { return true; } } throw new BusinessException(ErrorCode.ERR_500, "无操作权限"); } /** * 角色权限新增 * * @param roleIdList * @param sysUser */ @Transactional(rollbackFor = Exception.class) public void sysUserRoleSaveBatch(List roleIdList, SysUser sysUser) { Set sysUserRoleList = roleIdList.stream().map(sysRoleId -> { SysUserRole sysUserRole = new SysUserRole(); sysUserRole.setUserId(sysUser.getId()); sysUserRole.setRoleId(sysRoleId); return sysUserRole; }).collect(Collectors.toSet()); sysUserRoleService.saveBatch(sysUserRoleList); } /** * 通过id删除用户 * * @param id */ @Override @Transactional(rollbackFor = Exception.class) public void delete(Integer id) { if (id.equals(EnvUtils.getUser().getId())) { throw new BusinessException(ErrorCode.USER_CAN_UPDATE_OWN); } SysUser sysUser = getById(id); if (sysUser == null) { throw new BusinessException(ErrorCode.USER_NOT_FOUND); } SysDepartment myDepartment = sysDepartmentService.getMyDepartment(EnvUtils.getUser().getId()); //判断编辑前的组织是否是自身下属组织 SysDepartment originDepartment = sysDepartmentService.getMyDepartment(id); if (originDepartment != null) { if (!originDepartment.getTreeCode().startsWith(myDepartment.getTreeCode())) { throw new BusinessException(ErrorCode.ERR_500, "无操作权限"); } } sysUser.setAccount(sysUser.getAccount() + "-已删除"); sysUser.setName(sysUser.getName() + "-已删除"); updateById(sysUser); removeById(sysUser); Set roleIdSet = sysUserRoleService.list(new QueryWrapper().lambda().eq(SysUserRole::getUserId, sysUser.getId())).stream().map(SysUserRole::getId).collect(Collectors.toSet()); if (CollectionUtils.isNotEmpty(roleIdSet)) { sysUserRoleService.removeByIds(roleIdSet); } SysUserDepartment sysUserDepartment = sysUserDepartmentService.getOne(new QueryWrapper().lambda().eq(SysUserDepartment::getUserId, sysUser.getId())); if (sysUserDepartment != null) { sysUserDepartmentService.removeById(sysUserDepartment.getId()); } } /** * 通过id批量删除用户 * * @param vo * @return */ @Override @Transactional(rollbackFor = Exception.class) public boolean deleteBatch(BatchReqVO vo) { SysDepartment myDepartment = sysDepartmentService.getMyDepartment(EnvUtils.getUser().getId()); if (StringUtil.isBlank(vo.getIds())) { throw new BusinessException(ErrorCode.SYSTEM_REQUEST_PARAM_ERROR); } String[] ids = vo.getIds().split(","); for (String id : ids) { if (EnvUtils.getUser().getId().equals(Integer.parseInt(id))) { throw new BusinessException(ErrorCode.USER_CAN_UPDATE_OWN); } //判断编辑前的组织是否是自身下属组织 SysDepartment originDepartment = sysDepartmentService.getMyDepartment(Integer.parseInt(id)); if (originDepartment != null) { if (!originDepartment.getTreeCode().startsWith(myDepartment.getTreeCode())) { throw new BusinessException(ErrorCode.ERR_500, "无操作权限"); } } } List sysUserList = listByIds(Arrays.asList(ids)); for (SysUser sysUser : sysUserList) { sysUser.setDelFlag(CommonConstant.DEL_FLAG_1); sysUser.setAccount(sysUser.getAccount() + "-已删除"); sysUser.setName(sysUser.getName() + "-已删除"); updateById(sysUser); } Set roleIdSet = sysUserRoleService.list(new QueryWrapper().lambda().in(SysUserRole::getUserId, Arrays.asList(vo.getIds().split(",")))).stream().map(SysUserRole::getId).collect(Collectors.toSet()); if (CollectionUtils.isNotEmpty(roleIdSet)) { sysUserRoleService.removeByIds(roleIdSet); } List sysUserDepartmentIdList = sysUserDepartmentService.list(new QueryWrapper().lambda().in(SysUserDepartment::getUserId, Arrays.asList(vo.getIds().split(",")))).stream().map(SysUserDepartment::getId).collect(Collectors.toList()); if (CollectionUtils.isNotEmpty(sysUserDepartmentIdList)) { sysUserDepartmentService.removeByIds(sysUserDepartmentIdList); } return true; } /** * 通过id查询用户详情 * * @param id * @return */ @Override public SysUserDetailsRespDTO sysUserDetailsById(Integer id) { SysUserDetailsRespDTO sysUserDetails = new SysUserDetailsRespDTO(); SysUser sysUser = getById(id); if (sysUser == null) { throw new BusinessException(ErrorCode.USER_NOT_FOUND); } sysUserDetails.setSysUser(sysUser); //获取用户角色列表 sysUserDetails.setSysUserRoleList(getRoleIdSet(sysUser.getId())); SysUserDepartment sysUserDepartment = sysUserDepartmentService.getOne(new QueryWrapper().lambda().eq(SysUserDepartment::getUserId, sysUser.getId())); SysDepartment sysDepartment = sysDepartmentService.getById(sysUserDepartment.getDepartmentId()); SysDepartmentDTO sysDepartmentDTO = new SysDepartmentDTO(); BeanUtils.copyProperties(sysDepartment, sysDepartmentDTO); sysUserDetails.setSysDepartmentDTO(sysDepartmentDTO); return sysUserDetails; } /** * 获取用户角色列表 * * @param userId * @return */ private Set getRoleIdSet(Integer userId) { Set sysRoleSet = new HashSet<>(); Set roleIdSet = sysUserRoleService.list(new QueryWrapper().lambda().eq(SysUserRole::getUserId, userId)).stream().map(SysUserRole::getRoleId).collect(Collectors.toSet()); if (CollectionUtils.isNotEmpty(roleIdSet)) { Set sysRoleDTOSet = sysRoleService.listByIds(roleIdSet).stream().map(sysRole -> { SysRoleDTO sysRoleDTO = new SysRoleDTO(); BeanUtils.copyProperties(sysRole, sysRoleDTO); return sysRoleDTO; }).collect(Collectors.toSet()); sysRoleSet.addAll(sysRoleDTOSet); } return sysRoleSet; } /** * 禁用或启用用户 * * @param vo * @return */ @Override @Transactional(rollbackFor = Exception.class) public boolean frozenBatch(BatchReqVO vo) { if (StringUtil.isBlank(vo.getIds())) { throw new BusinessException(ErrorCode.SYSTEM_REQUEST_PARAM_ERROR); } SysDepartment myDepartment = sysDepartmentService.getMyDepartment(EnvUtils.getUser().getId()); String[] arr = vo.getIds().split(","); List list = new ArrayList<>(); for (String id : arr) { SysUser sysUser = getById(id); if (sysUser == null) { throw new BusinessException(ErrorCode.USER_NOT_FOUND); } // 获取登录用户信息 if (sysUser.getId().equals(EnvUtils.getUser().getId())) { throw new BusinessException(ErrorCode.USER_CAN_UPDATE_OWN); } //判断编辑前的组织是否是自身下属组织 SysDepartment originDepartment = sysDepartmentService.getMyDepartment(Integer.parseInt(id)); if (originDepartment != null) { if (!originDepartment.getTreeCode().startsWith(myDepartment.getTreeCode())) { throw new BusinessException(ErrorCode.ERR_500, "无操作权限"); } } sysUser.setStatus(vo.getStatus()); list.add(sysUser); } updateBatchById(list); return true; } /** * 获取验证码 * * @param account * @param phone * @param isFromApp * @return */ @Override public boolean getValidateCode(String account, String phone, boolean isFromApp) { if (redisUtil.hasKey(CacheKey.getValidateCodePeriodKey(account))) { throw new BusinessException(ErrorCode.USER_VALIDATE_CODE_FREQUENTLY); } SysUser sysUser = getOne(new QueryWrapper().lambda().eq(SysUser::getAccount, account)); if (sysUser == null) { throw new BusinessException(ErrorCode.LOGIN_USER_NOT_FOUND); } if (!sysUser.getPhone().equals(phone)) { throw new BusinessException(ErrorCode.LOGIN_USER_PHONE_INVALID); } if (!sysUser.getStatus().equals(CommonConstant.STATUS_NORMAL)) { throw new BusinessException(ErrorCode.USER_HAS_BEEN_FROZEN); } if (!sysUser.getDelFlag().equals(CommonConstant.DEL_FLAG_0)) { throw new BusinessException(ErrorCode.USER_NOT_FOUND); } // 如果是APP端重置密码,判断是否有APP登陆权限 if (isFromApp) { SysUserRole sysUserRole = sysUserRoleService.getOne(new QueryWrapper().lambda().eq(SysUserRole::getUserId, sysUser.getId())); if (sysUserRole == null) { throw new BusinessException(ErrorCode.ERR_500, "未授权账号"); } SysRole sysRole = sysRoleService.getById(sysUserRole.getRoleId()); if (sysRole == null) { throw new BusinessException(ErrorCode.ERR_500, "未授权账号"); } sysRolePermissionService.getAppPermissionList(sysRole.getId()); } try { String validateCode = StringUtil.randomCode(6); if (aliSmsConfig.isDebug()) { validateCode = "123456"; } //ali sms aliSmsService.sendLoginCode(phone, validateCode); //存redis redisUtil.set(CacheKey.getForgotValidateCodeKey(account), validateCode, CacheKey.SMS_VALIDATE_CODE_TIMEOUT); redisUtil.set(CacheKey.getValidateCodePeriodKey(account), validateCode, CacheKey.SMS_VALIDATE_CODE_PERIOD_TIMEOUT); return true; } catch (Exception e) { log.error("发送验证码失败,{}", e.getMessage()); return false; } } @Override public boolean checkValidateCode(String account, String phone, String validateCode) { SysUser sysUser = getOne(new QueryWrapper().lambda().eq(SysUser::getAccount, account)); if (sysUser == null) { throw new BusinessException(ErrorCode.LOGIN_USER_NOT_FOUND); } if (!sysUser.getPhone().equals(phone)) { throw new BusinessException(ErrorCode.LOGIN_USER_PHONE_INVALID); } String redisValidateCode = redisUtil.get(CacheKey.getForgotValidateCodeKey(account)); if (StringUtils.isEmpty(redisValidateCode)) { throw new BusinessException(ErrorCode.USER_VALIDATE_CODE_TIMEOUT); } if (!redisValidateCode.equals(validateCode)) { throw new BusinessException(ErrorCode.USER_VALIDATE_CODE_INVALID); } return true; } @Override public boolean resetPassword(String account, String phone, String validateCode, String password) { checkValidateCode(account, phone, validateCode); SysUser sysUser = getOne(new QueryWrapper().lambda().eq(SysUser::getAccount, account).eq(SysUser::getPhone, phone)); if (sysUser == null) { throw new BusinessException(ErrorCode.LOGIN_USER_NOT_FOUND); } sysUser.setPassword(MD5Util.MD5Encode(password + PASSWORD_SALT, null)); updateById(sysUser); //删除redis redisUtil.del(CacheKey.getForgotValidateCodeKey(account)); return true; } @Override public boolean updatePassword(String originPassword, String password) { SysUser sysUser = getById(EnvUtils.getUser().getId()); String passwordEncode = originPassword; if(passwordEncode.length()!=32) {//需要加密 passwordEncode = MD5Util.MD5Encode(originPassword + PASSWORD_SALT, null); } if (!passwordEncode.equals(sysUser.getPassword())) { throw new BusinessException(ErrorCode.LOGIN_USER_PASSWORD_INVALID); } String passwordEncodeNew = password; if(passwordEncodeNew.length()!=32) {//需要加密 passwordEncodeNew = MD5Util.MD5Encode(password + PASSWORD_SALT, null); } sysUser.setPassword(passwordEncodeNew); return updateById(sysUser); } @Override public boolean logout(HttpServletRequest request, HttpServletResponse response) { String token = getToken(request); if (token != null) { redisUtil.del(CacheKey.getUserCacheKey(token)); // Cookie cookie = new Cookie(CommonConstant.X_ACCESS_TOKEN, token); cookie.setPath("/"); cookie.setDomain(medicalDomain); cookie.setMaxAge(0); response.addCookie(cookie); } return true; } @Override public List getOfficeUserList(Integer officeId) { SysDepartment myDepartment = sysDepartmentService.getById(officeId); List departmentList = null; if (myDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.OFFICE.getType()) || myDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.DEPARTMENT.getType())) { SysDepartment hospital = sysDepartmentService.getHospital(myDepartment.getParentId()); departmentList = sysDepartmentService.list(new QueryWrapper().lambda().likeRight(SysDepartment::getTreeCode, hospital.getTreeCode())); } else { departmentList = sysDepartmentService.list(new QueryWrapper().lambda().likeRight(SysDepartment::getTreeCode, myDepartment.getTreeCode())); } if (CollectionUtils.isEmpty(departmentList)) { return new ArrayList<>(); } return baseMapper.getUserList(departmentList.stream().map(SysDepartment::getId).collect(Collectors.toList())); } @Override public List getDepartmentUserList(List departmentIdList) { return baseMapper.getDepartmentUserList(departmentIdList); } private static final Map importHeaderAliasMap = new HashMap<>(); static { importHeaderAliasMap.put("区域", "area"); importHeaderAliasMap.put("单位", "hospital"); importHeaderAliasMap.put("部门", "department"); importHeaderAliasMap.put("科室", "office"); importHeaderAliasMap.put("姓名(必填)", "name"); importHeaderAliasMap.put("用户名(必填)", "account"); importHeaderAliasMap.put("手机号(必填)", "phone"); importHeaderAliasMap.put("角色(必填)", "role"); importHeaderAliasMap.put("密码(必填)", "password"); // importHeaderAliasMap.put("姓名", "name"); importHeaderAliasMap.put("用户名", "account"); importHeaderAliasMap.put("手机号", "phone"); importHeaderAliasMap.put("角色", "role"); importHeaderAliasMap.put("密码", "password"); } @Transactional(rollbackFor = Exception.class) @Override public boolean importUser(ImportDTO dto){ SysDepartment sysDepartment = sysDepartmentService.getById(dto.getDepartmentId()); if (sysDepartment == null) { throw new BusinessException(ErrorCode.DEPARTMENT_NOT_FOUND); } ExcelReader reader = null; try { reader = ExcelUtil.getReader(dto.getFile().getInputStream()); } catch (IOException e) { e.printStackTrace(); } reader.setHeaderAlias(importHeaderAliasMap); List list = reader.read(0, 1, SysUserImportEntity.class); if (CollectionUtils.isEmpty(list)) { throw new BusinessException(ErrorCode.ERR_500, "导入用户信息列表不能为空"); } StopWatch stopWatch = new StopWatch(); stopWatch.start(); log.info("用户信息导入开始:指定部门id:{},名称:{}", sysDepartment.getId(), sysDepartment.getDepartName()); int count = 2; //存放批量保存 List sysUserList = new ArrayList<>(list.size()); List sysRoleList = new ArrayList<>(list.size()); List sysDepartmentList = new ArrayList<>(list.size()); //部门缓存集合 Map departmentCacheMap = sysDepartmentService.list(new QueryWrapper()// .lambda()// .likeRight(SysDepartment::getTreeCode, sysDepartment.getTreeCode())// .orderByAsc(SysDepartment::getTreeCode))// .stream().collect(Collectors.toMap(e -> e.getParentId() + ":" + e.getDepartName(), e -> e)); //用户账号缓存列表 List userCacheList = list().stream().map(SysUser::getAccount).collect(Collectors.toList()); //角色缓存集合 List roleTypeList = sysUserRoleService.getRoleTypeList(EnvUtils.getUser().getId()); if (CollectionUtils.isEmpty(roleTypeList)) { throw new BusinessException(ErrorCode.ERR_500, "无操作权限"); } List hasPermissionRoleList = sysRoleService.list(new QueryWrapper().lambda().in(SysRole::getType, roleTypeList)); if (CollectionUtils.isEmpty(hasPermissionRoleList)) { throw new BusinessException(ErrorCode.ERR_500, "无操作权限"); } Map sysRoleCacheMap = hasPermissionRoleList.stream().collect(Collectors.toMap(SysRole::getRoleName, sysRole -> sysRole)); for (SysUserImportEntity userImportEntity : list) { if (StringUtils.isEmpty(userImportEntity.getName())) { throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,请输入姓名"); } // if (userImportEntity.getName().length() > 20) { // throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,姓名格式错误:不超过20个字符"); // } // if (StringUtils.isEmpty(userImportEntity.getAccount())) { // throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,请输入用户名"); // } // if (userImportEntity.getAccount().length() < 5 || userImportEntity.getAccount().length() > 20) { // throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,用户名格式错误:请输入5~20个字符"); // } if (!validateAccount(userImportEntity.getAccount())) { throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,用户名格式错误"); } if (!validateName(userImportEntity.getName())) { throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,姓名格式错误"); } // if (StringUtils.isEmpty(userImportEntity.getPhone())) { // throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,请输入手机号"); // } if (!validatePhone(userImportEntity.getPhone())) { throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,手机号格式错误"); } if (StringUtils.isEmpty(userImportEntity.getRole())) { throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,请输入角色"); } if (StringUtils.isEmpty(userImportEntity.getPassword())) { throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,请输入密码"); } if (userImportEntity.getPassword().length() < 6 || userImportEntity.getPassword().length() > 20) { throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,密码格式错误:请输入6~20个字符,建议英文、数组混合,区分大小写"); } if (userCacheList.contains(userImportEntity.getAccount())) { throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,账号:" + userImportEntity.getAccount() + "已被使用"); } //判断账号 SysUser sysUser = getOne(new QueryWrapper().lambda().eq(SysUser::getAccount, userImportEntity.account)); if (sysUser != null) { throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,账号:" + userImportEntity.getAccount() + "已被使用"); } userCacheList.add(userImportEntity.getAccount()); //判断角色 SysRole sysRole = sysRoleCacheMap.get(userImportEntity.getRole()); if (sysRole == null) { throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,角色名:" + userImportEntity.getRole() + "不存在"); } SysDepartment office = sysDepartment; //指定医院 / 部门 if (sysDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.HOSPITAL.getType()) || sysDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.DEPARTMENT.getType())) { if (StringUtils.isNotEmpty(userImportEntity.getDepartment())) { String[] departmentArrays = userImportEntity.getDepartment().split(";"); for (int i = 0; i < departmentArrays.length; i++) { String departmentArray = departmentArrays[i]; if (departmentArray.equals(sysDepartment.getDepartName()) && i == 0) { continue; } if (departmentCacheMap.get(office.getId() + ":" + departmentArray) == null) { office = sysDepartmentService.getOne(new QueryWrapper().lambda().eq(SysDepartment::getParentId, office.getId()).eq(SysDepartment::getDepartName, departmentArray)); if (office == null) { throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,部门:" + departmentArray + "不存在"); } departmentCacheMap.put(office.getParentId() + ":" + departmentArray, office); } else { office = departmentCacheMap.get(office.getId() + ":" + departmentArray); } } } if (StringUtils.isNotEmpty(userImportEntity.getOffice())) { if (departmentCacheMap.get(office.getId() + ":" + userImportEntity.getOffice()) == null) { office = sysDepartmentService.getOne(new QueryWrapper().lambda().eq(SysDepartment::getParentId, office.getId()).eq(SysDepartment::getDepartName, userImportEntity.getOffice())); if (office == null) { throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,科室:" + userImportEntity.getOffice() + "不存在"); } departmentCacheMap.put(office.getParentId() + ":" + userImportEntity.getOffice(), office); } else { office = departmentCacheMap.get(office.getId() + ":" + userImportEntity.getOffice()); } } } //指定区域 else if (sysDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.AREA.getType())) { if (StringUtils.isNotEmpty(userImportEntity.getArea())) { String[] areaArrays = userImportEntity.getArea().split(";"); for (int i = 0; i < areaArrays.length; i++) { String areaArray = areaArrays[i]; if (areaArray.equals(sysDepartment.getDepartName()) && i == 0) { continue; } if (departmentCacheMap.get(office.getId() + ":" + areaArray) == null) { office = sysDepartmentService.getOne(new QueryWrapper().lambda().eq(SysDepartment::getParentId, office.getId()).eq(SysDepartment::getDepartName, areaArray)); if (office == null) { throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,区域:" + areaArray + "不存在"); } departmentCacheMap.put(office.getParentId() + ":" + areaArray, office); } else { office = departmentCacheMap.get(office.getId() + ":" + areaArray); } } } if (StringUtils.isNotEmpty(userImportEntity.getHospital())) { office = sysDepartmentService.getOne(new QueryWrapper().lambda().eq(SysDepartment::getParentId, office.getId()).eq(SysDepartment::getDepartName, userImportEntity.getHospital())); if (office == null) { throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,医院:" + userImportEntity.getHospital() + "不存在"); } if (StringUtils.isNotEmpty(userImportEntity.getDepartment())) { String[] departmentArrays = userImportEntity.getDepartment().split(";"); for (String departmentArray : departmentArrays) { if (departmentCacheMap.get(office.getId() + ":" + departmentArray) == null) { office = sysDepartmentService.getOne(new QueryWrapper().lambda().eq(SysDepartment::getParentId, office.getId()).eq(SysDepartment::getDepartName, departmentArray)); if (office == null) { throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,部门:" + departmentArray + "不存在"); } departmentCacheMap.put(office.getParentId() + ":" + departmentArray, office); } else { office = departmentCacheMap.get(office.getId() + ":" + departmentArray); } } } if (StringUtils.isNotEmpty(userImportEntity.getOffice())) { if (departmentCacheMap.get(office.getId() + ":" + userImportEntity.getOffice()) == null) { office = sysDepartmentService.getOne(new QueryWrapper().lambda().eq(SysDepartment::getParentId, office.getId()).eq(SysDepartment::getDepartName, userImportEntity.getOffice())); if (office == null) { throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,科室:" + userImportEntity.getOffice() + "不存在"); } departmentCacheMap.put(office.getParentId() + ":" + userImportEntity.getOffice(), office); } else { office = departmentCacheMap.get(office.getId() + ":" + userImportEntity.getOffice()); } } } } String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$"; if(!userImportEntity.getPassword().matches(regex)){ throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行,请输入6~20位字符,建议字母+数字混合"); } sysUser = new SysUser(); BeanUtils.copyProperties(userImportEntity, sysUser); String passwordEncode = MD5Util.MD5Encode(userImportEntity.getPassword() + PASSWORD_SALT, null); sysUser.setPassword(passwordEncode); sysUser.setDelFlag(CommonConstant.DEL_FLAG_0); sysUser.setStatus(CommonConstant.STATUS_NORMAL); sysUser.setCode(StringUtil.uuidNotLine().toUpperCase()); sysUserList.add(sysUser); sysRoleList.add(sysRole); sysDepartmentList.add(office); count++; } saveImportUserList(sysUserList, sysRoleList, sysDepartmentList); stopWatch.stop(); log.info("用户信息导入结束,耗时:{}秒", stopWatch.getTotalTimeSeconds()); return true; } @Transactional(rollbackFor = Exception.class) public boolean saveImportUserList(List sysUserList, List sysRoleList, List sysDepartmentList) { //用户 saveBatch(sysUserList); // List sysUserRoleList = new ArrayList<>(); List sysUserDepartmentList = new ArrayList<>(); for (int i = 0; i < sysUserList.size(); i++) { SysRole sysRole = sysRoleList.get(i); SysUserRole sysUserRole = new SysUserRole(); sysUserRole.setUserId(sysUserList.get(i).getId()); sysUserRole.setRoleId(sysRole.getId()); sysUserRoleList.add(sysUserRole); // SysDepartment sysDepartment = sysDepartmentList.get(i); SysUserDepartment sysUserDepartment = new SysUserDepartment(); sysUserDepartment.setUserId(sysUserList.get(i).getId()); sysUserDepartment.setDepartmentId(sysDepartment.getId()); sysUserDepartment.setTreeCode(sysDepartment.getTreeCode()); sysUserDepartmentList.add(sysUserDepartment); } //用户角色 sysUserRoleService.saveBatch(sysUserRoleList); //用户部门 sysUserDepartmentService.saveBatch(sysUserDepartmentList); return true; } @Data private static class SysUserImportEntity { private String area; private String hospital; private String department; private String office; private String name; private String account; private String phone; private String role; private String password; } private boolean validateAccount(String account) { if (StringUtils.isEmpty(account)) { return false; } String regex = "^[A-Za-z0-9_]{5,20}$"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(account); return matcher.matches(); } private boolean validateName(String name) { if (StringUtils.isEmpty(name)) { return false; } String regex = "^[A-Za-z0-9_\\-\\u4e00-\\u9fa5]{1,20}$"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(name); return matcher.matches(); } private boolean validatePhone(String phone) { // String regex="^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$"; String regex = "^1\\d{10}$"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(phone); return matcher.matches(); } @Override public void exportUser(HttpServletResponse response, Integer departmentId) throws UnsupportedEncodingException { SysDepartment sysDepartment = null; if (departmentId == null) { sysDepartment = sysDepartmentService.getMyDepartment(EnvUtils.getUser().getId()); } else { sysDepartment = sysDepartmentService.getById(departmentId); } List sysDepartmentList = sysDepartmentService.list(new QueryWrapper().lambda().likeRight(SysDepartment::getTreeCode, sysDepartment.getTreeCode())); Set sysDepartmentIdSet = sysDepartmentList.stream().map(SysDepartment::getId).collect(Collectors.toSet()); Map sysDepartmentMap = sysDepartmentList.stream().collect(Collectors.toMap(SysDepartment::getId, e -> e)); //获取用户列表 // List sysUserList = new ArrayList<>(); List roleTypeList = sysUserRoleService.getRoleTypeList(EnvUtils.getUser().getId()); if (CollectionUtils.isNotEmpty(roleTypeList)) { sysUserList = baseMapper.getAllSysUserList(sysDepartmentIdSet, roleTypeList); } List exportUserList = new ArrayList<>(); for (SysUserRespListDTO vo : sysUserList) { vo.setDepartmentIdList(new ArrayList<>()); fillDepartmentPath(sysDepartmentMap, vo, ";"); //获取角色列表 Set roleIdSet = getRoleIdSet(vo.getId()); vo.setRoleIdSet(roleIdSet.stream().map(SysRoleDTO::getId).collect(Collectors.toSet())); vo.setRoleName(String.join(",", new ArrayList<>(roleIdSet.stream().map(SysRoleDTO::getRoleName).collect(Collectors.toSet())))); // SysUserExportEntity exportEntity = new SysUserExportEntity(); BeanUtils.copyProperties(vo, exportEntity); exportUserList.add(exportEntity); } // ExcelWriter excelWriter = ExcelUtil.getWriter(true); for (int i = 0; i < 9; i++) { excelWriter.setColumnWidth(i, 20); } // 表头 excelWriter.addHeaderAlias("area", "区域"); excelWriter.addHeaderAlias("hospital", "单位"); excelWriter.addHeaderAlias("department", "部门"); excelWriter.addHeaderAlias("office", "科室"); excelWriter.addHeaderAlias("name", "姓名"); excelWriter.addHeaderAlias("account", "用户名"); excelWriter.addHeaderAlias("phone", "手机号"); excelWriter.addHeaderAlias("roleName", "角色"); excelWriter.addHeaderAlias("createTime", "创建时间"); excelWriter.write(exportUserList, true); // response.setContentType("application/octet-stream;charset=utf-8"); String fileName = "用户信息导出"; response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx"); ServletOutputStream out = null; try { out = response.getOutputStream(); excelWriter.flush(out, true); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } excelWriter.close(); } } @Data private static class SysUserExportEntity { private String area; private String hospital; private String department; private String office; private String name; private String account; private String phone; private String roleName; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date createTime; } @Override public void downloadImportTemplate(HttpServletResponse response) throws IOException { XSSFWorkbook workbook = new XSSFWorkbook(this.getClass().getResourceAsStream("/excel/user_import_template.xlsx")); response.setContentType("application/octet-stream;charset=utf-8"); String fileName = "用户信息导入模板"; response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx"); ServletOutputStream out = null; try { out = response.getOutputStream(); workbook.write(out); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } if (workbook != null) { workbook.close(); } } } @Override public List getUserList() { SysDepartment myDepartment = sysDepartmentService.getMyDepartment(EnvUtils.getUser().getId()); List departmentList = null; if (myDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.OFFICE.getType()) || myDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.DEPARTMENT.getType())) { SysDepartment hospital = sysDepartmentService.getHospital(myDepartment.getParentId()); departmentList = sysDepartmentService.list(new QueryWrapper().lambda().likeRight(SysDepartment::getTreeCode, hospital.getTreeCode())); } else { departmentList = sysDepartmentService.list(new QueryWrapper().lambda().likeRight(SysDepartment::getTreeCode, myDepartment.getTreeCode())); } if (CollectionUtils.isEmpty(departmentList)) { return new ArrayList<>(); } return baseMapper.getUserList(departmentList.stream().map(SysDepartment::getId).collect(Collectors.toList())); } //只获取医院下,并且是除暂存间之外的科室人员列表 @Override public List getUserListByApp(Integer userId) { SysDepartment myDepartment = sysDepartmentService.getMyDepartment(userId); List departmentList = null; if (myDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.OFFICE.getType()) || myDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.DEPARTMENT.getType())) { SysDepartment hospital = sysDepartmentService.getHospital(myDepartment.getParentId()); departmentList = sysDepartmentService.list(new QueryWrapper().lambda().likeRight(SysDepartment::getTreeCode, hospital.getTreeCode()).eq(SysDepartment::getOrgType, DepartmentEnum.OrgTypeEnum.OFFICE.getType()).eq(SysDepartment::getIsWarehouse, 0).eq(SysDepartment::getStatus,1)); } else if (myDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.AREA.getType())) { return new ArrayList<>(); } else { departmentList = sysDepartmentService.list(new QueryWrapper().lambda().likeRight(SysDepartment::getTreeCode, myDepartment.getTreeCode()).eq(SysDepartment::getOrgType, DepartmentEnum.OrgTypeEnum.OFFICE.getType()).eq(SysDepartment::getIsWarehouse, 0).eq(SysDepartment::getStatus,1)); } if (CollectionUtils.isEmpty(departmentList)) { return new ArrayList<>(); } return baseMapper.getUserList(departmentList.stream().map(SysDepartment::getId).collect(Collectors.toList())); } @Override public SysUser getSysUserById(Integer id) { return baseMapper.getSysUserById(id); } @Override public ServiceExpirationReminderVO getServiceExpirationReminder(HttpServletRequest request) { ServiceExpirationReminderVO serviceExpirationReminderVO = new ServiceExpirationReminderVO(); String token = getToken(request); SysUser user = getByToken(token); SysDepartment myDepartment = sysDepartmentService.getMyDepartment(user.getId()); if(null != myDepartment){ SysDepartment hospital = sysDepartmentService.getHospital(myDepartment.getParentId()); if(null != hospital){ serviceExpirationReminderVO.setId(hospital.getId()); if(null == hospital.getExpireDate()){ return serviceExpirationReminderVO; } if(System.currentTimeMillis() > hospital.getExpireDate().getTime()){ serviceExpirationReminderVO.setContent("您的服务已过期,请及时续费"); return serviceExpirationReminderVO; } if(hospital.getExpireDate().getTime() - ((null == hospital.getReminderDays() ? 0 : hospital.getReminderDays()) * (24 * 60 * 60 * 1000)) < System.currentTimeMillis()){ int i = Double.valueOf((hospital.getExpireDate().getTime() - System.currentTimeMillis()) / (24 * 60 * 60 * 1000)).intValue(); serviceExpirationReminderVO.setContent("您的有效期还有" + i + "天,请及时续费"); return serviceExpirationReminderVO; } } } return serviceExpirationReminderVO; } @Override public PayUrlVO getPayUrl(Integer id) { PayUrlVO payUrlVO = new PayUrlVO(); SysDepartment department = sysDepartmentService.getById(44); SysDictItem dictItem = dictItemService.getById(department.getBillingCompany()); if(null == dictItem){ throw new BusinessException(ErrorCode.ERR_500, "请先创建开票公司"); } MwServicePeriod servicePeriodInfo = servicePeriodService.getOne(new QueryWrapper().lambda().eq(MwServicePeriod::getDepartmentId, 44) .eq(MwServicePeriod::getStatus, 1).eq(MwServicePeriod::getDelFlag, 0).orderByDesc(MwServicePeriod::getCreateTime).last("limit 0, 1")); if(null == department.getServiceCharge() || department.getServiceCharge() == 0 || servicePeriodInfo.getPayStatus() == 2){ throw new BusinessException(ErrorCode.ERR_500, "暂无支付数据"); } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String format = sdf.format(new Date()); String customerOrderNo = format + servicePeriodInfo.getId();//16位开始截取 MwServicePeriod servicePeriod = servicePeriodService.getById(servicePeriodInfo.getId()); servicePeriod.setCode(customerOrderNo); servicePeriodService.updateById(servicePeriod); String url = nouNouPayUtil.paymentToOrders(dictItem.getItemValue(), customerOrderNo, department.getServiceCharge(), "服务费", servicePeriodInfo.getId().toString(), callbackUrl + "/api/user/NouNouPayCallback"); //创建定时任务查询支付状态 if(org.springframework.util.StringUtils.hasLength(url)){ queryPaymentOrder(customerOrderNo, dictItem.getItemValue(), servicePeriodInfo.getId()); } payUrlVO.setUrl(url); payUrlVO.setCode(customerOrderNo); return payUrlVO; } /** * 定时查询支付状态 * @param customerOrderNo * @param taxNo * @param id */ private void queryPaymentOrder(String customerOrderNo, String taxNo, Integer id){ new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(10000);//10秒后开始 System.out.println("定时查询支付状态"); int num = 1; int wait = 0; while (num <= 20){ int min = 3000; wait += (min * num); MwServicePeriod mwServicePeriod = servicePeriodService.getById(id); if(mwServicePeriod.getPayStatus() == 1){ break; } if(num == 20){//轮询结束 Boolean aBoolean = nouNouPayUtil.closeOrder("", customerOrderNo, taxNo); if(!aBoolean){ System.err.println("关闭订单失败"); } mwServicePeriod.setPayStatus(2); mwServicePeriod.setIsInvoiced(1); servicePeriodService.updateById(mwServicePeriod); break; } PaymentOrderVO paymentOrderVO = nouNouPayUtil.queryPaymentOrder("", customerOrderNo, taxNo); if(null == paymentOrderVO){ continue; } Integer payStatus = paymentOrderVO.getPayStatus(); if(payStatus == 0){//待支付 Thread.sleep(wait); num++; continue; } if(payStatus == 1){//已支付 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); mwServicePeriod.setPayStatus(1); mwServicePeriod.setIsInvoiced(paymentOrderVO.getIsInvoiced()); mwServicePeriod.setPayTime(sdf.parse(paymentOrderVO.getPayTime())); mwServicePeriod.setOrderNumber(paymentOrderVO.getOrderNo()); mwServicePeriod.setPayAmount(paymentOrderVO.getAmount()); mwServicePeriod.setPayType(paymentOrderVO.getPayType().equals("WECHAT") ? 1 : 2); servicePeriodService.updateById(mwServicePeriod); //修改企业信息上的结束时间 Calendar instance = Calendar.getInstance(); SysDepartment department = sysDepartmentService.getById(mwServicePeriod.getDepartmentId()); instance.setTime(department.getExpireDate()); instance.add(Calendar.YEAR,+1); Date time = instance.getTime(); department.setExpireDate(department.getExpireDate()); sysDepartmentService.updateById(department); break; }else{ mwServicePeriod.setPayStatus(payStatus); mwServicePeriod.setIsInvoiced(paymentOrderVO.getIsInvoiced()); servicePeriodService.updateById(mwServicePeriod); break; } } }catch (Exception e){ e.printStackTrace(); } } }).start(); } @Override public void NouNouPayCallback(Map map, HttpServletResponse response) { try { System.err.println("支付回调内容:" + JSON.toJSONString(map)); // ServletInputStream inputStream = request.getInputStream(); // BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); // StringBuilder sb = new StringBuilder(); // while (reader.ready()){ // sb.append(reader.readLine()); // } // if(org.springframework.util.StringUtils.hasLength(sb.toString())){ // // // // // } }catch (Exception e){ e.printStackTrace(); } } @Override public PaymentOrderVO getPayStatus(String code) { MwServicePeriod servicePeriod = servicePeriodService.getOne(new QueryWrapper().lambda().eq(MwServicePeriod::getCode, code)); SysDepartment department = sysDepartmentService.getById(servicePeriod.getDepartmentId()); SysDictItem dictItem = dictItemService.getById(department.getBillingCompany()); PaymentOrderVO paymentOrderVO = nouNouPayUtil.queryPaymentOrder("", code, dictItem.getItemValue()); // TODO 支付成功 完成订单成功记录 return paymentOrderVO; } }