1、新增小程序相关接口
2、调整OA
This commit is contained in:
@@ -45,6 +45,10 @@
|
||||
<groupId>org.springblade</groupId>
|
||||
<artifactId>blade-user-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springblade</groupId>
|
||||
<artifactId>blade-resource-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springblade</groupId>
|
||||
<artifactId>blade-process-api</artifactId>
|
||||
|
||||
+23
-4
@@ -54,7 +54,9 @@ import org.springblade.core.tool.utils.StringPool;
|
||||
import org.springblade.system.excel.UserExcel;
|
||||
import org.springblade.system.excel.UserImporter;
|
||||
import org.springblade.system.pojo.entity.User;
|
||||
import org.springblade.system.pojo.vo.OaPersonSyncPageVO;
|
||||
import org.springblade.system.pojo.vo.UserVO;
|
||||
import org.springblade.system.service.IOASyncService;
|
||||
import org.springblade.system.service.IUserService;
|
||||
import org.springblade.system.wrapper.UserWrapper;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
@@ -77,6 +79,7 @@ import java.util.Map;
|
||||
public class UserController {
|
||||
|
||||
private final IUserService userService;
|
||||
private final IOASyncService oaSyncService;
|
||||
|
||||
/**
|
||||
* 查询单条
|
||||
@@ -158,14 +161,16 @@ public class UserController {
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步IAM账号。
|
||||
* 从OA按页同步人员,并按公司/部门生成组织后绑定到三级部门。
|
||||
*/
|
||||
@IsAdmin
|
||||
@PostMapping("/sync-iam-accounts")
|
||||
@ApiOperationSupport(order = 6)
|
||||
@Operation(summary = "同步IAM账号")
|
||||
public R<Integer> syncIamAccounts() {
|
||||
return R.data(userService.syncIamAccounts());
|
||||
@Operation(summary = "同步OA人员")
|
||||
public R<OaPersonSyncPageVO> syncIamAccounts(
|
||||
@RequestParam(defaultValue = "1") Integer current,
|
||||
@RequestParam(defaultValue = "50") Integer size) {
|
||||
return R.data(oaSyncService.syncPersonFromUserList(current, size));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -227,6 +232,20 @@ public class UserController {
|
||||
return R.status(temp);
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前用户设置/重置登录密码(小程序首次设密、短信验证后改密)
|
||||
* <p>
|
||||
* 对外路径:/blade-system/user/password ;网关别名 /blade-user/password 亦可到达。
|
||||
*/
|
||||
@PostMapping("/password")
|
||||
@ApiOperationSupport(order = 10)
|
||||
@Operation(summary = "设置登录密码", description = "当前登录用户设置密码,无需原密码")
|
||||
public R password(BladeUser user,
|
||||
@Parameter(description = "新密码", required = true) @RequestParam String password,
|
||||
@Parameter(description = "确认密码", required = true) @RequestParam String password2) {
|
||||
return R.status(userService.setPassword(user.getUserId(), password, password2));
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员修改密码
|
||||
*/
|
||||
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* BladeX Commercial License Agreement
|
||||
* Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
|
||||
* <p>
|
||||
* Use of this software is governed by the Commercial License Agreement
|
||||
* obtained after purchasing a license from BladeX.
|
||||
* <p>
|
||||
* 1. This software is for development use only under a valid license
|
||||
* from BladeX.
|
||||
* <p>
|
||||
* 2. Redistribution of this software's source code to any third party
|
||||
* without a commercial license is strictly prohibited.
|
||||
* <p>
|
||||
* 3. Licensees may copyright their own code but cannot use segments
|
||||
* from this software for such purposes. Copyright of this software
|
||||
* remains with BladeX.
|
||||
* <p>
|
||||
* Using this software signifies agreement to this License, and the software
|
||||
* must not be used for illegal purposes.
|
||||
* <p>
|
||||
* THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
|
||||
* not liable for any claims arising from secondary or illegal development.
|
||||
* <p>
|
||||
* Author: Chill Zhuang (bladejava@qq.com)
|
||||
*/
|
||||
package org.springblade.system.controller;
|
||||
|
||||
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springblade.core.tenant.annotation.NonDS;
|
||||
import org.springblade.core.tool.api.R;
|
||||
import org.springblade.system.pojo.dto.PhoneChangeDTO;
|
||||
import org.springblade.system.pojo.dto.PhoneVerifyDTO;
|
||||
import org.springblade.system.service.IUserPhoneService;
|
||||
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.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* 用户手机号变更(小程序「修改手机号」)
|
||||
* <p>
|
||||
* 对外路径:/blade-system/user/phone/** ;网关别名 /blade-user/phone/** 亦可到达。
|
||||
*
|
||||
* @author Chill
|
||||
*/
|
||||
@NonDS
|
||||
@RestController
|
||||
@AllArgsConstructor
|
||||
@RequestMapping("/user/phone")
|
||||
@Tag(name = "用户手机号", description = "修改手机号")
|
||||
public class UserPhoneController {
|
||||
|
||||
private final IUserPhoneService userPhoneService;
|
||||
|
||||
/**
|
||||
* 发送短信验证码(需登录)
|
||||
* <p>
|
||||
* 当前手机号、未占用的新手机号均可发送;新号若已被其他账号占用则拒绝。
|
||||
*/
|
||||
@PostMapping("/send-code")
|
||||
@ApiOperationSupport(order = 1)
|
||||
@Operation(summary = "发送手机号变更验证码", description = "传入明文手机号,返回短信校验 id")
|
||||
public R sendCode(@Parameter(description = "手机号", required = true) @RequestParam String phone) {
|
||||
return userPhoneService.sendCode(phone);
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验原手机号验证码(修改手机号第 1 步)
|
||||
*/
|
||||
@PostMapping("/verify-old")
|
||||
@ApiOperationSupport(order = 2)
|
||||
@Operation(summary = "校验原手机号验证码", description = "传入发送验证码返回的 id 与验证码")
|
||||
public R verifyOld(@Valid @RequestBody PhoneVerifyDTO phoneVerify) {
|
||||
return R.status(userPhoneService.verifyOldPhone(phoneVerify));
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定新手机号(修改手机号第 3 步,需先完成 verify-old)
|
||||
*/
|
||||
@PostMapping("/change")
|
||||
@ApiOperationSupport(order = 3)
|
||||
@Operation(summary = "更换手机号", description = "传入新手机号及短信校验 id、验证码")
|
||||
public R change(@Valid @RequestBody PhoneChangeDTO phoneChange) {
|
||||
return R.status(userPhoneService.changePhone(phoneChange));
|
||||
}
|
||||
|
||||
}
|
||||
+25
-3
@@ -64,11 +64,11 @@ public interface UserConvert {
|
||||
@Mapping(target = "password", ignore = true)
|
||||
@Mapping(target = "birthday", ignore = true)
|
||||
@Mapping(target = "sex", ignore = true)
|
||||
@Mapping(target = "account", ignore = true)
|
||||
@Mapping(source = "workcode", target = "code")
|
||||
@Mapping(source = "lastname", target = "name")
|
||||
@Mapping(source = "lastname", target = "realName")
|
||||
@Mapping(source = "mobile", target = "phone")
|
||||
@Mapping(source = "mobile", target = "account")
|
||||
@Mapping(source = "email", target = "email")
|
||||
User baseConvert(OAPersonResponse person);
|
||||
|
||||
@@ -86,7 +86,7 @@ public interface UserConvert {
|
||||
*/
|
||||
default User person2user(OAPersonResponse person, String defaultPassword) {
|
||||
User user = baseConvert(person);
|
||||
|
||||
user.setAccount(resolveAccount(person));
|
||||
// 密码
|
||||
user.setPassword(defaultPassword);
|
||||
// 性别
|
||||
@@ -102,6 +102,28 @@ public interface UserConvert {
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析本系统登录账号:优先 OA loginid,其次工号,最后手机号
|
||||
*
|
||||
* @param person OA人员
|
||||
* @return 账号,无法识别时返回 null
|
||||
*/
|
||||
default String resolveAccount(OAPersonResponse person) {
|
||||
if (person == null) {
|
||||
return null;
|
||||
}
|
||||
if (StringUtils.isNotBlank(person.getLoginid())) {
|
||||
return person.getLoginid().trim();
|
||||
}
|
||||
if (StringUtils.isNotBlank(person.getWorkcode())) {
|
||||
return person.getWorkcode().trim();
|
||||
}
|
||||
if (StringUtils.isNotBlank(person.getMobile())) {
|
||||
return person.getMobile().trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* oa人员转本系统用户部门
|
||||
* @param person
|
||||
@@ -120,7 +142,7 @@ public interface UserConvert {
|
||||
// 排序
|
||||
userDept.setSort(OAUtils.parseInt(person.getDsporder()));
|
||||
// 用户id
|
||||
userDept.setUserId(userMap.get(person.getMobile()));
|
||||
userDept.setUserId(userMap.get(resolveAccount(person)));
|
||||
userDept.setSyncTime(new Date());
|
||||
return userDept;
|
||||
}
|
||||
|
||||
@@ -231,4 +231,10 @@ public class SysClient implements ISysClient {
|
||||
.orderByAsc(CargoType::getCargoCode)));
|
||||
}
|
||||
|
||||
@Override
|
||||
@GetMapping(PERMISSIONS)
|
||||
public R<List<String>> getPermissions(String roleId) {
|
||||
return R.data(menuService.permissionCodes(roleId));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -133,4 +133,10 @@ public class UserClient implements IUserClient {
|
||||
return R.data(service.remove(Wrappers.<User>query().lambda().in(User::getTenantId, Func.toStrList(tenantIds))));
|
||||
}
|
||||
|
||||
@Override
|
||||
@PostMapping(BIND_WX_MINI_OPENID)
|
||||
public R<Boolean> bindWxMiniOpenId(String tenantId, Long userId, String openid, String phone) {
|
||||
return R.data(service.bindWxMiniOpenId(tenantId, userId, openid, phone));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+8
@@ -77,6 +77,14 @@ public interface IMenuService extends IService<Menu> {
|
||||
*/
|
||||
List<MenuVO> buttons(String roleId);
|
||||
|
||||
/**
|
||||
* 权限标识集合(按钮编号,与前端 GetButtons 叶子 code 一致)
|
||||
*
|
||||
* @param roleId 角色id
|
||||
* @return 权限标识
|
||||
*/
|
||||
List<String> permissionCodes(String roleId);
|
||||
|
||||
/**
|
||||
* 树形结构
|
||||
*
|
||||
|
||||
+18
@@ -1,5 +1,7 @@
|
||||
package org.springblade.system.service;
|
||||
|
||||
import org.springblade.system.pojo.vo.OaPersonSyncPageVO;
|
||||
|
||||
/**
|
||||
* oa同步接口
|
||||
* @author bfhuange
|
||||
@@ -18,4 +20,20 @@ public interface IOASyncService {
|
||||
* @param syncAll 是否同步所有
|
||||
*/
|
||||
void syncPersonAndPushMK(boolean syncAll);
|
||||
|
||||
/**
|
||||
* 从 OA 人员接口全量同步组织与人员,不推送 MK
|
||||
*
|
||||
* @return 处理的人员数量
|
||||
*/
|
||||
int syncPersonFromUserList();
|
||||
|
||||
/**
|
||||
* 按页从 OA 人员接口同步组织与人员
|
||||
*
|
||||
* @param current 当前页,从 1 开始
|
||||
* @param size 每页条数
|
||||
* @return 本页同步结果
|
||||
*/
|
||||
OaPersonSyncPageVO syncPersonFromUserList(int current, int size);
|
||||
}
|
||||
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* BladeX Commercial License Agreement
|
||||
* Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
|
||||
* <p>
|
||||
* Use of this software is governed by the Commercial License Agreement
|
||||
* obtained after purchasing a license from BladeX.
|
||||
* <p>
|
||||
* 1. This software is for development use only under a valid license
|
||||
* from BladeX.
|
||||
* <p>
|
||||
* 2. Redistribution of this software's source code to any third party
|
||||
* without a commercial license is strictly prohibited.
|
||||
* <p>
|
||||
* 3. Licensees may copyright their own code but cannot use segments
|
||||
* from this software for such purposes. Copyright of this software
|
||||
* remains with BladeX.
|
||||
* <p>
|
||||
* Using this software signifies agreement to this License, and the software
|
||||
* must not be used for illegal purposes.
|
||||
* <p>
|
||||
* THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
|
||||
* not liable for any claims arising from secondary or illegal development.
|
||||
* <p>
|
||||
* Author: Chill Zhuang (bladejava@qq.com)
|
||||
*/
|
||||
package org.springblade.system.service;
|
||||
|
||||
import org.springblade.core.tool.api.R;
|
||||
import org.springblade.system.pojo.dto.PhoneChangeDTO;
|
||||
import org.springblade.system.pojo.dto.PhoneVerifyDTO;
|
||||
|
||||
/**
|
||||
* 用户手机号变更服务
|
||||
*
|
||||
* @author Chill
|
||||
*/
|
||||
public interface IUserPhoneService {
|
||||
|
||||
/**
|
||||
* 发送变更手机号短信验证码
|
||||
*
|
||||
* @param phone 明文手机号
|
||||
* @return 含短信校验 id 的响应
|
||||
*/
|
||||
R sendCode(String phone);
|
||||
|
||||
/**
|
||||
* 校验原手机号验证码,通过后写入短期凭证
|
||||
*
|
||||
* @param phoneVerify 校验参数
|
||||
* @return 是否通过
|
||||
*/
|
||||
boolean verifyOldPhone(PhoneVerifyDTO phoneVerify);
|
||||
|
||||
/**
|
||||
* 校验新手机号验证码并更换手机号
|
||||
*
|
||||
* @param phoneChange 更换参数
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean changePhone(PhoneChangeDTO phoneChange);
|
||||
|
||||
}
|
||||
+5
@@ -188,6 +188,11 @@ public interface IUserService extends BaseService<User> {
|
||||
*/
|
||||
UserInfo userInfo(UserOauth userOauth);
|
||||
|
||||
/**
|
||||
* 绑定微信小程序 openid 到已有用户(blade_user_oauth,source=WECHAT_MINI)
|
||||
*/
|
||||
boolean bindWxMiniOpenId(String tenantId, Long userId, String openid, String phone);
|
||||
|
||||
/**
|
||||
* 根据租户与账号获取用户
|
||||
*
|
||||
|
||||
+29
@@ -164,6 +164,35 @@ public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IM
|
||||
return menuWrapper.listNodeVO(buttons);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> permissionCodes(String roleId) {
|
||||
List<String> permissionCodes = new ArrayList<>();
|
||||
// Feign 调用时无登录态,不能走 AuthUtil.isAdministrator() 分支;按 roleId 取按钮权限
|
||||
List<Menu> buttons = StringUtil.isBlank(roleId)
|
||||
? Collections.emptyList()
|
||||
: baseMapper.buttons(Func.toLongList(roleId));
|
||||
MenuWrapper menuWrapper = new MenuWrapper();
|
||||
collectLeafPermissionCodes(menuWrapper.listNodeVO(buttons), permissionCodes);
|
||||
return permissionCodes;
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归收集按钮树叶子节点的权限编号(与前端 SET_PERMISSION 逻辑一致)
|
||||
*/
|
||||
private void collectLeafPermissionCodes(List<MenuVO> menuList, List<String> permissionCodes) {
|
||||
if (menuList == null || menuList.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (MenuVO menu : menuList) {
|
||||
List<MenuVO> children = menu.getChildren();
|
||||
if (children != null && !children.isEmpty()) {
|
||||
collectLeafPermissionCodes(children, permissionCodes);
|
||||
} else if (StringUtil.isNotBlank(menu.getCode())) {
|
||||
permissionCodes.add(menu.getCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<TreeNode> tree() {
|
||||
return ForestNodeMerger.merge(baseMapper.tree());
|
||||
|
||||
+110
-183
@@ -11,16 +11,14 @@ import org.springblade.common.constant.DictTypeEnum;
|
||||
import org.springblade.core.cache.utils.CacheUtil;
|
||||
import org.springblade.core.log.exception.ServiceException;
|
||||
import org.springblade.core.tool.utils.DateUtil;
|
||||
import org.springblade.core.tool.utils.DigestUtil;
|
||||
import org.springblade.system.cache.DictCache;
|
||||
import org.springblade.system.cache.ParamCache;
|
||||
import org.springblade.system.convert.DeptConvert;
|
||||
import org.springblade.system.convert.UserConvert;
|
||||
import org.springblade.system.log.ComposeLogUtil;
|
||||
import org.springblade.system.pojo.entity.*;
|
||||
import org.springblade.system.pojo.enums.DataSync;
|
||||
import org.springblade.system.pojo.enums.DeptCategory;
|
||||
import org.springblade.system.pojo.vo.UserDeptIdsVO;
|
||||
import org.springblade.system.pojo.vo.OaPersonSyncPageVO;
|
||||
import org.springblade.system.service.*;
|
||||
import org.springblade.system.util.DataSyncRecordUtils;
|
||||
import org.springblade.thirdparty.oa.constant.OAConstant;
|
||||
@@ -29,6 +27,8 @@ import org.springblade.thirdparty.oa.feign.IOAClient;
|
||||
import org.springblade.thirdparty.oa.pojo.response.OACompanyResponse;
|
||||
import org.springblade.thirdparty.oa.pojo.response.OADepartmentResponse;
|
||||
import org.springblade.thirdparty.oa.pojo.response.OAPersonResponse;
|
||||
import org.springblade.thirdparty.oa.pojo.response.OAResponse;
|
||||
import org.springblade.thirdparty.oa.pojo.response.OAResponseData;
|
||||
import org.springblade.thirdparty.oa.pojo.search.OACompanySearch;
|
||||
import org.springblade.thirdparty.oa.pojo.search.OADepartmentSearch;
|
||||
import org.springblade.thirdparty.oa.pojo.search.OAPersonSearch;
|
||||
@@ -38,6 +38,7 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -54,20 +55,14 @@ import static org.springblade.core.cache.constant.CacheConstant.USER_CACHE;
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class OASyncServiceImpl implements IOASyncService {
|
||||
/**
|
||||
* 用户表部门id最大长度
|
||||
*/
|
||||
private static final int MAX_DEPT_ID_LENGTH = 2000;
|
||||
|
||||
private final IOAClient oaClient;
|
||||
private final DeptConvert deptConvert;
|
||||
private final IDeptService deptService;
|
||||
private final IUserService userService;
|
||||
private final UserConvert userConvert;
|
||||
private final IUserDeptService userDeptService;
|
||||
private final IRoleService roleService;
|
||||
private final IMKPushService mkPushService;
|
||||
private final IDataSyncRecordService dataSyncRecordService;
|
||||
private final OaUserListSyncHelper oaUserListSyncHelper;
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
@Override
|
||||
@@ -104,6 +99,31 @@ public class OASyncServiceImpl implements IOASyncService {
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
@Override
|
||||
public int syncPersonFromUserList() {
|
||||
AtomicInteger syncedCount = new AtomicInteger();
|
||||
try {
|
||||
ComposeLogUtil.addLog(log);
|
||||
this.syncAndRecord(DataSyncRecordUtils::createOAPersonFetch, startTime ->
|
||||
syncedCount.set(this.syncPersonFromOa(null)), true);
|
||||
return syncedCount.get();
|
||||
} finally {
|
||||
ComposeLogUtil.removeLastLog();
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
@Override
|
||||
public OaPersonSyncPageVO syncPersonFromUserList(int current, int size) {
|
||||
try {
|
||||
ComposeLogUtil.addLog(log);
|
||||
return this.syncPersonFromOaPage(current, size);
|
||||
} finally {
|
||||
ComposeLogUtil.removeLastLog();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步并记录
|
||||
*
|
||||
@@ -213,174 +233,93 @@ public class OASyncServiceImpl implements IOASyncService {
|
||||
* @param startTime 查询开始时间
|
||||
*/
|
||||
private void syncPerson(Date startTime) {
|
||||
String subCompanyIds = getSubCompanyIds();
|
||||
if (StringUtils.isEmpty(subCompanyIds)) {
|
||||
ComposeLogUtil.getLastLog().warn("未查询到子公司查询参数");
|
||||
return;
|
||||
}
|
||||
// 1. 设置查询参数
|
||||
OAPersonSearch personSearch = new OAPersonSearch();
|
||||
personSearch.setCurPage(1);
|
||||
personSearch.setSubcompanyid1(subCompanyIds);
|
||||
if (startTime != null) {
|
||||
// 开始时间不为空,设置修改时间参数
|
||||
personSearch.setModified(DateUtil.format(startTime, DateUtil.PATTERN_DATETIME));
|
||||
}
|
||||
// 2. 分页查询并处理数据
|
||||
OAUtils.pageSyncHandler(personSearch, param -> oaClient.queryPersonPage(new OASearch<>(param)), response -> {
|
||||
ComposeLogUtil.getLastLog().error("调用OA接口查询人员信息失败 {}", JSON.toJSONString(response));
|
||||
return new ServiceException("调用OA接口查询人员信息失败");
|
||||
}, 10000, ComposeLogUtil.getLastLog()::info).accept(this::handlePerson);
|
||||
// 清除用户缓存
|
||||
CacheUtil.clear(USER_CACHE);
|
||||
this.syncPersonFromOa(startTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理oa人员
|
||||
* @param oaPersons
|
||||
* 从 OA 人员列表同步组织与人员
|
||||
*
|
||||
* @param startTime 增量查询开始时间,为空则全量
|
||||
* @return 处理的人员数量
|
||||
*/
|
||||
private void handlePerson(List<OAPersonResponse> oaPersons) {
|
||||
if (CollectionUtil.isEmpty(oaPersons)) {
|
||||
// 数据为空,直接返回
|
||||
return;
|
||||
}
|
||||
// 根公司id
|
||||
String rootCompanyId = getRootCompanyId();
|
||||
if (rootCompanyId == null) {
|
||||
return;
|
||||
}
|
||||
// 根公司下要同步的部门id
|
||||
Set<String> rootCompanyDeptIds = getRootCompanyDeptIds(rootCompanyId);
|
||||
oaPersons = oaPersons.stream()
|
||||
// 公司不是根公司,或者部门在根公司下要同步的部门列表中
|
||||
.filter(oaPerson -> !rootCompanyId.equals(oaPerson.getSubcompanyid1()) || rootCompanyDeptIds.contains(oaPerson.getDepartmentid()))
|
||||
.toList();
|
||||
// 根据手机号转成set
|
||||
TreeSet<OAPersonResponse> oaPersonSet = CollectionUtil.toTreeSet(oaPersons, Comparator.comparing(OAPersonResponse::getMobile));
|
||||
// 默认密码
|
||||
String defaultPassword = DigestUtil.encrypt(ParamCache.getValue(DEFAULT_PARAM_PASSWORD));
|
||||
// 转换数据
|
||||
List<User> users = oaPersonSet.stream()
|
||||
// 只需要手机不为空的
|
||||
.filter(person -> StringUtils.isNotBlank(person.getMobile()))
|
||||
.map(person -> userConvert.person2user(person, defaultPassword))
|
||||
.toList();
|
||||
List<String> phones = users.stream()
|
||||
.map(User::getPhone)
|
||||
.filter(StringUtils::isNotBlank)
|
||||
.distinct()
|
||||
.toList();
|
||||
// 查询所有用户
|
||||
Map<String, Long> userMap = userService.list(Wrappers.<User>lambdaQuery()
|
||||
//.eq(User::getIsDeleted, BladeConstant.DB_NOT_DELETED)
|
||||
.in(User::getPhone, phones)
|
||||
).stream()
|
||||
// 解密手机号
|
||||
.peek(userService::decryptPhone)
|
||||
.collect(Collectors.toMap(User::getPhone, User::getId, (a, b) -> b));
|
||||
// 数据库存在的所有用户id
|
||||
Set<Long> existsUserIds = new HashSet<>(userMap.values());
|
||||
users.forEach(user -> {
|
||||
if (userMap.containsKey(user.getPhone())) {
|
||||
// 根据手机号获取对应的用户id
|
||||
user.setId(userMap.get(user.getPhone()));
|
||||
// 清空密码,不修改密码
|
||||
user.setPassword(null);
|
||||
} else {
|
||||
// 没有就生成一个id
|
||||
user.setId(DefaultIdentifierGenerator.getInstance().nextId(null));
|
||||
userService.encryptPhone(user);
|
||||
userMap.put(user.getPhone(), user.getId());
|
||||
}
|
||||
});
|
||||
private int syncPersonFromOa(Date startTime) {
|
||||
OAPersonSearch personSearch = buildPersonSearch(startTime);
|
||||
List<OAPersonResponse> oaPersons = new ArrayList<>();
|
||||
OAUtils.pageSyncHandler(personSearch, param -> oaClient.queryPersonPage(new OASearch<>(param)), response -> {
|
||||
ComposeLogUtil.getLastLog().error("调用OA接口查询人员信息失败 {}", JSON.toJSONString(response));
|
||||
return new ServiceException("调用OA接口查询人员信息失败");
|
||||
}, 10000, ComposeLogUtil.getLastLog()::info).accept(oaPersons::addAll);
|
||||
OaUserListSyncHelper.OaOrgIndex orgIndex = oaUserListSyncHelper.syncOrgsFromPersons(oaPersons);
|
||||
OaUserListSyncHelper.PersonSyncCount personSyncCount = oaUserListSyncHelper.handlePerson(oaPersons, orgIndex);
|
||||
CacheUtil.clear(USER_CACHE);
|
||||
CacheUtil.clear(SYS_CACHE);
|
||||
CacheUtil.clear(SYS_CACHE, Boolean.FALSE);
|
||||
return personSyncCount.getSyncedCount();
|
||||
}
|
||||
|
||||
// 不存在的新增
|
||||
List<User> addUsers = users.stream()
|
||||
.filter(user -> !existsUserIds.contains(user.getId()))
|
||||
.toList();
|
||||
if (CollectionUtil.isNotEmpty(addUsers)) {
|
||||
ComposeLogUtil.getLastLog().info("批量新增用户:{}", addUsers.size());
|
||||
userService.saveBatch(addUsers);
|
||||
/**
|
||||
* 按页从 OA 人员列表同步组织与人员
|
||||
*
|
||||
* @param current 当前页
|
||||
* @param size 每页条数
|
||||
* @return 本页同步结果
|
||||
*/
|
||||
private OaPersonSyncPageVO syncPersonFromOaPage(int current, int size) {
|
||||
int pageNo = current < 1 ? 1 : current;
|
||||
int pageSize = size < 1 ? 50 : Math.min(size, 200);
|
||||
OAPersonSearch personSearch = buildPersonSearch(null);
|
||||
personSearch.setCurPage(pageNo);
|
||||
personSearch.setPageSize(pageSize);
|
||||
OAResponse<OAPersonResponse> oaResponse = oaClient.queryPersonPage(new OASearch<>(personSearch));
|
||||
if (oaResponse == null || !OAConstant.OA_SUCCESS_CODE.equals(oaResponse.getCode()) || oaResponse.getData() == null) {
|
||||
ComposeLogUtil.getLastLog().error("调用OA接口查询人员信息失败 {}", JSON.toJSONString(oaResponse));
|
||||
throw new ServiceException("调用OA接口查询人员信息失败");
|
||||
}
|
||||
// 存在的修改
|
||||
List<User> updateUsers = users.stream()
|
||||
.filter(user -> existsUserIds.contains(user.getId()))
|
||||
.toList();
|
||||
if (CollectionUtil.isNotEmpty(updateUsers)) {
|
||||
ComposeLogUtil.getLastLog().info("批量修改用户:{}", updateUsers.size());
|
||||
userService.updateBatchById(updateUsers);
|
||||
}
|
||||
// 没有手机号的数据 = 手机号为空的数量
|
||||
long noPhoneNum = oaPersons.stream()
|
||||
.map(OAPersonResponse::getMobile)
|
||||
.filter(StringUtils::isBlank)
|
||||
.count();
|
||||
ComposeLogUtil.getLastLog().info("没有手机号的数据:{}", noPhoneNum);
|
||||
OAResponseData<OAPersonResponse> responseData = oaResponse.getData();
|
||||
List<OAPersonResponse> oaPersons = responseData.getDataList() == null
|
||||
? Collections.emptyList() : responseData.getDataList();
|
||||
long totalSize = responseData.getTotalSize() == null ? 0L : responseData.getTotalSize();
|
||||
OaUserListSyncHelper.OaOrgIndex orgIndex = oaUserListSyncHelper.syncOrgsFromPersons(oaPersons);
|
||||
OaUserListSyncHelper.PersonSyncCount personSyncCount = oaUserListSyncHelper.handlePerson(oaPersons, orgIndex);
|
||||
CacheUtil.clear(USER_CACHE);
|
||||
CacheUtil.clear(SYS_CACHE);
|
||||
CacheUtil.clear(SYS_CACHE, Boolean.FALSE);
|
||||
OaPersonSyncPageVO pageVO = new OaPersonSyncPageVO();
|
||||
pageVO.setCurrent(pageNo);
|
||||
pageVO.setSize(pageSize);
|
||||
pageVO.setTotal(totalSize);
|
||||
pageVO.setFetchedCount(oaPersons.size());
|
||||
pageVO.setSyncedCount(personSyncCount.getSyncedCount());
|
||||
pageVO.setSkippedCount(personSyncCount.getSkippedCount());
|
||||
boolean finished = oaPersons.isEmpty()
|
||||
|| oaPersons.size() < pageSize
|
||||
|| (long) pageNo * pageSize >= totalSize;
|
||||
pageVO.setFinished(finished);
|
||||
ComposeLogUtil.getLastLog().info("OA人员分页同步完成 {}/{},成功{},跳过{}",
|
||||
pageNo, totalSize, personSyncCount.getSyncedCount(), personSyncCount.getSkippedCount());
|
||||
return pageVO;
|
||||
}
|
||||
|
||||
Map<String, Long> userDeptMap = userDeptService.list(Wrappers.<UserDept>lambdaQuery()
|
||||
.in(UserDept::getUserId, userMap.values())
|
||||
).stream()
|
||||
.collect(Collectors.toMap(this::getUserDeptKey, UserDept::getId, (a, b) -> b));
|
||||
// 数据库存在的所有用户部门id
|
||||
Set<Long> existsUserDeptIds = new HashSet<>(userDeptMap.values());
|
||||
|
||||
List<UserDept> userDeptList = oaPersons.stream()
|
||||
// 只要包含用户手机号的
|
||||
.filter(oaPerson -> userMap.containsKey(oaPerson.getMobile()))
|
||||
.map(oaPerson -> userConvert.person2userDept(oaPerson, userMap))
|
||||
.toList();
|
||||
userDeptList.forEach(userDept -> {
|
||||
String userDeptKey = getUserDeptKey(userDept);
|
||||
if (userDeptMap.containsKey(userDeptKey)) {
|
||||
// 根据key获取用户部门id
|
||||
userDept.setId(userDeptMap.get(userDeptKey));
|
||||
} else {
|
||||
// 没有就生成一个id
|
||||
userDept.setId(DefaultIdentifierGenerator.getInstance().nextId(null));
|
||||
}
|
||||
});
|
||||
// 不存在的新增
|
||||
List<UserDept> addList = userDeptList.stream()
|
||||
.filter(userDept -> !existsUserDeptIds.contains(userDept.getId()))
|
||||
.toList();
|
||||
if (CollectionUtil.isNotEmpty(addList)) {
|
||||
ComposeLogUtil.getLastLog().info("批量新增用户部门:{}", addList.size());
|
||||
userDeptService.saveBatch(addList);
|
||||
}
|
||||
// 存在的修改
|
||||
List<UserDept> updateList = userDeptList.stream()
|
||||
.filter(userDept -> existsUserDeptIds.contains(userDept.getId()))
|
||||
.toList();
|
||||
if (CollectionUtil.isNotEmpty(updateList)) {
|
||||
ComposeLogUtil.getLastLog().info("批量修改用户部门:{}", updateList.size());
|
||||
userDeptService.updateBatchById(updateList);
|
||||
}
|
||||
// 回写部门id到用户表
|
||||
Collection<Long> userIds = userMap.values();
|
||||
List<UserDeptIdsVO> list = userDeptService.queryUserDeptIds(userIds);
|
||||
// 查询没有角色的用户id
|
||||
Set<Long> noRoleUserIds = userService.list(Wrappers.<User>lambdaQuery()
|
||||
.in(User::getId, userIds)
|
||||
.isNull(User::getRoleId)
|
||||
).stream()
|
||||
.map(User::getId)
|
||||
.collect(Collectors.toSet());
|
||||
// 获取默认角色id
|
||||
String defaultRoleId = getDefaultRoleId();
|
||||
List<User> updateUserParams = list.stream()
|
||||
// 过滤掉空部门id及长度超长的
|
||||
.filter(userDeptIds -> StringUtils.isNotBlank(userDeptIds.getDeptIds()) && userDeptIds.getDeptIds().length() <= MAX_DEPT_ID_LENGTH)
|
||||
.map(userDeptIds -> {
|
||||
User user = new User();
|
||||
user.setId(userDeptIds.getUserId());
|
||||
user.setDeptId(userDeptIds.getDeptIds());
|
||||
user.setDeptCodes(userDeptIds.getDeptCodes());
|
||||
if (noRoleUserIds.contains(userDeptIds.getUserId())) {
|
||||
user.setRoleId(defaultRoleId);
|
||||
}
|
||||
return user;
|
||||
}).toList();
|
||||
userService.updateBatchById(updateUserParams);
|
||||
/**
|
||||
* 组装 OA 人员分页查询参数
|
||||
*
|
||||
* @param startTime 增量查询开始时间
|
||||
* @return 查询参数
|
||||
*/
|
||||
private OAPersonSearch buildPersonSearch(Date startTime) {
|
||||
OAPersonSearch personSearch = new OAPersonSearch();
|
||||
personSearch.setCurPage(1);
|
||||
personSearch.setPageSize(200);
|
||||
personSearch.setCreated("");
|
||||
personSearch.setWorkcode("");
|
||||
personSearch.setSubcompanyid1("");
|
||||
personSearch.setDepartmentid("");
|
||||
personSearch.setJobtitleid("");
|
||||
personSearch.setId("");
|
||||
personSearch.setLoginid("");
|
||||
personSearch.setIsadaccount("");
|
||||
personSearch.setModified(startTime == null ? "" : DateUtil.format(startTime, DateUtil.PATTERN_DATETIME));
|
||||
return personSearch;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -634,16 +573,4 @@ public class OASyncServiceImpl implements IOASyncService {
|
||||
// 部门编码去掉前缀,就是oa的id
|
||||
return dept.getDeptCode().replace(OAConvertConstant.COMPANY_OA_PREFIX, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户部门唯一标识,用户id+公司编码+部门编码
|
||||
* @param userDept
|
||||
* @return
|
||||
*/
|
||||
private String getUserDeptKey(UserDept userDept) {
|
||||
if (userDept == null) {
|
||||
return null;
|
||||
}
|
||||
return userDept.getUserId() + userDept.getCompanyCode() + userDept.getDeptCode();
|
||||
}
|
||||
}
|
||||
|
||||
+609
@@ -0,0 +1,609 @@
|
||||
/**
|
||||
* BladeX Commercial License Agreement
|
||||
* Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
|
||||
* <p>
|
||||
* Use of this software is governed by the Commercial License Agreement
|
||||
* obtained after purchasing a license from BladeX.
|
||||
* <p>
|
||||
* 1. This software is for development use only under a valid license
|
||||
* from BladeX.
|
||||
* <p>
|
||||
* 2. Redistribution of this software's source code to any third party
|
||||
* without a commercial license is strictly prohibited.
|
||||
* <p>
|
||||
* 3. Licensees may copyright their own code but cannot use segments
|
||||
* from this software for such purposes. Copyright of this software
|
||||
* remains with BladeX.
|
||||
* <p>
|
||||
* Using this software signifies agreement to this License, and the software
|
||||
* must not be used for illegal purposes.
|
||||
* <p>
|
||||
* THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
|
||||
* not liable for any claims arising from secondary or illegal development.
|
||||
* <p>
|
||||
* Author: Chill Zhuang (bladejava@qq.com)
|
||||
*/
|
||||
package org.springblade.system.service.impl;
|
||||
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springblade.common.constant.DataStatusEnum;
|
||||
import org.springblade.core.secure.utils.AuthUtil;
|
||||
import org.springblade.core.tool.constant.BladeConstant;
|
||||
import org.springblade.core.tool.utils.DigestUtil;
|
||||
import org.springblade.system.cache.ParamCache;
|
||||
import org.springblade.system.convert.UserConvert;
|
||||
import org.springblade.system.log.ComposeLogUtil;
|
||||
import org.springblade.system.pojo.entity.Dept;
|
||||
import org.springblade.system.pojo.entity.Role;
|
||||
import org.springblade.system.pojo.entity.User;
|
||||
import org.springblade.system.pojo.entity.UserDept;
|
||||
import org.springblade.system.pojo.enums.DeptCategory;
|
||||
import org.springblade.system.pojo.vo.UserDeptIdsVO;
|
||||
import org.springblade.system.service.IDeptService;
|
||||
import org.springblade.system.service.IRoleService;
|
||||
import org.springblade.system.service.IUserDeptService;
|
||||
import org.springblade.system.service.IUserService;
|
||||
import org.springblade.thirdparty.oa.constant.OAConvertConstant;
|
||||
import org.springblade.thirdparty.oa.pojo.response.OAPersonResponse;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.springblade.common.constant.CommonConstant.DEFAULT_PARAM_PASSWORD;
|
||||
import static org.springblade.common.constant.CommonConstant.DEFAULT_PARAM_ROLE;
|
||||
import static org.springblade.common.constant.CommonConstant.DEFAULT_ROLE;
|
||||
import static org.springblade.common.constant.CommonConstant.YES;
|
||||
|
||||
/**
|
||||
* 从 OA 人员列表提取组织并同步人员
|
||||
*
|
||||
* @author Chill
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class OaUserListSyncHelper {
|
||||
|
||||
private static final int MAX_DEPT_ID_LENGTH = 2000;
|
||||
|
||||
private final IDeptService deptService;
|
||||
private final IUserService userService;
|
||||
private final UserConvert userConvert;
|
||||
private final IUserDeptService userDeptService;
|
||||
private final IRoleService roleService;
|
||||
|
||||
/**
|
||||
* 从人员数据提取二级公司、三级部门,并挂到「桂物物流集团」下
|
||||
*
|
||||
* @param oaPersons OA人员
|
||||
* @return 组织索引
|
||||
*/
|
||||
public OaOrgIndex syncOrgsFromPersons(List<OAPersonResponse> oaPersons) {
|
||||
OaOrgIndex orgIndex = new OaOrgIndex();
|
||||
if (CollectionUtil.isEmpty(oaPersons)) {
|
||||
return orgIndex;
|
||||
}
|
||||
Date orgSyncStart = new Date();
|
||||
Dept rootCompany = this.getOrCreateRootCompany();
|
||||
String tenantId = resolveTenantId();
|
||||
Map<String, OAPersonResponse> companyPersonMap = new LinkedHashMap<>();
|
||||
Map<String, OAPersonResponse> departmentPersonMap = new LinkedHashMap<>();
|
||||
for (OAPersonResponse oaPerson : oaPersons) {
|
||||
String companyKey = resolveCompanyKey(oaPerson);
|
||||
if (StringUtils.isNotBlank(companyKey) && StringUtils.isNotBlank(oaPerson.getSubcompanyname())) {
|
||||
companyPersonMap.putIfAbsent(companyKey, oaPerson);
|
||||
}
|
||||
String departmentKey = resolveDepartmentKey(oaPerson);
|
||||
if (StringUtils.isNotBlank(departmentKey) && StringUtils.isNotBlank(oaPerson.getDepartmentname())
|
||||
&& StringUtils.isNotBlank(oaPerson.getSubcompanyname())) {
|
||||
departmentPersonMap.putIfAbsent(departmentKey, oaPerson);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, Dept> existingCompanyByCode = new HashMap<>();
|
||||
Map<String, Dept> existingCompanyByName = new HashMap<>();
|
||||
deptService.list(Wrappers.<Dept>lambdaQuery()
|
||||
.eq(Dept::getParentId, rootCompany.getId())
|
||||
.eq(Dept::getDeptCategory, DeptCategory.COMPANY.getCode())
|
||||
).forEach(dept -> {
|
||||
if (StringUtils.isNotBlank(dept.getDeptCode())) {
|
||||
existingCompanyByCode.put(dept.getDeptCode(), dept);
|
||||
}
|
||||
if (StringUtils.isNotBlank(dept.getDeptName())) {
|
||||
existingCompanyByName.put(dept.getDeptName(), dept);
|
||||
}
|
||||
});
|
||||
List<Dept> addCompanies = new ArrayList<>();
|
||||
List<Dept> updateCompanies = new ArrayList<>();
|
||||
companyPersonMap.forEach((companyKey, oaPerson) -> {
|
||||
String oaCode = buildCompanyCode(oaPerson, companyKey);
|
||||
Dept existing = existingCompanyByCode.get(oaCode);
|
||||
if (existing == null) {
|
||||
existing = existingCompanyByName.get(oaPerson.getSubcompanyname());
|
||||
}
|
||||
Dept company = this.upsertOrg(oaPerson.getSubcompanyname(), oaCode, existing, rootCompany, tenantId,
|
||||
DeptCategory.COMPANY, addCompanies, updateCompanies);
|
||||
orgIndex.companyByOaId.put(companyKey, company);
|
||||
});
|
||||
this.saveOrgs(addCompanies, updateCompanies, DeptCategory.COMPANY);
|
||||
|
||||
Map<String, Dept> existingDeptByCode = new HashMap<>();
|
||||
Map<String, Dept> existingDeptByParentAndName = new HashMap<>();
|
||||
List<Long> companyIds = orgIndex.companyByOaId.values().stream()
|
||||
.map(Dept::getId)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.toList();
|
||||
if (CollectionUtil.isNotEmpty(companyIds)) {
|
||||
deptService.list(Wrappers.<Dept>lambdaQuery()
|
||||
.in(Dept::getParentId, companyIds)
|
||||
.eq(Dept::getDeptCategory, DeptCategory.DEPT.getCode())
|
||||
).forEach(dept -> {
|
||||
if (StringUtils.isNotBlank(dept.getDeptCode())) {
|
||||
existingDeptByCode.put(dept.getDeptCode(), dept);
|
||||
}
|
||||
if (dept.getParentId() != null && StringUtils.isNotBlank(dept.getDeptName())) {
|
||||
existingDeptByParentAndName.put(dept.getParentId() + "#" + dept.getDeptName(), dept);
|
||||
}
|
||||
});
|
||||
}
|
||||
List<Dept> addDepartments = new ArrayList<>();
|
||||
List<Dept> updateDepartments = new ArrayList<>();
|
||||
departmentPersonMap.forEach((departmentKey, oaPerson) -> {
|
||||
Dept parentCompany = orgIndex.findCompany(oaPerson);
|
||||
if (parentCompany == null || parentCompany.getId() == null) {
|
||||
return;
|
||||
}
|
||||
String oaCode = buildDepartmentCode(oaPerson, departmentKey);
|
||||
Dept existing = existingDeptByCode.get(oaCode);
|
||||
if (existing == null) {
|
||||
existing = existingDeptByParentAndName.get(parentCompany.getId() + "#" + oaPerson.getDepartmentname());
|
||||
}
|
||||
Dept department = this.upsertOrg(oaPerson.getDepartmentname(), oaCode, existing, parentCompany, tenantId,
|
||||
DeptCategory.DEPT, addDepartments, updateDepartments);
|
||||
orgIndex.deptByOaId.put(departmentKey, department);
|
||||
orgIndex.deptByCompanyAndName.put(resolveCompanyKey(oaPerson) + "#" + oaPerson.getDepartmentname(), department);
|
||||
});
|
||||
this.saveOrgs(addDepartments, updateDepartments, DeptCategory.DEPT);
|
||||
deptService.updateAncestors(orgSyncStart);
|
||||
ComposeLogUtil.getLastLog().info("同步人员提取组织完成,二级公司{}个,三级部门{}个",
|
||||
orgIndex.companyByOaId.size(), orgIndex.deptByOaId.size());
|
||||
return orgIndex;
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步人员并绑定到三级部门
|
||||
*
|
||||
* @param oaPersons OA人员
|
||||
* @param orgIndex 组织索引
|
||||
* @return 本批同步成功与跳过数量
|
||||
*/
|
||||
public PersonSyncCount handlePerson(List<OAPersonResponse> oaPersons, OaOrgIndex orgIndex) {
|
||||
if (CollectionUtil.isEmpty(oaPersons)) {
|
||||
return new PersonSyncCount(0, 0);
|
||||
}
|
||||
Map<String, OAPersonResponse> uniquePersonMap = new LinkedHashMap<>();
|
||||
int skippedCount = 0;
|
||||
for (OAPersonResponse oaPerson : oaPersons) {
|
||||
String account = userConvert.resolveAccount(oaPerson);
|
||||
if (StringUtils.isBlank(account)) {
|
||||
skippedCount++;
|
||||
continue;
|
||||
}
|
||||
uniquePersonMap.putIfAbsent(account, oaPerson);
|
||||
}
|
||||
if (uniquePersonMap.isEmpty()) {
|
||||
ComposeLogUtil.getLastLog().warn("OA人员均缺少loginid/工号/手机号,跳过人员同步");
|
||||
return new PersonSyncCount(0, skippedCount);
|
||||
}
|
||||
String tenantId = resolveTenantId();
|
||||
String defaultPassword = DigestUtil.encrypt(ParamCache.getValue(DEFAULT_PARAM_PASSWORD));
|
||||
List<User> users = uniquePersonMap.values().stream()
|
||||
.map(person -> {
|
||||
User user = userConvert.person2user(person, defaultPassword);
|
||||
user.setTenantId(tenantId);
|
||||
return user;
|
||||
})
|
||||
.toList();
|
||||
List<String> accounts = users.stream()
|
||||
.map(User::getAccount)
|
||||
.filter(StringUtils::isNotBlank)
|
||||
.distinct()
|
||||
.toList();
|
||||
List<String> phones = users.stream()
|
||||
.map(User::getPhone)
|
||||
.filter(StringUtils::isNotBlank)
|
||||
.distinct()
|
||||
.toList();
|
||||
Map<String, User> existingByAccount = new HashMap<>();
|
||||
Map<String, User> existingByPhone = new HashMap<>();
|
||||
userService.list(Wrappers.<User>lambdaQuery()
|
||||
.and(wrapper -> {
|
||||
wrapper.in(User::getAccount, accounts);
|
||||
if (CollectionUtil.isNotEmpty(phones)) {
|
||||
wrapper.or().in(User::getPhone, phones);
|
||||
}
|
||||
})
|
||||
).stream()
|
||||
.peek(userService::decryptPhone)
|
||||
.forEach(user -> {
|
||||
if (StringUtils.isNotBlank(user.getAccount())) {
|
||||
existingByAccount.put(user.getAccount(), user);
|
||||
}
|
||||
if (StringUtils.isNotBlank(user.getPhone())) {
|
||||
existingByPhone.put(user.getPhone(), user);
|
||||
}
|
||||
});
|
||||
Map<String, Long> userMap = new HashMap<>();
|
||||
Set<Long> existsUserIds = new HashSet<>();
|
||||
users.forEach(user -> {
|
||||
User existingUser = existingByAccount.get(user.getAccount());
|
||||
if (existingUser == null && StringUtils.isNotBlank(user.getPhone())) {
|
||||
existingUser = existingByPhone.get(user.getPhone());
|
||||
}
|
||||
if (existingUser != null) {
|
||||
user.setId(existingUser.getId());
|
||||
user.setPassword(null);
|
||||
existsUserIds.add(existingUser.getId());
|
||||
} else {
|
||||
user.setId(DefaultIdentifierGenerator.getInstance().nextId(null));
|
||||
user.setPostId("-1");
|
||||
user.setPersonCategory(1);
|
||||
user.setDataScopeRange(1);
|
||||
user.setDataLevelRange(1);
|
||||
user.setIncludeNewCustomer(0);
|
||||
userService.encryptPhone(user);
|
||||
}
|
||||
userMap.put(user.getAccount(), user.getId());
|
||||
});
|
||||
|
||||
List<User> addUsers = users.stream()
|
||||
.filter(user -> !existsUserIds.contains(user.getId()))
|
||||
.toList();
|
||||
if (CollectionUtil.isNotEmpty(addUsers)) {
|
||||
ComposeLogUtil.getLastLog().info("批量新增用户:{}", addUsers.size());
|
||||
userService.saveBatch(addUsers);
|
||||
}
|
||||
List<User> updateUsers = users.stream()
|
||||
.filter(user -> existsUserIds.contains(user.getId()))
|
||||
.toList();
|
||||
if (CollectionUtil.isNotEmpty(updateUsers)) {
|
||||
ComposeLogUtil.getLastLog().info("批量修改用户:{}", updateUsers.size());
|
||||
userService.updateBatchById(updateUsers);
|
||||
}
|
||||
ComposeLogUtil.getLastLog().info("缺少账号已跳过的人员:{}", skippedCount);
|
||||
if (userMap.isEmpty()) {
|
||||
return new PersonSyncCount(0, skippedCount);
|
||||
}
|
||||
|
||||
Map<String, Long> userDeptMap = userDeptService.list(Wrappers.<UserDept>lambdaQuery()
|
||||
.in(UserDept::getUserId, userMap.values())
|
||||
).stream()
|
||||
.collect(Collectors.toMap(this::getUserDeptKey, UserDept::getId, (first, second) -> second));
|
||||
Set<Long> existsUserDeptIds = new HashSet<>(userDeptMap.values());
|
||||
List<UserDept> userDeptList = oaPersons.stream()
|
||||
.filter(oaPerson -> userMap.containsKey(userConvert.resolveAccount(oaPerson)))
|
||||
.map(oaPerson -> this.buildUserDept(oaPerson, userMap, orgIndex))
|
||||
.filter(Objects::nonNull)
|
||||
.toList();
|
||||
userDeptList.forEach(userDept -> {
|
||||
String userDeptKey = getUserDeptKey(userDept);
|
||||
if (userDeptMap.containsKey(userDeptKey)) {
|
||||
userDept.setId(userDeptMap.get(userDeptKey));
|
||||
} else {
|
||||
userDept.setId(DefaultIdentifierGenerator.getInstance().nextId(null));
|
||||
}
|
||||
});
|
||||
List<UserDept> addList = userDeptList.stream()
|
||||
.filter(userDept -> !existsUserDeptIds.contains(userDept.getId()))
|
||||
.toList();
|
||||
if (CollectionUtil.isNotEmpty(addList)) {
|
||||
ComposeLogUtil.getLastLog().info("批量新增用户部门:{}", addList.size());
|
||||
userDeptService.saveBatch(addList);
|
||||
}
|
||||
List<UserDept> updateList = userDeptList.stream()
|
||||
.filter(userDept -> existsUserDeptIds.contains(userDept.getId()))
|
||||
.toList();
|
||||
if (CollectionUtil.isNotEmpty(updateList)) {
|
||||
ComposeLogUtil.getLastLog().info("批量修改用户部门:{}", updateList.size());
|
||||
userDeptService.updateBatchById(updateList);
|
||||
}
|
||||
Collection<Long> userIds = userMap.values();
|
||||
List<UserDeptIdsVO> list = userDeptService.queryUserDeptIds(userIds);
|
||||
Set<Long> noRoleUserIds = userService.list(Wrappers.<User>lambdaQuery()
|
||||
.in(User::getId, userIds)
|
||||
.and(wrapper -> wrapper.isNull(User::getRoleId)
|
||||
.or().eq(User::getRoleId, "")
|
||||
.or().eq(User::getRoleId, "-1"))
|
||||
).stream()
|
||||
.map(User::getId)
|
||||
.collect(Collectors.toSet());
|
||||
String defaultRoleId = getDefaultRoleId();
|
||||
List<User> updateUserParams = list.stream()
|
||||
.filter(userDeptIds -> StringUtils.isNotBlank(userDeptIds.getDeptIds()) && userDeptIds.getDeptIds().length() <= MAX_DEPT_ID_LENGTH)
|
||||
.map(userDeptIds -> {
|
||||
User user = new User();
|
||||
user.setId(userDeptIds.getUserId());
|
||||
user.setDeptId(userDeptIds.getDeptIds());
|
||||
user.setDeptCodes(userDeptIds.getDeptCodes());
|
||||
if (noRoleUserIds.contains(userDeptIds.getUserId())) {
|
||||
user.setRoleId(defaultRoleId);
|
||||
}
|
||||
return user;
|
||||
}).toList();
|
||||
if (CollectionUtil.isNotEmpty(updateUserParams)) {
|
||||
userService.updateBatchById(updateUserParams);
|
||||
}
|
||||
return new PersonSyncCount(users.size(), skippedCount);
|
||||
}
|
||||
|
||||
private Dept getOrCreateRootCompany() {
|
||||
Dept rootCompany = deptService.getOne(Wrappers.<Dept>lambdaQuery()
|
||||
.eq(Dept::getDeptName, OAConvertConstant.ROOT_COMPANY_NAME)
|
||||
.last("limit 1"), false);
|
||||
if (rootCompany != null) {
|
||||
return rootCompany;
|
||||
}
|
||||
rootCompany = new Dept();
|
||||
rootCompany.setId(DefaultIdentifierGenerator.getInstance().nextId(null));
|
||||
rootCompany.setTenantId(resolveTenantId());
|
||||
rootCompany.setParentId(BladeConstant.TOP_PARENT_ID);
|
||||
rootCompany.setAncestors(String.valueOf(BladeConstant.TOP_PARENT_ID));
|
||||
rootCompany.setDeptName(OAConvertConstant.ROOT_COMPANY_NAME);
|
||||
rootCompany.setFullName(OAConvertConstant.ROOT_COMPANY_NAME);
|
||||
rootCompany.setShortName(OAConvertConstant.ROOT_COMPANY_NAME);
|
||||
rootCompany.setDeptCode("OACROOT");
|
||||
rootCompany.setParentCode(String.valueOf(BladeConstant.TOP_PARENT_ID));
|
||||
rootCompany.setBelongCompanyCode("OACROOT");
|
||||
rootCompany.setDeptCategory(DeptCategory.COMPANY.getCode());
|
||||
rootCompany.setSort(0);
|
||||
rootCompany.setStatus(DataStatusEnum.ENABLE.getCode());
|
||||
rootCompany.setIsDeleted(BladeConstant.DB_NOT_DELETED);
|
||||
rootCompany.setIsOa(YES);
|
||||
rootCompany.setIsPlatformCompany(0);
|
||||
rootCompany.setSyncTime(new Date());
|
||||
deptService.save(rootCompany);
|
||||
ComposeLogUtil.getLastLog().info("已创建顶级组织:{}", OAConvertConstant.ROOT_COMPANY_NAME);
|
||||
return rootCompany;
|
||||
}
|
||||
|
||||
private Dept upsertOrg(String name, String oaCode, Dept existing, Dept parent, String tenantId,
|
||||
DeptCategory deptCategory, List<Dept> addList, List<Dept> updateList) {
|
||||
if (existing != null) {
|
||||
Dept updateParam = new Dept();
|
||||
updateParam.setId(existing.getId());
|
||||
updateParam.setDeptName(name);
|
||||
updateParam.setFullName(name);
|
||||
updateParam.setShortName(name);
|
||||
updateParam.setParentId(parent.getId());
|
||||
updateParam.setParentCode(parent.getDeptCode());
|
||||
updateParam.setAncestors(buildAncestors(parent));
|
||||
updateParam.setIsOa(YES);
|
||||
updateParam.setSyncTime(new Date());
|
||||
updateList.add(updateParam);
|
||||
existing.setDeptName(name);
|
||||
existing.setFullName(name);
|
||||
existing.setShortName(name);
|
||||
existing.setParentId(parent.getId());
|
||||
existing.setParentCode(parent.getDeptCode());
|
||||
existing.setAncestors(updateParam.getAncestors());
|
||||
return existing;
|
||||
}
|
||||
Dept dept = this.buildOrgDept(name, oaCode, parent, tenantId, deptCategory);
|
||||
dept.setId(DefaultIdentifierGenerator.getInstance().nextId(null));
|
||||
addList.add(dept);
|
||||
return dept;
|
||||
}
|
||||
|
||||
private void saveOrgs(List<Dept> addList, List<Dept> updateList, DeptCategory deptCategory) {
|
||||
if (CollectionUtil.isNotEmpty(addList)) {
|
||||
ComposeLogUtil.getLastLog().info("批量新增{}:{}", deptCategory.getName(), addList.size());
|
||||
deptService.saveBatch(addList);
|
||||
}
|
||||
if (CollectionUtil.isNotEmpty(updateList)) {
|
||||
ComposeLogUtil.getLastLog().info("批量修改{}:{}", deptCategory.getName(), updateList.size());
|
||||
deptService.updateBatchById(updateList);
|
||||
}
|
||||
}
|
||||
|
||||
private Dept buildOrgDept(String name, String deptCode, Dept parent, String tenantId, DeptCategory deptCategory) {
|
||||
Dept dept = new Dept();
|
||||
dept.setTenantId(tenantId);
|
||||
dept.setParentId(parent.getId());
|
||||
dept.setParentCode(parent.getDeptCode());
|
||||
dept.setAncestors(this.buildAncestors(parent));
|
||||
dept.setDeptName(name);
|
||||
dept.setFullName(name);
|
||||
dept.setShortName(name);
|
||||
dept.setDeptCode(deptCode);
|
||||
dept.setBelongCompanyCode(DeptCategory.COMPANY.equals(deptCategory) ? deptCode : parent.getBelongCompanyCode());
|
||||
dept.setDeptCategory(deptCategory.getCode());
|
||||
dept.setSort(0);
|
||||
dept.setStatus(DataStatusEnum.ENABLE.getCode());
|
||||
dept.setIsDeleted(BladeConstant.DB_NOT_DELETED);
|
||||
dept.setIsOa(YES);
|
||||
dept.setIsPlatformCompany(0);
|
||||
dept.setSyncTime(new Date());
|
||||
return dept;
|
||||
}
|
||||
|
||||
private UserDept buildUserDept(OAPersonResponse oaPerson, Map<String, Long> userMap, OaOrgIndex orgIndex) {
|
||||
Dept department = orgIndex.findDept(oaPerson);
|
||||
if (department == null || department.getId() == null) {
|
||||
return null;
|
||||
}
|
||||
UserDept userDept = userConvert.person2userDept(oaPerson, userMap);
|
||||
if (userDept.getUserId() == null) {
|
||||
return null;
|
||||
}
|
||||
Dept company = orgIndex.findCompany(oaPerson);
|
||||
userDept.setDeptId(department.getId());
|
||||
userDept.setDeptCode(department.getDeptCode());
|
||||
userDept.setDeptName(department.getDeptName());
|
||||
if (company != null) {
|
||||
userDept.setCompanyCode(company.getDeptCode());
|
||||
userDept.setCompanyName(company.getDeptName());
|
||||
}
|
||||
return userDept;
|
||||
}
|
||||
|
||||
private String getDefaultRoleId() {
|
||||
String defaultRole = ParamCache.getValue(DEFAULT_PARAM_ROLE);
|
||||
if (defaultRole == null) {
|
||||
defaultRole = DEFAULT_ROLE;
|
||||
}
|
||||
List<Role> roleList = roleService.list(Wrappers.<Role>lambdaQuery()
|
||||
.eq(Role::getRoleAlias, defaultRole)
|
||||
);
|
||||
if (CollectionUtil.isEmpty(roleList)) {
|
||||
return null;
|
||||
}
|
||||
return roleList.get(0).getId().toString();
|
||||
}
|
||||
|
||||
private String resolveCompanyKey(OAPersonResponse oaPerson) {
|
||||
if (oaPerson == null) {
|
||||
return null;
|
||||
}
|
||||
if (StringUtils.isNotBlank(oaPerson.getSubcompanyid1())) {
|
||||
return oaPerson.getSubcompanyid1().trim();
|
||||
}
|
||||
if (StringUtils.isNotBlank(oaPerson.getSubcompanyname())) {
|
||||
return "NAME:" + oaPerson.getSubcompanyname().trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String resolveDepartmentKey(OAPersonResponse oaPerson) {
|
||||
if (oaPerson == null) {
|
||||
return null;
|
||||
}
|
||||
if (StringUtils.isNotBlank(oaPerson.getDepartmentid())) {
|
||||
return oaPerson.getDepartmentid().trim();
|
||||
}
|
||||
String companyKey = resolveCompanyKey(oaPerson);
|
||||
if (StringUtils.isNotBlank(companyKey) && StringUtils.isNotBlank(oaPerson.getDepartmentname())) {
|
||||
return companyKey + ":" + oaPerson.getDepartmentname().trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String buildCompanyCode(OAPersonResponse oaPerson, String companyKey) {
|
||||
if (StringUtils.isNotBlank(oaPerson.getSubcompanyid1())) {
|
||||
return OAConvertConstant.COMPANY_OA_PREFIX + oaPerson.getSubcompanyid1().trim();
|
||||
}
|
||||
return OAConvertConstant.COMPANY_OA_PREFIX + "N" + Math.abs(companyKey.hashCode());
|
||||
}
|
||||
|
||||
private String buildDepartmentCode(OAPersonResponse oaPerson, String departmentKey) {
|
||||
if (StringUtils.isNotBlank(oaPerson.getDepartmentid())) {
|
||||
return OAConvertConstant.DEPARTMENT_OA_PREFIX + oaPerson.getDepartmentid().trim();
|
||||
}
|
||||
return OAConvertConstant.DEPARTMENT_OA_PREFIX + "N" + Math.abs(departmentKey.hashCode());
|
||||
}
|
||||
|
||||
private String buildAncestors(Dept parent) {
|
||||
String ancestors = parent.getAncestors();
|
||||
if (StringUtils.isBlank(ancestors)) {
|
||||
ancestors = String.valueOf(BladeConstant.TOP_PARENT_ID);
|
||||
}
|
||||
return ancestors + "," + parent.getId();
|
||||
}
|
||||
|
||||
private String resolveTenantId() {
|
||||
String tenantId = AuthUtil.getTenantId();
|
||||
if (StringUtils.isBlank(tenantId)) {
|
||||
return BladeConstant.ADMIN_TENANT_ID;
|
||||
}
|
||||
return tenantId;
|
||||
}
|
||||
|
||||
private String getUserDeptKey(UserDept userDept) {
|
||||
if (userDept == null) {
|
||||
return null;
|
||||
}
|
||||
return userDept.getUserId() + userDept.getCompanyCode() + userDept.getDeptCode();
|
||||
}
|
||||
|
||||
/**
|
||||
* 本批人员同步计数
|
||||
*/
|
||||
public static class PersonSyncCount {
|
||||
private final int syncedCount;
|
||||
private final int skippedCount;
|
||||
|
||||
public PersonSyncCount(int syncedCount, int skippedCount) {
|
||||
this.syncedCount = syncedCount;
|
||||
this.skippedCount = skippedCount;
|
||||
}
|
||||
|
||||
public int getSyncedCount() {
|
||||
return syncedCount;
|
||||
}
|
||||
|
||||
public int getSkippedCount() {
|
||||
return skippedCount;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* OA 组织索引
|
||||
*/
|
||||
public static class OaOrgIndex {
|
||||
private final Map<String, Dept> companyByOaId = new HashMap<>();
|
||||
private final Map<String, Dept> deptByOaId = new HashMap<>();
|
||||
private final Map<String, Dept> deptByCompanyAndName = new HashMap<>();
|
||||
|
||||
private Dept findCompany(OAPersonResponse oaPerson) {
|
||||
if (oaPerson == null) {
|
||||
return null;
|
||||
}
|
||||
if (StringUtils.isNotBlank(oaPerson.getSubcompanyid1())) {
|
||||
Dept company = companyByOaId.get(oaPerson.getSubcompanyid1().trim());
|
||||
if (company != null) {
|
||||
return company;
|
||||
}
|
||||
}
|
||||
if (StringUtils.isNotBlank(oaPerson.getSubcompanyname())) {
|
||||
return companyByOaId.get("NAME:" + oaPerson.getSubcompanyname().trim());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private Dept findDept(OAPersonResponse oaPerson) {
|
||||
if (oaPerson == null) {
|
||||
return null;
|
||||
}
|
||||
if (StringUtils.isNotBlank(oaPerson.getDepartmentid())) {
|
||||
Dept department = deptByOaId.get(oaPerson.getDepartmentid().trim());
|
||||
if (department != null) {
|
||||
return department;
|
||||
}
|
||||
}
|
||||
String companyKey = StringUtils.isNotBlank(oaPerson.getSubcompanyid1())
|
||||
? oaPerson.getSubcompanyid1().trim()
|
||||
: (StringUtils.isNotBlank(oaPerson.getSubcompanyname()) ? "NAME:" + oaPerson.getSubcompanyname().trim() : null);
|
||||
if (StringUtils.isNotBlank(companyKey) && StringUtils.isNotBlank(oaPerson.getDepartmentname())) {
|
||||
Dept department = deptByCompanyAndName.get(companyKey + "#" + oaPerson.getDepartmentname());
|
||||
if (department != null) {
|
||||
return department;
|
||||
}
|
||||
return deptByOaId.get(companyKey + ":" + oaPerson.getDepartmentname().trim());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
/**
|
||||
* BladeX Commercial License Agreement
|
||||
* Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
|
||||
* <p>
|
||||
* Use of this software is governed by the Commercial License Agreement
|
||||
* obtained after purchasing a license from BladeX.
|
||||
* <p>
|
||||
* 1. This software is for development use only under a valid license
|
||||
* from BladeX.
|
||||
* <p>
|
||||
* 2. Redistribution of this software's source code to any third party
|
||||
* without a commercial license is strictly prohibited.
|
||||
* <p>
|
||||
* 3. Licensees may copyright their own code but cannot use segments
|
||||
* from this software for such purposes. Copyright of this software
|
||||
* remains with BladeX.
|
||||
* <p>
|
||||
* Using this software signifies agreement to this License, and the software
|
||||
* must not be used for illegal purposes.
|
||||
* <p>
|
||||
* THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
|
||||
* not liable for any claims arising from secondary or illegal development.
|
||||
* <p>
|
||||
* Author: Chill Zhuang (bladejava@qq.com)
|
||||
*/
|
||||
package org.springblade.system.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springblade.core.cache.utils.CacheUtil;
|
||||
import org.springblade.core.log.exception.ServiceException;
|
||||
import org.springblade.core.redis.cache.BladeRedis;
|
||||
import org.springblade.core.secure.utils.AuthUtil;
|
||||
import org.springblade.core.tool.api.R;
|
||||
import org.springblade.core.tool.utils.Func;
|
||||
import org.springblade.core.tool.utils.StringUtil;
|
||||
import org.springblade.resource.feign.ISmsClient;
|
||||
import org.springblade.resource.utils.SmsUtil;
|
||||
import org.springblade.system.pojo.dto.PhoneChangeDTO;
|
||||
import org.springblade.system.pojo.dto.PhoneVerifyDTO;
|
||||
import org.springblade.system.pojo.entity.User;
|
||||
import org.springblade.system.service.IUserPhoneService;
|
||||
import org.springblade.system.service.IUserService;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.springblade.core.cache.constant.CacheConstant.USER_CACHE;
|
||||
|
||||
/**
|
||||
* 用户手机号变更服务实现
|
||||
*
|
||||
* @author Chill
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class UserPhoneServiceImpl implements IUserPhoneService {
|
||||
|
||||
/**
|
||||
* 与登录短信一致,对应后台 /resource/sms 的 smsCode
|
||||
*/
|
||||
private static final String SMS_RESOURCE_CODE = "ali_reg";
|
||||
|
||||
/**
|
||||
* 原手机号已校验凭证(Redis)
|
||||
*/
|
||||
private static final String PHONE_CHANGE_VERIFIED_KEY = "blade:user:phone:change:verified:";
|
||||
|
||||
private static final Duration PHONE_CHANGE_VERIFIED_TTL = Duration.ofMinutes(15);
|
||||
|
||||
private static final Pattern MOBILE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");
|
||||
|
||||
private final IUserService userService;
|
||||
private final ISmsClient smsClient;
|
||||
private final BladeRedis bladeRedis;
|
||||
|
||||
@Override
|
||||
public R sendCode(String phone) {
|
||||
String normalizedPhone = normalizePhone(phone);
|
||||
Long userId = AuthUtil.getUserId();
|
||||
if (Func.isEmpty(userId)) {
|
||||
throw new ServiceException("请先登录");
|
||||
}
|
||||
User currentUser = requireCurrentUser(userId);
|
||||
String tenantId = Func.toStr(currentUser.getTenantId(), AuthUtil.getTenantId());
|
||||
boolean isCurrentPhone = StringUtil.equals(normalizedPhone, Func.toStr(currentUser.getPhone()));
|
||||
if (!isCurrentPhone) {
|
||||
assertPhoneAvailable(tenantId, normalizedPhone, userId);
|
||||
}
|
||||
R result = smsClient.sendValidate(tenantId, SMS_RESOURCE_CODE, normalizedPhone);
|
||||
if (result == null || !result.isSuccess()) {
|
||||
return R.fail(SmsUtil.SEND_FAIL);
|
||||
}
|
||||
return R.data(result.getData(), SmsUtil.SEND_SUCCESS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verifyOldPhone(PhoneVerifyDTO phoneVerify) {
|
||||
Long userId = AuthUtil.getUserId();
|
||||
if (Func.isEmpty(userId)) {
|
||||
throw new ServiceException("请先登录");
|
||||
}
|
||||
String id = Func.toStr(phoneVerify.getId()).trim();
|
||||
String code = Func.toStr(phoneVerify.getCode()).trim();
|
||||
if (StringUtil.isBlank(id) || StringUtil.isBlank(code)) {
|
||||
throw new ServiceException("请先获取并填写验证码");
|
||||
}
|
||||
User currentUser = requireCurrentUser(userId);
|
||||
String oldPhone = Func.toStr(currentUser.getPhone()).trim();
|
||||
if (StringUtil.isBlank(oldPhone)) {
|
||||
throw new ServiceException("当前账号未绑定手机号");
|
||||
}
|
||||
validateSms(currentUser.getTenantId(), id, code, oldPhone);
|
||||
bladeRedis.setEx(PHONE_CHANGE_VERIFIED_KEY + userId, "1", PHONE_CHANGE_VERIFIED_TTL);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean changePhone(PhoneChangeDTO phoneChange) {
|
||||
Long userId = AuthUtil.getUserId();
|
||||
if (Func.isEmpty(userId)) {
|
||||
throw new ServiceException("请先登录");
|
||||
}
|
||||
String verified = Func.toStr(bladeRedis.get(PHONE_CHANGE_VERIFIED_KEY + userId));
|
||||
if (!StringUtil.equals(verified, "1")) {
|
||||
throw new ServiceException("请先完成原手机号验证");
|
||||
}
|
||||
String id = Func.toStr(phoneChange.getId()).trim();
|
||||
String code = Func.toStr(phoneChange.getCode()).trim();
|
||||
String newPhone = normalizePhone(phoneChange.getNewPhone());
|
||||
if (StringUtil.isBlank(id) || StringUtil.isBlank(code)) {
|
||||
throw new ServiceException("请先获取并填写验证码");
|
||||
}
|
||||
User currentUser = requireCurrentUser(userId);
|
||||
String oldPhone = Func.toStr(currentUser.getPhone()).trim();
|
||||
if (StringUtil.equals(newPhone, oldPhone)) {
|
||||
throw new ServiceException("新手机号不可与当前手机号相同");
|
||||
}
|
||||
String tenantId = Func.toStr(currentUser.getTenantId(), AuthUtil.getTenantId());
|
||||
assertPhoneAvailable(tenantId, newPhone, userId);
|
||||
validateSms(tenantId, id, code, newPhone);
|
||||
|
||||
User updateUser = new User();
|
||||
updateUser.setId(userId);
|
||||
updateUser.setPhone(newPhone);
|
||||
// 账号若等于原手机号,同步更新,保证短信登录可用
|
||||
if (StringUtil.isNotBlank(oldPhone) && StringUtil.equals(oldPhone, Func.toStr(currentUser.getAccount()))) {
|
||||
assertAccountAvailable(tenantId, newPhone, userId);
|
||||
updateUser.setAccount(newPhone);
|
||||
}
|
||||
boolean updated = userService.updateById(updateUser);
|
||||
if (!updated) {
|
||||
throw new ServiceException("手机号修改失败");
|
||||
}
|
||||
bladeRedis.del(PHONE_CHANGE_VERIFIED_KEY + userId);
|
||||
CacheUtil.clear(USER_CACHE);
|
||||
return true;
|
||||
}
|
||||
|
||||
private User requireCurrentUser(Long userId) {
|
||||
User user = userService.getById(userId);
|
||||
if (user == null) {
|
||||
throw new ServiceException("用户不存在");
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
private void validateSms(String tenantId, String id, String value, String phone) {
|
||||
R result = smsClient.validateMessage(tenantId, SMS_RESOURCE_CODE, id, value, phone);
|
||||
if (result == null || !result.isSuccess()) {
|
||||
throw new ServiceException(SmsUtil.VALIDATE_FAIL);
|
||||
}
|
||||
}
|
||||
|
||||
private void assertPhoneAvailable(String tenantId, String phone, Long excludeUserId) {
|
||||
Long phoneCount = userService.count(
|
||||
Wrappers.<User>lambdaQuery()
|
||||
.eq(User::getTenantId, tenantId)
|
||||
.eq(User::getPhone, phone)
|
||||
.ne(User::getId, excludeUserId)
|
||||
);
|
||||
if (phoneCount != null && phoneCount > 0L) {
|
||||
throw new ServiceException(StringUtil.format("当前手机 [{}] 已存在!", phone));
|
||||
}
|
||||
}
|
||||
|
||||
private void assertAccountAvailable(String tenantId, String account, Long excludeUserId) {
|
||||
Long accountCount = userService.count(
|
||||
Wrappers.<User>lambdaQuery()
|
||||
.eq(User::getTenantId, tenantId)
|
||||
.eq(User::getAccount, account)
|
||||
.ne(User::getId, excludeUserId)
|
||||
);
|
||||
if (accountCount != null && accountCount > 0L) {
|
||||
throw new ServiceException(StringUtil.format("当前用户 [{}] 已存在!", account));
|
||||
}
|
||||
}
|
||||
|
||||
private String normalizePhone(String phone) {
|
||||
String normalizedPhone = Func.toStr(phone).trim();
|
||||
if (!MOBILE_PATTERN.matcher(normalizedPhone).matches()) {
|
||||
throw new ServiceException("手机号格式不正确");
|
||||
}
|
||||
return normalizedPhone;
|
||||
}
|
||||
|
||||
}
|
||||
+40
@@ -529,6 +529,46 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implement
|
||||
return userInfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean bindWxMiniOpenId(String tenantId, Long userId, String openid, String phone) {
|
||||
if (Func.isBlank(tenantId) || Func.isEmpty(userId) || Func.isBlank(openid)) {
|
||||
throw new ServiceException("绑定微信 openid 参数不完整");
|
||||
}
|
||||
String source = "WECHAT_MINI";
|
||||
UserOauth byOpenId = userOauthService.getOne(Wrappers.<UserOauth>lambdaQuery()
|
||||
.eq(UserOauth::getTenantId, tenantId)
|
||||
.eq(UserOauth::getSource, source)
|
||||
.eq(UserOauth::getUuid, openid)
|
||||
.last("LIMIT 1"));
|
||||
if (byOpenId != null) {
|
||||
byOpenId.setUserId(userId);
|
||||
if (Func.isNotBlank(phone)) {
|
||||
byOpenId.setUsername(phone);
|
||||
}
|
||||
return userOauthService.updateById(byOpenId);
|
||||
}
|
||||
UserOauth byUser = userOauthService.getOne(Wrappers.<UserOauth>lambdaQuery()
|
||||
.eq(UserOauth::getTenantId, tenantId)
|
||||
.eq(UserOauth::getSource, source)
|
||||
.eq(UserOauth::getUserId, userId)
|
||||
.last("LIMIT 1"));
|
||||
if (byUser != null) {
|
||||
byUser.setUuid(openid);
|
||||
if (Func.isNotBlank(phone)) {
|
||||
byUser.setUsername(phone);
|
||||
}
|
||||
return userOauthService.updateById(byUser);
|
||||
}
|
||||
UserOauth oauth = new UserOauth();
|
||||
oauth.setTenantId(tenantId);
|
||||
oauth.setUserId(userId);
|
||||
oauth.setUuid(openid);
|
||||
oauth.setUsername(Func.toStr(phone, ""));
|
||||
oauth.setSource(source);
|
||||
return userOauthService.save(oauth);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean grant(String userIds, String roleIds) {
|
||||
|
||||
Reference in New Issue
Block a user