Merge branch 'master' into feature/payment-apply-bfi-sync

# Conflicts:
#	blade-service/blade-transport/src/main/java/org/springblade/transport/service/impl/CustomerArchiveServiceImpl.java
This commit is contained in:
刘泉佳
2026-10-14 14:24:27 +08:00
205 changed files with 17746 additions and 907 deletions
@@ -93,7 +93,8 @@ public class DeptController extends BladeController {
@PreAuth(menu = "dept")
@GetMapping("/list")
@Parameters({
@Parameter(name = "deptName", description = "部门名称", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
@Parameter(name = "deptName", description = "组织名称", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
@Parameter(name = "shortName", description = "组织简称", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
@Parameter(name = "fullName", description = "部门全称", in = ParameterIn.QUERY, schema = @Schema(type = "string"))
})
@ApiOperationSupport(order = 2)
@@ -108,7 +109,8 @@ public class DeptController extends BladeController {
@PreAuth(menu = "dept")
@GetMapping("/lazy-list")
@Parameters({
@Parameter(name = "deptName", description = "部门名称", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
@Parameter(name = "deptName", description = "组织名称", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
@Parameter(name = "shortName", description = "组织简称", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
@Parameter(name = "fullName", description = "部门全称", in = ParameterIn.QUERY, schema = @Schema(type = "string"))
})
@ApiOperationSupport(order = 3)
@@ -195,8 +197,10 @@ public class DeptController extends BladeController {
@Operation(summary = "同步OA公司")
public R<OaOrgSyncPageVO> syncOaCompany(
@RequestParam(defaultValue = "1") Integer current,
@RequestParam(defaultValue = "20") Integer size) {
return R.data(oaSyncService.syncCompanyPage(current, size));
@RequestParam(defaultValue = "20") Integer size,
@RequestParam(defaultValue = "false") Boolean incremental,
@RequestParam(required = false) String modifiedSince) {
return R.data(oaSyncService.syncCompanyPage(current, size, Boolean.TRUE.equals(incremental), modifiedSince));
}
/**
@@ -208,8 +212,10 @@ public class DeptController extends BladeController {
@Operation(summary = "同步OA部门")
public R<OaOrgSyncPageVO> syncOaDepartment(
@RequestParam(defaultValue = "1") Integer current,
@RequestParam(defaultValue = "20") Integer size) {
return R.data(oaSyncService.syncDepartmentPage(current, size));
@RequestParam(defaultValue = "20") Integer size,
@RequestParam(defaultValue = "false") Boolean incremental,
@RequestParam(required = false) String modifiedSince) {
return R.data(oaSyncService.syncDepartmentPage(current, size, Boolean.TRUE.equals(incremental), modifiedSince));
}
/**
@@ -0,0 +1,134 @@
/**
* 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>
* Author: Chill Zhuang (bladejava@qq.com)
*/
package org.springblade.system.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.annotation.PreAuth;
import org.springblade.core.tenant.annotation.NonDS;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.system.pojo.entity.MpUser;
import org.springblade.system.pojo.vo.MpUserVO;
import org.springblade.system.service.IMpUserService;
import org.springblade.system.wrapper.MpUserWrapper;
import org.springframework.web.bind.annotation.GetMapping;
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;
import java.util.Map;
/**
* 小程序用户管理 控制器
*
* @author Chill
*/
@NonDS
@RestController
@AllArgsConstructor
@PreAuth(menu = "mp_user")
@RequestMapping("mp-user")
@Tag(name = "小程序用户", description = "小程序用户管理")
public class MpUserController extends BladeController {
private final IMpUserService mpUserService;
/**
* 详情
*/
@GetMapping("/detail")
@ApiOperationSupport(order = 1)
@Operation(summary = "详情", description = "传入id")
public R<MpUserVO> detail(MpUser mpUser) {
MpUser detail = mpUserService.getOne(Condition.getQueryWrapper(mpUser));
if (detail == null) {
return R.fail("小程序用户不存在");
}
return R.data(MpUserWrapper.build().entityVO(detail));
}
/**
* 分页
*/
@GetMapping("/list")
@ApiOperationSupport(order = 2)
@Operation(summary = "分页", description = "传入查询条件")
public R<IPage<MpUserVO>> list(MpUser mpUser, Query query) {
IPage<MpUser> pages = mpUserService.selectMpUserPage(Condition.getPage(query), mpUser);
return R.data(MpUserWrapper.build().pageVO(pages));
}
/**
* 新增或修改
*/
@PostMapping("/submit")
@ApiOperationSupport(order = 3)
@Operation(summary = "新增或修改", description = "传入MpUser")
public R submit(@Valid @RequestBody MpUser mpUser) {
return R.status(mpUserService.submitOrUpdate(mpUser));
}
/**
* 逻辑删除
*/
@PostMapping("/remove")
@ApiOperationSupport(order = 4)
@Operation(summary = "逻辑删除", description = "传入ids")
public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
return R.status(mpUserService.removeMpUser(Func.toLongList(ids)));
}
/**
* 启用 / 停用
*/
@PostMapping("/change-status")
@ApiOperationSupport(order = 5)
@Operation(summary = "修改状态", description = "status:1启用,0停用")
public R changeStatus(@Parameter(description = "用户主键", required = true) @RequestParam Long id,
@Parameter(description = "状态:1启用,0停用", required = true) @RequestParam Integer status) {
return R.status(mpUserService.changeStatus(id, status));
}
/**
* 重置密码
*/
@PostMapping("/reset-password")
@ApiOperationSupport(order = 6)
@Operation(summary = "重置密码", description = "传入userId集合,返回账号与明文密码")
public R<Map<String, String>> resetPassword(
@Parameter(description = "userId集合", required = true) @RequestParam String userIds) {
return R.data(mpUserService.resetPassword(Func.toLongList(userIds)));
}
}
@@ -53,11 +53,14 @@ import org.springblade.core.tool.utils.DateUtil;
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.MpUser;
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.IMpUserService;
import org.springblade.system.service.IUserService;
import org.springblade.system.utils.MpUserAuth;
import org.springblade.system.wrapper.UserWrapper;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@@ -79,6 +82,7 @@ import java.util.Map;
public class UserController {
private final IUserService userService;
private final IMpUserService mpUserService;
private final IOASyncService oaSyncService;
/**
@@ -101,6 +105,10 @@ public class UserController {
@Operation(summary = "查看详情", description = "传入id")
@GetMapping("/info")
public R<UserVO> info(BladeUser user) {
if (MpUserAuth.isMpUser(user)) {
MpUser mpUser = mpUserService.getById(user.getUserId());
return R.data(toMpUserVO(mpUser));
}
User detail = userService.getById(user.getUserId());
return R.data(UserWrapper.build().entityVO(detail));
}
@@ -112,11 +120,12 @@ public class UserController {
@GetMapping("/list")
@BladeView(Views.Admin.class)
@Parameters({
@Parameter(name = "account", description = "账号名", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
@Parameter(name = "realName", description = "姓名", in = ParameterIn.QUERY, schema = @Schema(type = "string"))
@Parameter(name = "account", description = "账号名(模糊)", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
@Parameter(name = "realName", description = "姓名(模糊)", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
@Parameter(name = "phone", description = "手机号(模糊)", in = ParameterIn.QUERY, schema = @Schema(type = "string"))
})
@ApiOperationSupport(order = 3)
@Operation(summary = "列表", description = "传入account和realName")
@Operation(summary = "列表", description = "传入account、realName、phone,支持模糊搜索")
public R<IPage<UserVO>> list(@Parameter(hidden = true) @RequestParam Map<String, Object> user, Query query) {
return R.data(userService.selectPage(user, query));
}
@@ -128,11 +137,12 @@ public class UserController {
@GetMapping("/page")
@BladeView(Views.Admin.class)
@Parameters({
@Parameter(name = "account", description = "账号名", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
@Parameter(name = "realName", description = "姓名", in = ParameterIn.QUERY, schema = @Schema(type = "string"))
@Parameter(name = "account", description = "账号名(模糊)", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
@Parameter(name = "realName", description = "姓名(模糊)", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
@Parameter(name = "phone", description = "手机号(模糊)", in = ParameterIn.QUERY, schema = @Schema(type = "string"))
})
@ApiOperationSupport(order = 4)
@Operation(summary = "列表", description = "传入account和realName")
@Operation(summary = "列表", description = "传入account、realName、phone,支持模糊搜索")
public R<IPage<UserVO>> page(@Parameter(hidden = true) User user, Query query, Long deptId, BladeUser bladeUser) {
IPage<User> pages = userService.selectUserPage(Condition.getPage(query), user, deptId, (AuthUtil.isAdministrator() ? StringPool.EMPTY : bladeUser.getTenantId()));
return R.data(UserWrapper.build().pageVO(pages));
@@ -169,8 +179,10 @@ public class UserController {
@Operation(summary = "同步OA人员")
public R<OaPersonSyncPageVO> syncIamAccounts(
@RequestParam(defaultValue = "1") Integer current,
@RequestParam(defaultValue = "20") Integer size) {
return R.data(oaSyncService.syncPersonFromUserList(current, size));
@RequestParam(defaultValue = "20") Integer size,
@RequestParam(defaultValue = "false") Boolean incremental,
@RequestParam(required = false) String modifiedSince) {
return R.data(oaSyncService.syncPersonFromUserList(current, size, Boolean.TRUE.equals(incremental), modifiedSince));
}
/**
@@ -184,6 +196,18 @@ public class UserController {
return R.status(userService.updateUser(user));
}
/**
* 启用或停用
*/
@IsAdmin
@PostMapping("/change-status")
@ApiOperationSupport(order = 6)
@Operation(summary = "启用停用", description = "传入id和status")
public R changeStatus(@Parameter(description = "用户主键", required = true) @RequestParam Long id,
@Parameter(description = "状态:1启用,0停用", required = true) @RequestParam Integer status) {
return R.status(userService.changeUserStatus(id, status));
}
/**
* 删除
*/
@@ -236,6 +260,7 @@ public class UserController {
* 当前用户设置/重置登录密码(小程序首次设密、短信验证后改密)
* <p>
* 对外路径:/blade-system/user/password ;网关别名 /blade-user/password 亦可到达。
* 小程序用户写入 blade_mp_user,系统用户仍写入 blade_user。
*/
@PostMapping("/password")
@ApiOperationSupport(order = 10)
@@ -243,6 +268,9 @@ public class UserController {
public R password(BladeUser user,
@Parameter(description = "新密码", required = true) @RequestParam String password,
@Parameter(description = "确认密码", required = true) @RequestParam String password2) {
if (MpUserAuth.isMpUser(user)) {
return R.status(mpUserService.setPassword(user.getUserId(), password, password2));
}
return R.status(userService.setPassword(user.getUserId(), password, password2));
}
@@ -422,4 +450,34 @@ public class UserController {
return R.data(list);
}
/**
* 小程序用户转 UserVO(兼容原 /user/info 响应结构)
*/
private UserVO toMpUserVO(MpUser mpUser) {
if (mpUser == null) {
return null;
}
UserVO userVO = new UserVO();
userVO.setId(mpUser.getId());
userVO.setTenantId(mpUser.getTenantId());
userVO.setCode(mpUser.getCode());
userVO.setAccount(mpUser.getAccount());
userVO.setName(mpUser.getName());
userVO.setRealName(mpUser.getRealName());
userVO.setAvatar(mpUser.getAvatar());
userVO.setEmail(mpUser.getEmail());
userVO.setPhone(mpUser.getPhone());
userVO.setBirthday(mpUser.getBirthday());
userVO.setSex(mpUser.getSex());
userVO.setDeptId(mpUser.getDeptId());
userVO.setPostId(mpUser.getPostId());
userVO.setRemark(mpUser.getRemark());
userVO.setStatus(mpUser.getStatus());
userVO.setCreateTime(mpUser.getCreateTime());
userVO.setUpdateTime(mpUser.getUpdateTime());
// 身份放入 roleName,便于前端兼容展示
userVO.setRoleName(mpUser.getIdentities());
return userVO;
}
}
@@ -43,7 +43,7 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* 用户手机号变更(小程序「修改手机号」)
* 小程序用户手机号变更(写入 blade_mp_user)
* <p>
* 对外路径:/blade-system/user/phone/** ;网关别名 /blade-user/phone/** 亦可到达。
*
@@ -44,92 +44,79 @@ public interface DeptConvert {
@Mapping(source = "subcompanyname", target = "deptName")
@Mapping(source = "subcompanydesc", target = "fullName")
// 父公司id转为父部门编码,要拼接前缀
@Mapping(source = "supsubcomid", target = "parentCode")
@Mapping(source = "created", target = "createTime", dateFormat = "yyyy-MM-dd HH:mm:ss")
@Mapping(source = "modified", target = "updateTime", dateFormat = "yyyy-MM-dd HH:mm:ss")
@Mapping(source = "modified", target = "oaModified")
Dept baseConvert(OACompanyResponse company);
@Mapping(source = "departmentname", target = "deptName")
@Mapping(source = "departmentmark", target = "fullName")
// 父部门id转为父部门编码,要拼接前缀
@Mapping(source = "supdepid", target = "parentCode")
// 所属子公司id转为所属公司编码,要拼接前缀
@Mapping(source = "subcompanyid1", target = "belongCompanyCode")
@Mapping(source = "created", target = "createTime", dateFormat = "yyyy-MM-dd HH:mm:ss")
@Mapping(source = "modified", target = "updateTime", dateFormat = "yyyy-MM-dd HH:mm:ss")
@Mapping(source = "modified", target = "oaModified")
Dept baseConvert(OADepartmentResponse department);
/**
* oa公司转本系统部门
* @param company
* @return
* oa公司转本系统部门。组织编码由同步服务按 GWWL+三位数字 统一分配。
*/
default Dept company2dept(OACompanyResponse company) {
Dept dept = this.baseConvert(company);
// 部门编码添加前缀
dept.setDeptCode(OAConvertConstant.COMPANY_OA_PREFIX + company.getId());
// 编码稍后按规则生成;此处仅落 OA 主键,供按 oaId 匹配与重建层级
dept.setDeptCode(null);
String parentCode = dept.getParentCode();
if (!OAConstant.ROOT_COMPANY_ID.equals(parentCode)) {
// 父部门编码不是0,拼接前缀
dept.setParentCode(OAConvertConstant.COMPANY_OA_PREFIX + parentCode);
// 父部门id后续处理
// 非顶级:parentCode 暂存上级 OA 主键,分配编码后再替换为正式组织编码
dept.setParentCode(parentCode);
dept.setParentId(null);
} else {
// 父部门编码是0,父id也设置为0
dept.setParentId(OAConvertConstant.ROOT_PARENT_ID);
dept.setParentCode(OAConvertConstant.OA_SYNC_ROOT_DEPT_CODE);
dept.setParentId(OAConvertConstant.OA_SYNC_ROOT_DEPT_ID);
}
// 公司所属公司编码就是他自己的部门编码
dept.setBelongCompanyCode(dept.getDeptCode());
// OA主键与上级OA主键,分批同步结束后用于重建层级
dept.setBelongCompanyCode(null);
dept.setOaId(company.getId());
dept.setOaSupSubComId(company.getSupsubcomid());
// 显示顺序处理
dept.setSort(OAUtils.parseInt(company.getShoworder()));
// 部门类型,公司
dept.setDeptCategory(DeptCategory.COMPANY.getCode());
dept.setSyncTime(new Date());
// 是oa的
dept.setIsOa(CommonConstant.YES);
return dept;
}
/**
* oa部门转本系统部门
* @param oaDept
* @param companyDeptMap 所有公司的部门编码与id map
* @return
* oa部门转本系统部门。组织编码由同步服务按「所属公司编码+三位数字」统一分配。
*
* @param oaDept OA部门
* @param companyByOaId 已同步公司(oaId → 本地公司)
*/
default Dept dept2dept(OADepartmentResponse oaDept, Map<String, Long> companyDeptMap) {
default Dept dept2dept(OADepartmentResponse oaDept, Map<String, Dept> companyByOaId) {
Dept dept = this.baseConvert(oaDept);
// 部门编码添加前缀
dept.setDeptCode(OAConvertConstant.DEPARTMENT_OA_PREFIX + oaDept.getId());
// OA主键;上级为根部门时记录所属公司OA主键,否则记录上级部门OA主键
dept.setDeptCode(null);
dept.setOaId(oaDept.getId());
if (OAConstant.ROOT_COMPANY_ID.equals(oaDept.getSupdepid())) {
dept.setOaSupSubComId(oaDept.getSubcompanyid1());
} else {
dept.setOaSupSubComId(oaDept.getSupdepid());
}
// 部门所属公司编码就是他所属公司编码加前缀
dept.setBelongCompanyCode(OAConvertConstant.COMPANY_OA_PREFIX + dept.getBelongCompanyCode());
String parentCode = dept.getParentCode();
if (!OAConstant.ROOT_COMPANY_ID.equals(parentCode)) {
// 父部门编码不是0,拼接前缀
dept.setParentCode(OAConvertConstant.DEPARTMENT_OA_PREFIX + parentCode);
// 父部门id后续处理
Dept belongCompany = companyByOaId == null ? null : companyByOaId.get(oaDept.getSubcompanyid1());
if (belongCompany != null) {
dept.setBelongCompanyCode(belongCompany.getDeptCode());
dept.setParentId(null);
if (OAConstant.ROOT_COMPANY_ID.equals(oaDept.getSupdepid())) {
dept.setParentCode(belongCompany.getDeptCode());
dept.setParentId(belongCompany.getId());
} else {
// 上级为部门:parentCode 暂存上级部门 OA 主键,重建层级时再解析
dept.setParentCode(oaDept.getSupdepid());
}
} else {
// 父部门编码是0,设置为公司编码
dept.setParentCode(dept.getBelongCompanyCode());
// 根据父部门编码获取对应的id
dept.setParentId(companyDeptMap.get(dept.getParentCode()));
// 所属公司尚未解析时,暂存 OA 公司主键,后续补齐正式编码
dept.setBelongCompanyCode(oaDept.getSubcompanyid1());
dept.setParentCode(oaDept.getSupdepid());
}
// 显示顺序处理
dept.setSort(OAUtils.parseInt(oaDept.getShoworder()));
// 部门类型,部门
dept.setDeptCategory(DeptCategory.DEPT.getCode());
dept.setSyncTime(new Date());
// 是oa的
dept.setIsOa(CommonConstant.YES);
return dept;
}
@@ -70,6 +70,7 @@ public interface UserConvert {
@Mapping(source = "lastname", target = "realName")
@Mapping(source = "mobile", target = "phone")
@Mapping(source = "email", target = "email")
@Mapping(source = "modified", target = "oaModified")
User baseConvert(OAPersonResponse person);
@Mapping(source = "subcompanyname", target = "companyName")
@@ -54,7 +54,7 @@ public class RailwayStationExcel implements Serializable {
@ExcelProperty("TMIS国标编码*")
private String tmisCode;
@ExcelProperty("电报略码*")
@ExcelProperty("电报略码")
private String telegraphCode;
@ExcelProperty("车站名称*")
@@ -56,7 +56,7 @@ public class RailwayStationExportExcel implements Serializable {
@ExcelProperty("TMIS国标编码*")
private String tmisCode;
@ExcelProperty("电报略码*")
@ExcelProperty("电报略码")
private String telegraphCode;
@ExcelProperty("车站名称*")
@@ -0,0 +1,110 @@
/**
* 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>
* Author: Chill Zhuang (bladejava@qq.com)
*/
package org.springblade.system.feign;
import io.swagger.v3.oas.annotations.Hidden;
import lombok.AllArgsConstructor;
import org.springblade.core.tenant.annotation.NonDS;
import org.springblade.core.tool.api.R;
import org.springblade.system.pojo.entity.MpUser;
import org.springblade.system.pojo.entity.MpUserInfo;
import org.springblade.system.service.IMpUserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
/**
* 小程序用户 Feign 实现类
*
* @author Chill
*/
@NonDS
@Hidden
@RestController
@AllArgsConstructor
public class MpUserClient implements IMpUserClient {
private final IMpUserService mpUserService;
@Override
@GetMapping(USER_BY_ID)
public R<MpUser> userById(Long userId) {
return R.data(mpUserService.getById(userId));
}
@Override
@GetMapping(USER_BY_PHONE)
public R<MpUser> userByPhone(String tenantId, String phone) {
return R.data(mpUserService.getByPhone(tenantId, phone));
}
@Override
@GetMapping(USER_BY_ACCOUNT)
public R<MpUser> userByAccount(String tenantId, String account) {
return R.data(mpUserService.getByAccount(tenantId, account));
}
@Override
@GetMapping(USER_INFO_BY_ID)
public R<MpUserInfo> userInfoById(Long userId) {
return R.data(mpUserService.userInfo(userId));
}
@Override
@GetMapping(USER_INFO_BY_PHONE)
public R<MpUserInfo> userInfoByPhone(String tenantId, String phone) {
return R.data(mpUserService.userInfoByPhone(tenantId, phone));
}
@Override
@GetMapping(USER_INFO_BY_ACCOUNT)
public R<MpUserInfo> userInfoByAccount(String tenantId, String account) {
return R.data(mpUserService.userInfoByAccount(tenantId, account));
}
@Override
@PostMapping(SAVE_USER)
public R<Boolean> saveUser(@RequestBody MpUser user) {
return R.data(mpUserService.submit(user));
}
@Override
@PostMapping(UPDATE_USER)
public R<Boolean> updateUser(@RequestBody MpUser user) {
return R.data(mpUserService.updateUser(user));
}
@Override
@PostMapping(BIND_OPENID)
public R<Boolean> bindOpenId(String tenantId, Long userId, String openid) {
return R.data(mpUserService.bindOpenId(tenantId, userId, openid));
}
@Override
@PostMapping(SET_PASSWORD)
public R<Boolean> setPassword(Long userId, String password, String password2) {
return R.data(mpUserService.setPassword(userId, password, password2));
}
}
@@ -13,6 +13,7 @@
<result column="dept_category" property="deptCategory"/>
<result column="dept_code" property="deptCode"/>
<result column="kingdee_dept_code" property="kingdeeDeptCode"/>
<result column="contract_code_prefix" property="contractCodePrefix"/>
<result column="short_name" property="shortName"/>
<result column="pinyin_mnemonic" property="pinyinMnemonic"/>
<result column="mnemonic_code" property="mnemonicCode"/>
@@ -34,6 +35,7 @@
<result column="dept_category" property="deptCategory"/>
<result column="dept_code" property="deptCode"/>
<result column="kingdee_dept_code" property="kingdeeDeptCode"/>
<result column="contract_code_prefix" property="contractCodePrefix"/>
<result column="short_name" property="shortName"/>
<result column="pinyin_mnemonic" property="pinyinMnemonic"/>
<result column="mnemonic_code" property="mnemonicCode"/>
@@ -78,6 +80,9 @@
<if test="param3.deptName!=null and param3.deptName!=''">
and dept.dept_name like concat(concat('%', #{param3.deptName}),'%')
</if>
<if test="param3.shortName!=null and param3.shortName!=''">
and dept.short_name like concat(concat('%', #{param3.shortName}),'%')
</if>
<if test="param3.fullName!=null and param3.fullName!=''">
and dept.full_name like concat(concat('%', #{param3.fullName}),'%')
</if>
@@ -0,0 +1,34 @@
/**
* 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>
* Author: Chill Zhuang (bladejava@qq.com)
*/
package org.springblade.system.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springblade.system.pojo.entity.MpUser;
/**
* 小程序用户 Mapper
*
* @author Chill
*/
public interface MpUserMapper extends BaseMapper<MpUser> {
}
@@ -45,6 +45,11 @@ public interface RailwayStationMapper extends BaseMapper<RailwayStation> {
*/
RailwayStation selectByCodeIncludingDeleted(@Param("code") String code);
/**
* 按 TMIS 国标编码查询铁路车站(包含逻辑删除记录,用于导入恢复)。
*/
RailwayStation selectByTmisCodeIncludingDeleted(@Param("tmisCode") String tmisCode);
/**
* 恢复逻辑删除铁路车站。
*/
@@ -36,6 +36,14 @@
SELECT *
FROM blade_railway_station
WHERE code = #{code}
LIMIT 1
</select>
<select id="selectByTmisCodeIncludingDeleted" resultType="org.springblade.system.pojo.entity.RailwayStation">
SELECT *
FROM blade_railway_station
WHERE tmis_code = #{tmisCode}
LIMIT 1
</select>
<update id="restoreById">
@@ -44,13 +44,16 @@
and bu.tenant_id = #{user.tenantId}
</if>
<if test="user.account!=null and user.account != ''">
and bu.account = #{user.account}
and bu.account like concat('%', #{user.account}, '%')
</if>
<if test="user.realName!=null and user.realName != ''">
and bu.real_name = #{user.realName}
and (
bu.real_name like concat('%', #{user.realName}, '%')
or bu.name like concat('%', #{user.realName}, '%')
)
</if>
<if test="user.phone!=null and user.phone != ''">
and bu.phone = #{user.phone}
and bu.phone like concat('%', #{user.phone}, '%')
</if>
<if test="user.userType!=null and user.userType != ''">
and bu.user_type = #{user.userType}
@@ -30,6 +30,7 @@ import org.springblade.core.literule.core.RuleComponent;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.system.pojo.entity.Dept;
import org.springblade.system.pojo.entity.Tenant;
import org.springblade.system.pojo.enums.DeptCategory;
import org.springblade.system.rule.context.TenantContext;
import static org.springblade.system.rule.constant.TenantRuleConstant.TENANT_DEPT_RULE;
@@ -54,7 +55,7 @@ public class TenantDeptRule extends RuleComponent {
dept.setAncestors(String.valueOf(BladeConstant.TOP_PARENT_ID));
dept.setDeptName(tenant.getTenantName());
dept.setFullName(tenant.getTenantName());
dept.setDeptCategory(1);
dept.setDeptCategory(DeptCategory.GROUP.getCode());
dept.setSort(2);
dept.setIsDeleted(BladeConstant.DB_NOT_DELETED);
@@ -149,12 +149,19 @@ public interface IDeptService extends IService<Dept> {
boolean removeDept(String ids);
/**
* 删除非顶级组织,顶级组织(父级为 0)保留
* 清除非保留顶级外的组织;保留 id=135 集团锚点,以及名称为「外部组织」的顶级
*
* @return 删除数量
*/
int clearNonTopDepts();
/**
* 确保双顶级:id=135 集团(编码 GWWL)+ 独立「外部组织」顶级
*
* @return 集团顶级组织(id=135)
*/
Dept ensureOaSyncRootDept();
/**
* 新增或修改部门
* <p>
@@ -0,0 +1,110 @@
/**
* 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>
* Author: Chill Zhuang (bladejava@qq.com)
*/
package org.springblade.system.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.core.mp.base.BaseService;
import org.springblade.system.pojo.entity.MpUser;
import org.springblade.system.pojo.entity.MpUserInfo;
import java.util.List;
import java.util.Map;
/**
* 小程序用户 服务类
*
* @author Chill
*/
public interface IMpUserService extends BaseService<MpUser> {
/**
* 按租户 + 手机号查询
*/
MpUser getByPhone(String tenantId, String phone);
/**
* 按租户 + 账号查询
*/
MpUser getByAccount(String tenantId, String account);
/**
* 按主键组装登录信息
*/
MpUserInfo userInfo(Long userId);
/**
* 按租户 + 手机号组装登录信息
*/
MpUserInfo userInfoByPhone(String tenantId, String phone);
/**
* 按租户 + 账号组装登录信息
*/
MpUserInfo userInfoByAccount(String tenantId, String account);
/**
* 后台分页查询
*/
IPage<MpUser> selectMpUserPage(IPage<MpUser> page, MpUser query);
/**
* 保存小程序用户
*/
boolean submit(MpUser user);
/**
* 更新小程序用户
*/
boolean updateUser(MpUser user);
/**
* 新增或修改(后台管理)
*/
boolean submitOrUpdate(MpUser user);
/**
* 逻辑删除
*/
boolean removeMpUser(List<Long> ids);
/**
* 启用 / 停用
*/
boolean changeStatus(Long id, Integer status);
/**
* 重置密码为随机密码,返回 account -> 明文密码
*/
Map<String, String> resetPassword(List<Long> userIds);
/**
* 绑定/更新 openid
*/
boolean bindOpenId(String tenantId, Long userId, String openid);
/**
* 当前小程序用户设置密码
*/
boolean setPassword(Long userId, String password, String password2);
}
@@ -32,27 +32,33 @@ public interface IOASyncService {
/**
* 按页从 OA 人员接口同步组织与人员
*
* @param current 当前页,从 1 开始
* @param size 每页条数
* @param current 当前页,从 1 开始
* @param size 每页条数
* @param incremental 是否增量同步(按本地最大 oaModified 过滤 OA)
* @param modifiedSince 增量起始时间;首屏可空,后续分页回传首屏返回值
* @return 本页同步结果
*/
OaPersonSyncPageVO syncPersonFromUserList(int current, int size);
OaPersonSyncPageVO syncPersonFromUserList(int current, int size, boolean incremental, String modifiedSince);
/**
* 按页从 OA 公司接口同步公司
*
* @param current 当前页,从 1 开始
* @param size 每页条数
* @param current 当前页,从 1 开始
* @param size 每页条数
* @param incremental 是否增量同步(按本地最大 oaModified 过滤 OA)
* @param modifiedSince 增量起始时间;首屏可空,后续分页回传首屏返回值
* @return 本页同步结果
*/
OaOrgSyncPageVO syncCompanyPage(int current, int size);
OaOrgSyncPageVO syncCompanyPage(int current, int size, boolean incremental, String modifiedSince);
/**
* 按页从 OA 部门接口同步部门;最后一页完成后更新祖级列表
*
* @param current 当前页,从 1 开始
* @param size 每页条数
* @param current 当前页,从 1 开始
* @param size 每页条数
* @param incremental 是否增量同步(按本地最大 oaModified 过滤 OA)
* @param modifiedSince 增量起始时间;首屏可空,后续分页回传首屏返回值
* @return 本页同步结果
*/
OaOrgSyncPageVO syncDepartmentPage(int current, int size);
OaOrgSyncPageVO syncDepartmentPage(int current, int size, boolean incremental, String modifiedSince);
}
@@ -93,6 +93,15 @@ public interface IUserService extends BaseService<User> {
*/
boolean updateUser(User user);
/**
* 启用或停用用户(租户守卫校验用户归属,仅更新状态)
*
* @param userId 用户主键
* @param status 状态:1 启用,0 停用
* @return 是否成功
*/
boolean changeUserStatus(Long userId, Integer status);
/**
* 修改用户基本信息(仅限当前登录用户自身,忽略角色 / 部门 / 岗位 / 账号等敏感字段)
*
@@ -27,6 +27,7 @@ package org.springblade.system.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
@@ -389,16 +390,193 @@ public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements ID
@Override
@Transactional(rollbackFor = Exception.class)
public int clearNonTopDepts() {
Long nonTopCount = this.count(Wrappers.<Dept>lambdaQuery()
.isNotNull(Dept::getParentId)
.ne(Dept::getParentId, BladeConstant.TOP_PARENT_ID));
if (nonTopCount == null || nonTopCount == 0L) {
// 同步前清理:保留集团锚点 id=135,以及「外部组织」顶级;其余删除
Dept groupRoot = this.ensureOaSyncRootDept();
Dept externalRoot = this.ensureExternalOrgTopDept();
Set<Long> keepIds = new HashSet<>();
if (groupRoot != null && groupRoot.getId() != null) {
keepIds.add(groupRoot.getId());
}
if (externalRoot != null && externalRoot.getId() != null) {
keepIds.add(externalRoot.getId());
}
if (keepIds.isEmpty()) {
return 0;
}
this.remove(Wrappers.<Dept>lambdaQuery()
.isNotNull(Dept::getParentId)
.ne(Dept::getParentId, BladeConstant.TOP_PARENT_ID));
return nonTopCount.intValue();
Long clearCount = this.count(Wrappers.<Dept>lambdaQuery().notIn(Dept::getId, keepIds));
if (clearCount == null || clearCount == 0L) {
return 0;
}
this.remove(Wrappers.<Dept>lambdaQuery().notIn(Dept::getId, keepIds));
return clearCount.intValue();
}
@Override
@Transactional(rollbackFor = Exception.class)
public Dept ensureOaSyncRootDept() {
this.migrateLegacyOaDeptCategory();
this.removeLegacyOaSyncRoots();
Dept rootDept = this.getById(OAConvertConstant.OA_SYNC_ROOT_DEPT_ID);
String tenantId = AuthUtil.getTenantId();
if (StringUtil.isBlank(tenantId)) {
tenantId = BladeConstant.ADMIN_TENANT_ID;
}
if (rootDept == null) {
rootDept = new Dept();
rootDept.setId(OAConvertConstant.OA_SYNC_ROOT_DEPT_ID);
rootDept.setTenantId(tenantId);
rootDept.setParentId(BladeConstant.TOP_PARENT_ID);
rootDept.setAncestors(String.valueOf(BladeConstant.TOP_PARENT_ID));
rootDept.setDeptName(OAConvertConstant.OA_SYNC_ROOT_DEPT_NAME);
rootDept.setFullName(OAConvertConstant.OA_SYNC_ROOT_DEPT_NAME);
rootDept.setShortName(OAConvertConstant.OA_SYNC_ROOT_DEPT_NAME);
rootDept.setDeptCode(OAConvertConstant.OA_SYNC_ROOT_DEPT_CODE);
rootDept.setParentCode(String.valueOf(BladeConstant.TOP_PARENT_ID));
rootDept.setBelongCompanyCode(OAConvertConstant.OA_SYNC_ROOT_DEPT_CODE);
rootDept.setDeptCategory(DeptCategory.GROUP.getCode());
rootDept.setSort(0);
rootDept.setStatus(DataStatusEnum.ENABLE.getCode());
rootDept.setIsDeleted(BladeConstant.DB_NOT_DELETED);
rootDept.setIsOa(0);
rootDept.setIsPlatformCompany(0);
rootDept.setSyncTime(new Date());
this.save(rootDept);
log.info("已创建 OA 同步集团顶级 id={} name={} code={}",
OAConvertConstant.OA_SYNC_ROOT_DEPT_ID,
OAConvertConstant.OA_SYNC_ROOT_DEPT_NAME,
OAConvertConstant.OA_SYNC_ROOT_DEPT_CODE);
} else {
boolean wronglyNamedAsExternal = OAConvertConstant.EXTERNAL_ORG_NAME.equals(rootDept.getDeptName());
boolean needUpdate = wronglyNamedAsExternal
|| !OAConvertConstant.OA_SYNC_ROOT_DEPT_CODE.equals(rootDept.getDeptCode())
|| !DeptCategory.GROUP.getCode().equals(rootDept.getDeptCategory())
|| !Objects.equals(BladeConstant.TOP_PARENT_ID, rootDept.getParentId());
if (needUpdate) {
Dept updateParam = new Dept();
updateParam.setId(rootDept.getId());
if (wronglyNamedAsExternal || StringUtil.isBlank(rootDept.getDeptName())) {
updateParam.setDeptName(OAConvertConstant.OA_SYNC_ROOT_DEPT_NAME);
updateParam.setFullName(OAConvertConstant.OA_SYNC_ROOT_DEPT_NAME);
updateParam.setShortName(OAConvertConstant.OA_SYNC_ROOT_DEPT_NAME);
rootDept.setDeptName(OAConvertConstant.OA_SYNC_ROOT_DEPT_NAME);
rootDept.setFullName(OAConvertConstant.OA_SYNC_ROOT_DEPT_NAME);
rootDept.setShortName(OAConvertConstant.OA_SYNC_ROOT_DEPT_NAME);
}
updateParam.setDeptCode(OAConvertConstant.OA_SYNC_ROOT_DEPT_CODE);
updateParam.setBelongCompanyCode(OAConvertConstant.OA_SYNC_ROOT_DEPT_CODE);
updateParam.setDeptCategory(DeptCategory.GROUP.getCode());
updateParam.setParentId(BladeConstant.TOP_PARENT_ID);
updateParam.setAncestors(String.valueOf(BladeConstant.TOP_PARENT_ID));
updateParam.setParentCode(String.valueOf(BladeConstant.TOP_PARENT_ID));
this.updateById(updateParam);
rootDept.setDeptCode(OAConvertConstant.OA_SYNC_ROOT_DEPT_CODE);
rootDept.setBelongCompanyCode(OAConvertConstant.OA_SYNC_ROOT_DEPT_CODE);
rootDept.setDeptCategory(DeptCategory.GROUP.getCode());
rootDept.setParentId(BladeConstant.TOP_PARENT_ID);
rootDept.setAncestors(String.valueOf(BladeConstant.TOP_PARENT_ID));
rootDept.setParentCode(String.valueOf(BladeConstant.TOP_PARENT_ID));
log.info("已校正 OA 同步集团顶级 id={} name={} code={} category={}",
rootDept.getId(), rootDept.getDeptName(), rootDept.getDeptCode(), rootDept.getDeptCategory());
}
}
this.ensureExternalOrgTopDept();
return rootDept;
}
/**
* 确保存在独立的「外部组织」顶级(与 id=135 集团并存,仅保留一个同名顶级)
*/
private Dept ensureExternalOrgTopDept() {
List<Dept> externalTops = this.list(Wrappers.<Dept>lambdaQuery()
.eq(Dept::getDeptName, OAConvertConstant.EXTERNAL_ORG_NAME)
.and(wrapper -> wrapper
.isNull(Dept::getParentId)
.or()
.eq(Dept::getParentId, BladeConstant.TOP_PARENT_ID))
.ne(Dept::getId, OAConvertConstant.OA_SYNC_ROOT_DEPT_ID)
.orderByAsc(Dept::getId));
if (CollectionUtil.isNotEmpty(externalTops)) {
Dept keep = externalTops.get(0);
if (externalTops.size() > 1) {
List<Long> duplicateIds = externalTops.stream()
.skip(1)
.map(Dept::getId)
.filter(Objects::nonNull)
.toList();
if (CollectionUtil.isNotEmpty(duplicateIds)) {
this.update(Wrappers.<Dept>lambdaUpdate()
.set(Dept::getParentId, keep.getId())
.in(Dept::getParentId, duplicateIds));
this.removeByIds(duplicateIds);
log.info("已合并重复的外部组织顶级,保留 id={},删除{}", keep.getId(), duplicateIds);
}
}
return keep;
}
String tenantId = AuthUtil.getTenantId();
if (StringUtil.isBlank(tenantId)) {
tenantId = BladeConstant.ADMIN_TENANT_ID;
}
Dept externalDept = new Dept();
externalDept.setId(DefaultIdentifierGenerator.getInstance().nextId(null));
externalDept.setTenantId(tenantId);
externalDept.setParentId(BladeConstant.TOP_PARENT_ID);
externalDept.setAncestors(String.valueOf(BladeConstant.TOP_PARENT_ID));
externalDept.setDeptName(OAConvertConstant.EXTERNAL_ORG_NAME);
externalDept.setFullName(OAConvertConstant.EXTERNAL_ORG_NAME);
externalDept.setShortName(OAConvertConstant.EXTERNAL_ORG_NAME);
externalDept.setDeptCode(null);
externalDept.setParentCode(String.valueOf(BladeConstant.TOP_PARENT_ID));
externalDept.setDeptCategory(DeptCategory.GROUP.getCode());
externalDept.setSort(0);
externalDept.setStatus(DataStatusEnum.ENABLE.getCode());
externalDept.setIsDeleted(BladeConstant.DB_NOT_DELETED);
externalDept.setIsOa(0);
externalDept.setIsPlatformCompany(0);
externalDept.setSyncTime(new Date());
this.save(externalDept);
log.info("已创建外部组织顶级 id={}", externalDept.getId());
return externalDept;
}
/**
* 清理历史伪顶级(OACROOT);同名「桂物物流集团」仅清理非 id=135 的顶级
*/
private void removeLegacyOaSyncRoots() {
List<Dept> legacyRoots = this.list(Wrappers.<Dept>lambdaQuery()
.ne(Dept::getId, OAConvertConstant.OA_SYNC_ROOT_DEPT_ID)
.and(wrapper -> wrapper
.eq(Dept::getDeptCode, OAConvertConstant.LEGACY_ROOT_DEPT_CODE)
.or(nameWrapper -> nameWrapper
.eq(Dept::getDeptName, OAConvertConstant.LEGACY_ROOT_DEPT_NAME)
.eq(Dept::getDeptCode, OAConvertConstant.LEGACY_ROOT_DEPT_CODE)
.and(parentWrapper -> parentWrapper
.isNull(Dept::getParentId)
.or()
.eq(Dept::getParentId, BladeConstant.TOP_PARENT_ID)))));
if (CollectionUtil.isEmpty(legacyRoots)) {
return;
}
Set<Long> legacyIds = legacyRoots.stream().map(Dept::getId).filter(Objects::nonNull).collect(Collectors.toSet());
this.update(Wrappers.<Dept>lambdaUpdate()
.set(Dept::getParentId, OAConvertConstant.OA_SYNC_ROOT_DEPT_ID)
.set(Dept::getParentCode, OAConvertConstant.OA_SYNC_ROOT_DEPT_CODE)
.in(Dept::getParentId, legacyIds));
this.removeByIds(legacyIds);
log.info("已清理历史伪顶级组织{}条:{}", legacyIds.size(), legacyIds);
}
/**
* 按编码前缀对齐组织类型:OAC→公司、OAD→部门(覆盖历史 1/2 映射)
*/
private void migrateLegacyOaDeptCategory() {
this.update(Wrappers.<Dept>lambdaUpdate()
.set(Dept::getDeptCategory, DeptCategory.DEPT.getCode())
.likeRight(Dept::getDeptCode, OAConvertConstant.DEPARTMENT_OA_PREFIX));
this.update(Wrappers.<Dept>lambdaUpdate()
.set(Dept::getDeptCategory, DeptCategory.COMPANY.getCode())
.likeRight(Dept::getDeptCode, OAConvertConstant.COMPANY_OA_PREFIX)
.ne(Dept::getDeptCode, OAConvertConstant.LEGACY_ROOT_DEPT_CODE));
}
@Override
@@ -434,10 +612,14 @@ public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements ID
if (dept.getIsPlatformCompany() == null) {
dept.setIsPlatformCompany(0);
}
// 排序未填时默认 1
if (dept.getSort() == null) {
dept.setSort(1);
}
if (Func.isEmpty(dept.getTenantId())) {
throw new ServiceException("租户ID不能为空");
}
validateDeptCategory(dept, parent);
validateDeptCategory(dept);
validateDeptCode(dept, parent);
return saveOrUpdate(dept);
}
@@ -619,27 +801,8 @@ public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements ID
return "Basic " + value;
}
private void validateDeptCategory(Dept dept, Dept parent) {
// 顶级组织不要求选择上级组织
if (parent == null) {
if (Integer.valueOf(6).equals(dept.getDeptCategory()) && Func.isEmpty(dept.getCarrierCustomerId())) {
throw new ServiceException("请选择承运商");
}
return;
}
List<Integer> allowedCategories;
if (BladeConstant.TOP_PARENT_ID.equals(parent.getParentId())) {
allowedCategories = "外部组织".equals(parent.getDeptName()) ? List.of(6) : List.of(1);
} else if (Integer.valueOf(1).equals(parent.getDeptCategory())) {
allowedCategories = List.of(2, 3);
} else if (List.of(2, 3).contains(parent.getDeptCategory())) {
allowedCategories = List.of(4, 5, 6);
} else {
throw new ServiceException("上级组织层级不支持新增下级组织");
}
if (!allowedCategories.contains(dept.getDeptCategory())) {
throw new ServiceException("组织类型不符合上级组织层级规则");
}
private void validateDeptCategory(Dept dept) {
// 组织树层级仅由 parentId / ancestors 决定,组织类型不再做上下级约束
if (Integer.valueOf(6).equals(dept.getDeptCategory()) && Func.isEmpty(dept.getCarrierCustomerId())) {
throw new ServiceException("请选择承运商");
}
@@ -665,9 +828,16 @@ public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements ID
if (StringUtil.isBlank(parent.getDeptCode())) {
throw new ServiceException("请选择已配置组织编码的上级组织");
}
String pattern = Pattern.quote(parent.getDeptCode()) + "-\\d+";
if (!deptCode.matches(pattern)) {
throw new ServiceException("组织编码格式应为:上级编码-分段数字");
// 公司:GWWL+三位数字;部门:所属公司编码+三位数字;其他:上级编码+三位数字
String expectedParentCode = parent.getDeptCode();
if (DeptCategory.COMPANY.getCode().equals(dept.getDeptCategory())) {
expectedParentCode = OAConvertConstant.OA_SYNC_ROOT_DEPT_CODE;
} else if (DeptCategory.DEPT.getCode().equals(dept.getDeptCategory())
&& StringUtil.isNotBlank(dept.getBelongCompanyCode())) {
expectedParentCode = dept.getBelongCompanyCode();
}
if (!org.springblade.system.util.DeptCodeUtil.matchesChildCode(expectedParentCode, deptCode)) {
throw new ServiceException("组织编码格式应为:" + expectedParentCode + "三位数字(不足补零,中间不加-)");
}
this.ensureDeptCodeUnique(dept, deptCode);
dept.setDeptCode(deptCode);
@@ -739,8 +909,8 @@ public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements ID
log.info("没有记录OA主键的组织,跳过层级重建");
return;
}
Map<String, Dept> companyByOaId = this.indexByOaId(oaDeptList, DeptCategory.COMPANY.getCode());
Map<String, Dept> departmentByOaId = this.indexByOaId(oaDeptList, DeptCategory.DEPT.getCode());
Map<String, Dept> companyByOaId = this.indexOaCompanies(oaDeptList);
Map<String, Dept> departmentByOaId = this.indexOaDepartments(oaDeptList);
Map<Long, Long> desiredParentIdMap = new LinkedHashMap<>();
Map<Long, String> desiredParentCodeMap = new HashMap<>();
for (Dept dept : oaDeptList) {
@@ -793,21 +963,20 @@ public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements ID
if (CollectionUtil.isEmpty(oaDeptList)) {
return 0;
}
Map<String, Dept> companyByOaId = this.indexByOaId(oaDeptList, DeptCategory.COMPANY.getCode());
Map<String, Dept> departmentByOaId = this.indexByOaId(oaDeptList, DeptCategory.DEPT.getCode());
Map<String, Dept> companyByOaId = this.indexOaCompanies(oaDeptList);
Map<String, Dept> departmentByOaId = this.indexOaDepartments(oaDeptList);
Set<Long> deleteIds = new HashSet<>();
for (Dept dept : oaDeptList) {
String parentOaId = dept.getOaSupSubComId();
// 上级为空或为 0:视为本地锚点/根级,不作为孤儿删除
// 上级为空或为 0:OA 顶级公司挂本地锚点,不作为孤儿
if (StringUtil.isBlank(parentOaId) || OAConstant.ROOT_COMPANY_ID.equals(parentOaId)) {
continue;
}
boolean parentExists;
if (DeptCategory.COMPANY.getCode().equals(dept.getDeptCategory())) {
parentExists = companyByOaId.containsKey(parentOaId);
} else {
parentExists = departmentByOaId.containsKey(parentOaId) || companyByOaId.containsKey(parentOaId);
}
boolean isCompany = this.isOaCompany(dept);
boolean parentExists = isCompany
? companyByOaId.containsKey(parentOaId)
: departmentByOaId.containsKey(parentOaId) || companyByOaId.containsKey(parentOaId);
// 全量数据整理后仍找不到上级:公司、部门一律删除,不改挂保留
if (!parentExists) {
deleteIds.add(dept.getId());
}
@@ -828,7 +997,7 @@ public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements ID
if (StringUtil.isBlank(parentOaId) || OAConstant.ROOT_COMPANY_ID.equals(parentOaId)) {
continue;
}
Dept parent = DeptCategory.COMPANY.getCode().equals(dept.getDeptCategory())
Dept parent = this.isOaCompany(dept)
? companyByOaId.get(parentOaId)
: Optional.ofNullable(departmentByOaId.get(parentOaId)).orElse(companyByOaId.get(parentOaId));
if (parent != null && deleteIds.contains(parent.getId())) {
@@ -857,6 +1026,72 @@ public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements ID
return deleteIds.size();
}
/**
* 索引 OA 公司:同时兼容类型迁移前后的公司记录
*/
private Map<String, Dept> indexOaCompanies(List<Dept> oaDeptList) {
Map<String, Dept> oaIdMap = new HashMap<>();
for (Dept dept : oaDeptList) {
if (!this.isOaCompany(dept) || StringUtil.isBlank(dept.getOaId())) {
continue;
}
Dept previous = oaIdMap.put(dept.getOaId(), dept);
if (previous != null) {
log.warn("OA公司主键重复,层级重建使用后一条 oaId={} id={} previousId={}",
dept.getOaId(), dept.getId(), previous.getId());
}
}
return oaIdMap;
}
private boolean isOaCompany(Dept dept) {
if (dept == null) {
return false;
}
if (DeptCategory.COMPANY.getCode().equals(dept.getDeptCategory())) {
return true;
}
if (org.springblade.system.util.DeptCodeUtil.isCompanyCode(dept.getDeptCode())) {
return true;
}
return StringUtil.isNotBlank(dept.getDeptCode())
&& dept.getDeptCode().startsWith(OAConvertConstant.COMPANY_OA_PREFIX)
&& !OAConvertConstant.LEGACY_ROOT_DEPT_CODE.equals(dept.getDeptCode());
}
private boolean isOaDepartment(Dept dept) {
if (dept == null) {
return false;
}
if (DeptCategory.DEPT.getCode().equals(dept.getDeptCategory())) {
return true;
}
if (StringUtil.isNotBlank(dept.getBelongCompanyCode())
&& org.springblade.system.util.DeptCodeUtil.matchesChildCode(dept.getBelongCompanyCode(), dept.getDeptCode())) {
return true;
}
return StringUtil.isNotBlank(dept.getDeptCode())
&& dept.getDeptCode().startsWith(OAConvertConstant.DEPARTMENT_OA_PREFIX);
}
/**
* 索引 OA 部门:兼容类型迁移前后
*/
private Map<String, Dept> indexOaDepartments(List<Dept> oaDeptList) {
Map<String, Dept> oaIdMap = new HashMap<>();
for (Dept dept : oaDeptList) {
if (!this.isOaDepartment(dept) || StringUtil.isBlank(dept.getOaId())) {
continue;
}
Dept previous = oaIdMap.put(dept.getOaId(), dept);
if (previous != null) {
log.warn("OA部门主键重复,层级重建使用后一条 oaId={} id={} previousId={}",
dept.getOaId(), dept.getId(), previous.getId());
}
}
return oaIdMap;
}
/**
* 按机构类型建立 OA 主键索引
*/
@@ -881,19 +1116,22 @@ public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements ID
private OaParentLink resolveOaParentLink(Dept dept, Map<String, Dept> companyByOaId, Map<String, Dept> departmentByOaId) {
String parentOaId = dept.getOaSupSubComId();
boolean rootParent = StringUtil.isBlank(parentOaId) || OAConstant.ROOT_COMPANY_ID.equals(parentOaId);
if (DeptCategory.COMPANY.getCode().equals(dept.getDeptCategory())) {
if (this.isOaCompany(dept)) {
if (rootParent) {
return new OaParentLink(OAConvertConstant.ROOT_PARENT_ID, OAConstant.ROOT_COMPANY_ID);
// OA 顶级公司统一挂到本地顶级锚点下
return new OaParentLink(OAConvertConstant.OA_SYNC_ROOT_DEPT_ID, OAConvertConstant.OA_SYNC_ROOT_DEPT_CODE);
}
Dept parent = companyByOaId.get(parentOaId);
if (parent == null || parent.getId() == null || Objects.equals(parent.getId(), dept.getId())) {
// 全量整理后仍无上级:跳过重建,交由孤儿清理直接删除
log.warn("未找到上级公司,跳过层级重建 oaId={} oaSupSubComId={} deptId={}",
dept.getOaId(), parentOaId, dept.getId());
return null;
}
return new OaParentLink(parent.getId(), this.resolveParentCode(parent, OAConvertConstant.COMPANY_OA_PREFIX, parentOaId));
}
if (!DeptCategory.DEPT.getCode().equals(dept.getDeptCategory())) {
if (!DeptCategory.DEPT.getCode().equals(dept.getDeptCategory())
&& !(StringUtil.isNotBlank(dept.getDeptCode()) && dept.getDeptCode().startsWith(OAConvertConstant.DEPARTMENT_OA_PREFIX))) {
return null;
}
if (rootParent) {
@@ -50,7 +50,7 @@ public class MeasurementUnitServiceImpl extends BaseServiceImpl<MeasurementUnitM
private static final int UNIT_NAME_MAX_LENGTH = 50;
private static final int DIMENSION_MAX_LENGTH = 20;
private static final int REMARK_MAX_LENGTH = 200;
private static final Set<String> DIMENSIONS = Set.of("重量", "体积", "数量");
private static final Set<String> DIMENSIONS = Set.of("重量", "体积", "数量", "整车", "里程", "吨·公里");
@Override
public IPage<MeasurementUnitVO> selectMeasurementUnitPage(IPage<MeasurementUnitVO> page,
@@ -0,0 +1,380 @@
/**
* 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>
* Author: Chill Zhuang (bladejava@qq.com)
*/
package org.springblade.system.service.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springblade.common.utils.PasswordRuleUtil;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.DigestUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.system.cache.MpUserCache;
import org.springblade.system.mapper.MpUserMapper;
import org.springblade.system.pojo.entity.MpUser;
import org.springblade.system.pojo.entity.MpUserInfo;
import org.springblade.system.pojo.enums.MpUserIdentity;
import org.springblade.system.service.IMpUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* 小程序用户 服务实现类
*
* @author Chill
*/
@Service
@RequiredArgsConstructor
public class MpUserServiceImpl extends BaseServiceImpl<MpUserMapper, MpUser> implements IMpUserService {
@Override
public MpUser getByPhone(String tenantId, String phone) {
if (Func.isBlank(tenantId) || Func.isBlank(phone)) {
return null;
}
return getOne(Wrappers.<MpUser>lambdaQuery()
.eq(MpUser::getTenantId, tenantId)
.eq(MpUser::getPhone, phone)
.orderByDesc(MpUser::getCreateTime)
.last("LIMIT 1"));
}
@Override
public MpUser getByAccount(String tenantId, String account) {
if (Func.isBlank(tenantId) || Func.isBlank(account)) {
return null;
}
return getOne(Wrappers.<MpUser>lambdaQuery()
.eq(MpUser::getTenantId, tenantId)
.eq(MpUser::getAccount, account)
.orderByDesc(MpUser::getCreateTime)
.last("LIMIT 1"));
}
@Override
public MpUserInfo userInfo(Long userId) {
if (Func.isEmpty(userId)) {
return null;
}
return buildUserInfo(getById(userId));
}
@Override
public MpUserInfo userInfoByPhone(String tenantId, String phone) {
return buildUserInfo(getByPhone(tenantId, phone));
}
@Override
public MpUserInfo userInfoByAccount(String tenantId, String account) {
return buildUserInfo(getByAccount(tenantId, account));
}
@Override
public IPage<MpUser> selectMpUserPage(IPage<MpUser> page, MpUser query) {
MpUser condition = query == null ? new MpUser() : query;
return page(page, Wrappers.<MpUser>lambdaQuery()
.like(Func.isNotBlank(condition.getPhone()), MpUser::getPhone, condition.getPhone())
.like(Func.isNotBlank(condition.getAccount()), MpUser::getAccount, condition.getAccount())
.like(Func.isNotBlank(condition.getRealName()), MpUser::getRealName, condition.getRealName())
.like(Func.isNotBlank(condition.getName()), MpUser::getName, condition.getName())
.like(Func.isNotBlank(condition.getIdentities()), MpUser::getIdentities, condition.getIdentities())
.eq(condition.getStatus() != null, MpUser::getStatus, condition.getStatus())
.orderByDesc(MpUser::getCreateTime));
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean submit(MpUser user) {
prepare(user);
validate(user);
MpUser existed = getByPhone(user.getTenantId(), user.getPhone());
if (existed != null && Func.isNotEmpty(existed.getId())) {
throw new ServiceException("该手机号已存在小程序用户");
}
encryptPasswordIfPresent(user);
boolean saved = save(user);
if (saved) {
MpUserCache.clear();
}
return saved;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean updateUser(MpUser user) {
if (user == null || Func.isEmpty(user.getId())) {
throw new ServiceException("小程序用户主键不能为空");
}
prepare(user);
validate(user);
MpUser existed = getByPhone(user.getTenantId(), user.getPhone());
if (existed != null && Func.isNotEmpty(existed.getId()) && !existed.getId().equals(user.getId())) {
throw new ServiceException("该手机号已存在小程序用户");
}
// 后台编辑不改密码,避免空串覆盖
user.setPassword(null);
boolean updated = updateById(user);
if (updated) {
MpUserCache.clear();
}
return updated;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean submitOrUpdate(MpUser user) {
if (user != null && Func.isNotEmpty(user.getId())) {
return updateUser(user);
}
return submit(user);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean removeMpUser(List<Long> ids) {
if (Func.isEmpty(ids)) {
throw new ServiceException("请选择要删除的小程序用户");
}
boolean removed = deleteLogic(ids);
if (removed) {
MpUserCache.clear();
}
return removed;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean changeStatus(Long id, Integer status) {
if (Func.isEmpty(id)) {
throw new ServiceException("小程序用户主键不能为空");
}
if (status == null || (status != 0 && status != 1)) {
throw new ServiceException("状态仅支持启用(1)或停用(0)");
}
MpUser user = getById(id);
if (user == null || Func.isEmpty(user.getId())) {
throw new ServiceException("小程序用户不存在");
}
MpUser patch = new MpUser();
patch.setId(id);
patch.setStatus(status);
boolean updated = updateById(patch);
if (updated) {
MpUserCache.clear();
}
return updated;
}
@Override
@Transactional(rollbackFor = Exception.class)
public Map<String, String> resetPassword(List<Long> userIds) {
if (Func.isEmpty(userIds)) {
throw new ServiceException("请选择要重置密码的小程序用户");
}
Map<String, String> passwordMap = new LinkedHashMap<>();
for (Long userId : userIds) {
MpUser user = getById(userId);
if (user == null || Func.isEmpty(user.getId())) {
continue;
}
String password = PasswordRuleUtil.generate();
MpUser patch = new MpUser();
patch.setId(userId);
patch.setPassword(DigestUtil.encrypt(password));
patch.setUpdateTime(DateUtil.now());
updateById(patch);
String account = Func.toStr(user.getAccount(), user.getPhone());
passwordMap.put(account, password);
}
if (passwordMap.isEmpty()) {
throw new ServiceException("未找到可重置密码的小程序用户");
}
MpUserCache.clear();
return passwordMap;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean bindOpenId(String tenantId, Long userId, String openid) {
if (Func.isBlank(tenantId) || Func.isEmpty(userId) || Func.isBlank(openid)) {
throw new ServiceException("绑定 openid 参数不完整");
}
MpUser user = getById(userId);
if (user == null || Func.isEmpty(user.getId())) {
throw new ServiceException("小程序用户不存在");
}
if (!tenantId.equals(user.getTenantId())) {
throw new ServiceException("租户不匹配,无法绑定 openid");
}
MpUser byOpenId = getOne(Wrappers.<MpUser>lambdaQuery()
.eq(MpUser::getTenantId, tenantId)
.eq(MpUser::getOpenid, openid)
.last("LIMIT 1"));
if (byOpenId != null && !byOpenId.getId().equals(userId)) {
throw new ServiceException("该微信已绑定其他小程序用户");
}
MpUser patch = new MpUser();
patch.setId(userId);
patch.setOpenid(openid);
boolean updated = updateById(patch);
if (updated) {
MpUserCache.clear();
}
return updated;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean setPassword(Long userId, String password, String password2) {
if (!Objects.equals(password, password2)) {
throw new ServiceException("两次输入密码不一致!");
}
if (!PasswordRuleUtil.isValid(password)) {
throw new ServiceException(PasswordRuleUtil.RULE_MESSAGE);
}
MpUser user = getById(userId);
if (user == null || Func.isEmpty(user.getId())) {
throw new ServiceException("小程序用户不存在");
}
MpUser patch = new MpUser();
patch.setId(userId);
patch.setPassword(DigestUtil.encrypt(password));
patch.setUpdateTime(DateUtil.now());
boolean updated = updateById(patch);
if (updated) {
MpUserCache.clear();
}
return updated;
}
private MpUserInfo buildUserInfo(MpUser user) {
if (user == null || Func.isEmpty(user.getId())) {
return null;
}
List<String> identities = MpUserIdentity.split(user.getIdentities());
if (identities.isEmpty()) {
throw new ServiceException("小程序用户未配置身份,无法登录");
}
MpUserInfo userInfo = new MpUserInfo();
userInfo.setUser(user);
userInfo.setIdentities(identities);
userInfo.setPermissions(MpUserIdentity.toPermissions(user.getIdentities()));
userInfo.setDetail(Kv.create()
.set("type", MpUserIdentity.DETAIL_TYPE)
.set("identities", user.getIdentities())
.set("openid", Func.toStr(user.getOpenid(), "")));
return userInfo;
}
private void prepare(MpUser user) {
if (user == null) {
return;
}
if (Func.isBlank(user.getTenantId())) {
user.setTenantId(AuthUtil.getTenantId());
}
user.setAccount(trimToNull(user.getAccount()));
user.setPhone(trimToNull(user.getPhone()));
user.setName(trimToNull(user.getName()));
user.setRealName(trimToNull(user.getRealName()));
user.setAvatar(trimToNull(user.getAvatar()));
user.setEmail(trimToNull(user.getEmail()));
user.setOpenid(trimToNull(user.getOpenid()));
user.setDeptId(trimToNull(user.getDeptId()));
user.setPostId(trimToNull(user.getPostId()));
user.setRemark(trimToNull(user.getRemark()));
user.setIdentities(normalizeIdentities(user.getIdentities()));
if (Func.isBlank(user.getAccount()) && Func.isNotBlank(user.getPhone())) {
user.setAccount(user.getPhone());
}
if (Func.isBlank(user.getName()) && Func.isNotBlank(user.getRealName())) {
user.setName(user.getRealName());
}
if (user.getStatus() == null) {
user.setStatus(1);
}
}
private void encryptPasswordIfPresent(MpUser user) {
if (user == null || Func.isBlank(user.getPassword())) {
user.setPassword(null);
return;
}
String password = user.getPassword().trim();
if (!PasswordRuleUtil.isValid(password)) {
throw new ServiceException(PasswordRuleUtil.RULE_MESSAGE);
}
user.setPassword(DigestUtil.encrypt(password));
}
private void validate(MpUser user) {
if (user == null) {
throw new ServiceException("小程序用户不能为空");
}
if (Func.isBlank(user.getTenantId())) {
throw new ServiceException("租户信息不能为空");
}
if (Func.isBlank(user.getPhone())) {
throw new ServiceException("手机号不能为空");
}
if (Func.isBlank(user.getIdentities())) {
throw new ServiceException("小程序身份不能为空");
}
List<String> identities = MpUserIdentity.split(user.getIdentities());
if (identities.isEmpty()) {
throw new ServiceException("小程序身份不能为空");
}
for (String code : identities) {
if (MpUserIdentity.of(code) == null) {
throw new ServiceException("不支持的小程序身份:" + code);
}
}
}
private String normalizeIdentities(String identities) {
List<String> identityList = MpUserIdentity.split(identities);
if (identityList.isEmpty()) {
return null;
}
return StringUtil.join(identityList);
}
private String trimToNull(String value) {
if (value == null) {
return null;
}
String trimValue = value.trim();
return trimValue.isEmpty() ? null : trimValue;
}
}
@@ -22,6 +22,7 @@ import org.springblade.system.pojo.vo.OaOrgSyncPageVO;
import org.springblade.system.pojo.vo.OaPersonSyncPageVO;
import org.springblade.system.service.*;
import org.springblade.system.util.DataSyncRecordUtils;
import org.springblade.system.util.DeptCodeUtil;
import org.springblade.thirdparty.oa.constant.OAConstant;
import org.springblade.thirdparty.oa.constant.OAConvertConstant;
import org.springblade.thirdparty.oa.feign.IOAClient;
@@ -60,6 +61,7 @@ public class OASyncServiceImpl implements IOASyncService {
private final IOAClient oaClient;
private final DeptConvert deptConvert;
private final IDeptService deptService;
private final IUserService userService;
private final IRoleService roleService;
private final IMKPushService mkPushService;
private final IDataSyncRecordService dataSyncRecordService;
@@ -72,6 +74,8 @@ public class OASyncServiceImpl implements IOASyncService {
ComposeLogUtil.addLog(log);
// 1. 同步公司和部门并记录
Date startTime = this.syncAndRecord(DataSyncRecordUtils::createOAOrgFetch, queryStartTime -> {
// 0. 确保双顶级:id=135 集团(GWWL) + 独立「外部组织」
deptService.ensureOaSyncRootDept();
// 1. 同步公司
this.syncCompany(queryStartTime);
// 公司分批入库后,重建层级并清理无法挂载的公司
@@ -124,10 +128,10 @@ public class OASyncServiceImpl implements IOASyncService {
@Transactional(rollbackFor = Exception.class)
@Override
public OaPersonSyncPageVO syncPersonFromUserList(int current, int size) {
public OaPersonSyncPageVO syncPersonFromUserList(int current, int size, boolean incremental, String modifiedSince) {
try {
ComposeLogUtil.addLog(log);
return this.syncPersonFromOaPage(current, size);
return this.syncPersonFromOaPage(current, size, incremental, modifiedSince);
} finally {
ComposeLogUtil.removeLastLog();
}
@@ -135,10 +139,10 @@ public class OASyncServiceImpl implements IOASyncService {
@Transactional(rollbackFor = Exception.class)
@Override
public OaOrgSyncPageVO syncCompanyPage(int current, int size) {
public OaOrgSyncPageVO syncCompanyPage(int current, int size, boolean incremental, String modifiedSince) {
try {
ComposeLogUtil.addLog(log);
return this.syncCompanyFromOaPage(current, size);
return this.syncCompanyFromOaPage(current, size, incremental, modifiedSince);
} finally {
ComposeLogUtil.removeLastLog();
}
@@ -146,10 +150,10 @@ public class OASyncServiceImpl implements IOASyncService {
@Transactional(rollbackFor = Exception.class)
@Override
public OaOrgSyncPageVO syncDepartmentPage(int current, int size) {
public OaOrgSyncPageVO syncDepartmentPage(int current, int size, boolean incremental, String modifiedSince) {
try {
ComposeLogUtil.addLog(log);
return this.syncDepartmentFromOaPage(current, size);
return this.syncDepartmentFromOaPage(current, size, incremental, modifiedSince);
} finally {
ComposeLogUtil.removeLastLog();
}
@@ -280,14 +284,17 @@ public class OASyncServiceImpl implements IOASyncService {
/**
* 按页从 OA 人员列表同步组织与人员
*
* @param current 当前页
* @param size 每页条数
* @param current 当前页
* @param size 每页条数
* @param incremental 是否增量同步
* @param modifiedSince 增量起始时间(后续分页回传)
* @return 本页同步结果
*/
private OaPersonSyncPageVO syncPersonFromOaPage(int current, int size) {
private OaPersonSyncPageVO syncPersonFromOaPage(int current, int size, boolean incremental, String modifiedSince) {
int pageNo = current < 1 ? 1 : current;
int pageSize = size < 1 ? 20 : Math.min(size, 200);
OAPersonSearch personSearch = buildPersonSearch(null);
IncrementalStart incrementalStart = resolvePersonIncrementalStart(incremental, modifiedSince);
OAPersonSearch personSearch = buildPersonSearch(incrementalStart.getStartTime());
personSearch.setCurPage(pageNo);
personSearch.setPageSize(pageSize);
OAResponse<OAPersonResponse> oaResponse = oaClient.queryPersonPage(new OASearch<>(personSearch));
@@ -311,26 +318,35 @@ public class OASyncServiceImpl implements IOASyncService {
pageVO.setFetchedCount(oaPersons.size());
pageVO.setSyncedCount(personSyncCount.getSyncedCount());
pageVO.setSkippedCount(personSyncCount.getSkippedCount());
pageVO.setModifiedSince(incrementalStart.getModifiedSince());
boolean finished = oaPersons.isEmpty()
|| oaPersons.size() < pageSize
|| (long) pageNo * pageSize >= totalSize;
pageVO.setFinished(finished);
ComposeLogUtil.getLastLog().info("OA人员分页同步完成 {}/{},成功{},跳过{}",
pageNo, totalSize, personSyncCount.getSyncedCount(), personSyncCount.getSkippedCount());
ComposeLogUtil.getLastLog().info("OA人员分页同步完成 mode={} {}/{},成功{},跳过{}",
incremental ? "incremental" : "full", pageNo, totalSize,
personSyncCount.getSyncedCount(), personSyncCount.getSkippedCount());
return pageVO;
}
/**
* 按页从 OA 公司接口同步公司
*
* @param current 当前页
* @param size 每页条数
* @param current 当前页
* @param size 每页条数
* @param incremental 是否增量同步
* @param modifiedSince 增量起始时间(后续分页回传)
* @return 本页同步结果
*/
private OaOrgSyncPageVO syncCompanyFromOaPage(int current, int size) {
private OaOrgSyncPageVO syncCompanyFromOaPage(int current, int size, boolean incremental, String modifiedSince) {
int pageNo = current < 1 ? 1 : current;
int pageSize = size < 1 ? 20 : Math.min(size, 200);
OACompanySearch companySearch = buildCompanySearch(null);
// 首屏确保双顶级:id=135 集团(GWWL) + 独立「外部组织」
if (pageNo == 1) {
deptService.ensureOaSyncRootDept();
}
IncrementalStart incrementalStart = resolveIncrementalStart(incremental, modifiedSince, DeptCategory.COMPANY);
OACompanySearch companySearch = buildCompanySearch(incrementalStart.getStartTime());
companySearch.setCurPage(pageNo);
companySearch.setPageSize(pageSize);
OAResponse<OACompanyResponse> oaResponse = oaClient.queryCompanyPage(new OASearch<>(companySearch));
@@ -347,6 +363,7 @@ public class OASyncServiceImpl implements IOASyncService {
ComposeLogUtil.getLastLog().warn("同步公司,本页未处理数据:{}", JSON.toJSONString(syncCount.getNotHandledList()));
}
OaOrgSyncPageVO pageVO = buildOrgSyncPageVO("company", pageNo, pageSize, totalSize, oaCompanies.size(), syncCount);
pageVO.setModifiedSince(incrementalStart.getModifiedSince());
if (Boolean.TRUE.equals(pageVO.getFinished())) {
// 公司全部分批入库后:重建层级,并删除上级不存在的数据
deptService.rebuildOaHierarchy();
@@ -354,19 +371,22 @@ public class OASyncServiceImpl implements IOASyncService {
}
CacheUtil.clear(SYS_CACHE);
CacheUtil.clear(SYS_CACHE, Boolean.FALSE);
ComposeLogUtil.getLastLog().info("OA公司分页同步完成 {}/{},成功{},跳过{}",
pageNo, totalSize, syncCount.getSyncedCount(), syncCount.getSkippedCount());
ComposeLogUtil.getLastLog().info("OA公司分页同步完成 mode={} {}/{},成功{},跳过{}",
incremental ? "incremental" : "full", pageNo, totalSize,
syncCount.getSyncedCount(), syncCount.getSkippedCount());
return pageVO;
}
/**
* 按页从 OA 部门接口同步部门
*
* @param current 当前页
* @param size 每页条数
* @param current 当前页
* @param size 每页条数
* @param incremental 是否增量同步
* @param modifiedSince 增量起始时间(后续分页回传)
* @return 本页同步结果
*/
private OaOrgSyncPageVO syncDepartmentFromOaPage(int current, int size) {
private OaOrgSyncPageVO syncDepartmentFromOaPage(int current, int size, boolean incremental, String modifiedSince) {
int pageNo = current < 1 ? 1 : current;
int pageSize = size < 1 ? 20 : Math.min(size, 200);
String subCompanyIds = getOaSubCompanyIds(true);
@@ -376,7 +396,8 @@ public class OASyncServiceImpl implements IOASyncService {
emptyPageVO.setFinished(true);
return emptyPageVO;
}
OADepartmentSearch departmentSearch = buildDepartmentSearch(null, subCompanyIds);
IncrementalStart incrementalStart = resolveIncrementalStart(incremental, modifiedSince, DeptCategory.DEPT);
OADepartmentSearch departmentSearch = buildDepartmentSearch(incrementalStart.getStartTime(), subCompanyIds);
departmentSearch.setCurPage(pageNo);
departmentSearch.setPageSize(pageSize);
OAResponse<OADepartmentResponse> oaResponse = oaClient.queryDepartmentPage(new OASearch<>(departmentSearch));
@@ -393,6 +414,7 @@ public class OASyncServiceImpl implements IOASyncService {
ComposeLogUtil.getLastLog().warn("同步部门,本页未处理数据:{}", JSON.toJSONString(syncCount.getNotHandledList()));
}
OaOrgSyncPageVO pageVO = buildOrgSyncPageVO("department", pageNo, pageSize, totalSize, oaDepartments.size(), syncCount);
pageVO.setModifiedSince(incrementalStart.getModifiedSince());
if (Boolean.TRUE.equals(pageVO.getFinished())) {
// 部门分批同步完成后,重建层级、清理无法挂载数据并刷新祖级列表
deptService.rebuildOaHierarchy();
@@ -401,11 +423,118 @@ public class OASyncServiceImpl implements IOASyncService {
}
CacheUtil.clear(SYS_CACHE);
CacheUtil.clear(SYS_CACHE, Boolean.FALSE);
ComposeLogUtil.getLastLog().info("OA部门分页同步完成 {}/{},成功{},跳过{}",
pageNo, totalSize, syncCount.getSyncedCount(), syncCount.getSkippedCount());
ComposeLogUtil.getLastLog().info("OA部门分页同步完成 mode={} {}/{},成功{},跳过{}",
incremental ? "incremental" : "full", pageNo, totalSize,
syncCount.getSyncedCount(), syncCount.getSkippedCount());
return pageVO;
}
/**
* 解析增量同步起始时间:优先使用前端回传值,保证同阶段分页起点不变
*/
private IncrementalStart resolveIncrementalStart(boolean incremental, String modifiedSince, DeptCategory deptCategory) {
if (!incremental) {
return IncrementalStart.empty();
}
if (StringUtils.isNotBlank(modifiedSince)) {
try {
Date startTime = DateUtil.parse(modifiedSince.trim(), DateUtil.PATTERN_DATETIME);
return new IncrementalStart(startTime, modifiedSince.trim());
} catch (Exception exception) {
ComposeLogUtil.getLastLog().warn("解析回传 modifiedSince 失败:{},重新计算", modifiedSince);
}
}
String codePrefix = DeptCategory.COMPANY.equals(deptCategory)
? OAConvertConstant.COMPANY_OA_PREFIX
: OAConvertConstant.DEPARTMENT_OA_PREFIX;
Dept latest = deptService.getOne(Wrappers.<Dept>lambdaQuery()
.select(Dept::getOaModified)
.eq(Dept::getIsOa, YES)
.and(wrapper -> wrapper
.eq(Dept::getDeptCategory, deptCategory.getCode())
.or()
.likeRight(Dept::getDeptCode, codePrefix))
.isNotNull(Dept::getOaModified)
.ne(Dept::getOaModified, "")
.orderByDesc(Dept::getOaModified)
.last("limit 1"), false);
if (latest == null || StringUtils.isBlank(latest.getOaModified())) {
ComposeLogUtil.getLastLog().info("本地无 {} oaModified 记录,增量同步按全量拉取后按字段比对跳过",
deptCategory.getName());
return IncrementalStart.empty();
}
try {
Date startTime = DateUtil.parse(latest.getOaModified(), DateUtil.PATTERN_DATETIME);
ComposeLogUtil.getLastLog().info("增量同步{} OA modified 起始时间:{}",
deptCategory.getName(), latest.getOaModified());
return new IncrementalStart(startTime, latest.getOaModified());
} catch (Exception exception) {
ComposeLogUtil.getLastLog().warn("解析本地最大 oaModified 失败:{},回退为全量拉取", latest.getOaModified());
return IncrementalStart.empty();
}
}
/**
* 人员增量同步起始时间:优先回传值,否则取本地 OA 用户最大 oaModified
*/
private IncrementalStart resolvePersonIncrementalStart(boolean incremental, String modifiedSince) {
if (!incremental) {
return IncrementalStart.empty();
}
if (StringUtils.isNotBlank(modifiedSince)) {
try {
Date startTime = DateUtil.parse(modifiedSince.trim(), DateUtil.PATTERN_DATETIME);
return new IncrementalStart(startTime, modifiedSince.trim());
} catch (Exception exception) {
ComposeLogUtil.getLastLog().warn("解析人员回传 modifiedSince 失败:{},重新计算", modifiedSince);
}
}
User latest = userService.getOne(Wrappers.<User>lambdaQuery()
.select(User::getOaModified)
.eq(User::getIsOa, YES)
.isNotNull(User::getOaModified)
.ne(User::getOaModified, "")
.orderByDesc(User::getOaModified)
.last("limit 1"), false);
if (latest == null || StringUtils.isBlank(latest.getOaModified())) {
ComposeLogUtil.getLastLog().info("本地无人员 oaModified 记录,增量同步按全量拉取后按字段比对跳过");
return IncrementalStart.empty();
}
try {
Date startTime = DateUtil.parse(latest.getOaModified(), DateUtil.PATTERN_DATETIME);
ComposeLogUtil.getLastLog().info("增量同步人员 OA modified 起始时间:{}", latest.getOaModified());
return new IncrementalStart(startTime, latest.getOaModified());
} catch (Exception exception) {
ComposeLogUtil.getLastLog().warn("解析本地人员最大 oaModified 失败:{},回退为全量拉取", latest.getOaModified());
return IncrementalStart.empty();
}
}
/**
* 增量同步起点
*/
private static class IncrementalStart {
private final Date startTime;
private final String modifiedSince;
private IncrementalStart(Date startTime, String modifiedSince) {
this.startTime = startTime;
this.modifiedSince = modifiedSince;
}
private static IncrementalStart empty() {
return new IncrementalStart(null, null);
}
private Date getStartTime() {
return startTime;
}
private String getModifiedSince() {
return modifiedSince;
}
}
/**
* 组装组织分页同步结果
*/
@@ -492,13 +621,8 @@ public class OASyncServiceImpl implements IOASyncService {
if (CollectionUtil.isEmpty(oaCompanies)) {
return OrgSyncCount.empty();
}
// 获取需要的公司名称
Set<String> companyNames = syncAll ? Collections.emptySet() : getCompanyNames();
// 转换数据
List<Dept> allParam = oaCompanies.stream()
// 强制跳过上级公司为 0 的数据
.filter(company -> !OAConstant.ROOT_COMPANY_ID.equals(company.getSupsubcomid()))
// 非全量同步时,筛选只要配置的公司
.filter(company -> syncAll || companyNames.contains(company.getSubcompanyname()))
.map(deptConvert::company2dept)
.toList();
@@ -507,14 +631,41 @@ public class OASyncServiceImpl implements IOASyncService {
return new OrgSyncCount(0, filteredSkipCount, Collections.emptyList());
}
// 查询数据库的部门,转换成map
Map<String, Long> deptMap = getAllCompanyDeptMap();
// 处理部门
List<Dept> notHandledList = handleDept(allParam, deptMap, DeptCategory.COMPANY);
int syncedCount = allParam.size() - notHandledList.size();
int skippedCount = filteredSkipCount + notHandledList.size();
return new OrgSyncCount(syncedCount, skippedCount, notHandledList);
Map<String, Dept> existingByOaId = loadExistingByOaId(DeptCategory.COMPANY);
Map<String, Dept> codeOwnerMap = loadCompanyCodeOwnerMap();
Set<String> usedCodes = new HashSet<>(codeOwnerMap.keySet());
Map<String, Dept> batchByOaId = new LinkedHashMap<>();
for (Dept dept : allParam) {
this.assignCompanyCode(dept, existingByOaId, usedCodes);
batchByOaId.put(dept.getOaId(), dept);
}
// 上级公司编码:OA 上级为 0 → GWWL;否则取上级公司已分配编码
for (Dept dept : allParam) {
if (OAConstant.ROOT_COMPANY_ID.equals(dept.getOaSupSubComId()) || StringUtils.isBlank(dept.getOaSupSubComId())) {
dept.setParentCode(OAConvertConstant.OA_SYNC_ROOT_DEPT_CODE);
dept.setParentId(OAConvertConstant.OA_SYNC_ROOT_DEPT_ID);
continue;
}
Dept parent = batchByOaId.get(dept.getOaSupSubComId());
if (parent == null) {
parent = existingByOaId.get(dept.getOaSupSubComId());
}
if (parent != null && StringUtils.isNotBlank(parent.getDeptCode())) {
dept.setParentCode(parent.getDeptCode());
dept.setParentId(parent.getId());
} else {
dept.setParentCode(null);
dept.setParentId(null);
}
}
Map<String, Long> deptIdByCode = new HashMap<>();
existingByOaId.values().forEach(dept -> {
if (StringUtils.isNotBlank(dept.getDeptCode()) && dept.getId() != null) {
deptIdByCode.put(dept.getDeptCode(), dept.getId());
}
});
deptIdByCode.put(OAConvertConstant.OA_SYNC_ROOT_DEPT_CODE, OAConvertConstant.OA_SYNC_ROOT_DEPT_ID);
return persistSyncedDepts(allParam, existingByOaId, deptIdByCode, DeptCategory.COMPANY, filteredSkipCount);
}
/**
@@ -527,80 +678,239 @@ public class OASyncServiceImpl implements IOASyncService {
if (CollectionUtil.isEmpty(oaDepts)) {
return OrgSyncCount.empty();
}
// 查询所有公司的编码和id的map
Map<String, Long> companyDeptMap = getAllCompanyDeptMap();
// 根公司id
Map<String, Dept> companyByOaId = loadCompanyByOaId();
String rootCompanyId = getRootCompanyId();
if (!syncAll && rootCompanyId == null) {
return new OrgSyncCount(0, oaDepts.size(), Collections.emptyList());
}
// 根公司下要同步的部门名称
Set<String> rootCompanyDeptNames = syncAll ? Collections.emptySet() : getRootCompanyDeptNames();
// 转换数据
List<Dept> allParam = oaDepts.stream()
// 全量同步时不过滤;否则:部门的公司不是根公司,或者部门名称在根公司下需要同步的部门列表中,且是根部门
.filter(oaDept -> syncAll
|| rootCompanyId == null
|| !rootCompanyId.equals(oaDept.getSubcompanyid1())
|| (OAConstant.ROOT_COMPANY_ID.equals(oaDept.getSupdepid()) && rootCompanyDeptNames.contains(oaDept.getDepartmentname())))
.map(dept -> deptConvert.dept2dept(dept, companyDeptMap))
.map(dept -> deptConvert.dept2dept(dept, companyByOaId))
.toList();
int filteredSkipCount = oaDepts.size() - allParam.size();
if (CollectionUtil.isEmpty(allParam)) {
return new OrgSyncCount(0, filteredSkipCount, Collections.emptyList());
}
Set<String> deptCodes = new HashSet<>();
allParam.forEach(dept -> {
if (StringUtils.isNotEmpty(dept.getDeptCode())) {
deptCodes.add(dept.getDeptCode());
Map<String, Dept> existingByOaId = loadExistingByOaId(DeptCategory.DEPT);
Map<String, Integer> nextSerialByCompany = new HashMap<>();
Map<String, Set<String>> usedCodesByCompany = new HashMap<>();
// 预载各公司下已有部门编码,保证分段连续
for (Dept existing : existingByOaId.values()) {
if (StringUtils.isBlank(existing.getBelongCompanyCode()) || StringUtils.isBlank(existing.getDeptCode())) {
continue;
}
if (StringUtils.isNotEmpty(dept.getParentCode())) {
deptCodes.add(dept.getParentCode());
usedCodesByCompany
.computeIfAbsent(existing.getBelongCompanyCode(), key -> new HashSet<>())
.add(existing.getDeptCode());
}
Map<String, Dept> batchByOaId = new LinkedHashMap<>();
for (Dept dept : allParam) {
this.assignDepartmentCode(dept, existingByOaId, companyByOaId, usedCodesByCompany, nextSerialByCompany);
batchByOaId.put(dept.getOaId(), dept);
}
// 解析上级:根部门挂公司;子部门挂上级部门(本批或已存在)
Map<String, Long> deptIdByCode = new HashMap<>();
companyByOaId.values().forEach(company -> {
if (StringUtils.isNotBlank(company.getDeptCode()) && company.getId() != null) {
deptIdByCode.put(company.getDeptCode(), company.getId());
}
});
// 查询数据库的部门,转换成map。包含本页及上级编码,便于命中已入库的上级
Map<String, Long> deptMap = deptCodes.isEmpty() ? new HashMap<>() : deptService.list(Wrappers.<Dept>lambdaQuery()
.eq(Dept::getDeptCategory, DeptCategory.DEPT.getCode())
.in(Dept::getDeptCode, deptCodes)
).stream()
.filter(dept -> StringUtils.isNotEmpty(dept.getDeptCode()))
.collect(Collectors.toMap(Dept::getDeptCode, Dept::getId, (a, b) -> b));
// 公司编码也放入 map,根部门挂到公司时才能解析父级
companyDeptMap.forEach(deptMap::putIfAbsent);
// 处理部门
List<Dept> notHandledList = this.handleDept(allParam, deptMap, DeptCategory.DEPT);
int syncedCount = allParam.size() - notHandledList.size();
int skippedCount = filteredSkipCount + notHandledList.size();
return new OrgSyncCount(syncedCount, skippedCount, notHandledList);
existingByOaId.values().forEach(dept -> {
if (StringUtils.isNotBlank(dept.getDeptCode()) && dept.getId() != null) {
deptIdByCode.put(dept.getDeptCode(), dept.getId());
}
});
for (Dept dept : allParam) {
if (dept.getParentId() != null && StringUtils.isNotBlank(dept.getParentCode())
&& DeptCodeUtil.matchesChildCode(dept.getBelongCompanyCode(), dept.getDeptCode())
&& dept.getBelongCompanyCode().equals(dept.getParentCode())) {
continue;
}
String parentOaId = dept.getOaSupSubComId();
Dept belongCompany = companyByOaId.values().stream()
.filter(company -> StringUtils.equals(company.getDeptCode(), dept.getBelongCompanyCode()))
.findFirst()
.orElse(null);
if (belongCompany != null && (OAConstant.ROOT_COMPANY_ID.equals(parentOaId)
|| StringUtils.equals(parentOaId, belongCompany.getOaId()))) {
dept.setParentCode(belongCompany.getDeptCode());
dept.setParentId(belongCompany.getId());
continue;
}
Dept parentDept = batchByOaId.get(parentOaId);
if (parentDept == null) {
parentDept = existingByOaId.get(parentOaId);
}
if (parentDept != null && StringUtils.isNotBlank(parentDept.getDeptCode())) {
dept.setParentCode(parentDept.getDeptCode());
dept.setParentId(parentDept.getId());
} else if (belongCompany != null) {
// 上级部门尚未就绪时先挂所属公司,分批结束后按 OA 主键重建
dept.setParentCode(belongCompany.getDeptCode());
dept.setParentId(belongCompany.getId());
} else {
dept.setParentCode(null);
dept.setParentId(null);
}
}
return persistSyncedDepts(allParam, existingByOaId, deptIdByCode, DeptCategory.DEPT, filteredSkipCount);
}
/**
* 处理部门
* @param allParam 待处理的部门
* @param deptMap 数据库所有部门编码和id map
* @return 未处理的数据
* 公司编码:GWWL+三位数字;已有合规编码则复用
*/
private List<Dept> handleDept(List<Dept> allParam, Map<String, Long> deptMap, DeptCategory deptCategory) {
// 数据库存在的所有部门id
Set<Long> existsDeptIds = new HashSet<>(deptMap.values());
private void assignCompanyCode(Dept dept, Map<String, Dept> existingByOaId, Set<String> usedCodes) {
Dept existing = existingByOaId.get(dept.getOaId());
if (existing != null && DeptCodeUtil.isCompanyCode(existing.getDeptCode())) {
dept.setDeptCode(existing.getDeptCode());
dept.setBelongCompanyCode(existing.getDeptCode());
usedCodes.add(existing.getDeptCode());
return;
}
int serial = DeptCodeUtil.nextSerial(OAConvertConstant.OA_SYNC_ROOT_DEPT_CODE, usedCodes);
String deptCode = DeptCodeUtil.formatChildCode(OAConvertConstant.OA_SYNC_ROOT_DEPT_CODE, serial);
while (usedCodes.contains(deptCode)) {
serial++;
deptCode = DeptCodeUtil.formatChildCode(OAConvertConstant.OA_SYNC_ROOT_DEPT_CODE, serial);
}
usedCodes.add(deptCode);
dept.setDeptCode(deptCode);
dept.setBelongCompanyCode(deptCode);
}
/**
* 部门编码:所属公司编码+三位数字;已有合规编码则复用
*/
private void assignDepartmentCode(Dept dept, Map<String, Dept> existingByOaId, Map<String, Dept> companyByOaId,
Map<String, Set<String>> usedCodesByCompany, Map<String, Integer> nextSerialByCompany) {
Dept existing = existingByOaId.get(dept.getOaId());
Dept belongCompany = null;
if (StringUtils.isNotBlank(dept.getBelongCompanyCode())) {
belongCompany = companyByOaId.values().stream()
.filter(company -> StringUtils.equals(company.getDeptCode(), dept.getBelongCompanyCode())
|| StringUtils.equals(company.getOaId(), dept.getBelongCompanyCode()))
.findFirst()
.orElse(null);
}
if (belongCompany == null && existing != null && StringUtils.isNotBlank(existing.getBelongCompanyCode())) {
String belongCode = existing.getBelongCompanyCode();
belongCompany = companyByOaId.values().stream()
.filter(company -> StringUtils.equals(company.getDeptCode(), belongCode))
.findFirst()
.orElse(null);
}
if (belongCompany == null) {
return;
}
final Dept resolvedCompany = belongCompany;
final String companyCode = resolvedCompany.getDeptCode();
dept.setBelongCompanyCode(companyCode);
if (existing != null && DeptCodeUtil.matchesChildCode(companyCode, existing.getDeptCode())) {
dept.setDeptCode(existing.getDeptCode());
usedCodesByCompany.computeIfAbsent(companyCode, key -> new HashSet<>()).add(existing.getDeptCode());
return;
}
Set<String> usedCodes = usedCodesByCompany.computeIfAbsent(companyCode, key -> new HashSet<>());
int serial = nextSerialByCompany.computeIfAbsent(companyCode,
key -> DeptCodeUtil.nextSerial(companyCode, usedCodes));
String deptCode = DeptCodeUtil.formatChildCode(companyCode, serial);
while (usedCodes.contains(deptCode)) {
serial++;
deptCode = DeptCodeUtil.formatChildCode(companyCode, serial);
}
nextSerialByCompany.put(companyCode, serial + 1);
usedCodes.add(deptCode);
dept.setDeptCode(deptCode);
}
/**
* 按 oaId 加载已存在组织
*/
private Map<String, Dept> loadExistingByOaId(DeptCategory deptCategory) {
List<Dept> deptList = deptService.list(Wrappers.<Dept>lambdaQuery()
.eq(Dept::getDeptCategory, deptCategory.getCode())
.isNotNull(Dept::getOaId)
.ne(Dept::getOaId, "")
.select(Dept::getId, Dept::getDeptCode, Dept::getOaModified, Dept::getParentId,
Dept::getOaId, Dept::getBelongCompanyCode, Dept::getParentCode, Dept::getOaSupSubComId));
Map<String, Dept> byOaId = new HashMap<>();
for (Dept dept : deptList) {
if (StringUtils.isNotBlank(dept.getOaId())) {
byOaId.put(dept.getOaId(), dept);
}
}
return byOaId;
}
/**
* 已占用的公司编码(GWWLxxx)
*/
private Map<String, Dept> loadCompanyCodeOwnerMap() {
List<Dept> companyList = deptService.list(Wrappers.<Dept>lambdaQuery()
.eq(Dept::getDeptCategory, DeptCategory.COMPANY.getCode())
.likeRight(Dept::getDeptCode, OAConvertConstant.OA_SYNC_ROOT_DEPT_CODE)
.select(Dept::getId, Dept::getDeptCode, Dept::getOaId));
Map<String, Dept> codeMap = new HashMap<>();
for (Dept dept : companyList) {
if (DeptCodeUtil.isCompanyCode(dept.getDeptCode())) {
codeMap.put(dept.getDeptCode(), dept);
}
}
return codeMap;
}
/**
* 已同步公司:oaId → 公司
*/
private Map<String, Dept> loadCompanyByOaId() {
List<Dept> companyList = deptService.list(Wrappers.<Dept>lambdaQuery()
.eq(Dept::getDeptCategory, DeptCategory.COMPANY.getCode())
.isNotNull(Dept::getOaId)
.ne(Dept::getOaId, ""));
Map<String, Dept> byOaId = new HashMap<>();
for (Dept dept : companyList) {
if (StringUtils.isNotBlank(dept.getOaId())) {
byOaId.put(dept.getOaId(), dept);
}
}
return byOaId;
}
/**
* 持久化同步数据:按 oaId 匹配;不存在则新增;存在且 oaModified 不一致才修改
*/
private OrgSyncCount persistSyncedDepts(List<Dept> allParam, Map<String, Dept> existingByOaId,
Map<String, Long> deptIdByCode, DeptCategory deptCategory,
int filteredSkipCount) {
Set<Long> existsDeptIds = existingByOaId.values().stream()
.map(Dept::getId)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
allParam.forEach(dept -> {
if (deptMap.containsKey(dept.getDeptCode())) {
// 根据部门编码获取对应的部门id
dept.setId(deptMap.get(dept.getDeptCode()));
Dept existing = existingByOaId.get(dept.getOaId());
if (existing != null && existing.getId() != null) {
dept.setId(existing.getId());
} else if (StringUtils.isNotBlank(dept.getDeptCode()) && deptIdByCode.containsKey(dept.getDeptCode())) {
dept.setId(deptIdByCode.get(dept.getDeptCode()));
} else {
// 没有就生成一个id
dept.setId(DefaultIdentifierGenerator.getInstance().nextId(null));
deptMap.put(dept.getDeptCode(), dept.getId());
}
if (StringUtils.isNotBlank(dept.getDeptCode())) {
deptIdByCode.put(dept.getDeptCode(), dept.getId());
}
});
// 重新把没有父id的数据设置一下父id;上级尚未入库时,新增记录先挂到根节点,全部分批完成后重建层级并清理无法挂载的数据
int unresolvedParentCount = 0;
for (Dept dept : allParam) {
if (dept.getParentId() != null) {
continue;
}
Long parentId = deptMap.get(dept.getParentCode());
Long parentId = StringUtils.isNotBlank(dept.getParentCode()) ? deptIdByCode.get(dept.getParentCode()) : null;
if (parentId != null) {
dept.setParentId(parentId);
continue;
@@ -615,11 +925,10 @@ public class OASyncServiceImpl implements IOASyncService {
deptCategory.getName(), unresolvedParentCount);
}
// 父id不为空才新增;已存在的记录即使父id未解析也更新(空父id不会覆盖原值)
List<Dept> list = allParam.stream()
.filter(dept -> StringUtils.isNotBlank(dept.getDeptCode()))
.filter(dept -> dept.getParentId() != null || existsDeptIds.contains(dept.getId()))
.toList();
// 不存在的新增
List<Dept> addList = list.stream()
.filter(dept -> !existsDeptIds.contains(dept.getId()))
.toList();
@@ -627,18 +936,48 @@ public class OASyncServiceImpl implements IOASyncService {
ComposeLogUtil.getLastLog().info("批量新增{}:{}", deptCategory.getName(), addList.size());
deptService.saveBatch(addList);
}
// 存在的修改
List<Dept> updateList = list.stream()
.filter(dept -> existsDeptIds.contains(dept.getId()))
.filter(dept -> !shouldSkipOaUpdate(existingByOaId.get(dept.getOaId()), dept))
.toList();
if (CollectionUtil.isNotEmpty(updateList)) {
ComposeLogUtil.getLastLog().info("批量修改{}:{}", deptCategory.getName(), updateList.size());
deptService.updateBatchById(updateList);
}
// 返回仍未保存的数据
return allParam.stream()
.filter(dept -> dept.getParentId() == null && !existsDeptIds.contains(dept.getId()))
int unchangedCount = (int) list.stream()
.filter(dept -> existsDeptIds.contains(dept.getId()))
.filter(dept -> shouldSkipOaUpdate(existingByOaId.get(dept.getOaId()), dept))
.count();
List<Dept> notHandledList = allParam.stream()
.filter(dept -> StringUtils.isBlank(dept.getDeptCode())
|| (dept.getParentId() == null && !existsDeptIds.contains(dept.getId())))
.toList();
int syncedCount = addList.size() + updateList.size();
int skippedCount = filteredSkipCount + unchangedCount + notHandledList.size();
if (unchangedCount > 0) {
ComposeLogUtil.getLastLog().info("跳过未变更{}:{}", deptCategory.getName(), unchangedCount);
}
return new OrgSyncCount(syncedCount, skippedCount, notHandledList);
}
/**
* oaModified 一致则跳过更新;任一侧为空无法确认一致,执行更新以补齐字段。
* 组织编码已按新规则重算且与库中不一致时,即使 modified 相同也要更新。
*/
private boolean shouldSkipOaUpdate(Dept existing, Dept incoming) {
if (existing == null) {
return false;
}
if (incoming != null && StringUtils.isNotBlank(incoming.getDeptCode())
&& !StringUtils.equals(existing.getDeptCode(), incoming.getDeptCode())) {
return false;
}
String localModified = StringUtils.trimToEmpty(existing.getOaModified());
String remoteModified = StringUtils.trimToEmpty(incoming == null ? null : incoming.getOaModified());
if (localModified.isEmpty() || remoteModified.isEmpty()) {
return false;
}
return localModified.equals(remoteModified);
}
/**
@@ -683,6 +1022,8 @@ public class OASyncServiceImpl implements IOASyncService {
if (syncAll) {
companyList = deptService.list(Wrappers.<Dept>lambdaQuery()
.eq(Dept::getDeptCategory, DeptCategory.COMPANY.getCode())
.isNotNull(Dept::getOaId)
.ne(Dept::getOaId, "")
);
} else {
Set<String> companyNames = this.getCompanyNames();
@@ -692,6 +1033,8 @@ public class OASyncServiceImpl implements IOASyncService {
companyList = deptService.list(Wrappers.<Dept>lambdaQuery()
.in(Dept::getDeptName, companyNames)
.eq(Dept::getDeptCategory, DeptCategory.COMPANY.getCode())
.isNotNull(Dept::getOaId)
.ne(Dept::getOaId, "")
);
}
return companyList.stream()
@@ -792,13 +1135,20 @@ public class OASyncServiceImpl implements IOASyncService {
return Collections.emptySet();
}
// 查询父部门编码是根公司的,部门类型的,根公司下部门名称的部门
Dept rootCompany = deptService.getOne(Wrappers.<Dept>lambdaQuery()
.eq(Dept::getOaId, rootCompanyId)
.eq(Dept::getDeptCategory, DeptCategory.COMPANY.getCode())
.last("limit 1"), false);
if (rootCompany == null || StringUtils.isBlank(rootCompany.getDeptCode())) {
return Collections.emptySet();
}
return deptService.list(Wrappers.<Dept>lambdaQuery()
.in(Dept::getDeptName, rootCompanyDeptNames)
.eq(Dept::getDeptCategory, DeptCategory.DEPT.getCode())
.eq(Dept::getParentCode, OAConvertConstant.COMPANY_OA_PREFIX + rootCompanyId)
.eq(Dept::getParentCode, rootCompany.getDeptCode())
).stream()
.filter(dept -> StringUtils.isNotBlank(dept.getDeptCode()))
.map(dept -> dept.getDeptCode().replace(OAConvertConstant.DEPARTMENT_OA_PREFIX, ""))
.map(Dept::getOaId)
.filter(StringUtils::isNotBlank)
.collect(Collectors.toSet());
}
@@ -821,11 +1171,11 @@ public class OASyncServiceImpl implements IOASyncService {
ComposeLogUtil.getLastLog().warn("未查询到根公司 名称:{}", companyName);
return null;
}
if (StringUtils.isBlank(dept.getDeptCode())) {
if (StringUtils.isBlank(dept.getOaId()) && StringUtils.isBlank(dept.getDeptCode())) {
ComposeLogUtil.getLastLog().warn("根公司编码为空:{}", companyName);
return null;
}
// 部门编码去掉前缀,就是oa的id
return dept.getDeptCode().replace(OAConvertConstant.COMPANY_OA_PREFIX, "");
return StringUtils.isNotBlank(dept.getOaId()) ? dept.getOaId()
: dept.getDeptCode().replace(OAConvertConstant.COMPANY_OA_PREFIX, "");
}
}
@@ -86,7 +86,7 @@ public class OaUserListSyncHelper {
private final IRoleService roleService;
/**
* 从人员数据提取二级公司、三级部门,并挂到「桂物物流集团」下
* 从人员数据提取二级公司、三级部门,并挂到集团顶级(id=135/GWWL) 下
*
* @param oaPersons OA人员
* @return 组织索引
@@ -249,6 +249,7 @@ public class OaUserListSyncHelper {
});
Map<String, Long> userMap = new HashMap<>();
Set<Long> existsUserIds = new HashSet<>();
Set<Long> unchangedUserIds = new HashSet<>();
users.forEach(user -> {
User existingUser = existingByAccount.get(user.getAccount());
if (existingUser == null && StringUtils.isNotBlank(user.getPhone())) {
@@ -258,6 +259,9 @@ public class OaUserListSyncHelper {
user.setId(existingUser.getId());
user.setPassword(null);
existsUserIds.add(existingUser.getId());
if (shouldSkipOaUpdate(existingUser, user)) {
unchangedUserIds.add(existingUser.getId());
}
} else {
user.setId(DefaultIdentifierGenerator.getInstance().nextId(null));
user.setPostId("-1");
@@ -279,12 +283,18 @@ public class OaUserListSyncHelper {
}
List<User> updateUsers = users.stream()
.filter(user -> existsUserIds.contains(user.getId()))
.filter(user -> !unchangedUserIds.contains(user.getId()))
.toList();
if (CollectionUtil.isNotEmpty(updateUsers)) {
ComposeLogUtil.getLastLog().info("批量修改用户:{}", updateUsers.size());
userService.updateBatchById(updateUsers);
}
if (!unchangedUserIds.isEmpty()) {
ComposeLogUtil.getLastLog().info("跳过未变更用户:{}", unchangedUserIds.size());
}
ComposeLogUtil.getLastLog().info("缺少账号已跳过的人员:{}", skippedCount);
int syncedCount = addUsers.size() + updateUsers.size();
skippedCount += unchangedUserIds.size();
if (userMap.isEmpty()) {
return new PersonSyncCount(0, skippedCount);
}
@@ -295,7 +305,13 @@ public class OaUserListSyncHelper {
.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)))
.filter(oaPerson -> {
String account = userConvert.resolveAccount(oaPerson);
if (!userMap.containsKey(account)) {
return false;
}
return !unchangedUserIds.contains(userMap.get(account));
})
.map(oaPerson -> this.buildUserDept(oaPerson, userMap, orgIndex))
.filter(Objects::nonNull)
.toList();
@@ -333,6 +349,7 @@ public class OaUserListSyncHelper {
.collect(Collectors.toSet());
String defaultRoleId = getDefaultRoleId();
List<User> updateUserParams = list.stream()
.filter(userDeptIds -> !unchangedUserIds.contains(userDeptIds.getUserId()))
.filter(userDeptIds -> StringUtils.isNotBlank(userDeptIds.getDeptIds()) && userDeptIds.getDeptIds().length() <= MAX_DEPT_ID_LENGTH)
.map(userDeptIds -> {
User user = new User();
@@ -347,37 +364,26 @@ public class OaUserListSyncHelper {
if (CollectionUtil.isNotEmpty(updateUserParams)) {
userService.updateBatchById(updateUserParams);
}
return new PersonSyncCount(users.size(), skippedCount);
return new PersonSyncCount(syncedCount, skippedCount);
}
/**
* oaModified 一致则跳过更新;任一侧为空无法确认一致,执行更新以补齐字段
*/
private boolean shouldSkipOaUpdate(User existing, User incoming) {
if (existing == null) {
return false;
}
String localModified = StringUtils.trimToEmpty(existing.getOaModified());
String remoteModified = StringUtils.trimToEmpty(incoming == null ? null : incoming.getOaModified());
if (localModified.isEmpty() || remoteModified.isEmpty()) {
return false;
}
return localModified.equals(remoteModified);
}
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;
return deptService.ensureOaSyncRootDept();
}
private Dept upsertOrg(String name, String oaCode, Dept existing, Dept parent, String tenantId,
@@ -29,7 +29,8 @@ import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tool.utils.BeanUtil;
@@ -44,6 +45,7 @@ import org.springblade.system.pojo.entity.Region;
import org.springblade.system.pojo.vo.PortTerminalVO;
import org.springblade.system.service.IPortTerminalService;
import org.springblade.system.service.IRegionService;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -66,8 +68,9 @@ import java.util.regex.Pattern;
*
* @author Chill
*/
@Slf4j
@Service
@AllArgsConstructor
@RequiredArgsConstructor
public class PortTerminalServiceImpl extends BaseServiceImpl<PortTerminalMapper, PortTerminal> implements IPortTerminalService {
private static final String CATEGORY_PORT = "港口";
@@ -76,8 +79,12 @@ public class PortTerminalServiceImpl extends BaseServiceImpl<PortTerminalMapper,
private static final String SOURCE_INITIAL_OLD = "初始导入";
private static final String SOURCE_BATCH = "批量导入";
private static final String SOURCE_MANUAL = "手工导入";
private static final String SOURCE_MANUAL_OLD = "手动录入";
private static final int STATUS_ENABLED = 1;
private static final int STATUS_DISABLED = 2;
private static final int PROVINCE_REGION_LEVEL = 1;
private static final int CITY_REGION_LEVEL = 2;
private static final int DISTRICT_REGION_LEVEL = 3;
private static final int CODE_MAX_LENGTH = 30;
private static final int NAME_MAX_LENGTH = 100;
private static final int REGION_MAX_LENGTH = 50;
@@ -102,6 +109,7 @@ public class PortTerminalServiceImpl extends BaseServiceImpl<PortTerminalMapper,
@Transactional(rollbackFor = Exception.class)
public boolean submit(PortTerminal portTerminal) {
prepare(portTerminal, SOURCE_MANUAL);
prepareSubmitTarget(portTerminal);
validate(portTerminal);
return saveOrUpdate(portTerminal);
}
@@ -206,7 +214,9 @@ public class PortTerminalServiceImpl extends BaseServiceImpl<PortTerminalMapper,
? PORT_CODE_PATTERN.matcher(code).matches()
: TERMINAL_CODE_PATTERN.matcher(code).matches();
if (!codeValid) {
String message = CATEGORY_PORT.equals(category) ? "港口编码为5位大写字母" : "码头编码格式为港口编码-码头标识";
String message = CATEGORY_PORT.equals(category)
? "港口编码为5位大写字母,当前为「" + code + "」"
: "码头编码格式为港口编码-码头标识,当前为「" + code + "」";
failureList.add(buildFailure(data, index, message));
continue;
}
@@ -239,8 +249,11 @@ public class PortTerminalServiceImpl extends BaseServiceImpl<PortTerminalMapper,
portTerminal.setDataSource(SOURCE_BATCH);
portTerminal.setStatus(STATUS_ENABLED);
prepare(portTerminal, SOURCE_BATCH);
prepareSubmitTarget(portTerminal);
validate(portTerminal);
save(portTerminal);
if (!saveOrUpdate(portTerminal)) {
throw new ServiceException("港口码头保存失败");
}
batchPortMap.put(portTerminal.getCode(), portTerminal);
} catch (Exception exception) {
failureList.add(buildFailure(data, index, resolveMessage(exception)));
@@ -265,8 +278,11 @@ public class PortTerminalServiceImpl extends BaseServiceImpl<PortTerminalMapper,
portTerminal.setDataSource(SOURCE_BATCH);
portTerminal.setStatus(STATUS_ENABLED);
prepareTerminal(portTerminal, batchPortMap);
prepareSubmitTarget(portTerminal);
validate(portTerminal);
save(portTerminal);
if (!saveOrUpdate(portTerminal)) {
throw new ServiceException("港口码头保存失败");
}
} catch (ParentPortNotFoundException exception) {
// 上级港口就声明在本文件里,只是那一行自己校验失败(已被标红)。
// 此时码头行本身没有问题,不再连带报错,避免用户看到"两行都错"的假象。
@@ -308,6 +324,12 @@ public class PortTerminalServiceImpl extends BaseServiceImpl<PortTerminalMapper,
if (Func.isNotEmpty(parent.getCountry())) {
portTerminal.setCountry(parent.getCountry());
}
if (Func.isNotEmpty(parent.getProvinceCode())) {
portTerminal.setProvinceCode(parent.getProvinceCode());
}
if (Func.isNotEmpty(parent.getProvinceName())) {
portTerminal.setProvinceName(parent.getProvinceName());
}
if (Func.isNotEmpty(parent.getCity())) {
portTerminal.setCity(parent.getCity());
}
@@ -341,10 +363,59 @@ public class PortTerminalServiceImpl extends BaseServiceImpl<PortTerminalMapper,
}
/**
* 解析异常信息,非业务异常统一提示导入失败。
* 解析异常信息:优先取业务异常,其次解包数据访问异常,避免失败明细只剩「导入失败」。
*/
private String resolveMessage(Exception exception) {
return exception instanceof ServiceException ? exception.getMessage() : "导入失败";
ServiceException serviceException = findCause(exception, ServiceException.class);
if (serviceException != null && Func.isNotEmpty(serviceException.getMessage())
&& !(serviceException instanceof ImportFailureException)) {
return serviceException.getMessage();
}
DataAccessException dataAccessException = findCause(exception, DataAccessException.class);
if (dataAccessException != null) {
Throwable root = rootCause(dataAccessException);
String rootMessage = root.getMessage();
log.warn("港口码头导入数据访问异常", exception);
if (Func.isNotEmpty(rootMessage)) {
if (rootMessage.contains("Duplicate") || rootMessage.contains("duplicate") || rootMessage.contains("uk_port_terminal_code")) {
return "该编码已存在";
}
return "数据保存失败:" + shortenMessage(rootMessage);
}
return "数据保存失败";
}
Throwable root = rootCause(exception);
String rootMessage = root.getMessage();
log.warn("港口码头导入非业务异常, type={}", root.getClass().getName(), exception);
if (Func.isNotEmpty(rootMessage)) {
return shortenMessage(rootMessage);
}
return "导入失败:" + root.getClass().getSimpleName();
}
private <T extends Throwable> T findCause(Throwable throwable, Class<T> type) {
for (Throwable current = throwable; current != null; current = current.getCause()) {
if (type.isInstance(current)) {
return type.cast(current);
}
if (current.getCause() == current) {
break;
}
}
return null;
}
private Throwable rootCause(Throwable throwable) {
Throwable root = throwable;
while (root.getCause() != null && root.getCause() != root) {
root = root.getCause();
}
return root;
}
private String shortenMessage(String message) {
String value = trimToEmpty(message);
return value.length() > 200 ? value.substring(0, 200) + "..." : value;
}
@Override
@@ -370,6 +441,26 @@ public class PortTerminalServiceImpl extends BaseServiceImpl<PortTerminalMapper,
return validRange(value, min, max) ? value.setScale(6, RoundingMode.HALF_UP) : null;
}
/**
* 编码已存在且为软删除时:取消软删除并复用原主键,后续按更新落库;
* 编码存在且未删除时仍报「该编码已存在」。
*/
private void prepareSubmitTarget(PortTerminal portTerminal) {
if (Func.isNotEmpty(portTerminal.getId())) {
return;
}
PortTerminal existingPortTerminal = baseMapper.selectByCodeIncludingDeleted(portTerminal.getCode());
if (existingPortTerminal == null) {
return;
}
if (!Objects.equals(existingPortTerminal.getIsDeleted(), 1)) {
throw new ServiceException("该编码已存在");
}
baseMapper.restoreById(existingPortTerminal.getId());
portTerminal.setId(existingPortTerminal.getId());
portTerminal.setIsDeleted(0);
}
private void prepare(PortTerminal portTerminal, String defaultDataSource) {
prepare(portTerminal, defaultDataSource, false);
}
@@ -386,6 +477,8 @@ public class PortTerminalServiceImpl extends BaseServiceImpl<PortTerminalMapper,
portTerminal.setCategory(trimToEmpty(portTerminal.getCategory()));
portTerminal.setName(trimToEmpty(portTerminal.getName()));
portTerminal.setCountry(trimToEmpty(portTerminal.getCountry()));
portTerminal.setProvinceCode(trimToNull(portTerminal.getProvinceCode()));
portTerminal.setProvinceName(trimToNull(portTerminal.getProvinceName()));
portTerminal.setCity(trimToEmpty(portTerminal.getCity()));
portTerminal.setDistrictCode(trimToNull(portTerminal.getDistrictCode()));
portTerminal.setDistrictName(trimToNull(portTerminal.getDistrictName()));
@@ -431,68 +524,99 @@ public class PortTerminalServiceImpl extends BaseServiceImpl<PortTerminalMapper,
if (!CATEGORY_PORT.equals(parent.getCategory())) {
throw new ServiceException("上级港口类型不正确");
}
portTerminal.setParentId(parent.getId());
portTerminal.setParentCode(parent.getCode());
portTerminal.setParentName(parent.getName());
// 父港口区域信息为空时保留码头自身填写的值,避免历史数据(区县为空)导致码头无法导入。
if (Func.isNotEmpty(parent.getCountry())) {
portTerminal.setCountry(parent.getCountry());
}
if (Func.isNotEmpty(parent.getCity())) {
portTerminal.setCity(parent.getCity());
}
if (Func.isNotEmpty(parent.getDistrictCode())) {
portTerminal.setDistrictCode(parent.getDistrictCode());
portTerminal.setRegionCode(parent.getDistrictCode());
} else if (Func.isNotEmpty(portTerminal.getRegionCode())) {
applyParent(portTerminal, parent);
if (Func.isEmpty(portTerminal.getDistrictCode()) && Func.isNotEmpty(portTerminal.getRegionCode())) {
portTerminal.setDistrictCode(portTerminal.getRegionCode());
}
if (Func.isNotEmpty(parent.getDistrictName())) {
portTerminal.setDistrictName(parent.getDistrictName());
}
}
private void fillRegion(PortTerminal portTerminal) {
Region province = null;
if (Func.isNotEmpty(portTerminal.getProvinceCode())) {
province = regionService.getById(portTerminal.getProvinceCode());
}
if (Func.isEmpty(province) && Func.isNotEmpty(portTerminal.getProvinceName())) {
province = findRegionByName(portTerminal.getProvinceName(), PROVINCE_REGION_LEVEL, null);
}
if (Func.isEmpty(province)) {
throw new ServiceException("请选择所属省份");
}
Region city = null;
if (Func.isNotEmpty(portTerminal.getCity())) {
city = findRegionByName(portTerminal.getCity(), CITY_REGION_LEVEL, province.getCode());
}
if (Func.isEmpty(city)) {
throw new ServiceException("请选择城市");
}
if (!Objects.equals(city.getParentCode(), province.getCode())) {
throw new ServiceException("所属城市与所属省份不匹配");
}
Region district = null;
if (Func.isNotEmpty(portTerminal.getDistrictCode())) {
district = regionService.getById(portTerminal.getDistrictCode());
}
if (Func.isEmpty(district) && Func.isNotEmpty(portTerminal.getDistrictName())) {
if (Func.isNotEmpty(portTerminal.getCity())) {
List<Region> cityList = regionService.list(Wrappers.<Region>lambdaQuery()
.eq(Region::getName, portTerminal.getCity())
.eq(Region::getRegionLevel, 2));
for (Region city : cityList) {
district = regionService.getOne(Wrappers.<Region>lambdaQuery()
.eq(Region::getParentCode, city.getCode())
.eq(Region::getName, portTerminal.getDistrictName()), false);
if (Func.isNotEmpty(district)) {
break;
}
}
}
if (Func.isEmpty(district)) {
district = regionService.getOne(Wrappers.<Region>lambdaQuery()
.eq(Region::getName, portTerminal.getDistrictName())
.eq(Region::getRegionLevel, 3), false);
}
district = findRegionByName(portTerminal.getDistrictName(), DISTRICT_REGION_LEVEL, city.getCode());
}
if (Func.isEmpty(district)) {
throw new ServiceException("请选择区县");
}
Region city = regionService.getById(district.getParentCode());
if (Func.isEmpty(city)) {
throw new ServiceException("区县所属城市不存在");
}
if (Func.isNotEmpty(portTerminal.getCity()) && !Objects.equals(portTerminal.getCity(), city.getName())) {
throw new ServiceException("区县与城市不匹配");
if (!Objects.equals(district.getParentCode(), city.getCode())) {
throw new ServiceException("所属区县与所属城市不匹配");
}
portTerminal.setProvinceCode(province.getCode());
portTerminal.setProvinceName(province.getName());
portTerminal.setCity(city.getName());
portTerminal.setDistrictCode(district.getCode());
portTerminal.setDistrictName(district.getName());
portTerminal.setRegionCode(district.getCode());
}
/**
* 按名称查找区划,兼容「福建/福建省」「泉州/泉州市」等简写。
*/
private Region findRegionByName(String name, int regionLevel, String parentCode) {
String normalized = trimToEmpty(name);
if (Func.isEmpty(normalized)) {
return null;
}
for (String candidate : regionNameCandidates(normalized)) {
LambdaQueryWrapper<Region> queryWrapper = Wrappers.<Region>lambdaQuery()
.eq(Region::getRegionLevel, regionLevel)
.eq(Region::getName, candidate);
if (Func.isNotEmpty(parentCode)) {
queryWrapper.eq(Region::getParentCode, parentCode);
}
Region region = regionService.getOne(queryWrapper, false);
if (Func.isNotEmpty(region)) {
return region;
}
}
return null;
}
private List<String> regionNameCandidates(String name) {
List<String> candidates = new ArrayList<>();
candidates.add(name);
if (name.endsWith("省") || name.endsWith("市") || name.endsWith("区") || name.endsWith("县") || name.endsWith("州")) {
String shortName = name.substring(0, name.length() - 1);
if (Func.isNotEmpty(shortName) && !candidates.contains(shortName)) {
candidates.add(shortName);
}
} else {
for (String suffix : List.of("省", "市", "区", "县", "州")) {
String fullName = name + suffix;
if (!candidates.contains(fullName)) {
candidates.add(fullName);
}
}
}
return candidates;
}
private void validate(PortTerminal portTerminal) {
if (!CATEGORY_PORT.equals(portTerminal.getCategory()) && !CATEGORY_TERMINAL.equals(portTerminal.getCategory())) {
throw new ServiceException("类型只能为港口或码头");
@@ -506,16 +630,17 @@ public class PortTerminalServiceImpl extends BaseServiceImpl<PortTerminalMapper,
validateLength(portTerminal.getCode(), CODE_MAX_LENGTH, "编码不能超过30字");
validateLength(portTerminal.getName(), NAME_MAX_LENGTH, "港口/码头名称不能超过100字");
validateLength(portTerminal.getCountry(), REGION_MAX_LENGTH, "国家不能超过50字");
validateLength(portTerminal.getProvinceName(), REGION_MAX_LENGTH, "所属省份不能超过50字");
validateLength(portTerminal.getCity(), REGION_MAX_LENGTH, "城市不能超过50字");
validateLength(portTerminal.getDistrictName(), REGION_MAX_LENGTH, "区县不能超过50字");
validateLength(portTerminal.getRegionCode(), REGION_CODE_MAX_LENGTH, "行政区划编码不能超过32字");
validateLength(portTerminal.getDetailAddress(), DETAIL_ADDRESS_MAX_LENGTH, "详细地址不能超过255字");
validateLength(portTerminal.getRemark(), REMARK_MAX_LENGTH, "备注不能超过200个字");
if (CATEGORY_PORT.equals(portTerminal.getCategory()) && !PORT_CODE_PATTERN.matcher(portTerminal.getCode()).matches()) {
throw new ServiceException("港口编码为5位大写字母");
throw new ServiceException("港口编码为5位大写字母,当前为「" + portTerminal.getCode() + "」");
}
if (CATEGORY_TERMINAL.equals(portTerminal.getCategory()) && !TERMINAL_CODE_PATTERN.matcher(portTerminal.getCode()).matches()) {
throw new ServiceException("码头编码格式为港口编码-码头标识");
throw new ServiceException("码头编码格式为港口编码-码头标识,当前为「" + portTerminal.getCode() + "」");
}
if (CATEGORY_TERMINAL.equals(portTerminal.getCategory()) && !portTerminal.getCode().startsWith(portTerminal.getParentCode() + "-")) {
throw new ServiceException("码头编码必须以所属港口编码开头");
@@ -523,12 +648,24 @@ public class PortTerminalServiceImpl extends BaseServiceImpl<PortTerminalMapper,
if (Func.isEmpty(portTerminal.getCountry())) {
throw new ServiceException("国家不能为空");
}
if (Func.isEmpty(portTerminal.getProvinceCode()) && Func.isEmpty(portTerminal.getProvinceName())) {
throw new ServiceException("所属省份不能为空");
}
if (Func.isEmpty(portTerminal.getCity())) {
throw new ServiceException("城市不能为空");
}
if (Func.isEmpty(portTerminal.getDistrictCode())) {
throw new ServiceException("区县不能为空");
}
if (Func.isEmpty(portTerminal.getDetailAddress())) {
throw new ServiceException("详细地址不能为空");
}
if (Func.isEmpty(portTerminal.getLongitude())) {
throw new ServiceException("经度不能为空");
}
if (Func.isEmpty(portTerminal.getLatitude())) {
throw new ServiceException("纬度不能为空");
}
validateDataSource(portTerminal.getDataSource());
validateStatus(portTerminal.getStatus());
validateRange(portTerminal.getLongitude(), MIN_LONGITUDE, MAX_LONGITUDE, "经度范围为 -180 到 180");
@@ -593,7 +730,13 @@ public class PortTerminalServiceImpl extends BaseServiceImpl<PortTerminalMapper,
private String normalizeDataSource(String dataSource) {
String value = trimToEmpty(dataSource);
return SOURCE_INITIAL_OLD.equals(value) ? SOURCE_INITIAL : value;
if (SOURCE_INITIAL_OLD.equals(value)) {
return SOURCE_INITIAL;
}
if (SOURCE_MANUAL_OLD.equals(value)) {
return SOURCE_MANUAL;
}
return value;
}
private void validateEnabledTerminal(Long parentId) {
@@ -611,7 +754,7 @@ public class PortTerminalServiceImpl extends BaseServiceImpl<PortTerminalMapper,
}
private String trimToEmpty(String value) {
return value == null ? "" : value.trim();
return value == null ? "" : value.replace("\uFEFF", "").strip();
}
private String trimToNull(String value) {
@@ -102,6 +102,7 @@ public class RailwayStationServiceImpl extends BaseServiceImpl<RailwayStationMap
@Transactional(rollbackFor = Exception.class)
public boolean submit(RailwayStation railwayStation) {
prepare(railwayStation, SOURCE_MANUAL);
prepareSubmitTarget(railwayStation);
validate(railwayStation);
return saveOrUpdate(railwayStation);
}
@@ -170,7 +171,8 @@ public class RailwayStationServiceImpl extends BaseServiceImpl<RailwayStationMap
throw new org.springblade.common.excel.ImportFailureException(data);
}
for (RailwayStation railwayStation : railwayStationList) {
prepareImportTarget(railwayStation);
// 编码/TMIS 命中逻辑删除记录时复用原主键,恢复后更新,避免唯一索引冲突。
prepareSubmitTarget(railwayStation);
if (!saveOrUpdate(railwayStation)) {
throw new ServiceException("铁路车站保存失败");
}
@@ -178,11 +180,18 @@ public class RailwayStationServiceImpl extends BaseServiceImpl<RailwayStationMap
return errorList;
}
private void prepareImportTarget(RailwayStation railwayStation) {
/**
* 编码或 TMIS 已存在且为软删除时:取消软删除并复用原主键,后续按更新落库;
* 存在且未删除时仍报「该编码已存在」。
*/
private void prepareSubmitTarget(RailwayStation railwayStation) {
if (Func.isNotEmpty(railwayStation.getId())) {
return;
}
RailwayStation existingRailwayStation = baseMapper.selectByCodeIncludingDeleted(railwayStation.getCode());
if (existingRailwayStation == null && Func.isNotEmpty(railwayStation.getTmisCode())) {
existingRailwayStation = baseMapper.selectByTmisCodeIncludingDeleted(railwayStation.getTmisCode());
}
if (existingRailwayStation == null) {
return;
}
@@ -207,7 +216,7 @@ public class RailwayStationServiceImpl extends BaseServiceImpl<RailwayStationMap
private void normalizeImportRailwayStation(RailwayStation railwayStation) {
railwayStation.setTmisCode(trimToEmpty(railwayStation.getTmisCode()));
railwayStation.setCode(CODE_PREFIX + railwayStation.getTmisCode());
railwayStation.setTelegraphCode(trimToEmpty(railwayStation.getTelegraphCode()).toUpperCase(Locale.ROOT));
railwayStation.setTelegraphCode(normalizeTelegraphCode(railwayStation.getTelegraphCode()));
railwayStation.setName(trimToEmpty(railwayStation.getName()));
railwayStation.setProvinceCode(trimToNull(railwayStation.getProvinceCode()));
railwayStation.setProvinceName(trimToNull(railwayStation.getProvinceName()));
@@ -247,9 +256,7 @@ public class RailwayStationServiceImpl extends BaseServiceImpl<RailwayStationMap
validateImportUnique(RailwayStation::getTmisCode, railwayStation.getTmisCode(), "该TMIS国标编码已存在", validationErrors);
validateImportUnique(RailwayStation::getCode, railwayStation.getCode(), "该编码已存在", validationErrors);
}
if (Func.isEmpty(railwayStation.getTelegraphCode())) {
addValidationError(validationErrors, "电报略码不能为空");
} else {
if (Func.isNotEmpty(railwayStation.getTelegraphCode())) {
if (!TELEGRAPH_CODE_PATTERN.matcher(railwayStation.getTelegraphCode()).matches()) {
addValidationError(validationErrors, "电报略码为3位大写字母");
}
@@ -377,7 +384,7 @@ public class RailwayStationServiceImpl extends BaseServiceImpl<RailwayStationMap
private void prepare(RailwayStation railwayStation, String defaultDataSource) {
railwayStation.setTmisCode(trimToEmpty(railwayStation.getTmisCode()));
railwayStation.setCode(CODE_PREFIX + railwayStation.getTmisCode());
railwayStation.setTelegraphCode(trimToEmpty(railwayStation.getTelegraphCode()).toUpperCase(Locale.ROOT));
railwayStation.setTelegraphCode(normalizeTelegraphCode(railwayStation.getTelegraphCode()));
railwayStation.setName(trimToEmpty(railwayStation.getName()));
railwayStation.setRailwayLine(trimToNull(railwayStation.getRailwayLine()));
railwayStation.setProvinceCode(trimToNull(railwayStation.getProvinceCode()));
@@ -410,10 +417,8 @@ public class RailwayStationServiceImpl extends BaseServiceImpl<RailwayStationMap
if (!TMIS_CODE_PATTERN.matcher(railwayStation.getTmisCode()).matches()) {
throw new ServiceException("TMIS国标编码为5位数字");
}
if (Func.isEmpty(railwayStation.getTelegraphCode())) {
throw new ServiceException("电报略码格式不正确或已存在");
}
if (!TELEGRAPH_CODE_PATTERN.matcher(railwayStation.getTelegraphCode()).matches()) {
if (Func.isNotEmpty(railwayStation.getTelegraphCode())
&& !TELEGRAPH_CODE_PATTERN.matcher(railwayStation.getTelegraphCode()).matches()) {
throw new ServiceException("电报略码格式不正确或已存在");
}
if (Func.isEmpty(railwayStation.getName())) {
@@ -446,7 +451,9 @@ public class RailwayStationServiceImpl extends BaseServiceImpl<RailwayStationMap
validateDataSource(railwayStation.getDataSource());
validateStatus(railwayStation.getStatus());
validateUnique(railwayStation, RailwayStation::getTmisCode, railwayStation.getTmisCode(), "该TMIS编码已存在");
validateUnique(railwayStation, RailwayStation::getTelegraphCode, railwayStation.getTelegraphCode(), "电报略码格式不正确或已存在");
if (Func.isNotEmpty(railwayStation.getTelegraphCode())) {
validateUnique(railwayStation, RailwayStation::getTelegraphCode, railwayStation.getTelegraphCode(), "电报略码格式不正确或已存在");
}
validateUnique(railwayStation, RailwayStation::getCode, railwayStation.getCode(), "该编码已存在");
}
@@ -562,6 +569,11 @@ public class RailwayStationServiceImpl extends BaseServiceImpl<RailwayStationMap
return trimValue.isEmpty() ? null : trimValue;
}
private String normalizeTelegraphCode(String value) {
String telegraphCode = trimToNull(value);
return telegraphCode == null ? null : telegraphCode.toUpperCase(Locale.ROOT);
}
private String normalizeDataSource(String dataSource) {
String value = trimToEmpty(dataSource);
if (SOURCE_INITIAL_OLD.equals(value)) {
@@ -18,9 +18,6 @@
* 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;
@@ -28,7 +25,6 @@ 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;
@@ -37,21 +33,21 @@ 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.cache.MpUserCache;
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.pojo.entity.MpUser;
import org.springblade.system.service.IMpUserService;
import org.springblade.system.service.IUserPhoneService;
import org.springblade.system.service.IUserService;
import org.springblade.system.utils.MpUserAuth;
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;
/**
* 用户手机号变更服务实现
* 小程序用户手机号变更服务实现(写入 blade_mp_user)
*
* @author Chill
*/
@@ -68,24 +64,22 @@ public class UserPhoneServiceImpl implements IUserPhoneService {
/**
* 原手机号已校验凭证(Redis)
*/
private static final String PHONE_CHANGE_VERIFIED_KEY = "blade:user:phone:change:verified:";
private static final String PHONE_CHANGE_VERIFIED_KEY = "blade:mp-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 IMpUserService mpUserService;
private final ISmsClient smsClient;
private final BladeRedis bladeRedis;
@Override
public R sendCode(String phone) {
assertMpLogin();
String normalizedPhone = normalizePhone(phone);
Long userId = AuthUtil.getUserId();
if (Func.isEmpty(userId)) {
throw new ServiceException("请先登录");
}
User currentUser = requireCurrentUser(userId);
MpUser currentUser = requireCurrentUser(userId);
String tenantId = Func.toStr(currentUser.getTenantId(), AuthUtil.getTenantId());
boolean isCurrentPhone = StringUtil.equals(normalizedPhone, Func.toStr(currentUser.getPhone()));
if (!isCurrentPhone) {
@@ -100,16 +94,14 @@ public class UserPhoneServiceImpl implements IUserPhoneService {
@Override
public boolean verifyOldPhone(PhoneVerifyDTO phoneVerify) {
assertMpLogin();
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);
MpUser currentUser = requireCurrentUser(userId);
String oldPhone = Func.toStr(currentUser.getPhone()).trim();
if (StringUtil.isBlank(oldPhone)) {
throw new ServiceException("当前账号未绑定手机号");
@@ -122,10 +114,8 @@ public class UserPhoneServiceImpl implements IUserPhoneService {
@Override
@Transactional(rollbackFor = Exception.class)
public boolean changePhone(PhoneChangeDTO phoneChange) {
assertMpLogin();
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("请先完成原手机号验证");
@@ -136,7 +126,7 @@ public class UserPhoneServiceImpl implements IUserPhoneService {
if (StringUtil.isBlank(id) || StringUtil.isBlank(code)) {
throw new ServiceException("请先获取并填写验证码");
}
User currentUser = requireCurrentUser(userId);
MpUser currentUser = requireCurrentUser(userId);
String oldPhone = Func.toStr(currentUser.getPhone()).trim();
if (StringUtil.equals(newPhone, oldPhone)) {
throw new ServiceException("新手机号不可与当前手机号相同");
@@ -145,27 +135,49 @@ public class UserPhoneServiceImpl implements IUserPhoneService {
assertPhoneAvailable(tenantId, newPhone, userId);
validateSms(tenantId, id, code, newPhone);
User updateUser = new User();
MpUser updateUser = new MpUser();
updateUser.setId(userId);
updateUser.setTenantId(tenantId);
updateUser.setPhone(newPhone);
updateUser.setName(currentUser.getName());
updateUser.setRealName(currentUser.getRealName());
updateUser.setIdentities(currentUser.getIdentities());
updateUser.setSex(currentUser.getSex());
updateUser.setDeptId(currentUser.getDeptId());
updateUser.setPostId(currentUser.getPostId());
updateUser.setAvatar(currentUser.getAvatar());
updateUser.setEmail(currentUser.getEmail());
updateUser.setRemark(currentUser.getRemark());
updateUser.setStatus(currentUser.getStatus());
// 账号若等于原手机号,同步更新,保证短信登录可用
if (StringUtil.isNotBlank(oldPhone) && StringUtil.equals(oldPhone, Func.toStr(currentUser.getAccount()))) {
assertAccountAvailable(tenantId, newPhone, userId);
updateUser.setAccount(newPhone);
} else {
updateUser.setAccount(currentUser.getAccount());
}
boolean updated = userService.updateById(updateUser);
boolean updated = mpUserService.updateUser(updateUser);
if (!updated) {
throw new ServiceException("手机号修改失败");
}
bladeRedis.del(PHONE_CHANGE_VERIFIED_KEY + userId);
CacheUtil.clear(USER_CACHE);
MpUserCache.clear();
return true;
}
private User requireCurrentUser(Long userId) {
User user = userService.getById(userId);
private void assertMpLogin() {
if (Func.isEmpty(AuthUtil.getUserId())) {
throw new ServiceException("请先登录");
}
if (!MpUserAuth.isMpUser()) {
throw new ServiceException("仅支持小程序用户修改手机号");
}
}
private MpUser requireCurrentUser(Long userId) {
MpUser user = mpUserService.getById(userId);
if (user == null) {
throw new ServiceException("用户不存在");
throw new ServiceException("小程序用户不存在");
}
return user;
}
@@ -178,11 +190,11 @@ public class UserPhoneServiceImpl implements IUserPhoneService {
}
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)
Long phoneCount = mpUserService.count(
Wrappers.<MpUser>lambdaQuery()
.eq(MpUser::getTenantId, tenantId)
.eq(MpUser::getPhone, phone)
.ne(MpUser::getId, excludeUserId)
);
if (phoneCount != null && phoneCount > 0L) {
throw new ServiceException(StringUtil.format("当前手机 [{}] 已存在!", phone));
@@ -190,11 +202,11 @@ public class UserPhoneServiceImpl implements IUserPhoneService {
}
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)
Long accountCount = mpUserService.count(
Wrappers.<MpUser>lambdaQuery()
.eq(MpUser::getTenantId, tenantId)
.eq(MpUser::getAccount, account)
.ne(MpUser::getId, excludeUserId)
);
if (accountCount != null && accountCount > 0L) {
throw new ServiceException(StringUtil.format("当前用户 [{}] 已存在!", account));
@@ -133,8 +133,12 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implement
@Override
public IPage<UserVO> selectPage(Map<String, Object> user, Query query) {
String account = Func.toStr(user.remove("account")).trim();
String realName = Func.toStr(user.remove("realName")).trim();
String phone = Func.toStr(user.remove("phone")).trim();
QueryWrapper<User> queryWrapper = Condition.getQueryWrapper(user, User.class);
applyTenantScope(queryWrapper);
applyUserFuzzyFilters(queryWrapper, account, realName, phone);
return UserWrapper.build().pageVO(page(Condition.getPage(query), queryWrapper));
}
@@ -335,6 +339,23 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implement
return submitUserInfo(user) && submitUserDept(user) && submitUserScopes(user);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean changeUserStatus(Long userId, Integer status) {
if (Func.isEmpty(userId)) {
throw new ServiceException("用户主键不能为空");
}
if (!Objects.equals(status, DataStatusEnum.ENABLE.getCode()) && !Objects.equals(status, 0)
&& !Objects.equals(status, DataStatusEnum.DISABLE.getCode())) {
throw new ServiceException("启停状态不正确");
}
TenantGuard.verify(this, userId, USER);
Integer targetStatus = Objects.equals(status, DataStatusEnum.ENABLE.getCode())
? DataStatusEnum.ENABLE.getCode() : 0;
CacheUtil.clear(USER_CACHE);
return changeStatus(Collections.singletonList(userId), targetStatus);
}
@Override
public boolean updateUserInfo(User user) {
// 用户修改自身信息强制指定当前请求账号的ID
@@ -360,7 +381,14 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implement
throw new ServiceException(StringUtil.format("当前手机 [{}] 已存在!", user.getPhone()));
}
user.setPassword(null);
return updateById(user);
Integer originalSex = user.getSex();
Integer normalizedSex = normalizeUserSex(originalSex);
user.setSex(normalizedSex);
boolean updated = updateById(user);
if (user.getId() != null && originalSex != null && normalizedSex == null) {
this.update(Wrappers.<User>lambdaUpdate().set(User::getSex, null).eq(User::getId, user.getId()));
}
return updated;
}
private boolean submitUserDept(User user) {
@@ -378,6 +406,7 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implement
@Override
public IPage<User> selectUserPage(IPage<User> page, User user, Long deptId, String tenantId) {
normalizeUserSearch(user);
List<Long> deptIdList = SysCache.getDeptChildIds(deptId);
return page.setRecords(baseMapper.selectUserPage(page, user, deptIdList, tenantId));
}
@@ -713,8 +742,12 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implement
@Override
public List<UserExcel> exportUser(Map<String, Object> user) {
String account = Func.toStr(user.remove("account")).trim();
String realName = Func.toStr(user.remove("realName")).trim();
String phone = Func.toStr(user.remove("phone")).trim();
QueryWrapper<User> queryWrapper = Condition.getQueryWrapper(user, User.class);
applyTenantScope(queryWrapper);
applyUserFuzzyFilters(queryWrapper, account, realName, phone);
queryWrapper.lambda().eq(User::getIsDeleted, BladeConstant.DB_NOT_DELETED);
return exportUser(queryWrapper);
}
@@ -1077,6 +1110,7 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implement
throw new ServiceException(StringUtil.format("当前手机 [{}] 已存在!", user.getPhone()));
}
CacheUtil.clear(USER_CACHE);
user.setSex(normalizeUserSex(user.getSex()));
return save(user) && submitUserDept(user) && submitUserScopes(user);
}
@@ -1087,6 +1121,16 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implement
if (user.getIncludeNewCustomer() == null) user.setIncludeNewCustomer(0);
}
/**
* 性别仅保留男 / 女 / 未知;空值或历史占位 -1 不回填,按空处理。
*/
private Integer normalizeUserSex(Integer sex) {
if (Objects.equals(sex, 1) || Objects.equals(sex, 2) || Objects.equals(sex, 3)) {
return sex;
}
return null;
}
private boolean submitUserScopes(User user) {
userDataScopeMapper.delete(Wrappers.<UserDataScope>lambdaQuery().eq(UserDataScope::getUserId, user.getId()));
userCustomerScopeMapper.delete(Wrappers.<UserCustomerScope>lambdaQuery().eq(UserCustomerScope::getUserId, user.getId()));
@@ -1127,6 +1171,35 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implement
}
}
/**
* 归一化用户列表搜索条件,避免首尾空格导致模糊匹配失效。
*/
private void normalizeUserSearch(User user) {
if (user == null) {
return;
}
if (user.getAccount() != null) {
user.setAccount(user.getAccount().trim());
}
if (user.getRealName() != null) {
user.setRealName(user.getRealName().trim());
}
if (user.getPhone() != null) {
user.setPhone(user.getPhone().trim());
}
}
/**
* 账号名、姓名、手机号统一按模糊匹配过滤。
*/
private void applyUserFuzzyFilters(QueryWrapper<User> queryWrapper, String account, String realName, String phone) {
queryWrapper.lambda().like(StringUtil.isNotBlank(account), User::getAccount, account);
if (StringUtil.isNotBlank(realName)) {
queryWrapper.lambda().and(wrapper -> wrapper.like(User::getRealName, realName).or().like(User::getName, realName));
}
queryWrapper.lambda().like(StringUtil.isNotBlank(phone), User::getPhone, phone);
}
@Override
public void decryptPhone(IPhone user) {
@@ -0,0 +1,97 @@
/**
* 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.util;
import org.apache.commons.lang3.StringUtils;
import org.springblade.thirdparty.oa.constant.OAConvertConstant;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 组织编码工具:上级编码直接拼接固定 3 位分段数字(不足补零,中间不加 "-")
*
* @author Chill
*/
public final class DeptCodeUtil {
/**
* 分段数字位数
*/
public static final int SEGMENT_WIDTH = 3;
private DeptCodeUtil() {
}
/**
* 生成子级编码:上级编码 + 三位数字
*/
public static String formatChildCode(String parentCode, int serial) {
return parentCode + String.format("%0" + SEGMENT_WIDTH + "d", serial);
}
/**
* 是否符合「上级编码 + 三位数字」格式(恰好多出 3 位数字)
*/
public static boolean matchesChildCode(String parentCode, String deptCode) {
if (StringUtils.isBlank(parentCode) || StringUtils.isBlank(deptCode)) {
return false;
}
return deptCode.matches("^" + Pattern.quote(parentCode) + "\\d{" + SEGMENT_WIDTH + "}$");
}
/**
* 是否为公司编码(GWWL + 三位数字)
*/
public static boolean isCompanyCode(String deptCode) {
return matchesChildCode(OAConvertConstant.OA_SYNC_ROOT_DEPT_CODE, deptCode);
}
/**
* 在已有编码中取下一分段序号(从 1 起)
*/
public static int nextSerial(String parentCode, Collection<String> existingCodes) {
if (StringUtils.isBlank(parentCode)) {
return 1;
}
Pattern pattern = Pattern.compile("^" + Pattern.quote(parentCode) + "(\\d{" + SEGMENT_WIDTH + "})$");
int maxSerial = 0;
if (existingCodes != null) {
for (String code : existingCodes) {
if (StringUtils.isBlank(code)) {
continue;
}
Matcher matcher = pattern.matcher(code.trim());
if (!matcher.matches()) {
continue;
}
maxSerial = Math.max(maxSerial, Integer.parseInt(matcher.group(1)));
}
}
return maxSerial + 1;
}
}
@@ -0,0 +1,78 @@
/**
* 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>
* Author: Chill Zhuang (bladejava@qq.com)
*/
package org.springblade.system.wrapper;
import org.springblade.core.mp.support.BaseEntityWrapper;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.system.cache.DictCache;
import org.springblade.system.cache.UserCache;
import org.springblade.system.pojo.entity.MpUser;
import org.springblade.system.pojo.enums.DictEnum;
import org.springblade.system.pojo.enums.MpUserIdentity;
import org.springblade.system.pojo.vo.MpUserVO;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* 小程序用户包装类
*
* @author Chill
*/
public class MpUserWrapper extends BaseEntityWrapper<MpUser, MpUserVO> {
public static MpUserWrapper build() {
return new MpUserWrapper();
}
@Override
public MpUserVO entityVO(MpUser mpUser) {
MpUserVO mpUserVO = Objects.requireNonNull(BeanUtil.copyProperties(mpUser, MpUserVO.class));
// 密码哈希不下发前端
mpUserVO.setPassword(null);
mpUserVO.setIdentitiesName(resolveIdentitiesName(mpUser.getIdentities()));
if (mpUser.getSex() != null) {
mpUserVO.setSexName(DictCache.getValue(DictEnum.SEX, mpUser.getSex()));
}
mpUserVO.setCreateUserName(UserCache.getUserRealName(mpUser.getCreateUser()));
mpUserVO.setUpdateUserName(UserCache.getUserRealName(mpUser.getUpdateUser()));
return mpUserVO;
}
private String resolveIdentitiesName(String identities) {
List<String> identityList = MpUserIdentity.split(identities);
if (identityList.isEmpty()) {
return "";
}
return identityList.stream()
.map(code -> {
MpUserIdentity identity = MpUserIdentity.of(code);
return identity == null ? code : identity.getLabel();
})
.filter(Func::isNotBlank)
.collect(Collectors.joining(","));
}
}
@@ -38,6 +38,7 @@ import org.springblade.system.pojo.enums.DictEnum;
import org.springblade.system.pojo.vo.UserVO;
import java.util.List;
import java.util.Objects;
/**
* 包装类,返回视图层所需的字段
@@ -81,7 +82,11 @@ public class UserWrapper extends BaseEntityWrapper<User, UserVO> {
userVO.setPostId(StringPool.EMPTY);
userVO.setPostName("暂未分配");
}
userVO.setSexName(DictCache.getValue(DictEnum.SEX, user.getSex()));
if (user.getSex() == null || Objects.equals(user.getSex(), -1)) {
userVO.setSexName("");
} else {
userVO.setSexName(DictCache.getValue(DictEnum.SEX, user.getSex()));
}
userVO.setUserTypeName(DictCache.getValue(DictEnum.USER_TYPE, user.getUserType()));
return userVO;
}